# Nevermined Documentation > ## Agent Instructions > If you are an agent buying services: start with these steps. Every page has a .md version. > 1. Install the Catalog MCP (live server https://mcp.live.nevermined.app/mcp, sandbox server https://mcp.sandbox.nevermined.app/mcp; rehearse on sandbox with a sandbox API key before live, as keys work only in their own environment; Claude Code and Cursor commands, Codex config.toml entry): https://nevermined.ai/docs/products/catalog/mcp.md > 2. Get an API key: https://nevermined.ai/docs/agents-guide/get-api-key.md > 3. Enroll a card and create a delegation (a payment method plus a spend mandate: an amount, an expiry and a number of purchases): https://nevermined.ai/docs/agents-guide/enroll-card.md > 4. Buy and call a paid agent over x402: https://nevermined.ai/docs/getting-started/ai-agent-purchase.md > SDK quickstart: https://nevermined.ai/docs/integrate/quickstart/typescript.md. Pricing: https://nevermined.ai/pricing/ # Add Payments to Your Agent Source: https://nevermined.ai/docs/agents-guide/add-payments Have a coding agent retrofit your existing AI agent or API so callers must pay per request through an x402 paywall — middleware, plan registration, and a test. This flow is the other side of the market: instead of paying, your agent **gets paid**. Point a coding agent (Claude Code, Cursor, an OpenAI agent) at your existing service and the Nevermined SDK, and it wires an x402 paywall in front of the endpoints you choose — so every call costs credits. ## Useful for * **Monetizing** an existing Express, FastAPI, MCP, or A2A agent without building billing yourself. * Charging **per request** (fixed or dynamic credits) with metering and settlement handled for you. * Generating the **registration script + middleware + a test** in one pass, so you go from unpaid to paid in minutes. ## Try it yourself Run this in your project with a coding agent that can read and edit your files: ```text theme={null} My project is an Express (TypeScript, ESM) AI agent with an endpoint `POST /ask`. Add Nevermined payments so callers must pay 1 credit per request via the x402 protocol, using the @nevermined-io/payments SDK (pin ^1.8.0) and following the Nevermined `nevermined-payments` skill (https://github.com/nevermined-io/docs/tree/main/skills/nevermined-payments) — its Track B + references/express-integration.md and references/client-integration.md cover the details. Project setup: package.json must have "type":"module" (required for the @nevermined-io/payments/express subpath import); local TS imports use .js extensions; run with `npx tsx .ts`. Keep my existing POST /ask handler logic completely intact — add payments only as a front layer (the paymentMiddleware), never inside the handler. Produce three files: 1. register.ts — publishes my agent and a "Starter" plan granting 100 credits for $10 in USDC on sandbox, then prints agentId and planId. Build configs with payments.plans.getERC20PriceConfig(10_000_000n, '0x036CbD53842c5426634e7929541eC2318f3dCF7e', '') (10 USDC = 10_000_000n, 6 decimals; all numeric helper args are BigInt — note the n) and payments.plans.getFixedCreditsConfig(100n, 1n), then payments.agents.registerAgentAndPlan(...). (The price helper splits payment into builder + platform-fee receivers, so the builder nets slightly under $10 — expected.) 2. server.ts — wire the middleware: app.use(paymentMiddleware(payments, { 'POST /ask': { planId: NVM_PLAN_ID, agentId: NVM_AGENT_ID, credits: 1 } })), reading NVM_API_KEY, NVM_PLAN_ID, NVM_AGENT_ID from env. Mount express.json() first; keep the existing app.post('/ask', askHandler) unchanged. The middleware auto-returns 402 + payment-required, verifies, runs the handler, then settles/burns and adds payment-response — no manual verify/settle. 3. test.ts — start the server, call POST /ask with no payment-signature (expect 402; decode the base64 payment-required header), then do the TWO-STEP token mint (the inline auto-create `delegationConfig` — passing `spendingLimitCents`/`durationSecs` without a `delegationId` — is deprecated since SDK 1.8.0: it emits a runtime deprecation warning, so use the explicit two-step): first `const { delegationId } = await payments.delegation.createDelegation({ provider: 'erc4337', spendingLimitCents: 10000, durationSecs: 604800, currency: 'usdc' })`, then `const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, { delegationConfig: { delegationId } })`, and retry POST /ask with header `payment-signature: ` (expect 200; decode the base64 payment-response receipt — creditsRedeemed/remainingBalance). Run in the sandbox environment. Use the modern payment-signature header and X402_HEADERS from @nevermined-io/payments/express; the middleware calls verifyPermissions/settlePermissions internally — do NOT use the deprecated isValidRequest or X-402. ``` > [!NOTE] > > Swap the framework line for your stack — guides exist for [Express](/docs/integrate/add-to-your-agent/express), [FastAPI](/docs/integrate/add-to-your-agent/fastapi), [Strands](/docs/integrate/add-to-your-agent/strands), and [generic HTTP](/docs/integrate/add-to-your-agent/generic-http). ## How it works **1. Register an agent and a plan** Publish the service and price it. The SDK helpers build the on-chain price/credits config for you: > [tab] TypeScript > > ```typescript theme={null} > const { agentId, planId } = await payments.agents.registerAgentAndPlan( > { name: 'My Agent', description: 'AI service', tags: ['ai'], dateCreated: new Date() }, > { endpoints: [{ POST: 'https://your-api.com/ask' }] }, > { 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), > ) > ``` > [tab] Python > > ```python theme={null} > 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/ask'}]}, > plan_metadata={'name': 'Starter Plan', 'description': '100 requests for $10'}, > price_config=payments.plans.get_erc20_price_config(10_000_000, USDC_ADDRESS, os.environ['BUILDER_ADDRESS']), > credits_config=payments.plans.get_fixed_credits_config(100, 1), > ) > ``` See [Register a plan & agent](/docs/agents-guide/register-plan-and-agent) for the full options (fiat pricing, time-based and pay-as-you-go plans). **2. Gate your routes with middleware** Add the payment middleware and list the routes to protect with their credit cost. Everything not listed stays public: > [tab] Express (TypeScript) > > ```typescript theme={null} > import { paymentMiddleware } from '@nevermined-io/payments/express' > > app.use(paymentMiddleware(payments, { > 'POST /ask': { planId: process.env.NVM_PLAN_ID, credits: 1 }, > })) > ``` > [tab] FastAPI (Python) > > ```python theme={null} > from payments_py.x402.fastapi import PaymentMiddleware > > app.add_middleware( > PaymentMiddleware, > payments=payments, > routes={"POST /ask": {"plan_id": os.environ["NVM_PLAN_ID"], "credits": 1}}, > ) > ``` The middleware returns `402` with a `payment-required` challenge when the token is missing, verifies it when present, runs your handler, then settles (burns credits) and returns the receipt in `payment-response`. **3. Test the paywall** Call without a token (expect `402`), then with a fresh token (expect `200`): ```bash theme={null} # 1) No token → 402 curl -i -X POST http://localhost:3000/ask -d '{"q":"hi"}' # 2) With an x402 token → 200 (mint one as a buyer would — see "Buy access") curl -i -X POST http://localhost:3000/ask \ -H "payment-signature: " -d '{"q":"hi"}' ``` ## Related > [card] [Register a plan & agent](/docs/agents-guide/register-plan-and-agent) > > Publish and price the service you're protecting. > [card] [Nevermined x402](/docs/development-guide/nevermined-x402) > > The protocol behind the paywall: schemes, headers, verify/settle. > [card] [Check revenue](/docs/agents-guide/check-revenue) > > Once you're charging, track what you earn. > [card] [Buy access](/docs/getting-started/ai-agent-purchase) > > See the buyer side that mints the token your paywall checks. # Check Your Credits (Buyer) Source: https://nevermined.ai/docs/agents-guide/check-credits Have an AI agent report your Nevermined buyer status — credits remaining on each plan, active delegations, and remaining spending budgets — so it can top up before running out. An agent that pays for services should know where it stands: how many credits are left on each plan, and how much budget remains on its delegations. This flow pulls that status over the REST API so the agent can warn you — or top up — before it runs dry mid-task. ## Useful for * A **pre-flight check** before a run: does the agent have enough credits and delegation budget to finish? * A **"what do I have" report** across every plan you hold and every delegation you've granted. * **Top-up triggers**: detect when a balance or budget is low and act before it hits zero. ## Try it yourself ```text theme={null} You are my autonomous payments agent. Use the Nevermined `nevermined-payments` skill (https://github.com/nevermined-io/docs/tree/main/skills/nevermined-payments) (Track A, sections A2 and A5) and my NVM_API_KEY. Base URL: https://api.sandbox.nevermined.app/api/v1. Authenticate every call with `Authorization: Bearer $NVM_API_KEY`. Give me a buyer-account status report for sandbox: 1) PAYMENT METHODS — GET /payment-methods. List each method's type (card vs crypto_wallet/stablecoin), brand+last4, provider, and status. Note that `status` is capitalized (e.g. "Active", "Revoked"). Tell me which are active and usable, and call out any revoked one (it cannot back a delegation). 2) DELEGATIONS — GET /delegation. For each, report spendingLimitCents, amountSpentCents, remainingBudgetCents, expiresAt, and status, formatting the cents fields (they come back as STRINGS) as dollars. Flag a delegation if status != "Active", OR remainingBudgetCents is at/below 20% of spendingLimitCents, OR it expires within 48 hours. Report `status` verbatim — note that a delegation can show "Exhausted" even when amountSpent is 0 (it just means expired-and-closed), so describe what the API says rather than guessing the cause. If a delegation has charges, you may inspect them via GET /delegation/{id}/transactions. 3) PLANS I HOLD + CREDIT BALANCE — there is NO endpoint that lists the plans a buyer has purchased. (GET /protocol/plans only returns plans I AUTHORED as a seller, so it will NOT surface plans I merely bought — don't rely on it to find my purchases.) So you need the plan ids to check: use the ones I give you, the ids I retained from past purchases, or the plans advertised in the agentic-instructions.md / llms.txt of any org I've bought from. For EACH such plan id, call GET /protocol/plans/{planId}/balance/{myAddress} — myAddress is the `id` of my erc4337/crypto_wallet payment method from step 1 (it covers both card- and crypto-bought plans) — and report planName, planType, balance (remaining credits), and isSubscriber (true = I hold it). Flag any held plan with a low balance (under 50 credits). If you have no plan ids to check, say so plainly rather than reporting "no plans held". Then give me a short "action needed" section: anything expired/exhausted/revoked/low, and exactly what I'd do to top up — to restore spending, create a fresh delegation via POST /delegation/create (provider "erc4337" for crypto, or "stripe" with providerPaymentMethodId = my active card's id for card); to add plan credits, run the x402 buy+settle flow (skill A4) against the plan id using a live delegation. Keep all secrets masked in your output. ``` ## How it works All three checks are simple authenticated `GET`s. **1. Payment methods** ```http theme={null} GET {API_BASE}/payment-methods Authorization: Bearer ``` Returns your cards and your stablecoin (`erc4337`) wallet, each with `status`. The `erc4337` method's `id` **is your wallet/holder address** — you'll use it as the holder when checking plan balances. **2. Delegations and remaining budget** ```http theme={null} GET {API_BASE}/delegation Authorization: Bearer ``` Returns `{ totalResults, page, offset, delegations: [ … ] }`, each with `spendingLimitCents`, `amountSpentCents`, `remainingBudgetCents`, `status`, and `expiresAt`. (Delegation and transaction lists use `totalResults`; the plan/agent lists use `total` — mind the difference if you write one pagination helper for both.) Drill into one delegation's charges with: ```http theme={null} GET {API_BASE}/delegation/{delegationId}/transactions Authorization: Bearer ``` (returns `{ totalResults, page, offset, transactions: [ … ] }`). **3. Credit balance per plan** For each plan you hold, query your balance with your wallet as the holder: > [tab] REST > > ```http theme={null} > GET {API_BASE}/protocol/plans/{planId}/balance/{yourAddress} > Authorization: Bearer > ``` > > `{yourAddress}` is the `id` of your `erc4337` payment method from step 1 (or the `userWallet` from an embed session). Returns `{ planName, planType, isSubscriber, balance, pricePerCredit, … }` — `balance` is your remaining credits. > [tab] TypeScript > > ```typescript theme={null} > const balance = await payments.plans.getPlanBalance(planId) > console.log(`Credits: ${balance.balance}`) // bigint > ``` > [tab] Python > > ```python theme={null} > balance = payments.plans.get_plan_balance(plan_id) > print(f"Credits: {balance['balance']}") > ``` > [!NOTE] > > The receipt from a purchase (`creditsRedeemed` / `remainingBalance`, returned by `settle` or decoded from the `payment-response` header) is also a live proof of your balance right after a buy — **on a `credits` plan**. A pay-as-you-go plan holds no credit balance: its receipt reads `"0"` for both fields whatever was charged, and the charge is referenced by `orderTx` (fiat rails) or `transaction` (crypto rails). Read `billingModel` off the receipt before either field. ## Related > [card] [Buy access](/docs/getting-started/ai-agent-purchase) > > Top up when a balance runs low. > [card] [Enroll a card & delegate](/docs/agents-guide/enroll-card) > > Grant a fresh budget when a delegation is spent or expired. > [card] [Order Plans](/docs/getting-started/ai-agent-purchase) > > Buy credits upfront for stablecoin plans. # Check Your Revenue (Seller) Source: https://nevermined.ai/docs/agents-guide/check-revenue Have an AI agent pull a revenue report for the agents and plans you sell on Nevermined — total revenue, MRR, active subscribers, and credits consumed per plan. If you sell agents or plans, this flow turns "how's it going?" into a report an agent generates on demand: revenue per agent, monthly recurring revenue, active subscribers, and how many credits buyers are burning. The aggregated numbers come from your organization's analytics; if you're not on a Premium tier, the agent falls back to the always-available building blocks. ## Useful for * A **revenue snapshot** — total earnings per agent over any date range. * Tracking **MRR and active subscribers** to see growth at a glance. * Seeing **which plans get used** (credits burned, unique users) so you can price and iterate. ## Try it yourself ```text theme={null} You are my autonomous payments agent. Using the Nevermined `nevermined-payments` skill (https://github.com/nevermined-io/docs/tree/main/skills/nevermined-payments) (Track A, A7 + references/seller-operations.md) and my NVM_API_KEY, produce a revenue report for the AI agents and plans I sell on Nevermined sandbox. Base URL: https://api.sandbox.nevermined.app/api/v1 . Send `Authorization: Bearer $NVM_API_KEY` on every call. Never print, echo, or persist the key. STEP 1 — Inventory + discover my org id (always do this first; it never needs Premium): - GET /protocol/plans?page=1&offset=50 and GET /protocol/agents?page=1&offset=50. - These return { total, page, offset, plans|agents: [ ] }. For each item read: name = metadata.main.name price = SUM of registry.price.amounts (each is a STRING in 6-decimal token units; the array splits across builder + a platform-fee receiver — contract-default 1% for crypto, 2% for fiat, and an org-level crypto fee can add a third receiver — so always SUM the array, never read index 0; then divide by 1,000,000 for USD/USDC; e.g. fiat ["9800000","200000"] => 10000000 = $10.00) paymentType = registry.price.isCrypto ? "crypto (USDC/EURC)" : "fiat (card)" credits = registry.credits.amount ; durationSecs (0 = non-expiring fixed credits; >0 = time-based) org id = item.orgId and item.organizationName <-- this is how you discover my org id - Summarize every plan and agent: name, type, price, credits, owning org. This summary is the baseline report and must always be produced. - Pick MY_ORG_ID = the most common non-null .orgId across my plans/agents. If none is non-null, skip STEP 2 entirely and report "no org-level analytics available; inventory only". STEP 2 — Org analytics enrichment (only if MY_ORG_ID matches ^org-[0-9a-f-]+$): Call, with from/to spanning the last 90 days (from = today-90d, to = today, ISO-8601 Z): GET /organizations/{MY_ORG_ID}/analytics/revenue?from=&to= GET /organizations/{MY_ORG_ID}/analytics/mrr GET /organizations/{MY_ORG_ID}/analytics/usage?from=&to= GET /organizations/{MY_ORG_ID}/analytics/customers?limit=50 Treat analytics as VALID only if you get HTTP 200 AND a validly-shaped org id was used. Note these real failure modes and fall back to the STEP 1 inventory summary if any occur: - 403 BCK.AUTH.0004 ("Organisation admin privileges required") — the org isn't mine / not Premium-admin. (The skill mentions BCK.ORGANIZATIONS.0022; the live code may instead return BCK.AUTH.0004 — treat any 403 the same.) - A 200 response that is all zeros/empty ({"mrr":"0"}, totalRevenue "0", items []) while STEP 1 shows I have published plans — this is the silent failure you get from a bad/placeholder org id. Do NOT report it as real; fall back. Report from the analytics data: 1. Revenue per row (the API labels rows agentId/agentName but actually groups by PLAN — report them as plans/offerings), last 90 days, plus the grand total. Convert all *Revenue/*Spent integer strings to USD by dividing by 1,000,000. 2. MRR and active subscribers (mrr, activeSubscriptions). Note that MRR can legitimately be 0 if my sales were one-off credit purchases rather than recurring subscriptions. 3. Credits consumed per plan with unique users (creditsBurned, uniqueUsers). Output: the inventory summary (always), then the analytics numbers if STEP 2 succeeded, clearly stating which path produced the figures and the exact date window used. ``` ## How it works There are two layers: aggregated **organization analytics** (Premium tier) and always-available **building blocks**. **1. Organization analytics (Premium tier)** Set the analytics base once, then pull each metric (`from`/`to` are ISO-8601; `from` inclusive, `to` exclusive): ```bash theme={null} B="{API_BASE}/organizations//analytics" # Revenue per agent curl -s -H "Authorization: Bearer $NVM_API_KEY" "$B/revenue?from=2026-03-20T00:00:00Z&to=2026-06-18T00:00:00Z" # → { items: [ { agentId, agentName, totalRevenue, transactionCount } ], totalRevenue } # MRR + active subscribers curl -s -H "Authorization: Bearer $NVM_API_KEY" "$B/mrr" # → { mrr, activeSubscriptions } # Credits burned per plan curl -s -H "Authorization: Bearer $NVM_API_KEY" "$B/usage?from=...&to=..." # → { items: [ { planId, planName, creditsBurned, uniqueUsers } ] } ``` **Discover your `orgId` from the records themselves** — every item in `GET /protocol/plans` and `/protocol/agents` carries `.orgId` and `.organizationName`; take the most common non-null `.orgId` across your published items (no separate lookup endpoint exists). Only call analytics if it matches `^org-[0-9a-f-]+$`. Three failure modes to handle: * A **foreign / non-admin** org returns `403 BCK.AUTH.0004` ("Organisation admin privileges required"). * A **non-Premium** org returns `403 BCK.ORGANIZATIONS.0022`. * A **malformed or placeholder** org id (e.g. an unsubstituted ``) returns a **silent `200` of all-zeros** — never report that as real revenue. Validate the id shape first, and treat a zero result while you *have* published plans as a failure: fall back to the building blocks below. > [!NOTE] > > The `revenue`/`usage` rows are labelled `agentId`/`agentName` but are actually grouped **by plan**. Money fields like `totalRevenue` are stringified integers in 6-decimal token units — divide by 1,000,000 for USD. (`creditsBurned` is a plain credit count, not money.) **2. Building blocks (any tier)** These need no Premium and no `orgId` — they're scoped to your API key: ```http theme={null} GET {API_BASE}/protocol/plans GET {API_BASE}/protocol/agents Authorization: Bearer ``` Each returns `{ total, page, offset, plans|agents: [ … ] }` where every item is the full record — read the name from `metadata.main.name` and the id from `id`. Combine with per-holder balances (`GET /protocol/plans/{planId}/balance/{address}`) to approximate usage when analytics aren't available. **3. Per-request usage (optional)** For token-level usage and cost tracking, the SDK integrates with Helicone via `payments.observability`. See [AI Agents Observability](/docs/solutions/ai-agents-observability) for the full picture. ## Related > [card] [Register a plan & agent](/docs/agents-guide/register-plan-and-agent) > > Publish the agents and plans this report measures. > [card] [AI Agents Observability](/docs/solutions/ai-agents-observability) > > Usage, cost, and performance tracking for your agents. > [card] [Add payments to your agent](/docs/agents-guide/add-payments) > > Start charging so there's revenue to report. # Enroll a Card & Delegate a Budget Source: https://nevermined.ai/docs/agents-guide/enroll-card Let an AI agent set up a card payment method and a capped, time-boxed spending delegation it can reuse to pay for Nevermined services autonomously. A **delegation** is what lets an agent spend on your behalf without asking every time. It is a payment method plus a **spend mandate**: an amount, an expiry and a number of purchases. This flow enrolls a card once (the human enters card details in a browser, as PCI requires) and hands the agent a `delegationId` it reuses until the budget is spent or the delegation expires. ## Useful for * Giving an agent a **card** to pay with when a plan is fiat (Stripe / Braintree / Visa) rather than stablecoin. * Putting a **hard cap** on what an agent can spend (e.g. `$50` over `30 days`) — the platform enforces it. * Doing the human part **once**: after enrollment, every purchase is programmatic and reuses the same delegation. > [!NOTE] > > Paying with **stablecoins** needs no card and no human enrollment — your account's ERC‑4337 wallet is ready as soon as it's funded. Use this flow only for card payments. See [Buy access](/docs/getting-started/ai-agent-purchase) for the stablecoin path. ## Try it yourself Hand this to your agent. It drives the embedded enrollment handshake, gives you a single URL to open, and captures the result automatically: ```text theme={null} You are my autonomous payments agent. Set up a credit card I can use to pay for Nevermined services in the sandbox environment, with a spending limit of $50 over 30 days. Use the **latest** Nevermined `nevermined-payments` skill — fetch the current `SKILL.md` and `references/` from https://github.com/nevermined-io/docs/tree/main/skills/nevermined-payments (don't rely on an older installed/cached copy). The card-enrollment endpoints (`POST /embed/session`, the `cards/setup` URL, `delegation/create`) are documented there even though `embed/session` is not in the API's OpenAPI. Do the work yourself: mint an embedded session with my API key, host a one-shot callback server on 127.0.0.1, and hand me a single card-setup URL to open in my browser. The only thing I should have to do is enter my card. When I'm done, verify the `state` echo, store the `delegationId`, and show me my payment methods and the new delegation's remaining budget. ``` > [!NOTE] > > This points at **Sandbox**, so card entry uses test cards and no real money moves. Use a `live:` API key to run it for real. ## How it works **1. Mint an embedded session** With your API key, mint a session bound to a **localhost** return URL — so run a tiny one-shot callback server on `127.0.0.1` first: ```http theme={null} POST {API_BASE}/embed/session Authorization: Bearer Content-Type: application/json { "returnUrl": "http://127.0.0.1:/callback" } ``` The response carries a `sessionToken`. This **open** endpoint needs no organization — it's the autonomous-agent path, and the card attaches to your own account. (Org members, e.g. the `nevermined` CLI, can use the org-scoped `POST {API_BASE}/widgets/session/self` with `{ orgId, returnUrl }` instead.) **2. Hand the human a card-setup URL** The human opens this once in their browser and enters the card: ``` https://embed.nevermined.app/cards/setup ?sessionToken= &returnUrl=http://127.0.0.1:/callback &state= &provider=stripe ``` Generate `state` as an unguessable nonce. `provider` only affects the Visa Agentic option: `provider=visa` starts it ticked, where it is offered. Any other value enrolls a plain card, which pays Stripe-priced and Braintree-priced plans. **3. Receive the delegation** When the human finishes, the browser redirects to your `returnUrl` with `paymentMethodId` and `delegationId`. **Verify the returned `state` matches** the one you sent (CSRF guard), then **store the `delegationId`** — that's what you pass at purchase time. > [!WARNING] > > `paymentMethodId` and `delegationId` arrive in the callback **query string**. Don't log the request line, and keep secrets in a secret store, not on disk in the clear. **4. (Optional) Re-budget an enrolled card** Already enrolled and just need a fresh budget? Create another delegation directly — no browser needed: ```http theme={null} POST {API_BASE}/delegation/create Authorization: Bearer Content-Type: application/json { "provider": "vgs", "providerPaymentMethodId": "", "spendingLimitCents": 5000, "durationSecs": 2592000, "currency": "usd" } ``` `provider`, `currency`, `spendingLimitCents`, and `durationSecs` are all required — there is no silent default for `provider` or `currency`. The response carries a new `delegationId`. The delegation is **plan-agnostic** unless you pass a `planId`. > [!NOTE] > > **Visa** is the exception: `provider: "visa"` needs a browser-produced `consumerPrompt` + `assuranceData` from a WebAuthn ceremony, which an agent can't generate — so create Visa delegations in the app and reuse the `delegationId`. **5. Reuse it to pay** Pass the stored `delegationId` whenever you buy — see [Buy access](/docs/getting-started/ai-agent-purchase). One delegation covers many purchases until its budget is spent or it expires. ## Related > [card] [Buy access](/docs/getting-started/ai-agent-purchase) > > Use the delegation to buy plan credits with x402. > [card] [Card Delegation](/docs/solutions/card-delegation) > > The full embedded handshake, widget embedding, and `state`/CSRF rules. > [card] [Card Enrollment](/docs/products/payments/card-enrollment) > > Provider-specific enrollment (Stripe, Braintree, Visa). > [card] [Check credits](/docs/agents-guide/check-credits) > > Inspect delegation budgets and remaining credits. # Get a Nevermined API Key Source: https://nevermined.ai/docs/agents-guide/get-api-key Let an AI agent obtain a Nevermined API key with a single sign-in from a human — captured automatically via a localhost callback, no copy-paste. Every Nevermined call an agent makes needs an API key. The first key is the **one thing an agent can't mint itself** — a human must sign in once. But the agent can make that painless: it hosts a callback, hands the human one URL, and captures the key automatically when they sign in. After that, it stores and reuses the key forever. ## Useful for * **Bootstrapping** a brand-new agent that has no credentials yet. * Getting the key **back to the agent automatically** — no human copy-pasting secrets. * Issuing **environment-specific** keys: a `sandbox:` key for testing, a `live:` key for production. ## Try it yourself ```text theme={null} You are my autonomous payments agent. I don't have a Nevermined API key yet — get one for the sandbox environment with as little effort from me as possible. Host a one-shot callback server on 127.0.0.1, then give me a single sign-in URL to open. Capture the key automatically from the redirect (don't make me copy-paste it), store it as NVM_API_KEY, and confirm it works by listing my payment methods. The key for this environment starts with "sandbox". Use the Nevermined `nevermined-payments` skill (https://github.com/nevermined-io/docs/tree/main/skills/nevermined-payments) for the steps and endpoints. ``` ## How it works There are two ways to get the key — the agent should prefer the embedded flow, which returns the key automatically. **1. Option A — embedded login (key returns automatically)** The agent hosts an HTTP server on `127.0.0.1:` with a `/callback` route, then hands the human this URL: ``` https://nevermined.app/auth/cli?callback_url=http://127.0.0.1:/callback ``` After the human signs in, the browser is redirected to `http://127.0.0.1:/callback?nvm_api_key=`. The agent reads `nvm_api_key` off that request and stores it. > [!WARNING] > > The key arrives in the callback **query string** — the most-logged part of a request. The callback server must not log the request line, and the key belongs in a secret store, never on disk in the clear. **2. Option B — manual paste (works anywhere)** If the agent can't host a localhost callback, the human creates the key in the app and pastes it back: sign in at [nevermined.app](https://nevermined.app) → **Settings → Global NVM API Keys** → create a key for the right environment. **3. Store, reuse, and use it** The key doesn't expire per request — store it once (e.g. `NVM_API_KEY`) and reuse it. Use it as a Bearer token on REST calls, or pass it to the SDK: > [tab] REST > > ```http theme={null} > GET {API_BASE}/payment-methods > Authorization: Bearer > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY, // "sandbox:..." or "live:..." > environment: 'sandbox', > }) > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ["NVM_API_KEY"], environment="sandbox") > ) > ``` > [!NOTE] > > Match the key to the environment: a `sandbox:` key only works against `api.sandbox.nevermined.app`, and `live:` only against `api.live.nevermined.app`. > [!NOTE] > > **Two cases need neither option.** A **headless** agent with no browser and no localhost can still get a key with a human's approval through the [device flow (RFC 8628)](/docs/integrate/authentication/device-flow). And an agent running **inside an AI assistant** that runs OAuth for it — Claude, ChatGPT, and the other hosts Nevermined's operator has listed — never handles a key at all: the assistant connects the [Catalog MCP](/docs/mcp/catalog-mcp/overview#auth-&-transport) and obtains one when the human approves a spending cap (which host and client each assistant uses differs — LangSmith Fleet, for one, is a pre-registered client on the strict host). Both ceremonies, the per-assistant mapping, and the key format are in the agent-facing manifest [`auth.md`](https://nevermined.app/auth.md). ## Related > [card] [Buy access](/docs/getting-started/ai-agent-purchase) > > With a key in hand, make your first autonomous purchase. > [card] [Register a plan and an agent](/docs/agents-guide/register-plan-and-agent) > > Publish a service others can pay for. # Agents Guide Source: https://nevermined.ai/docs/agents-guide/overview Give an AI agent a prompt and let it operate on Nevermined autonomously — buy plans, enroll cards, get keys, register agents, and report on credits and revenue. This guide is for **driving an AI agent to do the work** on Nevermined. Each page takes one task an agent can run on its own — paying for a service, enrolling a card, registering a plan — and gives you a copy‑paste prompt and the detailed flow behind it. The pattern is always the same: you hand an agent (Claude Code, Cursor, an OpenAI agent, your own) a prompt and a link to Nevermined's agent‑discoverable instructions, and it figures out the rest. A human is needed only for one‑time setup — the first API key, and a card if you pay by card — everything else is programmatic. > [!NOTE] > > Give your agent the **latest `nevermined-payments` skill** (fetch the current version from the [docs repo](https://github.com/nevermined-io/docs/tree/main/skills/nevermined-payments) — don't rely on an older installed/cached copy) or point it at your organization's `agentic-instructions.md` (e.g. `https://api.sandbox.nevermined.app/api/v1/organizations/{orgId}/agentic-instructions.md`). Either one teaches the agent every endpoint it needs — the prompts on these pages assume it has one of them. ## The seven flows > [!NOTE] > > **Buying a service or selling one?** A **buyer** needs flows 1, 3 & 6 (and flow 2 only if the plan is paid by card) — there's no registration. A **seller** publishes a service with flows 4, 5 & 7. Flow 3 (get an API key) is shared — every agent needs a key, buyer or seller. > [card] [1. Buy access](/docs/getting-started/ai-agent-purchase) > > Purchase plan credits autonomously via x402 — with stablecoins or a card. > [card] [2. Enroll a card & delegate](/docs/agents-guide/enroll-card) > > Add a card and grant the agent a delegation, a payment method plus a spend mandate: an amount, an expiry and a number of purchases. > [card] [3. Get an API key](/docs/agents-guide/get-api-key) > > Obtain a Nevermined API key with one click from a human, captured automatically. > [card] [4. Add payments to your agent](/docs/agents-guide/add-payments) > > Make your own agent charge callers per request behind an x402 paywall. > [card] [5. Register a plan & agent](/docs/agents-guide/register-plan-and-agent) > > Publish an AI agent and a priced payment plan so others can buy it. > [card] [6. Check credits (buyer)](/docs/agents-guide/check-credits) > > Report remaining credits and delegation budgets across your purchases. > [card] [7. Check revenue (seller)](/docs/agents-guide/check-revenue) > > Pull revenue, MRR, and usage for the agents and plans you sell. ## What's on each page Every flow is documented the same way, so you can scan or go deep: **1. Useful for** When to reach for this flow, and what the agent does for you. **2. Try it yourself** A battle‑tested prompt to paste into your agent — edit the bracketed values and go. **3. How it works** The step‑by‑step flow (REST and SDK) behind the prompt, for when you want the detail. ## Sandbox vs. Live Develop against **Sandbox** (test money), then switch to **Live**. API keys are environment‑specific — Sandbox keys start with `sandbox:`, Live keys with `live:` — and each only works against its own base URL. | Environment | Money | API base URL | Web app | | - | - | - | - | | **Sandbox** | Test only — no real charges | `https://api.sandbox.nevermined.app/api/v1` | [nevermined.app](https://nevermined.app) | | **Live** | Real charges | `https://api.live.nevermined.app/api/v1` | [nevermined.app](https://nevermined.app) | > [!WARNING] > > Agents always pay through the **x402 flow** (`verify` → `settle`) — never by calling Stripe or any processor directly. It works the same for cards and stablecoins. ## Related > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > Point your agent at external pay‑per‑call services in the Catalog — the code‑free flow, principles, and links. > [card] [AI Agents: Buy Access](/docs/getting-started/ai-agent-purchase) > > The end‑to‑end purchase walkthrough (flow 1). > [card] [Core Concepts](/docs/getting-started/core-concepts) > > Plans, credits, agents, delegations, and x402 in one place. # Register a Plan & AI Agent Source: https://nevermined.ai/docs/agents-guide/register-plan-and-agent Have an agent publish an AI agent and a priced payment plan on Nevermined — fiat or crypto, fixed credits or time-based — so others can discover and buy it. Before anyone can pay for your service, it has to exist on Nevermined: an **agent** (what you sell) linked to a **plan** (how it's priced). An agent can do this for you in one call — the SDK builds the on-chain price and credits configuration, registers both, and returns the IDs you'll reference everywhere else. > [!NOTE] > > This is a **seller** task. If you only want to **buy or use** an agent, you don't register one — see [Buy & Call a Paid Agent](/docs/getting-started/ai-agent-purchase). ## Useful for * **Going to market**: publishing a new AI agent or API and pricing access in one step. * Choosing a **pricing model** — fixed credits, time-based, pay-as-you-go, or a free trial — without learning the on-chain details. * Selling in **fiat or crypto**: priced in USD (Stripe / Braintree / Visa) or in USDC / EURC. ## Try it yourself ```text theme={null} You are my autonomous payments agent. Register a new AI agent and a payment plan on Nevermined sandbox using the @nevermined-io/payments SDK. Follow the Nevermined `nevermined-payments` skill (https://github.com/nevermined-io/docs/tree/main/skills/nevermined-payments) (section A6) for method signatures. - Agent: "Weather Agent" — description "On-demand weather forecasts", endpoint POST https://my-agent.example.com/forecast - Plan: "Weather Starter" — 100 credits for $10, paid by card (fiat, Stripe default), 1 credit per request - My builder wallet (receives payments): - Environment: sandbox (NVM_API_KEY is set — never print it) Build the config with the SDK helpers, then call payments.agents.registerAgentAndPlan(agentMetadata, agentApi, planMetadata, priceConfig, creditsConfig): - Price: payments.plans.getFiatPriceConfig(amount, builderAddress, 'USD'). The fiat amount is in 6-decimal units (USDC convention), NOT cents — so $10 = 10_000_000n. Arg order is (amount, receiver, currency). All helper numeric args are BigInt — use the n suffix. - Credits: payments.plans.getFixedCreditsConfig(100n, 1n) (100 granted, 1 per request). - agentApi = { endpoints: [{ POST: 'https://my-agent.example.com/forecast' }] }. Print the agentId and planId, then confirm with real REST calls: 1. GET /api/v1/protocol/plans/{planId} (public) → check metadata.curation.isListed === true, registry.price.isCrypto === false (fiat), registry.credits.amount === "100", and that the SUM of registry.price.amounts equals "10000000" ($10). Note: Nevermined takes a ~2% platform fee, so the array splits into ["9800000","200000"] across two receivers — verify the sum, not index 0; index 0 (9800000) is your wallet's net. 2. GET /api/v1/protocol/agents/{agentId}/plans (public) → confirm the plan id appears in plans[] (the plan is linked to the agent). Report both IDs and the confirmation results. (Fiat provider defaults to Stripe and is not echoed in the plan JSON, so you can only confirm "fiat" via isCrypto:false, not "Stripe" specifically.) ``` ## How it works **1. Build the price and credits config** Pick one **price** helper and one **credits** helper — they produce the on-chain config so you don't hand-build it: > [tab] TypeScript > > ```typescript theme={null} > // Price: fiat (Stripe/Braintree/Visa) — amount in 6-decimal units ($10.00) > const priceConfig = payments.plans.getFiatPriceConfig(10_000_000n, BUILDER_ADDRESS, 'USD') > // or crypto: getERC20PriceConfig(10_000_000n, USDC_ADDRESS, BUILDER_ADDRESS) > > // Credits: 100 granted, 1 burned per request > const creditsConfig = payments.plans.getFixedCreditsConfig(100n, 1n) > // or getExpirableDurationConfig(...) (time-based) · getPayAsYouGoCreditsConfig() (per-call) > ``` > [tab] Python > > ```python theme={null} > # Price: fiat — amount in 6-decimal units ($10.00) > price_config = payments.plans.get_fiat_price_config(10_000_000, BUILDER_ADDRESS, "USD") > # or crypto: payments.plans.get_erc20_price_config(10_000_000, USDC_ADDRESS, BUILDER_ADDRESS) > > # Credits: 100 granted, 1 burned per request > credits_config = payments.plans.get_fixed_credits_config(100, 1) > ``` > [!NOTE] > > In TypeScript, plan config amounts are `BigInt` — always pass `…n` (e.g. `10_000_000n`). **2. Register the agent and plan together** One call publishes both and links them: > [tab] TypeScript > > ```typescript theme={null} > const { agentId, planId } = await payments.agents.registerAgentAndPlan( > { name: 'Weather Agent', description: 'On-demand forecasts', tags: ['weather'], dateCreated: new Date() }, > { endpoints: [{ POST: 'https://my-agent.example.com/forecast' }] }, > { name: 'Weather Starter', description: '100 requests for $10', dateCreated: new Date() }, > priceConfig, > creditsConfig, > ) > console.log({ agentId, planId }) > ``` > [tab] Python > > ```python theme={null} > result = payments.agents.register_agent_and_plan( > agent_metadata={'name': 'Weather Agent', 'description': 'On-demand forecasts', 'tags': ['weather']}, > agent_api={'endpoints': [{'POST': 'https://my-agent.example.com/forecast'}]}, > plan_metadata={'name': 'Weather Starter', 'description': '100 requests for $10'}, > price_config=price_config, > credits_config=credits_config, > ) > print(result['agentId'], result['planId']) > ``` The `endpoints` are optional — omit them for an open agent, or include them so the platform enforces route-level access on top of your own middleware. > [accordion] URL pattern syntax (path-to-regexp) > > Endpoint URLs are matched with [path-to-regexp](https://github.com/pillarjs/path-to-regexp), so one entry can cover a whole family of routes: > > ``` > https://example.com/api/v1/agents/:agentId/tasks/:taskId > ``` > > Captures `agentId` and `taskId` as named parameters. > > ``` > https://example.com/api/v1/agents/*path > ``` > > Matches one or more segments after `agents/` and captures them into the `path` array. > > Use `openEndpoints` (TypeScript) or `open_endpoints` (Python) for routes that must stay public, such as documentation or health checks. **3. Confirm it's published** List what you've published to verify the agent and plan are live: ```http theme={null} GET {API_BASE}/protocol/agents Authorization: Bearer ``` Each item is the full record — read the name from `metadata.main.name` and the id from `id`. Then point buyers at your organization's `agentic-instructions.md`, where published plans and agents appear automatically. > [!NOTE] > > Prefer no code? You can register and price everything in the web app — see [Register Agents](/docs/products/nevermined-app/register-agents). ## Related > [card] [Add payments to your agent](/docs/agents-guide/add-payments) > > Gate the registered agent's endpoints behind the plan. > [card] [Register Agents (App)](/docs/products/nevermined-app/register-agents) > > The no-code path to publishing agents and plans. > [card] [Check revenue](/docs/agents-guide/check-revenue) > > Track sales once buyers start arriving. > [card] [Order Plans](/docs/getting-started/ai-agent-purchase) > > How buyers purchase the plan you just created. # Approve or deny a device authorization Source: https://nevermined.ai/docs/api-reference/authentication--ceremony/approve-or-deny-a-device-authorization /api-reference/oauth-openapi.json post /oauth/device Browser-initiated: the signed-in human resolves a user_code and approves (binding the ceremony to themselves) or denies. # Exchange a code, device_code, or refresh_token for a credential Source: https://nevermined.ai/docs/api-reference/authentication--ceremony/exchange-a-code-device_code-or-refresh_token-for-a-credential /api-reference/oauth-openapi.json post /oauth/token One endpoint, three grants. The grant only selects HOW the exchange happens; the *credential type* is selected by the `resource` (RFC 8707) and the binding, not the grant: an `account_access` consent always yields an NVM API key; otherwise a `resource` matching this API's host yields an NVM API key and any other `resource` yields an x402 payment permission; with no `resource`, a delegation-backed binding yields an x402 permission and a plan-only binding yields an NVM API key. Device-flow polling returns a top-level `error`: authorization_pending, slow_down (add 5s to your interval), access_denied, expired_token. Honour the `interval` — this endpoint is rate-limited (~60/min per client IP for device polls, shared across concurrent ceremonies from the same address), so a real HTTP 429 (distinct from the `slow_down` grant error) is reachable under a tight poll loop. # Generate an OAuth 2.1 authorization code Source: https://nevermined.ai/docs/api-reference/authentication--ceremony/generate-an-oauth-21-authorization-code /api-reference/oauth-openapi.json post /oauth/authorize Authorization Code flow with PKCE (mandatory). Mints an x402 payment permission for a specific agent and plan, or — with agent_id absent — an account-level grant: account_access (a capped card mandate) or, with consent_type=commerce, a capped on-chain spending mandate for paying external merchants. Browser-initiated in the signed-in user's context — authenticated with the user's Nevermined API key (unauthenticated → BCK.OAUTH.0007). Requires a pre-registered client_id (unregistered → BCK.OAUTH.0016). Account-level grants are authorized PER CONSENT TYPE: the client must be account-level (else BCK.OAUTH.0018), verified (else BCK.OAUTH.0025) and authorized for the requested consent type (else BCK.OAUTH.0035, whose params.consentType names it). # Resolve a connect client_id to its display name + eligibility Source: https://nevermined.ai/docs/api-reference/authentication--ceremony/resolve-a-connect-client_id-to-its-display-name-+-eligibility /api-reference/oauth-openapi.json post /oauth/connect/details For the account-level connect page: the connector name and which account-level consent types the client may request (allowedConsentTypes — account_access and/or commerce; accountLevelAllowed is true when that list is non-empty), so the page can refuse the type it is rendering before the spend form. A CIMD client_id (an https URL) is resolved from its Client ID Metadata Document, with the configured trust overlay applied exactly as /oauth/authorize applies it; clientOrigin is then the URL's origin, which the consent screen shows beside the document's self-asserted client_name. An unreachable or invalid document answers BCK.OAUTH.0031 (400). Browser-initiated — requires the human's Nevermined API key (unauthenticated → BCK.OAUTH.0007), like device/details. # Resolve a user_code to its verification-page details Source: https://nevermined.ai/docs/api-reference/authentication--ceremony/resolve-a-user_code-to-its-verification-page-details /api-reference/oauth-openapi.json post /oauth/device/details What the signed-in human sees on the verification page before approving: the connector name, the target agent, the consent type, and any bound resource/scope. Requires the human's Nevermined API key (unauthenticated → BCK.OAUTH.0007) — it is the browser verification-page surface, not the polling device. # RFC 8628 device authorization request Source: https://nevermined.ai/docs/api-reference/authentication--ceremony/rfc-8628-device-authorization-request /api-reference/oauth-openapi.json post /oauth/device_authorization Start the device flow. Requires a pre-registered client_id (BCK.OAUTH.0016) and an agent_id (absent → BCK.OAUTH.0018). Returns the device_code the agent polls with and the user_code the human approves. # List connected agents (AgentBindings) for the signed-in user Source: https://nevermined.ai/docs/api-reference/authentication--connections/list-connected-agents-agentbindings-for-the-signed-in-user /api-reference/oauth-openapi.json get /oauth/bindings Browser-initiated. Both credential types in one view, each with its human-facing lifecycle state. Paginated with the API-wide page/offset convention; totalResults is the honest cross-page total, and the applied page/offset are echoed back. # Revoke a credential (RFC 7009) Source: https://nevermined.ai/docs/api-reference/authentication--connections/revoke-a-credential-rfc-7009 /api-reference/oauth-openapi.json post /oauth/revoke Revoke an NVM API key or an x402 access token. Idempotent — revoking an already-revoked or unknown token succeeds. token_type_hint is advisory. # Revoke an AgentBinding by id Source: https://nevermined.ai/docs/api-reference/authentication--connections/revoke-an-agentbinding-by-id /api-reference/oauth-openapi.json post /oauth/bindings/{id}/revoke One action kills every credential minted from the binding. Owner-scoped — a binding that isn't the caller's returns 404. # Authorization Server Metadata (RFC 8414) Source: https://nevermined.ai/docs/api-reference/authentication--discovery/authorization-server-metadata-rfc-8414 /api-reference/oauth-openapi.json get /.well-known/oauth-authorization-server Advertises the authorization, token, and device_authorization endpoints, the supported grants (including urn:ietf:params:oauth:grant-type:device_code), the JWKS URI, and authorization_response_iss_parameter_supported: true (RFC 9207 — every authorization response the consent page redirects with, success or error, carries iss equal to this issuer). scopes_supported is deliberately absent (#2397). # JSON Web Key Set (ES256K / secp256k1) Source: https://nevermined.ai/docs/api-reference/authentication--discovery/json-web-key-set-es256k-secp256k1 /api-reference/oauth-openapi.json get /.well-known/jwks.json The public keys OAuth clients use to verify the JWTs this authorization server issues. Public — no authentication. # Protected Resource Metadata (RFC 9728) Source: https://nevermined.ai/docs/api-reference/authentication--discovery/protected-resource-metadata-rfc-9728 /api-reference/oauth-openapi.json get /.well-known/oauth-protected-resource Names this issuer in authorization_servers and points at the human/agent documentation (auth.md). The WWW-Authenticate challenge on a genuine 401 references this document. # Managing AI Agents Source: https://nevermined.ai/docs/api-reference/cli/agents Complete guide to registering and managing AI agents with the Nevermined CLI # Managing AI Agents Complete guide to registering and managing AI agents with the Nevermined CLI. ## Overview AI agents are services that users can access by purchasing payment plans. Agents can be: * **AI assistants**: Chat-based conversational agents * **API services**: REST APIs with metered access * **Data pipelines**: Processing services with usage tracking * **Tools**: Utility services with pay-per-use billing ## Listing Agent Plans Get the list of plans that can be ordered to access an agent: ```bash theme={null} nevermined agents get-agent-plans # With pagination nevermined agents get-agent-plans --pagination '{"page": 1, "offset": 10}' # JSON output nevermined agents get-agent-plans --format json ``` ## Getting Agent Details Retrieve detailed information about a specific agent: ```bash theme={null} nevermined agents get-agent ``` Example: ```bash theme={null} nevermined agents get-agent "did:nvm:abc123" ``` Output includes: * Agent metadata (name, description, creator) * API endpoint configuration * Associated payment plans ## Registering Agents ### Register Agent with Existing Plans Register a new AI agent and associate it with one or more existing payment plans: ```bash theme={null} nevermined agents register-agent \ --agent-metadata agent-metadata.json \ --agent-api agent-api.json \ --payment-plans "plan-id-1,plan-id-2" ``` `--agent-api` is a JSON object (`AgentAPIAttributes`), not a bare URL — pass a file or an inline JSON string. See [Config schemas](#config-schemas) for the full shape. **agent-metadata.json**: ```json theme={null} { "name": "My AI Assistant", "description": "GPT-4 powered conversational AI with specialized knowledge", "version": "1.0.0", "author": "Your Name", "tags": ["ai", "assistant", "gpt4"], "customData": { "capabilities": ["chat", "code-generation", "analysis"], "model": "gpt-4", "language": "en" } } ``` ### Register Agent and Plan Together Register a new AI agent and create a payment plan for it in a single command: ```bash theme={null} nevermined agents register-agent-and-plan \ --agent-metadata agent-metadata.json \ --agent-api agent-api.json \ --plan-metadata plan-metadata.json \ --price-config price-config.json \ --credits-config credits-config.json ``` Optional flags: * `--access-limit` — `credits` or `time`. When omitted, it is derived from the credits config: `time` if `durationSecs > 0`, otherwise `credits`. Each `--*` flag accepts **either** a path to a `.json` file **or** an inline JSON string (anything ending in `.json` is read as a file; everything else is parsed as JSON). Note that `--agent-api` is a JSON **object** (`AgentAPIAttributes`), not a bare URL. The four config flags map to the SDK types — see [Config schemas](#config-schemas) below for the full field reference and the helper commands that generate them. **agent-api.json** (`AgentAPIAttributes`): ```json theme={null} { "endpoints": [{ "POST": "https://api.example.com/v1/agents/:agentId/tasks" }], "openEndpoints": ["https://api.example.com/v1/docs"], "authType": "bearer", "token": "your-upstream-bearer-token" } ``` Only `endpoints` is commonly needed; `openEndpoints` and the auth fields (`authType`, `username`, `password`, `token`) are optional. **plan-metadata.json** (`PlanMetadata`): ```json theme={null} { "name": "My Agent - Basic Plan", "description": "100 credits for API access", "tags": ["ai", "assistant", "basic"] } ``` **price-config.json** (`PlanPriceConfig`) — a free plan (no charge to subscribe): ```json theme={null} { "isCrypto": true, "amounts": [], "receivers": [], "tokenAddress": "0x0000000000000000000000000000000000000000", "contractAddress": "0x0000000000000000000000000000000000000000", "feeController": "0x0000000000000000000000000000000000000000", "externalPriceAddress": "0x0000000000000000000000000000000000000000", "templateAddress": "0x0000000000000000000000000000000000000000" } ``` To charge a fixed crypto price instead, set `amounts` to the price in the token's smallest unit and `receivers` to the wallet that collects it (this is what `nevermined plans get-native-token-price-config` / `get-erc20-price-config` emit): ```json theme={null} { "isCrypto": true, "amounts": [1000000], "receivers": ["0xYourReceiverWallet"], "tokenAddress": "0x0000000000000000000000000000000000000000", "contractAddress": "0x0000000000000000000000000000000000000000", "feeController": "0x0000000000000000000000000000000000000000", "externalPriceAddress": "0x0000000000000000000000000000000000000000", "templateAddress": "0x0000000000000000000000000000000000000000" } ``` **credits-config.json** (`PlanCreditsConfig`) — grant 100 credits, burn 1 per request: ```json theme={null} { "isRedemptionAmountFixed": true, "redemptionType": 4, "onchainMirror": false, "durationSecs": 0, "amount": 100, "minAmount": 1, "maxAmount": 1 } ``` ### Config schemas `register-agent-and-plan` (and `nevermined plans register-credits-plan`) accept these JSON shapes. They match the SDK types exactly — the easiest way to produce a valid file is to run the matching `nevermined plans get-*-config` command and save its output, rather than hand-crafting the JSON. #### `--price-config` (`PlanPriceConfig`) | Field | Type | Notes | | - | - | - | | `isCrypto` | boolean | `true` for crypto/native/ERC-20 payments, `false` for fiat (Stripe/Braintree). Required. | | `amounts` | number\[] | Price(s) in the token's smallest unit (6-decimal units for USDC/EURC; `2000000` = \$2.00). Empty `[]` for a free plan. | | `receivers` | string\[] | Wallet address(es) that collect the payment. Empty `[]` for a free plan. Same length as `amounts`. | | `tokenAddress` | string | ERC-20 token address, or the zero address (`0x0000…0000`) for the native token / free / fiat plans. | | `contractAddress` | string | Price-calculator contract. Zero address unless using a smart-contract price. | | `feeController` | string | Fee-controller contract. Zero address uses the default. | | `externalPriceAddress` | string | External price contract. Zero address when unused. | | `templateAddress` | string | Template contract. Zero address except for pay-as-you-go plans. | | `currency` | string | Optional: `USD`, `EUR`, `USDC`, or `EURC`. When omitted, the backend infers it from the payment type. | Generators that emit this shape: `nevermined plans get-free-price-config`, `get-native-token-price-config`, `get-crypto-price-config`, `get-erc20-price-config`, `get-eurc-price-config`, `get-fiat-price-config`, `get-pay-as-you-go-price-config`. #### `--credits-config` (`PlanCreditsConfig`) | Field | Type | Notes | | - | - | - | | `isRedemptionAmountFixed` | boolean | `true` when every request burns a fixed number of credits (`minAmount == maxAmount`), `false` for a dynamic range. | | `redemptionType` | number | Who may redeem credits: `0` = global burner role, `1` = plan owner, `2` = plan role, `4` = subscriber. SDK helpers use `4` (`ONLY_SUBSCRIBER`). | | `onchainMirror` | boolean | `false` keeps the credit ledger off-chain (default). `true` mirrors each burn to the on-chain `NFT1155Credits` contract. | | `durationSecs` | number | Plan lifetime in seconds. `0` = non-expirable (credit-limited). `> 0` makes it a time-limited plan. | | `amount` | number | Credits granted when the plan is purchased. | | `minAmount` | number | Minimum credits burned per request. | | `maxAmount` | number | Maximum credits burned per request (equal to `minAmount` for fixed plans). | | `nftAddress` | string | Optional: NFT contract representing the plan's credits. Normally omitted — assigned by the backend. | Generators that emit this shape: `nevermined plans get-fixed-credits-config`, `get-dynamic-credits-config`, `get-expirable-duration-config`, `get-non-expirable-duration-config`, `get-pay-as-you-go-credits-config`. #### `--agent-api` (`AgentAPIAttributes`) | Field | Type | Notes | | - | - | - | | `endpoints` | object\[] | Allowlist of paid upstream endpoints, each `{ "": "" }` (e.g. `{ "POST": "https://…/:agentId/tasks" }`). Optional defense-in-depth on top of your library middleware. | | `openEndpoints` | string\[] | Endpoints that do **not** require a subscription (docs, health, etc.). Optional. | | `agentDefinitionUrl` | string | Optional link to an OpenAPI spec, MCP manifest, or A2A agent card (metadata only). | | `authType` | string | Upstream auth: `none`, `basic`, `bearer`, or `oauth`. Optional. | | `username` / `password` | string | Upstream credentials when `authType` is `basic`. | | `token` | string | Upstream bearer token when `authType` is `bearer` or `oauth`. | The CLI passes this object straight to the SDK, which wraps it as `agentApiAttributes` in the request body — you supply the unwrapped `AgentAPIAttributes` shown above. #### Generating valid configs ```bash theme={null} # A free plan that grants 100 credits, burning 1 per request: nevermined plans get-free-price-config --format json > price-config.json nevermined plans get-fixed-credits-config --credits-granted 100 --credits-per-request 1 \ --format json > credits-config.json nevermined agents register-agent-and-plan \ --agent-metadata agent-metadata.json \ --agent-api agent-api.json \ --plan-metadata plan-metadata.json \ --price-config price-config.json \ --credits-config credits-config.json ``` ## Updating Agents ### Update Agent Metadata Modify agent name, description, API endpoint, or other metadata: ```bash theme={null} nevermined agents update-agent-metadata \ --agent-metadata updated-metadata.json \ --agent-api updated-agent-api.json ``` Both `--agent-metadata` and `--agent-api` are required. As with registration, `--agent-api` is a JSON object (`AgentAPIAttributes`), not a bare URL. **updated-metadata.json**: ```json theme={null} { "name": "My AI Assistant Pro", "description": "Enhanced GPT-4 assistant with advanced capabilities", "version": "2.0.0", "tags": ["ai", "assistant", "gpt4", "premium"] } ``` ## Managing Payment Plans ### Add Payment Plan to Agent Associate an existing payment plan with an agent: ```bash theme={null} nevermined agents add-plan-to-agent --agent-id ``` Example: ```bash theme={null} nevermined agents add-plan-to-agent "did:nvm:plan123" --agent-id "did:nvm:agent456" ``` ### Remove Payment Plan from Agent Disassociate a payment plan from an agent: ```bash theme={null} nevermined agents remove-plan-from-agent --agent-id ``` Example: ```bash theme={null} nevermined agents remove-plan-from-agent "did:nvm:plan123" --agent-id "did:nvm:agent456" ``` ### List Plans Associated with Agent See which plans give access to an agent: ```bash theme={null} nevermined agents get-agent-plans ``` ## Integration Examples ### Example 1: Full Agent Setup Complete workflow to register and configure an AI agent: ```bash theme={null} #!/bin/bash # Complete agent setup script # 1. Create a payment plan first PLAN_ID=$(nevermined plans register-credits-plan \ --plan-metadata plan.json \ --price-config price.json \ --credits-config credits.json \ --format json | jq -r '.planId') echo "Created plan: $PLAN_ID" # 2. Register the agent with the plan AGENT_ID=$(nevermined agents register-agent \ --agent-metadata agent.json \ --agent-api agent-api.json \ --payment-plans "$PLAN_ID" \ --format json | jq -r '.agentId') echo "Registered agent: $AGENT_ID" # 3. Update agent metadata if needed nevermined agents update-agent-metadata $AGENT_ID \ --agent-metadata updated-agent.json \ --agent-api agent-api.json # 4. Verify agent is accessible nevermined agents get-agent $AGENT_ID echo "Agent setup complete!" ``` ### Example 2: One-Step Agent and Plan Registration Register an agent and its payment plan in a single command: ```bash theme={null} nevermined agents register-agent-and-plan \ --agent-metadata agent.json \ --agent-api agent-api.json \ --plan-metadata plan.json \ --price-config price.json \ --credits-config credits.json ``` ### Example 3: Multi-Plan Agent Register an agent with multiple pricing tiers: ```bash theme={null} # Create basic plan BASIC_PLAN=$(nevermined plans register-credits-plan \ --plan-metadata basic-plan.json \ --price-config basic-price.json \ --credits-config basic-credits.json \ --format json | jq -r '.planId') # Create premium plan PREMIUM_PLAN=$(nevermined plans register-credits-plan \ --plan-metadata premium-plan.json \ --price-config premium-price.json \ --credits-config premium-credits.json \ --format json | jq -r '.planId') # Register agent with both plans nevermined agents register-agent \ --agent-metadata agent.json \ --agent-api agent-api.json \ --payment-plans "$BASIC_PLAN,$PREMIUM_PLAN" ``` ## JSON Output for Automation Use `--format json` to integrate with other tools: ```bash theme={null} # Get agent data AGENT=$(nevermined agents get-agent "did:nvm:agent123" --format json) # Extract fields NAME=$(echo $AGENT | jq -r '.name') echo "Agent: $NAME" ``` ## Best Practices ### 1. Use Descriptive Metadata Provide comprehensive information about your agent: ```json theme={null} { "name": "GPT-4 Code Assistant", "description": "AI-powered code generation and debugging assistant", "version": "1.2.0", "author": "YourCompany", "tags": ["code", "ai", "programming", "debugging"] } ``` ### 2. Implement Proper API Endpoints Ensure your agent API follows best practices: * Use HTTPS for all endpoints * Implement rate limiting * Return proper HTTP status codes * Include error handling ### 3. Test Before Production Always test agents in sandbox environment: ```bash theme={null} # Register in sandbox nevermined --profile sandbox agents register-agent \ --agent-metadata agent.json \ --agent-api staging-agent-api.json \ --payment-plans "$STAGING_PLAN_ID" # Test the agent nevermined --profile sandbox agents get-agent $STAGING_AGENT_ID # Once verified, deploy to production nevermined --profile production agents register-agent \ --agent-metadata agent.json \ --agent-api agent-api.json \ --payment-plans "$PROD_PLAN_ID" ``` ## Common Issues ### "Payment plan not found" Verify the payment plan exists and you're using the correct plan ID: ```bash theme={null} # List all your plans nevermined plans get-plans # Verify specific plan nevermined plans get-plan ``` ### "Insufficient permissions" Ensure you're the agent owner or have proper permissions: ```bash theme={null} # Check agent details nevermined agents get-agent # Verify you're using the correct profile nevermined config show ``` ## Next Steps * [Purchases](./purchases.md) - Users ordering your agent plans * [Querying](./querying.md) - Accessing agents with X402 tokens * [Plans](./plans.md) - Creating payment plans for your agents # Getting Started Source: https://nevermined.ai/docs/api-reference/cli/getting-started Complete guide to installing and configuring the Nevermined CLI # Getting Started Complete guide to installing and configuring the Nevermined CLI. ## Prerequisites Before installing the CLI, ensure you have: * **Node.js** >= 18.0.0 * **npm** or **pnpm** package manager * A Nevermined account with API key ## Getting Your API Key To interact with the Nevermined API, you need an API key. Follow the [Get Your API Key](/docs/getting-started/get-your-api-key) guide to create one. ## Installation ### Option 1: Global Installation (Recommended) Install the CLI globally to use the `nevermined` command from anywhere: ```bash theme={null} npm install -g @nevermined-io/cli ``` Verify installation: ```bash theme={null} nevermined --version ``` > **Renamed from `nvm`**: earlier versions installed the binary as `nvm`, which collided with [Node Version Manager](https://github.com/nvm-sh/nvm). The command is now `nevermined`. Update any scripts that called `nvm `. ### Option 2: Using npx (No Installation) Run the CLI without installing: ```bash theme={null} npx @nevermined-io/cli --help ``` This is useful for one-off commands or trying the CLI before installing. ### Option 3: From Source For development or contributing: ```bash theme={null} # Clone the repository git clone https://github.com/nevermined-io/payments cd payments/cli # Install dependencies pnpm install # Build the project pnpm build:manifest # Run the CLI ./bin/run.js --help ``` ## Authentication ### Browser Login (Recommended) The quickest way to authenticate: ```bash theme={null} nevermined login ``` This opens your browser to sign in with Google, X, or email. After login, your API key is automatically captured and saved to your CLI config. Options: * `--environment ` — Target environment (default: sandbox) * `--profile ` — Config profile to save to (default: default) * `--no-browser` — Print the login URL instead of opening the browser Examples: ```bash theme={null} nevermined login --environment live nevermined login --profile production --environment live nevermined login --no-browser ``` ### Logout Remove your API key from the CLI config: ```bash theme={null} nevermined logout nevermined logout --profile production nevermined logout --all-profiles ``` ## Configuration ### Interactive Setup The easiest way to configure the CLI is using the interactive setup: ```bash theme={null} nevermined config init ``` This will prompt you for: * **NVM API Key**: Your API key from nevermined.app * **Environment**: Choose from: * `sandbox` - Testing (recommended for learning and development) * `live` - Production environment Example: ```bash theme={null} $ nevermined config init ? Enter your NVM API Key: sandbox:eyJxxxxaaaabbbbbbbb ? Select environment: sandbox ✅ Configuration saved to /home/user/.config/nvm/config.json ``` ### Configuration File The CLI stores configuration in `~/.config/nvm/config.json`: ```json theme={null} { "profiles": { "default": { "nvmApiKey": "live:eyJxxxxaaaabbbbbbbb", "environment": "live" } }, "activeProfile": "default" } ``` ### Multiple Profiles Create multiple profiles for different environments or accounts: ```bash theme={null} # Initialize with default profile nevermined config init # Create a production profile nevermined config set profiles.production.nvmApiKey nvm-yyyyyyyy... nevermined config set profiles.production.environment live # Switch active profile nevermined config set activeProfile production ``` Use a specific profile for a command: ```bash theme={null} nevermined --profile production plans get-plans ``` ### Environment Variables Override configuration with environment variables: ```bash theme={null} # Set API key export NVM_API_KEY=sandbox:eyJxxxxaaaabbbbbbbb # Set environment export NVM_ENVIRONMENT=sandbox # Run commands nevermined plans get-plans ``` This is useful for: * CI/CD pipelines * Temporary configuration changes * Scripting ### View Configuration Display your current configuration: ```bash theme={null} nevermined config show ``` Output: ``` Current Configuration ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Active Profile: default Environment: sandbox API Key: live:eyJxxxxaaaabbbbbbbb (truncated) ``` ## Verify Setup Test your configuration by listing available plans: ```bash theme={null} nevermined plans get-plans ``` If configured correctly, you should see a table of available payment plans. ## Environment Guide Choose the right environment for your use case: | Environment | Use Case | Blockchain | Payments | | - | - | - | - | | `sandbox` | Development, learning, testing | Test network | Test credits | | `live` | Production | Mainnet | Real payments | **Recommendation**: Start with `sandbox` for development and testing. ## Common Issues ### "Command not found: nevermined" After global installation, if `nevermined` command is not found: 1. Verify installation: `npm list -g @nevermined-io/cli` 2. Check your PATH includes npm global bin directory 3. Restart your terminal 4. Try using the full path: `npx @nevermined-io/cli` ### "API Key not found" If you get an API key error: ```bash theme={null} # Browser login (recommended) nevermined login # Or initialize configuration manually nevermined config init # Or set environment variable export NVM_API_KEY=your-api-key-here ``` ### Permission Errors If you get permission errors during global installation: ```bash theme={null} # Use npx instead npx @nevermined-io/cli --help # Or install without sudo using nvm/volta ``` ## Next Steps Now that you've installed and configured the CLI, explore: * [Plans](./plans.md) - Create and manage payment plans * [Agents](./agents.md) - Register AI agents * [Purchases](./purchases.md) - Order plans and make payments * [Querying](./querying.md) - Query agents with access tokens ## Getting Help Get help for any command: ```bash theme={null} # General help nevermined --help # Topic help nevermined plans --help # Command help nevermined plans get-plan --help ``` For support: * Documentation: [https://nevermined.ai/docs](https://nevermined.ai/docs) * Issues: [https://github.com/nevermined-io/payments/issues](https://github.com/nevermined-io/payments/issues) * Discord: [https://discord.gg/GZju2qScKq](https://discord.gg/GZju2qScKq) # Other Commands Source: https://nevermined.ai/docs/api-reference/cli/other-commands Reference guide for additional CLI commands including configuration, facilitator operations, organizations, and utilities # Other Commands Reference guide for additional CLI commands including configuration, facilitator operations, organizations, and utilities. ## Configuration Commands ### Login Authenticate via browser login. Opens your browser, waits for you to sign in, and saves the API key to your CLI config: ```bash theme={null} nevermined login nevermined login --environment live nevermined login --profile production --environment live nevermined login --no-browser # Print URL instead of opening browser ``` ### Logout Remove your API key from the local configuration so you need to authenticate again: ```bash theme={null} nevermined logout nevermined logout --profile production nevermined logout --all-profiles # Remove API keys from every profile ``` ### Initialize Configuration Set up your CLI configuration interactively: ```bash theme={null} nevermined config init ``` Interactive prompts: * NVM API Key * Environment (sandbox, live) * Profile name (optional) Flags: * `--api-key` — Provide API key non-interactively * `--environment` — Set environment (sandbox, live) * `-i, --interactive` — Interactive mode (default: true) ### View Configuration Display your current configuration: ```bash theme={null} nevermined config show # Show all profiles nevermined config show --all ``` Output: ``` Current Configuration Active Profile: default Environment: sandbox API Key: sandbox:eyJxxxxaaaa...bbbbbbbb (truncated) Config File: /home/user/.config/nvm/config.json ``` ### Set Configuration Values Update specific configuration values: ```bash theme={null} # Set API key nevermined config set nvmApiKey sandbox:eyJxxxxaaaa...bbbbbbbb # Set environment nevermined config set environment sandbox # Set active profile nevermined config set activeProfile production ``` ### Configuration File Structure The config file at `~/.config/nvm/config.json`: ```json theme={null} { "profiles": { "default": { "nvmApiKey": "sandbox:eyJxxxxaaaa...bbbbbbbb", "environment": "sandbox" }, "production": { "nvmApiKey": "live:eyJyyyybbbb...", "environment": "live" } }, "activeProfile": "default" } ``` ## Facilitator Commands Facilitator commands are used by agent owners to verify and settle permissions (credit burning). ### Verify Permissions Verify that a subscriber has permission to use credits from a payment plan. This simulates credit usage without actually burning credits: ```bash theme={null} nevermined facilitator verify-permissions \ --params verify.json ``` **verify.json**: ```json theme={null} { "paymentRequired": "eyJhbGci...", "x402AccessToken": "eyJhbGci...", "maxAmount": "5" } ``` ### Settle Permissions Settle (burn) credits from a subscriber's payment plan. This executes the actual credit consumption: ```bash theme={null} nevermined facilitator settle-permissions \ --params settle.json ``` **settle.json**: ```json theme={null} { "paymentRequired": "eyJhbGci...", "x402AccessToken": "eyJhbGci...", "maxAmount": "5" } ``` ## Organizations Commands Manage organization members and settings. ### List Members View all members in your organization: ```bash theme={null} nevermined organizations get-members # Filter by role nevermined organizations get-members --role admin # Filter active members nevermined organizations get-members --is-active true # Pagination nevermined organizations get-members --page 1 --offset 10 ``` ### Create Member Add a new member to your organization: ```bash theme={null} nevermined organizations create-member # With email and role nevermined organizations create-member --user-email "john@example.com" --user-role "developer" ``` Flags: * `--user-email` — Member's email address (optional) * `--user-role` — Member's role (optional) ### Connect Stripe Account Connect a user with Stripe for fiat payments: ```bash theme={null} nevermined organizations connect-stripe-account \ --user-email "john@example.com" \ --user-country-code "US" \ --return-url "https://yourapp.com/stripe-callback" ``` All flags are required: * `--user-email` — User's email address * `--user-country-code` — Two-letter country code * `--return-url` — URL to redirect after Stripe connection ## X402 Token Commands ### Get X402 Access Token Generate an access token for a plan with delegated permissions: ```bash theme={null} nevermined x402token get-x402-access-token ``` Example: ```bash theme={null} nevermined x402token get-x402-access-token "did:nvm:abc123" ``` Optional flags: * `--agent-id` — Target agent ID * `--redemption-limit` — Maximum credits that can be redeemed * `--order-limit` — Maximum number of orders * `--expiration` — Token expiration time Example with options: ```bash theme={null} nevermined x402token get-x402-access-token "did:nvm:abc123" \ --agent-id "did:nvm:agent456" \ --redemption-limit 100 \ --expiration 3600 ``` Output: ``` X402 Access Token Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... Plan ID: did:nvm:abc123 ``` ### Save Token Save token for later use: ```bash theme={null} # Save to environment variable export X402_TOKEN=$(nevermined x402token get-x402-access-token "did:nvm:abc123" \ --format json | jq -r '.token') # Use token in requests curl -H "payment-signature: $X402_TOKEN" https://agent-api.example.com ``` ## Global Flags All commands support these global flags: ### Format Flag Control output format: ```bash theme={null} # Table output (default) nevermined plans get-plans # JSON output nevermined plans get-plans --format json # Quiet output (minimal) nevermined plans get-plans --format quiet ``` ### Profile Flag Use a specific configuration profile: ```bash theme={null} # Use production profile nevermined --profile production plans get-plans # Use staging profile nevermined --profile staging agents get-agent ``` ### Verbose Flag Enable verbose output with detailed logging: ```bash theme={null} nevermined plans order-plan "did:nvm:abc123" --verbose ``` Output includes: * Request/response details * Stack traces for errors * Debug information ## Utility Commands ### Version Information Check CLI version: ```bash theme={null} nevermined --version ``` ### Help Get help for commands: ```bash theme={null} # General help nevermined --help # Topic help nevermined plans --help nevermined agents --help nevermined config --help # Command help nevermined plans get-plan --help nevermined agents register-agent --help ``` ## Scripting Examples ### Environment Switcher Switch between environments easily: ```bash theme={null} #!/bin/bash case $1 in production) nevermined config set activeProfile production echo "Switched to production environment" ;; sandbox) nevermined config set activeProfile default echo "Switched to sandbox environment" ;; *) echo "Usage: $0 {production|sandbox}" exit 1 ;; esac nevermined config show ``` ### Multi-Profile Operations Run commands across multiple profiles: ```bash theme={null} #!/bin/bash PROFILES=("default" "production") COMMAND="$@" for PROFILE in "${PROFILES[@]}"; do echo "Profile: $PROFILE" nevermined --profile $PROFILE $COMMAND echo "" done ``` Usage: ```bash theme={null} ./multi-profile.sh plans get-plans ``` ## Integration Examples ### CI/CD Pipeline Use CLI in CI/CD: ```yaml theme={null} # .github/workflows/deploy-agent.yml name: Deploy Agent on: push: tags: - 'v*' jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install CLI run: npm install -g @nevermined-io/cli - name: Configure CLI run: | nevermined config set nvmApiKey ${{ secrets.NVM_API_KEY }} nevermined config set environment live - name: Register Agent run: | nevermined agents register-agent \ --agent-metadata agent.json \ --agent-api "https://api.example.com" \ --payment-plans "${{ secrets.PLAN_ID }}" ``` ## Common Issues ### "Config file not found" Initialize configuration: ```bash theme={null} nevermined login # or nevermined config init ``` ### "Invalid profile" Check available profiles: ```bash theme={null} nevermined config show --all ``` ### "Permission denied" Fix config file permissions: ```bash theme={null} chmod 600 ~/.config/nvm/config.json ``` ## Next Steps * [Getting Started](./getting-started.md) - Installation and setup * [Plans](./plans.md) - Create and manage plans * [Agents](./agents.md) - Register and manage agents * [Purchases](./purchases.md) - Order plans and manage credits * [Querying](./querying.md) - Query agents with X402 tokens # Managing Payment Plans Source: https://nevermined.ai/docs/api-reference/cli/plans Complete guide to creating and managing payment plans with the Nevermined CLI # Managing Payment Plans Complete guide to creating and managing payment plans with the Nevermined CLI. ## Overview Payment plans define how users can access your AI agents and services. Plans can be: * **Credits-based**: Pay per API call or credit consumed * **Time-based**: Subscription access for a duration * **Trial plans**: One-time-use plans for testing (credits or time limited) ## Listing Plans View all available payment plans: ```bash theme={null} # Table output (default) nevermined plans get-plans # JSON output for scripting nevermined plans get-plans --format json # With pagination and sorting nevermined plans get-plans --page 1 --offset 10 --sort-by name --sort-order asc ``` ## Getting Plan Details Retrieve detailed information about a specific plan: ```bash theme={null} nevermined plans get-plan ``` Example: ```bash theme={null} nevermined plans get-plan "did:nvm:abc123" ``` Output includes: * Plan metadata (name, description, creator) * Pricing configuration * Credits configuration * Payment token information ## Checking Plan Balance Check your credit balance for a plan: ```bash theme={null} # Your balance nevermined plans get-plan-balance # Check balance for specific address nevermined plans get-plan-balance --account-address "0x1234..." ``` ## Getting Agents for a Plan List all agents accessible through a specific plan: ```bash theme={null} nevermined plans get-agents-associated-to-a-plan # With pagination nevermined plans get-agents-associated-to-a-plan --pagination '{"page": 1, "offset": 10}' ``` ## Creating Plans ### Flexible Plan Registration Register a plan with full control over price and credits/duration configuration: ```bash theme={null} nevermined plans register-plan \ --plan-metadata plan-metadata.json \ --price-config price-config.json \ --credits-config credits-config.json ``` Optional flags: * `--nonce` — Custom nonce value * `--access-limit` — Maximum number of times the plan can be ordered ### Credits Plan Create a pay-per-use plan with credits: ```bash theme={null} nevermined plans register-credits-plan \ --plan-metadata plan-metadata.json \ --price-config price-config.json \ --credits-config credits-config.json ``` **plan-metadata.json**: ```json theme={null} { "name": "My AI Agent - Basic Plan", "description": "100 credits for API access", "tags": ["ai", "assistant", "basic"], "customData": { "category": "AI Assistant" } } ``` **price-config.json** (`PlanPriceConfig`) — charge a fixed crypto price; `amounts` is in the token's smallest unit (e.g. `1000000` = 1 USDC at 6 decimals) and `receivers` collects it (this is what `nevermined plans get-erc20-price-config` / `get-native-token-price-config` emit): ```json theme={null} { "isCrypto": true, "amounts": [1000000], "receivers": ["0xYourReceiverWallet"], "tokenAddress": "0x0000000000000000000000000000000000000000", "contractAddress": "0x0000000000000000000000000000000000000000", "feeController": "0x0000000000000000000000000000000000000000", "externalPriceAddress": "0x0000000000000000000000000000000000000000", "templateAddress": "0x0000000000000000000000000000000000000000" } ``` **credits-config.json** (`PlanCreditsConfig`) — grant 100 credits, burn 1 per request (what `nevermined plans get-fixed-credits-config` emits): ```json theme={null} { "isRedemptionAmountFixed": true, "redemptionType": 4, "onchainMirror": false, "durationSecs": 0, "amount": 100, "minAmount": 1, "maxAmount": 1 } ``` ### Time-Based Plan Create a subscription plan with time-limited access: ```bash theme={null} nevermined plans register-time-plan \ --plan-metadata plan-metadata.json \ --price-config price-config.json \ --credits-config credits-config.json ``` **credits-config.json** (for time plan) (`PlanCreditsConfig`) — a time-limited plan sets `durationSecs > 0` (what `nevermined plans get-expirable-duration-config` emits): ```json theme={null} { "isRedemptionAmountFixed": false, "redemptionType": 4, "onchainMirror": false, "durationSecs": 2592000, "amount": 1, "minAmount": 1, "maxAmount": 1 } ``` `durationSecs` is in seconds (2592000 = 30 days). ### Trial Plans Trial plans can only be purchased once per user and are useful for letting users test your agents. **Credits trial** (limited by credits): ```bash theme={null} nevermined plans register-credits-trial-plan \ --plan-metadata plan-metadata.json \ --price-config price-config.json \ --credits-config credits-config.json ``` **Time trial** (limited by duration): ```bash theme={null} nevermined plans register-time-trial-plan \ --plan-metadata plan-metadata.json \ --price-config price-config.json \ --credits-config credits-config.json ``` ## Ordering Plans ### Crypto Payment Purchase a plan with cryptocurrency: ```bash theme={null} nevermined plans order-plan ``` ### Fiat Payment Initiate a plan purchase with fiat payment. Returns a URL where the user can complete the payment: ```bash theme={null} nevermined plans order-fiat-plan ``` ## Minting Credits ### Mint Credits Add credits to a plan and transfer them to a receiver (plan owner only): ```bash theme={null} nevermined plans mint-plan-credits \ --credits-amount 1000 \ --credits-receiver "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb" ``` ### Mint Expirable Credits Add time-limited credits: ```bash theme={null} nevermined plans mint-plan-expirable \ --credits-amount 1000 \ --credits-receiver "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb" \ --credits-duration 2592000 ``` The `--credits-duration` flag is optional and specifies duration in seconds. ## Redeeming Credits Credit redemption (burning credits after a paid request) is performed via the x402 facilitator, not via a dedicated `plans` command. The legacy `nevermined plans redeem-credits` command was removed because the backend exposes no direct redeem endpoint — the only burn path is `POST /api/v1/x402/settle`. Migration (subscriber side — get an access token): ```bash theme={null} nevermined x402token get-x402-access-token --format json # → { "accessToken": "eyJ4NDAyVm..." } ``` Migration (agent side — verify and settle): ```bash theme={null} # Build the params JSON once cat > /tmp/settle-params.json <", "extra": { "version": "1" } }], "extensions": {} }, "x402AccessToken": "", "agentRequestId": "", "maxAmount": "5" } EOF nevermined facilitator verify-permissions --params "$(cat /tmp/settle-params.json)" --format json nevermined facilitator settle-permissions --params "$(cat /tmp/settle-params.json)" --format json # → { "success": true, "creditsRedeemed": "5", "remainingBalance": "...", ... } ``` `settle-permissions` is idempotent on `agentRequestId` — replaying the same id returns the same transaction id without double-burning. ## Price Configuration Helpers The CLI provides helper commands to build price configuration objects: ```bash theme={null} # Free (no payment required) nevermined plans get-free-price-config # Fiat price nevermined plans get-fiat-price-config --amount 1000 --receiver "0x123..." # Crypto price nevermined plans get-crypto-price-config --amount 1000 --receiver "0x123..." # Crypto with specific token nevermined plans get-crypto-price-config --amount 1000 --receiver "0x123..." --token-address "0xToken..." # Native token price nevermined plans get-native-token-price-config --amount 1000 --receiver "0x123..." # ERC20 token price nevermined plans get-erc20-price-config --amount 1000 --receiver "0x123..." --token-address "0xToken..." # EURC (Euro stablecoin) price nevermined plans get-eurc-price-config --amount 1000 --receiver "0x123..." # Pay-as-you-go price nevermined plans get-pay-as-you-go-price-config --amount 1000 --receiver "0x123..." ``` ## Credits Configuration Helpers Helper commands to build credits configuration objects: ```bash theme={null} # Fixed credits (same amount per request) nevermined plans get-fixed-credits-config --credits-granted 100 --credits-per-request 1 # Dynamic credits (range per request) nevermined plans get-dynamic-credits-config --credits-granted 100 \ --min-credits-per-request 1 --max-credits-per-request 10 # Pay-as-you-go credits nevermined plans get-pay-as-you-go-credits-config # Expirable duration nevermined plans get-expirable-duration-config --duration-of-plan 2592000 # Non-expirable nevermined plans get-non-expirable-duration-config ``` ## Advanced Operations ### Set Onchain Mirror Mark whether burns of these credits are mirrored on-chain: ```bash theme={null} nevermined plans set-onchain-mirror \ --credits-config credits-config.json \ --onchain-mirror ``` ### Set Redemption Type Set the redemption type in a credits configuration: ```bash theme={null} nevermined plans set-redemption-type \ --credits-config credits-config.json \ --redemption-type "fixed" ``` ## JSON Output for Scripting Use `--format json` for machine-readable output: ```bash theme={null} # Get plan details as JSON PLAN_DATA=$(nevermined plans get-plan "did:nvm:abc123" --format json) # Extract specific field with jq PLAN_NAME=$(echo $PLAN_DATA | jq -r '.name') echo "Plan: $PLAN_NAME" ``` ## Examples ### Example 1: Create a Basic AI Agent Plan ```bash theme={null} # 1. Create plan metadata file cat > plan.json << EOF { "name": "ChatBot Basic", "description": "100 API calls for $10", "tags": ["chatbot", "ai"] } EOF # 2. Create price configuration (PlanPriceConfig) cat > price.json << EOF { "isCrypto": true, "amounts": [10000000], "receivers": ["0xYourReceiverWallet"], "tokenAddress": "0x0000000000000000000000000000000000000000", "contractAddress": "0x0000000000000000000000000000000000000000", "feeController": "0x0000000000000000000000000000000000000000", "externalPriceAddress": "0x0000000000000000000000000000000000000000", "templateAddress": "0x0000000000000000000000000000000000000000" } EOF # 3. Create credits configuration (PlanCreditsConfig) — 100 credits, burn 1-5 per request cat > credits.json << EOF { "isRedemptionAmountFixed": false, "redemptionType": 4, "onchainMirror": false, "durationSecs": 0, "amount": 100, "minAmount": 1, "maxAmount": 5 } EOF # 4. Register the plan nevermined plans register-credits-plan \ --plan-metadata plan.json \ --price-config price.json \ --credits-config credits.json ``` ### Example 2: Monitor Plan Balance ```bash theme={null} #!/bin/bash PLAN_ID="did:nvm:abc123" MIN_CREDITS=10 BALANCE=$(nevermined plans get-plan-balance $PLAN_ID --format json | jq -r '.balance') if [ "$BALANCE" -lt "$MIN_CREDITS" ]; then echo "Low balance: $BALANCE credits remaining" else echo "Balance healthy: $BALANCE credits" fi ``` ## Best Practices ### 1. Use Descriptive Metadata Make your plans discoverable with clear names and descriptions: ```json theme={null} { "name": "GPT-4 API Access - Starter", "description": "1000 GPT-4 API calls per month with 24/7 support", "tags": ["gpt4", "ai", "api", "starter"] } ``` ### 2. Set Appropriate Credit Limits Configure the min/max credits burned per request to prevent abuse (fields of `PlanCreditsConfig`): ```json theme={null} { "minAmount": 1, "maxAmount": 10 } ``` ### 3. Test in Sandbox First Always test new plans in sandbox before going live: ```bash theme={null} # Test in sandbox nevermined --profile sandbox plans register-credits-plan \ --plan-metadata metadata.json \ --price-config price.json \ --credits-config credits.json # Verify it works nevermined --profile sandbox plans get-plan ``` ## Common Issues ### "Insufficient balance" When registering plans, ensure you have enough credits or tokens in your account. ### "Plan not found" Ensure you're using the correct environment and plan ID: ```bash theme={null} # Check which environment you're using nevermined config show # Try the correct profile nevermined --profile sandbox plans get-plan ``` ## Next Steps * [Agents](./agents.md) - Register agents with your plans * [Purchases](./purchases.md) - Order plans and make payments * [Querying](./querying.md) - Query agents with access tokens # Making Purchases Source: https://nevermined.ai/docs/api-reference/cli/purchases Complete guide to ordering payment plans and managing credits with the Nevermined CLI # Making Purchases Complete guide to ordering payment plans and managing credits with the Nevermined CLI. ## Overview Purchasing a payment plan gives you access to AI agents and services. Once you order a plan, you receive credits or time-based access that you can use to query agents. ## Ordering a Plan ### Crypto Payment Purchase a payment plan with cryptocurrency: ```bash theme={null} nevermined plans order-plan ``` Example: ```bash theme={null} nevermined plans order-plan "did:nvm:abc123" ``` Output: ``` Plan Order Success Plan ID: did:nvm:abc123 Credits Purchased: 100 Transaction Hash: 0x1234567890abcdef... Status: Confirmed ``` ### Fiat Payment Initiate a plan purchase with fiat. This returns a URL where you can complete the payment: ```bash theme={null} nevermined plans order-fiat-plan ``` Example: ```bash theme={null} nevermined plans order-fiat-plan "did:nvm:abc123" ``` ## Checking Your Credits ### View Plan Balance Check how many credits you have remaining: ```bash theme={null} # Your balance nevermined plans get-plan-balance # Balance for specific address nevermined plans get-plan-balance --account-address "0x123..." ``` Example output: ``` Plan Balance Plan ID: did:nvm:abc123 Credits Remaining: 75 ``` ### Monitor Multiple Plans Check balances for all your plans: ```bash theme={null} #!/bin/bash PLANS=("did:nvm:plan1" "did:nvm:plan2" "did:nvm:plan3") for PLAN in "${PLANS[@]}"; do echo "Checking balance for $PLAN..." nevermined plans get-plan-balance $PLAN echo "" done ``` ## Refilling Credits ### Purchase Additional Credits Re-order a plan to add more credits to your existing balance: ```bash theme={null} nevermined plans order-plan ``` ### Bulk Credit Purchase Order multiple plans at once: ```bash theme={null} #!/bin/bash PLANS=("did:nvm:plan1" "did:nvm:plan2") for PLAN in "${PLANS[@]}"; do echo "Ordering $PLAN..." nevermined plans order-plan $PLAN done ``` ## Credit Usage ### Set Up Balance Monitoring Create a script to alert when credits run low: ```bash theme={null} #!/bin/bash PLAN_ID="did:nvm:abc123" MIN_CREDITS=10 BALANCE=$(nevermined plans get-plan-balance $PLAN_ID --format json | jq -r '.balance') if [ "$BALANCE" -lt "$MIN_CREDITS" ]; then echo "LOW CREDITS ALERT" echo "Plan: $PLAN_ID" echo "Remaining: $BALANCE credits" fi ``` ### Auto-Refill Script Automatically refill credits when low: ```bash theme={null} #!/bin/bash # Run as cron job: 0 */6 * * * /path/to/auto-refill.sh PLAN_ID="did:nvm:abc123" MIN_CREDITS=20 BALANCE=$(nevermined plans get-plan-balance $PLAN_ID --format json | jq -r '.balance') if [ "$BALANCE" -lt "$MIN_CREDITS" ]; then echo "$(date): Credits low ($BALANCE), ordering more..." nevermined plans order-plan $PLAN_ID if [ $? -eq 0 ]; then NEW_BALANCE=$(nevermined plans get-plan-balance $PLAN_ID --format json | jq -r '.balance') echo "$(date): New balance: $NEW_BALANCE credits" else echo "$(date): ERROR - Failed to order credits" fi else echo "$(date): Balance healthy: $BALANCE credits" fi ``` ## Examples ### Example 1: Complete Purchase Flow ```bash theme={null} #!/bin/bash # 1. Browse available plans echo "Available Plans:" nevermined plans get-plans # 2. Get details about a specific plan PLAN_ID="did:nvm:abc123" nevermined plans get-plan $PLAN_ID # 3. Check current balance echo "Current balance:" nevermined plans get-plan-balance $PLAN_ID # 4. Purchase the plan echo "Purchasing plan..." nevermined plans order-plan $PLAN_ID # 5. Verify purchase echo "New balance:" nevermined plans get-plan-balance $PLAN_ID # 6. Get access token for using the service echo "Getting access token..." nevermined x402token get-x402-access-token $PLAN_ID ``` ### Example 2: Team Credit Management ```bash theme={null} #!/bin/bash TEAM_PLANS=("did:nvm:plan1" "did:nvm:plan2" "did:nvm:plan3") # Purchase for entire team for PLAN in "${TEAM_PLANS[@]}"; do echo "Ordering $PLAN for team..." nevermined plans order-plan $PLAN done # Generate team usage report echo "Team Balances:" for PLAN in "${TEAM_PLANS[@]}"; do nevermined plans get-plan-balance $PLAN --format json | jq '{plan: .planId, remaining: .balance}' done ``` ## Best Practices ### 1. Monitor Credit Levels Set up monitoring to avoid service interruptions: ```bash theme={null} # Daily cron job 0 9 * * * /path/to/check-credits.sh ``` ### 2. Plan Ahead Purchase credits before you need them to avoid delays. ### 3. Use Automation Implement auto-refill to ensure continuous service: ```bash theme={null} # Check every 6 hours 0 */6 * * * /path/to/auto-refill.sh ``` ### 4. Use JSON Output for Scripting Always use `--format json` in scripts: ```bash theme={null} BALANCE=$(nevermined plans get-plan-balance $PLAN_ID --format json | jq -r '.balance') ``` ## Common Issues ### "Insufficient funds" Ensure your wallet has enough balance for crypto payments. ### "Plan not available" The plan may be sold out or no longer active: ```bash theme={null} # Verify plan status nevermined plans get-plan # Look for alternative plans nevermined plans get-plans ``` ## Next Steps * [Querying](./querying.md) - Use your credits to query agents * [Plans](./plans.md) - Learn about different plan types * [Agents](./agents.md) - Discover available agents # Querying Agents Source: https://nevermined.ai/docs/api-reference/cli/querying Complete guide to accessing AI agents using x402 access tokens and the payment-signature header with the Nevermined CLI # Querying Agents Complete guide to accessing AI agents using X402 access tokens with the Nevermined CLI. ## Overview After purchasing a payment plan, you can query AI agents using X402 access tokens. The X402 protocol enables pay-per-use access with automatic credit deduction. ## Getting an Access Token ### Generate X402 Token Get an access token for a purchased plan: ```bash theme={null} nevermined x402token get-x402-access-token ``` Example: ```bash theme={null} nevermined x402token get-x402-access-token "did:nvm:abc123" ``` Optional flags: * `--agent-id` — Target agent ID * `--redemption-limit` — Maximum credits that can be redeemed * `--order-limit` — Maximum number of orders * `--expiration` — Token expiration time Example with options: ```bash theme={null} nevermined x402token get-x402-access-token "did:nvm:abc123" \ --agent-id "did:nvm:agent456" \ --redemption-limit 100 \ --expiration 3600 ``` Output: ``` X402 Access Token Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... Plan ID: did:nvm:abc123 Use this token in the payment-signature header: curl -H "payment-signature: eyJhbGci..." https://agent-api.example.com ``` ### Token Format The token is a JWT containing: * Plan ID * Subscriber address * Credits information * Signature for verification ### Save Token for Reuse Store the token for multiple requests: ```bash theme={null} # Get token and save to file TOKEN=$(nevermined x402token get-x402-access-token "did:nvm:abc123" --format json | jq -r '.token') echo $TOKEN > ~/.nvm-token # Use token from file curl -H "payment-signature: $(cat ~/.nvm-token)" https://agent-api.example.com/query ``` ## Using X402 Tokens ### HTTP Requests with curl Query an agent using curl: ```bash theme={null} # Get access token TOKEN=$(nevermined x402token get-x402-access-token "did:nvm:abc123" --format json | jq -r '.token') # Make request with payment-signature header curl -X POST https://agent-api.example.com/v1/chat \ -H "Content-Type: application/json" \ -H "payment-signature: $TOKEN" \ -d '{ "message": "Hello, AI assistant!", "temperature": 0.7 }' ``` ### With JavaScript/TypeScript ```javascript theme={null} // Get token from CLI const { execSync } = require('child_process') const planId = 'did:nvm:abc123' const tokenCmd = `nevermined x402token get-x402-access-token ${planId} --format json` const result = JSON.parse(execSync(tokenCmd).toString()) const token = result.token // Make API request const response = await fetch('https://agent-api.example.com/v1/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', 'payment-signature': token }, body: JSON.stringify({ message: 'Hello, AI assistant!', temperature: 0.7 }) }) const data = await response.json() console.log(data) ``` ### With Python ```python theme={null} import subprocess import json import requests # Get token from CLI plan_id = 'did:nvm:abc123' cmd = f'nevermined x402token get-x402-access-token {plan_id} --format json' result = subprocess.run(cmd.split(), capture_output=True, text=True) token_data = json.loads(result.stdout) token = token_data['token'] # Make API request response = requests.post( 'https://agent-api.example.com/v1/chat', headers={ 'Content-Type': 'application/json', 'payment-signature': token }, json={ 'message': 'Hello, AI assistant!', 'temperature': 0.7 } ) print(response.json()) ``` ## Verifying Requests ### Manual Verification Verify that a request is valid before processing (for agent owners): ```bash theme={null} nevermined facilitator verify-permissions \ --params verify.json ``` **verify.json**: ```json theme={null} { "paymentRequired": "eyJhbGci...", "x402AccessToken": "eyJhbGci...", "maxAmount": "5" } ``` ### Automatic Verification (SDK) For agent implementations, use the SDK for automatic verification: ```typescript theme={null} import { Payments, buildPaymentRequired } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' }) // Build payment requirements for your plan/agent const paymentRequired = buildPaymentRequired({ planId: 'did:nvm:abc123', endpoint: '/v1/chat', agentId: process.env.NVM_AGENT_ID!, httpVerb: 'POST' }) // Verify incoming request const verification = await payments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: req.headers['payment-signature'] as string, maxAmount: BigInt(5) }) if (!verification.isValid) { return res.status(402).json({ error: 'Payment required' }) } ``` ## Settling Credits ### Burn Credits After Use After processing a request, burn the credits (agent owners): ```bash theme={null} nevermined facilitator settle-permissions \ --params settle.json ``` **settle.json**: ```json theme={null} { "paymentRequired": "eyJhbGci...", "x402AccessToken": "eyJhbGci...", "maxAmount": "5" } ``` ### Automatic Settlement (SDK) Integrate settlement into your agent: ```typescript theme={null} // After processing request await payments.facilitator.settlePermissions({ paymentRequired, x402AccessToken: req.headers['payment-signature'] as string, maxAmount: BigInt(5) }) ``` ## Complete Query Workflow ### End-to-End Example Complete flow from purchase to query: ```bash theme={null} #!/bin/bash # Complete agent query workflow PLAN_ID="did:nvm:abc123" AGENT_API="https://agent-api.example.com/v1/chat" # 1. Purchase plan if needed echo "Checking balance..." BALANCE=$(nevermined plans get-plan-balance $PLAN_ID --format json | jq -r '.balance') if [ "$BALANCE" -lt "10" ]; then echo "Low balance, purchasing plan..." nevermined plans order-plan $PLAN_ID fi # 2. Get X402 access token echo "Getting access token..." TOKEN=$(nevermined x402token get-x402-access-token $PLAN_ID --format json | jq -r '.token') # 3. Query the agent echo "Querying agent..." RESPONSE=$(curl -s -X POST $AGENT_API \ -H "Content-Type: application/json" \ -H "payment-signature: $TOKEN" \ -d '{ "message": "Explain quantum computing in simple terms", "temperature": 0.7 }') echo "Response:" echo $RESPONSE | jq '.' # 4. Check updated balance echo "Updated balance:" nevermined plans get-plan-balance $PLAN_ID ``` ## Advanced Usage ### Batch Queries Process multiple queries efficiently: ```bash theme={null} #!/bin/bash # Batch query script PLAN_ID="did:nvm:abc123" AGENT_API="https://agent-api.example.com/v1/chat" # Get token once TOKEN=$(nevermined x402token get-x402-access-token $PLAN_ID --format json | jq -r '.token') # Array of questions QUESTIONS=( "What is machine learning?" "Explain neural networks" "What is deep learning?" ) # Query each for QUESTION in "${QUESTIONS[@]}"; do echo "Query: $QUESTION" RESPONSE=$(curl -s -X POST $AGENT_API \ -H "Content-Type: application/json" \ -H "payment-signature: $TOKEN" \ -d "{\"message\": \"$QUESTION\"}") echo "Answer: $(echo $RESPONSE | jq -r '.answer')" echo "Credits used: $(echo $RESPONSE | jq -r '.creditsUsed')" echo "---" done # Check final balance nevermined plans get-plan-balance $PLAN_ID ``` ### Rate-Limited Queries Respect rate limits: ```bash theme={null} #!/bin/bash # Rate-limited query script PLAN_ID="did:nvm:abc123" AGENT_API="https://agent-api.example.com/v1/chat" RATE_LIMIT=10 # requests per minute DELAY=$(echo "60 / $RATE_LIMIT" | bc -l) TOKEN=$(nevermined x402token get-x402-access-token $PLAN_ID --format json | jq -r '.token') for i in {1..50}; do echo "Request $i..." curl -s -X POST $AGENT_API \ -H "Content-Type: application/json" \ -H "payment-signature: $TOKEN" \ -d "{\"message\": \"Query $i\"}" # Respect rate limit sleep $DELAY done ``` ### Error Handling Handle common errors gracefully: ```bash theme={null} #!/bin/bash # Robust query script with error handling query_agent() { local plan_id=$1 local message=$2 local max_retries=3 local retry_count=0 while [ $retry_count -lt $max_retries ]; do # Get fresh token TOKEN=$(nevermined x402token get-x402-access-token $plan_id --format json 2>&1) if [ $? -ne 0 ]; then echo "Error getting token: $TOKEN" return 1 fi TOKEN=$(echo $TOKEN | jq -r '.token') # Make request RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \ https://agent-api.example.com/v1/chat \ -H "Content-Type: application/json" \ -H "payment-signature: $TOKEN" \ -d "{\"message\": \"$message\"}") HTTP_CODE=$(echo "$RESPONSE" | tail -n1) BODY=$(echo "$RESPONSE" | head -n-1) case $HTTP_CODE in 200) echo "$BODY" return 0 ;; 402) echo "Insufficient credits. Purchasing more..." nevermined plans order-plan $plan_id ;; 429) echo "Rate limit exceeded. Waiting..." sleep 60 ;; *) echo "Error $HTTP_CODE: $BODY" ;; esac retry_count=$((retry_count + 1)) sleep 2 done echo "Max retries exceeded" return 1 } # Usage query_agent ""did:nvm:abc123"" "Hello, agent!" ``` ## Monitoring Usage ### Track Credit Consumption Monitor how credits are used per query: ```bash theme={null} #!/bin/bash # Credit usage tracking PLAN_ID="did:nvm:abc123" LOG_FILE="credit-usage.log" # Get initial balance INITIAL=$(nevermined plans get-plan-balance $PLAN_ID --format json | jq -r '.balance') # Make query TOKEN=$(nevermined x402token get-x402-access-token $PLAN_ID --format json | jq -r '.token') RESPONSE=$(curl -s -X POST https://agent-api.example.com/v1/chat \ -H "payment-signature: $TOKEN" \ -d '{"message": "test query"}') # Get new balance FINAL=$(nevermined plans get-plan-balance $PLAN_ID --format json | jq -r '.balance') # Calculate usage USED=$((INITIAL - FINAL)) # Log echo "$(date)|Query: test query|Credits used: $USED|Remaining: $FINAL" >> $LOG_FILE echo "Credits used: $USED" echo "Remaining: $FINAL" ``` ### Usage Reports Generate usage reports: ```bash theme={null} #!/bin/bash # Generate usage report from logs echo "Credit Usage Report" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" # Total credits used TOTAL_USED=$(awk -F'|' '{sum+=$3} END {print sum}' credit-usage.log | cut -d: -f2) echo "Total Credits Used: $TOTAL_USED" # Average per query NUM_QUERIES=$(wc -l < credit-usage.log) AVG=$(echo "$TOTAL_USED / $NUM_QUERIES" | bc -l | xargs printf "%.2f") echo "Average per Query: $AVG" # Queries by date echo " echo "Queries by Date:" awk -F'|' '{print substr($1, 1, 10)}' credit-usage.log | sort | uniq -c ``` ## Best Practices ### 1. Token Refresh Tokens may expire, always get fresh tokens for new sessions: ```bash theme={null} # Don't reuse old tokens TOKEN=$(nevermined x402token get-x402-access-token $PLAN_ID --format json | jq -r '.token') ``` ### 2. Credit Management Monitor balance before queries: ```bash theme={null} BALANCE=$(nevermined plans get-plan-balance $PLAN_ID --format json | jq -r '.balance') if [ "$BALANCE" -lt "10" ]; then echo "Low credits, refilling..." nevermined plans order-plan $PLAN_ID fi ``` ### 3. Error Recovery Implement retries with exponential backoff: ```bash theme={null} retry_with_backoff() { local max_attempts=5 local timeout=1 local attempt=1 while [ $attempt -le $max_attempts ]; do if "$@"; then return 0 fi echo "Attempt $attempt failed. Retrying in ${timeout}s..." sleep $timeout timeout=$((timeout * 2)) attempt=$((attempt + 1)) done return 1 } ``` ### 4. Secure Token Storage Never commit tokens to version control: ```bash theme={null} # Use environment variables export X402_TOKEN=$(nevermined x402token get-x402-access-token $PLAN_ID --format json | jq -r '.token') # Or secure file storage chmod 600 ~/.nvm-token ``` ### 5. Rate Limiting Respect API rate limits to avoid 429 errors: ```bash theme={null} # Add delays between requests sleep 0.1 # 100ms between requests ``` ## Common Issues ### "Invalid token" Token may be expired or malformed: ```bash theme={null} # Get a fresh token nevermined x402token get-x402-access-token $PLAN_ID ``` ### "Insufficient credits" Your balance is too low: ```bash theme={null} # Check balance nevermined plans get-plan-balance $PLAN_ID # Purchase more nevermined plans order-plan $PLAN_ID ``` ### "402 Payment Required" The agent requires payment but token is invalid or missing: ```bash theme={null} # Ensure payment-signature header is included curl -H "payment-signature: $TOKEN" https://agent-api.example.com ``` ## Next Steps * [Other Commands](./other-commands.md) - Additional CLI features * [Purchases](./purchases.md) - Managing your credits * [Agents](./agents.md) - Discover more agents # Create Delegation Source: https://nevermined.ai/docs/api-reference/delegation/create-delegation POST /delegation/create Creates a spending delegation for the authenticated user against a previously enrolled payment method. For fiat-backed delegations (stripe/braintree/visa) the response includes a signed JWT (`delegationToken`); for crypto (erc4337) flows the token is held client-side and omitted. Requires a Nevermined API key. # Get Delegation Source: https://nevermined.ai/docs/api-reference/delegation/get-delegation GET /delegation/{delegationId} Returns the full details of a single delegation owned by the authenticated user, including remaining budget and last-used timestamp. Requires a Nevermined API key. # List Delegation Transactions Source: https://nevermined.ai/docs/api-reference/delegation/list-delegation-transactions GET /delegation/{delegationId}/transactions Returns a paginated list of charge transactions recorded against a delegation owned by the authenticated user. Requires a Nevermined API key. # List Delegations Source: https://nevermined.ai/docs/api-reference/delegation/list-delegations GET /delegation Returns a paginated list of the authenticated user's spending delegations. Use `accessible=true` to return only delegations the requesting API key may spend against. Requires a Nevermined API key. # Revoke Delegation Source: https://nevermined.ai/docs/api-reference/delegation/revoke-delegation DELETE /delegation/{delegationId} Revokes a delegation owned by the authenticated user and cascade-revokes its linked permissions. For Visa delegations the linked VGS intent is cancelled best-effort. Requires a Nevermined API key. # Add an organization member to a group Source: https://nevermined.ai/docs/api-reference/groups/add-an-organization-member-to-a-group /api-reference/organizations-openapi.json post /organizations/{orgId}/groups/{groupId}/members # Create a per-currency budget for a group Source: https://nevermined.ai/docs/api-reference/groups/create-a-per-currency-budget-for-a-group /api-reference/organizations-openapi.json post /organizations/{orgId}/groups/{groupId}/budgets # Create an organization group Source: https://nevermined.ai/docs/api-reference/groups/create-an-organization-group /api-reference/organizations-openapi.json post /organizations/{orgId}/groups Creates a named group of members. Requires org admin + a Premium/Enterprise tier. # Deactivate a group (soft delete) Source: https://nevermined.ai/docs/api-reference/groups/deactivate-a-group-soft-delete /api-reference/organizations-openapi.json delete /organizations/{orgId}/groups/{groupId} # Get a group and its members Source: https://nevermined.ai/docs/api-reference/groups/get-a-group-and-its-members /api-reference/organizations-openapi.json get /organizations/{orgId}/groups/{groupId} # List a group's budgets (one per currency) Source: https://nevermined.ai/docs/api-reference/groups/list-a-groups-budgets-one-per-currency /api-reference/organizations-openapi.json get /organizations/{orgId}/groups/{groupId}/budgets # List a group's shared payment methods Source: https://nevermined.ai/docs/api-reference/groups/list-a-groups-shared-payment-methods /api-reference/organizations-openapi.json get /organizations/{orgId}/groups/{groupId}/payment-methods # List the organization's groups Source: https://nevermined.ai/docs/api-reference/groups/list-the-organizations-groups /api-reference/organizations-openapi.json get /organizations/{orgId}/groups # Read a budget's usage for the current period Source: https://nevermined.ai/docs/api-reference/groups/read-a-budgets-usage-for-the-current-period /api-reference/organizations-openapi.json get /organizations/{orgId}/groups/{groupId}/budgets/{budgetId}/usage # Read one budget by id Source: https://nevermined.ai/docs/api-reference/groups/read-one-budget-by-id /api-reference/organizations-openapi.json get /organizations/{orgId}/groups/{groupId}/budgets/{budgetId} # Remove a member from a group Source: https://nevermined.ai/docs/api-reference/groups/remove-a-member-from-a-group /api-reference/organizations-openapi.json delete /organizations/{orgId}/groups/{groupId}/members/{memberId} # Remove a payment method from a group (reverts it to personal) Source: https://nevermined.ai/docs/api-reference/groups/remove-a-payment-method-from-a-group-reverts-it-to-personal /api-reference/organizations-openapi.json delete /organizations/{orgId}/groups/{groupId}/payment-methods/{id} # Remove one budget by id Source: https://nevermined.ai/docs/api-reference/groups/remove-one-budget-by-id /api-reference/organizations-openapi.json delete /organizations/{orgId}/groups/{groupId}/budgets/{budgetId} # Rename or re-describe a group Source: https://nevermined.ai/docs/api-reference/groups/rename-or-re-describe-a-group /api-reference/organizations-openapi.json patch /organizations/{orgId}/groups/{groupId} # Share an enrolled card with a group as a payment method Source: https://nevermined.ai/docs/api-reference/groups/share-an-enrolled-card-with-a-group-as-a-payment-method /api-reference/organizations-openapi.json post /organizations/{orgId}/groups/{groupId}/payment-methods # Update a budget's limit / interval / alert threshold Source: https://nevermined.ai/docs/api-reference/groups/update-a-budgets-limit-interval-alert-threshold /api-reference/organizations-openapi.json patch /organizations/{orgId}/groups/{groupId}/budgets/{budgetId} # Pre-requisites Source: https://nevermined.ai/docs/api-reference/introduction Get your Nevermined API Key to use the Payment libraries and REST API To interact with Nevermined programmatically, you need a **Nevermined API Key**. This key is required for both: * **Payment Libraries** (TypeScript SDK and Python SDK) * **REST API** (direct HTTP calls) ## Get Your API Key Open [nevermined.app](https://nevermined.app), sign in, then go to **Settings > Global NVM API Keys** and click **+ New API Key**. Copy the key and set it as an environment variable: ```bash theme={null} export NVM_API_KEY="sandbox:your-api-key-here" ``` > [!WARNING] > > Keep your API key secure. Do not commit it to version control or share it > publicly. ## Choose Your Environment Nevermined offers two environments: | Environment | Purpose | Network | | - | - | - | | **Sandbox** | Testing and development | Base Sepolia | | **Live** | Production | Base Mainnet | > [tab] TypeScript SDK > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY, > environment: 'sandbox' // or 'live' > }) > ``` > [tab] Python SDK > > ```python theme={null} > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ['NVM_API_KEY'], > environment='sandbox' # or 'live' > ) > ) > ``` > [tab] REST API > > | Environment | Base URL | > | - | - | > | **Sandbox** | `https://api.sandbox.nevermined.app/api/v1` | > | **Live** | `https://api.live.nevermined.app/api/v1` | > > ```bash theme={null} > curl -X GET "https://api.sandbox.nevermined.app/api/v1/protocol/agents" \ > -H "Authorization: Bearer $NVM_API_KEY" > ``` ## API Versioning Every request resolves to a pinned API version (the platform release `MAJOR.MINOR`), so your integration keeps working across releases. The pin comes from your API key (editable in the dashboard) or, per request, from the optional `Nevermined-Version` header: ```bash theme={null} curl -X GET "https://api.sandbox.nevermined.app/api/v1/protocol/agents" \ -H "Authorization: Bearer $NVM_API_KEY" \ -H "Nevermined-Version: 1.0" ``` See [API Versioning](/docs/development-guide/api-versioning) for the resolution rules and compatibility guarantees. ## Authentication Every request is authenticated with a single bearer header — `Authorization: Bearer `. The key above is all most integrations need. For the full picture — the on-chain identity model, obtaining a key **with or without a browser** (the OAuth 2.1 Authorization Code and RFC 8628 device flows), standards-based discovery, and how to read a `401` — see the [**Authentication & Identity** guide](/docs/integrate/authentication/overview). ## Error model Errors return a typed envelope — a `BCK..` code, a `message`, often a `hint`, a `category`, and an `x-correlation-id` header. Branch on the `code`/`category`, not the prose. See the [API error model](/docs/development-guide/api-errors/overview) for the shape and the [API error codes](/docs/development-guide/api-errors/codes) for the full catalog. ## Next Steps > [card] [Authentication & Identity](/docs/integrate/authentication/overview) > > The bearer-token contract, the device flow, OAuth 2.1, and discovery. > [card] [API error codes](/docs/development-guide/api-errors/codes) > > The full catalog of `BCK.*` codes and what they mean. > [card] [TypeScript SDK](/docs/api-reference/typescript/installation) > > Install and use the TypeScript Payments library. > [card] [Python SDK](/docs/api-reference/python/installation) > > Install and use the Python Payments library. # Accept an organization invitation Source: https://nevermined.ai/docs/api-reference/invitations/accept-an-organization-invitation /api-reference/organizations-openapi.json post /organizations/invitations/{token}/accept Accepts a pending invitation identified by its magic-link token. The organization is resolved from the token, not the URL. The authenticated user must have the same email as the invitation target (verified server-side from the user profile). On success the user becomes an active member of the organization and the response is `{ success, orgId, membershipId, role }`. Requires a Nevermined API key or a Privy identity token. # Get public info for a pending invitation by token Source: https://nevermined.ai/docs/api-reference/invitations/get-public-info-for-a-pending-invitation-by-token /api-reference/organizations-openapi.json get /organizations/invitations/{token} Used by the webapp to pre-fill the sign-in form when arriving via a magic link, before the user authenticates. The raw token itself authorises this read-only lookup; the accept mutation still requires authentication. Returns 404 for tokens that are unknown, already used, or expired. Public endpoint — no authentication required. # Invite a teammate by email Source: https://nevermined.ai/docs/api-reference/invitations/invite-a-teammate-by-email /api-reference/organizations-openapi.json post /organizations/{orgId}/invitations Creates a pending invitation for the given email and sends a magic-link email so the invitee can join the organization. The response is `{ success, invitation }`; outside production it also includes `magicLinkUrl` for testing (it is omitted in production, where the link is delivered by email only). Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # List organization invitations Source: https://nevermined.ai/docs/api-reference/invitations/list-organization-invitations /api-reference/organizations-openapi.json get /organizations/{orgId}/invitations Returns a paginated list of the organization’s invitations, optionally filtered by status. The response is `{ success, items, total, page, limit }`. Requires a Nevermined API key. Requires organization admin privileges. # Revoke an invitation Source: https://nevermined.ai/docs/api-reference/invitations/revoke-an-invitation /api-reference/organizations-openapi.json post /organizations/{orgId}/invitations/{id}/revoke Revokes a pending invitation so its magic link can no longer be used. The operation is idempotent — revoking an invitation that is already non-pending still returns success. Requires a Nevermined API key. Requires organization admin privileges. # API Reference Source: https://nevermined.ai/docs/api-reference/openclaw-plugin/commands All available tools and slash commands in the Nevermined OpenClaw plugin # API Reference The plugin provides slash commands for chat channels and tools that agents can invoke on behalf of users. Slash commands are triggered directly by users with the `/` prefix, while tools are called by the AI agent in response to natural language requests. ## Authentication Commands ### Log In — `/nvm_login` Authenticate with the Nevermined platform to enable all payment tools. The plugin supports three authentication flows: automatic browser login, environment selection, and direct API key input. When using browser login, the plugin starts a temporary local server, opens your default browser to the Nevermined login page, and captures the API key automatically after you sign in. On headless servers where no browser is available, paste your API key directly. | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `environment` | string | No | `sandbox` | `sandbox` or `live` | > **Example prompt:** "Log me in to Nevermined" ``` /nvm_login /nvm_login live /nvm_login sandbox:eyJhbG... ``` *** ### Log Out — `/nvm_logout` End your Nevermined session and remove the stored API key from memory. After logging out, all payment tools will be unavailable until you authenticate again. Use this when switching accounts or when you want to revoke the current session for security. *** ## Subscriber Tools These tools are designed for users who consume paid AI agent services. They handle the full lifecycle of subscribing to a plan, paying for access, and querying agents. ### Check Credit Balance — `nevermined_checkBalance` Retrieve the current credit balance for a payment plan. This is useful to verify how many credits remain before making requests, or to confirm that a recent purchase was credited to your account. The response includes the plan name, remaining balance, and whether you are an active subscriber. If a `planId` is configured in the plugin settings, it is used by default. You can override it per call. | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `planId` | string | No | Config `planId` | The payment plan ID to check | **Example prompt:** > How many credits do I have left on my Weather Forecast plan? **Returns:** ```json theme={null} { "planId": "did:nv:abc123...", "planName": "Basic Plan", "balance": "95", "isSubscriber": true } ``` *** ### Get Access Token — `nevermined_getAccessToken` Generate an x402 access token that authorizes requests to a paid Nevermined agent. The token is cryptographically signed and contains delegated permissions (order, burn) that allow the agent to verify and settle payments on your behalf. This tool supports two payment schemes. **Crypto** (the default) uses the `nvm:erc4337` on-chain scheme with session keys and smart accounts. **Fiat** uses the `nvm:card-delegation` scheme, which charges a previously enrolled credit card via Stripe delegation. When using fiat, the plugin automatically looks up your enrolled payment methods and selects the first one unless you specify a `paymentMethodId`. Most users will not need to call this tool directly — `nevermined_queryAgent` handles token acquisition automatically. Use this tool when you need the raw token for custom integrations or debugging. | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `planId` | string | No | Config `planId` | The payment plan ID | | `agentId` | string | No | Config `agentId` | The agent ID | | `paymentType` | string | No | Config `paymentType` or `"crypto"` | `"crypto"` (nvm:erc4337 scheme) or `"fiat"` (nvm:card-delegation scheme) | | `paymentMethodId` | string | No | Auto-selects first enrolled card | Stripe payment method ID (`pm_...`). Only used for fiat. | | `spendingLimitCents` | number | No | Config `defaultSpendingLimitCents` or `1000` | Max spend in cents. Only used for fiat. | | `delegationDurationSecs` | number | No | Config `defaultDelegationDurationSecs` or `3600` | Delegation duration in seconds. Only used for fiat. | **Example prompt:** > Get me an access token for the Weather Oracle agent so I can call it from my script. > **Example prompt:** "Get me an access token for the translation agent" **Returns:** ```json theme={null} { "accessToken": "eyJhbG..." } ``` *** ### Purchase a Crypto Plan — `nevermined_orderPlan` Purchase a payment plan using cryptocurrency. This initiates an on-chain transaction that transfers the plan's price to the builder's wallet and credits your account with the plan's allotted credits. The transaction is processed through the Nevermined Protocol smart contracts. Use this for plans priced in native tokens (ETH, MATIC) or ERC-20 tokens (USDC). For plans priced in fiat currency, use `nevermined_orderFiatPlan` instead. > ⚠️ **Two-step confirmation flow.** This tool spends real money. The first call returns a *quote* — `planId`, `name`, `price`, `credits`, `paymentType`, `environment`, plus the literal `"Re-call with confirm: true to proceed."`. The agent must show that quote to the user and only call again with `confirm: true` once the user has explicitly approved. | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `planId` | string | No | Config `planId` | The plan ID to purchase | | `confirm` | boolean | No | `false` | Set to `true` only after the user has approved the quote returned by the first call. | **Example prompt:** > Buy the Weather Forecast plan so I can start querying the agent. **Returns:** * Without `confirm: true`: `{ planId, name, price, credits, paymentType, environment, requiresConfirmation: true, message: "Re-call with confirm: true to proceed." }` * With `confirm: true`: order confirmation with transaction hash. *** ### Purchase a Fiat Plan — `nevermined_orderFiatPlan` Purchase a payment plan using fiat currency (USD). Instead of executing an on-chain transaction, this tool returns a Stripe checkout URL where you complete the payment in a browser. Once the payment is confirmed, credits are added to your account. Use this for plans that have been created with `pricingType: fiat`. For crypto-priced plans, use `nevermined_orderPlan` instead. > ⚠️ **Two-step confirmation flow.** Same as `nevermined_orderPlan`: the first call returns a quote, the second call (with `confirm: true`) issues the Stripe checkout URL. | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `planId` | string | No | Config `planId` | The plan ID to purchase | | `confirm` | boolean | No | `false` | Set to `true` only after the user has approved the quote returned by the first call. | **Example prompt:** > I want to subscribe to the Premium Agent plan using my credit card. **Returns:** * Without `confirm: true`: `{ planId, name, price, credits, paymentType: "fiat", environment, requiresConfirmation: true, message: "Re-call with confirm: true to proceed." }` * With `confirm: true`: ```json theme={null} { "result": { "checkoutUrl": "https://checkout.stripe.com/..." } } ``` *** ### List Payment Methods — `nevermined_listPaymentMethods` Retrieve the list of credit cards you have enrolled for fiat payments. Cards are enrolled through the [Nevermined App](https://nevermined.app) under Settings > Payment Methods. Each entry includes the card brand, last four digits, and expiration date. This is useful to verify which cards are available before making a fiat payment, or to find the `paymentMethodId` for a specific card when you have multiple cards enrolled. No parameters required. **Example prompt:** > Which credit cards do I have on file for Nevermined payments? **Returns:** ```json theme={null} [ { "id": "pm_...", "brand": "visa", "last4": "4242", "expMonth": 12, "expYear": 2027 } ] ``` *** ### Query a Paid Agent — `nevermined_queryAgent` Send a prompt to a paid Nevermined AI agent and get the response. This is the main tool for interacting with agents — it handles the full payment lifecycle in a single call: 1. Acquires an x402 access token (crypto or fiat, depending on `paymentType`) 2. Sends the prompt to the agent's URL with the `payment-signature` header 3. Returns the agent's response If the agent returns a 402 (Payment Required) response, the tool returns an error suggesting you purchase credits first. This typically means your plan has run out of credits or you haven't subscribed yet. Like `nevermined_getAccessToken`, this tool supports both crypto and fiat payment types. When using fiat, it automatically resolves your enrolled card and builds the delegation config. | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `agentUrl` | string | **Yes** | — | The URL of the agent to query | | `prompt` | string | **Yes** | — | The prompt to send to the agent | | `planId` | string | No | Config `planId` | The payment plan ID | | `agentId` | string | No | Config `agentId` | The agent ID | | `method` | string | No | `POST` | HTTP method | | `paymentType` | string | No | Config `paymentType` or `"crypto"` | `"crypto"` (nvm:erc4337 scheme) or `"fiat"` (nvm:card-delegation scheme) | | `paymentMethodId` | string | No | Auto-selects first enrolled card | Stripe payment method ID (`pm_...`). Only used for fiat. | | `spendingLimitCents` | number | No | Config `defaultSpendingLimitCents` or `1000` | Max spend in cents. Only used for fiat. | | `delegationDurationSecs` | number | No | Config `defaultDelegationDurationSecs` or `3600` | Delegation duration in seconds. Only used for fiat. | **Example prompts:** > Ask the Weather Oracle at [https://weather.example.com/agent](https://weather.example.com/agent) what the forecast is for Barcelona. > Query the translation agent at [https://translate.example.com/tasks](https://translate.example.com/tasks) to translate "hello world" into French, and pay with my credit card. *** ## Builder Tools These tools are designed for agent builders who want to register their AI agents on the Nevermined marketplace and create payment plans that subscribers can purchase. ### Register an Agent — `nevermined_registerAgent` Register a new AI agent on Nevermined and create an associated payment plan in a single operation. This publishes your agent to the Nevermined marketplace, making it discoverable and purchasable by subscribers. The tool creates both the agent record (with its endpoint URL) and a payment plan (with pricing and credit allocation). The `pricingType` parameter controls how the plan is priced: `"crypto"` for native blockchain tokens, `"erc20"` for stablecoins like USDC, or `"fiat"` for USD pricing via Stripe. After registration, the returned `agentId` and `planId` should be saved in your plugin config for the paid endpoint to work. | Parameter | Type | Required | Description | | - | - | - | - | | `name` | string | **Yes** | Agent name | | `description` | string | No | Agent description | | `agentUrl` | string | **Yes** | The endpoint URL for the agent | | `planName` | string | **Yes** | Name for the payment plan | | `priceAmounts` | string | **Yes** | Comma-separated price amounts in wei (crypto) or cents (fiat) | | `priceReceivers` | string | **Yes** | Comma-separated receiver addresses | | `creditsAmount` | number | **Yes** | Number of credits in the plan | | `tokenAddress` | string | No | ERC20 token address (e.g. USDC). Omit for native token. | | `pricingType` | string | No | `"crypto"` (default), `"erc20"`, or `"fiat"` | **Example prompt:** > Register a new agent called "Code Review Bot" at [https://my-server.com/nevermined/agent](https://my-server.com/nevermined/agent) with a plan named "Code Review" priced at 1000000 (1 USDC) to address 0xABC... with token 0x036CbD... granting 10 credits. > **Example prompt:** "Register my translation agent hosted at [https://agent.example.com](https://agent.example.com) with a plan named 'Translation Plan' that costs 1000000 wei (1 USDC) sent to address 0x123... for 100 credits" **Returns:** ```json theme={null} { "agentId": "did:nv:...", "planId": "did:nv:...", "txHash": "0x..." } ``` *** ### Create a Payment Plan — `nevermined_createPlan` Create a standalone payment plan without associating it with an agent. This is useful when you want to manage plans separately from agents, or when a single plan should grant access to multiple agents. The plan can be priced in three ways: `"fiat"` sets the price in USD cents (e.g. `"100"` = \$1.00) and subscribers pay via Stripe, `"erc20"` sets the price in an ERC-20 token's smallest unit (e.g. `"1000000"` = 1 USDC) and requires a `tokenAddress`, and `"crypto"` (the default) sets the price in the blockchain's native token. | Parameter | Type | Required | Description | | - | - | - | - | | `name` | string | **Yes** | Plan name | | `description` | string | No | Plan description | | `priceAmount` | string | **Yes** | Price in cents for fiat (e.g. "100" = \$1.00), in token smallest unit for crypto | | `receiver` | string | **Yes** | Receiver wallet address (0x...) | | `creditsAmount` | number | **Yes** | Number of credits in the plan | | `pricingType` | string | No | `"fiat"` for Stripe/USD, `"erc20"` for ERC20 tokens, `"crypto"` for native token (default) | | `accessLimit` | string | No | `"credits"` (default) or `"time"` | | `tokenAddress` | string | No | ERC20 token contract address. Required when pricingType is "erc20". | **Example prompt:** > Create a fiat payment plan called "Pro Tier" at \$5.00 (500 cents) to wallet 0xABC... with 50 credits. **Returns:** ```json theme={null} { "planId": "did:nv:..." } ``` *** ### List My Plans — `nevermined_listPlans` Retrieve all payment plans owned by the authenticated builder. This returns the full list of plans you have created, including their IDs, names, and configuration. Useful for finding a `planId` to use with other tools or to review your current offerings. No parameters required. **Example prompt:** > Show me all the payment plans I've created on Nevermined. **Returns:** Array of plan objects. # Getting Started Source: https://nevermined.ai/docs/api-reference/openclaw-plugin/getting-started Install and configure the Nevermined OpenClaw plugin in minutes # Getting Started The Nevermined OpenClaw plugin exposes AI agent payment operations as gateway tools callable from any OpenClaw channel — Telegram, Discord, WhatsApp, and more. ## Prerequisites * An [OpenClaw](https://openclaw.ai) gateway instance * Node.js >= 18.0.0 * A [Nevermined account](https://nevermined.app) (free to create) ## Installation Install the plugin from your OpenClaw gateway: ```bash theme={null} openclaw plugin install @nevermined-io/openclaw-plugin@^1.1 ``` The plugin requires `@nevermined-io/payments@^1.1` as a peer dependency. Pin both packages and commit your lockfile so SDK upgrades are explicit. ## Authentication > [!NOTE] > > To interact with the Nevermined API, you need an API key. Follow the [Get Your API Key](/docs/getting-started/get-your-api-key) guide to create one. ### Option A: Browser login (recommended) Use the `/nvm_login` command from any connected chat channel: ``` /nvm_login ``` This opens a browser window where you authenticate with Nevermined. The API key is captured automatically and stored in your gateway config. To target the live environment: ``` /nvm_login live ``` To use a specific API key: ``` /nvm_login sandbox:eyJhbG... ``` ### Option B: Manual configuration Add your API key directly to `openclaw.json`: ```json theme={null} { "plugins": { "entries": { "openclaw-plugin": { "enabled": true, "config": { "nvmApiKey": "sandbox:eyJhbG...", "environment": "sandbox" } } } } } ``` ## Quick Test After authenticating, verify the plugin is working: 1. **Check your balance** — from any chat channel, the agent can ask `Example prompt: “How many credits do I have left on my plan?”` to verify connectivity. 2. **List plans** — you can ask `Example prompt: Show me all my payment plans”` to see available payment plans. ## Fiat Payments The plugin also supports fiat payments via credit card delegation. Enroll a card at [nevermined.app](https://nevermined.app), then use `paymentType: fiat` with any token or query tool. See the [guide](./guide.md#fiat-payments-credit-card) for details. ## Next Steps * [Setup](/docs/api-reference/openclaw-plugin/setup) — full configuration reference * [Commands](/docs/api-reference/openclaw-plugin/commands) — all available tools and slash commands # Building a Paid AI Agent with OpenClaw and Nevermined Source: https://nevermined.ai/docs/api-reference/openclaw-plugin/guide Step-by-step guide to building, monetizing, and querying a paid AI agent using the Nevermined OpenClaw plugin # Building a Paid AI Agent with OpenClaw and Nevermined The Nevermined OpenClaw plugin lets you monetize AI agents directly from chat channels. Subscribers pay per-request using the [x402 payment protocol](https://nevermined.ai/docs/api-reference/typescript/x402-protocol), and builders collect revenue automatically through on-chain payment plans. This guide walks through building a **Weather Oracle** — a paid agent that serves weather forecasts and charges 1 credit per request. ## What You Get The plugin adds 9 payment tools and 2 slash commands to your OpenClaw gateway: **Subscriber tools** — for users who consume paid services: | Tool | Purpose | | - | - | | `nevermined_checkBalance` | Check remaining credits on a plan | | `nevermined_getAccessToken` | Get an x402 token for authenticating requests (crypto or fiat) | | `nevermined_orderPlan` | Purchase a crypto payment plan | | `nevermined_orderFiatPlan` | Purchase a fiat payment plan (returns Stripe checkout URL) | | `nevermined_listPaymentMethods` | List enrolled credit cards for fiat payments | | `nevermined_queryAgent` | Send a paid query to an agent (crypto or fiat) | **Builder tools** — for developers who create paid services: | Tool | Purpose | | - | - | | `nevermined_registerAgent` | Register an agent with a payment plan (crypto or fiat) | | `nevermined_createPlan` | Create a standalone payment plan | | `nevermined_listPlans` | List your payment plans | **Slash commands**: `/nvm_login` and `/nvm_logout` for authentication. **Paid HTTP endpoint**: An x402-compatible endpoint on the gateway that handles payment verification, request processing, and credit settlement automatically. ## Prerequisites * An [OpenClaw](https://openclaw.ai) gateway instance (v2026.2+) * Node.js >= 18 * A [Nevermined account](https://nevermined.app) with an API key > 🔐 **Security expectations.** This plugin issues `payment-signature` bearer tokens that authorise spending against your plan. In production: > > * **Use HTTPS for every `agentUrl`** passed to `nevermined_queryAgent`. The tool warns when the URL is not `https://` (loopback hosts excepted for local dev). > * **Validate agent cards** at `/.well-known/agent.json` before issuing a paid request — confirm `agentId` and supported X402 schemes match what you expect. > * **Never log payment tokens** — redact the `payment-signature` header in pino, winston, OpenTelemetry, and any sentry/datadog/log-shipping layer. > * **Confirm before ordering** — `nevermined_orderPlan` and `nevermined_orderFiatPlan` are gated by a `confirm: true` parameter so the agent must show the user the price/credits/environment first. ## Step 1: Install the Plugin From your OpenClaw gateway server: ```bash theme={null} openclaw plugin install @nevermined-io/openclaw-plugin@^1.1 ``` Or install manually by placing the package in `~/.openclaw/extensions/nevermined/`. Pin the major version and commit your lockfile so SDK upgrades are explicit. After installation, restart the gateway: ```bash theme={null} openclaw gateway restart ``` You should see in the logs: ``` Registered 9 Nevermined payment tools ``` ## Step 2: Authenticate Send `/nvm_login` from any connected chat channel (Telegram, Discord, etc.). The plugin supports two flows: **Browser login** (if your server has a display): ``` /nvm_login ``` A browser window opens for Nevermined authentication. The API key is captured automatically. **Manual login** (headless servers): ``` /nvm_login sandbox:eyJhbGciOiJFUzI1NksifQ... ``` Paste your API key directly. Get one from [Nevermined App](https://nevermined.app) under Settings > API Keys. Use `sandbox` for testing, `live` for production. ## Step 3: Register Your Agent and Payment Plan Ask your Claw to register an agent. In any chat channel, send a message like: > Register a Nevermined agent called "Weather Oracle" at URL `https://my-gateway.example.com/nevermined/agent` with a plan named "Weather Forecast" priced at 1000000 (1 USDC) to address `0xYourWalletAddress` with token `0x036CbD53842c5426634e7929541eC2318f3dCF7e` granting 5 credits. The agent will call `nevermined_registerAgent` with these parameters: | Parameter | Value | Description | | - | - | - | | `name` | Weather Oracle | Display name on Nevermined | | `agentUrl` | `https://my-gateway.example.com/nevermined/agent` | Public URL of your paid endpoint | | `planName` | Weather Forecast | Name for the payment plan | | `priceAmounts` | `1000000` | Price in token units (1 USDC = 1,000,000 wei) | | `priceReceivers` | `0xYourWalletAddress` | Your wallet that receives payments | | `creditsAmount` | `5` | Credits granted per purchase | | `tokenAddress` | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | USDC on Base Sepolia. Omit for native token. | The tool returns the `agentId` and `planId` — save these for the next step. ## Step 4: Enable the Paid Endpoint Add the returned IDs and enable the paid endpoint in your gateway config (`~/.openclaw/openclaw.json`): ```json theme={null} { "plugins": { "entries": { "openclaw-plugin": { "enabled": true, "config": { "nvmApiKey": "sandbox:eyJhbG...", "environment": "sandbox", "planId": "", "agentId": "", "enablePaidEndpoint": true, "agentEndpointPath": "/nevermined/agent", "creditsPerRequest": 1 } } } } } ``` Restart the gateway. You should see: ``` Registered 9 Nevermined payment tools Registered paid endpoint at /nevermined/agent ``` The paid endpoint handles the full x402 lifecycle: 1. Extracts the `payment-signature` header from incoming requests 2. Calls `verifyPermissions` to check the subscriber has credits 3. Processes the request (runs your agent handler) 4. Calls `settlePermissions` to burn credits 5. Returns the response with a `payment-response` header ### Configuration Reference | Field | Required | Default | Description | | - | - | - | - | | `nvmApiKey` | No | — | API key (set via `/nvm_login` or config) | | `environment` | No | `sandbox` | `sandbox` for testing, `live` for production | | `planId` | No | — | Default plan ID for tools and the paid endpoint | | `agentId` | No | — | Default agent ID | | `creditsPerRequest` | No | `1` | Credits burned per request | | `enablePaidEndpoint` | No | `false` | Enable the x402 paid HTTP endpoint | | `agentEndpointPath` | No | `/nevermined/agent` | Path for the paid endpoint | ## Step 5: Test as a Subscriber From the same gateway (or a different one with a subscriber API key), test the full flow: ### Order the plan > Order the Weather Oracle plan `` The Claw calls `nevermined_orderPlan`. You receive 5 credits. ### Check your balance > Check my Nevermined balance for plan `` Should show 5 credits. ### Query the agent > Ask the Weather Oracle at `http://localhost:18789/nevermined/agent` about the weather in Barcelona The Claw calls `nevermined_queryAgent`, which: 1. Acquires an x402 access token 2. Sends the prompt with a `payment-signature` header 3. The paid endpoint verifies, processes, and settles 4. Returns the weather forecast ### Verify credit burn > Check my balance again Should show 4 credits — one was consumed. ## Fiat Payments (Credit Card) The plugin supports fiat payments via credit card delegation, allowing users who have enrolled a card through the [Nevermined App](https://nevermined.app) to pay for agent queries without cryptocurrency. ### 1. Enroll a card Users enroll a credit card via the Nevermined App under Settings > Payment Methods. ### 2. List enrolled cards > List my payment methods The Claw calls `nevermined_listPaymentMethods` and returns the enrolled cards with brand, last 4 digits, and expiration. ### 3. Order a fiat plan > Order the fiat plan `` The Claw calls `nevermined_orderFiatPlan`, which returns a Stripe checkout URL. The user completes payment in a browser. ### 4. Query an agent with fiat > Ask the Weather Oracle at `http://localhost:18789/nevermined/agent` about the weather in Paris, pay with my credit card The Claw calls `nevermined_queryAgent` with `paymentType: fiat`. The plugin: 1. Looks up enrolled payment methods (or uses the specified `paymentMethodId`) 2. Gets an x402 access token using the `nvm:card-delegation` scheme 3. Sends the request with the `payment-signature` header 4. The agent verifies and settles as usual You can also set `paymentType: fiat` in the plugin config to make fiat the default for all calls. ## Custom Agent Handlers The plugin includes a mock weather handler for demonstration. To use your own logic, pass a custom `agentHandler` when registering the plugin: ```typescript theme={null} import neverminedPlugin from '@nevermined-io/openclaw-plugin' neverminedPlugin.register(api, { agentHandler: async (body) => { const response = await myAIModel.generate(body.prompt) return { result: response } }, }) ``` The handler receives `{ prompt: string }` and returns any JSON-serializable object. ## Credit Balance Awareness When the plugin is authenticated and a `planId` is configured, it automatically injects the current credit balance into the agent's context before each prompt. This means your Claw can proactively warn users when credits are running low: > "You have 2 credits remaining on the Weather Forecast plan. Consider ordering more credits." The balance is cached for 60 seconds to avoid excessive API calls. ## How It Works The plugin implements the [x402 payment protocol](https://nevermined.ai/docs/api-reference/typescript/x402-protocol) for agent-to-agent payments. It supports two payment schemes: * **Crypto** (`nvm:erc4337`) — on-chain payments using session keys and smart accounts * **Fiat** (`nvm:card-delegation`) — credit card payments via Stripe delegation Both schemes follow the same token flow: ``` Subscriber Claw Builder Claw (Gateway) │ │ │ 1. getX402AccessToken(planId, │ │ tokenOptions) │ │─────────────────────────────────────>│ Nevermined API │<─────────────────────────────────────│ returns token │ │ │ 2. POST /nevermined/agent │ │ Header: payment-signature: token │ │ Body: { prompt: "..." } │ │─────────────────────────────────────>│ │ │ 3. verifyPermissions() │ │ 4. Process request │ │ 5. settlePermissions() │ 6. Response + payment-response hdr │ │<─────────────────────────────────────│ ``` For crypto, credits are managed on-chain through the Nevermined Protocol. For fiat, credits are charged against the delegated card via Stripe. In both cases, `verifyPermissions` checks the subscriber's balance without consuming credits, and `settlePermissions` consumes them only after successful processing. ## Next Steps * [Commands Reference](./commands.md) — full parameter documentation for all tools * [Setup Reference](./setup.md) — detailed configuration options * [Nevermined Docs](https://nevermined.ai/docs) — platform documentation * [x402 Protocol](https://nevermined.ai/docs/api-reference/typescript/x402-protocol) — payment protocol specification * [OpenClaw Plugin Development](https://docs.openclaw.ai/tools/plugin) — building OpenClaw plugins # Setup Source: https://nevermined.ai/docs/api-reference/openclaw-plugin/setup Full configuration reference for the Nevermined OpenClaw plugin # Setup ## Configuration The plugin reads its configuration from the `plugins.openclaw-plugin` section of your `openclaw.json`: ```json theme={null} { "plugins": { "entries": { "openclaw-plugin": { "enabled": true, "config": { "nvmApiKey": "sandbox:eyJhbG...", "environment": "sandbox", "planId": "did:nv:abc123...", "agentId": "did:nv:def456...", "creditsPerRequest": 1, "enablePaidEndpoint": false, "agentEndpointPath": "/nevermined/agent", "paymentType": "crypto", "defaultSpendingLimitCents": 1000, "defaultDelegationDurationSecs": 3600 } } } } } ``` ### Configuration Fields | Field | Required | Default | Description | | - | - | - | - | | `nvmApiKey` | No | — | Your Nevermined API key. Can be set via `/nvm_login` instead. | | `environment` | No | `sandbox` | Target environment: `sandbox` for testing, `live` for production. | | `planId` | No | — | Default payment plan ID. When set, subscriber tools use this plan automatically. | | `agentId` | No | — | Default agent ID. Required for plans with multiple agents. | | `creditsPerRequest` | No | `1` | Number of credits consumed per request. | | `enablePaidEndpoint` | No | `false` | Enable the x402 paid HTTP endpoint on the gateway. | | `agentEndpointPath` | No | `/nevermined/agent` | HTTP path for the paid agent endpoint. | | `paymentType` | No | `crypto` | Default payment type: `crypto` (nvm:erc4337) or `fiat` (nvm:card-delegation). | | `defaultSpendingLimitCents` | No | `1000` | Default max spend in cents (\$10) for fiat payments. | | `defaultDelegationDurationSecs` | No | `3600` | Default delegation duration in seconds (1 hour) for fiat payments. | ### Environment Details | Environment | Description | Use Case | | - | - | - | | `sandbox` | Test environment on Base Sepolia | Development, testing, integration | | `live` | Production environment on Base Mainnet | Live deployments with real payments | ## Authentication Flow The plugin supports a browser-based login flow identical to the [Nevermined CLI](/docs/api-reference/cli/getting-started): 1. User sends `/nvm_login` in any chat channel 2. The plugin starts a local HTTP server on a random port 3. A browser window opens to the Nevermined login page 4. After authentication, Nevermined redirects back with the API key 5. The key is stored in the plugin's in-memory config for the current session The login times out after 5 minutes if no authentication is received. ### Logging Out Send `/nvm_logout` or call `nvm_logout` to remove the stored API key. All payment tools will require re-authentication after logout. ## Default Values When `planId` and `agentId` are set in the config, all subscriber tools (`checkBalance`, `getAccessToken`, `orderPlan`, `queryAgent`) use them as defaults. You can always override them per-call by passing the parameter explicitly. This is useful for gateways that serve a single plan — configure it once and all tools work without extra parameters. # List organization activity events Source: https://nevermined.ai/docs/api-reference/organizations--activity/list-organization-activity-events /api-reference/organizations-openapi.json get /organizations/{orgId}/activity Returns a paginated feed of the organization’s activity events (membership changes, resource and plan lifecycle, customer and subscription events, etc.), ordered most recent first. Filter by one or more event types, by the acting user, and by an ISO timestamp window. The response is `{ items, total }`, where `total` is the count across all pages matching the filter. Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Premium tier or higher. # Get a group's Router-rail (crypto) spend Source: https://nevermined.ai/docs/api-reference/organizations--analytics/get-a-groups-router-rail-crypto-spend /api-reference/organizations-openapi.json get /organizations/{orgId}/analytics/groups/{groupId}/router-spend Returns a group's crypto-rail spend from the router-payment ledger — the org/group counterpart to the buyer-scoped router payments list. Amounts are per-asset atomic units (token units are not additive across assets, and not comparable to the fiat/credit rails — the group budget tracks the card-rail cents cap separately). Requires a Nevermined API key, active organization membership, and the Premium tier or higher. # Get conversion funnel metrics Source: https://nevermined.ai/docs/api-reference/organizations--analytics/get-conversion-funnel-metrics /api-reference/organizations-openapi.json get /organizations/{orgId}/analytics/conversion Returns the sessions-to-purchases conversion funnel for the organization over an optional date range: the number of sessions, the number of purchases, and the conversion rate. `conversionRate` is `null` when no sessions were observed in the period (clients should render an empty state). Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Premium tier or higher. # Get monthly recurring revenue Source: https://nevermined.ai/docs/api-reference/organizations--analytics/get-monthly-recurring-revenue /api-reference/organizations-openapi.json get /organizations/{orgId}/analytics/mrr Returns the organization’s monthly recurring revenue (`mrr`, serialised as a string) and the count of active subscriptions, computed as of an optional reference date (defaults to now). Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Premium tier or higher. # Get per-member credit-burn attribution Source: https://nevermined.ai/docs/api-reference/organizations--analytics/get-per-member-credit-burn-attribution /api-reference/organizations-openapi.json get /organizations/{orgId}/analytics/credits-by-member Returns credit-burn totals attributed to each organization member across the org’s tier plans, with each member’s burn count and the timestamp of their most recent burn (`lastBurnAt`, nullable). Pass `planId` to narrow the report to a single tier plan; otherwise every tier-plan burn is rolled up to one total per member. Credit amounts are serialised as strings (bigint). Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Premium tier or higher. # Get plan consumption Source: https://nevermined.ai/docs/api-reference/organizations--analytics/get-plan-consumption /api-reference/organizations-openapi.json get /organizations/{orgId}/analytics/usage Returns credits burned per plan for the organization over an optional date range, with the number of unique users per plan. Credit amounts are serialised as strings (bigint). Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Premium tier or higher. # Get revenue breakdown by agent Source: https://nevermined.ai/docs/api-reference/organizations--analytics/get-revenue-breakdown-by-agent /api-reference/organizations-openapi.json get /organizations/{orgId}/analytics/revenue Returns total revenue per agent for the organization over an optional date range, plus an aggregate `totalRevenue`. Monetary amounts are serialised as strings (bigint). Omit the date range to cover all time. Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Premium tier or higher. # Get top customers by spend Source: https://nevermined.ai/docs/api-reference/organizations--analytics/get-top-customers-by-spend /api-reference/organizations-openapi.json get /organizations/{orgId}/analytics/customers Returns the organization’s highest-spending customers (descending by total spent) along with the total customer count. Spend amounts are serialised as strings (bigint). Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Premium tier or higher. # Cancel the org tier subscription at period end Source: https://nevermined.ai/docs/api-reference/organizations--billing/cancel-the-org-tier-subscription-at-period-end /api-reference/organizations-openapi.json post /organizations/{orgId}/billing/cancel Schedules the Stripe subscription to cancel at the end of the current billing period — the org keeps access until `currentPeriodEnd`. Marks the row as canceled locally and pre-shrinks published agents/plans to the post-cancel (Lapsed) caps. Requires a Nevermined API key. Requires organization admin privileges. # Create a tier-plan Stripe checkout Source: https://nevermined.ai/docs/api-reference/organizations--billing/create-a-tier-plan-stripe-checkout /api-reference/organizations-openapi.json post /organizations/{orgId}/billing/checkout **Deprecated:** organization tiers are bought in the Nevermined app with an enrolled card; no API route replaces this one, and it will be removed in the next major API version. Resolves the catalog row by (tier, currency, interval) and returns a hosted Stripe Checkout URL (fiat subscription). The org id is taken from the verified session and must match the path `:orgId` (mismatch is rejected). Tier changes on a live subscription must go through /upgrade or /downgrade, not a second checkout. Requires a Nevermined API key. Requires organization admin privileges. # Current tier subscription for this org (or null) Source: https://nevermined.ai/docs/api-reference/organizations--billing/current-tier-subscription-for-this-org-or-null /api-reference/organizations-openapi.json get /organizations/{orgId}/billing/subscription Returns the most-recent tier subscription row for the org as `{ subscription: { id, tier, status, source, currentPeriodStart, currentPeriodEnd, canceledAt, hasStripeSubscription } }`, or `{ subscription: null }` when none exists. The raw Stripe subscription id is never exposed — `hasStripeSubscription` is a server-derived boolean. Requires a Nevermined API key. Requires organization admin privileges. # Downgrade an Enterprise org to Premium without resubscribing Source: https://nevermined.ai/docs/api-reference/organizations--billing/downgrade-an-enterprise-org-to-premium-without-resubscribing /api-reference/organizations-openapi.json post /organizations/{orgId}/billing/downgrade Swaps the active Stripe subscription item to the Premium USD/month price with prorated billing. The webhook handler picks up the new tier from `customer.subscription.updated`; this call also pre-shrinks published agents/plans so the org fits Premium caps immediately. Requires a Nevermined API key. Requires organization admin privileges. # Effective tier, caps and feature flags for this org Source: https://nevermined.ai/docs/api-reference/organizations--billing/effective-tier-caps-and-feature-flags-for-this-org /api-reference/organizations-openapi.json get /organizations/{orgId}/billing/entitlements Returns the live tier (derived from the latest subscription row, with on-read lapse enforcement), the cap matrix (agents / plans / members), the boolean feature flags, current usage counters, and the next-tier upgrade suggestion. Members (not just admins) can read this — the page is informational. Requires a Nevermined API key. Requires active organization membership. # List Stripe invoices for the org tier subscription Source: https://nevermined.ai/docs/api-reference/organizations--billing/list-stripe-invoices-for-the-org-tier-subscription /api-reference/organizations-openapi.json get /organizations/{orgId}/billing/invoices Returns up to the 20 most-recent Stripe invoices for the org tier subscription customer, or an empty list when the org has no Stripe customer. Requires a Nevermined API key. Requires organization admin privileges. # List the active hybrid-tier catalog Source: https://nevermined.ai/docs/api-reference/organizations--billing/list-the-active-hybrid-tier-catalog /api-reference/organizations-openapi.json get /organizations/billing/catalog Returns every active row in `organizationTierCatalog`. The list is static per environment once the bootstrap has run — call this once at webapp boot and cache for the session. Public endpoint — no authentication required. # Upgrade a Premium org to Enterprise without resubscribing Source: https://nevermined.ai/docs/api-reference/organizations--billing/upgrade-a-premium-org-to-enterprise-without-resubscribing /api-reference/organizations-openapi.json post /organizations/{orgId}/billing/upgrade Swaps the active Stripe subscription item to the Enterprise USD/month price with prorated billing — the SAME subscription, swapped in place. This avoids the second-subscription / double-billing bug of routing an upgrade through /checkout. The metadata is re-stamped to the Enterprise catalog row so the renewal handler (handleInvoicePaid) mints Enterprise credits on the next invoice. Unlike downgrade, no asset shrink runs — an upgrade only RAISES the caps. Requires a Nevermined API key. Requires organization admin privileges. # Block an organization customer Source: https://nevermined.ai/docs/api-reference/organizations--customers/block-an-organization-customer /api-reference/organizations-openapi.json post /organizations/{orgId}/customers/{customerId}/block Blocks a customer: revokes the API keys this organization issued to them via white-label onboarding, and refuses to re-issue those until they are unblocked. Their own personal keys, and keys issued by other organizations, are untouched. Note: short-lived credentials minted through the embedded widget/iframe session flow are not org-scoped, so a block neither revokes an outstanding one nor prevents a new one (tracked separately). Idempotent — blocking an already-blocked customer succeeds without re-revoking or re-emitting the activity event. Requires a Nevermined API key, organization admin privileges, and the Enterprise tier. # Export organization customers as CSV Source: https://nevermined.ai/docs/api-reference/organizations--customers/export-organization-customers-as-csv /api-reference/organizations-openapi.json get /organizations/{orgId}/customers/export Streams the organization’s customers as a CSV file (text/csv, attachment), enriched with each customer’s name and email. Honors the same `status` and `search` filters as the list endpoint but is not paginated. Requires a Nevermined API key, organization admin privileges, and the Enterprise tier. # Get an organization customer Source: https://nevermined.ai/docs/api-reference/organizations--customers/get-an-organization-customer /api-reference/organizations-openapi.json get /organizations/{orgId}/customers/{customerId} Returns a single customer record by ID. Responds 404 if the customer does not exist or belongs to a different organization. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Enterprise tier. # List organization customers Source: https://nevermined.ai/docs/api-reference/organizations--customers/list-organization-customers /api-reference/organizations-openapi.json get /organizations/{orgId}/customers Returns a paginated list of the organization’s customers (the users who have transacted with its agents/plans), optionally narrowed by a free-text search. The response is `{ items, total }`, where `total` is the count across all pages. Each item is enriched with the buyer’s userName/userEmail from their user profile when available. Requires a Nevermined API key, organization admin privileges, and the Enterprise tier. # Org-wide customer aggregations Source: https://nevermined.ai/docs/api-reference/organizations--customers/org-wide-customer-aggregations /api-reference/organizations-openapi.json get /organizations/{orgId}/customers/aggregations Returns org-level summary cards for the Customers tab: total customer count, purchase count and total spend in the requested date range, and a gap-filled daily time-series of purchases over that range. Requires a Nevermined API key and Enterprise tier. # Per-customer aggregations + drill-down series Source: https://nevermined.ai/docs/api-reference/organizations--customers/per-customer-aggregations-+-drill-down-series /api-reference/organizations-openapi.json get /organizations/{orgId}/customers/{customerId}/aggregations Returns the customer entity plus their purchase aggregates (count, total spent) and a gap-filled daily time-series of purchases in the requested window. Requires a Nevermined API key, organization admin privileges, and the Enterprise tier. # Per-customer purchase history Source: https://nevermined.ai/docs/api-reference/organizations--customers/per-customer-purchase-history /api-reference/organizations-openapi.json get /organizations/{orgId}/customers/{customerId}/purchases Returns a paginated history of plan purchases for the customer, ordered by newest first, joined with the plan’s display name. Requires a Nevermined API key, organization admin privileges, and the Enterprise tier. # Unblock an organization customer Source: https://nevermined.ai/docs/api-reference/organizations--customers/unblock-an-organization-customer /api-reference/organizations-openapi.json post /organizations/{orgId}/customers/{customerId}/unblock Restores a blocked customer to active, so the organization can issue them credentials again. Does NOT reinstate the keys revoked at block time — those stay revoked and a new one must be issued. Idempotent. Requires a Nevermined API key, organization admin privileges, and the Enterprise tier. # Public agentic instructions for an organization Source: https://nevermined.ai/docs/api-reference/organizations--integration/public-agentic-instructions-for-an-organization /api-reference/organizations-openapi.json get /organizations/{orgId}/agentic-instructions.md Returns a markdown document instructing autonomous AI agents how to discover and pay for the organization's plans and agents via Nevermined. Only active Premium/Enterprise organizations are served; any other org (Lapsed or non-existent) returns 404 without leaking the reason. Public endpoint — no authentication required. # Public ARD ai-catalog.json for an organization Source: https://nevermined.ai/docs/api-reference/organizations--integration/public-ard-ai-catalogjson-for-an-organization /api-reference/organizations-openapi.json get /organizations/{orgId}/ai-catalog.json Returns the organization's Agentic Resource Discovery (ARD) catalog: one entry per listed agent, each carrying its x402 payment terms (plan, price, settlement network) in `metadata`. Crawlable by ARD registries. Only active Premium/Enterprise organizations are served; any other org (Lapsed or non-existent) returns 404. Public endpoint — no authentication required. # Public llms.txt index for an organization Source: https://nevermined.ai/docs/api-reference/organizations--integration/public-llmstxt-index-for-an-organization /api-reference/organizations-openapi.json get /organizations/{orgId}/llms.txt Returns the agent-discoverable llms.txt index listing the organization's payment plans, agents, and Nevermined reference links, rendered as plain text. Only active Premium/Enterprise organizations are served; any other org (Lapsed or non-existent) returns 404 without leaking the reason. Public endpoint — no authentication required. # Generate a WebSocket secret Source: https://nevermined.ai/docs/api-reference/organizations--realtime/generate-a-websocket-secret /api-reference/organizations-openapi.json post /organizations/{orgId}/realtime/secrets Creates a new per-member WebSocket secret used to authenticate against the organization realtime activity stream. The plaintext secret is returned ONCE in the response and is never retrievable again — store it immediately. The secret belongs to the calling member; any active member manages their own secrets. The realtime feature is gated on the org's live subscription tier (resolved from the subscription row, not the denormalised cache). Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Enterprise tier. # List the caller's own WebSocket secrets Source: https://nevermined.ai/docs/api-reference/organizations--realtime/list-the-callers-own-websocket-secrets /api-reference/organizations-openapi.json get /organizations/{orgId}/realtime/secrets Returns the WebSocket secrets owned by the calling member for this organization. The plaintext secret is never included — each item carries only the id, label, last four characters, status, and timestamps. Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Enterprise tier. # Revoke a WebSocket secret Source: https://nevermined.ai/docs/api-reference/organizations--realtime/revoke-a-websocket-secret /api-reference/organizations-openapi.json delete /organizations/{orgId}/realtime/secrets/{id} Permanently revokes a WebSocket secret and terminates any live socket currently authenticated with it. The caller may only revoke secrets they own. Returns 204 No Content on success. Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Enterprise tier. # Rotate a WebSocket secret Source: https://nevermined.ai/docs/api-reference/organizations--realtime/rotate-a-websocket-secret /api-reference/organizations-openapi.json post /organizations/{orgId}/realtime/secrets/{id}/rotate Issues a fresh plaintext secret for an existing secret record and immediately invalidates the previous value, terminating any live socket still using it. The new plaintext secret is returned ONCE and is never retrievable again. The caller may only rotate secrets they own. Requires a Nevermined API key. Requires active organization membership. Requires the organization to be on the Enterprise tier. # Create an organization stablecoin wallet Source: https://nevermined.ai/docs/api-reference/organizations--wallets/create-an-organization-stablecoin-wallet /api-reference/organizations-openapi.json post /organizations/{orgId}/wallets # List an org's active stablecoin wallets Source: https://nevermined.ai/docs/api-reference/organizations--wallets/list-an-orgs-active-stablecoin-wallets /api-reference/organizations-openapi.json get /organizations/{orgId}/wallets # List the groups a wallet is shared with Source: https://nevermined.ai/docs/api-reference/organizations--wallets/list-the-groups-a-wallet-is-shared-with /api-reference/organizations-openapi.json get /organizations/{orgId}/wallets/{id}/groups # List the org wallets shared with a group (fund its budgets) Source: https://nevermined.ai/docs/api-reference/organizations--wallets/list-the-org-wallets-shared-with-a-group-fund-its-budgets /api-reference/organizations-openapi.json get /organizations/{orgId}/groups/{groupId}/wallets # Read a wallet's USDC + EURC balances on the deployment's chain Source: https://nevermined.ai/docs/api-reference/organizations--wallets/read-a-wallets-usdc-+-eurc-balances-on-the-deployments-chain /api-reference/organizations-openapi.json get /organizations/{orgId}/wallets/{id}/balances # Read one organization wallet by id Source: https://nevermined.ai/docs/api-reference/organizations--wallets/read-one-organization-wallet-by-id /api-reference/organizations-openapi.json get /organizations/{orgId}/wallets/{id} # Rename an organization wallet Source: https://nevermined.ai/docs/api-reference/organizations--wallets/rename-an-organization-wallet /api-reference/organizations-openapi.json patch /organizations/{orgId}/wallets/{id} # Revoke (soft-delete) an organization wallet Source: https://nevermined.ai/docs/api-reference/organizations--wallets/revoke-soft-delete-an-organization-wallet /api-reference/organizations-openapi.json delete /organizations/{orgId}/wallets/{id} # Share an org wallet with a group (so it funds the group budget) Source: https://nevermined.ai/docs/api-reference/organizations--wallets/share-an-org-wallet-with-a-group-so-it-funds-the-group-budget /api-reference/organizations-openapi.json post /organizations/{orgId}/wallets/{id}/groups/{groupId} # Stop a group from drawing on a wallet Source: https://nevermined.ai/docs/api-reference/organizations--wallets/stop-a-group-from-drawing-on-a-wallet /api-reference/organizations-openapi.json delete /organizations/{orgId}/wallets/{id}/groups/{groupId} # Withdraw stablecoins from an org wallet to a nominated address Source: https://nevermined.ai/docs/api-reference/organizations--wallets/withdraw-stablecoins-from-an-org-wallet-to-a-nominated-address /api-reference/organizations-openapi.json post /organizations/{orgId}/wallets/{id}/withdraw # Create a webhook subscription Source: https://nevermined.ai/docs/api-reference/organizations--webhooks/create-a-webhook-subscription /api-reference/organizations-openapi.json post /organizations/{orgId}/webhooks Registers an outbound webhook endpoint for the organization. Every matching activity event is delivered as a signed HTTP POST to the target URL. The HMAC signing secret is generated server-side and returned ONCE in the response (in the `secret` field); it is never retrievable again, so store it immediately. Subsequent reads expose only a `secretHint` (last four characters). The URL is validated against an SSRF guard and must be https:// in production. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # Delete a webhook subscription Source: https://nevermined.ai/docs/api-reference/organizations--webhooks/delete-a-webhook-subscription /api-reference/organizations-openapi.json delete /organizations/{orgId}/webhooks/{id} Permanently removes a webhook subscription and stops all future deliveries to its endpoint. Returns 204 No Content on success. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # Get a webhook delivery record Source: https://nevermined.ai/docs/api-reference/organizations--webhooks/get-a-webhook-delivery-record /api-reference/organizations-openapi.json get /organizations/{orgId}/webhooks/deliveries/{deliveryId} Returns the full audit record for a single webhook delivery attempt, including the JSON payload that was POSTed, the response status code, and a truncated response body. The delivery is resolved by its own ID scoped to the organization — not to a specific subscription — so no subscription ID is needed in the path. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # Get a webhook subscription Source: https://nevermined.ai/docs/api-reference/organizations--webhooks/get-a-webhook-subscription /api-reference/organizations-openapi.json get /organizations/{orgId}/webhooks/{id} Returns a single webhook subscription by ID. The signing secret is never included — a `secretHint` (last four characters) is returned instead. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # List deliveries for a webhook subscription Source: https://nevermined.ai/docs/api-reference/organizations--webhooks/list-deliveries-for-a-webhook-subscription /api-reference/organizations-openapi.json get /organizations/{orgId}/webhooks/{subscriptionId}/deliveries Returns the paginated delivery-attempt log for a single webhook subscription, ordered most-recent first. Each row records the event type, attempt count, lifecycle status, response code, and timestamps. Optionally filter by delivery status. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # List webhook subscriptions Source: https://nevermined.ai/docs/api-reference/organizations--webhooks/list-webhook-subscriptions /api-reference/organizations-openapi.json get /organizations/{orgId}/webhooks Returns every webhook subscription registered for the organization. The signing secret is never included — each item carries a `secretHint` (last four characters) instead. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # Retry a webhook delivery Source: https://nevermined.ai/docs/api-reference/organizations--webhooks/retry-a-webhook-delivery /api-reference/organizations-openapi.json post /organizations/{orgId}/webhooks/deliveries/{deliveryId}/retry Queues a webhook delivery for an immediate retry by resetting it to pending and dispatching it without waiting for the next scheduled attempt. The delivery is resolved by its own ID scoped to the organization, so no subscription ID is needed in the path. Responds 202 Accepted as soon as the retry is queued; the actual POST happens asynchronously. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # Rotate a webhook signing secret Source: https://nevermined.ai/docs/api-reference/organizations--webhooks/rotate-a-webhook-signing-secret /api-reference/organizations-openapi.json post /organizations/{orgId}/webhooks/{id}/rotate-secret Generates a new HMAC signing secret for the subscription and immediately invalidates the previous one. Signatures computed with the old secret stop verifying as soon as this returns. The new plaintext secret is returned ONCE in the response and is never retrievable again. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # Update a webhook subscription Source: https://nevermined.ai/docs/api-reference/organizations--webhooks/update-a-webhook-subscription /api-reference/organizations-openapi.json patch /organizations/{orgId}/webhooks/{id} Partially updates a webhook subscription. Only the fields present in the request body are changed (URL, subscribed event types, enabled flag, and description). A new URL is revalidated against the SSRF guard. The response omits the signing secret. Requires a Nevermined API key. Requires organization admin privileges. Requires the organization to be on the Premium tier or higher. # Change an organization member role Source: https://nevermined.ai/docs/api-reference/organizations/change-an-organization-member-role /api-reference/organizations-openapi.json patch /organizations/{orgId}/members/{memberId} Changes a member role between Admin and Member. Cannot demote the last active admin (returns 422). Requires a Nevermined API key. Requires organization admin privileges. # Deactivate an organization member Source: https://nevermined.ai/docs/api-reference/organizations/deactivate-an-organization-member /api-reference/organizations-openapi.json post /organizations/{orgId}/members/{memberId}/deactivate Sets the member isActive flag to false. Idempotent — no-op if already inactive. Cannot deactivate the last active admin (returns 422). Requires a Nevermined API key. Requires organization admin privileges. # Get the organization info for a user Source: https://nevermined.ai/docs/api-reference/organizations/get-the-organization-info-for-a-user /api-reference/organizations-openapi.json get /organizations/user-info/{userId} Returns the resolved organization context for the given user: orgId, role, active flags, organization type, fee settings, Stripe account (for the requested environment), and organization wallet. When `orgId` is supplied the membership for that specific org is returned; otherwise it falls back to the user most-recent active membership. Callers may only request their own `:userId` (ownership is enforced). Requires a Nevermined API key or a Privy identity token. # List the authenticated user's active org memberships Source: https://nevermined.ai/docs/api-reference/organizations/list-the-authenticated-users-active-org-memberships /api-reference/organizations-openapi.json get /organizations/my-memberships Returns all active memberships for the authenticated user. Used by the workspace switcher dropdown. Empty array when the user belongs to no active organizations. Requires a Nevermined API key or a Privy identity token. # Provision an account for the organization (member or customer) Source: https://nevermined.ai/docs/api-reference/organizations/provision-an-account-for-the-organization-member-or-customer /api-reference/organizations-openapi.json post /organizations/account Provisions a Nevermined identity (and Privy-managed wallet) for the given email under the caller's organization. The `as` field selects the outcome: - `member` (default): adds a seat-consuming `OrganizationMember` with the requested role (defaults to Member), starting inactive pending an email-challenge confirmation. Returns 201 when the membership was created, or 200 when the user is already a member. - `customer`: **white-label onboarding** — no seat is consumed. `role` is ignored. The behaviour depends on whether the email already has a Nevermined identity: - **new account**: recorded into the organization Customers CRM immediately (before any purchase) and the response returns a usable, scoped NVM API key (`walletResult.nvmApiKey`, 201) so the organization can transparently act for its own customer. The key is tagged to the caller's organization, so the customer's requests resolve to that workspace and their activity/purchases are attributed to it. - **existing account**: no key is issued (account-takeover guard). An email challenge is sent to the owner and the response is `202` with `walletResult.consentRequired = true`; the organization cannot obtain a credential for an account it does not own without the owner’s consent. Requires a Nevermined API key and organization admin privileges. # Reactivate an organization member Source: https://nevermined.ai/docs/api-reference/organizations/reactivate-an-organization-member /api-reference/organizations-openapi.json post /organizations/{orgId}/members/{memberId}/reactivate Sets the member isActive flag to true. Idempotent — no-op if already active. Role is preserved unchanged. Requires a Nevermined API key. Requires organization admin privileges. # Remove an organization member Source: https://nevermined.ai/docs/api-reference/organizations/remove-an-organization-member /api-reference/organizations-openapi.json delete /organizations/{orgId}/members/{memberId} Deletes the member record. Idempotent — returns success if the row is already gone. Cannot remove the last active admin (returns 422). Requires a Nevermined API key. Requires organization admin privileges. # Search the members of an organization Source: https://nevermined.ai/docs/api-reference/organizations/search-the-members-of-an-organization /api-reference/organizations-openapi.json post /organizations/members Returns a paginated list of the members of the caller organization, optionally filtered by role and active status, alongside the total count of active admins (used to guard "last admin" actions across pages). The organization is resolved from the authenticated context, not from the request body. Read-only — any active member (not just admins) may call it. Requires a Nevermined API key. # Update organization details Source: https://nevermined.ai/docs/api-reference/organizations/update-organization-details /api-reference/organizations-openapi.json put /organizations Updates mutable metadata on the caller organization (name, description, url, active flag, crypto/fiat fees). The organization is resolved from the authenticated context. Only fields present in the body are changed. Requires a Nevermined API key. Requires organization admin privileges. # Validate that the user may use an org as their workspace context Source: https://nevermined.ai/docs/api-reference/organizations/validate-that-the-user-may-use-an-org-as-their-workspace-context /api-reference/organizations-openapi.json post /organizations/{orgId}/validate Checks active membership in the given org before the client flips its `X-Current-Org-Id` header. The literal value "personal" is always valid and returns `currentOrgId: null` without a database lookup. Returns 403 if the user is not an active member of the requested org. Requires a Nevermined API key or a Privy identity token. # List Payment Methods Source: https://nevermined.ai/docs/api-reference/payment-methods/list-payment-methods GET /payment-methods Returns the saved payment methods for the authenticated user. Requires a Nevermined API key. # Revoke Payment Method Source: https://nevermined.ai/docs/api-reference/payment-methods/revoke-payment-method DELETE /payment-methods/{paymentMethodId} Revokes (detaches) a saved payment method so it can no longer be used for delegated payments. Requires a Nevermined API key. # Update Payment Method Source: https://nevermined.ai/docs/api-reference/payment-methods/update-payment-method PATCH /payment-methods/{paymentMethodId} Updates a saved payment method, changing its friendly alias and/or the set of NVM API keys allowed to use it. Requires a Nevermined API key. # Add Plan to Agent Source: https://nevermined.ai/docs/api-reference/protocol/add-plan-to-agent POST /protocol/agents/{agentId}/plan/{planId} Associates an existing payment plan with an agent. # Get Access Token Source: https://nevermined.ai/docs/api-reference/protocol/get-access-token GET /protocol/token/{planId}/{agentId} Generates access credentials for agent-plan interaction. # Get Agent Source: https://nevermined.ai/docs/api-reference/protocol/get-agent GET /protocol/agents/{agentId} Retrieves agent configuration and associated plans. # Get Agent Plans Source: https://nevermined.ai/docs/api-reference/protocol/get-agent-plans GET /protocol/agents/{agentId}/plans Lists all payment plans associated with an agent. # Get Plan Source: https://nevermined.ai/docs/api-reference/protocol/get-plan GET /protocol/plans/{planId} Retrieves details about a specific payment plan. # Get Plan Agents Source: https://nevermined.ai/docs/api-reference/protocol/get-plan-agents GET /protocol/plans/{planId}/agents Lists all agents associated with a payment plan. # Get Plan Balance Source: https://nevermined.ai/docs/api-reference/protocol/get-plan-balance GET /protocol/plans/{planId}/balance/{holderAddress} Retrieves credit balance for a specific account on a plan. # Initialize Agent Request Source: https://nevermined.ai/docs/api-reference/protocol/initialize-agent-request POST /protocol/agents/initialize/{agentId} Validates access and initializes an agent request session. # List Agents Source: https://nevermined.ai/docs/api-reference/protocol/list-agents GET /protocol/agents Get paginated list of agents for the current user. # List Plans Source: https://nevermined.ai/docs/api-reference/protocol/list-plans GET /protocol/plans Get paginated list of payment plans for the current user. # Mint Credits Source: https://nevermined.ai/docs/api-reference/protocol/mint-credits POST /protocol/plans/mint Adds credits to a plan account. Builder-only operation. # Mint Expirable Credits Source: https://nevermined.ai/docs/api-reference/protocol/mint-expirable-credits POST /protocol/plans/mintExpirable Adds time-limited credits to a plan account. # Order Plan Source: https://nevermined.ai/docs/api-reference/protocol/order-plan POST /protocol/plans/{planId}/order Purchases a payment plan. Credits are issued immediately. # Redeem Credits Source: https://nevermined.ai/docs/api-reference/protocol/redeem-credits POST /protocol/plans/redeem Consumes credits from a plan account after processing a request. # Register Agent Source: https://nevermined.ai/docs/api-reference/protocol/register-agent POST /protocol/agents Creates a new AI agent with API configuration. # Register Agent and Plan Source: https://nevermined.ai/docs/api-reference/protocol/register-agent-and-plan POST /protocol/agents/plans Creates both an agent and associated payment plan in a single request. # Register Plan Source: https://nevermined.ai/docs/api-reference/protocol/register-plan POST /protocol/plans Creates a new payment plan with pricing and credit configuration. # Remove Plan from Agent Source: https://nevermined.ai/docs/api-reference/protocol/remove-plan-from-agent DELETE /protocol/agents/{agentId}/plan/{planId} Disassociates a payment plan from an agent. # Activate/Deactivate Agent Source: https://nevermined.ai/docs/api-reference/protocol/toggle-agent-listing PUT /protocol/agents/{agentId}/list/{activate} Controls the agent's public listing status. # Activate/Deactivate Plan Source: https://nevermined.ai/docs/api-reference/protocol/toggle-plan-listing PUT /protocol/plans/{planId}/list/{activate} Lists (`activate=true`) or unlists (`activate=false`) a plan. This is a flag stored by Nevermined, not an on-chain change. An unlisted plan is hidden from discovery and can no longer be purchased. Checkout, crypto order and the card-delegation x402 settle are refused with the error `BCK.PROTOCOL.0062`; the other x402 refusals (every verify, and the erc4337 settle of an auto-order or pay-as-you-go call) answer `isValid: false` / `success: false` with that error's message as the reason, without a `code` field. Subscribers keep spending the credits they already hold while their balance covers a call. # Track Agent Sub Task Source: https://nevermined.ai/docs/api-reference/protocol/track-agent-sub-task POST /protocol/agent-sub-tasks Records task completion and credit consumption for complex agent workflows. # Update Agent Source: https://nevermined.ai/docs/api-reference/protocol/update-agent PUT /protocol/agents/{agentId} Modifies agent configuration and metadata. # Update Plan Source: https://nevermined.ai/docs/api-reference/protocol/update-plan PUT /protocol/plans/{planId} Modifies plan metadata. # A2A Integration Source: https://nevermined.ai/docs/api-reference/python/a2a-module Implement Agent-to-Agent protocol with payments This guide explains how to integrate the Nevermined Payments Python SDK with A2A (Agent-to-Agent) protocol servers. ## Overview A2A (Agent-to-Agent) is a protocol that enables AI agents to communicate with each other using JSON-RPC. The Nevermined SDK provides A2A integration to: * Build A2A servers with payment validation * Automatically verify x402 tokens on incoming requests * Handle credit redemption for agent tasks ## Building Agent Cards ### With a Single Plan ```python theme={null} from payments_py.a2a.agent_card import build_payment_agent_card agent_card = build_payment_agent_card( base_card={ "name": "Code Review Agent", "description": "Automated code review powered by AI", "url": "https://localhost:8080", "version": "1.0.0", "capabilities": { "streaming": False, "pushNotifications": False, }, }, payment_metadata={ "paymentType": "fixed", "credits": 1, "agentId": "your-agent-id", "planId": "your-plan-id", "costDescription": "1 credit per review", }, ) ``` ### With Multiple Plans When your agent supports multiple plans (e.g. a basic and a premium tier), use `planIds` instead of `planId`: ```python theme={null} agent_card = build_payment_agent_card( base_card={ "name": "Code Review Agent", "url": "https://localhost:8080", "version": "1.0.0", "capabilities": {}, }, payment_metadata={ "paymentType": "dynamic", "credits": 5, "agentId": "your-agent-id", "planIds": ["plan-basic", "plan-premium"], "costDescription": "1-5 credits depending on review depth", }, ) ``` > **Note:** Provide either `planId` or `planIds`, not both. `planIds` must be a non-empty list. ### Agent Card Structure The agent card declares two extensions: the Nevermined payment extension (pricing metadata) and the official a2a-x402 extension (`https://github.com/google-agentic-commerce/a2a-x402/blob/main/spec/v0.2`), which signals support for the standards-compliant in-band x402 v2 flow (see [In-Band x402 v2 Payments](#in-band-x402-v2-payments-standards-flow)). Both ship for one release; `urn:nevermined:payment` is dropped once clients use v0.2 only. ```json theme={null} { "name": "Code Review Agent", "url": "https://localhost:8080", "version": "1.0.0", "capabilities": { "extensions": [ { "uri": "urn:nevermined:payment", "params": { "paymentType": "dynamic", "credits": 5, "agentId": "your-agent-id", "planIds": ["plan-basic", "plan-premium"], "costDescription": "1-5 credits depending on review depth" } }, { "uri": "https://github.com/google-agentic-commerce/a2a-x402/blob/main/spec/v0.2" } ] } } ``` ## Using the `@a2a_requires_payment` Decorator The simplest way to create a payment-protected A2A agent: ```python theme={null} from payments_py import Payments from payments_py.common.types import PaymentOptions from payments_py.a2a import AgentResponse, a2a_requires_payment, build_payment_agent_card payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) agent_card = build_payment_agent_card( base_card={ "name": "My Agent", "url": "http://localhost:8080", "version": "1.0.0", "capabilities": {}, }, payment_metadata={ "paymentType": "dynamic", "credits": 3, "agentId": "your-agent-id", "planIds": ["plan-1", "plan-2"], }, ) @a2a_requires_payment( payments=payments, agent_card=agent_card, default_credits=1, ) async def my_agent(context) -> AgentResponse: text = context.get_user_input() return AgentResponse(text=f"Echo: {text}", credits_used=1) # Start serving (blocking) my_agent.serve(port=8080) ``` The decorator handles: * Payment middleware (verify/settle) automatically * Publishing task status events with `creditsUsed` metadata * Credit burning on task completion ### `AgentResponse` | Field | Type | Description | | - | - | - | | `text` | `str` | The agent's text response | | `credits_used` | `int \| None` | Credits consumed (falls back to `default_credits`) | | `metadata` | `dict \| None` | Extra metadata for the final event | ## Starting an A2A Server (Advanced) For more control, use `PaymentsA2AServer.start()` directly: ```python theme={null} from payments_py.a2a.server import PaymentsA2AServer from a2a.server.agent_execution import AgentExecutor from a2a.server.events.event_queue import EventQueue class MyExecutor(AgentExecutor): async def execute(self, context, event_queue: EventQueue): # Your agent logic — publish events to event_queue ... async def cancel(self, context, event_queue: EventQueue): ... result = PaymentsA2AServer.start( agent_card=agent_card, executor=MyExecutor(), payments_service=payments, port=8080, base_path="/", expose_agent_card=True, async_execution=False, ) # Run the server import asyncio asyncio.run(result.server.serve()) ``` ## Server Configuration Options | Option | Type | Required | Description | | - | - | - | - | | `agent_card` | `AgentCard` | Yes | A2A agent card with payment extension | | `executor` | `AgentExecutor` | Yes | Your agent implementation | | `payments_service` | `Payments` | Yes | Payments instance | | `port` | `int` | No | Server port (default: 8080) | | `task_store` | `TaskStore` | No | Task storage implementation | | `base_path` | `str` | No | Base URL path (default: "/") | | `expose_agent_card` | `bool` | No | Expose /.well-known/agent-card.json (+ legacy /.well-known/agent.json alias) | | `hooks` | `dict` | No | Request lifecycle hooks | | `async_execution` | `bool` | No | Enable async task execution | ## Request Validation The A2A server automatically validates payments on every POST request: 1. Extracts Bearer token from Authorization header 2. Reads `planId` or `planIds` from the agent card's payment extension 3. Verifies permissions via `build_payment_required_for_plans()` 4. Rejects requests with 402 if validation fails, including a base64-encoded `payment-required` header When multiple plans are configured, the 402 response includes all plans in `accepts[]`, allowing the client to choose which plan to purchase. ``` HTTP/1.1 402 Payment Required payment-required: eyJ4NDAy... (base64-encoded X402PaymentRequired) {"error": {"code": -32001, "message": "Missing bearer token."}} ``` ## In-Band x402 v2 Payments (Standards Flow) Payment is signalled **in band** following the [Coinbase x402 v2 A2A transport spec](https://github.com/coinbase/x402/blob/main/specs/transports-v2/a2a.md) and the official [a2a-x402 extension](https://github.com/google-agentic-commerce/a2a-x402). The `X402A2AUtils` helpers (see [x402 README](https://github.com/nevermined-io/payments-py/blob/main/payments_py/x402/README.md)) now power this live server flow — `PaymentsA2AServer` stamps and reads the metadata automatically, so the executor is unchanged. The handshake rides on A2A task/message metadata, correlated by `taskId` — no HTTP 402 is exchanged. Lifecycle: 1. **Payment required** — a payment-gated `message/send` arrives with no payment. The server returns a Task with `status.state = "input-required"` and `status.message.metadata`: ```json theme={null} { "x402.payment.status": "payment-required", "x402.payment.required": { "...": "X402PaymentRequired (accepts[] of plans)" } } ``` 2. **Payment submitted** — the client replies with a follow-up `message/send` whose `message.metadata` carries the payload, correlated via `message.taskId`: ```json theme={null} { "x402.payment.status": "payment-submitted", "x402.payment.payload": { "...": "PaymentPayload" } } ``` 3. **Completed / failed** — on success the final Task carries `x402.payment.status: "payment-completed"` plus `x402.payment.receipts`. On failure it is `failed` / `payment-failed` with the error under `x402.payment.error`, and paid content is suppressed. Metadata keys: `x402.payment.status`, `x402.payment.required`, `x402.payment.payload`, `x402.payment.receipts`, `x402.payment.error`. > **Note:** The legacy `payment-signature` HTTP header flow still works but is now a **deprecated fallback, kept for one release**. New integrations should use the in-band metadata flow above. ## Client Usage ### Discovering Plans from the Agent Card Consumers can fetch the agent card to discover available plans: ```python theme={null} import httpx async with httpx.AsyncClient() as client: # Canonical path (A2A 0.3+); /.well-known/agent.json still works as a legacy alias resp = await client.get("http://agent-url/.well-known/agent-card.json") card = resp.json() extensions = card["capabilities"]["extensions"] payment_ext = next(e for e in extensions if e["uri"] == "urn:nevermined:payment") plan_ids = payment_ext["params"].get("planIds") or [payment_ext["params"]["planId"]] agent_id = payment_ext["params"]["agentId"] ``` ### Ordering a Plan and Sending Messages ```python theme={null} from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:subscriber-key", environment="sandbox") ) # Order (purchase) the plan payments.plans.order_plan(plan_ids[0]) # Get x402 access token token_resp = payments.x402.get_x402_access_token( plan_id=plan_ids[0], agent_id=agent_id, ) access_token = token_resp["accessToken"] # Send A2A JSON-RPC message async with httpx.AsyncClient() as client: resp = await client.post( "http://agent-url/", json={ "jsonrpc": "2.0", "id": 1, "method": "message/send", "params": { "message": { "messageId": "msg-1", "role": "user", "parts": [{"kind": "text", "text": "Review this code"}], } }, }, headers={"Authorization": f"Bearer {access_token}"}, ) result = resp.json() ``` ## Hooks Add custom logic at request lifecycle points: ```python theme={null} async def before_request(method, params, request): print(f"Incoming request: {method}") async def after_request(method, response, request): print(f"Request completed: {method}") async def on_error(method, error, request): print(f"Request failed: {method} - {error}") result = PaymentsA2AServer.start( agent_card=agent_card, executor=executor, payments_service=payments, hooks={ "beforeRequest": before_request, "afterRequest": after_request, "onError": on_error, }, ) ``` ## Error Handling | Error Code | HTTP Status | Description | | - | - | - | | -32001 | 402 | Missing Bearer token | | -32001 | 402 | Payment validation failed | | -32001 | 402 | Agent ID missing from card | | -32001 | 402 | Plan ID missing from card | ## Next Steps > [card] [x402 Protocol](/docs/api-reference/python/x402-module) > > Deep dive into x402 payment protocol > [card] [Request Validation](/docs/api-reference/python/validation-module) > > Manual validation patterns # Agents Source: https://nevermined.ai/docs/api-reference/python/agents-module Register and manage AI agents with the Python SDK This guide covers how to register and manage AI agents using the Nevermined Payments Python SDK. ## Overview AI Agents are services that users can access through payment plans. The Agents API allows you to: * Register new agents with associated payment plans * Register agents and plans together in a single operation * Update agent metadata and endpoints * Manage plan associations ## Agents API Access the Agents API through `payments.agents`: ```python theme={null} from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) # Access agents API agents_api = payments.agents ``` ## Register Agents ### Basic Agent Registration Register an agent and associate it with existing payment plans: ```python theme={null} import os from payments_py.common.types import AgentMetadata, AgentAPIAttributes, AuthType # Define agent metadata agent_metadata = AgentMetadata( name="My AI Assistant", description="An intelligent assistant that helps with various tasks", tags=["ai", "assistant", "productivity"], author="Your Company" ) # Define API configuration. All AgentAPIAttributes fields are optional — # most builders only need to set authentication. See # "AgentAPIAttributes Fields" below for opt-in Additional Security. agent_api = AgentAPIAttributes( auth_type=AuthType.BEARER, token=os.environ["AGENT_BEARER_TOKEN"], ) # List of plan IDs that grant access to this agent payment_plans = [plan_id_1, plan_id_2] # Register the agent result = payments.agents.register_agent( agent_metadata=agent_metadata, agent_api=agent_api, payment_plans=payment_plans ) print(f"Agent ID: {result['agentId']}") ``` ### Register Agent and Plan Together Create both an agent and a payment plan in a single operation: ```python theme={null} import os from payments_py.common.types import ( AgentMetadata, AgentAPIAttributes, AuthType, PlanMetadata, ) from payments_py.plans import get_erc20_price_config, get_fixed_credits_config # Agent configuration agent_metadata = AgentMetadata( name="AI Code Reviewer", description="Automated code review assistant", tags=["code", "review", "ai"] ) agent_api = AgentAPIAttributes( auth_type=AuthType.BEARER, token=os.environ["AGENT_BEARER_TOKEN"], ) # Plan configuration plan_metadata = PlanMetadata( name="Code Review Plan", description="100 code reviews" ) price_config = get_erc20_price_config( amount=50, token_address="0xYourTokenAddress", receiver=payments.account_address ) credits_config = get_fixed_credits_config(credits_granted=100) # Register both in one call result = payments.agents.register_agent_and_plan( agent_metadata=agent_metadata, agent_api=agent_api, plan_metadata=plan_metadata, price_config=price_config, credits_config=credits_config, access_limit="credits" # or "time" ) print(f"Agent ID: {result['agentId']}") print(f"Plan ID: {result['planId']}") print(f"Transaction: {result['txHash']}") ``` ## Agent Configuration ### AgentMetadata Fields | Field | Type | Required | Description | | - | - | - | - | | `name` | `str` | Yes | Agent display name | | `description` | `str` | No | Agent description | | `author` | `str` | No | Author/company name | | `tags` | `list[str]` | No | Categorization tags | | `license` | `str` | No | License information | | `sample_link` | `str` | No | Link to demo/sample | | `api_description` | `str` | No | API documentation | ### AgentAPIAttributes Fields All fields are optional. Provide only what your integration needs. | Field | Type | Required | Description | | - | - | - | - | | `auth_type` | `AuthType` | No | Authentication type (default: `AuthType.NONE`) | | `token` | `str` | No | Bearer token (when `auth_type` is `BEARER` or `OAUTH`) | | `username` | `str` | No | Basic-auth username | | `password` | `str` | No | Basic-auth password | | `endpoints` | `list[Endpoint]` | No | **Additional Security** allowlist — see below | | `open_endpoints` | `list[str]` | No | Public endpoints (no subscription required) | | `agent_definition_url` | `str` | No | Discoverable agent definition (OpenAPI / MCP / A2A) | ### Additional Security: Endpoint Allowlist (opt-in) Setting `endpoints` opts the agent into a platform-enforced allowlist. When set, only requests matching one of the registered URLs are accepted during x402 verification; non-matching requests are rejected. When omitted, the platform performs no route-level allowlist check — your Payments library middleware (`PaymentMiddleware`, `@requires_payment`) remains the sole gate. ```python theme={null} import os from payments_py.common.types import AgentAPIAttributes, AuthType, Endpoint agent_api = AgentAPIAttributes( auth_type=AuthType.BEARER, token=os.environ["AGENT_BEARER_TOKEN"], # Opt-in: route allowlist enforced by x402 verify endpoints=[ Endpoint(verb="POST", url="https://api.example.com/agents/:agentId/tasks"), Endpoint(verb="GET", url="https://api.example.com/agents/:agentId/tasks/:taskId"), Endpoint(verb="DELETE", url="https://api.example.com/agents/:agentId/tasks/:taskId"), ], open_endpoints=["https://api.example.com/health"], agent_definition_url="https://api.example.com/openapi.json", ) ``` The `:agentId` and `:taskId` placeholders will be replaced with actual values during request validation. > **Migration note:** existing agents that registered before April 2026 still have these fields populated and continue to enforce the allowlist as before. No migration is needed. ## Retrieve Agents ### List Your Agents List the agents **you** published. This is caller-scoped account management — it returns only the agents the authenticated account created, never other users' agents (Nevermined is not a marketplace, so there is no global agent search). Useful for finding and managing your own agents (e.g. spotting duplicates). ```python theme={null} from payments_py.common.types import PaginationOptions # Your own agents result = payments.agents.get_user_agents( pagination=PaginationOptions(page=1, offset=10) ) print(f"Total: {result['total']}") for agent in result["agents"]: print(agent["id"]) # Every agent in an organization you belong to org_agents = payments.agents.get_user_agents(org_id="org-acme") ``` ### Get a Single Agent ```python theme={null} agent = payments.agents.get_agent(agent_id="your-agent-id") print(f"Agent name: {agent['name']}") print(f"Agent endpoints: {agent['endpoints']}") ``` ### Get Plans for an Agent ```python theme={null} from payments_py.common.types import PaginationOptions plans = payments.agents.get_agent_plans( agent_id="your-agent-id", pagination=PaginationOptions(page=1, offset=10) ) print(f"Associated plans: {plans}") ``` ## Update Agents ### Update Agent Metadata `update_agent_metadata` is also where builders typically opt in to **Additional Security** by adding an `endpoints` allowlist or `agent_definition_url` to an existing agent: ```python theme={null} import os from payments_py.common.types import ( AgentMetadata, AgentAPIAttributes, AuthType, Endpoint, ) updated_metadata = AgentMetadata( name="Updated Agent Name", description="Updated description with new features", tags=["ai", "updated", "v2"] ) # Adding `endpoints` activates the platform-enforced allowlist for this # agent. To return to allow-all, omit it on the next update. updated_api = AgentAPIAttributes( auth_type=AuthType.BEARER, token=os.environ["AGENT_BEARER_TOKEN"], endpoints=[Endpoint(verb="POST", url="https://new-api.com/v2/tasks")], agent_definition_url="https://new-api.com/v2/openapi.json", ) result = payments.agents.update_agent_metadata( agent_id="your-agent-id", agent_metadata=updated_metadata, agent_api=updated_api ) print(f"Update successful: {result}") ``` ## Manage Plan Associations ### Add a Plan to an Agent ```python theme={null} result = payments.agents.add_plan_to_agent( plan_id="plan-to-add", agent_id="your-agent-id" ) print(f"Plan added: {result}") ``` ### Remove a Plan from an Agent ```python theme={null} result = payments.agents.remove_plan_from_agent( plan_id="plan-to-remove", agent_id="your-agent-id" ) print(f"Plan removed: {result}") ``` ## Complete Example ```python theme={null} from payments_py import Payments, PaymentOptions from payments_py.common.types import AgentMetadata, AgentAPIAttributes, PlanMetadata from payments_py.plans import ( get_erc20_price_config, get_fixed_credits_config, get_free_price_config ) # Initialize payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) ERC20_TOKEN = "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d" builder_address = payments.account_address # 1. Create a payment plan first plan_result = payments.plans.register_credits_plan( plan_metadata=PlanMetadata(name="AI Agent Plan"), price_config=get_erc20_price_config(20, ERC20_TOKEN, builder_address), credits_config=get_fixed_credits_config(100) ) plan_id = plan_result['planId'] # 2. Register an agent with the plan agent_result = payments.agents.register_agent( agent_metadata=AgentMetadata( name="My First AI Agent", description="A demo AI agent", tags=["demo", "ai"] ), agent_api=AgentAPIAttributes( endpoints=[{"POST": "https://api.example.com/agents/:agentId/tasks"}], agent_definition_url="https://api.example.com/openapi.json" ), payment_plans=[plan_id] ) agent_id = agent_result['agentId'] print(f"Created agent: {agent_id}") # 3. Or create both together combo_result = payments.agents.register_agent_and_plan( agent_metadata=AgentMetadata(name="Combo Agent"), agent_api=AgentAPIAttributes( endpoints=[{"POST": "https://api.example.com/combo"}], agent_definition_url="https://api.example.com/openapi.json" ), plan_metadata=PlanMetadata(name="Combo Plan"), price_config=get_free_price_config(), credits_config=get_fixed_credits_config(10) ) print(f"Combo Agent: {combo_result['agentId']}, Plan: {combo_result['planId']}") # 4. Retrieve agent details agent = payments.agents.get_agent(agent_id) print(f"Agent details: {agent}") # 5. Get associated plans plans = payments.agents.get_agent_plans(agent_id) print(f"Agent plans: {plans}") # 6. Update agent metadata payments.agents.update_agent_metadata( agent_id=agent_id, agent_metadata=AgentMetadata(name="Updated Agent Name"), agent_api=AgentAPIAttributes( endpoints=[{"POST": "https://api.example.com/v2/agents/:agentId/tasks"}], agent_definition_url="https://api.example.com/v2/openapi.json" ) ) ``` ## Next Steps > [card] [Publishing Static Resources](/docs/api-reference/python/resources-module) > > Publish files and datasets > [card] [Querying an Agent](/docs/api-reference/python/requests-module) > > Learn how to access agents # Payments and Balance Source: https://nevermined.ai/docs/api-reference/python/balance-module Order plans and manage credit balances This guide covers how to order payment plans and manage balances using the Nevermined Payments Python SDK. ## Overview As a subscriber, you need to order payment plans to gain access to AI agents and resources. This guide explains: * How to check plan balances * How to order plans (crypto payments) * How to mint and burn credits (for plan owners) ## Check Plan Balance Before ordering or using a plan, check the current balance: ```python theme={null} from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) # Check balance for current user balance = payments.plans.get_plan_balance(plan_id="your-plan-id") print(f"Plan ID: {balance.plan_id}") print(f"Plan Name: {balance.plan_name}") print(f"Plan Type: {balance.plan_type}") print(f"Balance: {balance.balance}") print(f"Is Subscriber: {balance.is_subscriber}") print(f"Price per Credit: {balance.price_per_credit}") ``` ### Check Balance for Another User ```python theme={null} balance = payments.plans.get_plan_balance( plan_id="your-plan-id", account_address="0xOtherUserAddress" ) ``` ### Balance Response Fields | Field | Type | Description | | - | - | - | | `plan_id` | `str` | Plan identifier | | `plan_name` | `str` | Plan display name | | `plan_type` | `str` | "credits" or "time" | | `balance` | `int` | Current credit balance | | `is_subscriber` | `bool` | Whether user has access | | `holder_address` | `str` | Wallet address checked | | `price_per_credit` | `float` | Cost per credit | ## Order Plans ### Order with Crypto Order a plan using cryptocurrency (ERC20 or native tokens): ```python theme={null} # Order a plan (requires sufficient token balance) result = payments.plans.order_plan(plan_id="your-plan-id") print(f"Success: {result['success']}") print(f"Order details: {result}") ``` > [!NOTE] > > For ERC20 token payments, ensure you have approved the Nevermined contract to spend your tokens before ordering. ### Order Fiat Plans For plans priced in fiat (USD), use Stripe checkout: ```python theme={null} # Get Stripe checkout session checkout = payments.plans.order_fiat_plan(plan_id="fiat-plan-id") print(f"Checkout URL: {checkout['checkoutUrl']}") print(f"Session ID: {checkout['sessionId']}") # Redirect user to checkout['checkoutUrl'] to complete payment ``` ## Mint Credits (Plan Owners) Plan owners can mint additional credits for subscribers: ```python theme={null} # Mint credits to a user result = payments.plans.mint_plan_credits( plan_id="your-plan-id", credits_amount=50, credits_receiver="0xSubscriberAddress" ) print(f"Minted: {result}") ``` ### Mint Expirable Credits For time-limited plans, mint credits with an expiration: ```python theme={null} result = payments.plans.mint_plan_expirable( plan_id="your-plan-id", credits_amount=100, credits_receiver="0xSubscriberAddress", credits_duration=86400 # 1 day in seconds ) ``` ## Burn Credits (Plan Owners) Plan owners can burn credits from the plan: ```python theme={null} result = payments.plans.burn_credits( plan_id="your-plan-id", credits_amount="10" ) print(f"Burned: {result}") ``` ## Redeem Credits Agents can redeem credits from subscribers for completed work: ```python theme={null} result = payments.plans.redeem_credits( agent_request_id="request-123", plan_id="plan-id", redeem_from="0xSubscriberAddress", credits_amount_to_redeem="5" ) ``` ## Complete Example ```python theme={null} from payments_py import Payments, PaymentOptions from payments_py.common.types import PlanMetadata from payments_py.plans import get_erc20_price_config, get_fixed_credits_config # Initialize as builder (plan owner) payments_builder = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:builder-key", environment="sandbox") ) # Initialize as subscriber payments_subscriber = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:subscriber-key", environment="sandbox") ) ERC20_TOKEN = "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d" builder_address = payments_builder.account_address # 1. Builder creates a plan plan_result = payments_builder.plans.register_credits_plan( plan_metadata=PlanMetadata(name="Premium Plan"), price_config=get_erc20_price_config(20, ERC20_TOKEN, builder_address), credits_config=get_fixed_credits_config(100) ) plan_id = plan_result['planId'] print(f"Created plan: {plan_id}") # 2. Subscriber checks initial balance (should be 0 or not subscribed) initial_balance = payments_subscriber.plans.get_plan_balance(plan_id) print(f"Initial balance: {initial_balance.balance}") print(f"Is subscriber: {initial_balance.is_subscriber}") # 3. Subscriber orders the plan order_result = payments_subscriber.plans.order_plan(plan_id) print(f"Order success: {order_result['success']}") # 4. Subscriber checks balance after ordering final_balance = payments_subscriber.plans.get_plan_balance(plan_id) print(f"Final balance: {final_balance.balance}") print(f"Is subscriber: {final_balance.is_subscriber}") # 5. Builder can mint additional credits if final_balance.is_subscriber: mint_result = payments_builder.plans.mint_plan_credits( plan_id=plan_id, credits_amount=50, credits_receiver=payments_subscriber.account_address ) print(f"Minted 50 additional credits") # Check updated balance updated_balance = payments_subscriber.plans.get_plan_balance(plan_id) print(f"Updated balance: {updated_balance.balance}") ``` ## Workflow Summary ```mermaid theme={null} flowchart TD subgraph Builder B1[1. Create Plan — register_credits_plan] B2[2. Register Agent with Plan] B3[3. Optionally mint credits to users] B1 --> B2 --> B3 end subgraph Subscriber S1[1. Check Balance — get_plan_balance] S2[2. Order Plan — order_plan] S3[3. Get Access Token — get_x402_access_token] S4[4. Query Agent with access token] S1 --> S2 --> S3 --> S4 end Builder --> Subscriber ``` ## Next Steps > [card] [Querying an Agent](/docs/api-reference/python/requests-module) > > Get access tokens and make requests > [card] [Request Validation](/docs/api-reference/python/validation-module) > > How agents validate requests # Installation Source: https://nevermined.ai/docs/api-reference/python/installation Install and configure the payments-py Python SDK This guide covers how to install the Nevermined Payments Python SDK. ## Overview The Nevermined Payments Python SDK (`payments-py`) is a Python library that provides tools for integrating AI agent monetization and access control into your applications. It supports: * Payment plans (credits-based and time-based) * AI agent registration and management * X402 payment protocol * MCP (Model Context Protocol) integration * A2A (Agent-to-Agent) protocol support ## Prerequisites Before installing the SDK, ensure you have: * **Python 3.10 or higher** - The SDK requires Python 3.10+ * **pip or Poetry** - Package manager for installation * **Nevermined API Key** - Obtain from the [Nevermined App](https://nevermined.app) ## Installation Steps ### Using pip ```bash theme={null} pip install payments-py ``` ### Using Poetry ```bash theme={null} poetry add payments-py ``` ### With Optional Dependencies For FastAPI/x402 middleware support: ```bash theme={null} # Using pip pip install payments-py[fastapi] # Using Poetry poetry add payments-py -E fastapi ``` ## Verify Installation After installation, verify the SDK is working: ```python theme={null} from payments_py import Payments, PaymentOptions # Check version import payments_py print(f"payments-py installed successfully") ``` ## Environment Setup Create a `.env` file or set environment variables: ```bash theme={null} # Required NVM_API_KEY=nvm:your-api-key-here # Optional (for custom environments) NVM_BACKEND_URL=https://api.sandbox.nevermined.app NVM_PROXY_URL=https://proxy.sandbox.nevermined.app ``` ## Next Steps Once installed, proceed to [Initializing the Library](/docs/api-reference/python/payments-class) to configure the SDK. # LangChain Integration Source: https://nevermined.ai/docs/api-reference/python/langchain-module Decorator, helpers, and exceptions for protecting LangChain and LangGraph tools This guide covers the LangChain and LangGraph integration shipped in the `[langchain]` optional extra of `payments-py`. The module `payments_py.x402.langchain` provides the decorator, helpers, and exceptions for monetizing LangChain tools with the x402 protocol. For the conceptual walk-through (two integration approaches, the discovery-first flow, dynamic credits patterns), see the [LangChain integration guide](/docs/integrate/add-to-your-agent/langchain). For a runnable end-to-end demo, see the [`langchain-paid-agent-py`](https://github.com/nevermined-io/tutorials/tree/main/langchain-paid-agent-py) tutorial. > Looking to gate a **LangSmith Deployment** entry point (`/threads/{id}/runs/wait` etc.) rather than individual tools? See [LangSmith Deployment Middleware](/docs/api-reference/python/langsmith-deployment-module). The two integrations are complementary: the decorator covered here protects tools the agent calls; the LangSmith Deployment middleware protects the agent's HTTP entry point. ## Installation ```bash theme={null} pip install payments-py[langchain] langgraph langchain-openai ``` The `[langchain]` extra installs `langchain-core`. `langgraph` and `langchain-openai` are optional — needed only if you build a LangGraph agent. ## Exports | Symbol | Purpose | | - | - | | `requires_payment` | Decorator that gates a `@tool` on an x402 access token | | `PaymentRequiredError` | Exception raised when the token is missing or verification fails | | `last_settlement` | Read the most recent settlement receipt from outside the agent's call stack | | `create_paid_react_agent` | LangGraph ReAct agent builder that lets `PaymentRequiredError` propagate intact | All four are exported from `payments_py.x402.langchain`: ```python theme={null} from payments_py.x402.langchain import ( requires_payment, PaymentRequiredError, last_settlement, create_paid_react_agent, ) ``` ## `requires_payment` Decorator that protects a LangChain `@tool` with x402 payment verification and settlement. Pulls the access token from `RunnableConfig.configurable["payment_token"]`, verifies it, runs the tool body, then settles credits. ### Signature ```python theme={null} def requires_payment( payments: Payments, plan_id: str | None = None, plan_ids: list[str] | None = None, credits: int | Callable[[dict], int] = 1, agent_id: str | None = None, network: str | None = None, scheme: str | None = None, ) -> Callable ``` | Parameter | Description | | - | - | | `payments` | A `Payments` instance with `payments.facilitator` configured. | | `plan_id` / `plan_ids` | The plan(s) the tool charges against. Pass one of the two; `plan_id` is a convenience for the single-plan case. | | `credits` | How many credits to charge. Sent to the facilitator as `max_amount`. See [credits semantics](#credits-semantics) for fixed-vs-range plans. | | `agent_id` | Optional agent identifier propagated to the receipt. | | `network` | Optional CAIP-2 network ID. Auto-resolved from the plan when omitted. | | `scheme` | Optional x402 scheme (`nvm:erc4337` or `nvm:card-delegation`). Auto-resolved when omitted. | ### Decorator order `@tool` **outside**, `@requires_payment` **inside**: ```python theme={null} from langchain_core.runnables import RunnableConfig from langchain_core.tools import tool from payments_py import Payments, PaymentOptions from payments_py.x402.langchain import requires_payment payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:builder-key", environment="sandbox") ) @tool @requires_payment(payments=payments, plan_id="plan-123", credits=1) def get_market_insight(topic: str, config: RunnableConfig = None) -> str: """Return a short market insight. Costs 1 credit per call.""" return f"Market insight for '{topic}': demand is up 12% QoQ." ``` The protected function **must** accept a `config: RunnableConfig` parameter — that is how the decorator reads the payment token at call time. ### Dynamic credits `credits` accepts three forms: * **Static int** — `credits=1` (fixed cost per call). * **Lambda** — `credits=lambda ctx: max(1, len(ctx["result"]) // 100)`. * **Named function** — `credits=my_fn` where `my_fn(ctx) -> int`. When callable, `ctx` is `{"args": , "result": }`. Dynamic credits resolve **after** execution so the result is available. ### Credits semantics The `credits` argument is sent to the facilitator as `max_amount`. The actual amount redeemed depends on the plan's server-side credit configuration: * **Fixed plans** (`plan.credits.minAmount == plan.credits.maxAmount`) always burn `plan.credits.maxAmount`. The decorator's `credits=N` is then effectively a no-op (per [nevermined-io/nvm-monorepo#1568](https://github.com/nevermined-io/nvm-monorepo/issues/1568)). * **Range plans** clamp the supplied value into `[plan.credits.minAmount, plan.credits.maxAmount]`. If you want predictable per-call cost, configure the plan as fixed; the decorator value is then a client-side declaration. ## `PaymentRequiredError` Raised by `@requires_payment` when the token is missing from `config["configurable"]["payment_token"]`, or when the facilitator rejects the token (expired, invalid signature, insufficient balance, etc.). Carries the full `X402PaymentRequired` payload so callers can run the x402 discovery flow. ```python theme={null} from payments_py.x402.langchain import PaymentRequiredError try: agent.invoke({"messages": [("human", "...")]}, config={"configurable": {}}) except PaymentRequiredError as err: accepts = err.payment_required.accepts[0] # accepts.scheme → "nvm:erc4337" or "nvm:card-delegation" # accepts.network → CAIP-2 chain or provider name (stripe, braintree, visa) # accepts.plan_id → which plan to acquire a token against ``` ### Attributes | Attribute | Type | Description | | - | - | - | | `payment_required` | `X402PaymentRequired \| None` | The full x402 v2 payment-required payload. `accepts[0]` carries scheme / network / plan\_id / agent\_id. | For the discovery → acquire → retry flow, see the [LangChain integration guide](/docs/integrate/add-to-your-agent/langchain). ## `last_settlement` Returns the most recent `SettleResponse` produced by `@requires_payment` in this process. Use this after invoking a LangGraph runnable to recover the settlement receipt — `credits_redeemed`, `remaining_balance`, `transaction`, `network`, `payer` — without threading it back through `RunnableConfig.configurable` (which LangGraph copies per node, so the SDK's in-place write is not visible to the outer caller). ### Signature ```python theme={null} def last_settlement() -> SettleResponse | None ``` Returns `None` if no settlement has happened yet in this process, or if the most recent invocation raised before reaching the settle phase. ### Example ```python theme={null} from payments_py.x402.langchain import last_settlement result = agent.invoke( {"messages": [("human", "...")]}, config={"configurable": {"payment_token": token}}, ) receipt = last_settlement() if receipt: print(f" credits_redeemed: {receipt.credits_redeemed}") print(f" remaining_balance: {receipt.remaining_balance}") print(f" transaction: {receipt.transaction}") ``` > [!WARNING] > > `last_settlement()` reads from a module-level slot. In multi-tenant processes (e.g. a server handling concurrent settlements), the value reflects whichever invocation settled most recently — there is no per-call isolation. For multi-tenant scenarios, surface settlement via a callback or observability layer instead. ## `create_paid_react_agent` Thin wrapper over [`langgraph.prebuilt.create_react_agent`](https://langchain-ai.github.io/langgraph/reference/prebuilt/#create_react_agent) that constructs the underlying `ToolNode` with `handle_tool_errors=False`. That single change is what lets `PaymentRequiredError` propagate all the way back to `agent.invoke()`'s caller with its `X402PaymentRequired` payload intact — the default `ToolNode` behaviour stringifies the exception into a `ToolMessage` for the LLM and **loses the payload**. ### Signature ```python theme={null} def create_paid_react_agent( model: Any, tools: Sequence[Any], **kwargs: Any, ) -> CompiledStateGraph ``` | Parameter | Description | | - | - | | `model` | Anything accepted by `create_react_agent`'s `model` argument (a `BaseChatModel`, a string, a runnable, etc.). | | `tools` | Sequence of LangChain tools — typically functions decorated with `@tool` and `@requires_payment`. | | `**kwargs` | Forwarded verbatim to `create_react_agent` (`prompt`, `state_schema`, `checkpointer`, …). Unknown kwargs raise `TypeError` from LangGraph at call time. | `langgraph` is imported lazily so the `[langchain]` extra need not pull it in. Install LangGraph yourself (`pip install langgraph`) to use this helper. ### Example ```python theme={null} from langchain_openai import ChatOpenAI from payments_py.x402.langchain import create_paid_react_agent, requires_payment @tool @requires_payment(payments=payments, plan_id=PLAN_ID, credits=1) def get_market_insight(topic: str, config=None) -> str: return f"Market insight for {topic} ..." agent = create_paid_react_agent( ChatOpenAI(model="gpt-4o-mini", temperature=0), [get_market_insight], prompt="You are a market data assistant. Always call get_market_insight.", ) ``` ## End-to-end usage The canonical x402 flow uses all four symbols together — discovery, acquisition, retry, receipt read: ```python theme={null} import os from dotenv import load_dotenv from payments_py import Payments, PaymentOptions from payments_py.x402.langchain import ( PaymentRequiredError, create_paid_react_agent, last_settlement, requires_payment, ) from payments_py.x402.types import ( CreateDelegationPayload, DelegationConfig, X402TokenOptions, ) load_dotenv() payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment=os.getenv("NVM_ENVIRONMENT", "sandbox"), ) ) # 1. Build the agent (see the LangChain integration guide for the protected tool). agent = create_paid_react_agent(model, [get_market_insight], prompt=prompt) # 2. Discover what the agent's tool charges by invoking without a token. try: agent.invoke({"messages": [("human", QUERY)]}, config={"configurable": {}}) except PaymentRequiredError as err: accept = err.payment_required.accepts[0] # 3. Create a delegation once (currency is required), then acquire a token # against the discovered plan by referencing the delegation id. pm = next(m for m in payments.delegation.list_payment_methods() if m.provider == accept.network) delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider=pm.provider, provider_payment_method_id=pm.id, spending_limit_cents=10000, duration_secs=3600, currency="usd", ) ) token = payments.x402.get_x402_access_token( accept.plan_id, token_options=X402TokenOptions( scheme=accept.scheme, delegation_config=DelegationConfig(delegation_id=delegation.delegation_id), ), )["accessToken"] # 4. Retry with the token and read the settlement. result = agent.invoke( {"messages": [("human", QUERY)]}, config={"configurable": {"payment_token": token}}, ) receipt = last_settlement() ``` For the full, runnable version see [`tutorials/langchain-paid-agent-py`](https://github.com/nevermined-io/tutorials/tree/main/langchain-paid-agent-py). ## Observability with LangSmith When the optional `[langsmith]` extra is installed and a LangSmith run is active in the calling context, `@requires_payment` automatically emits two child spans nested under the active tool span: * **`nvm:verify`** — opens around the verify-permissions call, with attributes describing the scheme, plan, payer, and verify duration. * **`nvm:settlement`** — opens around the settle-permissions call, with attributes describing credits redeemed, remaining balance, transaction hash, network, and settle duration. The same `nvm.*` metadata is also attached to the parent tool span so the trace is searchable from either level. The per-call child spans are always authoritative; the parent copy is best-effort and can be overwritten when two protected tools run in the same node — see [Known limitations](#known-limitations). ### Install ```bash theme={null} pip install "payments-py[langchain,langsmith]" ``` ### Enable ```bash theme={null} export LANGSMITH_TRACING=true export LANGSMITH_API_KEY= export LANGSMITH_PROJECT= # optional ``` No code changes are needed beyond the existing `@requires_payment` decorator — the spans are emitted automatically when LangSmith is active. If `langsmith` is not installed or `LANGSMITH_TRACING` is unset, span emission is a silent no-op. #### Regional endpoint LangSmith hosts accounts across several regions. The SDK defaults to GCP US (`https://api.smith.langchain.com`); accounts in any other region must set `LANGSMITH_ENDPOINT` or the trace POST will fail with `403 Forbidden` on `/runs/multipart`. | Region | Endpoint | | - | - | | GCP US | `https://api.smith.langchain.com` *(default)* | | GCP EU | `https://eu.api.smith.langchain.com` | | GCP APAC | `https://apac.api.smith.langchain.com` | | AWS US | `https://aws.api.smith.langchain.com` | ```bash theme={null} export LANGSMITH_ENDPOINT=https://eu.api.smith.langchain.com ``` The payment flow itself is unaffected by trace-shipping failures — verify, tool execution, and settle proceed normally. Only the LangSmith trace ingestion fails, surfaced as `langsmith.utils.LangSmithError` warnings. ### Span attributes | Span | Attribute | Source | | - | - | - | | `nvm:verify` | `nvm.plan_ids` | configured `plan_id` / `plan_ids` | | `nvm:verify` | `nvm.scheme` | resolved scheme (`nvm:erc4337` or `nvm:card-delegation`) | | `nvm:verify` | `nvm.network` | CAIP-2 chain or provider name | | `nvm:verify` | `nvm.agent_id` | configured `agent_id` | | `nvm:verify` | `nvm.payer` | from `VerifyResponse.payer` | | `nvm:verify` | `nvm.agent_request_id` | from `VerifyResponse.agent_request_id` | | `nvm:verify` | `nvm.payment_token` | first 16 chars + `…` + last 4 chars of the x402 access token | | `nvm:verify` | `nvm.verify.duration_ms` | measured | | `nvm:settlement` | `nvm.credits_redeemed` | from `SettleResponse.credits_redeemed` | | `nvm:settlement` | `nvm.balance.after` | from `SettleResponse.remaining_balance` | | `nvm:settlement` | `nvm.tx_hash` | from `SettleResponse.transaction` | | `nvm:settlement` | `nvm.network` | from `SettleResponse.network` | | `nvm:settlement` | `nvm.payer` | from `SettleResponse.payer` | | `nvm:settlement` | `nvm.payment_token` | first 16 chars + `…` + last 4 chars of the x402 access token | | `nvm:settlement` | `nvm.settle.duration_ms` | measured | ### Sensitive data in traces The `payment_token` that the buyer passes via `config["configurable"]["payment_token"]` is captured by LangChain into the parent tool span's metadata, and would normally be inherited by any child span — including the `nvm:verify` and `nvm:settlement` spans the decorator emits. The full token grants access to the protected tool until it expires, so the decorator **proactively strips `payment_token` from the parent tool span's metadata** before opening any child span. The full credential never reaches a Nevermined span attribute. For correlation across spans the decorator surfaces an abbreviated `nvm.payment_token` attribute (`eyJ4NDAyVmVyc2lv…bsig`, first 16 chars + ellipsis + last 4) on both `nvm:verify` and `nvm:settlement`. That gives you "which token was this?" without exposing the credential itself. A real x402 access token is a JWT, which is far longer than 20 chars. If a token of **20 characters or fewer** is passed — almost always a misconfiguration (a plan id or opaque handle where the JWT was expected) — it is **redacted, not exported**: `nvm.payment_token` shows at most the first 4 chars plus a `…(short)` marker (e.g. `eyJ4…(short)`), and a runtime warning is logged. For a token of 4 chars or fewer, nothing is revealed at all — it collapses to just `…(short)`. The full short value never reaches a span attribute, so a misrouted secret cannot leak into a durable trace store even when it is shorter than the abbreviation threshold. The active redaction covers the documented LangChain-via-configurable path. If you're surfacing the token through a different channel (custom callbacks, an explicit `add_metadata({"payment_token": ...})`, raw inputs to a tool whose signature contains the token), the decorator can't see those — strip them yourself or set `export LANGSMITH_HIDE_INPUTS=true` for blanket coverage. Other `nvm.*` attributes that may be considered sensitive depending on your context: * `nvm.payer` — the payer's wallet address (public on-chain, but a stable identifier). * `nvm.tx_hash` — the settlement transaction id. * `nvm.agent_request_id` — Nevermined-internal correlation id. * `nvm.balance.after` — the payer's remaining credit balance after this settlement. Reveals per-payer depletion patterns to anyone with trace read access on the operator's LangSmith project. Suppress with `LANGSMITH_HIDE_OUTPUTS=true` or post-filter. None of these grant access on their own. ### Known limitations #### Parent metadata is last-writer-wins across tools in one node `@requires_payment` attaches its `nvm.*` metadata to **two** places: the per-call **child** spans (`nvm:verify` / `nvm:settlement`) and, as a convenience for searchability, the **parent** LangSmith run tree. The child spans are isolated per call, so they are always correct. The parent copy is **not** namespaced per tool: the bare `nvm.*` keys (`nvm.tx_hash`, `nvm.credits_redeemed`, `nvm.payment_token`, …) are written directly onto the parent run's metadata. When an agent calls **two `@requires_payment` tools within the same LangGraph `ToolNode`** — the common pattern, since a single ReAct step can dispatch multiple tool calls into one node — both decorators target the **same** parent run tree, and the second `add_metadata` **silently overwrites** the first's `nvm.*` values. The parent therefore reflects only the **last** tool that settled in that node; the earlier tool's parent-level `nvm.*` is lost. What this means in practice: * **Per-call billing fidelity lives on the child spans, not the parent.** For accurate per-tool accounting (which token, which tx hash, how many credits each call redeemed), filter and aggregate on the `nvm:verify` / `nvm:settlement` **child** spans. Each child carries the values for exactly one call. * **Treat parent `nvm.*` as best-effort.** It is convenient for "did this trace touch Nevermined at all?" searches, but do not rely on it for last-writer-sensitive fields when multiple paid tools can run in one node. * This is a **last-writer-wins** behaviour, not a correctness bug in settlement — every call still verifies and settles independently and correctly. Only the parent's *denormalized copy* of the metadata is affected. This matches the cross-SDK **observability spans v1** contract (the SDK-neutral span spec maintained in `nvm-monorepo`, which both `payments-py` and `@nevermined-io/payments` emit against): child spans are authoritative per tool; parent `nvm.*` is best-effort / last-writer-wins. ### Manual use (non-LangChain paths) The same context managers are also exported for code that wants to emit Nevermined-flavored spans without going through `@requires_payment` (e.g. the FastAPI middleware path): ```python theme={null} from payments_py.langsmith import ( settlement_span, verify_span, build_settle_metadata, ) with settlement_span(plan_ids=["plan-1"]) as span: settlement = payments.facilitator.settle_permissions(...) if span is not None: span.add_metadata(build_settle_metadata(settlement, ["plan-1"])) ``` Span emission failures are caught internally — observability is best-effort and will not interfere with the payment flow. ## Related * [LangChain integration guide](/docs/integrate/add-to-your-agent/langchain) — conceptual walk-through, the two integration approaches (decorator vs. HTTP middleware), and the TypeScript variant. * [x402 Protocol](/docs/api-reference/python/x402-module) — token generation, delegation config, scheme resolution. * [`tutorials/langchain-paid-agent-py`](https://github.com/nevermined-io/tutorials/tree/main/langchain-paid-agent-py) — the minimal end-to-end demo. # LangSmith Deployment Middleware Source: https://nevermined.ai/docs/api-reference/python/langsmith-deployment-module Starlette middleware for gating a LangGraph agent deployed to LangSmith Deployment with x402 A Starlette ASGI middleware (`PaymentMiddleware`) that gates a LangGraph agent deployed to **LangSmith Deployment** (formerly LangGraph Platform) with the Nevermined x402 payment flow. Use the `build_payment_app` factory for one-line wiring via the `http.app` field in `langgraph.json`. For tool-time gating inside an agent (`@requires_payment` decorator), see [LangChain Integration](/docs/api-reference/python/langchain-module). The two integrations are complementary — that page is for protecting tools the agent calls; this page is for protecting the agent's HTTP entry point. ## Installation ```bash theme={null} pip install payments-py[langsmith] ``` The `[langsmith]` extra pulls `fastapi`, `starlette`, and `langsmith`. ## Exports ```python theme={null} from payments_py.langsmith import ( PaymentMiddleware, # Starlette BaseHTTPMiddleware subclass RouteConfig, # dataclass for per-route pricing X402_HEADERS, # dict of x402 v2 header names build_payment_app, # FastAPI app factory (recommended) ) ``` ## `build_payment_app` The recommended entry point — returns a `FastAPI` app pre-wired with `PaymentMiddleware`. Mount the returned app in `langgraph.json`'s `http.app` field. ### Signature ```python theme={null} def build_payment_app( payments: Payments, routes: Optional[Dict[str, Union[RouteConfig, dict]]] = None, ) -> FastAPI: ... ``` ### Why FastAPI and not plain Starlette `langgraph-api` versions prior to a known internal OpenAPI fix crash on plain Starlette `http.app` wrappers — `update_openapi_spec` falls through to Starlette's `SchemaGenerator` which YAML-parses internal endpoint docstrings and chokes on them. `app.openapi()` (FastAPI's own generator) takes a clean path. `build_payment_app` returns a FastAPI app so users do not need to know about this upstream bug. The middleware class itself (`PaymentMiddleware`) is a `starlette.middleware.base.BaseHTTPMiddleware` and works on both Starlette and FastAPI — only the outer app wrapper matters. ### Example ```python theme={null} # nvm_app.py import os from payments_py import Payments, PaymentOptions from payments_py.langsmith import build_payment_app, RouteConfig payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), ) ) app = build_payment_app( payments=payments, routes={ "POST /threads/{thread_id}/runs/wait": RouteConfig( plan_id=os.environ["NVM_PLAN_ID"], credits=int(os.environ.get("NVM_CREDITS_PER_INVOKE", "1")), ), }, ) ``` ```json theme={null} // langgraph.json { "graphs": { "my_agent": "./src/agent.py:graph" }, "http": { "app": "./nvm_app.py:app" }, "env": ".env" } ``` `langgraph dev` and `langgraph up` both honor the `http.app` field — the middleware composes around LangSmith Deployment's built-in routes (`/runs`, `/threads/{id}/runs`, `/assistants`, etc.). ## Lifecycle The middleware implements the canonical x402 verify-then-work-then-settle ordering inside one HTTP cycle: ``` Request in ├─ PaymentMiddleware.dispatch: │ ├─ resolve scheme + network from plan metadata (cached) │ ├─ build the x402 PaymentRequired envelope │ ├─ read payment-signature header │ │ └─ missing → 402 + envelope in payment-required header │ ├─ facilitator.verify_permissions(...) │ │ └─ invalid → 402 + envelope in payment-required header │ ├─ stash PaymentContext on request.state │ ├─ await call_next(request) ← agent runs │ ├─ if response is 2xx: │ │ ├─ facilitator.settle_permissions(...) │ │ ├─ on success → attach settlement receipt to payment-response header │ │ └─ on failure → log + return response unchanged at 200 │ └─ else: skip settle (no charge for failed runs) │ Response out ``` Agent exceptions propagate naturally to the ASGI runtime as 5xx — buyers are not charged for failed runs. Settle failures after a successful 2xx response are logged at `ERROR` and do not surface to the client (the buyer already received the value). ## `RouteConfig` Per-route pricing. Routes that don't match an incoming request pass through ungated. ### Fields | Field | Type | Default | Purpose | | - | - | - | - | | `plan_id` | `str` | required | The Nevermined plan ID gating this route | | `credits` | `int` or `Callable[[Request], int \| Awaitable[int]]` | `1` | Static or dynamic credits to charge | | `agent_id` | `str \| None` | `None` | Optional — surfaces in the envelope and on `nvm.*` metadata for per-agent reconciliation | | `network` | `str \| None` | `None` | Override the auto-resolved network | | `scheme` | `str \| None` | `None` | Override the auto-resolved scheme | | `description` | `str \| None` | `None` | Free-text description for the envelope | | `mime_type` | `str \| None` | `None` | Expected response MIME type | ### Route matching Routes are keyed as `"METHOD /path"`. Path parameters can use either Starlette `:param` or FastAPI/LangGraph `{param}` syntax — both match by position against the incoming request path. Examples that all match `POST /threads/abc-123/runs/wait`: ```python theme={null} "POST /threads/{thread_id}/runs/wait" "POST /threads/:thread_id/runs/wait" ``` For LangSmith Deployment specifically, the only path that fits the verify-work-settle lifecycle in one HTTP cycle is `POST /threads/{thread_id}/runs/wait` (or its stateless counterpart `POST /runs/wait`). Background runs (`POST /runs`) return immediately; streaming runs (`POST /runs/stream`) lose streaming due to body buffering (see Limitations). ## `PaymentMiddleware` (direct use) `build_payment_app` is the recommended entry point. If you need a custom Starlette or FastAPI app (e.g. additional middleware, custom routes), use `PaymentMiddleware` directly: ```python theme={null} from fastapi import FastAPI from starlette.middleware import Middleware from payments_py.langsmith import PaymentMiddleware, RouteConfig app = FastAPI( middleware=[ Middleware( PaymentMiddleware, payments=payments, routes={"POST /runs/wait": RouteConfig(plan_id="...", credits=1)}, ), ] ) ``` ## Observability When `LANGSMITH_TRACING=true` is set, the middleware opens a top-level `nvm:x402-request` trace per gated request, with `nvm:verify` and `nvm:settlement` child spans nested under it. Both child spans carry the same `nvm.*` metadata the decorator emits (plan\_ids, scheme, network, payer, credits\_redeemed, balance.after, tx\_hash, payment\_token abbreviated, verify/settle durations) — see the Observability section in [LangChain Integration](/docs/api-reference/python/langchain-module). The same metadata is also attached to the parent trace. The graph's own LangGraph-emitted trace appears as a sibling top-level trace, not a child of `nvm:x402-request` — `langgraph-api` initiates the graph trace at the graph-invocation boundary, independent of our middleware's trace context. Verification failures (missing token, invalid signature, insufficient credits) raise `PaymentRequiredError` inside the `verify_span` so LangSmith marks the parent + child as **failed** via the canonical context-manager exit path. Settle failures after a successful 2xx mark the settle span as failed but leave the parent trace successful (matching the buyer-visible outcome). ## Limitations * **Streaming responses are buffered.** The middleware reads the downstream response body in full before attaching the `payment-response` settlement header. SSE / `/runs/stream` endpoints become blocking-then-bulk. Gate `/runs/wait` only, or accept the trade-off. * **Python only.** LangSmith Deployment's custom-app surface is documented as Python-only by LangChain. TypeScript variant tracked in the LangChain integration epic (TS-3). * **Sync I/O in async dispatch.** The four sync SDK calls (`resolve_scheme`, `resolve_network`, `verify_permissions`, `settle_permissions`) are wrapped in `asyncio.to_thread(...)` so they do not block the event loop. langgraph dev's blocking-call detector treats unwrapped sync HTTP calls as fatal warnings; the wrapping is load-bearing. ## See also * [x402 Protocol](/docs/api-reference/python/x402-module) for envelope and header semantics. * [LangChain Integration](/docs/api-reference/python/langchain-module) for the `@requires_payment` decorator (tool-time gating). * `payments_py.langsmith.spans` for the observability helpers used internally (verify\_span, settlement\_span, attach\_metadata\_safely). # MCP Integration Source: https://nevermined.ai/docs/api-reference/python/mcp-module Build MCP servers with integrated payments This guide explains how to integrate the Nevermined Payments Python SDK with MCP (Model Context Protocol) servers. ## Overview MCP (Model Context Protocol) enables AI applications to interact with external tools, resources, and prompts. The Nevermined SDK provides built-in MCP integration to: * Protect tools, resources, and prompts with paywalls * Handle OAuth 2.1 authentication * Manage credit consumption per operation ## MCP Integration API Access the MCP integration through `payments.mcp`: ```python theme={null} from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) # MCP integration is available as: mcp = payments.mcp ``` ## Simplified API (Recommended) The simplified API handles server setup automatically: ### Register a Tool ```python theme={null} async def hello_handler(args, context=None): """Handle the hello tool request.""" name = args.get("name", "World") return { "content": [{"type": "text", "text": f"Hello, {name}!"}] } # Register the tool payments.mcp.register_tool( name="hello_world", config={ "description": "Says hello to someone", "inputSchema": { "type": "object", "properties": { "name": {"type": "string", "description": "Name to greet"} } } }, handler=hello_handler, options={"credits": 1} # Cost: 1 credit per call ) ``` ### Register a Resource ```python theme={null} async def config_handler(uri, variables, context=None): """Handle the configuration resource request.""" return { "contents": [{ "uri": str(uri), "mimeType": "application/json", "text": '{"version": "1.0.0", "feature_flags": {"beta": true}}' }] } payments.mcp.register_resource( uri="data://config", config={ "name": "Configuration", "description": "Application configuration", "mimeType": "application/json" }, handler=config_handler, options={"credits": 2} # Cost: 2 credits per access ) ``` ### Register a Prompt ```python theme={null} async def greeting_handler(args, context=None): """Handle the greeting prompt request.""" style = args.get("style", "formal") return { "messages": [{ "role": "user", "content": { "type": "text", "text": f"Please greet me in a {style} way." } }] } payments.mcp.register_prompt( name="greeting", config={ "name": "Greeting", "description": "Generates a greeting" }, handler=greeting_handler, options={"credits": 1} ) ``` ### Start the Server ```python theme={null} import asyncio async def main(): # Register handlers first payments.mcp.register_tool("hello", {...}, hello_handler) # Start the MCP server result = await payments.mcp.start({ "port": 5001, "planId": "your-plan-id", # required "serverName": "my-mcp-server", # "agentId": "your-agent-id", # optional (informational only) "version": "1.0.0", "description": "My MCP server with Nevermined payments" }) print(f"Server running at: {result['info']['baseUrl']}") print(f"Tools: {result['info']['tools']}") # Server runs until stopped # To stop: await payments.mcp.stop() asyncio.run(main()) ``` ## Advanced API For more control, use the advanced API: ### Configure and Protect Handlers ```python theme={null} # Configure shared options (planId required; agentId optional/informational) payments.mcp.configure({ "planId": "your-plan-id", "serverName": "my-mcp-server" }) # Wrap a handler with paywall async def my_handler(args): return {"result": "processed"} protected_handler = payments.mcp.with_paywall( handler=my_handler, options={ "kind": "tool", "name": "my_tool", "credits": 1 } ) ``` ### Attach to Existing Server ```python theme={null} from mcp.server import MCPServer # Create your own MCP server server = MCPServer() # Attach payments integration registrar = payments.mcp.attach(server) # Register protected handlers registrar.register_tool( name="hello", config={"description": "Hello tool"}, handler=hello_handler, options={"credits": 1} ) registrar.register_resource( name="config", template="data://{path}", config={"name": "Config"}, handler=config_handler, options={"credits": 2} ) ``` ## Complete Example ```python theme={null} import asyncio from payments_py import Payments, PaymentOptions # Initialize payments payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) # Define handlers async def analyze_code(args, context=None): """Analyze code for issues.""" code = args.get("code", "") language = args.get("language", "python") # Your analysis logic here issues = analyze(code, language) return { "content": [{ "type": "text", "text": f"Found {len(issues)} issues in {language} code." }] } async def get_docs(uri, variables, context=None): """Return documentation.""" topic = variables.get("topic", "general") return { "contents": [{ "uri": str(uri), "mimeType": "text/markdown", "text": f"# Documentation for {topic}\n\nContent here..." }] } async def code_review_prompt(args, context=None): """Generate code review prompt.""" return { "messages": [{ "role": "user", "content": { "type": "text", "text": "Please review the following code for best practices..." } }] } # Register handlers payments.mcp.register_tool( "analyze_code", { "description": "Analyzes code for potential issues", "inputSchema": { "type": "object", "properties": { "code": {"type": "string"}, "language": {"type": "string", "default": "python"} }, "required": ["code"] } }, analyze_code, {"credits": 5} # 5 credits per analysis ) payments.mcp.register_resource( "docs://{topic}", { "name": "Documentation", "description": "Technical documentation", "mimeType": "text/markdown" }, get_docs, {"credits": 1} ) payments.mcp.register_prompt( "code_review", { "name": "Code Review", "description": "Generates a code review prompt" }, code_review_prompt, {"credits": 2} ) # Start server async def main(): result = await payments.mcp.start({ "port": 5001, "planId": "plan-123", "serverName": "code-assistant-mcp", "version": "1.0.0" }) print(f"MCP Server running at {result['info']['baseUrl']}") print(f"Tools: {result['info']['tools']}") print(f"Resources: {result['info']['resources']}") print(f"Prompts: {result['info']['prompts']}") # Keep running try: while True: await asyncio.sleep(1) except KeyboardInterrupt: await payments.mcp.stop() asyncio.run(main()) ``` ## Server Configuration | Option | Type | Required | Description | | - | - | - | - | | `port` | `int` | Yes | Server port | | `planId` | `str` | Yes | Nevermined plan ID the server charges against | | `serverName` | `str` | Yes | Human-readable name | | `agentId` | `str` | No | Nevermined agent DID (informational; the facilitator resolves access from the plan + token) | | `baseUrl` | `str` | No | Base URL (default: localhost) | | `version` | `str` | No | Server version | | `description` | `str` | No | Server description | ## Handler Options | Option | Type | Description | | - | - | - | | `credits` | `int` or `callable` | Credits to consume per call | | `planId` | `str` | Per-handler plan ID override. A server-level `planId` (set via `configure`/`start`) is required; set this only to charge a different plan for this handler. | | `maxAmount` | `int` | Max credits to verify during authentication (default: `1`) | | `onRedeemError` | `str` | On post-execution settlement failure: `"ignore"` (default) returns the in-band payment error; `"propagate"` raises a JSON-RPC error. Tool content is always suppressed either way (a paid result is never delivered without settlement). | ## In-band x402 signaling (`_meta`) The MCP transport follows the [x402 v2 MCP transport specification](https://github.com/coinbase/x402/blob/main/specs/transports-v2/mcp.md): payments are signalled **in band** through the MCP tool-call machinery, not via HTTP status codes or headers. **Request — payment payload.** The client sends the x402 `PaymentPayload` as plain JSON in the tool-call request params under `_meta["x402/payment"]`. This is the **payment** channel — separate from session auth: the MCP session is an OAuth-protected resource, so the client must also send an `Authorization: Bearer ` header when opening the transport to establish the session (`initialize` returns `401` without it). ```json theme={null} { "method": "tools/call", "params": { "name": "premium_tool", "arguments": { "...": "..." }, "_meta": { "x402/payment": { "x402Version": 2, "accepted": { "...": "..." }, "payload": { "...": "..." } } } } } ``` For backward compatibility the server still falls back to reading the access token from the `Authorization: Bearer` header when `_meta["x402/payment"]` is absent, but that path is deprecated under the x402 v2 MCP transport. **Response — settlement receipt.** On a successful paid call the SDK injects the settlement receipt under the spec key `_meta["x402/payment-response"]`, alongside Nevermined-specific observability under the namespaced `_meta["nevermined/credits"]` key (not part of the x402 spec): ```python theme={null} { "content": [{"type": "text", "text": "result"}], "_meta": { "x402/payment-response": { "success": True, "transaction": "0xabc...", "network": "eip155:84532", "payer": "0x123..." }, "nevermined/credits": { "success": True, "txHash": "0xabc...", "creditsRedeemed": "5", "planId": "plan-123", "subscriberAddress": "0x123..." } } } ``` **Payment required.** When the caller has not paid (or cannot be authorized), the tool returns an **error tool result** carrying the `PaymentRequired` object in both `structuredContent` (the object) and `content[0].text` (its JSON-stringified copy): ```python theme={null} { "isError": True, "structuredContent": { "x402Version": 2, "error": "payment required", "resource": { "url": "mcp://my-server/tools/premium_tool", "...": "..." }, "accepts": [ { "scheme": "nvm:erc4337", "planId": "plan-123", "...": "..." } ] }, "content": [{"type": "text", "text": "{\"x402Version\": 2, ...}"}] } ``` **Settlement failure after execution.** If settlement fails *after* the tool has already executed, the server returns the same payment-required error result and **suppresses the tool's content** — a paid result is never delivered without payment landing. > **Note on `onRedeemError`.** Under the in-band MCP transport, content is *always* suppressed when post-execution settlement fails — even with the default `onRedeemError: "ignore"` — because the x402 v2 spec forbids delivering a paid result without settlement. `onRedeemError` no longer controls whether content is returned; it now only affects the *kind* of error surfaced: `"ignore"` yields the in-band payment-required error result, while `"propagate"` raises a JSON-RPC misconfiguration error instead. | `nevermined/credits` field | Type | Description | | - | - | - | | `success` | `bool` | Whether credit redemption succeeded | | `txHash` | `str` or `None` | Blockchain transaction hash (only on success) | | `creditsRedeemed` | `str` | Number of credits burned (`"0"` on failure) | | `planId` | `str` | Plan used for the operation | | `subscriberAddress` | `str` | Subscriber's wallet address | | `errorReason` | `str` | Error message (only on failure) | ## Endpoints The MCP server exposes: * `/.well-known/oauth-authorization-server` - OAuth 2.1 discovery * `/.well-known/oauth-protected-resource` - Resource metadata * `/.well-known/oauth-protected-resource/mcp` - MCP-specific protected resource metadata * `/register` - Client registration * `/mcp` - MCP protocol endpoint (POST/GET/DELETE) * `/health` - Health check ## OAuth `401` vs. payment-required OAuth and x402 payment-required live at **different layers**, so they never collide: | Layer | Signal | Meaning | | - | - | - | | HTTP transport | `401 Unauthorized` + `WWW-Authenticate: Bearer` (OAuth 2.1) | The request is not authenticated; follow OAuth discovery to obtain a token. | | MCP tool call | tool result with `isError: true` + `PaymentRequired` in `structuredContent` | The caller is authenticated but has not paid for this tool. | Because payment-required is signalled **in band** as a tool result (not as an HTTP `402`), there is no clash with the OAuth `401` challenge and no need to special-case the `/mcp` status code. The `/mcp` endpoint keeps the standard OAuth `401` behavior; payment is negotiated entirely through the tool-call `_meta` / tool-result mechanism described above. x402 discovery is therefore **implicit on the first tool call**: a client that has not paid receives the `PaymentRequired` object (with its `accepts` array) in the error tool result and pays on the next call. There is no `/.well-known/x402-payment` endpoint. ## Next Steps > [card] [A2A Integration](/docs/api-reference/python/a2a-module) > > Agent-to-Agent protocol > [card] [x402 Protocol](/docs/api-reference/python/x402-module) > > Payment protocol details # Initializing the Library Source: https://nevermined.ai/docs/api-reference/python/payments-class Initialize and configure the Payments class for Python This guide explains how to import, configure, and initialize the Nevermined Payments Python SDK. ## Get the NVM API Key Before using the SDK, you need a Nevermined API Key: 1. Go to the [Nevermined App](https://nevermined.app) 2. Sign in or create an account 3. Navigate to **Settings** > **API Keys** 4. Generate a new API key 5. Copy the key (format: `nvm:xxxxxxxx...`) > [!WARNING] > > Never commit your API key to version control. Use environment variables or a secrets manager. ## Import and Initialize ### Basic Initialization ```python theme={null} from payments_py import Payments, PaymentOptions # Initialize with API key and environment payments = Payments.get_instance( PaymentOptions( nvm_api_key="nvm:your-api-key-here", environment="sandbox" ) ) # Verify initialization print(f"Connected to: {payments.environment.backend}") print(f"Account: {payments.account_address}") ``` ### Using Environment Variables ```python theme={null} import os from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.getenv("NVM_API_KEY"), environment=os.getenv("NVM_ENVIRONMENT", "sandbox") ) ) ``` ## Configuration Options The `PaymentOptions` class accepts the following parameters: | Parameter | Type | Required | Description | | - | - | - | - | | `nvm_api_key` | `str` | Yes | Your Nevermined API key | | `environment` | `str` | Yes | Environment name (see below) | | `app_id` | `str` | No | Application identifier | | `version` | `str` | No | Application version | | `api_version` | `str` | No | Backend API version sent as the `Nevermined-Version` header. Defaults to the version this SDK release targets (see below) | | `headers` | `dict` | No | Additional HTTP headers | | `return_url` | `str` | No | Return URL (browser mode only) | ```python theme={null} from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions( nvm_api_key="nvm:your-api-key", environment="sandbox", app_id="my-app", version="1.0.0", headers={"X-Custom-Header": "value"} ) ) ``` ### API Version Pinning Every request the SDK sends to the Nevermined backend carries a `Nevermined-Version` header declaring which backend API version (`MAJOR.MINOR`) the SDK was built and tested against. You normally don't need to touch this — the SDK pins the right version for you. To target a different backend contract explicitly: ```python theme={null} payments = Payments.get_instance( PaymentOptions( nvm_api_key="nvm:your-api-key", environment="sandbox", api_version="1.1", # override the pinned backend API version ) ) ``` See the [API versioning guide](/docs/development-guide/api-versioning) for the resolution rules, and the [API changelog](/docs/development-guide/api-changelog) for what changed in each version. ## Environments ### Sandbox Environment (Testing) Use `sandbox` for development and testing: ```python theme={null} payments = Payments.get_instance( PaymentOptions( nvm_api_key="nvm:your-api-key", environment="sandbox" ) ) ``` * Backend: `https://api.sandbox.nevermined.app` * Proxy: `https://proxy.sandbox.nevermined.app` * Uses test tokens and test networks ### Live Environment (Production) Use `live` for production: ```python theme={null} payments = Payments.get_instance( PaymentOptions( nvm_api_key="nvm:your-api-key", environment="live" ) ) ``` * Backend: `https://api.live.nevermined.app` * Proxy: `https://proxy.live.nevermined.app` * Uses real tokens and mainnet networks ### Custom Environment For self-hosted or development setups: ```python theme={null} import os # Set environment variables first os.environ["NVM_BACKEND_URL"] = "http://localhost:3001" os.environ["NVM_PROXY_URL"] = "http://localhost:443" payments = Payments.get_instance( PaymentOptions( nvm_api_key="nvm:your-api-key", environment="custom" ) ) ``` ### Available Environments | Environment | Description | | - | - | | `sandbox` | Production sandbox (testing) | | `live` | Production mainnet | | `custom` | Custom URLs via environment variables | ## Accessing Sub-APIs The initialized `Payments` object provides access to specialized APIs: ```python theme={null} # Plans API - manage payment plans payments.plans.register_credits_plan(...) payments.plans.get_plan(plan_id) payments.plans.get_plan_balance(plan_id) # Agents API - manage AI agents payments.agents.register_agent(...) payments.agents.get_agent(agent_id) # Facilitator API - x402 verification/settlement payments.facilitator.verify_permissions(...) payments.facilitator.settle_permissions(...) # X402 Token API - generate access tokens payments.x402.get_x402_access_token(plan_id, agent_id) # MCP Integration payments.mcp.register_tool(...) await payments.mcp.start(config) # A2A Integration payments.a2a["start"](agent_card=card, executor=executor) ``` ## Error Handling The SDK raises `PaymentsError` for API errors: ```python theme={null} from payments_py.common.payments_error import PaymentsError try: result = payments.plans.get_plan("invalid-id") except PaymentsError as e: print(f"Error: {e.message}") print(f"Code: {e.code}") ``` ## Next Steps Now that you have initialized the SDK, proceed to: * [Payment Plans](/docs/api-reference/python/plans-module) - Create payment plans * [Agents](/docs/api-reference/python/agents-module) - Register AI agents # Payment Plans Source: https://nevermined.ai/docs/api-reference/python/plans-module Create and manage payment plans with the Python SDK This guide covers how to create and manage payment plans using the Nevermined Payments Python SDK. ## Overview Payment Plans define how users pay to access your AI agents and services. Nevermined supports two types of plans: * **Credits Plans**: Users purchase a fixed number of credits that are consumed with each request * **Time Plans**: Users purchase access for a specific duration (e.g., 1 day, 1 month) ## Plans API Access the Plans API through `payments.plans`: ```python theme={null} from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) # Access plans API plans_api = payments.plans ``` ## Types of Payment Plans ### Credits Plans Credits plans grant users a fixed number of credits. Each agent request consumes credits according to the plan configuration. ```python theme={null} from payments_py.common.types import PlanMetadata from payments_py.plans import get_erc20_price_config, get_fixed_credits_config # Plan metadata plan_metadata = PlanMetadata( name="Basic Plan", description="100 credits for AI agent access" ) # Price: 20 tokens (ERC20) price_config = get_erc20_price_config( amount=20, token_address="0xYourERC20TokenAddress", receiver="0xYourWalletAddress" ) # Credits: 100 credits, 1 credit per request credits_config = get_fixed_credits_config( credits_granted=100, credits_per_request=1 ) # Register the plan result = payments.plans.register_credits_plan( plan_metadata=plan_metadata, price_config=price_config, credits_config=credits_config ) print(f"Plan ID: {result['planId']}") ``` ### Time Plans Time plans grant users unlimited access for a specific duration: ```python theme={null} from payments_py.plans import get_expirable_duration_config, ONE_DAY_DURATION # Price configuration price_config = get_erc20_price_config( amount=50, token_address="0xYourERC20TokenAddress", receiver="0xYourWalletAddress" ) # Duration: 1 day credits_config = get_expirable_duration_config(ONE_DAY_DURATION) result = payments.plans.register_time_plan( plan_metadata=PlanMetadata(name="Daily Plan"), price_config=price_config, credits_config=credits_config ) ``` ### Trial Plans Trial plans can only be purchased once per user. Perfect for free trials: ```python theme={null} from payments_py.plans import get_free_price_config # Free trial with 10 credits price_config = get_free_price_config() credits_config = get_fixed_credits_config(credits_granted=10) result = payments.plans.register_credits_trial_plan( plan_metadata=PlanMetadata(name="Free Trial", description="10 free credits"), price_config=price_config, credits_config=credits_config ) ``` ```python theme={null} # Free trial with 1 day access credits_config = get_expirable_duration_config(ONE_DAY_DURATION) result = payments.plans.register_time_trial_plan( plan_metadata=PlanMetadata(name="1-Day Trial"), price_config=get_free_price_config(), credits_config=credits_config ) ``` ## Price Configuration ### ERC20 Token Price ```python theme={null} from payments_py.plans import get_erc20_price_config price_config = get_erc20_price_config( amount=100, # Amount in token units token_address="0xTokenAddress", # ERC20 token contract receiver="0xBuilderAddress" # Payment receiver ) ``` ### Native Token Price (ETH) ```python theme={null} from payments_py.plans import get_native_token_price_config price_config = get_native_token_price_config( amount=1000000000000000, # Amount in wei (0.001 ETH) receiver="0xBuilderAddress" ) ``` ### Fiat Price (USD) ```python theme={null} from payments_py.plans import get_fiat_price_config price_config = get_fiat_price_config( amount=9_990_000, # $9.99 (6-decimal units, not cents) receiver="0xBuilderAddress" ) ``` ### Fiat Price (EUR) ```python theme={null} from payments_py.plans import get_fiat_price_config from payments_py.common.types import Currency price_config = get_fiat_price_config( amount=29_000_000, # €29.00 (6-decimal units, not cents) receiver="0xBuilderAddress", currency=Currency.EUR ) ``` > Fiat amounts are in **6-decimal units** (the USDC convention used across the Nevermined protocol), **not** cents — `10_000_000` = $10.00. The server-side minimum is **$1.00\*\* (`1_000_000`); smaller amounts are rejected with `BCK.PROTOCOL.0047`. ### EURC Token Price (Euro Stablecoin) ```python theme={null} from payments_py.plans import get_eurc_price_config # EURC pricing (Euro stablecoin on Base, 6 decimals) price_config = get_eurc_price_config( amount=29_000_000, # €29.00 in smallest unit (6 decimals) receiver="0xBuilderAddress" ) # Or use a custom EURC address (e.g., testnet) from payments_py.common.types import EURC_TOKEN_ADDRESS_TESTNET testnet_config = get_eurc_price_config( amount=29_000_000, receiver="0xBuilderAddress", eurc_address=EURC_TOKEN_ADDRESS_TESTNET ) ``` ### Free Price ```python theme={null} from payments_py.plans import get_free_price_config price_config = get_free_price_config() ``` ## Credits Configuration ### Fixed Credits Each request consumes a fixed number of credits: ```python theme={null} from payments_py.plans import get_fixed_credits_config credits_config = get_fixed_credits_config( credits_granted=100, # Total credits granted credits_per_request=1 # Credits consumed per request ) ``` ### Dynamic Credits Each request can consume a variable number of credits: ```python theme={null} from payments_py.plans import get_dynamic_credits_config credits_config = get_dynamic_credits_config( credits_granted=100, min_credits_per_request=1, # Minimum credits per request max_credits_per_request=10 # Maximum credits per request ) ``` ### Duration-Based (Time Plans) ```python theme={null} from payments_py.plans import ( get_expirable_duration_config, get_non_expirable_duration_config, ONE_DAY_DURATION, ONE_WEEK_DURATION, ONE_MONTH_DURATION, ONE_YEAR_DURATION ) # Expirable (time-limited) credits_config = get_expirable_duration_config(ONE_MONTH_DURATION) # Non-expirable (permanent access) credits_config = get_non_expirable_duration_config() ``` ## Retrieve Plans ### List Your Plans List the plans **you** published. This is caller-scoped account management — it returns only the plans the authenticated account created, never other users' plans (Nevermined is not a marketplace, so there is no global plan search). Useful for finding and managing your own plans (e.g. spotting duplicates). ```python theme={null} from payments_py.common.types import PaginationOptions # Your own plans result = payments.plans.get_user_plans( pagination=PaginationOptions(page=1, offset=10) ) print(f"Total: {result['total']}") for plan in result["plans"]: print(plan["id"]) # Every plan in an organization you belong to org_plans = payments.plans.get_user_plans(org_id="org-acme") ``` ### Get a Single Plan ```python theme={null} plan = payments.plans.get_plan(plan_id="123456") print(f"Plan name: {plan['name']}") print(f"Plan type: {plan['planType']}") ``` ### Get Plan Balance Check the balance for a specific account: ```python theme={null} balance = payments.plans.get_plan_balance( plan_id="123456", account_address="0xUserAddress" # Optional, defaults to current user ) print(f"Balance: {balance.balance} credits") print(f"Is subscriber: {balance.is_subscriber}") ``` ### Get Agents Associated to a Plan ```python theme={null} from payments_py.common.types import PaginationOptions agents = payments.plans.get_agents_associated_to_plan( plan_id="123456", pagination=PaginationOptions(page=1, offset=10) ) print(f"Agents: {agents}") ``` ## Complete Example ```python theme={null} from payments_py import Payments, PaymentOptions from payments_py.common.types import PlanMetadata from payments_py.plans import ( get_erc20_price_config, get_fixed_credits_config, get_expirable_duration_config, get_free_price_config, ONE_DAY_DURATION ) # Initialize payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) builder_address = payments.account_address # ERC20 token address (use a test token in sandbox) ERC20_TOKEN = "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d" # 1. Create a credits plan credits_plan = payments.plans.register_credits_plan( plan_metadata=PlanMetadata(name="Basic Credits Plan"), price_config=get_erc20_price_config(20, ERC20_TOKEN, builder_address), credits_config=get_fixed_credits_config(100) ) print(f"Credits Plan: {credits_plan['planId']}") # 2. Create a time plan time_plan = payments.plans.register_time_plan( plan_metadata=PlanMetadata(name="Monthly Plan"), price_config=get_erc20_price_config(50, ERC20_TOKEN, builder_address), credits_config=get_expirable_duration_config(ONE_DAY_DURATION) ) print(f"Time Plan: {time_plan['planId']}") # 3. Create a free trial trial_plan = payments.plans.register_credits_trial_plan( plan_metadata=PlanMetadata(name="Free Trial"), price_config=get_free_price_config(), credits_config=get_fixed_credits_config(10) ) print(f"Trial Plan: {trial_plan['planId']}") # 4. Retrieve plan details plan_details = payments.plans.get_plan(credits_plan['planId']) print(f"Plan details: {plan_details}") ``` ## Next Steps > [card] [Agents](/docs/api-reference/python/agents-module) > > Register AI agents and associate them with plans > [card] [Payments and Balance](/docs/api-reference/python/balance-module) > > Order plans and manage balances # Querying an Agent Source: https://nevermined.ai/docs/api-reference/python/requests-module Query agents and process requests with the Python SDK This guide explains how to get x402 access tokens and make authenticated requests to AI agents. ## Overview To query an AI agent, subscribers need to: 1. Have an active subscription to a plan associated with the agent 2. Generate an x402 access token 3. Include the token in requests to the agent ## Get X402 Access Token The x402 access token authorizes requests to agents and enables credit verification/settlement. ```python theme={null} from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:subscriber-key", environment="sandbox") ) # Generate access token (basic — no delegation config needed for credit/fiat plans) result = payments.x402.get_x402_access_token( plan_id="your-plan-id", agent_id="agent-id" # Optional but recommended ) access_token = result['accessToken'] print(f"Access Token: {access_token[:50]}...") ``` ### Token Generation Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `plan_id` | `str` | Yes | The payment plan ID | | `agent_id` | `str` | No | Target agent ID (recommended) | | `token_options` | `X402TokenOptions` | No | Scheme and delegation configuration | ### Token Generation with Delegation For erc4337 (crypto) plans, token generation uses delegations. The supported flow is **create-first**: create the delegation once, then reference it by `delegation_id` on every token request. Delegations are plan-agnostic by default, so a single delegation can back token requests across many plans. ```python theme={null} from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload # Step 1 — create the delegation once. `currency` is required. delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="erc4337", spending_limit_cents=10000, # $100 duration_secs=604800, # 1 week currency="usdc", ) ) # Step 2 — request a token referencing the delegation id (reusable across plans). result = payments.x402.get_x402_access_token( plan_id="your-plan-id", agent_id="agent-id", token_options=X402TokenOptions( delegation_config=DelegationConfig( delegation_id=delegation.delegation_id ) ) ) ``` > **Deprecated:** passing `spending_limit_cents` / `duration_secs` (or a payment > method) directly to `get_x402_access_token` — inline "create-on-the-fly" — > still works but emits a `DeprecationWarning` and will be removed in a future > release. Create the delegation first as shown above. ## Make Requests to Agents ### Using the x402 Payment Header Include the access token in the `payment-signature` header (per [x402 v2 HTTP transport spec](https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md)): ```python theme={null} import requests # Get access token token_result = payments.x402.get_x402_access_token( plan_id=plan_id, agent_id=agent_id ) access_token = token_result['accessToken'] # Make request to the agent response = requests.post( f"https://agent-api.example.com/agents/{agent_id}/tasks", headers={ "payment-signature": access_token, "Content-Type": "application/json" }, json={ "task": "Analyze this data", "data": {"key": "value"} } ) if response.status_code == 200: result = response.json() print(f"Agent response: {result}") elif response.status_code == 402: print("Payment required - check plan balance") else: print(f"Error: {response.status_code}") ``` ## Decode Access Token You can decode the token to inspect its contents: ```python theme={null} from payments_py.x402.token import decode_access_token decoded = decode_access_token(access_token) if decoded: payload = decoded.get('payload', {}) authorization = payload.get('authorization', {}) print(f"Subscriber: {authorization.get('from')}") print(f"Plan ID: {authorization.get('planId')}") print(f"Agent ID: {authorization.get('agentId')}") ``` ## Complete Example ```python theme={null} from payments_py import Payments, PaymentOptions from payments_py.common.types import PlanMetadata, AgentMetadata, AgentAPIAttributes from payments_py.plans import get_free_price_config, get_fixed_credits_config import requests # Initialize as builder builder = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:builder-key", environment="sandbox") ) # Initialize as subscriber subscriber = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:subscriber-key", environment="sandbox") ) # 1. Builder creates plan and agent plan_result = builder.plans.register_credits_plan( plan_metadata=PlanMetadata(name="API Access Plan"), price_config=get_free_price_config(), # Free for demo credits_config=get_fixed_credits_config(100) ) plan_id = plan_result['planId'] agent_result = builder.agents.register_agent( agent_metadata=AgentMetadata(name="Demo Agent"), # AgentAPIAttributes() with no args registers a minimal agent — your # Payments library middleware handles per-route gating. See # docs/api/04-agents.md for opt-in Additional Security. agent_api=AgentAPIAttributes(), payment_plans=[plan_id] ) agent_id = agent_result['agentId'] # 2. Subscriber orders the plan subscriber.plans.order_plan(plan_id) # 3. Subscriber generates access token token_result = subscriber.x402.get_x402_access_token( plan_id=plan_id, agent_id=agent_id ) access_token = token_result['accessToken'] # 4. Subscriber makes request to agent response = requests.post( "https://api.example.com/tasks", headers={ "payment-signature": access_token, "Content-Type": "application/json" }, json={"prompt": "Hello, agent!"} ) print(f"Status: {response.status_code}") print(f"Response: {response.json()}") # 5. Check updated balance balance = subscriber.plans.get_plan_balance(plan_id) print(f"Remaining credits: {balance.balance}") ``` ## Error Handling ### 402 Payment Required ```python theme={null} response = requests.post(agent_endpoint, headers=headers, json=payload) if response.status_code == 402: error = response.json() print(f"Payment required: {error}") # Check balance balance = payments.plans.get_plan_balance(plan_id) if balance.balance <= 0: print("No credits remaining - order more credits") elif not balance.is_subscriber: print("Not subscribed - order the plan first") ``` ### Token Expired or Invalid ```python theme={null} try: response = requests.post(agent_endpoint, headers=headers, json=payload) response.raise_for_status() except requests.HTTPError as e: if e.response.status_code == 401: print("Token expired or invalid - generate a new token") # Regenerate token new_token = payments.x402.get_x402_access_token(plan_id, agent_id, token_options=token_options) ``` ## Request Flow Diagram ```mermaid theme={null} sequenceDiagram participant Subscriber participant Nevermined participant Agent Subscriber->>Nevermined: get_x402_access_token() Nevermined-->>Subscriber: accessToken Subscriber->>Agent: POST /tasks
payment-signature: token Agent->>Nevermined: verify_permissions() Nevermined-->>Agent: {isValid: true} Agent->>Nevermined: settle_permissions() Nevermined-->>Agent: {success: true} Agent-->>Subscriber: Response ``` ## Next Steps > [card] [Request Validation](/docs/api-reference/python/validation-module) > > How agents validate incoming requests > [card] [x402 Protocol](/docs/api-reference/python/x402-module) > > Deep dive into x402 verification and settlement # Publishing Static Resources Source: https://nevermined.ai/docs/api-reference/python/resources-module Publish and manage static resources with access control This guide explains how to publish static resources (files, datasets) using the Nevermined Payments Python SDK. ## Overview Static resources are files or datasets that users can access through payment plans. Unlike AI agents that process requests, static resources are downloadable content such as: * Documents (PDFs, reports) * Datasets (CSV, JSON files) * Media files (images, videos) * Software packages ## Register Static Resource Agents Static resources are registered as a special type of agent with file endpoints: ```python theme={null} from payments_py.common.types import AgentMetadata, AgentAPIAttributes # Resource metadata resource_metadata = AgentMetadata( name="Premium Dataset Collection", description="A curated collection of ML training datasets", tags=["dataset", "machine-learning", "premium"] ) # Static file endpoints resource_api = AgentAPIAttributes( endpoints=[ {"GET": "https://storage.example.com/datasets/training-data.csv"}, {"GET": "https://storage.example.com/datasets/validation-data.csv"}, {"GET": "https://storage.example.com/datasets/test-data.csv"} ], agent_definition_url="https://storage.example.com/datasets/manifest.json" ) # Register with a payment plan result = payments.agents.register_agent( agent_metadata=resource_metadata, agent_api=resource_api, payment_plans=[plan_id] ) print(f"Resource ID: {result['agentId']}") ``` ## Using Wildcards for Multiple Files When you have multiple files that follow a pattern, you can use wildcard URLs: ```python theme={null} # Single wildcard for dynamic file names resource_api = AgentAPIAttributes( endpoints=[ # Matches: /files/report-001.pdf, /files/report-2024.pdf, etc. {"GET": "https://storage.example.com/files/report-*.pdf"}, # Matches: /data/dataset_v1.csv, /data/dataset_v2.csv, etc. {"GET": "https://storage.example.com/data/dataset_*.csv"} ], agent_definition_url="https://storage.example.com/manifest.json" ) ``` ### Wildcard Patterns | Pattern | Matches | | - | - | | `*.pdf` | Any PDF file | | `report-*.pdf` | report-001.pdf, report-2024.pdf | | `data/*.csv` | All CSV files in data folder | | `v*/data.json` | v1/data.json, v2/data.json | ## Complete Example: Dataset Publishing ```python theme={null} from payments_py import Payments, PaymentOptions from payments_py.common.types import AgentMetadata, AgentAPIAttributes, PlanMetadata from payments_py.plans import get_erc20_price_config, get_fixed_credits_config # Initialize payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) ERC20_TOKEN = "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d" builder_address = payments.account_address # 1. Create a plan for the dataset plan_result = payments.plans.register_credits_plan( plan_metadata=PlanMetadata( name="Dataset Access Plan", description="Access to premium ML datasets" ), price_config=get_erc20_price_config(100, ERC20_TOKEN, builder_address), credits_config=get_fixed_credits_config(10) # 10 downloads ) plan_id = plan_result['planId'] # 2. Register the dataset resource dataset_result = payments.agents.register_agent( agent_metadata=AgentMetadata( name="ML Training Datasets", description="High-quality labeled datasets for machine learning", tags=["dataset", "ml", "training", "labeled"] ), agent_api=AgentAPIAttributes( endpoints=[ {"GET": "https://storage.example.com/datasets/images/*.zip"}, {"GET": "https://storage.example.com/datasets/text/*.jsonl"}, {"GET": "https://storage.example.com/datasets/audio/*.tar.gz"} ], agent_definition_url="https://storage.example.com/datasets/catalog.json" ), payment_plans=[plan_id] ) print(f"Dataset Resource ID: {dataset_result['agentId']}") ``` ## Example: Document Repository ```python theme={null} # Publishing a document repository doc_result = payments.agents.register_agent( agent_metadata=AgentMetadata( name="Research Papers Collection", description="Exclusive research papers and technical reports", tags=["research", "papers", "technical"] ), agent_api=AgentAPIAttributes( endpoints=[ # Specific documents {"GET": "https://docs.example.com/papers/whitepaper-2024.pdf"}, {"GET": "https://docs.example.com/papers/research-findings.pdf"}, # Wildcard for quarterly reports {"GET": "https://docs.example.com/reports/q*-report.pdf"}, # All supplementary materials {"GET": "https://docs.example.com/supplementary/*.zip"} ], agent_definition_url="https://docs.example.com/index.json" ), payment_plans=[plan_id] ) ``` ## Example: Software Distribution ```python theme={null} # Publishing software packages software_result = payments.agents.register_agent( agent_metadata=AgentMetadata( name="Premium Software Tools", description="Professional development tools and utilities", tags=["software", "tools", "professional"] ), agent_api=AgentAPIAttributes( endpoints=[ # Version-specific downloads {"GET": "https://releases.example.com/tool/v*/tool-*.zip"}, # Platform-specific binaries {"GET": "https://releases.example.com/tool/latest/tool-linux-*.tar.gz"}, {"GET": "https://releases.example.com/tool/latest/tool-macos-*.dmg"}, {"GET": "https://releases.example.com/tool/latest/tool-windows-*.exe"}, # Documentation {"GET": "https://releases.example.com/tool/docs/*.pdf"} ], agent_definition_url="https://releases.example.com/tool/manifest.json" ), payment_plans=[plan_id] ) ``` ## Accessing Static Resources For details on how subscribers access static resources using x402 access tokens, see [Request Validation](/docs/api-reference/python/validation-module). ## Best Practices 1. **Use descriptive metadata**: Include clear names, descriptions, and tags for discoverability 2. **Organize files logically**: Use consistent URL patterns that work well with wildcards 3. **Version your resources**: Include version numbers in URLs for easy updates 4. **Provide a manifest**: Create a JSON manifest at the `agent_definition_url` listing all available files 5. **Set appropriate credits**: Consider the value and size of files when setting credit costs ## Next Steps > [card] [Payments and Balance](/docs/api-reference/python/balance-module) > > Order plans and check balances > [card] [Querying an Agent](/docs/api-reference/python/requests-module) > > Access resources with tokens # Request Validation Source: https://nevermined.ai/docs/api-reference/python/validation-module Validate incoming requests and access tokens This guide explains how AI agents can validate incoming requests using the Nevermined Payments Python SDK. ## Overview When an agent receives a request, it needs to: 1. Extract the x402 access token from the request 2. Verify the subscriber has valid permissions 3. Optionally settle (burn) credits after processing The SDK provides the Facilitator API for these operations. ## Receiving Requests Agents receive requests with the x402 access token in the `payment-signature` header (per [x402 v2 HTTP transport spec](https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md)): ```python theme={null} from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/tasks', methods=['POST']) def handle_task(): # Extract x402 token from payment-signature header x402_token = request.headers.get('payment-signature', '') if not x402_token: return jsonify({'error': 'Missing payment-signature header'}), 402 # Validate and process... ``` ## Validating Requests with Facilitator ### Build Payment Required Object First, build the payment requirement specification: ```python theme={null} from payments_py.x402.helpers import build_payment_required payment_required = build_payment_required( plan_id="your-plan-id", endpoint="https://your-api.com/tasks", agent_id="your-agent-id", http_verb="POST" ) ``` ### Verify Permissions Check if the subscriber has valid permissions without burning credits: ```python theme={null} from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:agent-key", environment="sandbox") ) # Verify the request verification = payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=access_token, max_amount="1" # Optional: max credits to verify ) if verification.is_valid: print("Request is valid!") print(f"Payer: {verification.payer}") else: print(f"Invalid request: {verification.invalid_reason}") ``` ### Settle Permissions After successfully processing a request, burn the credits: ```python theme={null} settlement = payments.facilitator.settle_permissions( payment_required=payment_required, x402_access_token=access_token, max_amount="1" # Credits to burn ) if settlement.success: print(f"Credits redeemed: {settlement.credits_redeemed}") print(f"Transaction: {settlement.transaction}") ``` ## Complete Example: Flask Agent ```python theme={null} from flask import Flask, request, jsonify from payments_py import Payments, PaymentOptions from payments_py.x402.helpers import build_payment_required from payments_py.common.payments_error import PaymentsError app = Flask(__name__) # Initialize payments payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:agent-key", environment="sandbox") ) AGENT_ID = "your-agent-id" PLAN_ID = "your-plan-id" @app.route('/api/tasks', methods=['POST']) def create_task(): # 1. Extract x402 access token from payment-signature header access_token = request.headers.get('payment-signature', '') if not access_token: return jsonify({'error': 'Missing payment-signature header'}), 402 # 2. Build payment required object payment_required = build_payment_required( plan_id=PLAN_ID, endpoint=request.url, agent_id=AGENT_ID, http_verb=request.method ) try: # 3. Verify permissions verification = payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=access_token, max_amount="1" ) if not verification.is_valid: return jsonify({ 'error': 'Payment verification failed', 'details': verification.invalid_reason }), 402 # 4. Process the request task_data = request.json result = process_task(task_data) # 5. Settle (burn credits) after successful processing settlement = payments.facilitator.settle_permissions( payment_required=payment_required, x402_access_token=access_token, max_amount="1" ) return jsonify({ 'result': result, 'credits_used': settlement.credits_redeemed }) except PaymentsError as e: return jsonify({'error': str(e)}), 402 def process_task(data): # Your AI logic here return {"status": "completed", "output": "Task result"} if __name__ == '__main__': app.run(port=8080) ``` ## FastAPI Example with Manual Validation ```python theme={null} from fastapi import FastAPI, Request, HTTPException from payments_py import Payments, PaymentOptions from payments_py.x402.helpers import build_payment_required app = FastAPI() payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:agent-key", environment="sandbox") ) AGENT_ID = "your-agent-id" PLAN_ID = "your-plan-id" async def validate_payment(request: Request) -> dict: """Validate payment and return verification result.""" # Extract x402 token from payment-signature header access_token = request.headers.get('payment-signature', '') if not access_token: raise HTTPException(status_code=402, detail="Missing payment-signature header") payment_required = build_payment_required( plan_id=PLAN_ID, endpoint=str(request.url), agent_id=AGENT_ID, http_verb=request.method ) verification = payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=access_token, max_amount="1" ) if not verification.is_valid: raise HTTPException(status_code=402, detail="Payment verification failed") return { "access_token": access_token, "payment_required": payment_required, "verification": verification } @app.post("/api/tasks") async def create_task(request: Request, body: dict): # Validate payment payment_info = await validate_payment(request) # Process task result = {"output": f"Processed: {body}"} # Settle credits settlement = payments.facilitator.settle_permissions( payment_required=payment_info["payment_required"], x402_access_token=payment_info["access_token"], max_amount="1" ) return { "result": result, "credits_used": settlement.credits_redeemed } ``` ## Using x402 FastAPI Middleware For FastAPI applications, use the built-in x402 middleware: ```python theme={null} from fastapi import FastAPI from payments_py import Payments, PaymentOptions from payments_py.x402.fastapi import PaymentMiddleware app = FastAPI() # Initialize payments payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:agent-key", environment="sandbox") ) # Add x402 middleware app.add_middleware( PaymentMiddleware, payments=payments, routes={ "/api/tasks": { "plan_id": "your-plan-id", "agent_id": "your-agent-id", } } ) @app.post("/api/tasks") async def create_task(body: dict): # Middleware handles verification automatically # Just process the request return {"result": "Task completed"} ``` ## Verification Response The `verify_permissions` method returns a `VerifyResponse`: | Field | Type | Description | | - | - | - | | `is_valid` | `bool` | Whether the request is authorized | | `invalid_reason` | `str` | Reason for invalidity (if `is_valid` is false) | | `payer` | `str` | Payer's wallet address | | `agent_request_id` | `str` | Agent request ID for observability tracking | ## Settlement Response The `settle_permissions` method returns a `SettleResponse`: | Field | Type | Description | | - | - | - | | `success` | `bool` | Whether settlement succeeded | | `error_reason` | `str` | Reason for settlement failure (if `success` is false) | | `payer` | `str` | Payer's wallet address | | `transaction` | `str` | Blockchain transaction hash | | `credits_redeemed` | `str` | Number of credits burned | | `remaining_balance` | `str` | Credits remaining | ## Best Practices 1. **Always verify before processing**: Don't process expensive operations without verification 2. **Handle errors gracefully**: Return 402 Payment Required with helpful error messages 3. **Settle after completion**: Only burn credits after successfully completing the request 4. **Log transactions**: Keep records of verification and settlement for debugging 5. **Use middleware for consistency**: Apply validation uniformly across all endpoints ## Next Steps > [card] [MCP Integration](/docs/api-reference/python/mcp-module) > > Build MCP servers with payment validation > [card] [x402 Protocol](/docs/api-reference/python/x402-module) > > Deep dive into x402 protocol # x402 Protocol Source: https://nevermined.ai/docs/api-reference/python/x402-module Use x402 protocol for payment verification and settlement This guide covers the x402 payment protocol for verifying permissions and settling payments. ## Overview x402 is a payment protocol that enables: * **Permission Generation**: Subscribers create access tokens for agents * **Permission Verification**: Agents verify tokens without burning credits * **Permission Settlement**: Agents burn credits after completing work The protocol is named after HTTP status code 402 (Payment Required). ## Supported Schemes Nevermined supports two x402 payment schemes: | Scheme | Network | Use Case | Settlement | | - | - | - | - | | `nvm:erc4337` | `eip155:84532` | Crypto payments | ERC-4337 UserOps + session keys | | `nvm:card-delegation` | `stripe` \| `braintree` \| `visa` | Fiat/credit card | Provider charge + credit burn | The scheme is determined by the plan's pricing configuration. Plans with `isCrypto: false` use `nvm:card-delegation`; all others use `nvm:erc4337`. The SDK auto-detects the scheme via `resolve_scheme()`. The `network` value within `nvm:card-delegation` is determined by which provider issued the delegation being consumed (`stripe`, `braintree`, or `visa`). ### Visa support Visa delegations use the same `nvm:card-delegation` scheme and SDK surface as Stripe and Braintree, but two steps must happen in a **browser** before the SDK can consume them: 1. **Card enrolment** — the cardholder enrols a Visa card through VGS Collect (PCI-compliant iframe) in the Nevermined webapp. The card is bound to a Visa Agentic Token via the VGS Credential Management Platform. 2. **Delegation creation** — the cardholder approves a delegation via a WebAuthn/passkey (FIDO) device-binding ceremony embedded by Visa VTS. This produces a single-use `assuranceData` blob bound to the spending limit + duration + merchant context. Both steps require a real DOM and a user gesture, so the SDK cannot perform them programmatically. Once a Visa delegation exists, the SDK consumes it identically to Stripe/Braintree — pass `delegation_id` to `DelegationConfig` and call `get_x402_access_token` as usual: ```python theme={null} from payments_py.x402 import X402TokenOptions, DelegationConfig result = subscriber_payments.x402.get_x402_access_token( plan_id, token_options=X402TokenOptions( scheme="nvm:card-delegation", network="visa", delegation_config=DelegationConfig( delegation_id="11111111-1111-1111-1111-111111111111", ), ), ) ``` `delegation_id` reuse is the **only** supported pattern for Visa — `create_delegation(provider="visa", ...)` is rejected by the backend without the browser-only `consumer_prompt` + `assurance_data` blobs the SDK has no way to produce. When a Visa creation call fails this way, `PaymentsError.code` carries the backend `BCK.VISA.0014` so consumers can branch programmatically. ## Generate Payment Permissions ### From Nevermined App The easiest way to generate permissions is through the [Nevermined App Permissions page](https://nevermined.app/permissions/agent-permissions): 1. Navigate to the permissions page 2. Select your plan and agent 3. Configure limits (optional) 4. Generate the access token ### From SDK ```python theme={null} from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:subscriber-key", environment="sandbox") ) # Basic token generation result = payments.x402.get_x402_access_token( plan_id="your-plan-id", agent_id="agent-id" ) access_token = result['accessToken'] # With delegation config (crypto — erc4337) from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload # Create the delegation once (currency is required), then reuse it across plans. delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="erc4337", spending_limit_cents=10000, # $100 duration_secs=604800, # 1 week currency="usdc", ) ) result = payments.x402.get_x402_access_token( plan_id="your-plan-id", agent_id="agent-id", token_options=X402TokenOptions( delegation_config=DelegationConfig(delegation_id=delegation.delegation_id) ) ) ``` > **Deprecated:** passing `spending_limit_cents` / `duration_secs` directly to > `get_x402_access_token` (inline create-on-the-fly, a `DelegationConfig` with no > `delegation_id`) emits a `DeprecationWarning` and will be removed in a future > release. Create the delegation first as shown above, then pass only > `delegation_id`. ### Card-Delegation Token Generation For fiat plans using `nvm:card-delegation`, create the card delegation once (`currency` is required), then request the token by `delegation_id`: ```python theme={null} from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload # Step 1 — create a USD card delegation (currency is required). usd_delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="stripe", provider_payment_method_id="pm_1AbCdEfGhIjKlM", spending_limit_cents=10000, # $100.00 duration_secs=2592000, # 30 days currency="usd", max_transactions=100, ) ) # Step 2 — request the token referencing the delegation id. result = payments.x402.get_x402_access_token( plan_id="your-plan-id", agent_id="agent-id", token_options=X402TokenOptions( scheme="nvm:card-delegation", delegation_config=DelegationConfig( delegation_id=usd_delegation.delegation_id ), ) ) access_token = result['accessToken'] # EUR card delegation — same flow, currency="eur". eur_delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="stripe", provider_payment_method_id="pm_1AbCdEfGhIjKlM", spending_limit_cents=10000, # €100.00 (in euro cents) duration_secs=2592000, # 30 days currency="eur", max_transactions=100, ) ) eur_result = payments.x402.get_x402_access_token( plan_id="your-plan-id", agent_id="agent-id", token_options=X402TokenOptions( scheme="nvm:card-delegation", delegation_config=DelegationConfig( delegation_id=eur_delegation.delegation_id ), ) ) ``` ### Auto Scheme Resolution Use `resolve_scheme()` to auto-detect the correct scheme from plan metadata: ```python theme={null} from payments_py.x402.resolve_scheme import resolve_scheme # Auto-detect scheme from plan metadata (cached for 5 minutes) scheme = resolve_scheme(payments, plan_id="your-plan-id") # Returns "nvm:erc4337" for crypto plans, "nvm:card-delegation" for fiat plans # Explicit override scheme = resolve_scheme(payments, plan_id="your-plan-id", explicit_scheme="nvm:card-delegation") ``` ### DelegationAPI Create delegations and list enrolled payment methods: ```python theme={null} from payments_py.x402 import CreateDelegationPayload # Create a crypto delegation (currency is required) delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="erc4337", spending_limit_cents=10000, duration_secs=604800, currency="usdc", ) ) print(f"Delegation ID: {delegation.delegation_id}") # List enrolled payment methods (every provider) methods = payments.delegation.list_payment_methods() for method in methods: print(f"{method.brand} ****{method.last4} (expires {method.exp_month}/{method.exp_year})") # e.g., "visa ****4242 (expires 12/2027)" # Restrict the result to a single provider with the optional `provider` kwarg stripe_methods = payments.delegation.list_payment_methods(provider="stripe") ``` `list_payment_methods()` accepts an optional `provider` keyword argument (`'stripe' | 'braintree' | 'visa' | 'erc4337'`). When set, it is forwarded as a `?provider=` query string and only methods backed by that provider are returned. Omit it (the default) to return methods from every provider. `PaymentMethodSummary` fields: | Field | Type | Description | | - | - | - | | `id` | `str` | Payment method ID (e.g., `pm_...`) | | `brand` | `str` | Card brand (e.g., `visa`, `mastercard`) | | `last4` | `str` | Last 4 digits of the card number | | `exp_month` | `int` | Card expiration month | | `exp_year` | `int` | Card expiration year | ### Token Structure The x402 token is a base64-encoded JSON document: ```json theme={null} { "payload": { "authorization": { "from": "0xSubscriberAddress", "planId": "plan-123", "agentId": "agent-456" }, "sessionKey": { "address": "0xSessionKeyAddress", "permissions": ["order", "burn"], "limits": { "redemptionLimit": 100, "orderLimit": "1000000000000000000" } } }, "signature": "0x..." } ``` ## Verify Payment Permissions Verification checks if a subscriber has valid permissions without burning credits: ```python theme={null} from payments_py import Payments, PaymentOptions from payments_py.x402.helpers import build_payment_required payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:agent-key", environment="sandbox") ) # Build the 402 Payment Required specification payment_required = build_payment_required( plan_id="your-plan-id", endpoint="https://your-api.com/endpoint", agent_id="your-agent-id", http_verb="POST" ) # Verify the token verification = payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=access_token, max_amount="1" # Optional: max credits to verify ) if verification.is_valid: print(f"Valid! Payer: {verification.payer}") else: print(f"Invalid: {verification.invalid_reason}") ``` ### Verification Response | Field | Type | Description | | - | - | - | | `is_valid` | `bool` | Whether verification passed | | `invalid_reason` | `str` | Reason for invalidity (if `is_valid` is false) | | `payer` | `str` | Payer's wallet address | | `agent_request_id` | `str` | Agent request ID for observability tracking | ## Settle Payment Permissions Settlement burns credits after successfully processing a request: ```python theme={null} # After processing the request successfully settlement = payments.facilitator.settle_permissions( payment_required=payment_required, x402_access_token=access_token, max_amount="1", # Credits to burn agent_request_id="request-123" # Optional: for tracking ) if settlement.success: print(f"Settled! Credits burned: {settlement.credits_redeemed}") print(f"Transaction: {settlement.transaction}") print(f"Remaining: {settlement.remaining_balance}") else: print(f"Settlement failed: {settlement.error_reason}") ``` ### Settlement Response | Field | Type | Description | | - | - | - | | `success` | `bool` | Whether settlement succeeded | | `error_reason` | `str` | Reason for failure (if `success` is false) | | `payer` | `str` | Payer's wallet address | | `transaction` | `str` | Blockchain transaction hash | | `credits_redeemed` | `str` | Credits that were burned | | `remaining_balance` | `str` | Credits remaining | ## Payment Required Object The `X402PaymentRequired` object specifies what payment is required. The `scheme` and `network` fields vary by payment type: ```python theme={null} from payments_py.x402.types import X402PaymentRequired, X402Resource, X402Scheme, X402SchemeExtra # Crypto plan (nvm:erc4337) payment_required = X402PaymentRequired( x402_version=2, resource=X402Resource( url="https://your-api.com/endpoint", description="Protected endpoint" # Optional ), accepts=[ X402Scheme( scheme="nvm:erc4337", network="eip155:84532", # Base Sepolia plan_id="your-plan-id", extra=X402SchemeExtra( http_verb="POST", # HTTP method goes in extra, not resource agent_id="agent-123" # Optional ) ) ], extensions={} ) # Fiat plan (nvm:card-delegation) payment_required_fiat = X402PaymentRequired( x402_version=2, resource=X402Resource( url="https://your-api.com/endpoint", description="Protected endpoint" ), accepts=[ X402Scheme( scheme="nvm:card-delegation", network="stripe", plan_id="your-plan-id", extra=X402SchemeExtra( http_verb="POST", agent_id="agent-123" ) ) ], extensions={} ) ``` ### Using the Helpers ```python theme={null} from payments_py.x402.helpers import build_payment_required, build_payment_required_for_plans # Single plan (scheme auto-detected from plan metadata when omitted) payment_required = build_payment_required( plan_id="your-plan-id", endpoint="https://api.example.com/tasks", agent_id="agent-123", http_verb="POST" ) # Explicit scheme override payment_required = build_payment_required( plan_id="your-plan-id", endpoint="https://api.example.com/tasks", agent_id="agent-123", http_verb="POST", scheme="nvm:card-delegation" # Force fiat/Stripe scheme ) # Multiple plans — creates one entry per plan in accepts[] payment_required = build_payment_required_for_plans( plan_ids=["plan-basic", "plan-premium"], endpoint="https://api.example.com/tasks", agent_id="agent-123", http_verb="POST" ) ``` For a single plan, `build_payment_required_for_plans` delegates to `build_payment_required` internally. When `scheme` is omitted, the network defaults to `eip155:84532` (Base Sepolia). When `scheme="nvm:card-delegation"`, the network is automatically set to `stripe`. ## Complete Workflow Example ```python theme={null} from payments_py import Payments, PaymentOptions from payments_py.x402.helpers import build_payment_required from flask import Flask, request, jsonify app = Flask(__name__) # Agent's payments instance agent_payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:agent-key", environment="sandbox") ) PLAN_ID = "your-plan-id" AGENT_ID = "your-agent-id" @app.route('/api/process', methods=['POST']) def process_request(): # 1. Extract x402 token from payment-signature header token = request.headers.get('payment-signature', '') if not token: return jsonify({'error': 'Missing payment-signature header'}), 402 # 2. Build payment requirement payment_required = build_payment_required( plan_id=PLAN_ID, endpoint=request.url, agent_id=AGENT_ID, http_verb=request.method ) # 3. Verify (doesn't burn credits) verification = agent_payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=token, max_amount="1" ) if not verification.is_valid: return jsonify({ 'error': 'Payment required', 'details': verification.invalid_reason, 'paymentRequired': payment_required.model_dump() }), 402 # 4. Process the request try: result = do_expensive_work(request.json) except Exception as e: # Don't settle on failure return jsonify({'error': str(e)}), 500 # 5. Settle (burn credits) on success settlement = agent_payments.facilitator.settle_permissions( payment_required=payment_required, x402_access_token=token, max_amount="1" ) return jsonify({ 'result': result, 'creditsUsed': settlement.credits_redeemed, 'remainingBalance': settlement.remaining_balance }) def do_expensive_work(data): # Your processing logic return {'processed': True} if __name__ == '__main__': app.run(port=8080) ``` ## HTTP Flow ```mermaid theme={null} sequenceDiagram participant Subscriber participant Agent participant Nevermined Subscriber->>Agent: GET /api/process (no token) Agent-->>Subscriber: 402 Payment Required
{paymentRequired: {...}} Subscriber->>Nevermined: get_x402_access_token() Nevermined-->>Subscriber: {accessToken: "..."} Subscriber->>Agent: GET /api/process
payment-signature: token Agent->>Nevermined: verify_permissions() Nevermined-->>Agent: {isValid: true} Note over Agent: Process request Agent->>Nevermined: settle_permissions() Nevermined-->>Agent: {success: true} Agent-->>Subscriber: 200 OK {result: ...} ``` ## Best Practices 1. **Always verify before processing**: Don't do expensive work without verification 2. **Only settle on success**: Don't burn credits if processing fails 3. **Use agent\_request\_id**: Include request IDs for tracking and debugging 4. **Handle 402 responses**: Return proper payment required responses with scheme info 5. **Cache verifications carefully**: Tokens can be used multiple times until limits are reached ## Error Codes | Error | Description | Resolution | | - | - | - | | `invalid_token` | Token is malformed | Generate a new token | | `expired_token` | Token has expired | Generate a new token | | `insufficient_balance` | Not enough credits | Order more credits | | `invalid_plan` | Plan ID mismatch | Use correct plan ID | | `invalid_agent` | Agent ID mismatch | Use correct agent ID | ## Next Steps > [card] [Request Validation](/docs/api-reference/python/validation-module) > > More validation patterns > [card] [MCP Integration](/docs/api-reference/python/mcp-module) > > x402 with MCP servers > [card] [OAuth 401 vs. payment-required](/docs/api-reference/python/mcp-module#oauth-401-vs-payment-required) > > In-band x402 v2 MCP signaling # Quote from a Commerce Grant Source: https://nevermined.ai/docs/api-reference/router/commerce-quote POST /router/commerce/quote The OAuth counterpart of `POST /api/v1/router/quote`, for a credential minted from a `commerce` authorization. Identical behaviour and identical response, with one difference: **you do not choose the delegation.** The quote prices the options the delegation your grant is pinned to would select, so it is what `POST /api/v1/router/commerce/route` would charge for the same call. Sending a `delegationId` is refused, not ignored. Nothing is signed, no credential is minted, no payment is recorded and no budget is reserved. The Router still makes the unpaid request to the service, and the quote spends the same per-key and per-service rate budgets as a payment. Compare `fee.capChargedCents` with what you want to spend, then call `/commerce/route` with `maxTotalCents` set to that figure. A plain (non-OAuth) API key cannot use this route: it has no grant to price. Use `POST /api/v1/router/quote` and name your own `delegationId` instead. > [!NOTE] > > **Rolling out.** This route ships in the first API release after 1.49. Until your environment runs it, the route answers `404`: bound the price with `maxTotalCents` on [`POST /router/commerce/route`](/docs/api-reference/router/commerce-route) instead. # Route and Pay from a Commerce Grant Source: https://nevermined.ai/docs/api-reference/router/commerce-route POST /router/commerce/route The OAuth counterpart of `POST /api/v1/router/route`, for a credential minted from a `commerce` authorization. Identical behaviour and identical response — with one difference: **you do not choose the delegation.** It is derived from your grant: the capped, expiring mandate the user approved when they connected you. Sending a `delegationId` is refused, not ignored. The cap, its expiry, and the user revoking the grant are the boundary on what you can spend. The routing fee is drawn from that same cap, in addition to each merchant’s price. A plain (non-OAuth) API key cannot use this route — it has no grant to derive from. Use `POST /api/v1/router/route` and name your own `delegationId` instead. # Read Your Credits Source: https://nevermined.ai/docs/api-reference/router/credits-balance GET /credits/balance Your Nevermined credits: every credit your personal account holds — free welcome credits, a Nevermined Subscription's monthly allowance and top-up credits — as one balance, subscribed or not. They are spent earliest expiry first. Charges nothing; a caller with no credits gets `total: "0"` and an empty `parts`. Always personal: an organization tag on the key and an `X-Current-Org-Id` header are ignored — but a call made in an organization never spends these credits (`BCK.SUBSCRIPTION_ROUTER.0002`), so `spendable` is what a personal key can pay with. API keys only: an OAuth-minted credential is refused (`BCK.OAUTH.0030`), even a commerce connection allowed to spend your credits. Frozen credits count in `total` but not in `spendable`. # List Payments Source: https://nevermined.ai/docs/api-reference/router/list-payments GET /router/payments Returns your Router payments (newest first, capped at 1000) across every agent and delegation — the unified audit trail. Filter by `delegationId` and by `from`/`to` (ISO-8601, inclusive on `createdAt`). `format=csv` returns a CSV file download instead of the JSON array. Supplying `requestId` selects a separate, exact, caller-scoped lookup instead: the list filters are ignored and it is not subject to the 1000-row window. JSON answers it with an explicit `presence` discriminator and zero or one `payments`; a failed lookup is an error, never `absent`. With `format=csv` it answers the matching row, or only the header when there is none. An older Router that ignores `requestId` answers a plain array, which is never authoritative absence. # Mint Payment Credential Source: https://nevermined.ai/docs/api-reference/router/mint-payment-credential POST /router/payments Pay any x402-compatible agent WITHOUT that agent integrating Nevermined. Returns a signed credential you attach to your own request to the agent. Prerequisite: a spending **Delegation**. Create one once via `POST /api/v1/delegation/create` with `provider: 'erc4337'`, a `spendingLimitCents`, and a `durationSecs`; pass its `id` as `delegationId` here. The Router signs with your custodial wallet and enforces the cap. Steps: 1. Call the agent once WITHOUT payment → it replies HTTP 402 with requirements. x402 v1 puts them in the JSON body `{ x402Version: 1, accepts: [...] }`; x402 v2 puts them in a base64 `PAYMENT-REQUIRED` response header (decode to an object). Pass what you got as `target`. 2. POST here. The Router selects a fundable option, signs an x402 `exact` (EIP-3009) payment, reserves the amount against your Delegation, and returns `credential` + `settlement`. 3. Re-send your original request to the agent with the HTTP header named `credential.name` (`PAYMENT-SIGNATURE` for v2, `X-PAYMENT` for v1) set to `credential.value`. The agent verifies, settles on-chain, and returns the resource. Optionally call `POST /api/v1/router/payments/{id}/settled` with the on-chain tx to complete the audit record. Pass a stable `requestId` for idempotency (one credential per id). Prefer `POST /api/v1/router/route` to have the Router call the agent and pay in one step (mode B). MPP: set `protocol: "mpp"` and pass the raw `WWW-Authenticate: Payment …` header value as `target.challenge` to pay a Merchant-Payment-Protocol (tempo `charge` or `evm` charge) merchant. The Router returns an `Authorization: Payment <…>` credential (attach it under header `credential.name`). An `evm` charge can't be paid from a wallet that signs through an EIP-7702 smart account, as personal wallets do: the call is refused with `400 BCK.ROUTER.0001` before signing, with no fallback. # Payments Summary Source: https://nevermined.ai/docs/api-reference/router/payments-summary GET /router/payments/summary Returns the buyer’s total number of Router payment requests (uncapped — unlike the 1000-row list endpoint) plus a per-bucket time-series for a dashboard chart. Filter by `from`/`to` (ISO-8601, inclusive on `createdAt`); choose the bucket size with `granularity` (day/week/month). # Quote a Request Before Paying Source: https://nevermined.ai/docs/api-reference/router/quote POST /router/quote Ask what `POST /route` would charge for this call, WITHOUT paying it. The Router makes the same unpaid probe `/route` makes, reads the 402, selects the payment option exactly as a payment would (MPP first, then x402) and prices it with the Router fee — then stops. Nothing is signed, no credential is minted, no payment is recorded and no delegation budget is reserved, so no money moves. A quote is not free of consequence, though: the unpaid probe reaches the service (one that does not charge for the request performs it), and a quote spends the same per-key and per-service rate limit as a payment — so quote once per decision rather than repeating it. Use it to decide whether ONE call fits the allocation you planned for it: compare `fee.capChargedMicros` (exact) or `fee.capChargedCents` (rounded up, the figure `maxTotalCents` is compared against) with what you want to spend, then call `/route` with `maxTotalCents` set to that figure so a price change between quote and call is refused rather than paid. `delegationId` is optional. With it, the quote prices the options that delegation would select (an organization-wallet delegation pays only in its own currency, a card delegation pays over MPP-stripe, a recipient allowlist is enforced); without it, the options a personal crypto delegation would select. `optionSet` says which. Either way it quotes only what the paying wallet can sign: an MPP `evm` charge is never quoted for a wallet that signs through an EIP-7702 smart account (a personal wallet wherever the deployment migrates personal wallets to EIP-7702, or an organization wallet upgraded to EIP-7702), so a service that also offers x402 is quoted on x402 and its `quoteId` pays x402. A quote checks neither the remaining cap nor the wallet balance — those are the payment’s checks (BCK.ROUTER.0003, BCK.ROUTER.0009). Provide the target `url` OR a catalog `slug` (+ optional `path`, `search`, `method`, `headers`, `body`), as on `/route`. A non-402 answer returns `paymentRequired: false` with the upstream status only — the upstream body and headers are never returned. > [!NOTE] > > A quote charges nothing, but it is not free of consequence: the Router sends your request to the service unpaid, so a service that doesn't charge for it performs it, and the quote spends the same per-key and per-service rate budgets as a payment. Quote once per decision; don't poll. Available from API 1.48. # Report Settlement Source: https://nevermined.ai/docs/api-reference/router/report-settlement POST /router/payments/{id}/settled After you attached a mode-A credential and the agent settled on-chain, report the settlement `txHash` (from the agent’s `PAYMENT-RESPONSE` / `X-PAYMENT-RESPONSE` header) so the payment record moves `Issued → Settled`. Idempotent: re-reporting the same txHash is a no-op; a different txHash, or a record not in `Issued`, is rejected. NOT needed for mode B (`/route` and `/proxy` self-complete the record from the upstream settlement header). # Route and Pay a Request Source: https://nevermined.ai/docs/api-reference/router/route-request POST /router/route Hand the Router the request you want made to an upstream x402 agent; it probes, pays any 402 with your Delegation (same engine as `POST /router/payments`), and relays the agent’s response in ONE call — you never see the 402 or handle the credential yourself. Prerequisite: a Delegation `id` (`POST /api/v1/delegation/create`, provider `erc4337`). Provide the target `url` (+ optional `method`, `headers`, `body`). A free (non-402) upstream is relayed unchanged with `paid=false` and no `payment`. `requestId` is REQUIRED (the Router pays automatically, so a retry must be idempotency-keyed); a duplicate returns 409 with the original paymentId (from API 1.48, the first purchase's retained result instead — see `GET /router/payments/{id}/result`). For LARGE or STREAMED responses, a transparent streaming variant exists at `ALL /api/v1/router/proxy`: point your HTTP client at it with headers `X-Router-Target-Url` and `X-Router-Delegation-Id` (optional `X-Router-Upstream-Authorization` for the agent’s own auth). Method/body/headers pass through and the response streams back, with payment metadata in `X-Router-Payment-Id`, `X-Router-Payment-Status`, and `X-Router-Tx-Hash` response headers. Use this JSON endpoint when you want a single structured result instead. # Read Your Subscription Credits Source: https://nevermined.ai/docs/api-reference/router/subscription-balance GET /router/subscription/balance Your credits left — the whole balance your Nevermined Subscription pays from, free welcome credits included — when the monthly allowance resets, and your plan. Charges nothing. Called in an organization you are an active member of (`X-Current-Org-Id`, or that organization's API key), it reads that organization's subscription instead, never your personal one; organizations can no longer subscribe, so that is `subscribed: false` unless the organization still holds one bought earlier. `subscribed: false` carries no other field; every other field is present exactly when `subscribed` is true. Personal API keys only: Nevermined credits and the Nevermined Subscription belong to a personal account, so call with a key that carries no organization tag and without `X-Current-Org-Id`. Of OAuth-minted credentials, only a `commerce` connection the user allowed to spend their Nevermined credits is accepted: another `commerce` connection is refused with `BCK.OAUTH.0037`, one acting in an organization with `BCK.OAUTH.0038`, and any other OAuth credential with `BCK.OAUTH.0030`. For every credit you hold, subscribed or not, by kind and expiry, read `GET /credits/balance`. Where the subscription is not available — on this deployment or to this account — it answers 404 `BCK.SUBSCRIPTION_ACCESS.0001`. # Quote a Call in Subscription Credits Source: https://nevermined.ai/docs/api-reference/router/subscription-quote POST /router/subscription/quote Credits one call to a catalog endpoint costs with your Nevermined credits — free welcome credits or a Nevermined Subscription's allowance, subscribed or not: the endpoint's current rate on Nevermined's rate card, whatever the merchant charges at the moment of the call. Rates change without notice; the rate in force when the call is made applies. Answers from the rate card alone — the merchant is not contacted, nothing is reserved and nothing is charged. It refuses what `POST /router/subscription/route` would refuse before contacting the merchant (an ineligible or untariffed endpoint, nothing that can pay the call, credits frozen by a card dispute or an overdue renewal). For a subscriber in good standing it does NOT check the credits left; without a subscription in good standing it checks that your spendable credits cover this call, unless an automatic credit top-up would cover it. It never checks the merchant's live price or Nevermined's treasury; the route checks those when the call is made. A `url` is refused (`BCK.SUBSCRIPTION_ROUTER.0005`). Personal API keys only: Nevermined credits and the Nevermined Subscription belong to a personal account, so call with a key that carries no organization tag and without `X-Current-Org-Id`. Of OAuth-minted credentials, only a `commerce` connection the user allowed to spend their Nevermined credits is accepted: another `commerce` connection is refused with `BCK.OAUTH.0037`, one acting in an organization with `BCK.OAUTH.0038`, and any other OAuth credential with `BCK.OAUTH.0030`. Where the subscription is not available — on this deployment or to this account — it answers 404 `BCK.SUBSCRIPTION_ACCESS.0001`. # Call a Service with Subscription Credits Source: https://nevermined.ai/docs/api-reference/router/subscription-route POST /router/subscription/route Call a catalog service and pay it with your Nevermined credits (mode B) — free welcome credits, top-up credits or a Nevermined Subscription's allowance, subscribed or not. Like `POST /router/route`, but Nevermined pays the merchant from its treasury and your credits are charged the endpoint's rate. There is no Delegation, no wallet to fund and no routing fee. - **A slug, never a URL.** Address the service by `slug` (+ `path`, `search`, `method`, `headers`, `body`). A `url` or a `delegationId` is refused (`BCK.SUBSCRIPTION_ROUTER.0005`), not ignored. - **`requestId` is required** (idempotency): a retry with the same id is never paid twice. - **Only a merchant `2xx` keeps the credits.** They are reserved before the merchant is called and kept (`Committed`) only on a `2xx`; anything else marks them for refund and they are returned (`Refunded`). Every refusal below happens before anything is reserved, signed or charged — except a 502, which can follow a payment, and a `BCK.SUBSCRIPTION_ROUTER.0009` whose `params.topUps` is `bought` (or `pending`), or a `BCK.SUBSCRIPTION_ROUTER.0015` or `0016` whose `params.topUps` is `bought`, which follows a credit pack charged to your card (`params.purchaseId` names it). - **Credit top-ups.** With top-ups on, a call that runs out of credits charges one never-expiring credit pack to the saved card and goes ahead; the answer then carries `topUp`. Your card was charged: tell the person you are acting for. - **Rails:** only an EIP-3009 `exact` authorization (x402, or an MPP `evm` charge), an MPP `tempo` `charge`, and an MPP `tempo` `session` where this deployment has MPP sessions turned on. For large or streamed responses, the streaming form is `ALL /api/v1/router/subscription/svc/{slug}/{path}` with an `X-Router-Request-Id` header; it answers with `X-Router-Credits-Charged` and `X-Router-Credits-Status` beside the `X-Router-Payment-*` headers (plus `X-Router-Topup-Credits` and `X-Router-Topup-Amount-Usd` when the call charged a credit pack), and refuses `X-Router-Target-Url`, `X-Router-Target-Slug` and `X-Router-Delegation-Id`. Personal API keys only: Nevermined credits and the Nevermined Subscription belong to a personal account, so call with a key that carries no organization tag and without `X-Current-Org-Id`. Of OAuth-minted credentials, only a `commerce` connection the user allowed to spend their Nevermined credits is accepted: another `commerce` connection is refused with `BCK.OAUTH.0037`, one acting in an organization with `BCK.OAUTH.0038`, and any other OAuth credential with `BCK.OAUTH.0030`. Where the subscription is not available — on this deployment or to this account — it answers 404 `BCK.SUBSCRIPTION_ACCESS.0001`. # Read the Welcome Credits Offer Source: https://nevermined.ai/docs/api-reference/router/welcome-credits-offer GET /credits/welcome/offer The free welcome credits a new account is granted when it signs up with a verified email, and how many days they last. `offer` is `null` while the offer is closed. A non-null offer says what the offer grants, not that a particular sign-up right now will be granted. No authentication; the answer is the same for every caller and may be cached for 5 minutes. # A2A Integration Source: https://nevermined.ai/docs/api-reference/typescript/a2a-integration Enable agent-to-agent communication with payment-protected streaming and task execution # A2A Integration The Agent-to-Agent (A2A) protocol integration enables AI agents to communicate with each other using payment-protected message streams. The Nevermined Payments Library provides complete A2A server functionality with automatic payment handling. ## Overview of A2A Integration The A2A integration provides: * **Agent Card**: Payment metadata extension for discovery * **Streaming Support**: Real-time task updates via Server-Sent Events * **Task Management**: Async execution with status tracking * **Credit Burning**: Automatic credit settlement after task completion * **EventBus Pattern**: Clean event-driven architecture for task execution ## Build Payment Agent Card The agent card is published at the canonical `/.well-known/agent-card.json` (A2A 0.3+), with the legacy `/.well-known/agent.json` kept as a backward-compat alias. It includes payment metadata. Before sending a paid request, **clients should fetch and validate the target agent's card** to confirm the expected `agentId`, the `capabilities`, and the supported X402 schemes — this protects against routing payment tokens to a typosquatted or unauthorised endpoint: ```typescript theme={null} const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1']) const cardUrl = new URL('/.well-known/agent-card.json', agentUrl) const card = await fetch(cardUrl, { method: 'GET' }).then((r) => r.json()) if (card.agentId !== expectedAgentId) { throw new Error(`Agent card mismatch: expected ${expectedAgentId}, got ${card.agentId}`) } if (cardUrl.protocol !== 'https:' && !LOOPBACK_HOSTS.has(cardUrl.hostname)) { console.warn(`Agent card fetched over ${cardUrl.protocol} — production traffic must use HTTPS.`) } ``` ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Build agent card with payment extension const agentCard = Payments.a2a.buildPaymentAgentCard( { name: 'Weather AI Agent', description: 'Real-time weather forecasts and analysis', version: '1.0.0', protocolVersion: '0.3.0', url: 'http://localhost:6000/a2a/', capabilities: { streaming: true, pushNotifications: false, }, defaultInputModes: ['text'], defaultOutputModes: ['text'], skills: [], }, { agentId: process.env.NVM_AGENT_ID!, planId: process.env.NVM_PLAN_ID!, credits: 5, // Fixed credit cost paymentType: 'fixed', // 'fixed' or 'dynamic' costDescription: '5 credits per request (optional)', } ) ``` ## Payment Extension Structure The agent card declares two extensions in `capabilities.extensions`: the Nevermined payment extension (pricing metadata) and the official a2a-x402 extension (`https://github.com/google-agentic-commerce/a2a-x402/blob/main/spec/v0.2`), which signals support for the standards-compliant in-band x402 v2 flow (see below). Both are emitted for one release; `urn:nevermined:payment` will be dropped once clients migrate to v0.2 only. ```json theme={null} { "capabilities": { "streaming": true, "extensions": [ { "uri": "urn:nevermined:payment", "required": false, "params": { "paymentType": "fixed", "credits": 5, "agentId": "did:nv:agent-123", "planId": "plan-456", "costDescription": "5 credits per request" } }, { "uri": "https://github.com/google-agentic-commerce/a2a-x402/blob/main/spec/v0.2", "required": false } ] } } ``` ## x402 v2 In-Band Payments (Standards Flow) Payment is signalled **in band** following the [Coinbase x402 v2 A2A transport spec](https://github.com/coinbase/x402/blob/main/specs/transports-v2/a2a.md) and the official [a2a-x402 extension](https://github.com/google-agentic-commerce/a2a-x402). No HTTP 402 is involved — the whole handshake rides on A2A task/message metadata, correlated by `taskId`. This is automatic when you use `payments.a2a.start`; nothing changes in your executor. Lifecycle: 1. **Payment required** — a payment-gated `message/send` arrives with no payment. The server returns a Task with `status.state = "input-required"` and `status.message.metadata`: ```json theme={null} { "x402.payment.status": "payment-required", "x402.payment.required": { /* X402PaymentRequired (accepts[] of plans) */ } } ``` 2. **Payment submitted** — the client sends a follow-up `message/send` whose `message.metadata` carries the payload, correlated via `message.taskId`: ```json theme={null} { "x402.payment.status": "payment-submitted", "x402.payment.payload": { /* PaymentPayload */ } } ``` 3. **Completed / failed** — on success the final Task carries `x402.payment.status: "payment-completed"` plus `x402.payment.receipts` (array of settle receipts). On failure it is `failed` / `x402.payment.status: "payment-failed"` with the error under `x402.payment.error`, and paid content is suppressed. Metadata keys: `x402.payment.status`, `x402.payment.required`, `x402.payment.payload`, `x402.payment.receipts`, `x402.payment.error`. > **Batch (deferred) settlement.** If the server settles credits in batch, a successful call returns `x402.payment.status: "payment-verified"` (not `payment-completed`) plus the Nevermined marker `x402.payment.settlement: "deferred"` — the payment was verified but settled out-of-band, so there is no in-band receipt. Spec-only clients ignore the unknown key. > ⚠️ **Header flow deprecated.** The legacy `payment-signature` HTTP header still works but is now a **deprecated fallback, kept for one release**. New integrations should rely on the in-band metadata flow above. ## Implement Executor The executor contains your agent's business logic and emits events via the EventBus: ```typescript theme={null} const executor = { async execute(context, eventBus) { const taskId = context.task?.id // Emit working status eventBus.publish({ kind: 'status-update', taskId, status: { state: 'working' }, final: false, }) try { // Process the task const userMessage = context.history?.[0] const prompt = userMessage?.parts?.find(p => p.kind === 'text')?.text const result = await processPrompt(prompt) // Emit completion with credits used eventBus.publish({ kind: 'status-update', taskId, status: { state: 'completed', message: { role: 'agent', parts: [{ kind: 'text', text: result }], }, }, final: true, metadata: { creditsUsed: 5 }, // Report credits consumed }) } catch (error) { // Emit failure eventBus.publish({ kind: 'status-update', taskId, status: { state: 'failed', message: { role: 'agent', parts: [{ kind: 'text', text: `Error: ${error.message}` }], }, }, final: true, }) } // Signal completion eventBus.finished() }, async cancelTask(taskId, eventBus) { // Handle task cancellation eventBus.publish({ kind: 'status-update', taskId, status: { state: 'canceled' }, final: true, }) eventBus.finished() }, } ``` ## EventBus Events The executor communicates via event publishing: ### Task Event ```typescript theme={null} eventBus.publish({ kind: 'task', id: taskId, contextId: contextId, status: { state: 'working' }, history: [userMessage], }) ``` ### Status Update Event ```typescript theme={null} eventBus.publish({ kind: 'status-update', taskId, status: { state: 'completed', // or 'working', 'failed', 'canceled' message: { role: 'agent', parts: [{ kind: 'text', text: 'Result here' }], }, }, final: true, // Set true when task is done metadata: { creditsUsed: 5, // Required for credit settlement }, }) ``` ### Message Event (Streaming) ```typescript theme={null} eventBus.publish({ kind: 'message', messageId: generateId(), role: 'agent', parts: [{ kind: 'text', text: 'Partial result...' }], }) ``` ### Signal Completion ```typescript theme={null} eventBus.finished() // Must call when done ``` ## Start A2A Server Start the complete A2A server with payment integration: ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Build agent card const agentCard = Payments.a2a.buildPaymentAgentCard( { name: 'Weather Agent', description: 'Weather forecasts and analysis', version: '1.0.0', protocolVersion: '0.3.0', url: 'http://localhost:6000/a2a/', capabilities: { streaming: true, pushNotifications: false }, defaultInputModes: ['text'], defaultOutputModes: ['text'], skills: [], }, { agentId: process.env.NVM_AGENT_ID!, planId: process.env.NVM_PLAN_ID!, credits: 5, paymentType: 'fixed', } ) // Define executor const executor = { async execute(context, eventBus) { const taskId = context.task?.id eventBus.publish({ kind: 'status-update', taskId, status: { state: 'working' }, final: false, }) // Your logic here const result = await processTask(context) eventBus.publish({ kind: 'status-update', taskId, status: { state: 'completed', message: { role: 'agent', parts: [{ kind: 'text', text: result }] }, }, final: true, metadata: { creditsUsed: 5 }, }) eventBus.finished() }, async cancelTask(taskId, eventBus) { // Handle cancellation }, } // Start server const { server, close } = await payments.a2a.start({ agentCard, executor, port: 6000, basePath: '/a2a/', exposeAgentCard: true, // Expose /.well-known/agent-card.json (+ legacy /.well-known/agent.json alias) exposeDefaultRoutes: true, // Expose health and info routes }) console.log('A2A Server running on port 6000') // Graceful shutdown process.on('SIGINT', async () => { await close() console.log('Server stopped') process.exit(0) }) ``` > 🔐 **Run behind a reverse proxy with HTTPS in production.** A2A peers exchange paid tokens — in band via `x402.payment.payload`, or over the deprecated `payment-signature` header — so never expose the raw server on a public hostname without TLS. Bind the dev server to `127.0.0.1` (e.g. by running it inside a container with no published port, or behind a localhost-bound proxy). ## Credit Reporting The executor reports credits used in the final status update: ### Fixed Credits ```typescript theme={null} eventBus.publish({ kind: 'status-update', taskId, status: { state: 'completed', message: {...} }, final: true, metadata: { creditsUsed: 5 }, // Always 5 credits }) ``` ### Dynamic Credits Calculate credits based on actual usage: ```typescript theme={null} async execute(context, eventBus) { const taskId = context.task?.id // Execute task const result = await processTask(context) // Calculate credits based on result const creditsUsed = calculateCredits(result) eventBus.publish({ kind: 'status-update', taskId, status: { state: 'completed', message: {...} }, final: true, metadata: { creditsUsed }, // Variable credits }) eventBus.finished() } function calculateCredits(result: string): number { // Example: charge based on response length return Math.ceil(result.length / 1000) // 1 credit per KB } ``` ## Streaming Example For long-running tasks, stream partial results: ```typescript theme={null} const executor = { async execute(context, eventBus) { const taskId = context.task?.id eventBus.publish({ kind: 'status-update', taskId, status: { state: 'working' }, final: false, }) // Stream partial results const chunks = await processInChunks(context) for (const chunk of chunks) { eventBus.publish({ kind: 'message', messageId: generateId(), role: 'agent', parts: [{ kind: 'text', text: chunk }], }) } // Final result eventBus.publish({ kind: 'status-update', taskId, status: { state: 'completed', message: { role: 'agent', parts: [{ kind: 'text', text: 'Done!' }] }, }, final: true, metadata: { creditsUsed: 5 }, }) eventBus.finished() }, } ``` ## Complete Example: Weather A2A Agent ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Build agent card const agentCard = Payments.a2a.buildPaymentAgentCard( { name: 'Weather Forecast Agent', description: 'Get weather forecasts for any location', version: '1.0.0', protocolVersion: '0.3.0', url: 'http://localhost:6000/a2a/', capabilities: { streaming: true, pushNotifications: false, }, defaultInputModes: ['text'], defaultOutputModes: ['text'], skills: [ { name: 'weather_forecast', description: 'Get weather forecast', }, ], }, { agentId: process.env.NVM_AGENT_ID!, planId: process.env.NVM_PLAN_ID!, credits: 3, paymentType: 'fixed', costDescription: '3 credits per forecast request', } ) // Implement executor const executor = { async execute(context, eventBus) { const taskId = context.task?.id // Extract user message const userMessage = context.history?.[0] const prompt = userMessage?.parts?.find(p => p.kind === 'text')?.text if (!prompt) { eventBus.publish({ kind: 'status-update', taskId, status: { state: 'failed', message: { role: 'agent', parts: [{ kind: 'text', text: 'No prompt provided' }], }, }, final: true, }) eventBus.finished() return } // Emit working status eventBus.publish({ kind: 'status-update', taskId, status: { state: 'working' }, final: false, }) try { // Process weather request const city = extractCity(prompt) const forecast = await getWeatherForecast(city) // Emit completion eventBus.publish({ kind: 'status-update', taskId, status: { state: 'completed', message: { role: 'agent', parts: [{ kind: 'text', text: formatForecast(forecast) }], }, }, final: true, metadata: { creditsUsed: 3 }, }) } catch (error) { eventBus.publish({ kind: 'status-update', taskId, status: { state: 'failed', message: { role: 'agent', parts: [{ kind: 'text', text: `Error: ${error.message}` }], }, }, final: true, }) } eventBus.finished() }, async cancelTask(taskId, eventBus) { eventBus.publish({ kind: 'status-update', taskId, status: { state: 'canceled' }, final: true, }) eventBus.finished() }, } // Start server const { server, close } = await payments.a2a.start({ agentCard, executor, port: 6000, basePath: '/a2a/', }) console.log('Weather A2A Agent running on http://localhost:6000/a2a/') console.log('Agent card: http://localhost:6000/a2a/.well-known/agent-card.json') // Graceful shutdown process.on('SIGINT', async () => { console.log('Shutting down...') await close() process.exit(0) }) // Helper functions function extractCity(prompt: string): string { // Simple extraction logic const match = prompt.match(/weather (?:in|for) (.+)/i) return match?.[1] || 'San Francisco' } async function getWeatherForecast(city: string) { // Mock weather API call return { city, temperature: 72, condition: 'Sunny', forecast: ['Mon: 70°F', 'Tue: 68°F', 'Wed: 73°F'], } } function formatForecast(forecast: any): string { return `Weather in ${forecast.city}: Current: ${forecast.temperature}°F, ${forecast.condition} Forecast: ${forecast.forecast.join(', ')}` } ``` ## Server Configuration Options ```typescript theme={null} const { server, close } = await payments.a2a.start({ agentCard, // Payment agent card (required) executor, // Task executor (required) port: 6000, // Server port (required) basePath: '/a2a/', // Base path (optional, default: '/') exposeAgentCard: true, // Expose /.well-known/agent-card.json + legacy alias (optional) exposeDefaultRoutes: true, // Expose /health, /info (optional) paymentsService: payments, // Custom payments instance (optional) handlerOptions: { asyncExecution: false, // Async task execution (optional) defaultBatch: false, // Batch credit settlement (optional) defaultMarginPercent: 5, // Add 5% margin to credits (optional) }, }) ``` ## Best Practices 1. **Always Report Credits**: Include `creditsUsed` in final status updates 2. **Handle Errors**: Emit 'failed' status on errors 3. **Signal Completion**: Always call `eventBus.finished()` 4. **Streaming for Long Tasks**: Use message events for real-time updates 5. **Graceful Shutdown**: Implement proper server cleanup 6. **Descriptive Agent Cards**: Provide clear descriptions and skills 7. **Version Control**: Include version in agent card metadata ## Related Documentation * [Agents](./agents) - Register your A2A agent in Nevermined * [Payment Plans](./payment-plans) - Configure pricing for your agent * [Validation of Requests](./validation-of-requests) - Understanding credit settlement *** **Source References**: * `RUN.md` (A2A Server section, lines 88-156) * `src/a2a/server.ts` (PaymentsA2AServer) * `src/a2a/agent-card.ts` (buildPaymentAgentCard) * `tests/integration/a2a/complete-message-send-flow.test.ts` (executor patterns) * `tests/e2e/helpers/a2a-setup-helpers.ts` (setup examples) # Agents Source: https://nevermined.ai/docs/api-reference/typescript/agents Register and manage AI agents with payment plans, metadata, and API endpoints # Agents The Agents API allows AI builders to register their AI agents with the Nevermined protocol, making them discoverable and accessible through payment plans. ## Overview of Agents API The Agents API (`payments.agents`) enables you to: * Register AI agents with metadata and API endpoints * Associate agents with one or more payment plans * Register agents and plans together in a single operation * Update agent metadata and configuration * Retrieve agent information * Manage plan associations (add/remove plans from agents) ## Agent Metadata Structure Agents require metadata for discovery and identification: ```typescript theme={null} import { AgentMetadata } from '@nevermined-io/payments' const agentMetadata: AgentMetadata = { name: 'Weather AI Agent', description: 'Provides real-time weather forecasts and climate data', tags: ['weather', 'forecast', 'climate'], dateCreated: new Date(), author: 'Your Company Name', // Additional metadata fields... } ``` ## Agent API Configuration `AgentAPIAttributes` describes how requests to your agent are authenticated and (optionally) which routes are gated by your Payment Plan. **All fields are optional.** ### Minimal (recommended) Most builders only need to configure how the agent is authenticated. If you integrate with the Payments library and gate paid routes via library annotations or middleware, you do **not** need to declare endpoints or an OpenAPI URL at registration time. ```typescript theme={null} import { AgentAPIAttributes } from '@nevermined-io/payments' const agentApi: AgentAPIAttributes = { authType: 'bearer', token: process.env.AGENT_BEARER_TOKEN, } ``` ### With Additional Security (opt-in) If you want the Nevermined platform to enforce a route-level allowlist (defense-in-depth on top of your library-level gating), provide `endpoints`. You can also provide `agentDefinitionUrl` to publish a discoverable OpenAPI / MCP / A2A descriptor. ```typescript theme={null} const agentApi: AgentAPIAttributes = { authType: 'bearer', token: process.env.AGENT_BEARER_TOKEN, // Additional Security: only requests matching this allowlist are accepted by // the Nevermined platform's x402 verification service. Omitted = allow-all (default). endpoints: [ { POST: 'https://api.example.com/v1/agents/:agentId/tasks' }, { GET: 'https://api.example.com/v1/agents/:agentId/tasks/:taskId' }, ], openEndpoints: ['https://api.example.com/v1/health'], // Optional: discoverable agent definition (OpenAPI / MCP Manifest / A2A card). agentDefinitionUrl: 'https://api.example.com/openapi.json', } ``` > **Migration note:** agents registered before endpoint and agent definition fields became optional may still have these fields populated and will continue to enforce the allowlist as before. Nothing changes for them. Use the Edit Agent screen on app.nevermined.app to add or remove the configuration. ### Endpoint Patterns (Additional Security) When you opt in to the allowlist, you can use path parameters in your endpoint definitions: ```typescript theme={null} const agentApi: AgentAPIAttributes = { endpoints: [ { POST: 'https://api.example.com/agents/:agentId/query' }, { GET: 'https://api.example.com/agents/:agentId/status' }, { POST: 'https://api.example.com/agents/:agentId/tasks/:taskId/cancel' }, ], } ``` ## Register Agents ### Register Agent with Existing Plans If you've already registered payment plans, you can register an agent and associate it with those plans: ```typescript theme={null} import { Payments, AgentMetadata, AgentAPIAttributes } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox', }) // Define agent metadata const agentMetadata: AgentMetadata = { name: 'Weather Forecast Agent', description: 'Get accurate weather forecasts for any location', tags: ['weather', 'forecast', 'api'], } // Configure API authentication. endpoints + agentDefinitionUrl are // optional — see "Additional Security (opt-in)" above. const agentApi: AgentAPIAttributes = { authType: 'bearer', token: process.env.AGENT_BEARER_TOKEN, } // Register agent with existing plans const { agentId } = await payments.agents.registerAgent( agentMetadata, agentApi, [planId1, planId2] // Array of plan IDs ) console.log(`Agent registered with ID: ${agentId}`) ``` ### Register Agent and Plan Together For convenience, you can register both an agent and its payment plan in a single operation: ```typescript theme={null} import { Payments, AgentMetadata, AgentAPIAttributes, PlanMetadata } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox', }) const builderAddress = payments.getAccountAddress() const ERC20_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' // Define plan const planMetadata: PlanMetadata = { name: 'Weather Agent Access Plan', description: 'Get 1000 credits to access weather data', } const priceConfig = payments.plans.getCryptoPriceConfig( 10_000_000n, builderAddress, ERC20_ADDRESS ) const creditsConfig = payments.plans.getFixedCreditsConfig(1000n, 1n) // Define agent const agentMetadata: AgentMetadata = { name: 'Weather Forecast Agent', description: 'Real-time weather forecasts powered by AI', tags: ['weather', 'ai', 'forecast'], } const agentApi: AgentAPIAttributes = { authType: 'bearer', token: process.env.AGENT_BEARER_TOKEN, // Optional: opt in to platform-enforced route allowlist. See // "Additional Security (opt-in)" above. // endpoints: [ // { POST: 'https://weather-api.example.com/v1/agents/:agentId/tasks' }, // ], } // Register both together const { agentId, planId } = await payments.agents.registerAgentAndPlan( agentMetadata, agentApi, planMetadata, priceConfig, creditsConfig ) console.log(`Agent ID: ${agentId}`) console.log(`Plan ID: ${planId}`) ``` ## Retrieve Agents ### List Your Agents List the agents **you** published — the authenticated caller's own agents. This is account management, not a marketplace search: it never returns other users' agents. Pass an `orgId` to list every agent in an organization you belong to. ```typescript theme={null} // Your own agents (paginated: { total, page, offset, agents }) const { agents } = await payments.agents.getAgents() agents.forEach((agent) => { console.log(`${agent.name}: ${agent.agentId}`) }) // Every agent in an organization you belong to const { agents: orgAgents } = await payments.agents.getAgents(1, 100, 'created', 'desc', 'org-acme') ``` ### Get a Specific Agent ```typescript theme={null} // Get agent details by ID const agent = await payments.agents.getAgent(agentId) console.log(`Name: ${agent.name}`) console.log(`Description: ${agent.description}`) console.log(`Endpoints: ${JSON.stringify(agent.endpoints)}`) ``` ### Get Plans for an Agent ```typescript theme={null} // Get all payment plans associated with an agent const plans = await payments.agents.getAgentPlans(agentId) plans.forEach(plan => { console.log(`Plan: ${plan.name} (${plan.planId})`) }) ``` ## Update Agent Metadata You can update agent metadata and API configuration after registration. This is also where builders typically **opt in to Additional Security** by adding an `endpoints` allowlist or an `agentDefinitionUrl` to an existing agent: ```typescript theme={null} // Update agent information and opt in to the route-level allowlist. await payments.agents.updateAgentMetadata( agentId, { description: 'Updated description with new features', tags: ['weather', 'forecast', 'climate', 'ai-powered'], }, { // Adding `endpoints` activates the platform-enforced allowlist. // Do not use `endpoints: []` to mean "allow all": a configured-but-empty // allowlist is treated as deny-all unless `openEndpoints` matches, // preserving legacy semantics. Only include `endpoints` when you want // the allowlist to be enforced. endpoints: [ { POST: 'https://weather-api.example.com/v2/agents/:agentId/forecast' }, { GET: 'https://weather-api.example.com/v2/agents/:agentId/history' }, { GET: 'https://weather-api.example.com/v2/agents/:agentId/alerts' }, ], agentDefinitionUrl: 'https://weather-api.example.com/openapi.json', } ) console.log('Agent updated successfully') ``` ## Manage Agent Plans ### Add Plans to an Agent Associate additional payment plans with an existing agent: ```typescript theme={null} // Add new plans to an agent await payments.agents.addPlanToAgent(newPlanId, agentId) console.log(`Added plan ${newPlanId} to agent ${agentId}`) ``` ### Remove Plans from an Agent Remove payment plan associations: ```typescript theme={null} // Remove a plan from an agent await payments.agents.removePlanFromAgent(planIdToRemove, agentId) console.log(`Removed plan ${planIdToRemove} from agent ${agentId}`) ``` ## Authentication Types The Agents API supports multiple authentication types: ```typescript theme={null} // No authentication required const agentApi = { endpoints: [{ GET: 'https://api.example.com/public' }], authType: 'none', } // Basic authentication const agentApi = { endpoints: [{ POST: 'https://api.example.com/agent' }], authType: 'basic', } // Bearer token (most common for AI agents) const agentApi = { endpoints: [{ POST: 'https://api.example.com/agent' }], authType: 'bearer', // X402 access token in Authorization header } // OAuth const agentApi = { endpoints: [{ POST: 'https://api.example.com/agent' }], authType: 'oauth', } ``` ## Complete Example: Multi-Endpoint Agent ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' import { AgentMetadata, AgentAPIAttributes } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Comprehensive agent configuration const agentMetadata: AgentMetadata = { name: 'Advanced Weather AI', description: 'Multi-modal weather analysis with forecasts, alerts, and historical data', tags: ['weather', 'forecast', 'climate', 'alerts', 'ai'], author: 'Weather Tech Inc.', dateCreated: new Date(), } const agentApi: AgentAPIAttributes = { endpoints: [ { POST: 'https://api.weather-tech.com/v1/agents/:agentId/forecast' }, { GET: 'https://api.weather-tech.com/v1/agents/:agentId/forecast/:forecastId' }, { POST: 'https://api.weather-tech.com/v1/agents/:agentId/alerts' }, { GET: 'https://api.weather-tech.com/v1/agents/:agentId/history' }, { DELETE: 'https://api.weather-tech.com/v1/agents/:agentId/alerts/:alertId' }, ], openEndpoints: [ 'https://api.weather-tech.com/v1/health', 'https://api.weather-tech.com/v1/status', ], authType: 'bearer', agentDefinitionUrl: 'https://api.weather-tech.com/openapi.json', } // Register with multiple plans const { agentId } = await payments.agents.registerAgent( agentMetadata, agentApi, [basicPlanId, proPlanId, enterprisePlanId] ) console.log(`Advanced agent registered: ${agentId}`) // Retrieve and verify const agent = await payments.agents.getAgent(agentId) const { plans, total, page, offset } = await payments.agents.getAgentPlans(agentId) console.log(`Agent has ${plans.length} plans on page ${page} (offset ${offset}, total ${total})`) ``` ## Best Practices 1. **Descriptive Metadata**: Use clear names and descriptions for better discoverability 2. **Relevant Tags**: Add tags that help users find your agent 3. **RESTful Endpoints**: Follow REST conventions for endpoint paths 4. **OpenAPI Specs**: Provide agent definition URLs for better integration 5. **Multiple Plans**: Offer different pricing tiers for various use cases 6. **Bearer Auth**: Use bearer token authentication for secure access ## Related Documentation * [Payment Plans](./payment-plans) - Create plans to associate with agents * [Publishing Static Resources](./publishing-static-resources) - Register static content agents * [Validation of Requests](./validation-of-requests) - Validate incoming agent requests *** **Source References**: * `src/api/agents-api.ts` (Agents API methods) * `tests/e2e/test_payments_e2e.test.ts` (lines 373-449) * `tests/e2e/test_x402_e2e.test.ts` (agent registration examples) # Getting Started Source: https://nevermined.ai/docs/api-reference/typescript/initializing-the-library Initialize the Payments SDK in Node.js and browser environments with your API key # Initializing the Library This guide shows how to initialize the Nevermined Payments Library in your application. The library supports both server-side (Node.js) and browser environments with different initialization methods. ## Get Your NVM API Key Before initializing the library, you need a Nevermined API key: 1. Visit [nevermined.app](https://nevermined.app) 2. Sign in or create a free account 3. Navigate to your profile settings 4. Generate an API key **Important**: There are two types of API keys: * **Builder Key**: For AI builders who register agents and payment plans * **Subscriber Key**: For users who purchase access and query agents Most applications will use a builder key for server-side operations. ## Server-Side Initialization For Node.js applications, use the `getInstance` method: ```typescript theme={null} import { Payments } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, }) ``` The environment is derived automatically from your API key — see [Environment derivation](#environment-derivation) below. ### Configuration Options The `getInstance` method accepts a `PaymentOptions` object: ```typescript theme={null} interface PaymentOptions { nvmApiKey: string // Your Nevermined API key (required) environment?: EnvironmentName // @deprecated — derived from the API key (optional) returnUrl?: string // OAuth callback URL (optional, for browser) appId?: string // Your application ID (optional) version?: string // Backend API version pin, MAJOR.MINOR (optional) } ``` ### Environment derivation NVM API keys are prefixed with the environment they belong to (`:`), so the SDK resolves the target environment from the key — you no longer need to pass `environment`. The `environment` option is **deprecated** but still accepted: * When the key prefix maps to a known environment, the **key always wins** and the `environment` option is ignored (a one-time deprecation warning is logged). * When the key has no recognized prefix (for example a local/custom build), the SDK falls back to the `environment` option, and finally to `custom`. This keeps local and custom-backend workflows working unchanged. ### Complete Server-Side Example ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' // Initialize with environment variables const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: process.env.NVM_ENVIRONMENT as EnvironmentName, }) // Verify connection const accountAddress = payments.getAccountAddress() console.log(`Connected as: ${accountAddress}`) ``` ## Browser Initialization For browser-based applications, use the `getBrowserInstance` method: ```typescript theme={null} import { Payments } from '@nevermined-io/payments' const payments = Payments.getBrowserInstance({ returnUrl: 'https://myapp.example/callback', environment: 'sandbox', appId: 'my-app', // Optional: pin the backend API version (MAJOR.MINOR). Defaults to the // version this SDK release targets — omit unless you must pin an older one. version: '1.1', }) ``` ### Browser Authentication Flow The browser instance supports OAuth-style authentication: ```typescript theme={null} // Check if user is logged in if (!payments.isLoggedIn) { // Redirect to Nevermined login payments.connect() } // After login, use the payments instance const balance = await payments.plans.getPlanBalance(planId) // Logout when needed payments.logout() ``` ## Environments The Nevermined protocol supports multiple environments: ### Production Environments | Environment | Description | Usage | | - | - | - | | `sandbox` | Production testing environment | Development and testing with real blockchain | | `live` | Production environment | Live agents and real payments | ### Choosing an Environment ```typescript theme={null} // Development and testing const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox', }) // Production deployment const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'live', }) ``` **Important**: Agents and plans registered in one environment cannot be accessed from another. Always use the same environment throughout your application. ## Environment Configuration Details Each environment has specific API endpoints: ```typescript theme={null} // Example environment structure interface EnvironmentInfo { frontend: string // Nevermined App URL backend: string // API URL proxy: string // Proxy service URL heliconeUrl: string // Observability service URL } ``` The library automatically configures these endpoints based on your chosen environment. ## Verify Connection After initialization, verify the connection is working: ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Get account address from API key const accountAddress = payments.getAccountAddress() console.log(`Initialized for account: ${accountAddress}`) // For browser instances if (payments.isLoggedIn) { console.log('User authenticated successfully') } ``` ## Best Practices 1. **Environment Variables**: Always store API keys in environment variables, never hardcode them 2. **Singleton Pattern**: Create one Payments instance per application 3. **Environment Consistency**: Use the same environment for all operations in a session 4. **Error Handling**: Wrap initialization in try-catch blocks for production apps ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' let payments: Payments try { payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: process.env.NVM_ENVIRONMENT as EnvironmentName, }) console.log('✓ Nevermined Payments initialized') } catch (error) { console.error('Failed to initialize Payments:', error) process.exit(1) } ``` ## Related Documentation * [Payment Plans](./payment-plans) * [Agents](./agents) *** **Source References**: * `src/payments.ts` (getInstance, getBrowserInstance methods) * `src/environments.ts` (environment configurations) * `tests/e2e/fixtures.ts` (createPaymentsBuilder, createPaymentsSubscriber) # Installation Source: https://nevermined.ai/docs/api-reference/typescript/installation Install and configure the @nevermined-io/payments TypeScript SDK for monetizing AI agents # Installation The Nevermined Payments Library is a TypeScript SDK that enables AI builders and subscribers to monetize and access AI agents through the Nevermined protocol. The library supports flexible payment plans (credits and time-based), multiple payment methods (crypto and fiat), and seamless integration with AI agent frameworks. ## Overview The Payments Library provides: * Registration and discovery of AI agents with payment plans * Flexible pricing options (fixed per request or dynamic usage-based) * Credit-based access control with on-chain settlement * Support for browser and Node.js environments * Integration with MCP (Model Context Protocol) and A2A (Agent-to-Agent) protocols ## Prerequisites Before installing the Nevermined Payments Library, ensure you have: * **Node.js**: Version 18.x or higher * **TypeScript**: Version 5.x or higher (recommended) * **Nevermined API Key**: Get your free API key from [nevermined.app](https://nevermined.app) * **Package Manager**: npm (included with Node.js) or pnpm ## Installation Install the library using npm or pnpm. Pin the major version (or use a lockfile-tracked exact version) so SDK upgrades are explicit and reviewable: ```bash theme={null} # Using npm npm install @nevermined-io/payments@^1.1 # Using pnpm pnpm add @nevermined-io/payments@^1.1 ``` > 🔐 **Security:** always commit your `package-lock.json` / `pnpm-lock.yaml` and review SDK version bumps before deploying. Running unpinned installs in production lets transitive dependencies change between deploys. ### Peer Dependencies The library has optional peer dependencies for specific integrations: ```bash theme={null} # For MCP (Model Context Protocol) integration npm install @modelcontextprotocol/sdk # For Express-based HTTP agents npm install express @types/express ``` These dependencies are only required if you're using the respective integration features. ## Verify Installation After installation, verify the library is correctly installed by importing it: ```typescript theme={null} import { Payments } from '@nevermined-io/payments' console.log('Nevermined Payments Library installed successfully!') ``` You can also check the installed version: ```bash theme={null} npm list @nevermined-io/payments ``` ## Next Steps After successful installation: 1. Get your Nevermined API key from [nevermined.app](https://nevermined.app) 2. Choose your environment (sandbox for testing, live for production) 3. Initialize the Payments instance in your application Continue to [Initializing the Library](./initializing-the-library) to get started. *** **Source References**: * `package.json` * `README.md` # MCP Integration Source: https://nevermined.ai/docs/api-reference/typescript/mcp-integration Build payment-protected MCP servers with OAuth 2.1 authentication and automatic credit management # MCP Integration The Model Context Protocol (MCP) integration provides a complete payment-protected MCP server with OAuth 2.1 support and automatic credit management. This is the simplest way to run a payment-protected AI agent. ## Overview of MCP Integration The MCP integration automatically handles: * **OAuth 2.1 Discovery**: Auto-configured `.well-known` endpoints * **Paywall Protection**: Automatic token verification and credit burning * **Streaming Support**: SSE (Server-Sent Events) for streaming responses * **Credit Management**: Fixed or dynamic credit costs per tool/resource/prompt * **Client Registration**: Dynamic client registration for OAuth flows ## OAuth 2.1 Discovery When you start an MCP server, the library automatically exposes OAuth 2.1 discovery endpoints required by the X402 spec: | Endpoint | Description | | - | - | | `/.well-known/oauth-protected-resource` | Protected resource metadata | | `/.well-known/oauth-authorization-server` | Authorization server metadata | | `/.well-known/openid-configuration` | OpenID Connect discovery | | `POST /register` | Dynamic client registration | These endpoints are generated automatically—no manual configuration required. ## Configure MCP Initialize the MCP integration with your plan details: ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Configure MCP integration payments.mcp.configure({ planId: process.env.NVM_PLAN_ID!, agentId: process.env.NVM_AGENT_ID, // optional — informational only serverName: 'my-mcp-server', }) ``` > **`planId` is required; `agentId` is optional.** The x402 facilitator is > plan-centric — verify/settle resolve everything from the plan and the > subscriber's token. `agentId` is informational only (it also populates the > OAuth `client_id` when present). A per-tool `planId` option overrides the > server-level plan. ## Register Tools with Credits Register MCP tools and specify their credit cost: ```typescript theme={null} import { z } from 'zod' // Register a tool with fixed credit cost payments.mcp.registerTool( 'get_weather', // Tool name { title: 'Get Weather', description: 'Get current weather for a city', inputSchema: z.object({ city: z.string().describe('City name'), }), }, async (args) => { // Handler function // Your tool logic here const weather = await getWeatherData(args.city) return { content: [{ type: 'text', text: `Weather in ${args.city}: ${weather}` }], } }, { credits: 1n }, // Fixed: 1 credit per call ) ``` ### Dynamic Credit Calculation For variable costs based on input/output: ```typescript theme={null} payments.mcp.registerTool( 'analyze_text', { title: 'Analyze Text', description: 'Perform text analysis', inputSchema: z.object({ text: z.string(), }), }, async (args) => { const analysis = await analyzeText(args.text) return { content: [{ type: 'text', text: JSON.stringify(analysis) }], } }, { // Dynamic credits based on text length credits: (ctx) => { const { text } = ctx.args as { text: string } const textLength = text.length return BigInt(Math.ceil(textLength / 1000)) // 1 credit per KB }, }, ) ``` ## Register Resources Register MCP resources with payment protection: ```typescript theme={null} payments.mcp.registerResource( 'weather-data', // Resource name 'weather://current', // Resource URI { title: 'Current Weather Data', description: 'Real-time weather information', }, async (uri, vars) => { // Handler function const data = await fetchWeatherData() return { contents: [ { uri: 'weather://current', mimeType: 'application/json', text: JSON.stringify(data), }, ], } }, { credits: 2n }, // 2 credits per access ) ``` ## Register Prompts Register MCP prompts with credit costs: ```typescript theme={null} payments.mcp.registerPrompt( 'weather-query', // Prompt name { title: 'Weather Query Template', description: 'Generate weather queries', }, async (args) => { // Handler function return { messages: [ { role: 'user', content: { type: 'text', text: `What is the weather in ${args.city}?`, }, }, ], } }, { credits: 1n }, // 1 credit per prompt ) ``` ## Start Managed Server Start a complete MCP server with all endpoints configured: ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Configure payments.mcp.configure({ planId: process.env.NVM_PLAN_ID!, agentId: process.env.NVM_AGENT_ID, // optional — informational only serverName: 'weather-server', }) // Register tools payments.mcp.registerTool( 'get_weather', { title: 'Get Weather', description: 'Get current weather', inputSchema: z.object({ city: z.string(), }), }, async (args) => ({ content: [{ type: 'text', text: `Weather in ${args.city}: Sunny` }], }), { credits: 1n }, ) // Start server (bind to localhost by default; expose via a reverse proxy with HTTPS for public traffic) const { info, stop } = await payments.mcp.start({ port: 5001, host: process.env.MCP_HOST ?? '127.0.0.1', planId: process.env.NVM_PLAN_ID!, agentId: process.env.NVM_AGENT_ID, // optional — informational only serverName: 'weather-server', version: '1.0.0', }) console.log(`MCP Server running at: ${info.baseUrl}`) console.log(`MCP endpoint: ${info.baseUrl}/mcp`) // Graceful shutdown process.on('SIGINT', async () => { await stop() console.log('Server stopped') process.exit(0) }) ``` > 🔐 **Bind to localhost in development.** The MCP server holds an OAuth issuer and accepts paid requests — exposing it directly on `0.0.0.0` is rarely what you want. Bind to `127.0.0.1` and front it with a reverse proxy (Caddy, nginx, Traefik) terminating TLS for any public traffic. ## MCP Logical URIs When registering your agent at [nevermined.app](https://nevermined.app), use MCP logical URIs instead of HTTP URLs: ### URI Format ``` mcp://// ``` ### Examples | Type | URI | Description | | - | - | - | | Tool | `mcp://weather-server/tools/get_weather` | Single tool | | Tool Wildcard | `mcp://weather-server/tools/*` | All tools | | Resource | `mcp://weather-server/resources/weather://current` | Single resource | | Resource Wildcard | `mcp://weather-server/resources/*` | All resources | | Prompt | `mcp://weather-server/prompts/weather-query` | Single prompt | ### Wildcard Registration Use wildcards to register all tools/resources/prompts at once: ``` mcp://weather-server/tools/* mcp://weather-server/resources/* mcp://weather-server/prompts/* ``` ## Auto-Configured Endpoints The `start()` method automatically creates these endpoints: ``` POST /mcp - MCP JSON-RPC endpoint GET /mcp - SSE streaming endpoint DELETE /mcp - Session cleanup GET / - Server info GET /health - Health check GET /.well-known/oauth-protected-resource GET /.well-known/oauth-authorization-server GET /.well-known/openid-configuration POST /register - Dynamic client registration ``` ## Complete Example: Weather Agent ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' import { z } from 'zod' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Configure MCP payments.mcp.configure({ planId: process.env.NVM_PLAN_ID!, agentId: process.env.NVM_AGENT_ID, // optional — informational only serverName: 'weather-agent', }) // Register multiple tools payments.mcp.registerTool( 'get_current_weather', { title: 'Get Current Weather', description: 'Get real-time weather for a location', inputSchema: z.object({ city: z.string(), country: z.string().optional(), }), }, async (args) => { const weather = await fetchWeather(args.city, args.country) return { content: [{ type: 'text', text: JSON.stringify(weather) }], } }, { credits: 1n }, ) payments.mcp.registerTool( 'get_forecast', { title: 'Get Weather Forecast', description: 'Get 7-day weather forecast', inputSchema: z.object({ city: z.string(), days: z.number().min(1).max(7).default(3), }), }, async (args) => { const forecast = await fetchForecast(args.city, args.days) return { content: [{ type: 'text', text: JSON.stringify(forecast) }], } }, { credits: 2n }, // Forecasts cost more ) // Register resource payments.mcp.registerResource( 'weather-alerts', 'weather://alerts', { title: 'Weather Alerts', description: 'Active weather alerts', }, async (uri) => { const alerts = await fetchAlerts() return { contents: [ { uri: 'weather://alerts', mimeType: 'application/json', text: JSON.stringify(alerts), }, ], } }, { credits: 1n }, ) // Start server (bind to localhost by default; front with HTTPS reverse proxy for public traffic) const { info, stop } = await payments.mcp.start({ port: 5001, host: process.env.MCP_HOST ?? '127.0.0.1', planId: process.env.NVM_PLAN_ID!, agentId: process.env.NVM_AGENT_ID, // optional — informational only serverName: 'weather-agent', version: '1.0.0', }) console.log(`Weather MCP Agent running at ${info.baseUrl}`) console.log(`Register in Nevermined App with:`) console.log(` - mcp://weather-agent/tools/*`) console.log(` - mcp://weather-agent/resources/*`) // Graceful shutdown process.on('SIGINT', async () => { await stop() process.exit(0) }) // Mock functions async function fetchWeather(city: string, country?: string) { return { city, temp: 72, condition: 'sunny' } } async function fetchForecast(city: string, days: number) { return { city, days, forecast: [] } } async function fetchAlerts() { return { alerts: [] } } ``` ## Handler Options | Option | Type | Description | | - | - | - | | `credits` | `bigint` or `function` | Credits to consume per call | | `planId` | `string` | Per-handler plan ID override. A server-level `planId` (set via `configure`/`start`) is required; set this only to charge a different plan for this handler. | | `maxAmount` | `bigint` | Max credits to verify during authentication (default: `1n`) | | `onRedeemError` | `string` | On post-execution settlement failure: `'ignore'` (default) returns the in-band payment error; `'propagate'` throws a JSON-RPC error. Tool content is always suppressed either way (paid content is never delivered without settlement). | ## In-band x402 signaling (`_meta`) The MCP transport follows the [x402 v2 MCP transport spec](https://github.com/coinbase/x402/blob/main/specs/transports-v2/mcp.md): payments are signaled **in band** through the MCP tool-call machinery, not via HTTP status codes or headers. ### Request — payment payload The client sends the x402 `PaymentPayload` in the request params `_meta["x402/payment"]` (plain JSON). Note this is the **payment** channel — separate from session auth: the MCP session is an OAuth-protected resource, so the client must also send an `Authorization: Bearer ` header on the transport to establish the session (`initialize` returns `401` without it). For backwards compatibility the server also reads the payment from that header alone (no `_meta`) as a **deprecated fallback** for one release. ```typescript theme={null} import { decodeAccessToken } from '@nevermined-io/payments' // Mint a token against a delegation (create one first). `agentId` (2nd arg) is // optional, but `delegationConfig` is required. const { delegationId } = await payments.delegation.createDelegation({ provider: 'erc4337', // 'stripe' | 'braintree' | 'visa' for fiat plans spendingLimitCents: 10000, durationSecs: 604800, currency: 'usdc', // 'usd' for fiat plans }) const { accessToken } = await payments.x402.getX402AccessToken(planId, undefined, { delegationConfig: { delegationId }, }) await client.callTool({ name: 'get_weather', arguments: { city: 'Madrid' }, // Carry the payment in band (the spec-defined transport): _meta: { 'x402/payment': decodeAccessToken(accessToken) }, }) ``` ### Response — settlement receipt On a successful paid call, the SDK injects the settlement receipt under `_meta["x402/payment-response"]` (the spec key), and Nevermined-specific observability under a namespaced `_meta["nevermined/credits"]` key: ```typescript theme={null} { content: [{ type: 'text', text: 'result' }], _meta: { // Spec-defined settlement receipt (x402 v2 MCP transport) 'x402/payment-response': { success: true, transaction: '0xabc...', network: 'eip155:84532', payer: '0x123...', creditsRedeemed: '5', remainingBalance: '95', }, // Nevermined-namespaced observability (NOT part of the x402 spec) 'nevermined/credits': { success: true, txHash: '0xabc...', creditsRedeemed: '5', planId: 'plan-123', subscriberAddress: '0x123...', }, } } ``` Free / no-credit calls omit the `x402/payment-response` key (no settlement occurred); `nevermined/credits` is still attached with `creditsRedeemed: '0'`. ### Payment required When payment is required (missing/invalid token, or no subscription), the tool returns an **error tool result** carrying the x402 `PaymentRequired` object — there is no HTTP `402` on `/mcp`: ```typescript theme={null} { isError: true, structuredContent: { x402Version: 2, error: 'payment required', resource: { /* ... */ }, accepts: [ /* ... */ ] }, content: [{ type: 'text', text: '' }], } ``` Both `structuredContent` (the object) and `content[0].text` (its JSON string) are populated, per spec. This applies to **tools** only — resources and prompts raise a JSON-RPC error instead (they have no tool-result error channel). ## Error Handling Payment-required is signaled **in band** as an error tool result (see above) — there is no HTTP `402` on `/mcp`. OAuth and payment-required live at different layers and never collide: OAuth rejects at the HTTP layer (`401`), while payment-required is an MCP tool-call result. The in-band shape inherently disambiguates the two. `onRedeemError` controls only the *error type* surfaced when settlement fails **after** the tool executed — it no longer controls whether content is returned. Per the spec, a paid result is never delivered without settlement landing, so the executed tool's content is always suppressed on settlement failure. `'ignore'` (default) surfaces the in-band payment error; `'propagate'` throws a JSON-RPC misconfiguration error. ```typescript theme={null} payments.mcp.registerTool('premium_tool', toolConfig, handler, { credits: 5n, onRedeemError: 'propagate', // throw a JSON-RPC error on settlement failure (default: 'ignore') }) ``` ## Advanced: Custom Express App For existing Express applications, use `createRouter`: ```typescript theme={null} import express from 'express' import { Payments } from '@nevermined-io/payments' const app = express() const payments = Payments.getInstance({...}) payments.mcp.configure({ planId: process.env.NVM_PLAN_ID!, agentId: process.env.NVM_AGENT_ID, // optional — informational only serverName: 'my-server', }) // Register tools... // Create MCP router const mcpRouter = payments.mcp.createRouter({ planId: process.env.NVM_PLAN_ID!, agentId: process.env.NVM_AGENT_ID, // optional — informational only serverName: 'my-server', }) // Mount router app.use('/mcp', mcpRouter) // Your other routes app.get('/custom', (req, res) => { res.json({ status: 'ok' }) }) // Bind to localhost; expose via a reverse proxy with HTTPS for public traffic const server = app.listen(5001, '127.0.0.1') process.on('SIGINT', () => { server.close(() => process.exit(0)) }) ``` ## Best Practices 1. **Descriptive Names**: Use clear tool/resource/prompt names 2. **Schema Validation**: Always define proper input schemas with Zod 3. **Credit Pricing**: Set appropriate credits based on resource cost 4. **Error Messages**: Provide clear error messages in responses 5. **Graceful Shutdown**: Always implement `SIGINT` handlers 6. **Wildcard URIs**: Use wildcards for simpler agent registration 7. **Version Control**: Include version in server configuration ## Related Documentation * [Agents](./agents) - Register your MCP agent in Nevermined * [Payment Plans](./payment-plans) - Configure pricing for your agent * [Validation of Requests](./validation-of-requests) - Understanding the validation flow *** **Source References**: * `RUN.md` (MCP Server section, lines 16-86) * `src/mcp/index.ts` (MCP integration API) * `tests/integration/mcp-integration.test.ts` (integration examples) # Payment Plans Source: https://nevermined.ai/docs/api-reference/typescript/payment-plans Create and manage flexible payment plans with credits, time-based access, and multiple pricing options # Payment Plans Payment plans define how subscribers access your AI agents. The Nevermined Payments Library provides a flexible Plans API for registering different types of plans with various pricing and credit configurations. ## Overview of Payment Plans API The Plans API (`payments.plans`) allows AI builders to: * Define pricing structures (fiat, crypto, ERC20 tokens, or free) * Configure credit allocation (fixed, dynamic, time-based) * Register plans with the Nevermined protocol * Retrieve and manage existing plans * Associate plans with agents ## Types of Payment Plans ### Credits Plans Grant subscribers a specific number of credits to use across multiple requests. Each agent request burns a defined number of credits. **Use cases**: API calls, LLM queries, data processing tasks ### Time Plans Provide unlimited access for a fixed duration. No per-request credit deduction during the validity period. **Use cases**: Subscriptions, unlimited access periods, trial memberships ### Trial Plans Free plans with time limitations, perfect for demos and user onboarding. **Use cases**: Free trials, demonstrations, testing ### Pay-As-You-Go Plans Dynamic pricing where subscribers pay per request without pre-purchasing credits. **Use cases**: Variable usage patterns, enterprise integrations ## Price Configuration The library provides helper functions for different payment methods: ### Crypto Payment (Native Token) ```typescript theme={null} import { Payments } from '@nevermined-io/payments' import { ZeroAddress } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox', }) const builderAddress = payments.getAccountAddress() // Native token pricing (ETH, MATIC, etc.) const priceConfig = payments.plans.getCryptoPriceConfig( 100n, // Amount in wei builderAddress, // Receiver address ZeroAddress // Native token ) ``` ### ERC20 Token Payment ```typescript theme={null} // ERC20 token pricing (USDC, DAI, etc.) const USDC_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' // USDC on Base Sepolia const priceConfig = payments.plans.getERC20PriceConfig( 20n, // Amount in token's smallest unit USDC_ADDRESS, // Token contract address builderAddress // Receiver address ) ``` ### EURC Token Payment (Euro Stablecoin) ```typescript theme={null} // EURC pricing (Euro stablecoin on Base, 6 decimals) const eurcPriceConfig = payments.plans.getEURCPriceConfig( 29_000_000n, // €29.00 in smallest unit (6 decimals) builderAddress // Receiver address ) // Or use a custom EURC address (e.g., testnet) import { EURC_TOKEN_ADDRESS_TESTNET } from '@nevermined-io/payments' const testnetEurcConfig = payments.plans.getEURCPriceConfig( 29_000_000n, builderAddress, EURC_TOKEN_ADDRESS_TESTNET ) ``` ### Fiat Payment (Stripe) ```typescript theme={null} // Fiat pricing in USD (default) const priceConfig = payments.plans.getFiatPriceConfig( 10_000_000n, // Amount in 6-decimal units ($10.00) — NOT cents builderAddress ) // Fiat pricing in EUR import { Currency } from '@nevermined-io/payments' const eurPriceConfig = payments.plans.getFiatPriceConfig( 29_000_000n, // Amount in 6-decimal units (€29.00) — NOT cents builderAddress, Currency.EUR ) ``` > Fiat amounts are in **6-decimal units** (the USDC convention used across the Nevermined protocol), **not** cents — `10_000_000n` = $10.00. The server-side minimum is **$1.00\*\* (`1_000_000n`); smaller amounts are rejected with `BCK.PROTOCOL.0047`. ### Free Plans ```typescript theme={null} // Free plan (no payment required) const priceConfig = payments.plans.getFreePriceConfig() ``` ### Pay-As-You-Go Pricing ```typescript theme={null} // Get template address for PAYG plans const templateAddress = await payments.contracts.getPayAsYouGoTemplateAddress() const priceConfig = payments.plans.getPayAsYouGoPriceConfig( 100n, // Cost per request builderAddress, ZeroAddress, // Token address (optional) templateAddress ) ``` ## Credits Configuration ### Fixed Credits Grants a specific number of credits with a fixed burn rate per request. ```typescript theme={null} import { ONE_DAY_DURATION } from '@nevermined-io/payments' // Grant 100 credits, burn 1 credit per request const creditsConfig = payments.plans.getFixedCreditsConfig( 100n, // Total credits granted 1n // Credits per request ) ``` ### Dynamic Credits Allows variable credit consumption per request within a range. ```typescript theme={null} // Grant 10 credits, burn 1-2 credits per request (agent decides) const creditsConfig = payments.plans.getDynamicCreditsConfig( 10n, // Total credits granted 1n, // Minimum credits per request 2n // Maximum credits per request ) ``` ### Time-Based Credits (Expirable) Provides unlimited access for a fixed duration. ```typescript theme={null} import { ONE_DAY_DURATION, ONE_WEEK_DURATION, ONE_MONTH_DURATION } from '@nevermined-io/payments' // Unlimited access for 24 hours const creditsConfig = payments.plans.getExpirableDurationConfig( ONE_DAY_DURATION // Duration in seconds ) // Other durations const weeklyConfig = payments.plans.getExpirableDurationConfig(ONE_WEEK_DURATION) const monthlyConfig = payments.plans.getExpirableDurationConfig(ONE_MONTH_DURATION) ``` ### Non-Expirable Duration ```typescript theme={null} // Unlimited access with no expiration const creditsConfig = payments.plans.getNonExpirableDurationConfig() ``` ## Registering Plans ### Register a Credits Plan ```typescript theme={null} import { Payments } from '@nevermined-io/payments' import { PlanMetadata } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox', }) const builderAddress = payments.getAccountAddress() const ERC20_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' // Define plan metadata const planMetadata: PlanMetadata = { name: 'Basic AI Agent Access', description: 'Get 100 credits to query our AI agent', } // Configure pricing and credits const priceConfig = payments.plans.getERC20PriceConfig( 20n, ERC20_ADDRESS, builderAddress ) const creditsConfig = payments.plans.getFixedCreditsConfig(100n, 1n) // Register the plan const { planId } = await payments.plans.registerCreditsPlan( planMetadata, priceConfig, creditsConfig ) console.log(`Credits plan registered with ID: ${planId}`) ``` ### Register a Time Plan ```typescript theme={null} import { ONE_DAY_DURATION, PlanMetadata } from '@nevermined-io/payments' const planMetadata: PlanMetadata = { name: '24-Hour Unlimited Access', description: 'Unlimited queries for 24 hours', } const priceConfig = payments.plans.getERC20PriceConfig( 50n, ERC20_ADDRESS, builderAddress ) const creditsConfig = payments.plans.getExpirableDurationConfig(ONE_DAY_DURATION) const { planId } = await payments.plans.registerTimePlan( planMetadata, priceConfig, creditsConfig ) console.log(`Time plan registered with ID: ${planId}`) ``` ### Register a Trial Plan ```typescript theme={null} import { ONE_DAY_DURATION, PlanMetadata } from '@nevermined-io/payments' const planMetadata: PlanMetadata = { name: 'Free 24-Hour Trial', description: 'Try our AI agent free for 24 hours', } // Free pricing const priceConfig = payments.plans.getFreePriceConfig() // Limited duration const creditsConfig = payments.plans.getExpirableDurationConfig(ONE_DAY_DURATION) const { planId } = await payments.plans.registerTimeTrialPlan( planMetadata, priceConfig, creditsConfig ) console.log(`Trial plan registered with ID: ${planId}`) ``` ## Retrieving Plans ### Get a Specific Plan ```typescript theme={null} // Retrieve plan details by ID const plan = await payments.plans.getPlan(planId) console.log(`Plan: ${plan.name}`) console.log(`Price: ${plan.price}`) console.log(`Credits: ${plan.credits}`) ``` ### List Your Plans List the plans **you** published — the authenticated caller's own plans. This is account management, not a marketplace search: it never returns other users' plans. Pass an `orgId` to list every plan in an organization you belong to. ```typescript theme={null} // Your own plans (paginated: { total, page, offset, plans }) const { plans } = await payments.plans.getPlans() plans.forEach((plan) => { console.log(`${plan.name}: ${plan.planId}`) }) // Every plan in an organization you belong to const { plans: orgPlans } = await payments.plans.getPlans(1, 100, 'created', 'desc', 'org-acme') ``` ### Get Plans for an Agent To find plans associated with an agent, use the agents API: ```typescript theme={null} // Get all payment plans associated with an agent const { plans } = await payments.agents.getAgentPlans(agentId) plans.forEach(plan => { console.log(`Plan: ${plan.name} (${plan.planId})`) }) ``` ## Duration Constants The library provides convenient duration constants: ```typescript theme={null} import { ONE_DAY_DURATION, // 86,400 seconds (24 hours) ONE_WEEK_DURATION, // 604,800 seconds (7 days) ONE_MONTH_DURATION, // 2,629,746 seconds (~30.44 days) ONE_YEAR_DURATION // 31,557,600 seconds (~365.25 days) } from '@nevermined-io/payments' ``` ## Complete Example: Multi-Tier Plans ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' import { ONE_DAY_DURATION, ONE_MONTH_DURATION } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) const builderAddress = payments.getAccountAddress() const ERC20_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' // Free trial plan const { planId: trialPlanId } = await payments.plans.registerTimeTrialPlan( { name: 'Free Trial', description: '24 hours free access' }, payments.plans.getFreePriceConfig(), payments.plans.getExpirableDurationConfig(ONE_DAY_DURATION) ) // Basic tier - 100 credits const { planId: basicPlanId } = await payments.plans.registerCreditsPlan( { name: 'Basic Plan', description: '100 credits for basic usage' }, payments.plans.getERC20PriceConfig(10n, ERC20_ADDRESS, builderAddress), payments.plans.getFixedCreditsConfig(100n, 1n) ) // Pro tier - unlimited monthly access const { planId: proPlanId } = await payments.plans.registerTimePlan( { name: 'Pro Plan', description: 'Unlimited access for 30 days' }, payments.plans.getERC20PriceConfig(50n, ERC20_ADDRESS, builderAddress), payments.plans.getExpirableDurationConfig(ONE_MONTH_DURATION) ) console.log('Multi-tier plans created:') console.log(`Trial: ${trialPlanId}`) console.log(`Basic: ${basicPlanId}`) console.log(`Pro: ${proPlanId}`) ``` ## Related Documentation * [Agents](./agents) - Associate plans with agents * [Payments and Balance](./payments-and-balance) - How subscribers order plans *** **Source References**: * `src/plans.ts` (helper functions, duration constants) * `src/api/plans-api.ts` (Plans API methods) * `tests/e2e/test_payments_e2e.test.ts` (lines 277-369) # Payments & Balance Source: https://nevermined.ai/docs/api-reference/typescript/payments-and-balance Purchase payment plans and manage credit balances for accessing AI agents # Payments and Balance This guide explains how subscribers purchase payment plans and check their credit balances. These operations are typically performed by users who want to access AI agents. ## Overview The payment flow consists of: 1. **Discovering Plans**: Browse available payment plans for agents 2. **Ordering Plans**: Purchase a plan to receive credits 3. **Checking Balance**: Monitor available credits and subscription status ## Get Plan Balance Subscribers can check their available credits for a specific plan: ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' // Initialize with subscriber's API key const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Get balance for a plan const balance = await subscriberPayments.plans.getPlanBalance(planId) console.log(`Available credits: ${balance.balance}`) console.log(`Is owner: ${balance.isOwner}`) console.log(`Is subscriber: ${balance.isSubscriber}`) ``` ### Balance Response Structure The balance response contains: ```typescript theme={null} interface PlanBalance { balance: string // Available credits as string isOwner: boolean // True if you're the plan creator isSubscriber: boolean // True if you have an active subscription } ``` ### Working with Balance ```typescript theme={null} // Get balance const balance = await subscriberPayments.plans.getPlanBalance(planId) // Convert to BigInt for calculations const creditsAvailable = BigInt(balance.balance) // Check if sufficient credits const creditsNeeded = 10n if (creditsAvailable >= creditsNeeded) { console.log('Sufficient credits available') } else { console.log(`Need ${creditsNeeded - creditsAvailable} more credits`) } ``` ## Order a Plan Subscribers purchase plans to receive credits: ### Crypto Payment For plans priced in cryptocurrency: ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Order the plan const orderResult = await subscriberPayments.plans.orderPlan(planId) if (orderResult.success) { console.log('Plan ordered successfully!') console.log(`Transaction: ${orderResult.transaction}`) } else { console.error('Failed to order plan') } ``` ### Fiat Payment (Stripe) For plans priced in fiat currency, use `orderFiatPlan` to get a Stripe checkout URL: ```typescript theme={null} const fiatResult = await subscriberPayments.plans.orderFiatPlan(planId) if (fiatResult.checkoutUrl) { console.log(`Complete payment at: ${fiatResult.checkoutUrl}`) // Redirect the user to the Stripe checkout page } ``` #### CLI ```bash theme={null} # Order a fiat plan (returns a Stripe checkout URL) nevermined plans order-fiat-plan ``` > **Note**: When using X402 card-delegation tokens (`nvm:card-delegation` scheme), the payment is handled automatically through the delegated card — no separate checkout URL is needed. See [Querying an Agent](./querying-an-agent) for details on card-delegation tokens. ### Complete Purchase Flow ```typescript theme={null} async function purchaseAndVerify(planId: string) { const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox', }) // Check current balance const beforeBalance = await subscriberPayments.plans.getPlanBalance(planId) console.log(`Balance before: ${beforeBalance.balance} credits`) // Order the plan const orderResult = await subscriberPayments.plans.orderPlan(planId) if (!orderResult.success) { throw new Error('Failed to order plan') } console.log('Plan ordered successfully') // Wait for credits to be allocated (blockchain settlement) await new Promise(resolve => setTimeout(resolve, 5000)) // Check new balance const afterBalance = await subscriberPayments.plans.getPlanBalance(planId) console.log(`Balance after: ${afterBalance.balance} credits`) } ``` ## Waiting for Balance Updates After ordering a plan, credits are allocated on-chain, which may take a few seconds: ```typescript theme={null} async function waitForCredits( payments: Payments, planId: string, timeoutMs: number = 60000 ): Promise { const startTime = Date.now() const checkInterval = 2000 // Check every 2 seconds while (Date.now() - startTime < timeoutMs) { const balance = await payments.plans.getPlanBalance(planId) const credits = BigInt(balance.balance) if (credits > 0n) { return credits } await new Promise(resolve => setTimeout(resolve, checkInterval)) } throw new Error('Timeout waiting for credits') } // Usage const credits = await waitForCredits(subscriberPayments, planId) console.log(`Received ${credits} credits`) ``` ## Check Multiple Plan Balances If a subscriber has multiple plans: ```typescript theme={null} async function checkAllBalances(planIds: string[]) { const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox', }) for (const planId of planIds) { const balance = await subscriberPayments.plans.getPlanBalance(planId) console.log(`Plan ${planId}: ${balance.balance} credits`) } } await checkAllBalances([planId1, planId2, planId3]) ``` ## Stripe Checkout Integration Stripe checkout for fiat-priced plans is managed through the Nevermined App dashboard. Visit [nevermined.app](https://nevermined.app) to configure Stripe payments for your plans. ## Plan Information Before ordering, subscribers might want to view plan details: ```typescript theme={null} // Get plan details const plan = await subscriberPayments.plans.getPlan(planId) console.log(`Plan: ${plan.name}`) console.log(`Description: ${plan.description}`) console.log(`Price: ${plan.price}`) console.log(`Credits: ${plan.credits}`) // Check if already subscribed const balance = await subscriberPayments.plans.getPlanBalance(planId) if (balance.isSubscriber && BigInt(balance.balance) > 0n) { console.log('Already subscribed with available credits') } else { console.log('Need to order plan') } ``` ## Complete Example: Purchase Flow with UI ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' class PlanPurchaseManager { private payments: Payments constructor(apiKey: string, environment: EnvironmentName) { this.payments = Payments.getInstance({ nvmApiKey: apiKey, environment, }) } async checkBalance(planId: string): Promise { const balance = await this.payments.plans.getPlanBalance(planId) return BigInt(balance.balance) } async purchasePlan(planId: string): Promise { try { // Get plan details const plan = await this.payments.plans.getPlan(planId) console.log(`Purchasing: ${plan.name}`) // Check if already subscribed const currentBalance = await this.checkBalance(planId) if (currentBalance > 0n) { console.log(`Already have ${currentBalance} credits`) return true } // Order the plan const orderResult = await this.payments.plans.orderPlan(planId) if (!orderResult.success) { throw new Error('Order failed') } console.log(`Order successful: ${orderResult.transaction}`) // Wait for credits const credits = await this.waitForCredits(planId) console.log(`Received ${credits} credits`) return true } catch (error) { console.error('Purchase failed:', error) return false } } private async waitForCredits( planId: string, timeoutMs: number = 60000 ): Promise { const startTime = Date.now() const checkInterval = 2000 while (Date.now() - startTime < timeoutMs) { const credits = await this.checkBalance(planId) if (credits > 0n) return credits await new Promise(resolve => setTimeout(resolve, checkInterval)) } throw new Error('Timeout waiting for credits') } } // Usage const manager = new PlanPurchaseManager( process.env.SUBSCRIBER_API_KEY!, 'sandbox' ) const success = await manager.purchasePlan(planId) if (success) { const balance = await manager.checkBalance(planId) console.log(`Ready to use agent with ${balance} credits`) } ``` ## Best Practices 1. **Check Balance First**: Always check existing balance before ordering 2. **Wait for Settlement**: Allow time for on-chain credit allocation after purchase 3. **Handle Errors**: Wrap order operations in try-catch blocks 4. **User Feedback**: Provide clear feedback during the purchase process 5. **Balance Monitoring**: Check balance before each agent request 6. **Stripe Redirects**: Use absolute URLs for Stripe success/cancel URLs ## Related Documentation * [Payment Plans](./payment-plans) - Understanding plan types and pricing * [Querying an Agent](./querying-an-agent) - Using credits to access agents *** **Source References**: * `src/api/plans-api.ts` (orderPlan, getPlanBalance methods) * `tests/e2e/test_payments_e2e.test.ts` (ordering and balance verification) # Static Resources Source: https://nevermined.ai/docs/api-reference/typescript/publishing-static-resources Monetize access to static content like files, datasets, and documents with payment protection # Publishing Static Resources In addition to AI agents, you can register static resources (files, datasets, documents) as payment-protected content. This allows you to monetize access to files, datasets, models, or any static content through the Nevermined protocol. ## Overview of Static Resources Static resource agents are specialized agent registrations that provide access to files and documents instead of interactive AI services. They work identically to regular agents but are optimized for static content delivery. **Use Cases**: * Premium datasets (CSV, JSON, Parquet files) * Trained ML models (PyTorch, TensorFlow checkpoints) * Documents and reports (PDF, DOCX) * Media files (images, audio, video) * Configuration files and templates * API specifications and documentation ## Register Static Resource Agents Static resources are registered using the same Agents API, but with HTTP GET endpoints pointing to your content URLs: ```typescript theme={null} import { Payments, AgentMetadata, AgentAPIAttributes } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox', }) // Define static resource metadata const resourceMetadata: AgentMetadata = { name: 'Premium Weather Datasets', description: 'Historical weather data for the past 10 years', tags: ['dataset', 'weather', 'csv', 'historical'], } // Configure file endpoints const resourceApi: AgentAPIAttributes = { endpoints: [ { GET: 'https://storage.example.com/weather/monthly-data-2024.csv' }, { GET: 'https://storage.example.com/weather/monthly-data-2023.csv' }, ], authType: 'bearer', // Require X402 access token } // Register as agent const { agentId } = await payments.agents.registerAgent( resourceMetadata, resourceApi, [planId] ) console.log(`Static resource agent registered: ${agentId}`) ``` ## Using Wildcards for Multiple Files You can use wildcards to grant access to multiple files with a single endpoint pattern: ### Single Wildcard ```typescript theme={null} const resourceApi: AgentAPIAttributes = { endpoints: [ { GET: 'https://storage.example.com/datasets/:dataset/*' }, ], authType: 'bearer', } ``` This pattern allows access to: * `https://storage.example.com/datasets/weather/2024-data.csv` * `https://storage.example.com/datasets/weather/hourly-readings.json` * `https://storage.example.com/datasets/climate/temperature-records.csv` ### Multiple Wildcards ```typescript theme={null} const resourceApi: AgentAPIAttributes = { endpoints: [ { GET: 'https://storage.example.com/datasets/:category/:year/*' }, ], authType: 'bearer', } ``` This pattern allows access to: * `https://storage.example.com/datasets/weather/2024/january.csv` * `https://storage.example.com/datasets/climate/2023/summer.json` ### File Type Wildcards ```typescript theme={null} const resourceApi: AgentAPIAttributes = { endpoints: [ { GET: 'https://storage.example.com/models/:model/*.pt' }, // PyTorch models { GET: 'https://storage.example.com/models/:model/*.safetensors' }, // Safetensors { GET: 'https://storage.example.com/datasets/:name/*.csv' }, // CSV files ], authType: 'bearer', } ``` ## Examples ### Example 1: Dataset Collection ```typescript theme={null} import { Payments, AgentMetadata, AgentAPIAttributes } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox', }) const datasetMetadata: AgentMetadata = { name: 'ML Training Datasets', description: 'Curated datasets for machine learning training', tags: ['dataset', 'ml', 'training', 'csv', 'json'], } const datasetApi: AgentAPIAttributes = { endpoints: [ { GET: 'https://cdn.example.com/datasets/:category/:filename' }, ], openEndpoints: [ 'https://cdn.example.com/datasets/samples/preview.json', // Free preview ], authType: 'bearer', } const { agentId } = await payments.agents.registerAgent( datasetMetadata, datasetApi, [planId] ) console.log(`Dataset collection registered: ${agentId}`) ``` ### Example 2: Model Repository ```typescript theme={null} const modelMetadata: AgentMetadata = { name: 'Fine-tuned Language Models', description: 'Pre-trained and fine-tuned models for NLP tasks', tags: ['model', 'nlp', 'pytorch', 'transformers'], } const modelApi: AgentAPIAttributes = { endpoints: [ { GET: 'https://models.example.com/nlp/:model-name/*.pt' }, { GET: 'https://models.example.com/nlp/:model-name/*.safetensors' }, { GET: 'https://models.example.com/nlp/:model-name/config.json' }, ], authType: 'bearer', } const { agentId } = await payments.agents.registerAgent( modelMetadata, modelApi, [premiumPlanId] ) ``` ### Example 3: Document Library ```typescript theme={null} const documentMetadata: AgentMetadata = { name: 'Research Reports & Whitepapers', description: 'Premium industry research and technical whitepapers', tags: ['documents', 'research', 'reports', 'pdf'], } const documentApi: AgentAPIAttributes = { endpoints: [ { GET: 'https://docs.example.com/reports/:year/:category/*.pdf' }, { GET: 'https://docs.example.com/whitepapers/:topic/*.pdf' }, ], openEndpoints: [ 'https://docs.example.com/samples/index.html', // Catalog ], authType: 'bearer', } const { agentId } = await payments.agents.registerAgent( documentMetadata, documentApi, [basicPlanId, proPlanId] ) ``` ### Example 4: Directory-Level Access ```typescript theme={null} const directoryMetadata: AgentMetadata = { name: 'Premium Asset Library', description: 'Complete directory access to all assets', tags: ['assets', 'media', 'images', 'videos'], } const directoryApi: AgentAPIAttributes = { endpoints: [ { GET: 'https://assets.example.com/premium/*' }, // Everything under /premium/ ], authType: 'bearer', } const { agentId } = await payments.agents.registerAgent( directoryMetadata, directoryApi, [unlimitedPlanId] ) ``` ## MCP Logical URIs for Static Resources When registering static resource agents in the Nevermined App, you can also use MCP logical URIs with wildcards: ``` mcp://storage-server/resources/weather://2024/* mcp://model-server/resources/models://:model-name/* mcp://docs-server/resources/reports://:category/* ``` ## Access Control Static resources use the same X402 access token authentication as AI agents: 1. Subscribers order a plan and receive credits 2. Subscribers generate an X402 access token 3. Requests to static resources include the token in the `payment-signature` header 4. Your server verifies the token and grants access 5. Credits are burned based on your plan configuration See [Validation of Requests](./validation-of-requests) for implementation details. ## Best Practices 1. **Organized Structure**: Use clear URL patterns with logical path segments 2. **Wildcard Strategy**: Balance flexibility (broad wildcards) with security (specific patterns) 3. **File Types**: Specify file extensions in patterns when possible (e.g., `*.csv`, `*.pdf`) 4. **Preview Access**: Consider providing free samples via `openEndpoints` 5. **Metadata Tags**: Include file types and categories in tags for discoverability 6. **Plan Configuration**: Set appropriate credits per download based on file size/value ## Complete Example: Multi-Format Resource Library ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' import { AgentMetadata, AgentAPIAttributes } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) const resourceMetadata: AgentMetadata = { name: 'Data Science Resource Library', description: 'Comprehensive collection of datasets, models, and notebooks', tags: ['dataset', 'model', 'notebook', 'ml', 'ai'], } const resourceApi: AgentAPIAttributes = { endpoints: [ // Datasets { GET: 'https://cdn.example.com/datasets/:category/:name.csv' }, { GET: 'https://cdn.example.com/datasets/:category/:name.json' }, { GET: 'https://cdn.example.com/datasets/:category/:name.parquet' }, // Models { GET: 'https://cdn.example.com/models/:framework/:name/*' }, // Notebooks { GET: 'https://cdn.example.com/notebooks/:topic/*.ipynb' }, // Documentation { GET: 'https://cdn.example.com/docs/:section/*.pdf' }, ], openEndpoints: [ 'https://cdn.example.com/catalog.json', 'https://cdn.example.com/samples/preview-dataset.csv', ], authType: 'bearer', } const { agentId } = await payments.agents.registerAgent( resourceMetadata, resourceApi, [basicPlanId, proPlanId, enterprisePlanId] ) console.log(`Multi-format resource library registered: ${agentId}`) ``` ## Related Documentation * [Agents](./agents) - Agent registration fundamentals * [Payment Plans](./payment-plans) - Configure pricing for resource access * [Validation of Requests](./validation-of-requests) - Verify access tokens for downloads *** **Source References**: * `src/api/agents-api.ts` (Agents API for static resources) * `RUN.md` (MCP logical URIs with wildcards) # Querying Agents Source: https://nevermined.ai/docs/api-reference/typescript/querying-an-agent Generate X402 access tokens and make authenticated requests to AI agents # Querying an Agent After purchasing a payment plan, subscribers can generate X402 access tokens and use them to query AI agents. This guide explains how to get tokens and make authenticated requests. > 🔐 **Treat access tokens like API keys.** The `accessToken` returned by `getX402AccessToken()` is a bearer credential that authorises spending against your plan. Send it only over HTTPS, never log its full value, and scrub the `payment-signature` header from any pino/winston/OpenTelemetry exporter. Use a redaction helper such as ``redactToken(t) => `${t.slice(0,6)}…${t.slice(-4)}` `` if you need diagnostic output. ## Overview The query flow consists of: 1. **Generate X402 Access Token**: Get a payment-authorized token for agent access 2. **Make Authenticated Requests**: Include the token in HTTP headers 3. **Receive Responses**: Agent validates the token and processes the request ## Get X402 Access Token The X402 access token is a cryptographically signed credential that proves you have purchased access to an agent: ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' // Initialize with subscriber's API key const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Generate access token const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, // Required: The plan you purchased agentId // Optional: Specific agent ID to restrict access ) console.log('Access token generated') ``` ### Token Parameters The `getX402AccessToken` method takes the plan id plus two optional arguments: ```typescript theme={null} const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId, // Optional: restrict the token to a specific agent tokenOptions, // Optional: X402TokenOptions (scheme, network, delegationConfig) ) ``` Both schemes require `tokenOptions.delegationConfig` — pass `{ delegationId }` for a delegation created via [`createDelegation`](#card-delegation-tokens-fiat). ### Card-Delegation Tokens (Fiat) For plans that accept fiat payments, use the `nvm:card-delegation` scheme. Create the delegation once with `createDelegation` (passing the enrolled card's `providerPaymentMethodId` and the required `currency`), then request tokens by its `delegationId`: ```typescript theme={null} import { Payments, EnvironmentName, X402TokenOptions } from '@nevermined-io/payments' const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // 1. List enrolled payment methods and create a delegation once. const methods = await subscriberPayments.delegation.listPaymentMethods() console.log(`Found ${methods.length} enrolled card(s)`) const { delegationId } = await subscriberPayments.delegation.createDelegation({ provider: methods[0].provider ?? 'stripe', providerPaymentMethodId: methods[0].id, // or a specific 'pm_...' ID spendingLimitCents: 1000, // max $10.00 durationSecs: 3600, // 1 hour delegation currency: 'usd', }) // 2. Request a token by delegationId (reuse it for subsequent requests). const tokenOptions: X402TokenOptions = { scheme: 'nvm:card-delegation', delegationConfig: { delegationId }, } const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId, tokenOptions, ) ``` #### Auto-Detecting the Scheme If you don't know whether a plan uses crypto or fiat, use `resolveScheme()` to auto-detect from plan metadata: ```typescript theme={null} import { Payments, resolveScheme } from '@nevermined-io/payments' const scheme = await resolveScheme(subscriberPayments, planId) let tokenOptions: X402TokenOptions | undefined if (scheme === 'nvm:card-delegation') { const methods = await subscriberPayments.delegation.listPaymentMethods() const { delegationId } = await subscriberPayments.delegation.createDelegation({ provider: methods[0].provider ?? 'stripe', providerPaymentMethodId: methods[0].id, spendingLimitCents: 1000, durationSecs: 3600, currency: 'usd', }) tokenOptions = { scheme: 'nvm:card-delegation', delegationConfig: { delegationId }, } } const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId, tokenOptions, ) ``` #### CLI > ⚠️ Inline create-on-the-fly is deprecated (nevermined-io/nvm-monorepo#1674) — the `--payment-type fiat` / `--payment-method-id` / `--spending-limit-cents` / `--delegation-duration-secs` flags create a delegation on the fly. Prefer creating a delegation first, then requesting the token by its `delegationId`. ```bash theme={null} # Crypto (default) nevermined x402token get-x402-access-token # Fiat with auto-selected card nevermined x402token get-x402-access-token --payment-type fiat # Fiat with specific card and limits nevermined x402token get-x402-access-token --payment-type fiat \ --payment-method-id pm_1AbCdEfGhIjKlM \ --spending-limit-cents 5000 \ --delegation-duration-secs 7200 # Auto-detect scheme from plan metadata nevermined x402token get-x402-access-token --auto-resolve-scheme # List enrolled payment methods nevermined delegation list-payment-methods ``` ### Basic Example ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Simple token generation const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId ) // ⚠️ Never log the full token — it is a bearer credential. console.log('Access token generated') ``` ## Token Structure (X402 v2) The access token is a JSON Web Token (JWT) containing an X402 v2 payment credential: ```json theme={null} { "x402Version": 2, "accepted": { "scheme": "nvm:erc4337", "network": "eip155:84532", "planId": "plan-123", "extra": { "version": "1", "agentId": "did:nv:agent-456" } }, "payload": { "signature": "0x...", "authorization": { "from": "0xSubscriberAddress", "sessionKeysProvider": "zerodev", "sessionKeys": [] } }, "extensions": {} } ``` ## Make Requests with X402 Token ### Using payment-signature Header (X402 v2 Spec) The X402 v2 specification defines the `payment-signature` header for payment credentials: ```typescript theme={null} // Make authenticated request to agent const response = await fetch('https://agent.example.com/api/v1/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json', 'payment-signature': accessToken, // X402 v2 standard header }, body: JSON.stringify({ prompt: 'What is the weather in San Francisco?', }), }) const result = await response.json() console.log(result) ``` **Note**: The A2A (Agent-to-Agent) protocol also uses the `payment-signature` header for authentication. For A2A integration details, see the [A2A Integration](./a2a-integration) guide. ## Complete Query Example ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' async function queryAgent( planId: string, agentId: string, agentUrl: string, prompt: string ) { // Initialize subscriber payments const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox' as EnvironmentName, }) try { // 1. Generate access token const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId ) console.log('✓ Access token generated') // 2. Make authenticated request const response = await fetch(`${agentUrl}/tasks`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'payment-signature': accessToken, }, body: JSON.stringify({ prompt }), }) // 3. Handle response if (!response.ok) { if (response.status === 402) { console.error('Payment required - insufficient credits') } else { console.error(`Request failed: ${response.statusText}`) } return null } const result = await response.json() console.log('✓ Agent response received') return result } catch (error) { console.error('Failed to query agent:', error) return null } } // Usage const result = await queryAgent( 'plan-123', 'did:nv:agent-456', 'https://weather-agent.example.com/api/v1', 'What is the weather forecast for tomorrow?' ) ``` ## Handling 402 Payment Required If the token is invalid or credits are insufficient, agents return HTTP 402 with payment details: ```typescript theme={null} const response = await fetch(agentUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'payment-signature': accessToken, }, body: JSON.stringify({ prompt }), }) if (response.status === 402) { // Read PAYMENT-REQUIRED header const paymentRequiredHeader = response.headers.get('PAYMENT-REQUIRED') if (paymentRequiredHeader) { // Decode base64 payment required info const paymentRequired = JSON.parse( Buffer.from(paymentRequiredHeader, 'base64').toString() ) console.log('Payment required:', paymentRequired) console.log(`Plan ID: ${paymentRequired.accepts[0].planId}`) // User needs to purchase plan or top up credits } } ``` ## MCP JSON-RPC Requests For MCP-based agents, use JSON-RPC format: ```typescript theme={null} const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId ) const response = await fetch('https://mcp-agent.example.com/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'payment-signature': accessToken, }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_weather', arguments: { city: 'San Francisco' } } }), }) const result = await response.json() console.log(result.result) ``` ## Token Reuse X402 access tokens can be reused for multiple requests until they expire or credits are exhausted: ```typescript theme={null} // Generate token once const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId ) // Use for multiple requests for (const city of ['San Francisco', 'New York', 'London']) { const response = await fetch(agentUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'payment-signature': accessToken, // Reuse same token }, body: JSON.stringify({ prompt: `Weather in ${city}` }), }) const result = await response.json() console.log(`${city}:`, result) } ``` ## Check Balance Before Querying To avoid 402 errors, check your balance before making requests: ```typescript theme={null} async function queryWithBalanceCheck( planId: string, agentId: string, agentUrl: string, prompt: string ) { const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox', }) // Check balance first const balance = await subscriberPayments.plans.getPlanBalance(planId) const availableCredits = BigInt(balance.balance) if (availableCredits === 0n) { console.error('No credits available - please purchase a plan') return null } console.log(`Available credits: ${availableCredits}`) // Generate token and query const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId ) const response = await fetch(agentUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'payment-signature': accessToken, }, body: JSON.stringify({ prompt }), }) return await response.json() } ``` ## Best Practices 1. **Token Caching**: Generate tokens once and reuse them for multiple requests 2. **Balance Checking**: Check balance before generating tokens 3. **Error Handling**: Always handle 402 Payment Required responses 4. **HTTPS Only**: Never send tokens over unencrypted HTTP 5. **Token Expiration**: Regenerate tokens if you receive 402 errors 6. **Header Standard**: Prefer `payment-signature` header (X402 v2 spec) ## Related Documentation * [Payments and Balance](./payments-and-balance) - How to purchase plans and check credits * [Validation of Requests](./validation-of-requests) - How agents validate tokens (for builders) * [X402 Protocol](./x402) - Complete X402 specification *** **Source References**: * `src/x402/token.ts` (getX402AccessToken method) * `tests/e2e/test_x402_e2e.test.ts` (lines 114-133, token generation) * `tests/e2e/test_payments_e2e.test.ts` (MockAgentServer, lines 72-127) # Request Validation Source: https://nevermined.ai/docs/api-reference/typescript/validation-of-requests Verify X402 access tokens and settle payments when subscribers access your agents # Validation of Requests This guide explains how AI agents validate incoming requests and settle payments using the Nevermined Facilitator. Agent builders use these methods to verify subscriber access and burn credits. > 🔐 **Never log incoming tokens.** When you extract the `payment-signature` header, treat it as a bearer secret: do not echo it in error messages, debug output, or telemetry. Configure your log/trace exporters to redact `payment-signature`, `authorization`, and `cookie` headers by default. ## Overview The validation flow consists of: 1. **Extract Token**: Read X402 access token from request headers 2. **Build Payment Required**: Create payment requirement specification 3. **Verify Permissions**: Check if subscriber has valid access 4. **Execute Task**: Process the agent request 5. **Settle Permissions**: Burn credits after successful execution 6. **Return Response**: Send result or 402 error to subscriber ## Receiving Requests Extract the X402 access token from request headers. The X402 v2 spec defines the `payment-signature` header: ```typescript theme={null} import express from 'express' const app = express() app.use(express.json()) app.post('/api/v1/tasks', async (req, res) => { // Extract token from payment-signature header (X402 v2) const accessToken = req.headers['payment-signature'] as string // Alternative: Authorization header // const accessToken = req.headers.authorization?.replace('Bearer ', '') if (!accessToken) { return res.status(402).json({ error: 'Payment required' }) } // Process request... }) ``` ## Build Payment Required Use the `buildPaymentRequired` helper to create the payment specification: ```typescript theme={null} import { buildPaymentRequired } from '@nevermined-io/payments' const paymentRequired = buildPaymentRequired(planId, { endpoint: req.url, // Resource URL agentId: agentId, // Your agent ID httpVerb: req.method, // HTTP method (POST, GET, etc.) network: 'eip155:84532', // Optional: blockchain network description: 'Task API' // Optional: description }) ``` ## Verify Permissions Before executing the request, verify the subscriber has valid access: ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' import { buildPaymentRequired } from '@nevermined-io/payments' const agentPayments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, // Builder/agent API key environment: 'sandbox' as EnvironmentName, }) app.post('/api/v1/tasks', async (req, res) => { const accessToken = req.headers['payment-signature'] as string if (!accessToken) { return res.status(402).json({ error: 'Payment required' }) } // Build payment required const paymentRequired = buildPaymentRequired(planId, { endpoint: req.url, agentId: agentId, httpVerb: req.method, }) try { // Verify permissions const verification = await agentPayments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 1n, // Max credits to verify }) if (!verification.isValid) { return res.status(402).json({ error: 'Insufficient credits or invalid token' }) } // Verification successful, proceed with request... } catch (error) { return res.status(500).json({ error: error.message }) } }) ``` ## Settle Permissions After successfully processing the request, burn the credits: ```typescript theme={null} app.post('/api/v1/tasks', async (req, res) => { const accessToken = req.headers['payment-signature'] as string if (!accessToken) { return res.status(402).json({ error: 'Payment required' }) } const paymentRequired = buildPaymentRequired(planId, { endpoint: req.url, agentId: agentId, httpVerb: req.method, }) try { // Verify const verification = await agentPayments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 1n, }) if (!verification.isValid) { return res.status(402).json({ error: 'Insufficient credits' }) } // Execute task const result = await processTask(req.body) // Settle permissions (burn credits) const settlement = await agentPayments.facilitator.settlePermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 1n, // Credits to burn }) // Return success with payment metadata return res.json({ result, transaction: settlement.transaction, creditsUsed: settlement.creditsRedeemed, remainingBalance: settlement.remainingBalance, }) } catch (error) { return res.status(500).json({ error: error.message }) } }) ``` ## Return 402 Payment Required When payment is required, return HTTP 402 with the `PAYMENT-REQUIRED` header: ```typescript theme={null} import { buildPaymentRequired } from '@nevermined-io/payments' function return402Response(res: express.Response, planId: string, agentId: string, endpoint: string) { const paymentRequired = buildPaymentRequired(planId, { endpoint, agentId, httpVerb: 'POST', }) // Encode payment required as base64 const paymentRequiredHeader = Buffer.from( JSON.stringify(paymentRequired) ).toString('base64') res.writeHead(402, { 'Content-Type': 'application/json', 'PAYMENT-REQUIRED': paymentRequiredHeader, }) res.end(JSON.stringify({ error: 'Payment required', message: 'Valid X402 access token required in payment-signature header', })) } // Usage app.post('/api/v1/tasks', async (req, res) => { const accessToken = req.headers['payment-signature'] as string if (!accessToken) { return return402Response(res, planId, agentId, req.url) } // Verify and process... }) ``` ## Complete Validation Example ```typescript theme={null} import express from 'express' import { Payments, EnvironmentName } from '@nevermined-io/payments' import { buildPaymentRequired } from '@nevermined-io/payments' const app = express() app.use(express.json()) const agentPayments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) const PLAN_ID = process.env.NVM_PLAN_ID! const AGENT_ID = process.env.NVM_AGENT_ID! app.post('/api/v1/tasks', async (req, res) => { // 1. Extract token const accessToken = req.headers['payment-signature'] as string if (!accessToken) { return return402Response(res, PLAN_ID, AGENT_ID, req.url) } // 2. Build payment required const paymentRequired = buildPaymentRequired(PLAN_ID, { endpoint: req.url, agentId: AGENT_ID, httpVerb: req.method, }) try { // 3. Verify permissions const verification = await agentPayments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 1n, }) if (!verification.isValid) { console.log('Verification failed: insufficient credits or invalid token') return return402Response(res, PLAN_ID, AGENT_ID, req.url) } console.log('✓ Permissions verified') // 4. Execute task const result = await processTask(req.body) // 5. Settle permissions const settlement = await agentPayments.facilitator.settlePermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 1n, }) console.log(`✓ Credits settled: ${settlement.creditsRedeemed}`) console.log(`✓ Transaction: ${settlement.transaction}`) // 6. Return response with payment metadata const paymentResponse = { success: settlement.success, network: settlement.network, transaction: settlement.transaction, creditsRedeemed: settlement.creditsRedeemed, } res.writeHead(200, { 'Content-Type': 'application/json', 'PAYMENT-RESPONSE': Buffer.from(JSON.stringify(paymentResponse)).toString('base64'), }) res.end(JSON.stringify({ result })) } catch (error) { console.error('Request processing failed:', error) res.status(500).json({ error: error.message }) } }) function return402Response( res: express.Response, planId: string, agentId: string, endpoint: string ) { const paymentRequired = buildPaymentRequired(planId, { endpoint, agentId, httpVerb: 'POST', }) const paymentRequiredHeader = Buffer.from( JSON.stringify(paymentRequired) ).toString('base64') res.writeHead(402, { 'Content-Type': 'application/json', 'PAYMENT-REQUIRED': paymentRequiredHeader, }) res.end(JSON.stringify({ error: 'Payment required' })) } async function processTask(body: any): Promise { // Your agent logic here return { response: 'Task completed' } } app.listen(3000, () => { console.log('Agent server running on port 3000') }) ``` ## Dynamic Credit Burning For agents with variable credit costs, calculate credits based on the request: ```typescript theme={null} async function calculateCredits(request: any, response: any): Promise { // Example: charge based on response length const responseLength = JSON.stringify(response).length return BigInt(Math.ceil(responseLength / 1000)) // 1 credit per KB } app.post('/api/v1/tasks', async (req, res) => { const accessToken = req.headers['payment-signature'] as string const paymentRequired = buildPaymentRequired(PLAN_ID, { endpoint: req.url, agentId: AGENT_ID, httpVerb: req.method, }) // Verify with max possible credits const verification = await agentPayments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 10n, // Max credits subscriber might need }) if (!verification.isValid) { return return402Response(res, PLAN_ID, AGENT_ID, req.url) } // Execute const result = await processTask(req.body) // Calculate actual credits used const creditsUsed = await calculateCredits(req.body, result) // Settle with actual amount const settlement = await agentPayments.facilitator.settlePermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: creditsUsed, }) return res.json({ result, creditsUsed: settlement.creditsRedeemed, }) }) ``` ## Settle Options The `settlePermissions` method accepts additional options: ```typescript theme={null} const settlement = await agentPayments.facilitator.settlePermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 5n, // Credits to burn batch: false, // Batch settlement (optional) marginPercent: 5, // Add 5% margin to calculated cost (optional) agentRequestId: 'req-123', // Request ID from verification (optional) }) ``` ## Best Practices 1. **Always Verify First**: Call `verifyPermissions` before executing tasks 2. **Settle After Success**: Only burn credits after successful task completion 3. **Handle Errors**: Wrap verification/settlement in try-catch blocks 4. **Return 402 Properly**: Include `PAYMENT-REQUIRED` header with payment details 5. **Log Transactions**: Record transaction hashes for audit trails 6. **Dynamic Pricing**: Calculate credits based on actual resource usage 7. **Token Validation**: Never skip verification even if token looks valid ## Related Documentation * [Querying an Agent](./querying-an-agent) - How subscribers generate and use tokens * [X402 Protocol](./x402) - Complete X402 specification * [MCP Integration](./mcp-integration) - Automatic validation in MCP servers * [A2A Integration](./a2a-integration) - Automatic validation in A2A servers *** **Source References**: * `src/x402/facilitator-api.ts` (buildPaymentRequired, verifyPermissions, settlePermissions) * `tests/e2e/test_payments_e2e.test.ts` (MockAgentServer class, complete validation flow) * `tests/e2e/test_x402_e2e.test.ts` (lines 135-150, verification examples) # X402 Protocol Source: https://nevermined.ai/docs/api-reference/typescript/x402 Understand the X402 payment protocol for HTTP-based AI agent authentication and authorization # X402 Protocol The X402 protocol is a payment-aware HTTP extension that enables AI agents to require and verify payments for API access. This guide provides a complete overview of X402 implementation in the Nevermined Payments Library. > 🔐 **Bearer-token hygiene.** The `payment-signature` header is a bearer credential — anyone holding it can spend the associated plan's credits until it expires. Send it only over HTTPS, never log the full value, and configure your log/trace exporters (pino, winston, OpenTelemetry) to redact `payment-signature`, `authorization`, and `cookie` headers by default. ## Overview of X402 X402 is an HTTP-based protocol for payment-protected resources: * **402 Payment Required**: HTTP status code for payment requests * **payment-signature**: Header containing payment credentials (X402 v2) * **PAYMENT-REQUIRED**: Header with payment requirements in 402 responses * **PAYMENT-RESPONSE**: Header with payment settlement details in success responses * **Cryptographic Signatures**: ERC-4337 account abstraction for secure payments ## Supported Schemes Nevermined supports two x402 payment schemes: | Scheme | Network | Use Case | Settlement | | - | - | - | - | | `nvm:erc4337` | `eip155:84532` | Crypto payments | ERC-4337 UserOps + session keys | | `nvm:card-delegation` | `stripe` \| `braintree` \| `visa` | Fiat/credit card | Provider charge + credit burn | The scheme is determined by the plan's pricing configuration. Plans with `isCrypto: false` use `nvm:card-delegation`; all others use `nvm:erc4337`. The SDK auto-detects the scheme via `resolveScheme()`. The `network` value within `nvm:card-delegation` is determined by which provider issued the delegation being consumed (`stripe`, `braintree`, or `visa`). ### Visa support Visa delegations use the same `nvm:card-delegation` scheme and SDK surface as Stripe and Braintree, but two steps must happen in a **browser** before the SDK can consume them: 1. **Card enrolment** — the cardholder enrols a Visa card through VGS Collect (PCI-compliant iframe) in the Nevermined webapp. The card is bound to a Visa Agentic Token via the VGS Credential Management Platform. 2. **Delegation creation** — the cardholder approves a delegation via a WebAuthn/passkey (FIDO) device-binding ceremony embedded by Visa VTS. This produces a single-use `assuranceData` blob bound to the spending limit + duration + merchant context. Both steps require a real DOM and a user gesture, so the SDK cannot perform them programmatically. Once a Visa delegation exists, the SDK consumes it identically to Stripe/Braintree — see [Reusing Existing Delegations](#reusing-existing-delegations). ## X402 Version 2 Specification The Nevermined Payments Library implements X402 v2, which uses: * `payment-signature` header for access tokens (replaces Authorization) * `PAYMENT-REQUIRED` header for payment requirements (replaces custom formats) * `PAYMENT-RESPONSE` header for settlement receipts * Structured payment credentials with cryptographic signatures ## Generate X402 Access Tokens The supported flow is **create-first**: create a delegation once with `payments.delegation.createDelegation(...)`, then request access tokens by passing only its `delegationId`. **Both schemes (`nvm:erc4337` and `nvm:card-delegation`) require a `delegationConfig`** — the older "just pass planId + agentId" shape no longer mints a token and surfaces `BCK.X402.0030` ("Required token-generation input is missing or incomplete"; the `details` field names the missing input) at the backend. ```typescript theme={null} import { Payments, EnvironmentName, X402TokenOptions } from '@nevermined-io/payments' const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // 1. Create a delegation once. `currency` is required: 'usdc' for the // crypto (erc4337) scheme, 'usd'/'eur'/… for card providers. const { delegationId } = await subscriberPayments.delegation.createDelegation({ provider: 'erc4337', spendingLimitCents: 1000, // $10 cap durationSecs: 86_400, // 1 day currency: 'usdc', }) // 2. Request a token by delegationId. Reuse this delegation for every // subsequent token request until it expires or is exhausted. const tokenOptions: X402TokenOptions = { scheme: 'nvm:erc4337', delegationConfig: { delegationId }, } const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, // Required: Plan ID agentId, // Optional: Agent ID (restricts token to specific agent) tokenOptions, // Required: scheme + delegationConfig ) console.log('X402 access token generated') ``` > ⚠️ **Inline create-on-the-fly is deprecated.** Passing creation fields > (`spendingLimitCents`, `durationSecs`, `providerPaymentMethodId`, `cardId`, > `currency`, `merchantAccountId`, `maxTransactions`) directly in > `delegationConfig` instead of a `delegationId` still works, but > `getX402AccessToken` now emits a runtime deprecation warning. Create the > delegation first (above) and pass only `{ delegationId }`. ### Generate Tokens via Nevermined App Users can also generate X402 access tokens through the Nevermined App: 1. Visit [nevermined.app/permissions/agent-permissions](https://nevermined.app/permissions/agent-permissions) 2. Select the plan you've purchased 3. Configure token parameters (agent, expiration, limits) 4. Generate and copy the X402 access token 5. Use the token in API requests This provides a user-friendly interface for non-technical users to generate tokens without code. ### Generate Card-Delegation Tokens For fiat plans using `nvm:card-delegation`, create the delegation first with `createDelegation` (passing the card's `providerPaymentMethodId`), then request tokens by its `delegationId`. `currency` is required on creation: ```typescript theme={null} import { X402TokenOptions } from '@nevermined-io/payments' // 1. Create a USD card delegation once. const { delegationId: usdDelegationId } = await subscriberPayments.delegation.createDelegation({ provider: 'stripe', providerPaymentMethodId: 'pm_1AbCdEfGhIjKlM', spendingLimitCents: 10000, // $100.00 durationSecs: 2592000, // 30 days currency: 'usd', maxTransactions: 100, }) // 2. Request a token by delegationId (reuse for every subsequent request). const tokenOptions: X402TokenOptions = { scheme: 'nvm:card-delegation', delegationConfig: { delegationId: usdDelegationId }, } const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId, tokenOptions, ) ``` A EUR delegation is the same call with `currency: 'eur'`. The delegation's currency is fixed at creation, so you create one delegation per currency and reuse each by its `delegationId`. ### Reusing Existing Delegations Passing `delegationConfig: { delegationId }` is the supported pattern for every provider, and the **only** supported pattern for Visa delegations (which cannot be created from the SDK). Reuse one delegation across multiple agents that share a single spending budget: ```typescript theme={null} const tokenOptions: X402TokenOptions = { scheme: 'nvm:card-delegation', delegationConfig: { delegationId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', } } const { accessToken } = await subscriberPayments.x402.getX402AccessToken( planId, agentId, tokenOptions, ) ``` When `delegationId` is provided, the backend verifies that the delegation is active and that the requesting API key has access, then returns its existing token without creating a new delegation. The provider (`stripe`, `braintree`, or `visa`) is inferred from the delegation record on the server. To scope a token request to a specific NVM API key, add `apiKeyId` alongside `delegationId` — both fields stay active (non-deprecated): ```typescript theme={null} delegationConfig: { delegationId: '…', apiKeyId: 'key-uuid' } ``` ### Deprecated: inline create-on-the-fly > ⚠️ **Deprecated.** Supplying creation fields directly in `delegationConfig` > instead of a `delegationId` (e.g. `providerPaymentMethodId` + > `spendingLimitCents`, a bare `cardId`, or an identifier-less "auto-select" > shape) still creates a delegation on the fly, but `getX402AccessToken` now > emits a runtime deprecation warning. Use the create-first pattern above > (`createDelegation` → `{ delegationId }`); inline creation will be removed in > a future major release. ### CardDelegationConfig Reference | Field | Type | Status | Description | | - | - | - | - | | `delegationId` | `string` | Active | Existing delegation UUID to reuse — the supported path | | `apiKeyId` | `string` | Active | NVM API Key ID to scope the token request to | | `cardId` | `string` | Deprecated | Payment method UUID to target (inline create) | | `providerPaymentMethodId` | `string` | Deprecated | Stripe payment method ID (e.g., `pm_...`) (inline create) | | `spendingLimitCents` | `number` | Deprecated | Max spending in cents (inline create) | | `durationSecs` | `number` | Deprecated | Duration in seconds (inline create) | | `currency` | `string` | Deprecated | Currency code (inline create) | | `planId` | `string` | Deprecated | Plan ID to scope a new delegation to (inline create) | | `merchantAccountId` | `string` | Deprecated | Stripe Connect account ID (inline create) | | `maxTransactions` | `number` | Deprecated | Max transactions allowed (inline create) | The deprecated fields apply only to inline create-on-the-fly. Create the delegation with [`createDelegation`](#createdelegation) and pass only `delegationId` (optionally `apiKeyId`) here. ### Auto Scheme Resolution Use `resolveScheme()` to auto-detect the correct scheme from plan metadata: ```typescript theme={null} import { resolveScheme } from '@nevermined-io/payments' // Auto-detect scheme from plan metadata (cached for 5 minutes) const scheme = await resolveScheme(payments, planId) // Returns "nvm:erc4337" for crypto plans, "nvm:card-delegation" for fiat plans // Explicit override const scheme = await resolveScheme(payments, planId, 'nvm:card-delegation') ``` ### DelegationAPI Manage payment methods and delegations for card delegation: ```typescript theme={null} import { DelegationAPI, PaymentMethodSummary } from '@nevermined-io/payments' const delegationApi = DelegationAPI.getInstance(payments.options) // List enrolled payment methods (every provider) const methods: PaymentMethodSummary[] = await delegationApi.listPaymentMethods() // Restrict the result to a single provider with the optional `provider` filter const stripeMethods: PaymentMethodSummary[] = await delegationApi.listPaymentMethods({ provider: 'stripe', }) for (const method of methods) { console.log(`${method.brand} ****${method.last4} (expires ${method.expMonth}/${method.expYear})`) if (method.allowedApiKeyIds) { console.log(` Restricted to API keys: ${method.allowedApiKeyIds.join(', ')}`) } } ``` `listPaymentMethods` accepts an optional `ListOptions`: | Option | Type | Description | | - | - | - | | `provider` | `DelegationProvider` (`'stripe' \| 'braintree' \| 'visa' \| 'erc4337'`) | Server-side filter that restricts the result to payment methods backed by this provider. Omit it (the default) to return methods from every provider. | | `accessible` | `boolean` | When `true`, return only methods accessible to the requesting API key. | #### Update Payment Method Restrict a card to specific NVM API Keys so only designated agents can use it: ```typescript theme={null} await delegationApi.updatePaymentMethod('pm-uuid-here', { alias: 'Production Card', allowedApiKeyIds: ['sk-agent-1', 'sk-agent-2'], // Only these API keys can use this card }) // Remove restrictions (any API key can use the card) await delegationApi.updatePaymentMethod('pm-uuid-here', { allowedApiKeyIds: null, }) ``` #### List Delegations Retrieve all delegations for the authenticated user: ```typescript theme={null} const { delegations, totalResults } = await delegationApi.listDelegations() console.log(`Total delegations: ${totalResults}`) for (const d of delegations) { console.log(`${d.delegationId} - ${d.status} (${d.remainingBudgetCents} cents remaining)`) if (d.apiKeyId) { console.log(` Restricted to API key: ${d.apiKeyId}`) } } ``` #### createDelegation Create a delegation once, then reuse it across token requests by its `delegationId` (the create-first pattern). This is the supported way to provision spending authority for `nvm:erc4337` and `nvm:card-delegation` — prefer it over inline create-on-the-fly in `getX402AccessToken`. ```typescript theme={null} // Crypto (erc4337): currency must be 'usdc'. const { delegationId } = await delegationApi.createDelegation({ provider: 'erc4337', spendingLimitCents: 100000, // $1000 cap durationSecs: 604800, // 1 week currency: 'usdc', }) // Card (stripe / braintree): pass the enrolled card's providerPaymentMethodId. const { delegationId: cardDelegationId } = await delegationApi.createDelegation({ provider: 'stripe', providerPaymentMethodId: 'pm_1AbCdEfGhIjKlM', spendingLimitCents: 10000, durationSecs: 2592000, currency: 'usd', }) ``` `CreateDelegationPayload` fields: | Field | Type | Required | Description | | - | - | - | - | | `provider` | `'stripe' \| 'braintree' \| 'visa' \| 'erc4337'` | Yes | Delegation provider | | `spendingLimitCents` | `number` | Yes | Maximum spending limit in cents | | `durationSecs` | `number` | Yes | Delegation lifetime in seconds | | `currency` | `DelegationCurrency` (`'usd' \| 'eur' \| 'usdc' \| 'eurc'`) | Yes | Currency code — `'usdc'`/`'eurc'` for erc4337, `'usd'`/`'eur'` for card providers. No silent default; the backend requires it. | | `providerPaymentMethodId` | `string` | Card only | Payment method ID (Stripe `pm_...`, Braintree vault token, Visa Agentic token id) | | `planId` | `string` | No | Optional and additive — delegations are plan-agnostic by default; supply `planId` to bind the delegation to a single plan. (Visa is always plan-specific and requires it.) | | `merchantAccountId` | `string` | No | Stripe Connect account ID or Braintree merchantId | | `maxTransactions` | `number` | No | Maximum number of transactions allowed | | `apiKeyId` | `string` | No | NVM API Key ID to scope the delegation to | > Visa delegations require a browser-side device-binding ceremony and cannot be > created from the SDK — see [Visa support](#visa-support). Create them in the > Nevermined webapp, then consume them here by `delegationId`. #### DelegationListResponse Fields `listDelegations()` resolves to a `DelegationListResponse` object: | Field | Type | Description | | - | - | - | | `delegations` | `DelegationSummary[]` | Array of delegation records | | `totalResults` | `number` | Total number of delegations | | `page` | `number` | Current page number | | `offset` | `number` | Offset into the full result set | #### DelegationSummary Fields Each item in the `delegations` array is a `DelegationSummary`: | Field | Type | Description | | - | - | - | | `delegationId` | `string` | Unique delegation identifier | | `provider` | `string` | Payment provider (`stripe`, `braintree`, or `visa`) | | `providerPaymentMethodId` | `string` | Provider-side payment method ID | | `status` | `string` | Delegation status (`Active`, `Revoked`, etc.) | | `spendingLimitCents` | `string` | Maximum spendable amount in cents | | `amountSpentCents` | `string` | Amount already spent in cents | | `remainingBudgetCents` | `string` | Remaining budget in cents | | `currency` | `string` | Currency code (e.g., `usd`) | | `transactionCount` | `number` | Number of transactions made | | `expiresAt` | `string` | Expiry timestamp (ISO 8601) | | `createdAt` | `string` | Creation timestamp (ISO 8601) | | `apiKeyId` | `string \| null` | API key this delegation is restricted to, or `null` if unrestricted | #### PaymentMethodSummary Fields | Field | Type | Description | | - | - | - | | `id` | `string` | Payment method ID (e.g., `pm_...`) | | `brand` | `string` | Card brand (e.g., `visa`, `mastercard`) | | `last4` | `string` | Last 4 digits of the card number | | `expMonth` | `number` | Card expiration month | | `expYear` | `number` | Card expiration year | | `allowedApiKeyIds` | `string[] \| null` | API keys allowed to use this card (`null` = unrestricted) | ## X402 Access Token Structure The access token is a JWT containing an X402 v2 payment credential: ```json theme={null} { "x402Version": 2, "accepted": { "scheme": "nvm:erc4337", // Payment scheme "network": "eip155:84532", // Blockchain network (Base Sepolia) "planId": "plan-123", // Payment plan ID "extra": { "version": "1", // Extra version info "agentId": "did:nv:agent-456" // Optional agent restriction } }, "payload": { "signature": "0x...", // Cryptographic signature "authorization": { "from": "0xSubscriberAddress", // Subscriber's wallet address "sessionKeysProvider": "zerodev", // Session key provider "sessionKeys": [] // Session keys for gasless transactions } }, "extensions": {} // Optional extensions } ``` ### Card-Delegation Token Structure For fiat plans using `nvm:card-delegation`, the token contains a JWT-based delegation authorization: ```json theme={null} { "x402Version": 2, "accepted": { "scheme": "nvm:card-delegation", "network": "stripe", "planId": "plan-123", "extra": { "version": "1", "agentId": "did:nv:agent-456" } }, "payload": { "token": "eyJhbGciOiJSUzI1NiIs...", "authorization": { "from": "0xSubscriberAddress", "sessionKeys": [{ "id": "redeem", "data": "0xabc123..." }] } }, "extensions": {} } ``` ### Token Components * **x402Version**: Protocol version (2 for current spec) * **accepted**: Payment method specification * **scheme**: `nvm:erc4337` for crypto or `nvm:card-delegation` for fiat * **network**: `eip155:84532` (Base Sepolia) for crypto, one of `stripe`, `braintree`, or `visa` for fiat * **planId**: The payment plan being used * **extra**: Additional metadata (version, agentId, etc.) * **payload**: Payment authorization * **signature** (erc4337): Cryptographic proof of payment authorization * **token** (card-delegation): Signed JWT encoding the delegation claims * **authorization**: Subscriber identity and session keys * **extensions**: Optional protocol extensions ## Verify X402 Permissions Agents verify tokens before executing requests: ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' import { buildPaymentRequired } from '@nevermined-io/payments' const agentPayments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, // Builder/agent API key environment: 'sandbox' as EnvironmentName, }) // Build payment required specification const paymentRequired = buildPaymentRequired(planId, { endpoint: '/api/v1/tasks', agentId: agentId, httpVerb: 'POST', network: 'eip155:84532', description: 'Task execution API', }) // Verify subscriber permissions const verification = await agentPayments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 2n, // Max credits to verify }) if (verification.isValid) { console.log('✓ Permissions verified') console.log(`Payer: ${verification.payer}`) } else { console.log(`✗ Verification failed: ${verification.invalidReason}`) } ``` ### Verification Response ```typescript theme={null} interface VerifyPermissionsResult { isValid: boolean // True if token is valid invalidReason?: string // Reason for invalidity (if isValid is false) payer?: string // Address of the payer's wallet agentRequestId?: string // Agent request ID for observability tracking (Nevermined extension) urlMatching?: string // URL pattern that matched the endpoint (Nevermined extension) agentRequest?: StartAgentRequest // Agent request context for observability (Nevermined extension) } interface StartAgentRequest { agentRequestId: string // Unique request identifier agentName: string // Name of the agent agentId: string // Agent identifier balance: PlanBalance // Current plan balance (planId, balance, pricePerCredit, etc.) urlMatching: string // URL pattern that was matched verbMatching: string // HTTP verb that was matched batch: boolean // Whether this is a batch request } ``` ## Settle X402 Permissions After successful execution, burn credits: ```typescript theme={null} // Settle permissions (burn credits) const settlement = await agentPayments.facilitator.settlePermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 2n, // Credits to burn batch: false, // Batch settlement (optional) marginPercent: 5, // Add 5% margin (optional) agentRequestId: verification.agentRequest?.agentRequestId, // From verification }) console.log(`✓ Settlement successful`) console.log(`Transaction: ${settlement.transaction}`) console.log(`Credits burned: ${settlement.creditsRedeemed}`) console.log(`Remaining balance: ${settlement.remainingBalance}`) ``` ### Settlement Response ```typescript theme={null} interface SettlePermissionsResult { success: boolean // True if settlement succeeded transaction: string // Blockchain transaction hash creditsRedeemed: string // Credits burned remainingBalance: string // Subscriber's remaining credits network: string // Blockchain network } ``` ## HTTP Headers (X402 v2) ### payment-signature Header Subscribers include this header in requests: ```http theme={null} POST /api/v1/tasks HTTP/1.1 Host: agent.example.com Content-Type: application/json payment-signature: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... {"prompt": "Hello"} ``` ### PAYMENT-REQUIRED Header (402 Response) Agents return this header when payment is required: ```http theme={null} HTTP/1.1 402 Payment Required Content-Type: application/json PAYMENT-REQUIRED: eyJ4NDAyVmVyc2lvbiI6MiwicmVzb3VyY2UiOnsidXJsIjoiL2FwaS92MS90YXNrcyJ9... {"error": "Payment required"} ``` The header contains base64-encoded payment requirement JSON. The `scheme` and `network` vary by plan type: **Crypto plan:** ```json theme={null} { "x402Version": 2, "resource": { "url": "/api/v1/tasks", "description": "Task execution API", "mimeType": "application/json" }, "accepts": [ { "scheme": "nvm:erc4337", "network": "eip155:84532", "planId": "plan-123", "extra": { "version": "1", "agentId": "did:nv:agent-456" } } ], "extensions": {} } ``` **Fiat plan:** ```json theme={null} { "x402Version": 2, "resource": { "url": "/api/v1/tasks", "description": "Task execution API", "mimeType": "application/json" }, "accepts": [ { "scheme": "nvm:card-delegation", "network": "stripe", "planId": "plan-123", "extra": { "version": "1", "agentId": "did:nv:agent-456" } } ], "extensions": {} } ``` ### PAYMENT-RESPONSE Header (Success) Agents include this header in successful responses: ```http theme={null} HTTP/1.1 200 OK Content-Type: application/json PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0cmFuc2FjdGlvbiI6IjB4Li4uIn0= {"result": "Task completed"} ``` The header contains base64-encoded settlement details: ```json theme={null} { "success": true, "network": "eip155:84532", "transaction": "0x...", "creditsRedeemed": "2", "remainingBalance": "98" } ``` ## Complete X402 Flow ### Subscriber Side ```typescript theme={null} import { Payments, EnvironmentName } from '@nevermined-io/payments' const subscriberPayments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // 1. Create a delegation once (currency required; 'usdc' for erc4337), // then generate an access token by its delegationId. const { delegationId } = await subscriberPayments.delegation.createDelegation({ provider: 'erc4337', spendingLimitCents: 1000, durationSecs: 86_400, currency: 'usdc', }) const { accessToken } = await subscriberPayments.x402.getX402AccessToken(planId, agentId, { scheme: 'nvm:erc4337', delegationConfig: { delegationId }, }) // 2. Make request with payment-signature header const response = await fetch('https://agent.example.com/api/v1/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json', 'payment-signature': accessToken, }, body: JSON.stringify({ prompt: 'Hello, agent!' }), }) // 3. Handle response if (response.status === 402) { // Payment required - need to purchase plan or top up const paymentRequired = response.headers.get('PAYMENT-REQUIRED') console.error('Payment required:', paymentRequired) } else { const result = await response.json() const paymentResponse = response.headers.get('PAYMENT-RESPONSE') console.log('Success:', result) console.log('Payment:', paymentResponse) } ``` ### Agent Side ```typescript theme={null} import express from 'express' import { Payments, EnvironmentName } from '@nevermined-io/payments' import { buildPaymentRequired } from '@nevermined-io/payments' const app = express() app.use(express.json()) const agentPayments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) app.post('/api/v1/tasks', async (req, res) => { // 1. Extract token const accessToken = req.headers['payment-signature'] as string if (!accessToken) { const paymentRequired = buildPaymentRequired(planId, { endpoint: req.url, agentId: agentId, httpVerb: req.method, }) return res .status(402) .set('PAYMENT-REQUIRED', Buffer.from(JSON.stringify(paymentRequired)).toString('base64')) .json({ error: 'Payment required' }) } // 2. Build payment required const paymentRequired = buildPaymentRequired(planId, { endpoint: req.url, agentId: agentId, httpVerb: req.method, }) try { // 3. Verify permissions const verification = await agentPayments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 2n, }) if (!verification.isValid) { return res .status(402) .set('PAYMENT-REQUIRED', Buffer.from(JSON.stringify(paymentRequired)).toString('base64')) .json({ error: 'Insufficient credits' }) } // 4. Execute task const result = await processTask(req.body) // 5. Settle permissions const settlement = await agentPayments.facilitator.settlePermissions({ paymentRequired, x402AccessToken: accessToken, maxAmount: 2n, }) // 6. Return response with PAYMENT-RESPONSE header const paymentResponse = { success: settlement.success, network: settlement.network, transaction: settlement.transaction, creditsRedeemed: settlement.creditsRedeemed, } return res .status(200) .set('PAYMENT-RESPONSE', Buffer.from(JSON.stringify(paymentResponse)).toString('base64')) .json({ result }) } catch (error) { res.status(500).json({ error: error.message }) } }) app.listen(3000) ``` ## buildPaymentRequired Helper Simplifies creating X402PaymentRequired objects: ```typescript theme={null} import { buildPaymentRequired } from '@nevermined-io/payments' // Scheme auto-detected from plan metadata when omitted const paymentRequired = buildPaymentRequired( planId, { endpoint: '/api/v1/tasks', // Resource URL agentId: 'did:nv:agent-456', // Agent ID httpVerb: 'POST', // HTTP method network: 'eip155:84532', // Blockchain (default for nvm:erc4337) description: 'Task execution', // Description scheme: 'nvm:erc4337' // Optional: omit to auto-detect from plan metadata } ) ``` When `scheme` is set to `'nvm:card-delegation'`, the `network` is automatically set to `'stripe'`. ## Best Practices 1. **Always Verify Before Execute**: Never skip token verification 2. **Settle After Success**: Only burn credits after successful execution 3. **Use X402 v2 Headers**: Prefer `payment-signature` over Authorization 4. **Return 402 Properly**: Include `PAYMENT-REQUIRED` header with details 5. **Log Transactions**: Record settlement transaction hashes 6. **Handle Errors**: Provide clear error messages in 402 responses 7. **Token Reuse**: Subscribers can reuse tokens for multiple requests 8. **Restrict Cards to API Keys**: When running multiple agents, restrict each card to specific NVM API Keys using `allowedApiKeyIds` to prevent unauthorized spending 9. **Reuse Delegations**: Pass `delegationId` to reuse existing delegations instead of creating new ones on each request — this avoids delegation sprawl and keeps spending consolidated ## Related Documentation * [Querying an Agent](./querying-an-agent) - How subscribers use X402 tokens * [Validation of Requests](./validation-of-requests) - How agents verify and settle * [MCP Integration](./mcp-integration) - Automatic X402 handling in MCP * [A2A Integration](./a2a-integration) - Automatic X402 handling in A2A *** **Source References**: * `src/x402/token.ts` (getX402AccessToken) * `src/x402/delegation-api.ts` (DelegationAPI: listPaymentMethods, listDelegations, updatePaymentMethod) * `src/x402/facilitator-api.ts` (verifyPermissions, settlePermissions, buildPaymentRequired) * `tests/e2e/test_x402_e2e.test.ts` (complete X402 flow) # Create Permission Source: https://nevermined.ai/docs/api-reference/x402/create-permission POST /x402/permissions Creates a delegated permission and generates an x402 access token. # Get Permission Source: https://nevermined.ai/docs/api-reference/x402/get-permission GET /x402/permissions/{permissionHash} Retrieves complete information about a specific permission. # List Permissions Source: https://nevermined.ai/docs/api-reference/x402/list-permissions GET /x402/permissions Retrieves paginated list of your delegated permissions. # Revoke Permission Source: https://nevermined.ai/docs/api-reference/x402/revoke-permission DELETE /x402/permissions/{permissionHash} Invalidates a delegated permission, preventing further use. # Settle Source: https://nevermined.ai/docs/api-reference/x402/settle-permission POST /x402/settle Finalizes and records delegated permission usage after service delivery. # Verify Source: https://nevermined.ai/docs/api-reference/x402/verify-permission POST /x402/verify Validates a delegated permission before processing a request. # API error codes Source: https://nevermined.ai/docs/development-guide/api-errors/codes Catalogue of every BCK.* error code returned by the Nevermined API Every error response from the Nevermined API carries a stable `code` (e.g. `BCK.X402.0008`). The table below enumerates every code, its HTTP status, category, canonical message, and remediation hint. Pages on this site are anchored by code — link directly to `#bck-x402-0008` from your error handlers, runbooks, or support tickets. > [!NOTE] > > Locked response fields are `code`, `message`, and the HTTP status. Optional fields (`hint`, `docsUrl`, `category`, `retryable`, `correlationId`) appear only when supplied. Consumers that branch only on `code` and `message` ignore the rest transparently. > [!NOTE] > > Beyond the catalogued codes below, any endpoint may also return a framework-level `BCK.HTTP.` code (e.g. `BCK.HTTP.400` from request validation, `BCK.HTTP.429` from throttling, `BCK.HTTP.404`) for an HTTP error that carries no domain-specific code. Branch defensively — treat an unknown `BCK.HTTP.*` as its HTTP status class. ## Namespaces * [`BCK.ACCOUNT_PROVISIONING`](#bck-account_provisioning) — 2 codes * [`BCK.AGENT`](#bck-agent) — 12 codes * [`BCK.APIKEY`](#bck-apikey) — 19 codes * [`BCK.ARD`](#bck-ard) — 3 codes * [`BCK.AUTH`](#bck-auth) — 17 codes * [`BCK.BILLING`](#bck-billing) — 27 codes * [`BCK.BRAINTREE`](#bck-braintree) — 21 codes * [`BCK.BUDGETS`](#bck-budgets) — 6 codes * [`BCK.CARD_PAYMENT`](#bck-card_payment) — 21 codes * [`BCK.CATALOG`](#bck-catalog) — 48 codes * [`BCK.COMMON`](#bck-common) — 35 codes * [`BCK.CREDITS`](#bck-credits) — 17 codes * [`BCK.CREDIT_RESCALE`](#bck-credit_rescale) — 7 codes * [`BCK.CREDIT_TOPUPS`](#bck-credit_topups) — 23 codes * [`BCK.DELEGATION`](#bck-delegation) — 10 codes * [`BCK.ENTITLEMENTS`](#bck-entitlements) — 5 codes * [`BCK.FEATURE_ACCESS`](#bck-feature_access) — 3 codes * [`BCK.GROUPS`](#bck-groups) — 12 codes * [`BCK.GUEST`](#bck-guest) — 2 codes * [`BCK.INVITATIONS`](#bck-invitations) — 5 codes * [`BCK.LEGAL_DOCS`](#bck-legal_docs) — 6 codes * [`BCK.METRIC`](#bck-metric) — 5 codes * [`BCK.METRICS`](#bck-metrics) — 1 code * [`BCK.MPP`](#bck-mpp) — 7 codes * [`BCK.NOTIF`](#bck-notif) — 9 codes * [`BCK.OAUTH`](#bck-oauth) — 40 codes * [`BCK.OBSERVABILITY`](#bck-observability) — 5 codes * [`BCK.ORDER`](#bck-order) — 8 codes * [`BCK.ORGANIZATIONS`](#bck-organizations) — 37 codes * [`BCK.ORG_INTEGRATION`](#bck-org_integration) — 4 codes * [`BCK.ORG_WALLETS`](#bck-org_wallets) — 13 codes * [`BCK.PAYMENT_CREDENTIAL`](#bck-payment_credential) — 4 codes * [`BCK.PAYPAL`](#bck-paypal) — 1 code * [`BCK.PLANS`](#bck-plans) — 1 code * [`BCK.POINT`](#bck-point) — 19 codes * [`BCK.PROTOCOL`](#bck-protocol) — 62 codes * [`BCK.PURCHASES`](#bck-purchases) — 5 codes * [`BCK.ROUTER`](#bck-router) — 47 codes * [`BCK.STRIPE`](#bck-stripe) — 42 codes * [`BCK.STRIPE.CONNECT`](#bck-stripe-connect) — 12 codes * [`BCK.SUBSCRIPTION_ACCESS`](#bck-subscription_access) — 1 code * [`BCK.SUBSCRIPTION_BILLING`](#bck-subscription_billing) — 19 codes * [`BCK.SUBSCRIPTION_CATALOG`](#bck-subscription_catalog) — 9 codes * [`BCK.SUBSCRIPTION_COMPLIANCE`](#bck-subscription_compliance) — 8 codes * [`BCK.SUBSCRIPTION_MCP`](#bck-subscription_mcp) — 1 code * [`BCK.SUBSCRIPTION_REFUND`](#bck-subscription_refund) — 9 codes * [`BCK.SUBSCRIPTION_ROUTER`](#bck-subscription_router) — 19 codes * [`BCK.SUBSCRIPTION_STRIPE`](#bck-subscription_stripe) — 6 codes * [`BCK.SUBSCRIPTION_TARIFF`](#bck-subscription_tariff) — 12 codes * [`BCK.SUBSCRIPTION_TREASURY`](#bck-subscription_treasury) — 15 codes * [`BCK.TRANSCODING`](#bck-transcoding) — 4 codes * [`BCK.TXS`](#bck-txs) — 16 codes * [`BCK.USER_PROFILE`](#bck-user_profile) — 7 codes * [`BCK.VERSION`](#bck-version) — 2 codes * [`BCK.VGS`](#bck-vgs) — 10 codes * [`BCK.VISA`](#bck-visa) — 27 codes * [`BCK.WALLET`](#bck-wallet) — 6 codes * [`BCK.WELCOME_CREDITS`](#bck-welcome_credits) — 4 codes * [`BCK.WIDGET`](#bck-widget) — 5 codes * [`BCK.WIDGET_KEYS`](#bck-widget_keys) — 2 codes * [`BCK.WIDGET_SESSION`](#bck-widget_session) — 13 codes * [`BCK.X402`](#bck-x402) — 56 codes ## `BCK.ACCOUNT_PROVISIONING` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.ACCOUNT_PROVISIONING.0001` | 400 | validation | — | Account provisioning requires an email | Pass an email in the request body. Account provisioning is keyed on email; passwordless flows are not supported here. | | `BCK.ACCOUNT_PROVISIONING.0003` | 500 | integration | — | Unexpected failure during account provisioning | Inspect the underlying error in logs. Provisioning failed mid-way — usually a Privy or DB-layer error. The partial profile (if any) needs manual cleanup. | ## `BCK.AGENT` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.AGENT.0001` | 400 | business | — | Invalid Agent Execution Status | Provide one of the valid execution statuses (Pending, In\_Progress, Completed, Failed). Other strings are rejected to keep state-machine transitions auditable. | | `BCK.AGENT.0002` | 500 | business | — | Error updating step agent | Inspect the underlying error in logs. The step persistence failed — usually a DB-layer constraint or stale step row. | | `BCK.AGENT.0003` | 403 | business | — | Unable to create task for agent | Verify the caller holds an active plan that covers this agent, and that the agent is published. | | `BCK.AGENT.0004` | 403 | business | — | Invalid user | Verify the authenticated user identity. The agent task endpoint requires a real (non-guest) user with a wallet. | | `BCK.AGENT.0005` | 403 | business | — | Unable to get task for did, task and user | Verify the (DID, taskId, user) tuple matches an existing task the user owns. Most often a stale taskId or wrong agent DID. | | `BCK.AGENT.0006` | 403 | business | — | Unable to find tasks by subscriber | Inspect the underlying error in logs. Subscriber-side task lookup failed — usually a DB-layer error. | | `BCK.AGENT.0007` | 404 | business | — | Connection not found for clientId | Verify the clientId is the value returned by the websocket handshake for this session. Clients reconnecting must rebind a fresh clientId. | | `BCK.AGENT.0008` | 500 | business | — | Error registering websocket connection | Inspect the underlying error in logs. Websocket registration failed — usually a Redis/queue-layer issue. | | `BCK.AGENT.0009` | 403 | business | — | Error creating steps for agent | Inspect the underlying error in logs. Step creation failed — verify the agent task exists and is in a state that accepts new steps. | | `BCK.AGENT.0010` | 403 | business | — | Task not found or completed | Verify the taskId. The task may have been marked Completed/Failed already and no longer accepts state changes. | | `BCK.AGENT.0011` | 500 | internal | ❌ | Agent lookup failed: agent with the given entryId not found in service layer | The service-layer findOneById returned null. The original behaviour was a generic 500; consumer code that needs 404 semantics should use BCK.PROTOCOL.0004. | | `BCK.AGENT.0012` | 500 | internal | ❌ | Agent DTO mapping called with a null entity | GetAgentDto.fromEntity received null. The caller should branch on the service-layer lookup result before calling fromEntity; this code only fires if a programming error leaks past that guard. | ## `BCK.APIKEY` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.APIKEY.0001` | 403 | auth | — | API Key not registered, you need to register it first | Register the API key via POST /api-keys before using it. The key signature is valid but no record exists in our DB. | | `BCK.APIKEY.0002` | 404 | auth | — | API Key with given hash not found | Verify the API key value. The hashed lookup returned no row; the key may have been revoked or never registered. | | `BCK.APIKEY.0003` | 404 | business | ❌ | Unable to revoke API Key | No active key matched this hash for your account — it may not exist, not belong to you, or already be revoked. | | `BCK.APIKEY.0004` | 401 | auth | — | Invalid Nevermined API Key | Verify the API key value is well-formed (header.payload.signature) and not truncated. Reissue if it was rotated. | | `BCK.APIKEY.0006` | 401 | auth | — | Invalid Nevermined Key Metadata | Verify the API-key payload includes the expected metadata fields (sub, iss, aud, exp). Reissue if it predates the metadata schema change. | | `BCK.APIKEY.0007` | 401 | auth | — | API Key issuer does not match user address | Reissue the API key from the authenticated user’s wallet. The token’s iss claim must equal the authenticated address byte-for-byte. | | `BCK.APIKEY.0008` | 403 | auth | — | API Key with hash already exists | Revoke and reissue the API key. The collision means the same hash was already stored (extremely rare; usually a duplicate-create call). | | `BCK.APIKEY.0009` | 500 | auth | — | Error searching API Key transactions | Inspect the underlying error in logs. The API-key transactions query failed — usually a DB-layer error or pagination issue. | | `BCK.APIKEY.0010` | 400 | validation | ❌ | Expiration date must be in the future | Provide an exp claim in the future when creating the key, or omit it for a never-expiring key. | | `BCK.APIKEY.0011` | 500 | auth | — | Error searching user API Keys | Inspect the underlying error in logs. The per-user API-keys lookup failed — usually a DB-layer error. | | `BCK.APIKEY.0012` | 500 | internal | — | Unexpected failure registering the API key | Inspect the underlying error in the logs by correlation id — an unexpected server-side failure during key registration, not a caller credential or signer/audience issue. | | `BCK.APIKEY.0013` | 401 | auth | — | Malformed API Key payload | Verify the JWT was not truncated or tampered with in transit. Reissue the API key from the source credential store and retry. | | `BCK.APIKEY.0014` | 500 | internal | ❌ | API Key claim is missing the issuer (iss) address | The validated JWT payload reached the service layer without an iss claim. Inspect the upstream guard that produced this payload — iss is mandatory for API-key issuance. | | `BCK.APIKEY.0015` | 500 | auth | — | Error aggregating API Key usage | Inspect the underlying error in logs. The per-key usage aggregation query failed — usually a DB-layer error. | | `BCK.APIKEY.0016` | 400 | validation | ❌ | No updatable API key fields provided | Send at least one of `name` or `apiVersion` in the PATCH body. | | `BCK.APIKEY.0017` | 409 | auth | ✅ | API key has no session key for the requested network | This API key was issued without a session key for this network (#1929). Re-issue the key including this network and retry — the webapp rotates the key automatically. | | `BCK.APIKEY.0018` | 400 | validation | — | Authenticated but no wallet linked to the account | Link a wallet to your account before registering an API key. Email/social sign-ins must add a wallet first. | | `BCK.APIKEY.0019` | 500 | internal | — | Unexpected failure minting the API key | Minting failed server-side. Common causes: a pending DB migration on a freshly-deployed image, a Privy/ZeroDev outage while deriving the account, or a served network with no settlement token configured (the details name the network; retrying cannot fix that one). Retry; if it persists, quote the correlation id. | | `BCK.APIKEY.0020` | 409 | auth | ✅ | The wallet has not authorized Nevermined to sign for it | The Nevermined app grants this when the user signs in. Retry once sign-in has finished; if it keeps failing, sign out of the Nevermined app and sign in again to grant it. | ## `BCK.ARD` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.ARD.0001` | 400 | validation | ❌ | Invalid ARD request argument | An ARD `/search`, `/explore` or `/agents` argument was rejected — e.g. an unsupported `filter`/facet term, a malformed EBNF `filter` or `orderBy`, or an invalid value (`query.text`, `updatedAt`, a non-string filter value). The specific cause is in the response `details`. Supported filter/facet terms: type, tags, capabilities, publisher, pay:protocol, pay:currency, pay:network, pay:price (ARD §5.3.1). | | `BCK.ARD.0002` | 500 | internal | ✅ | ARD federation fan-out failed | The ARD federation layer threw while layering peers onto the local result. Unreachable while the fan-out is total (per-peer failures degrade to partial results, not throws); reaching a caller means a regression in the federation path. Distinct from a catalog read failure (BCK.CATALOG.0002). Inspect the underlying error in logs. | | `BCK.ARD.0003` | 502 | integration | ❌ | ARD federation peer response exceeded the size cap | A federated ARD peer answered with a body larger than the API reads, so its results were dropped and the search answered with the remaining peers. Operator-facing; no client receives this code. | ## `BCK.AUTH` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.AUTH.0001` | 500 | internal | — | Error registering API Key | Inspect the underlying error in the logs by correlation id. API-key registration failed with an unexpected server-side error (usually a DB-layer fault). | | `BCK.AUTH.0002` | 401 | auth | — | Authentication required: credentials are missing, expired or invalid | Send an `Authorization: Bearer ` header or a valid Nevermined API key. Anonymous access is not permitted on this endpoint. | | `BCK.AUTH.0003` | 403 | auth | — | Forbidden: caller is not the owner of this resource and lacks an admin role | Authenticate as the resource owner or an admin who has access to it. Cross-account access is rejected unless you carry an admin role. | | `BCK.AUTH.0004` | 403 | auth | ❌ | Organisation admin privileges required | The caller is not an active admin of the target organisation. Prefer the more specific siblings (BCK.AUTH.0005-0009) at new throw sites; this code remains as a catch-all. | | `BCK.AUTH.0005` | 403 | auth | ✅ | Unable to verify organisation membership | The membership lookup itself failed (e.g. transient DB error). Check the cause field on the server log; retry once. | | `BCK.AUTH.0006` | 403 | auth | ❌ | Caller does not belong to any organisation | Add the user as a member of the target organisation before calling admin-scoped endpoints. | | `BCK.AUTH.0007` | 403 | auth | ❌ | Caller does not have administrator privileges | The caller is a member but not an admin. Promote the role via the organisation admin UI / API, or call from an admin account. | | `BCK.AUTH.0008` | 403 | auth | ❌ | Caller account is not active | The user is suspended/disabled. Reactivate via the admin UI before retrying. | | `BCK.AUTH.0009` | 403 | auth | ❌ | Target organisation is not active | The org has been deactivated (subscription lapsed, manual disable, etc.). Reactivate before performing admin operations. | | `BCK.AUTH.0010` | 403 | auth | ❌ | Direct organisation creation is restricted to internal callers | End users must upgrade via /checkout/organization-upgrade. Internal tooling must provide a valid X-Ops-Org-Create-Token header matching OPS\_ORG\_CREATE\_TOKEN. | | `BCK.AUTH.0011` | 500 | internal | ❌ | Authenticated request did not yield a resolvable account address | The guard did not populate req.address or req.smartAccountAddress. The request either lacks a complete verified Privy identity or contains a linked wallet whose address was not resolved. Inspect the guard chain and wallet derivation for this route. | | `BCK.AUTH.0012` | 401 | auth | ❌ | Malformed Authorization header | The Authorization header was present but not a well-formed `Bearer `. Send `Authorization: Bearer ` (the second space-separated segment is the token). Triage tip: this code separates "garbage token" from "no token" — the latter throws BCK.AUTH.0002. | | `BCK.AUTH.0013` | 403 | internal | ❌ | Role guard active without @Roles metadata | A route was decorated with `@UseGuards(RolesGuard)` but no `@Roles(...)` declaration. The guard fails closed: no role list means no caller can satisfy the requirement. Add `@Roles(...)` to the handler or remove the `RolesGuard` wiring. | | `BCK.AUTH.0014` | 503 | integration | ✅ | Identity provider temporarily unavailable — could not verify the session | The Privy identity-token verification (`users().get({ id_token })`) could not reach Privy (rate-limited after the SDK retries, a 5xx, or a network/timeout). This is transient and does NOT mean the session is invalid — retry after a short backoff. If it persists, check the Privy status page and the service's identity-provider configuration. | | `BCK.AUTH.0015` | 401 | auth | — | Authentication required | Attach a valid `Authorization: Bearer ` (a Nevermined API key or a Privy identity token) and retry. | | `BCK.AUTH.0016` | 403 | auth | ❌ | Server-to-server operation not authorized | This server-to-server endpoint requires its configured workload identity or legacy ops-token credential. Send the credential documented for the route; browsers are not supported. | | `BCK.AUTH.0017` | 400 | validation | ❌ | Authenticated session has no linked wallet | Complete wallet setup or link a wallet, then refresh the Privy identity token and retry. Wallet-scoped resources require a wallet in the authenticated session. | ## `BCK.BILLING` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.BILLING.0001` | 403 | auth | ❌ | Bootstrap endpoint is not enabled in this environment | The Stripe tier-products bootstrap endpoint, the Nevermined Subscription catalog bootstrap and /invitations/expire-stale are gated behind `OPS_BOOTSTRAP_TOKEN`. Leave the env var unset to keep them disabled; set it to enable. | | `BCK.BILLING.0002` | 403 | auth | ❌ | Invalid bootstrap token | The X-Bootstrap-Token header did not match `OPS_BOOTSTRAP_TOKEN`. This endpoint is operator-only — request the token from infra. | | `BCK.BILLING.0003` | 503 | integration | ❌ | Stripe is not configured in this environment | `STRIPE_API_KEY` is unset in this deployment, so nothing that calls Stripe can run: the tier-products bootstrap, organization billing, and the cancellation of stale tier subscriptions during reconciliation. Configure Stripe credentials. | | `BCK.BILLING.0004` | 503 | integration | ✅ | Tier catalog row missing for the requested (tier, currency, interval) combination | Run the hybrid-tier-plans bootstrap (`ENABLE_ORG_TIER_BOOTSTRAP`=true on next startup, or POST /api/v1/organizations/billing/tier-bootstrap with the ops token) to materialise the catalog rows. Returns 503 because the deployment has not been fully provisioned yet — clients may retry once the operator finishes the bootstrap. | | `BCK.BILLING.0010` | 400 | validation | ❌ | Invalid combination of currency and interval for org-tier checkout | USD and EUR plans must use interval=month or year (Stripe). USDC and EURC plans must use interval=one\_shot (on-chain payment). Other combinations are rejected. | | `BCK.BILLING.0013` | 400 | business | ❌ | No active subscription found to cancel for this organization | The /billing/cancel endpoint requires an existing Stripe-backed subscription on the org. An organization tier bought in the Nevermined app populates this row; legacy crypto-paid orgs do not and cannot be canceled this way. | | `BCK.BILLING.0014` | 400 | business | ❌ | Subscription is already canceled — cannot downgrade | Stripe rejects updates on canceled subscriptions. Start a fresh subscription via /checkout/organization-upgrade instead of attempting to downgrade the cancelled one. | | `BCK.BILLING.0015` | 400 | validation | ❌ | Invalid downgrade target tier | A downgrade target must be a paid tier below your current one. Use /billing/cancel to end the subscription instead. | | `BCK.BILLING.0016` | 400 | business | ❌ | No active subscription found to downgrade for this organization | The /billing/downgrade endpoint requires an existing live Stripe-backed subscription on the org. Legacy crypto-paid orgs and orgs without a tier subscription cannot be downgraded this way. | | `BCK.BILLING.0017` | 400 | business | ❌ | Target tier is not below the current tier — nothing to downgrade | A downgrade target must be a paid tier strictly below the current one (Enterprise → Premium/Starter, Premium → Starter). Use /billing/upgrade to move up, or /billing/cancel to end the subscription. | | `BCK.BILLING.0018` | 503 | integration | ✅ | Catalog row has no Stripe priceId — Stripe products bootstrap incomplete | Run the Stripe products bootstrap (POST /api/v1/organizations/billing/bootstrap with the ops token, or `ENABLE_ORG_TIER_BOOTSTRAP`=true at startup) so the catalog row is paired with a Stripe price. Returns 503 because the deployment is partially provisioned; clients may retry once Stripe wiring lands. | | `BCK.BILLING.0019` | 502 | integration | ❌ | Stripe subscription has no line items | The Stripe subscription on file has zero items, which prevents an in-place price swap (upgrade or downgrade). Inspect the subscription in the Stripe dashboard — this should never happen for org-tier subs we minted ourselves. | | `BCK.BILLING.0020` | 502 | integration | ✅ | Stripe Checkout session created without a hosted URL | Stripe accepted the Checkout session create but returned no `url`. Treat as a transient Stripe API anomaly — retry the checkout endpoint. If it persists, inspect the Stripe Dashboard's events for the session id we return in params. | | `BCK.BILLING.0022` | 409 | business | ❌ | Organization already has an active subscription | A live Stripe subscription (active, trialing, or past\_due) already exists for this org, so /billing/checkout would create a SECOND one and bill the org twice. Use /billing/upgrade or /billing/downgrade to change tier on the existing subscription. Re-subscribing via /checkout is only allowed once the current subscription is canceled. | | `BCK.BILLING.0023` | 400 | validation | ❌ | Invalid upgrade target tier | An upgrade target must be a paid tier above your current one. To start a brand-new subscription use /checkout; to step down use /billing/downgrade. | | `BCK.BILLING.0024` | 400 | business | ❌ | No active subscription found to upgrade for this organization | The in-place /billing/upgrade requires an existing live Stripe-backed subscription on the org. An organization tier is first bought in the Nevermined app with an enrolled card; legacy crypto-paid orgs and orgs without a tier subscription cannot be upgraded this way. | | `BCK.BILLING.0025` | 400 | business | ❌ | Target tier is not above the current tier — no in-place upgrade available | An upgrade target must be a paid tier strictly above the current one (Starter → Premium/Enterprise, Premium → Enterprise). A not-yet-subscribed org first buys its tier in the Nevermined app with an enrolled card, and Enterprise is already the top tier. | | `BCK.BILLING.0026` | 400 | business | ❌ | Subscription is already canceled — cannot upgrade | Stripe rejects updates on canceled subscriptions. Buy the tier again in the Nevermined app with an enrolled card instead of attempting to upgrade the canceled one. | | `BCK.BILLING.0027` | 502 | integration | ❌ | Could not set up payment for the upgrade | The upgrade opened a Stripe proration invoice but no payment secret could be resolved for it — the invoice has none, a Stripe error blocked reading it, or an unexpected failure occurred — so the tier was not granted. Try again shortly; if it persists, contact support. | | `BCK.BILLING.0028` | 502 | integration | ✅ | Transient Stripe error resolving the upgrade proration payment | Stripe could not be reached to resolve the proration invoice for the tier upgrade, so the tier was not granted. This is transient — retry the upgrade shortly. | | `BCK.BILLING.0029` | 409 | business | ❌ | Upgrade requires a payment but the prorated amount is zero | The prorated charge for this tier change is \$0 (the subscription is already effectively on this tier for the current period, or an account credit covers it). A tier upgrade must collect a real payment, so it was refused and the tier was NOT changed. If you believe this is wrong, contact support — the subscription may need reconciliation. | | `BCK.BILLING.0030` | 409 | business | ❌ | You are already subscribed to this tier or a higher one. | Your local subscription view is stale. Please refresh to see your current tier. | | `BCK.BILLING.0031` | 400 | business | ❌ | This in-place upgrade requires an interactive-payment client (API 1.43+). | The upgrade now returns a Stripe payment secret the caller must confirm, so it is refused BEFORE any change is made in Stripe for a client pinned below API 1.43 (which cannot render the payment form). Pin `Nevermined-Version: 1.43` (or a newer default on your API key) and retry. | | `BCK.BILLING.0032` | 409 | business | ❌ | A payment for this upgrade is already being processed. | An earlier payment for this exact tier upgrade is still clearing (e.g. a bank debit), so there is nothing to collect and starting a new one would risk a double charge. Wait for it to settle — the upgrade applies automatically once it does — then refresh. | | `BCK.BILLING.0033` | 500 | internal | ❌ | Organization tier upgrade reversal requires manual reconciliation | The upgrade payment or subscription is missing the metadata needed to safely restore the prior tier. An operator must reconcile the paymentIntentId and subscriptionId and repair the metadata before replaying the webhook. Automatic retries alone cannot resolve this data-integrity error. | | `BCK.BILLING.0034` | 500 | integration | ❌ | Stripe org-tier event references an organization not in this environment | A Stripe org-tier event (test or live mode) carried a metadata orgId with no organization in this deployment's database — almost always another deployment on the same Stripe account. The error is permanent, so the webhook is ACKed and Stripe stops retrying. Investigate only if this deployment owns params.orgId: if no deployment on that Stripe account has the org, this is local state loss and the event (possibly a paid invoice) was dropped. | | `BCK.BILLING.0035` | 502 | integration | ✅ | Could not read the organization's invoices | The organization's Stripe invoices or upgrade receipts could not be read, so the list was not returned. A Stripe connection or rate-limit error clears on a retry; if it persists, the API's `org billing: invoices read failed for org …` log line names the cause. A refund state that cannot be read does not cause this: that row reads `refundStatus: 'unknown'` and the list is still returned. | ## `BCK.BRAINTREE` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.BRAINTREE.0001` | 500 | integration | — | Braintree platform gateway is not configured | The Braintree platform gateway could not be built. Check `BRAINTREE_MERCHANT_ID` / `BRAINTREE_PUBLIC_KEY` / `BRAINTREE_PRIVATE_KEY` (the platform gateway itself), `BRAINTREE_OAUTH_CLIENT_ID` / `BRAINTREE_OAUTH_CLIENT_SECRET` (connecting seller accounts), and that `ENVIRONMENT` is a value this deployment recognises. | | `BCK.BRAINTREE.0002` | 400 | integration | — | Braintree charge failed | Inspect the Braintree dashboard for the transaction id in params. Common causes: processor declined, invalid CVV, or insufficient funds. | | `BCK.BRAINTREE.0003` | 502 | integration | — | Braintree OAuth token refresh failed | Inspect the underlying error in logs. Token refresh failed — usually expired credentials; the merchant must re-authorize via OAuth. | | `BCK.BRAINTREE.0004` | 400 | integration | — | Plan owner has not connected a Braintree merchant account | The plan owner has not connected Braintree. They must complete OAuth on the seller dashboard before their plans can be sold via Braintree. | | `BCK.BRAINTREE.0005` | 400 | integration | — | Plan is not a fiat plan — cannot be purchased via Braintree | Use Braintree only for fiat plans. Crypto plans must be paid through the on-chain flow. | | `BCK.BRAINTREE.0006` | 409 | integration | — | Plan owner has no Braintree merchant account connected | The plan owner has revoked or never connected their Braintree account. Ask them to reconnect before retrying the purchase. | | `BCK.BRAINTREE.0007` | 400 | integration | — | Plan owner's Braintree account has no active merchant account in the plan's currency | No active Braintree merchant account was found for the plan’s currency: commonly the seller has none in that currency and must add one, or has one that is suspended or pending rather than active — a suspended account has to be resolved with Braintree, while a pending one activates on its own. Either way the seller must then reconnect Braintree (disconnect, then connect again) for the cached account list to be rebuilt. | | `BCK.BRAINTREE.0008` | 400 | integration | — | Cannot create a Braintree plan in this currency: no active Braintree merchant account was found for you in that currency. If you have not connected Braintree, start there; otherwise add a merchant account in that currency, or check whether the one you have is suspended or pending, then reconnect Braintree to refresh. | You will also see this if you have never connected Braintree, so confirm the connection first. If it is connected, look in the Braintree dashboard for a merchant account in the requested currency: add one if there is none; if there is one it is commonly suspended or pending — a suspended account has to be resolved with Braintree, while a pending one activates on its own. Once it is active, reconnect Braintree (disconnect, then connect again) so the cached account list is rebuilt. | | `BCK.BRAINTREE.0009` | 400 | integration | — | Plan metadata is missing currency. Plans must specify a currency to be settled via Braintree. | Re-publish the plan with metadata.currency populated. Braintree cannot route the settlement without a target currency. | | `BCK.BRAINTREE.0010` | 503 | integration | ✅ | Braintree/PayPal payment provider is not available in this environment | Set `BRAINTREE_MERCHANT_ID`, `BRAINTREE_PUBLIC_KEY`, and `BRAINTREE_PRIVATE_KEY` in the deployment env. Returns 503 because the route is reachable only after the operator wires Braintree up. | | `BCK.BRAINTREE.0011` | 400 | integration | — | The connected Braintree account has no merchant account that can receive payments, so the connection was refused | No merchant account on that Braintree account is active — commonly every one of them is pending or suspended, and it also covers having none at all. A suspended account has to be resolved with Braintree, while a pending one becomes active on its own. Connect again once one is active. Nothing was stored on our side, so our record of any previous connection is unchanged. | | `BCK.BRAINTREE.0012` | 503 | integration | ✅ | Could not verify the connected Braintree account’s merchant accounts, so the connection was refused | Listing the merchant accounts failed transiently (network, timeout, rate limit or a Braintree outage), so we cannot confirm the account can receive payments. Connect again. Nothing was stored on our side, so our record of any previous connection is unchanged. | | `BCK.BRAINTREE.0013` | 502 | integration | ❌ | Braintree permanently refused to list the merchant accounts, so the connection was refused | Braintree rejected the request outright (authentication, authorization, not found or upgrade required) rather than failing transiently, so retrying will not help. Seller: disconnect and connect again from the dashboard to re-authorize. Operator: if every seller hits this, the OAuth application has most likely lost the `merchant_account:all` scope. Nothing was stored on our side. | | `BCK.BRAINTREE.0014` | 400 | integration | ❌ | The connected Braintree account has no active merchant account in a currency Nevermined settles, so the connection was refused. Nevermined settles USD and EUR. | Merchant accounts were found on that Braintree account, but none of them is an active account in USD or EUR — the only currencies Nevermined settles. Add a USD or EUR merchant account in the Braintree control panel, then connect again; the accounts already there do not need changing. Nothing was stored on our side, so our record of any previous connection is unchanged. | | `BCK.BRAINTREE.0015` | 400 | validation | ❌ | That merchant account is not one of the accounts discovered for this currency on your connected Braintree account | Pick one of the merchant accounts listed for this currency. If the account is new, or the list is empty because your connection predates us recording it, disconnect and connect Braintree again to rediscover your accounts. Nevermined settles USD and EUR only. | | `BCK.BRAINTREE.0016` | 400 | business | ❌ | That merchant account cannot currently receive payments, so it cannot be used to settle this currency | The account is yours, but Braintree reports it as pending or suspended and a charge routed to it would fail. A suspended account has to be resolved with Braintree, while a pending one becomes active on its own; reconnect Braintree once it is active and it becomes selectable. Your current setting is unchanged. | | `BCK.BRAINTREE.0017` | 400 | validation | ❌ | Nevermined does not settle that currency, so a merchant account cannot be routed to it | Nevermined settles USD and EUR only. Plans can be priced in USD, EUR, USDC or EURC, and the two crypto currencies settle on-chain rather than through Braintree. Your current setting is unchanged. | | `BCK.BRAINTREE.0018` | 402 | business | ❌ | Braintree declined the card | The card issuer refused the charge — commonly insufficient funds, or a card that is expired, blocked or not permitted for this kind of purchase. No charge was captured and the spending reservation is rolled back, so nothing needs reconciling. Use a different payment method; retrying the same card will not help. The processor-side detail is in the API logs (the response deliberately carries no processor text, which can echo card data). | | `BCK.BRAINTREE.0019` | 400 | integration | ❌ | This plan cannot be purchased through checkout | Checkout fulfils a purchase through the fiat payment template, and this plan is registered on a different on-chain template (see params.templateAddress). A pay-as-you-go plan is paid per request through a card delegation (x402) instead of checkout; for any other template, contact the plan owner. Nothing was charged. | | `BCK.BRAINTREE.0020` | 502 | integration | ❌ | Braintree GraphQL request failed | Braintree answered a network-token GraphQL request with a 5xx, a 408 or another non-2xx status that does not prove the request was refused, or with a body that is not JSON. The card payment flow classifies it by step: before the charge it is a decline that nothing was charged for (BCK.BRAINTREE.0002), during the charge it may have charged (BCK.X402.0048). Clients receive those codes, not this one. | | `BCK.BRAINTREE.0021` | 502 | integration | ❌ | Braintree refused the GraphQL request before running it | Braintree answered a network-token GraphQL request with a 4xx other than 408 (for example an expired seller OAuth token, a rate limit or a request it would not accept). Braintree answers every operation it executes with a 200, so nothing was authorized; the card payment flow reports it as the rollback-safe decline BCK.BRAINTREE.0002 at either step. Clients receive that code, not this one. | ## `BCK.BUDGETS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.BUDGETS.0001` | 403 | business | ❌ | Group budgets are not available on this organization tier | Group budgets require a Premium or Enterprise organization. Upgrade the organization tier to set spend budgets on groups. | | `BCK.BUDGETS.0002` | 404 | business | ❌ | Group budget not found | No budget with that id for this group. Create one with POST /organizations/:orgId/groups/:groupId/budgets. | | `BCK.BUDGETS.0003` | 422 | business | ❌ | Group budget exceeded: this charge would exceed the group spend budget for the current period | The group has reached its spend budget for this period. Wait for the budget to reset, or an org admin can raise the limit. | | `BCK.BUDGETS.0004` | 422 | validation | ❌ | Invalid group budget: the spending limit must be a positive number of cents | Provide spendingLimitCents as a whole number of minor units greater than 0 (e.g. "150000" for \$1,500). | | `BCK.BUDGETS.0005` | 409 | business | ❌ | A budget already exists for this currency in this group | Each group holds one budget per currency. Edit the existing budget for this currency, or create the budget in a different currency. | | `BCK.BUDGETS.0006` | 422 | business | ❌ | No group budget is configured for this currency | An organization-wallet spend must be capped by a group budget. Add a budget in this currency to the group that shares the wallet. | ## `BCK.CARD_PAYMENT` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.CARD_PAYMENT.0001` | 404 | business | ❌ | The enrolled card cannot pay | params.paymentMethodId names no active card of the caller that can pay this purchase: it does not exist, belongs to someone else, is revoked, or carries no active network token. Only cards listed by GET /api/v1/payment-methods/chargeable qualify. Nothing was charged. | | `BCK.CARD_PAYMENT.0002` | 402 | business | ❌ | The enrolled card was declined | The card issuer refused the payment (params.declineCode when it gave one). Nothing was charged. Try another card. | | `BCK.CARD_PAYMENT.0003` | 502 | integration | ✅ | The enrolled card could not be authorised with the card network | No payment cryptogram could be obtained for the card, so nothing was sent to the payment processor and nothing was charged (paying the Nevermined Subscription, params.subscriptionId names the attempt, which was cancelled). Retry, or use another card. | | `BCK.CARD_PAYMENT.0004` | 502 | integration | ❌ | The outcome of the enrolled-card payment is unknown | The payment processor did not confirm the outcome, and the card may have been charged. Do not retry: the purchase completes, or fails, once the processor reports it. On a card change, send the same card with params.intentId to read where its payment stands. | | `BCK.CARD_PAYMENT.0005` | 409 | business | ❌ | Paying with an enrolled card is not available for this purchase | Paying this purchase (params.purpose) with a card enrolled with Nevermined is turned off on this deployment. GET /api/v1/payment-methods/chargeable answers enabled: false for it. | | `BCK.CARD_PAYMENT.0006` | 503 | internal | ✅ | The enrolled cards could not be read | Reading the caller’s enrolled cards failed, so it is not known which can pay. Nothing was charged and no card was judged unusable. Retry shortly. | | `BCK.CARD_PAYMENT.0007` | 409 | business | ❌ | An earlier payment for this purchase was made or is under way | An earlier attempt at the same purchase (params.subscriptionId) was charged or its payment is still being processed, so this one was refused and nothing was charged for it. Do not pay again. For a one-off plan (params.paymentIntentId) the same holds until a few minutes after that purchase was delivered. | | `BCK.CARD_PAYMENT.0008` | 400 | validation | ❌ | The organization tier purchase does not say which organization it is for | Paying an organization tier (params.planId) with an enrolled card needs orgId (the organization to upgrade) or intent: create without orgId (a new organization). Nothing was charged. | | `BCK.CARD_PAYMENT.0009` | 503 | internal | ✅ | What the enrolled card pays for could not be read | Reading the subscriptions and credit top-ups the card pays for failed, so the card was not revoked. Retry shortly, or revoke it anyway with confirm=true. | | `BCK.CARD_PAYMENT.0010` | 409 | business | ❌ | The card pays for a subscription, an organization tier or credit top-ups | params.pays lists what the card pays for (purpose, and orgId/orgName for an org tier). Nothing was revoked. Revoking it pauses automatic credit top-ups, but a subscription or org tier keeps renewing on the card saved at Stripe until it is cancelled or paid with another card. Send confirm=true to revoke it anyway. | | `BCK.CARD_PAYMENT.0011` | 404 | business | ❌ | No live subscription to change the card of | The subscription or organization tier (params.ownerType, params.orgId or params.subscriptionId) has ended, was never paid through Stripe, or its first payment is still in progress, so no card renews it. Finish or restart the subscription to choose a card. | | `BCK.CARD_PAYMENT.0012` | 404 | business | ❌ | The card change to finish is not this subscription’s | params.intentId is not a card change of this subscription to this card (another subscription, another card, no longer its latest invoice, unknown to Stripe or cancelled). Nothing was changed. Start the card change again. | | `BCK.CARD_PAYMENT.0013` | 502 | internal | ✅ | Stripe could not complete the card change | params.step names the Stripe call that failed. With params.intentId the change reached Stripe: send the same card with that intentId to finish it. Without it nothing was confirmed: start the change again. | | `BCK.CARD_PAYMENT.0014` | 503 | internal | ✅ | The card that renews the subscription could not be read | Reading the subscription at Stripe failed (an outage, or a configuration fault on our side). Nothing was changed: retry shortly, and report it if it persists. | | `BCK.CARD_PAYMENT.0015` | 404 | business | ❌ | No enrolled card to reactivate | The caller has no active enrolled card with this id (the CRD id, or the id GET /api/v1/payment-methods lists). Pick a card from that list. | | `BCK.CARD_PAYMENT.0016` | 422 | validation | ❌ | The card network refused a new token for the card | The card cannot be reactivated (it may have been replaced, suspended or closed). Nothing was charged. Add the card again, or use another card. | | `BCK.CARD_PAYMENT.0017` | 503 | integration | ✅ | The card could not be reactivated yet | The new token is still being issued, or the card vault did not answer. Nothing was charged. Retry in a few seconds. | | `BCK.CARD_PAYMENT.0018` | 422 | business | ❌ | The enrolled card needs to be reactivated by its holder | The card has no active network token any more, so it cannot pay. Nothing was charged. Its holder reactivates it from Payment Methods in the Nevermined app; until then, use another card. To the cardholder, params.paymentMethodId names the card; an x402 settle names none. | | `BCK.CARD_PAYMENT.0019` | 403 | auth | ❌ | Only the cardholder can reactivate the card | A card is reactivated by its holder, signed in to the Nevermined app. An API key or an OAuth-minted credential cannot do it. | | `BCK.CARD_PAYMENT.0020` | 500 | internal | ❌ | The card could not be reactivated because of a fault on our side | The card vault refused the request for a reason that is not the card (a configuration fault on our side). Nothing was charged. Contact support. | | `BCK.CARD_PAYMENT.0021` | 409 | business | ✅ | Another card purchase by the caller is still being paid | Another of the caller’s card purchases held the per-user lock past its timeout, so this one stopped before doing anything. Nothing was charged for it. Retry once the other purchase has finished. | ## `BCK.CATALOG` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.CATALOG.0001` | 404 | business | ❌ | Agent service not found | No listed catalog service matches that slug. Slugs are case-sensitive; unlisted services are not exposed. | | `BCK.CATALOG.0002` | 500 | internal | ✅ | Failed to read the agent services catalog | Transient server-side error reading the catalog (list, detail, categories, or the claim-flow by-slug summary); safe to retry. Query inputs are validated upstream, so this is not a bad-request issue. | | `BCK.CATALOG.0003` | 400 | validation | ❌ | Invalid catalog filter | The `protocol` filter must be one of: x402, mpp, rest, a2a, other. | | `BCK.CATALOG.0004` | 404 | business | ❌ | Agent not found | No agent with that DID belongs to your organization. You can only publish agents your organization owns. | | `BCK.CATALOG.0006` | 409 | business | ❌ | Agent is already listed in the catalog | This agent already has a catalog listing. Edit or remove the existing listing instead of publishing it again. | | `BCK.CATALOG.0007` | 404 | business | ❌ | Catalog listing not found | No catalog listing with that id belongs to your organization. | | `BCK.CATALOG.0008` | 500 | internal | ✅ | Failed to write the catalog listing | Transient server-side error creating or updating the listing; safe to retry. | | `BCK.CATALOG.0009` | 409 | business | ❌ | Listing is not in a re-submittable state | Only an unlisted listing (validation failed or removed) can be re-submitted. A live or degraded listing is still publicly listed (re-submitting would unlist it until the next probe), and a pending one is already being validated. | | `BCK.CATALOG.0010` | 403 | business | ❌ | Listing is under moderation hold | A Nevermined moderator unlisted this listing. It cannot be re-submitted or re-validated by the owner — contact Nevermined support to have it reviewed. | | `BCK.CATALOG.0011` | 500 | internal | ✅ | Failed to store the catalog listing logo | Transient server-side error uploading the logo image to storage; safe to retry. | | `BCK.CATALOG.0012` | 400 | business | ❌ | Unsupported or invalid logo image | The logo must be a PNG, JPEG, WebP, GIF or ICO image (SVG is not accepted). Re-uploading the same file will not help — convert it to a supported raster format. | | `BCK.CATALOG.0013` | 500 | internal | ❌ | Logo storage is not configured | The public storage bucket for catalog logos is not set on this deployment; this is a server-side configuration issue, not retryable by the client. | | `BCK.CATALOG.0014` | 500 | internal | ❌ | Logo image bytes were not received | The raw logo bytes were not captured on the server for this request — a server-side body-parser wiring issue, not a client payload problem. Distinct from BCK.CATALOG.0012 (the bytes were received but are not a supported raster image). | | `BCK.CATALOG.0015` | 500 | internal | ✅ | Catalog validation service failed | The centralized validation service failed before it could classify the merchant endpoint. This is an API infrastructure failure, not an invalid-listing verdict; safe to retry. | | `BCK.CATALOG.0016` | 409 | business | ❌ | Listing is not pending validation | Only a pending listing can be validated. Refresh the listing state instead of retrying this request. | | `BCK.CATALOG.0017` | 409 | business | ✅ | Catalog validation retry is not due yet | The monitor must wait until the persisted validation retry schedule elapses. Read params.retryAfter for the next allowed attempt. An owner may still use the owned validate-now endpoint. | | `BCK.CATALOG.0018` | 409 | business | ✅ | Catalog validation is already in progress | Another validator owns the active claim. Wait for it to finish or for the claim timeout, then retry. | | `BCK.CATALOG.0019` | 400 | validation | ❌ | Catalog target already contains an endpoint path | Set targetUrl to the service base URL. The Router appends the selected endpoint path, so storing that same path in targetUrl would send requests to a double-stacked path. | | `BCK.CATALOG.0020` | 400 | validation | ❌ | Raw response bodies are forbidden with verification evidence | Remove the observation body before submitting bounded canary verification evidence. | | `BCK.CATALOG.0021` | 409 | business | ✅ | A catalog scoring analysis is already active | Wait for the active analysis to finish before requesting another one. | | `BCK.CATALOG.0022` | 404 | business | ❌ | Catalog scoring analysis not found | The analysis does not exist or is not accessible to this caller. | | `BCK.CATALOG.0023` | 400 | validation | ❌ | Catalog scoring target is invalid or unsafe | Use a public HTTP(S) endpoint URL (a path is fine) with no credentials, query string, or fragment. | | `BCK.CATALOG.0024` | 500 | internal | ❌ | Catalog scoring queue received an unusable service URL | Inspect the original error in logs. Queue callers must supply an absolute HTTP(S) service URL. | | `BCK.CATALOG.0026` | 409 | validation | ❌ | Catalog scoring idempotency key conflicts with the original request | Retry with the original serviceUrl, listingId, and agentDid unchanged, or use a new Idempotency-Key for a different analysis. | | `BCK.CATALOG.0027` | 400 | validation | ❌ | Catalog scoring request parameters are invalid | Supply no more than 50 valid UUID listing identifiers. | | `BCK.CATALOG.0028` | 400 | validation | ❌ | Catalog ops request body is invalid | Supply valid, size-bounded ops job evidence, result, and claim parameters. | | `BCK.CATALOG.0029` | 409 | business | ❌ | Catalog scoring claim is stale or no longer running | Drop the stale claim and request new work before reporting another outcome. | | `BCK.CATALOG.0030` | 400 | validation | ❌ | Catalog readiness badge style is invalid | Use one of the supported styles: shields, card, flat, or pill. | | `BCK.CATALOG.0031` | 404 | validation | ❌ | Unknown or non-claimable catalog ops queue | Use an external queue assigned to the authenticated workload identity. | | `BCK.CATALOG.0032` | 409 | business | ✅ | Catalog ops job target changed since claim | Discard the stale result and claim the job again to receive the current target. | | `BCK.CATALOG.0033` | 422 | validation | ❌ | Catalog ops evidence chunk too large | Send at most 50 probes per chunk and keep the JSON body within 256 KiB. | | `BCK.CATALOG.0034` | 403 | auth | ❌ | Catalog ops verification requires the canary capability | Only the catalog-canary workload identity may submit verification evidence. | | `BCK.CATALOG.0036` | 429 | business | ✅ | Daily readiness-analysis limit reached for this organization | You have reached the maximum manual readiness analyses for today (UTC). Try again tomorrow or contact support to raise the limit. | | `BCK.CATALOG.0037` | 429 | business | ✅ | Too many listings are pending readiness analysis for this organization | Wait for some pending analyses to finish before requesting new ones, or contact support to raise the limit. | | `BCK.CATALOG.0039` | 409 | business | ✅ | Catalog job lease is stale or no longer owned | Drop the stale claim and request new work. A retry of a committed completion returns outcome replayed; this code means no matching completion marker exists. | | `BCK.CATALOG.0040` | 400 | validation | ❌ | Catalog event or job payload is too large | Keep event payloads to ids and small facts (8 KB maximum), and job params to hints (4 KB maximum). | | `BCK.CATALOG.0041` | 500 | internal | ✅ | Catalog event processing failed | Retry the request and inspect the underlying catalog event error in server logs. | | `BCK.CATALOG.0042` | 404 | business | ❌ | Catalog listing not found or not available to claim | Only an unclaimed, auto-discovered listing can be claimed. | | `BCK.CATALOG.0043` | 409 | business | ❌ | Catalog listing already has an owner | This service has already been claimed or was published by an organization. | | `BCK.CATALOG.0044` | 422 | validation | ✅ | Domain ownership could not be verified | Add the exact DNS TXT record (or well-known file) and try again — DNS can take a few minutes to propagate. | | `BCK.CATALOG.0045` | 422 | business | ❌ | This service cannot be claimed by domain proof | This listing's host cannot be used for domain proof — it is a shared gateway serving many merchants, or its address could not be determined. Domain-based claiming is not available for it. | | `BCK.CATALOG.0046` | 422 | business | ✅ | The service domain cannot be verified from its current DNS | The domain resolves to a private or reserved address, which we will not probe. Point it at a public address and try again. | | `BCK.CATALOG.0047` | 503 | internal | ✅ | Domain ownership could not be checked right now | A DNS or network lookup did not complete while verifying — this is a transient condition, not a missing record. Try again shortly. | | `BCK.CATALOG.0048` | 500 | internal | ❌ | Catalog internal invariant violated | A catalog component found its own state inconsistent. Among others: a readiness rule that produced no result, catalog event writes switched on without the dependencies they need (both our wiring), or a settled payment row whose amount is not a whole number (bad data — inspect the router\_payments row named in the details). This is a server-side defect, not a problem with your request; quote the correlation id when reporting it. | | `BCK.CATALOG.0049` | 500 | internal | ✅ | Catalog owner-notification job has no reason | An owner-notification job was claimed without the unlist reason it must carry, so no email was sent. The job is failed and retried by the catalog queue. This is a server-side defect in whatever enqueued the job; inspect the job params for the listing id. | | `BCK.CATALOG.0050` | 500 | internal | ❌ | Catalog claim secret is not configured | CATALOG\_CLAIM\_SECRET is unset or shorter than its minimum length, so the catalog claim feature cannot sign challenge tokens and the API does not start. Set CATALOG\_CLAIM\_SECRET. | | `BCK.CATALOG.0051` | 409 | business | ✅ | A claim for this catalog listing is already in progress | Another verified claimant is completing the atomic adoption. Wait briefly and retry; the listing will either become owned or become available again. | | `BCK.CATALOG.0052` | 409 | business | ❌ | A claimed catalog listing cannot change its verified service URL | Keep the service URL that was bound to the domain proof. Claim metadata may still be edited. | ## `BCK.COMMON` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.COMMON.0001` | 500 | internal | — | Unable to initialize Nevermined instance | Inspect the API logs around startup. The Nevermined SDK could not initialise — usually a misconfigured RPC provider, missing wallet seed, or a chain-config mismatch. | | `BCK.COMMON.0002` | 500 | internal | — | Unable to generate session key | Inspect the underlying error in logs. The Nevermined SDK could not derive a session signer — usually a wallet/keystore configuration problem. | | `BCK.COMMON.0003` | 500 | internal | — | Unable to retrieve fees information from Nevermined | Inspect the underlying error in logs. The protocol fee lookup failed — verify chain connectivity and that the FeeController contract is reachable. | | `BCK.COMMON.0004` | 500 | internal | — | Unable to calculate Asset Price | Inspect the underlying error in logs. The pricing helper failed — usually a missing/invalid plan price metadata or a chain-side revert. | | `BCK.COMMON.0005` | 500 | internal | — | Unable to load NFT Contract | Inspect the underlying error in logs. The NFT contract handle could not be resolved — verify the address registered in protocol config matches the deployed contract. | | `BCK.COMMON.0006` | 500 | internal | — | Unable to register Credits Plan on Nevermined | Inspect the underlying error in logs. Credit plan registration failed at protocol or SDK layer — re-run after fixing the cause; the partial plan row (if any) needs manual cleanup. | | `BCK.COMMON.0007` | 500 | internal | — | Unable to register Time Plan on Nevermined | Inspect the underlying error in logs. Time plan registration failed at protocol or SDK layer — re-run after fixing the cause; the partial plan row (if any) needs manual cleanup. | | `BCK.COMMON.0008` | 500 | internal | — | Unable to register Points event in the database | Inspect the underlying error in logs. The points-event insert failed — typically a DB-side constraint or connectivity issue. Re-run idempotently or backfill manually. | | `BCK.COMMON.0009` | 500 | internal | — | Unable to register API Key usage in the database | Inspect the underlying error in logs. The API-key usage insert failed — typically a DB-side constraint or connectivity issue. | | `BCK.COMMON.0010` | 500 | internal | — | Unable to register AI Agent | Inspect the underlying error in logs. Agent registration failed at protocol or DB layer. The partial row (if any) should be removed before retry. | | `BCK.COMMON.0011` | 500 | internal | — | Unable to register File asset | Inspect the underlying error in logs. File asset registration failed — usually a storage-layer or DDO-write error. | | `BCK.COMMON.0012` | 500 | internal | — | Unable to generate access token to AI Agent | Inspect the underlying error in logs. Access-token minting failed — verify the agent is registered and the requesting user has a valid plan. | | `BCK.COMMON.0013` | 404 | internal | — | Unable to resolve DDO from DID | Verify the DID is well-formed and exists in metadata. The DDO resolver returned no document; this is a 404 by design. | | `BCK.COMMON.0014` | 404 | internal | — | Plan not found | Verify the planId. The plan may have been deleted or never registered. Common causes: stale link, environment mismatch (sandbox vs live). | | `BCK.COMMON.0015` | 500 | internal | — | Unable to get the Plan balance | Inspect the underlying error in logs. Balance lookup failed — usually a chain RPC or contract-call revert. | | `BCK.COMMON.0016` | 500 | internal | — | Unable to order the subscription | Inspect the underlying error in logs. Subscription ordering failed — verify the buyer has sufficient balance and the plan is active. | | `BCK.COMMON.0017` | 500 | internal | — | There are no files associated to the file asset | Re-publish the asset with at least one file entry, or use a different agent endpoint that does not require files. | | `BCK.COMMON.0018` | 500 | internal | — | An error happened while downloading the asset files | Inspect the underlying error in logs. Asset file download failed — usually a storage-layer access issue or expired signed URL. | | `BCK.COMMON.0019` | 500 | internal | — | An error happened while trying to mint credits | Inspect the underlying error in logs. Credit minting failed at protocol or SDK layer — verify the plan exists and the credit type matches. | | `BCK.COMMON.0020` | 500 | internal | — | An error happened while trying to burn credits | Inspect the underlying error in logs. Credit burning failed — verify the user holds enough credits and the plan permits burning at this point. | | `BCK.COMMON.0021` | 404 | internal | — | Unable to resolve widget metadata from DID | Verify the DID is a widget DID and exists. Widget metadata resolution returns 404 when the DID is not registered or its metadata was pruned. | | `BCK.COMMON.0022` | 403 | internal | — | Method not supported | The endpoint or sub-feature is disabled in this deployment. Check feature-flag configuration before retrying. | | `BCK.COMMON.0023` | 403 | internal | — | Error parsing input | Inspect the request body against the documented schema for this endpoint. The parser rejected a required field or malformed JSON. | | `BCK.COMMON.0024` | 401 | auth | — | Could not validate the login claim | Re-issue a fresh login claim. The signed claim either has an invalid signature, an expired timestamp, or was issued for a different audience. | | `BCK.COMMON.0025` | 400 | internal | — | Invalid UUID format in request | Provide a valid UUID v4 string in the highlighted field. Most ID parameters require canonical UUID format. | | `BCK.COMMON.0026` | 400 | validation | — | Invalid uint256 identifier (must be a decimal string in \[0, 2^256 - 1]) | Provide a decimal-string uint256 in the highlighted field (no 0x prefix, no scientific notation). Plan IDs and agent IDs use this format end-to-end. | | `BCK.COMMON.0027` | 409 | business | ❌ | Resource already exists (database unique constraint violated) | A record with the same unique key already exists. Either update the existing record or use a different identifier. | | `BCK.COMMON.0028` | 409 | business | ❌ | Referenced resource does not exist (foreign key violation) | The request references an entity (plan, agent, user, organisation) that does not exist or has been deleted. Verify the referenced ID. | | `BCK.COMMON.0029` | 503 | integration | ✅ | Database temporarily unavailable | The database is being restarted or is under maintenance. Retry the request after a short backoff. | | `BCK.COMMON.0030` | 500 | internal | ❌ | Invalid ECDSA public key format | The provider public key did not match the expected 65-byte uncompressed prefix (0x04 + x + y). Inspect getProviderPublicKey() output. | | `BCK.COMMON.0031` | 500 | internal | ❌ | Invalid ECDSA public key length | After normalising, the provider public key was not 128 hex characters (64 bytes). Inspect getProviderPublicKey() output and the upstream key derivation. | | `BCK.COMMON.0032` | 500 | internal | ❌ | Provider public key not available for JWKS endpoint | NeverminedService.getProviderPublicKey() returned empty. Verify the node wallet seed configuration and that the service initialised successfully at startup. | | `BCK.COMMON.0033` | 404 | integration | ❌ | Email challenge search returned no rows or the query failed | Inspect the underlying error in logs. The historical behaviour mapped any failure here to a 404; preserved for backward compatibility. A failed search usually means a DB-layer error or invalid filter combination. | | `BCK.COMMON.0034` | 400 | validation | ❌ | Query parameter exceeds maximum length | A bounded query parameter (e.g. `textSearch`) was sent above its byte/character limit. Truncate the value client-side and retry. Limits exist to bound the cost of downstream filters — see the parameter description in the OpenAPI spec. | | `BCK.COMMON.0035` | 500 | internal | ❌ | No RPC is configured for the primary network | WEB3\_PROVIDER\_URIS has no entry for the deployment's primary network, and the API refuses to fall back to a public RPC for login-token verification. The API does not start. Set WEB3\_PROVIDER\_URIS for the primary network. | ## `BCK.CREDITS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.CREDITS.0001` | 400 | business | — | Mint amount must be positive | Send mint amount > 0. Zero or negative mints are rejected; cleanup of bad lots must happen through a refund path. | | `BCK.CREDITS.0002` | 400 | business | — | Burn amount must be positive | Send burn amount > 0. Zero or negative burns are rejected. | | `BCK.CREDITS.0003` | 402 | business | — | Insufficient credits for plan | Buy or top up credits before retrying. The buyer wallet does not hold enough credits for the requested redemption. | | `BCK.CREDITS.0004` | 400 | business | — | Refund amount must be positive | Send refund amount > 0. Zero or negative refunds are rejected; they are also bounded by the original mint amount. | | `BCK.CREDITS.0005` | 500 | business | — | Credit lots do not satisfy the burned amount — FIFO invariant violated | Inspect the underlying error and the planId/userId in params. The FIFO credit-lots ledger could not satisfy the burn — this indicates a data-integrity issue; do not retry blindly. | | `BCK.CREDITS.0006` | 500 | internal | ❌ | Cannot enqueue on-chain order mirror without a corresponding minted credit lot | enqueueFiatOrderMirror must be called after a successful creditsService.mint with the same sourceTx. This usually indicates an out-of-order call by a service, not a runtime data issue. | | `BCK.CREDITS.0007` | 500 | internal | ❌ | Refusing to create a credit lot without a valid expiry for this plan | A refund or reversal may omit expiresAt only for a plan that resolves with durationSecs = 0. See params.reason: expirablePlan / invalidExpiry mean the caller must pass a valid expiry (the restored lot's, or the current billing period end); planNotFound / durationUnknown mean the plan row could not prove the plan never expires, so the lot was refused rather than made immortal. | | `BCK.CREDITS.0008` | 404 | internal | ❌ | Credit burn to reverse was not found | reverseBurn takes the settlementId (planTransactions.txId) returned by burn(). No CreditBurn audit row carries this id. | | `BCK.CREDITS.0009` | 409 | internal | ❌ | Credit burn cannot be reversed automatically | The burn record does not identify exactly which lots it consumed and by how much, a consumed lot is missing from both the active ledger and the archive, the burn was mirrored on-chain (reversing it off-chain would drift the two ledgers), or an earlier reversal record of this burn is malformed. See params.reason. Do not retry; reconcile manually. | | `BCK.CREDITS.0010` | 404 | internal | ❌ | No credit lot was ever minted for this source | revokeBySource found no active lot and no CreditMint or CreditRefund audit row for (planId, holder, sourceTx). Check the source reference (e.g. the invoice id used at mint). | | `BCK.CREDITS.0011` | 409 | internal | ❌ | The credit burn for this request id was reversed; the id cannot be replayed | An agentRequestId buys at most one burn. Its burn was reversed (reverseBurn), so its credits are back with the holder and replaying it as settled would treat an uncharged call as paid. Retry the call under a NEW agentRequestId. | | `BCK.CREDITS.0012` | 500 | internal | ❌ | Could not persist the pending on-chain burn | The on-chain mirror worker could not record the UserOp hash of a burn it had submitted, so it rolled the whole tick back rather than lose track of the burn. The row stays pending and the next tick checks the on-chain balance before acting. Operator-facing; no client receives this code. | | `BCK.CREDITS.0013` | 500 | internal | ❌ | Refusing a credit lot or burn with a missing or unknown credit kind | Every lot of the Nevermined credits plan carries a credit kind (allowance, welcome, topup or sla), and a burn may only exclude those kinds. See params.reason: kindRequired means a mint or refund on the credits plan omitted its kind; unknownKind means a value outside the set was passed. A caller bug, not a runtime data issue; do not retry. | | `BCK.CREDITS.0014` | 503 | internal | ✅ | The credits balance could not be read | Reading your credits failed on our side (see the server log). Reading charges nothing and changes nothing; retry in a moment. | | `BCK.CREDITS.0015` | 500 | internal | ❌ | The credit scale is not available | No credit count can be converted safely, so none is assumed. See params.reason: noRow means the deployment has lost its stored scale, notLoaded means this process has not read it yet, and noTransaction means a caller read it for a write outside a transaction. A fault on our side; no client action helps. | | `BCK.CREDITS.0016` | 409 | business | ❌ | This deployment has not been rescaled | The credit scale is still 1, so there is nothing to tell holders and no email was sent. Run the rescale on this deployment first, then run this again. | | `BCK.CREDITS.0017` | 503 | internal | ✅ | The credit scale changed during this write | The count was read at params.expectedScale and the stored scale is now params.scale, so writing it would be wrong by the difference. Nothing was written. Read the count again and retry. | ## `BCK.CREDIT_RESCALE` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.CREDIT_RESCALE.0001` | 409 | business | ❌ | The stored credit scale is not the one this run expects | Nothing changed. params.scale is the stored scale and params.expectedScale is what the run named: usually this deployment has already been rescaled. Read the scale before running again. | | `BCK.CREDIT_RESCALE.0002` | 409 | internal | ❌ | A check failed, so the rescale was rolled back | Nothing changed. params.failures names each check that failed. Explain each before running again. A total moved by a concurrent writer (a notice being sent, a buyer changing a limit) clears on a re-run; anything else is a defect. | | `BCK.CREDIT_RESCALE.0003` | 503 | internal | ✅ | The rescale did not finish, so it was rolled back | Nothing changed. params.stage says whether it could not take its locks in time (locks), ran past its time limit (rewrite), or lost a deadlock (deadlock). Run again at a quieter moment. | | `BCK.CREDIT_RESCALE.0004` | 404 | business | ❌ | No rescale has run on this deployment | There is nothing to check. This deployment has no credit\_rescale\_runs row. | | `BCK.CREDIT_RESCALE.0005` | 409 | business | ❌ | This deployment has no single credits plan to rescale | Nothing changed. subscription\_catalog must name exactly one credits plan; params.plans says how many it names. Bootstrap the catalog first, or resolve the extra plan. | | `BCK.CREDIT_RESCALE.0006` | 500 | internal | ❌ | The rescale failed, so it was rolled back | Nothing changed. A statement failed unexpectedly: see the server log for the cause. | | `BCK.CREDIT_RESCALE.0007` | 500 | internal | ❌ | The rescale may or may not have committed | The commit did not answer. Read the stored scale and credit\_rescale\_runs for params.runId before doing anything: a run that applied has its row. Running again is safe, because expectedScale refuses a second run. | ## `BCK.CREDIT_TOPUPS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.CREDIT_TOPUPS.0001` | 404 | business | ❌ | Not found | This route is not available to the caller. Credit top-ups are dark-launched: they answer 404 when NVM\_CREDIT\_TOPUPS\_ENABLED is off in this deployment, and otherwise — unless NVM\_CREDIT\_TOPUPS\_OPEN admits every personal account — to every caller who has not been granted access. The cases are deliberately identical on the wire; the server log names which one applied. | | `BCK.CREDIT_TOPUPS.0002` | 400 | validation | ❌ | The monthly top-up limit is out of range | The limit is a whole number of US dollars, at least the price of one pack (params.minUsd) and at most the Nevermined maximum (params.maxUsd), and is sent only with `enabled: true` (switching top-ups off takes no limit). params.reason names a malformed body: limitRequired, enabledRequired or limitWithoutEnabled. Nothing was changed. | | `BCK.CREDIT_TOPUPS.0003` | 409 | business | ❌ | Top-ups are off | Top-ups are switched on by buying the first pack at checkout, which saves the card and sets the monthly limit; this route only changes the limit of top-ups that are on, or switches them off. Nothing was changed. | | `BCK.CREDIT_TOPUPS.0004` | 503 | internal | ✅ | The top-up settings could not be read or saved | Reading or saving your top-up settings — or the top-up consent (params.operation: readConsent, recordConsent or linkConsent), the first-pack checkout (checkout), or the pack history (history) — failed on our side (see the server log). Nothing was charged, and a failed save changed nothing; retry in a moment. | | `BCK.CREDIT_TOPUPS.0005` | 500 | internal | ❌ | Credit top-ups are not set up in this deployment | A configuration problem, not yours to fix. params.reason says which: noPackPrice — no credit top-up pack price is active here, and an operator must run the subscription catalog bootstrap with a topupPack; invalidSetting — a top-up setting of this deployment is unusable (the server log names it). Nothing was changed. | | `BCK.CREDIT_TOPUPS.0006` | 500 | internal | ❌ | The account’s billing record conflicts with another account | The Stripe customer this checkout resolved is recorded for a different account, so it was not used (see the server log). Nothing was charged and nothing was saved; contact support. | | `BCK.CREDIT_TOPUPS.0007` | 503 | internal | ✅ | The account’s billing record could not be read or saved | Reading or saving the billing record failed on our side (see the server log). Nothing was charged and nothing was saved; retry in a moment. | | `BCK.CREDIT_TOPUPS.0008` | 400 | validation | ❌ | The top-up consent was not given | The first pack is bought only with both top-up consents ticked: consent.autoTopup and consent.immediateSupplyWaiver must be true (params.missing names the ones that were not). Show each text from GET /api/v1/credits/topups/consent as its own unticked checkbox, and send them back once the buyer ticks them. Nothing was charged. | | `BCK.CREDIT_TOPUPS.0009` | 409 | business | ❌ | The top-up consent shown to the buyer is out of date | consent.version or consent.textSha256 is not the wording served now (params.currentVersion): the wording or the pack price it names changed since the page loaded. Reload GET /api/v1/credits/topups/consent, show it to the buyer again, and send its version and textSha256. Nothing was charged. | | `BCK.CREDIT_TOPUPS.0010` | 500 | internal | ❌ | The top-up consent could not be linked to this checkout | The checkout could not link its consent record (params.consentId) to its purchase (params.reason: notFound — no such consent for this account; linkedElsewhere — it is already linked to another purchase), so it stopped before charging (see the server log). Nothing was charged; start the checkout again. | | `BCK.CREDIT_TOPUPS.0011` | 409 | business | ❌ | Top-ups are already on, or being switched on | The first pack is bought once, to switch top-ups on. params.reason says why this checkout was refused: enabled — top-ups are on and not paused, so packs are already charged automatically when your credits run out (change the limit with PUT /api/v1/credits/topups); paymentInProgress — a first-pack checkout of yours was already paid and is still being recorded: wait a moment and read GET /api/v1/credits/topups; paymentUnrecorded — a first-pack checkout of yours was paid over an hour ago and could not be recorded: contact support, do not pay again. Nothing was charged by this request. | | `BCK.CREDIT_TOPUPS.0012` | 409 | business | ❌ | Top-ups are suspended | A card dispute on your subscription or on a top-up pack is open, so your credits are frozen and no pack can be bought until it is resolved. Nothing was charged. | | `BCK.CREDIT_TOPUPS.0013` | 409 | business | ❌ | This month’s top-up limit is reached | The packs bought this calendar month (UTC; params.boughtThisMonthUsd) plus one more pack (params.packPriceUsd) would exceed the monthly limit chosen (params.monthlyLimitUsd). Choose a higher limit, up to the Nevermined maximum, or wait for next month. Nothing was charged. | | `BCK.CREDIT_TOPUPS.0014` | 502 | integration | ✅ | Stripe refused or failed a top-up request | A Stripe call of the first-pack checkout failed (params.step: customer, customer-country, customer-tax-id, tax-preview, previous-invoice, invoice, item, finalize or payment-intent; see the server log). Nothing was charged. Retry in a moment. | | `BCK.CREDIT_TOPUPS.0015` | 500 | internal | ❌ | A paid top-up pack could not be recorded | An operator problem, never the buyer’s. A pack invoice of this deployment was paid, but could not be recorded (params.reason: purchasePaidByOtherInvoice — the purchase params.purchaseId was already paid by another invoice; purchaseMissing — the payment names a top-up consent of this deployment but no purchase (its checkout rolled back); customerMismatch / packMismatch — the purchase is billed to another Stripe customer, or for another pack price or terms, than it was claimed for; invoiceNotPaid — the invoice is not paid; noHolder — the account has no address to hold credits; noPlan — the pack price names no credits plan; noSavedCard — the first pack’s invoice names no enrolled card; noConsent — no top-up consent of the account names the purchase). The event is left unprocessed for a dashboard resend once fixed, or the payment refunded (see the server log). | | `BCK.CREDIT_TOPUPS.0016` | 409 | business | ❌ | The withdrawal period of this pack has ended | No longer returned: top-up packs are not withdrawable (BCK.CREDIT\_TOPUPS.0021). Older API versions returned it for a withdrawal requested more than 14 days after the purchase. Nothing was changed. | | `BCK.CREDIT_TOPUPS.0017` | 409 | business | ❌ | This pack cannot be refunded | params.reason says why the refund of the pack’s unused credits was refused: notPaid — the pack was never paid (params.status), so there is nothing to refund; nothingLeft — every credit of the pack was spent, or what is left is worth less than one cent; disputed — a card dispute on the account is open or was lost, so no refund can be made until it is resolved; refunded — part of the pack was already refunded another way, so it is handled by hand. Nothing was changed. | | `BCK.CREDIT_TOPUPS.0018` | 404 | business | ❌ | No such top-up pack | params.purchaseId names no top-up pack. Nothing was changed. | | `BCK.CREDIT_TOPUPS.0019` | 502 | integration | ✅ | Stripe refused or failed the refund | A Stripe call of the refund failed (params.step: invoice, credit-notes, credit-note-preview or credit-note; see the server log), and the pack’s credits were not touched. At every step but credit-note nothing was refunded; at credit-note Stripe may still have issued the refund. Retrying is safe either way: a refund already issued is recognised and never made twice. | | `BCK.CREDIT_TOPUPS.0020` | 500 | internal | ❌ | The pack’s refund could not be worked out | An operator problem, not yours to fix. params.reason says which: invoiceMismatch — the pack’s invoice does not bill the pack as it was bought; noPlan — no pack price of this deployment names the credits plan; noHolder — the account has no address holding its credits; alreadyRevoked — the pack’s credits were already clawed back; lotNotFound — the ledger holds no lot of the pack for the account’s address. Nothing was refunded and your credits were not touched (see the server log); contact support. | | `BCK.CREDIT_TOPUPS.0021` | 409 | business | ❌ | Top-up packs are not withdrawable | Packs are bought with an immediate-supply waiver: at the first pack the buyer asks for the credits of every pack to be made available at once and gives up the 14-day withdrawal right, so no pack can be withdrawn, however recently it was bought. Its credits stay in your balance and never expire. For a refund, contact support. Nothing was changed. | | `BCK.CREDIT_TOPUPS.0022` | 500 | internal | ✅ | An unexpected error occurred while charging a top-up pack | Whether a pack was charged for this request is unknown. Re-send the SAME requestId, which returns the pack already charged (if any) instead of charging another; do not start a new one. | | `BCK.CREDIT_TOPUPS.0023` | 500 | internal | ✅ | Could not determine whether a top-up pack was charged | A transient database fault prevented reading whether a pack was charged for this request. Re-send the SAME requestId, which returns the pack already charged (if any) instead of charging another; do not start a new one. | ## `BCK.DELEGATION` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.DELEGATION.0001` | 404 | business | ❌ | Payment method not found | Verify the paymentMethodId. The payment method may have been removed or never existed. | | `BCK.DELEGATION.0002` | 404 | business | ❌ | Delegation not found | Verify the delegationId. The delegation may have been revoked, expired, or never existed. | | `BCK.DELEGATION.0003` | 400 | validation | ❌ | Unknown payment method provider | The ?provider= query param must be one of the supported providers (stripe, braintree, erc4337, visa, vgs). Omit it to list methods from every provider. | | `BCK.DELEGATION.0004` | 400 | validation | ❌ | Required delegation input is missing | Provide both `provider` (stripe \| braintree \| erc4337 \| visa) and `currency` (usd \| eur \| usdc \| eurc) when creating a delegation. Both are required — the backend no longer defaults them. The `details` field names the specific missing input. | | `BCK.DELEGATION.0005` | 422 | business | ❌ | Card is not network-token chargeable | A `provider: "vgs"` delegation needs a portable credential (a CRD canonical card with an ACTIVE network token). The referenced card has none — it was enrolled with the canonical-credential flag off, its network-token provision failed at enrol, or the token was revoked. Re-enrol the card via the unified VGS-Collect enroll endpoint to (re)provision a network token, then retry. | | `BCK.DELEGATION.0006` | 422 | business | ❌ | Plan payment provider is not network-token capable | A `provider: "vgs"` delegation is plan-agnostic and settles through the plan’s `fiatPaymentProvider`, resolved at CHARGE time (#2082) — but that plan’s provider is not in the network-token-capable acquirer set (currently stripe, braintree). The plan metadata likely carries an unexpected/unsupported `fiatPaymentProvider`. Fix the plan’s payment provider, then retry. | | `BCK.DELEGATION.0007` | 400 | business | ❌ | Requested provider does not match the stored payment method | The create-delegation request declared a `provider` that does not match the provider the referenced payment method was enrolled under (e.g. requesting `stripe` for a card enrolled via the unified VGS-Collect rail, whose provider is `vgs`). Send the `provider` that matches the payment method — the value the delegation payment-methods list returns for it. | | `BCK.DELEGATION.0008` | 422 | business | ❌ | Delegation cannot be settled via card | This delegation was created on the crypto (`erc4337`) rail, which settles on-chain and has no card payment provider — a `nvm:card-delegation` settle cannot charge it (#2627). Settle a crypto delegation through the `nvm:erc4337` scheme instead, or create a card delegation (stripe/braintree/visa/vgs) for card settlement. | | `BCK.DELEGATION.0009` | 400 | validation | ❌ | delegationId must be a v4 UUID | The `delegationId` path parameter must be a v4 UUID (e.g. a1b2c3d4-e5f6-4a90-8bcd-ef1234567890). This is a request-format error, not an authentication or not-found failure — a well-formed but unknown id returns 404 instead. | | `BCK.DELEGATION.0010` | 500 | internal | ❌ | Invalid spend-cap amount | An amount to reserve, record, release or roll back against a spending cap was negative, blank or not a whole number, so the cap was left unchanged. On a reserve that means nothing was charged; on a release or rollback, what should have been given back was not; on a record of an already-settled payment, the spend was not counted. This is an internal invariant violation — inspect the API logs for the amount and the operation that produced it. | ## `BCK.ENTITLEMENTS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.ENTITLEMENTS.0001` | 403 | business | ❌ | Resource cap reached for your current workspace. Upgrade to unlock higher limits. | The active workspace (personal or Premium org) has hit its agent/plan cap. Response `params.cap` and `params.current` carry the limit and current count; switch workspaces, deactivate unused resources, or upgrade the org tier to lift the cap. | | `BCK.ENTITLEMENTS.0002` | 403 | business | ❌ | Organization is not active. Reactivate the subscription before creating new resources. | The target workspace has a lapsed subscription (paid period ended without renewal, or admin override). Existing resources remain visible but new agents/plans cannot be registered until the org is reactivated via the Billing page. | | `BCK.ENTITLEMENTS.0003` | 403 | business | ❌ | PayPal/Braintree settlement requires a Premium or Enterprise organization. | PayPal/Braintree settlement is available only to Premium or Enterprise organization workspaces. This is enforced both when linking a Braintree merchant account and when publishing a Braintree plan. Connect or publish under a paid organization workspace, choose Stripe or stablecoin settlement, or upgrade the organization on the Billing page. | | `BCK.ENTITLEMENTS.0004` | 403 | business | ❌ | Catalog publishing requires an active paid tier (Starter, Premium, or Enterprise). | Upgrade the organization to a paid tier to publish agents to the catalog. | | `BCK.ENTITLEMENTS.0005` | 403 | business | ❌ | Catalog listing limit reached for this tier. | Remove an existing listing or upgrade the tier to publish more agents to the catalog. | ## `BCK.FEATURE_ACCESS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.FEATURE_ACCESS.0001` | 404 | validation | ❌ | Unknown feature | The featureKey in the path is not one this API gates. Known keys are listed in apps/api/src/subscription/access/feature-keys.ts (`subscription`, `welcome-credits` and `credit-topups`); a grant for any other key would be a row nothing ever reads, so it is refused rather than stored. | | `BCK.FEATURE_ACCESS.0002` | 404 | validation | ❌ | Grant subject not found | No user profile (subjectType `user`, a `us-…` id) or organization (subjectType `org`, an `org-…` id) exists with that subjectId. Grants are refused for unknown subjects so a typo fails loudly instead of silently allowlisting nobody. | | `BCK.FEATURE_ACCESS.0003` | 500 | internal | ✅ | Feature access store failed | Reading or writing the feature\_access table failed (see the server log), or a grant raced a concurrent revoke of the same subject. A grant or revoke that returned this MAY OR MAY NOT have been applied: list the feature’s grants to see where it stands, or simply retry — grant and revoke are both idempotent. | ## `BCK.GROUPS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.GROUPS.0001` | 403 | business | ❌ | Organization groups are not available for this organization tier | Groups require a Premium or Enterprise organization. Upgrade the organization tier to create and manage groups. | | `BCK.GROUPS.0002` | 404 | business | ❌ | Group not found | The groupId does not exist in this organization, or has been deactivated. List groups to get valid ids. | | `BCK.GROUPS.0003` | 422 | business | ❌ | Groups cap reached: cannot create more groups for this organization | The active-group cap for this tier has been reached. Deactivate an unused group or upgrade the tier to create more. | | `BCK.GROUPS.0004` | 409 | business | ❌ | Member already belongs to an active group | A member can belong to at most one active group. Remove the member from their current group before adding them to another. | | `BCK.GROUPS.0005` | 404 | business | ❌ | Organization member not found | The memberId is not an active member of this organization. List members to get valid ids. | | `BCK.GROUPS.0006` | 404 | business | ❌ | Member is not in this group | The member is not an active member of the specified group; nothing to remove. | | `BCK.GROUPS.0007` | 404 | business | ❌ | Payment method not found | The payment method id does not match an enrolled card you own. Enroll a card first, then share it with the group. | | `BCK.GROUPS.0008` | 422 | validation | ❌ | Only card payment methods can be shared with a group | Only a Stripe or Braintree card already saved on the organization can be shared with a group. A crypto wallet cannot, and neither can a card enrolled today, which is a network-token card. | | `BCK.GROUPS.0009` | 409 | business | ❌ | Payment method is already shared with a group | A payment method belongs to at most one group. Remove it from its current group before sharing it elsewhere. | | `BCK.GROUPS.0010` | 404 | business | ❌ | Group payment method not found | This payment method is not shared with the specified group; nothing to remove. | | `BCK.GROUPS.0011` | 422 | validation | ❌ | Payment method is bound to a specific API key and cannot be shared with a group | This card is locked to one of your API keys, so group members could not charge it. Unbind the API key from the card before sharing it with the group. | | `BCK.GROUPS.0012` | 409 | business | ❌ | Card is not associated with this organization | Associate the card with this organization first (a personal card cannot be shared with an organization group). Only a card whose orgId matches this organization can fund its group budgets. | ## `BCK.GUEST` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.GUEST.0001` | 400 | validation | ❌ | Invalid guest account request | Check the request body — guest provisioning requires either fingerprint or externalId. | | `BCK.GUEST.0002` | 500 | business | — | Failed to provision guest account | Inspect the underlying error in logs. Guest provisioning failed mid-way — usually a DB-layer or Privy issue. | ## `BCK.INVITATIONS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.INVITATIONS.0001` | 422 | business | ❌ | Seat cap reached: cannot invite more members to this organization | The seat cap (members + pending invitations) for this tier has been reached. Remove pending invitations, deactivate inactive members, or upgrade the tier to invite more seats. | | `BCK.INVITATIONS.0002` | 409 | business | ❌ | A pending invitation already exists for this email in the organization | Revoke the existing invitation (or wait for the invitee to accept it) before sending a new one. Resending overwrites the role; revoking removes it entirely. | | `BCK.INVITATIONS.0003` | 404 | business | ❌ | Invitation token is invalid or has expired | Invitations expire 7 days after creation. Ask the org Admin to resend the invitation, which mints a fresh token. | | `BCK.INVITATIONS.0004` | 403 | business | ❌ | Email mismatch: the invitation was sent to a different email address | Sign in with the email address the invitation was sent to. Invitations are bound to a specific email and cannot be redirected. | | `BCK.INVITATIONS.0005` | 400 | validation | ❌ | Role not allowed: only Admin and Member roles are permitted for invitations | Pass role=Admin or role=Member. Other role values (e.g. Owner) are not assignable via invitation. | ## `BCK.LEGAL_DOCS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.LEGAL_DOCS.0001` | 404 | business | — | Unknown legal document | Verify the legal-document slug (terms, privacy, etc.). Unknown slugs are rejected to surface typos early. | | `BCK.LEGAL_DOCS.0002` | 404 | business | — | Unknown legal document version | Verify the document version. Unknown versions are rejected; ask the admin to publish the version first. | | `BCK.LEGAL_DOCS.0003` | 422 | business | — | Submitted legal document version is not the current effective version | Submit consent against the current effective version. The version in the request is older or newer than what the system is currently asking for. | | `BCK.LEGAL_DOCS.0004` | 412 | business | — | Legal consent is required for the current document versions | Have the user accept the current legal documents before retrying. The endpoint is gated on up-to-date consent. | | `BCK.LEGAL_DOCS.0005` | 500 | internal | ❌ | Authenticated request without a resolvable user identity | This is a server-side identity-resolution failure; retrying will not help. If it persists, contact support with the correlation id. | | `BCK.LEGAL_DOCS.0006` | 400 | business | — | No wallet linked to the authenticated Privy account | Link a wallet to the Privy account before retrying. Legal consent must be bound to an on-chain identity. | ## `BCK.METRIC` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.METRIC.0001` | 500 | integration | — | Error registering asset access | Inspect the underlying error in logs. Asset-access metric write failed — usually a DB/queue layer issue. Metrics are best-effort; the user request still completed. | | `BCK.METRIC.0002` | 404 | integration | — | Error search asset metrics | Verify the asset DID and that metrics retention has not pruned the rows. Empty metric lookups return 404 by design. | | `BCK.METRIC.0003` | 404 | integration | — | Error getting info from metrics service for | Inspect the underlying error in logs. Upstream metrics service did not respond — verify the metrics service URL and that it is reachable from the API. | | `BCK.METRIC.0004` | 500 | integration | — | Error getting balance for account | Inspect the underlying error in logs. Account-balance metric query failed — usually a DB or chain-RPC issue. | | `BCK.METRIC.0005` | 500 | integration | — | Error getting total hits for account | Inspect the underlying error in logs. Hits-counter aggregation query failed — usually a DB-layer error. | ## `BCK.METRICS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.METRICS.0001` | 401 | auth | ❌ | Unauthorized metrics scrape | The internal metrics endpoint is token-protected (METRICS\_SCRAPE\_TOKEN is set). Send `Authorization: Bearer ` matching the configured scrape token. | ## `BCK.MPP` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.MPP.0001` | 400 | validation | — | MPP is not supported on this payment rail | MPP settles on the crypto rail (nvm:erc4337) only. The card-delegation rail unwraps a JWT rather than an EIP-712 signature, so no MPP token can be settled through it. Request the token with the nvm:erc4337 scheme, or pay this plan over x402 instead. | | `BCK.MPP.0002` | 501 | internal | — | MPP is not configured on this deployment | MPP\_SECRET\_KEY and MPP\_REALM are missing or empty. Both are backend-only values set per deployment; without them the server cannot issue or verify challenges and fails closed. This deployment does not serve MPP — pay over x402 instead, or set both values to enable it. | | `BCK.MPP.0003` | 402 | business | — | Invalid payment credential | The credential did not verify. Request a fresh challenge and present a new credential. The reason is deliberately not disclosed — reporting which check failed would let a caller forge one iteratively. | | `BCK.MPP.0004` | 402 | business | — | Payment challenge expired | Challenges are short-lived. Re-request the protected resource to obtain a fresh 402 challenge and present a credential against that one. | | `BCK.MPP.0005` | 402 | business | — | Request body does not match the payment challenge | The challenge is bound to a digest of the request body. Send the exact body the challenge was issued for, or request a new challenge for the body you intend to send. | | `BCK.MPP.0006` | 500 | internal | — | Could not mint the MPP payment challenge | The challenge could not be built. Retry; if it persists this is a server-side fault and the correlation id in this response identifies it in the logs. | | `BCK.MPP.0007` | 400 | validation | — | MPP access tokens carry no token version | x402 struct versions are an x402 concept: MPP has its own token shape, chosen by the server, with no ordinal for a client to name — so `tokenVersion` is rejected on this route whatever its value, including 2. The split exists because MPP access tokens are reusable by design: one token is presented against many challenges, and single-use lives in the challenge — its id is the settlement id, so a replayed credential settles to the same burn. x402 version 3 makes the TOKEN single-use and stays available on POST /api/v1/x402/permissions. | ## `BCK.NOTIF` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.NOTIF.0001` | 404 | integration | — | Unable to find notification by id | Verify the notification id. The notification may have been deleted or never existed. | | `BCK.NOTIF.0002` | 404 | integration | — | Error searching for notifications | Inspect the underlying error in logs. Notification search failed — usually a DB-layer error or invalid query filter. | | `BCK.NOTIF.0003` | 500 | integration | — | Error updating notification | Inspect the underlying error in logs. Notification update failed — usually a DB-layer error. | | `BCK.NOTIF.0004` | 500 | integration | — | Error updating notification read status | Inspect the underlying error in logs. Notification read-status update failed — usually a DB-layer error. | | `BCK.NOTIF.0005` | 500 | integration | — | Error deleting notification | Inspect the underlying error in logs. Notification deletion failed — usually a DB-layer error. | | `BCK.NOTIF.0006` | 404 | integration | — | Error searching for notifications filtered by receiver | Verify the receiver address. Empty result sets surface as 404 by design. | | `BCK.NOTIF.0007` | 500 | integration | — | Resend API Key or Email Sender not set | Configure `RESEND_API_KEY` and `EMAIL_SENDER` in the deployment env. Email notifications are disabled until both are present. | | `BCK.NOTIF.0008` | 500 | integration | — | Error sending email notification | params.receiver names who the email was for, usually a user or organization id rather than an address, so resolve it to an address before searching the Resend dashboard logs. Common causes: invalid recipient address, domain not verified, or quota exhaustion. | | `BCK.NOTIF.0009` | 403 | business | ❌ | The user doesnt own this notification | Notifications are scoped to a single recipient; only the owner can act on them. Re-authenticating as the same caller will not help. | ## `BCK.OAUTH` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.OAUTH.0001` | 404 | auth | ❌ | OAuth resource not found | Verify the agentId or client identifier in the OAuth request. | | `BCK.OAUTH.0002` | 400 | auth | ❌ | Invalid OAuth request | Check the request parameters — typically the redirect\_uri, scope, or grant\_type does not match the registered client. Prefer the more specific BCK.OAUTH.0003-0006 siblings at new throw sites. | | `BCK.OAUTH.0003` | 400 | business | ❌ | No payment plans available for agent | The target agent has no published plans the caller can purchase. Publish a plan first, or pass an explicit plan\_id that the caller already owns. | | `BCK.OAUTH.0004` | 400 | auth | ❌ | Invalid or expired authorization code | Authorization codes are single-use and short-lived. Restart the flow from /authorize to obtain a fresh code, and ensure the code\_verifier matches the original PKCE code\_challenge. | | `BCK.OAUTH.0005` | 400 | auth | ❌ | Resource mismatch between token request and authorization code | The `resource` parameter on /token does not match the value bound to the authorization code. Resend with the same `resource` you used on /authorize. | | `BCK.OAUTH.0006` | 400 | auth | ❌ | User profile not found for the authorization code | The user bound to the authorization code no longer exists in our DB (deleted profile, or environment mismatch). Restart the flow with a valid signed-in user. | | `BCK.OAUTH.0007` | 400 | auth | ❌ | Authorize endpoint requires an authenticated user | The POST /oauth/authorize endpoint expects a signed-in user (NVM API key hash or Privy identity token). Authenticate before requesting an authorization code. | | `BCK.OAUTH.0008` | 400 | business | ❌ | Requested resource is not covered by this authorization | RFC 8707 invalid\_target: the `resource` you requested at /oauth/token maps to a credential the binding does not cover (e.g. an x402 resource on a binding with no spend delegation). The authorization code is single-use and has already been consumed, so it cannot be retried — restart the flow at POST /oauth/authorize requesting a `resource` the binding covers (or omit `resource` to receive its default credential). | | `BCK.OAUTH.0009` | 401 | auth | ❌ | Credential revoked | The authorization behind this credential was revoked (the human withdrew consent via /oauth/revoke). Every credential minted from that binding — API key and x402 permission — is now invalid. Restart the flow at POST /oauth/authorize to obtain a new credential. | | `BCK.OAUTH.0010` | 401 | auth | ❌ | Credential presented outside its resource audience | This credential was minted (RFC 8707) for a specific `resource` and is confined to it, but was presented to a different Nevermined API deployment/audience than the one it was authorized for. Restart the flow at POST /oauth/authorize requesting the `resource` you are calling. | | `BCK.OAUTH.0011` | 400 | auth | ❌ | Invalid refresh token | OAuth `invalid_grant`: the refresh token is unknown, expired, already rotated (one-time use — replaying it revokes the whole chain), revoked, or was issued to a different client. Restart at POST /oauth/authorize to obtain a fresh token pair. | | `BCK.OAUTH.0012` | 400 | business | ❌ | Delegation expired | OAuth `invalid_grant` (sub-reason `delegation_expired`): the spend delegation this binding relies on has expired, so no new credential can be minted from it. The human must re-authorize a fresh delegation at POST /oauth/authorize. | | `BCK.OAUTH.0013` | 400 | business | ❌ | Budget exhausted | OAuth `invalid_grant` (sub-reason `budget_exhausted`): the plan credits / delegation funding this binding are spent — either the amount cap (`spendingLimitCents`) or the transaction-count cap (`maxTransactions`) is reached — so re-minting is refused. Top up the plan (or authorize a new delegation) and retry, or restart at POST /oauth/authorize. | | `BCK.OAUTH.0014` | 400 | business | ❌ | Delegation revoked | OAuth `invalid_grant` (sub-reason `delegation_revoked`): the spend delegation this binding relies on has been revoked, so no new credential can be minted from it. The human must authorize a fresh delegation at POST /oauth/authorize. | | `BCK.OAUTH.0015` | 404 | business | ❌ | AgentBinding not found | No AgentBinding with this id belongs to the signed-in user. It may not exist or may belong to another user (#2401 Connected agents). Refresh the list and retry. | | `BCK.OAUTH.0016` | 400 | auth | ❌ | Unknown OAuth client | The `client_id` is not a registered OAuth client. Clients are provisioned out-of-band (Dynamic Client Registration is not supported). Note (#2235 G3): `client_id` identifies the OAuth client — a connector or the first-party webapp — NOT the agent; the target agent goes in `agent_id`. | | `BCK.OAUTH.0017` | 400 | auth | ❌ | redirect\_uri not registered for this client | RFC 6749 §4.1.3: the `redirect_uri` must EXACTLY match one registered for the `client_id` (no wildcard or prefix match). Send a redirect URI already registered for the client. | | `BCK.OAUTH.0018` | 400 | auth | ❌ | Missing required parameter: agent\_id | An agent-specific authorization requires `agent_id` (the target agent) in addition to `client_id` (the connector). Include `agent_id` in the connector's authorize URL. #2235 G3. | | `BCK.OAUTH.0019` | 400 | business | ❌ | Plan is not associated with the requested agent | The supplied `plan_id` does not belong to the target `agent_id`. Pass a plan registered for that agent, or omit `plan_id` to use the agent's default plan. | | `BCK.OAUTH.0020` | 400 | auth | ❌ | Invalid or expired user code | The code may be mistyped, expired, or already used. Ask the agent to start a new device authorization and read out the fresh code. | | `BCK.OAUTH.0021` | 400 | auth | ✅ | Authorization pending | RFC 8628 authorization\_pending: the user has not yet approved. Keep polling /oauth/token at the interval from the device authorization response. | | `BCK.OAUTH.0022` | 400 | auth | ✅ | Polling too fast | RFC 8628 slow\_down: you polled faster than the interval. Increase your poll interval by 5 seconds and continue. | | `BCK.OAUTH.0023` | 400 | auth | ❌ | Device code expired | RFC 8628 expired\_token: the device\_code/user\_code lifetime elapsed before approval. Start a new device authorization. | | `BCK.OAUTH.0024` | 400 | auth | ❌ | The user denied the authorization request | RFC 8628 access\_denied: the human declined at the verification page. Do not retry with this device\_code. | | `BCK.OAUTH.0025` | 403 | auth | ❌ | Account-level authorization requires a verified client | This client is enabled for account-level connect but is not `verified`. Account-wide spending authority is granted only to verified clients (#2541 / G3 F2/F4). Use an agent-specific authorization (include `agent_id`) instead, or have the client verified. | | `BCK.OAUTH.0026` | 400 | auth | ❌ | Account-level authorization requires funding details | An account-level connect is delegation-backed: it must carry the spend cap it binds to — `provider`, `provider_payment_method_id`, `spending_limit_cents`, `duration_secs`, and `currency`. Enrol a card and set a cap before authorizing. #2541. | | `BCK.OAUTH.0027` | 403 | auth | ❌ | This credential cannot create authorizations or spend mandates | An OAuth-minted credential — `account_access`, `commerce`, or `credits_purchase` — may spend only its consented authority and cannot run another authorization ceremony, create a new mandate, or grant itself credit top-up authority on the human’s card. It could otherwise mint itself a second, larger mandate on the same card, defeating the consented cap. Authorize from the human browser session, or use an agent-specific key for agent flows. #2574 B1, #4766. | | `BCK.OAUTH.0029` | 500 | internal | ❌ | Internal error creating the agent binding | A server-side data-integrity condition — an agent-specific (credits\_purchase) binding reached persistence without an agent id, which the database CHECK forbids. No action is required from the caller; inspect the API logs (the failing authorization request id is on the error `details`/`params`). #2578. | | `BCK.OAUTH.0030` | 403 | auth | ❌ | This credential cannot manage account keys, use the Router spend rails or create delegations | An OAuth-minted credential (`credits_purchase`, `account_access` or `commerce`) may not call the Router’s spend rails (`/router/payments`, `/router/route`, `/router/route/with-controls`, `/router/select`, `/router/proxy`, `/router/svc/`) or `POST /delegation/create`: those routes sign from the account wallet, outside the session-key policy the credential advertises — and a `credits_purchase` key owns no delegation, so any delegation it reaches was never consented for. Their unpaid price check, `/router/quote`, is refused too. Nor may it use billing-management routes (`/subscription/portal`, `/subscription/cancel`, `/subscription/payment-method`): existing billing is controlled with a plain (non-OAuth) API key only. Nor may it change the personal daily credit budget (`/router/subscription/credit-budget`); only the buyer sets that limit. Subscription quote, route and balance accept only commerce bindings with an explicit personal subscription-credit grant; other OAuth credentials are refused. Triggering a credit top-up likewise accepts only a plain key or a commerce binding with an explicit credit-top-up grant; a non-commerce OAuth credential is refused there. Nor may it read the credits balance (`/credits/balance`) or the welcome credits (`/credits/welcome`), read or change the top-up settings (`/credits/topups`), read the top-up consent (`/credits/topups/consent`), price or buy the first top-up pack (`/credits/topups/checkout/preview`, `/credits/topups/checkout`), list the packs (`/credits/topups/purchases`), or withdraw a pack (`/credits/topups/purchases/:id/withdraw`), which serve plain personal API keys only. Account key management and usage (`/api-keys`, `/api-keys/search`, `/api-keys/txs`, `/api-keys/stats`, `/api-keys/counts`, `/api-keys/:skId/aggregations`, `/api-keys/validate`) also require a plain key: an OAuth grant cannot inspect or change other account credentials. Nor may it reactivate an enrolled card (`/payment-methods/:paymentMethodId/reactivate`), which only the cardholder does from the Nevermined app. Starting a new subscription checkout remains available to OAuth-minted credentials because it returns a link where the user chooses whether to pay. Use a plain API key from the account owner (a personal one for the subscription), or — for `credits_purchase` / `account_access` — the credential’s own x402 spend rail. A `commerce` credential spends through `POST /api/v1/router/commerce/route`, where the delegation is derived from the grant, and prices a call without paying through `POST /api/v1/router/commerce/quote`. | | `BCK.OAUTH.0031` | 400 | auth | ❌ | Invalid client metadata document | The `client_id` was treated as a CIMD (Client ID Metadata Document) URL but did not resolve to a valid document. It must be an https URL on a public host that returns a JSON document whose `client_id` equals the URL and which declares a non-empty `client_name` and `redirect_uris`. If your host uses static registration instead, register it out-of-band and use its issued `client_id`. | | `BCK.OAUTH.0032` | 400 | validation | ❌ | Invalid funding parameters for a commerce authorization | A `consent_type=commerce` authorization mints a capped on-chain (erc4337) spending mandate during consent, so its funding terms must be sent TOGETHER when a stablecoin cap is requested: `commerce_spending_limit_cents`, `commerce_duration_secs` and `commerce_currency` (`usdc` or `eurc`). The account-level CARD fields (`provider` / `provider_payment_method_id` / `spending_limit_cents` / `duration_secs` / `currency`) belong to a different grant and must NOT be sent alongside them — the two groups are mutually exclusive, and sending both is refused rather than silently resolved in favour of one, so you are never charged against a cap you did not mean. For a credits-only grant, explicitly send `commerce_subscription_credits: true` and/or `commerce_credit_topup: true` (credit spend and card-funded top-ups are separate authorities, either satisfies the rule) and omit all three stablecoin fields. Both credit authorities default to false and are independent of the stablecoin cap and of each other. A commerce mandate is funded by the user’s own custodial wallet, so it takes no payment-method id. | | `BCK.OAUTH.0033` | 403 | auth | ❌ | This route requires a commerce grant | The commerce routes under `POST /api/v1/router` — `/commerce/route`, `/commerce/route/with-controls`, `/commerce/select` and `/commerce/quote` — are reachable only by a credential minted from a `commerce` authorization, because they spend or price the delegation that grant is pinned to and take no `delegationId` from you. A plain API key, or a credential from any other consent type, is refused here — plain keys use the twin that names its own delegation instead: `POST /api/v1/router/route` to pay, `POST /api/v1/router/select` to pick a service, or `POST /api/v1/router/quote` to price a call without paying. If you hold a commerce credential and still see this, the grant’s delegation is missing or the credential is bound to a different one: re-run the authorization to mint a fresh mandate. | | `BCK.OAUTH.0034` | 400 | validation | ❌ | delegationId must not be supplied on a commerce route | On the commerce routes under `POST /api/v1/router` — `/commerce/route`, `/commerce/route/with-controls`, `/commerce/select` and `/commerce/quote` — the delegation is derived server-side from your grant: it is the one the user consented to and capped, and naming another is refused rather than ignored. Remove `delegationId` from the request body. To choose a delegation per call, use the plain-key twins instead: `POST /api/v1/router/route` to pay, `POST /api/v1/router/select` to pick a service, or `POST /api/v1/router/quote` to price a call without paying. | | `BCK.OAUTH.0035` | 403 | auth | ❌ | This client is not authorized for the requested consent type | The client is enabled for account-level authorization, but not for the consent type it asked for — `params.consentType` is either `account_access` (a capped card mandate on the user’s saved card) or `commerce` (a capped on-chain spending mandate for paying external merchants). A connector is authorized for each account-level consent type separately when it is registered; request one it is authorized for, or ask for its registration to be widened. The consent page shows the human which type was refused. #3462. | | `BCK.OAUTH.0036` | 500 | internal | ❌ | OAuth frontend URL cannot be built: ENVIRONMENT is not sandbox or live | The OAuth discovery and device flows link to the webapp with the deployment tier (sandbox or live), and ENVIRONMENT was not one of them. It is validated when the API starts, so this only fires in a misconfigured test double. Set ENVIRONMENT to sandbox or live. | | `BCK.OAUTH.0037` | 403 | auth | ❌ | Nevermined credits were not granted on this commerce binding | Ask the human to reconnect and explicitly enable Nevermined credits on the consent screen. An existing grant never gains credit authority automatically. Nothing was reserved, signed or charged. | | `BCK.OAUTH.0038` | 403 | auth | ❌ | A personal Nevermined-credit grant cannot act in an organization | Remove the organization context and use a personal commerce grant. Nevermined-credit consent grants access only to the consenting human’s own credits, even when they are an organization admin. Nothing was reserved, signed or charged. | | `BCK.OAUTH.0039` | 403 | auth | ❌ | This commerce grant has Nevermined credits but no stablecoin spending cap | Use the subscription credit routes under /api/v1/router/subscription with this credits-only grant. To pay from a stablecoin wallet instead, ask the human to reconnect and approve a stablecoin spending cap. This credential cannot create a new delegation itself. Nothing was reserved, signed or charged. | | `BCK.OAUTH.0040` | 403 | auth | ❌ | Credit top-ups were not granted on this commerce binding | Ask the human to reconnect and explicitly enable credit top-ups on the consent screen. An existing grant never gains top-up authority automatically. The human must also have enrolled a card and set a monthly top-up limit. This call charged nothing; but if you reused a requestId from an earlier call made with top-up consent, that earlier call may have charged — read GET /api/v1/credits/topups/purchases before starting a new top-up. | | `BCK.OAUTH.0041` | 403 | auth | ❌ | This commerce grant can only top up credits, not spend them | This grant may only trigger a credit top-up on the human’s card (POST /api/v1/credits/topups/pack), not spend credits or stablecoins on a router route. To spend, ask the human to reconnect and enable Nevermined credit spend, or approve a stablecoin spending cap. Nothing was reserved, signed or charged. | ## `BCK.OBSERVABILITY` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.OBSERVABILITY.0001` | 500 | integration | — | Error fetching observability data from Helicone | Inspect Helicone dashboard logs for the request id in params. Common causes: invalid filter, expired token, or a transient Helicone outage. | | `BCK.OBSERVABILITY.0002` | 502 | integration | ✅ | Invalid response from Helicone API | Retry after a short backoff. Helicone returned a non-JSON / error-page body (usually a transient upstream incident); if it persists, check the Helicone status page. | | `BCK.OBSERVABILITY.0003` | 500 | integration | ❌ | Unauthorized access to Helicone API | Refresh `HELICONE_API_KEY` in the deployment env. The current key is missing, revoked, or scoped to a different workspace. | | `BCK.OBSERVABILITY.0004` | 429 | integration | — | Rate limit exceeded for Helicone API | Back off and retry. Helicone is rate-limiting our API key; consider increasing the plan limit or batching requests. | | `BCK.OBSERVABILITY.0005` | 502 | integration | — | Helicone API service unavailable | Inspect Helicone status page. The upstream Helicone API is unavailable; retry after a backoff. | ## `BCK.ORDER` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.ORDER.0001` | 400 | validation | ❌ | Invalid Order request | The Order create was rejected before any charge was attempted. `amountMinor` must be an integer from 100 to 99999999 (USD $1.00 to $999,999.99), `currency` must be `usd` (Phase 1 is USD-only), and `captureMode`, if supplied, must be `automatic`. Fix the field named in the validation details and resend. | | `BCK.ORDER.0002` | 404 | business | ❌ | Order not found | No Order exists with that id. The id is the sole access control for the buyer-facing read, so a wrong, mistyped, or already-removed id is indistinguishable from one that never existed. Verify the id the merchant handed the buyer. | | `BCK.ORDER.0003` | 403 | business | ❌ | Merchant not authorized for Orders | The order was not initiated by an active organization account, or the requested amount exceeds the merchant's per-order cap. This is a permanent authorization decision — retrying will fail identically. Create the order from an active organization account (any active organization is enabled for Orders), or raise the cap. Distinct from the velocity limit BCK.ORDER.0010, which is temporary and retryable. | | `BCK.ORDER.0004` | 500 | integration | ❌ | Merchant has no payable Connect account for Orders | This allow-listed merchant has no Stripe Connect account currently able to receive card payments (missing, not validated, or not `acct_`-prefixed) for this environment. Anomalous for a vetted merchant and alert-worthy — inspect the merchant profile or organization Connect status. No charge was attempted. | | `BCK.ORDER.0005` | 500 | integration | ❌ | The Order PaymentIntent could not be created | Creating the Stripe PaymentIntent for this Order failed before the buyer could confirm it, so no charge was attempted and the Order is marked failed. This is an internal or Stripe-infrastructure error, not a declined card (the buyer confirms client-side, so a decline never reaches this endpoint). Inspect the logged Stripe error; resend as a new Order once the underlying cause is resolved. | | `BCK.ORDER.0007` | 409 | business | ❌ | Order idempotency conflict | An Order create was retried with a body that conflicts with the one already stored for this idempotency key (or its resulting paymentIntentId already exists). Resend the ORIGINAL request unchanged to get the same Order back, or use a fresh idempotencyKey for a genuinely different charge. | | `BCK.ORDER.0010` | 429 | business | ✅ | Order velocity cap exceeded | The merchant exceeded its Orders velocity cap. Unlike the allow-list / max-amount refusal BCK.ORDER.0003, this is temporary — back off and retry after a short delay. It is a separate code precisely because its retry semantics differ (retryable, where 0003 is permanent). | | `BCK.ORDER.0011` | 500 | integration | ❌ | Payment provider not implemented for Orders | The requested Order payment provider is accepted on the wire but has no charge path implemented in this deployment. No charge was attempted. This is an internal configuration gap (a PSP was exposed before it was wired), not a client error — inspect the logs and use a supported provider. | ## `BCK.ORGANIZATIONS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.ORGANIZATIONS.0001` | 500 | business | — | Error creating organization member | Inspect the underlying error in logs. Member-create failed — usually a DB-layer constraint (duplicate membership, FK violation). | | `BCK.ORGANIZATIONS.0002` | 500 | business | — | Error getting organization members | Inspect the underlying error in logs. Members lookup failed — usually a DB-layer error. | | `BCK.ORGANIZATIONS.0003` | 500 | business | — | Error saving organization branding | Inspect the underlying error in logs. Branding persistence failed — usually a storage-layer error for the uploaded logo, or a DB-layer error for the colour palette. | | `BCK.ORGANIZATIONS.0004` | 500 | business | — | Error updating organization | Inspect the underlying error in logs. Organization update failed — usually a DB-layer error or validation reject on the new fields. | | `BCK.ORGANIZATIONS.0005` | 500 | business | — | Error creating organization | Inspect the underlying error in logs. Organization-create failed — usually a DB-layer error or a duplicate slug/name. | | `BCK.ORGANIZATIONS.0006` | 500 | business | — | Error creating organization with first admin | The two-step bootstrap (create org + add first admin) failed. Check the underlying error in logs; the org may have been created without the admin link. | | `BCK.ORGANIZATIONS.0007` | 500 | auth | — | Login failed for organization | Inspect the underlying error in logs. Org login failed — typically a misconfigured Privy app id or membership lookup error. | | `BCK.ORGANIZATIONS.0008` | 403 | business | ❌ | User is already a member of the organization | The membership already exists. Read the membership instead of recreating it, or change the role via the update endpoint. | | `BCK.ORGANIZATIONS.0009` | 403 | business | ❌ | User is not a member of the organization | Add the user as a member before performing membership-scoped operations. | | `BCK.ORGANIZATIONS.0010` | 500 | business | — | Failed to update organization member | Inspect the underlying error in logs. Member-update failed — usually a DB-layer error. | | `BCK.ORGANIZATIONS.0011` | 404 | business | ❌ | Organization not found | Verify the orgId. Soft-deleted organizations also surface as not-found. | | `BCK.ORGANIZATIONS.0012` | 500 | business | — | Failed to deactivate organization | Inspect the underlying error in logs. Org deactivation failed — usually a DB-layer error. | | `BCK.ORGANIZATIONS.0013` | 500 | business | — | Failed to retrieve updated organization | Inspect the underlying error in logs. The post-update re-read returned nothing — the row may have been deleted between the update and the read. | | `BCK.ORGANIZATIONS.0014` | 403 | business | ❌ | User already belongs to another organization | A user can only belong to one organization at a time. Remove the user from the current organization before adding them to a new one. | | `BCK.ORGANIZATIONS.0015` | 500 | integration | ✅ | Failed to look up organization (database error) | Repository.findOne returned a driver/connection error rather than null. Inspect the cause field on the server log; if the database is up, this is likely a query timeout or connection-pool exhaustion. Distinct from BCK.ORGANIZATIONS.0011, which signals a confirmed not-found result. | | `BCK.ORGANIZATIONS.0016` | 404 | business | ❌ | Organization customer not found | Verify the customerId is correct and belongs to the organization in the URL. Customers are scoped per-org; a customer that exists in another org will surface as not-found here. | | `BCK.ORGANIZATIONS.0017` | 422 | business | ❌ | Cannot remove the last admin from the organization | An organization must always have at least one active admin. Promote another member to Admin (or invite a new one) before demoting, deactivating, or removing the last admin. | | `BCK.ORGANIZATIONS.0018` | 404 | business | ❌ | Organization member not found | Verify the memberId (the OrganizationMember row PK) and that it belongs to the orgId in the URL. Deactivated members still exist; truly removed members return 404. | | `BCK.ORGANIZATIONS.0019` | 403 | business | ❌ | Customer management is not available for this organization tier | Viewing organization customers requires the Enterprise tier. Upgrade the organization to Enterprise to access the customers tab and per-customer activity. (Customers are still tracked on every tier — only the view is gated.) | | `BCK.ORGANIZATIONS.0020` | 403 | business | ❌ | Activity feed is not available for this organization tier | The activity feed is a Premium+ feature. Upgrade the organization to Premium or Enterprise to access the activity log. | | `BCK.ORGANIZATIONS.0021` | 403 | business | ❌ | Outbound webhooks are not available for this organization tier | Outbound webhooks are a Premium+ feature. Upgrade the organization to Premium or Enterprise to subscribe to org events from external systems. | | `BCK.ORGANIZATIONS.0022` | 403 | business | ❌ | Analytics are not available for this organization tier | The analytics dashboard is a Premium+ feature. Upgrade the organization to Premium or Enterprise to access revenue, customer, and agent-usage metrics. | | `BCK.ORGANIZATIONS.0023` | 404 | business | ❌ | Webhook subscription not found | Verify the subscription id and that it belongs to the orgId in the URL. Deleted subscriptions return 404. | | `BCK.ORGANIZATIONS.0024` | 422 | validation | ❌ | Invalid webhook URL: must be a valid URL with http or https scheme | Provide an absolute URL with an http\:// or https\:// scheme. Schemes like ftp\:// or relative URLs are rejected. | | `BCK.ORGANIZATIONS.0025` | 422 | validation | ❌ | Webhook URL must use HTTPS in production environments | Webhook URLs in live environments must use HTTPS so the signed payload cannot be intercepted in transit. Use HTTPS, or test against the sandbox environment which permits HTTP for local development. | | `BCK.ORGANIZATIONS.0026` | 404 | business | ❌ | Webhook delivery not found | Verify the deliveryId. Old deliveries may be pruned by the retention job; check the activity feed for the parent event instead. | | `BCK.ORGANIZATIONS.0027` | 404 | business | ❌ | Webhook delivery not found in this organization | The delivery exists but belongs to a different organization. Use the orgId that owns the delivery, or call this endpoint as a member of that org. | | `BCK.ORGANIZATIONS.0028` | 404 | business | ❌ | User organisation info not found | The user exists but has no membership matching the requested environment. Verify the userId and environment query param. | | `BCK.ORGANIZATIONS.0029` | 400 | validation | ❌ | Role transition not permitted: only Admin and Member roles are assignable | Pass role=Admin or role=Member. Other role values (Owner, Client, etc.) are not supported via this endpoint. | | `BCK.ORGANIZATIONS.0030` | 400 | auth | ❌ | Required caller identity is missing from the request | The userId/address fields populated by the auth guards were absent. This typically means the guard chain has been misconfigured — the endpoint should be reachable only after auth. | | `BCK.ORGANIZATIONS.0031` | 403 | business | ❌ | Realtime event streaming is not available for this organization tier | The realtime (WebSocket) activity stream is an Enterprise-only feature. Upgrade the organization to Enterprise to manage WebSocket secrets and subscribe to the live event stream. | | `BCK.ORGANIZATIONS.0032` | 404 | business | ❌ | WebSocket secret not found | No WebSocket secret with that id exists for the current member in this organization. It may have already been deleted, or belongs to a different member. | | `BCK.ORGANIZATIONS.0033` | 500 | business | ✅ | Failed to onboard customer | White-label customer provisioning failed unexpectedly (e.g. a Privy or key-minting outage). Inspect the underlying error in logs and retry — provisioning is idempotent by email. | | `BCK.ORGANIZATIONS.0034` | 409 | business | ❌ | This customer is blocked by your organization | Your organization has blocked this customer, so no new credential can be issued to them. Unblock them first (`POST /organizations/{orgId}/customers/{customerId}/unblock`) if this was in error. | | `BCK.ORGANIZATIONS.0035` | 409 | business | ❌ | This account has been disabled | The Nevermined account behind this email is disabled, so no credential can be issued for it. Contact support if the account should be reactivated. | | `BCK.ORGANIZATIONS.0036` | 500 | business | ✅ | Could not securely complete the member invitation | The bootstrap key minted while provisioning the invitee could not be revoked, so the invitation was failed closed rather than leave a live credential on the invitee account. Inspect the underlying error in logs and retry — provisioning is idempotent by email. | | `BCK.ORGANIZATIONS.0037` | 500 | internal | ❌ | Could not record organization customer activity | Recording a customer's activity for an organization returned no row from the database upsert. The payment itself is unaffected; only the organization's customer list and totals missed this update. This is a server-side defect; quote the correlation id when reporting it. | ## `BCK.ORG_INTEGRATION` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.ORG_INTEGRATION.0001` | 404 | business | ❌ | Organization integration document not found | The org id does not exist, or the public slug is unknown, inactive, or not entitled to agentic integration. | | `BCK.ORG_INTEGRATION.0002` | 500 | internal | ✅ | Failed to render organization integration document | Inspect the underlying error in logs. The integration template rendering failed — usually a missing template variable or a malformed organization metadata row. | | `BCK.ORG_INTEGRATION.0003` | 403 | business | ❌ | Organization is inactive | The organization must be reactivated before its agentic integration documents are available. | | `BCK.ORG_INTEGRATION.0004` | 403 | business | ❌ | Organization is not entitled to agentic integration | Agentic integration documents require an active Premium or Enterprise tier (or legacy equivalent). The organization owner can upgrade or renew its subscription. | ## `BCK.ORG_WALLETS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.ORG_WALLETS.0001` | 422 | business | ❌ | Organization wallet cap reached: cannot create more wallets for this organization | The organization-wallet cap for this tier has been reached. Premium allows one; upgrade to Enterprise for more. | | `BCK.ORG_WALLETS.0002` | 404 | business | ❌ | Organization wallet not found | No organization wallet with this id exists for the specified organization. | | `BCK.ORG_WALLETS.0003` | 502 | integration | ✅ | Failed to provision the organization wallet | The custodial wallet provider could not create the wallet. Retry; if it persists, contact support. | | `BCK.ORG_WALLETS.0004` | 403 | business | ❌ | Organization wallets are not available on this tier | Organization stablecoin wallets require a Premium or Enterprise organization. | | `BCK.ORG_WALLETS.0005` | 409 | business | ❌ | Wallet is already shared with this group | This organization wallet already funds the group; nothing to add. | | `BCK.ORG_WALLETS.0006` | 404 | business | ❌ | Wallet is not shared with this group | This organization wallet does not fund the specified group; nothing to remove. | | `BCK.ORG_WALLETS.0007` | 502 | integration | ❌ | Failed to withdraw from the organization wallet | The withdrawal may have partially completed. Check the wallet’s balance and recent transactions before retrying; contact support if unsure. | | `BCK.ORG_WALLETS.0008` | 409 | business | ❌ | Cannot remove a wallet that still holds funds | Withdraw the wallet’s USDC/EURC balance to another address first, then remove it. Money locked in MPP payment channels comes back to the wallet when the channels close; withdraw it then. | | `BCK.ORG_WALLETS.0009` | 422 | validation | ❌ | Insufficient balance for the requested withdrawal | The withdrawal amount exceeds the wallet’s balance for that token. | | `BCK.ORG_WALLETS.0010` | 422 | validation | ❌ | Invalid withdrawal destination address | The destination cannot be the zero address or the wallet’s own address. Provide a different recipient. | | `BCK.ORG_WALLETS.0011` | 422 | validation | ❌ | Withdrawals are not available on the requested network | This deployment can withdraw on its primary network and on Tempo. Omit `chainId` to use the primary network, or pass one this deployment serves. | | `BCK.ORG_WALLETS.0012` | 500 | integration | ✅ | Could not sign the withdrawal for this wallet | Nothing was submitted and the wallet is unchanged. Retrying is safe; if it persists, contact support. | | `BCK.ORG_WALLETS.0013` | 502 | integration | ✅ | The network rejected the withdrawal transaction | The node refused the transaction, so nothing moved. Common causes are an expired signing window or a balance that cannot also cover gas in the token being withdrawn. Retrying is safe. | ## `BCK.PAYMENT_CREDENTIAL` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.PAYMENT_CREDENTIAL.0001` | 500 | internal | ❌ | Canonical payment-credential dual-write failed (mirror drift) | Epic #1958 T1.A: the canonical payment\_credentials/payment\_instruments mirror could not be kept in sync with payment\_methods (enrol/revoke/webhook fan-out). The legacy payment\_methods write already succeeded — this is logged-and-swallowed because the mirror is non-authoritative while PAYMENT\_CREDENTIALS\_ENABLED is the only consumer. Alert on this code: drift must be reconciled before the canonical model becomes load-bearing (T1.B/T1.C). Inspect the logged stack for the underlying DB error. | | `BCK.PAYMENT_CREDENTIAL.0002` | 500 | internal | ❌ | Canonical payment-credential resolve failed (delegation FK) | Epic #1958 T1.B: resolving the delegation→payment\_credentials FK at delegation-create time failed (resolveActiveCredentialId). Logged-and-swallowed — the delegation is created with credentialId NULL, identical to the flag-off path, because the FK is a non-authoritative back-reference while PAYMENT\_CREDENTIALS\_ENABLED is the only consumer. Distinct from 0001 (dual-write/mirror) so an alert can tell a resolve-during-create failure from an enrol/revoke/webhook mirror failure. Inspect the logged stack for the underlying DB error. | | `BCK.PAYMENT_CREDENTIAL.0003` | 500 | internal | ❌ | Canonical payment-credential instrument lookup failed (charge router) | Epic #1958 T1.C: loading a credential’s active payment\_instruments for the charge-time router (listActiveInstrumentsForCredential) failed. Logged-and-swallowed — the router falls back to the retained delegations.provider column, identical to the flag-off path, because the derivation is non-authoritative while PAYMENT\_CREDENTIALS\_ENABLED is the only consumer. Distinct from 0001 (dual-write/mirror) and 0002 (resolve-on-create) so an alert can pinpoint a derive-at-charge failure. Inspect the logged stack for the underlying DB error. | | `BCK.PAYMENT_CREDENTIAL.0004` | 404 | business | ❌ | Unified card enrolment is not available | Epic #1958 T3.A: the unified VGS-Collect card-enrol endpoint (POST /api/v1/delegation/enroll) is gated behind the PAYMENT\_CREDENTIALS\_ENABLED flag and is OFF in this environment. The other enrol path (enroll-visa) remains available. 404 (not 503) so a flag-off deploy presents the endpoint as simply absent. | ## `BCK.PAYPAL` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.PAYPAL.0001` | 500 | integration | — | Unexpected error during PayPal/Braintree checkout | Inspect the underlying error in logs. PayPal-via-Braintree checkout failed — usually a Braintree transaction reject or PayPal account restriction. | ## `BCK.PLANS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.PLANS.0001` | 500 | internal | ❌ | Plan lookup failed: plan with the given entryId not found in service layer | The service-layer findOneById returned null. Original behaviour was a generic 500; consumer code that needs 404 semantics should use BCK.PROTOCOL.0003. | ## `BCK.POINT` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.POINT.0001` | 403 | business | ❌ | User with address is not allowed to access | Register the caller wallet as a user before accruing points. The points endpoints require a user-profile row; re-authenticating the same wallet will not grant access. | | `BCK.POINT.0002` | 404 | business | — | User with id not found | Verify the user id. The user may have been deleted or never existed. | | `BCK.POINT.0003` | 404 | business | — | Unable to search user points | Verify the user id and that points retention has not pruned the rows. Empty per-user point lookups surface as 404. | | `BCK.POINT.0004` | 404 | business | — | Unable to search event points | Verify the event id. Empty per-event point lookups surface as 404. | | `BCK.POINT.0005` | 404 | business | — | Unable to find user points aggregated | Verify the user id. Empty aggregated lookups surface as 404. | | `BCK.POINT.0006` | 404 | business | — | Points rule not found | Verify the ruleId. Empty rule lookups surface as 404; rules may be disabled or removed. | | `BCK.POINT.0007` | 403 | business | ❌ | Points rule recurrency exhausted for user | The rule allows only one (or N) accruals per user; the cap has been reached. | | `BCK.POINT.0008` | 500 | internal | — | Points rule recurrency type not implemented | The rule references an unimplemented recurrency type. Update points.rules.ts to use one of: onlyonce, timeslimitted, onceperitem, capday, capweek, capmonth. | | `BCK.POINT.0009` | 500 | internal | ❌ | No points rule matches the supplied price/role | The price/role tiers in points.rules.ts are exhaustive for non-negative inputs; reaching this code typically means a negative or otherwise unexpected price was supplied. The status is 500 to preserve the original "throw new Error" behaviour from before #1538; a follow-up (tracked in the Wave-B issue) will demote this to 400 and add input validation at the API boundary. | | `BCK.POINT.0010` | 403 | business | ❌ | Unsupported points cap recurrency type | The rule references a cap recurrency variant that the engine does not recognise. Update the rule to one of capday/capweek/capmonth. | | `BCK.POINT.0011` | 403 | business | ❌ | Points rule (onlyonce) already accrued by this user | The rule allows exactly one accrual per user and the user already received their share. No retry will succeed. | | `BCK.POINT.0012` | 403 | business | ❌ | Points rule (timeslimitted) per-user lifetime cap reached | The rule allows at most rule.cap accruals per (user, rule); the user has reached that ceiling and the cap does not reset. Note: the throw-site `details` line may mention an item reference for historical reasons — the check is per-user, not per-item. Per-item semantics live in BCK.POINT.0013 (onceperitem). | | `BCK.POINT.0013` | 403 | business | ❌ | Points rule (onceperitem) already accrued for this item | The user already received points for this specific item/reference. Try a different item. | | `BCK.POINT.0014` | 403 | business | ❌ | Points rule (capday/week/month) time-window cap exhausted | The user reached the cap for this rule within the current time window (day/week/month). Wait for the window to roll over. | | `BCK.POINT.0015` | 500 | internal | ❌ | No subscription-price points rule for the supplied price | getRuleIdBySubscriptionPrice() saw a price the tier table does not cover — typically a negative value. Add input validation at the API boundary. | | `BCK.POINT.0016` | 500 | internal | ❌ | No crypto-seller points rule for the supplied price | getRuleIdByCryptoSellerPrice() saw a price the tier table does not cover. | | `BCK.POINT.0017` | 500 | internal | ❌ | No crypto-buyer points rule for the supplied price | getRuleIdByCryptoBuyerPrice() saw a price the tier table does not cover. | | `BCK.POINT.0018` | 500 | internal | ❌ | No fiat-seller points rule for the supplied price | getRuleIdByFiatSellerPrice() saw a price the tier table does not cover. | | `BCK.POINT.0019` | 500 | internal | ❌ | No fiat-buyer points rule for the supplied price | getRuleIdByFiatBuyerPrice() saw a price the tier table does not cover. | ## `BCK.PROTOCOL` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.PROTOCOL.0001` | 500 | integration | — | Unable to register payment plan | Inspect the underlying error in logs. Payment-plan registration failed at protocol or SDK layer — usually a chain revert or missing token approval. | | `BCK.PROTOCOL.0002` | 500 | integration | — | Unable to register agent | Inspect the underlying error in logs. Agent registration failed at protocol or SDK layer — usually a chain revert or duplicate agentId. | | `BCK.PROTOCOL.0003` | 404 | integration | — | Unable to get payment plan by planId | Verify the planId. The plan may have been removed at the protocol side or never registered. Sandbox/live mismatches surface here too. | | `BCK.PROTOCOL.0004` | 404 | integration | — | Unable to get agent by agentId | Verify the agentId. The agent may have been removed at the protocol side or never registered. Sandbox/live mismatches surface here too. | | `BCK.PROTOCOL.0005` | 500 | integration | — | Error ordering plan | Inspect the underlying error in logs. Plan ordering failed — usually insufficient balance, expired plan, or chain revert. | | `BCK.PROTOCOL.0006` | 500 | integration | — | Error getting balance of plan | Inspect the underlying error in logs. Balance retrieval reverted — verify the planId and that the chain RPC is reachable. | | `BCK.PROTOCOL.0007` | 500 | integration | — | Error minting plan | Inspect the underlying error in logs. Credit minting reverted — verify the planId, credit type, and the minter role on the protocol contract. | | `BCK.PROTOCOL.0008` | 500 | integration | — | Error deleting plan from agent | Inspect the underlying error in logs. The agent→plan unlink call reverted — verify the caller owns both the agent and the plan. | | `BCK.PROTOCOL.0009` | 500 | integration | — | Error adding plan to agent | Inspect the underlying error in logs. The agent→plan link call reverted — verify the caller owns both the agent and the plan. | | `BCK.PROTOCOL.0010` | 403 | integration | — | Invalid credits type | Provide one of the valid credit types: FIXED, DYNAMIC, EXPIRABLE. Other strings are rejected by the protocol layer. | | `BCK.PROTOCOL.0011` | 402 | integration | — | Insufficient balance | Top up the buyer balance (USDC/EURC/USD/EUR depending on plan currency) before retrying. The protocol reverted because the order amount exceeds the wallet balance. | | `BCK.PROTOCOL.0012` | 500 | integration | — | Error updating agent | Inspect the underlying error in logs. Agent metadata update reverted — verify the caller owns the agent and the new metadata is well-formed. | | `BCK.PROTOCOL.0013` | 500 | integration | — | Error updating plan | Inspect the underlying error in logs. Plan metadata update reverted — verify the caller owns the plan and the new metadata is well-formed. | | `BCK.PROTOCOL.0014` | 500 | integration | — | Error de-activating agent | Inspect the underlying error in logs. Agent de-activation reverted — verify the caller owns the agent and it is not already inactive. | | `BCK.PROTOCOL.0015` | 500 | integration | — | Error de-activating plan | Inspect the underlying error in logs. Plan de-activation reverted — verify the caller owns the plan and it is not already inactive. | | `BCK.PROTOCOL.0016` | 403 | business | ❌ | The user doesnt own this agent | Only the wallet that registered the agent can perform owner-scoped operations. Re-authenticating as the same caller will not help. | | `BCK.PROTOCOL.0017` | 403 | business | ❌ | The user doesnt own this plan | Only the wallet that registered the plan can perform owner-scoped operations. Re-authenticating as the same caller will not help. | | `BCK.PROTOCOL.0018` | 200 | integration | — | The agent is already in the desired state | No action required. The agent is already in the requested active/inactive state; the response carries the current state in params. | | `BCK.PROTOCOL.0019` | 200 | integration | — | The plan is already in the desired state | No action required. The plan is already in the requested active/inactive state; the response carries the current state in params. | | `BCK.PROTOCOL.0020` | 500 | integration | — | Error redeming credits | Inspect the underlying error in logs. Credit redemption reverted — verify the buyer holds enough credits and the plan permits redemption at this point. | | `BCK.PROTOCOL.0021` | 500 | integration | — | Error getting user plans | Inspect the underlying error in logs. The per-user plans query failed — usually a DB-layer or chain-RPC issue. | | `BCK.PROTOCOL.0022` | 404 | integration | — | Error getting user agents | Verify the user address. Empty per-user agent listings surface as 404; users with zero agents fall through this code. | | `BCK.PROTOCOL.0023` | 404 | integration | — | Error getting plan associated to agent. Agent not found | Verify the agentId. The agent may have been removed, or no plan is associated with it yet. | | `BCK.PROTOCOL.0024` | 404 | integration | — | Error getting agent associated to plan. Plan not found | Verify the planId. The plan may have been removed, or no agent is associated with it yet. | | `BCK.PROTOCOL.0025` | 500 | integration | — | Unable to generate agent access token | Inspect the underlying error in logs. Agent access-token minting failed — verify the agent is registered and the requesting plan is active. | | `BCK.PROTOCOL.0026` | 403 | integration | — | The agent doesnt include the plan specified | Re-link the plan to the agent (or use a different plan that is linked to this agent). Plans without an explicit link cannot grant access. | | `BCK.PROTOCOL.0027` | 403 | integration | — | Unable to validate access token | Re-mint the access token. The supplied token is expired, malformed, or signed by a key the API does not recognise. | | `BCK.PROTOCOL.0028` | 403 | integration | — | Invalid agent ID in access token | Verify the agentId encoded in the access-token claim matches the agent the caller is invoking. Cross-agent token use is rejected. | | `BCK.PROTOCOL.0029` | 403 | integration | — | Proof is required for this plan | Attach a signed proof to the request when ordering against this plan. The plan owner enabled proof-required for credit redemption. | | `BCK.PROTOCOL.0030` | 403 | integration | — | Invalid proof | Re-sign the proof. The proof signature does not validate against the registered signer or the proof payload does not match the request. | | `BCK.PROTOCOL.0031` | 403 | integration | — | Endpoint not included in the agent api | Add the endpoint to the agent metadata `endpoints` array (or call a registered endpoint). Only listed endpoints are reachable via the access token. | | `BCK.PROTOCOL.0032` | 500 | integration | — | Unable to track access transaction | Inspect the underlying error in logs. The access-tx insert failed — usually a DB-layer or queue-layer error. Metrics are best-effort; the consumer request still completed. | | `BCK.PROTOCOL.0033` | 403 | integration | — | You do not have permission to track access transactions for this owner | Authenticate as the agent or plan owner before retrying. Only owners can track access transactions for resources they own. | | `BCK.PROTOCOL.0034` | 500 | integration | — | Unable to track access processor queue entry | Inspect the underlying error in logs. The processor-queue insert failed — usually a queue-layer error. Safe to retry idempotently. | | `BCK.PROTOCOL.0035` | 500 | integration | — | Unable to track agent task | Inspect the underlying error in logs. The agent-task tracking insert failed — usually a DB-layer or constraint issue. | | `BCK.PROTOCOL.0036` | 500 | integration | — | Unable to track agent processor queue entry | Inspect the underlying error in logs. The agent-task processor-queue insert failed — usually a queue-layer error. Safe to retry idempotently. | | `BCK.PROTOCOL.0037` | 404 | integration | — | Agent task not found | Verify the taskId and that it belongs to the caller agent. Task ids are scoped per-agent. | | `BCK.PROTOCOL.0038` | 500 | integration | — | Error updating agent task | Inspect the underlying error in logs. Agent-task update failed — usually a state-transition guard rejection (the task is in a terminal state). | | `BCK.PROTOCOL.0039` | 500 | integration | — | Error redeeming credits and updating agent task | Inspect the underlying error in logs. The combined redeem+update transaction failed mid-way — the DB row may be left inconsistent and need manual reconciliation. | | `BCK.PROTOCOL.0040` | 500 | integration | — | Unable to register agent and plan | Inspect the underlying error in logs. The combined register-agent-and-plan call failed — verify the caller owns both resources and the protocol contract is reachable. | | `BCK.PROTOCOL.0041` | 403 | integration | — | The user doesnt have a valid Stripe account enabled | Complete Stripe Connect onboarding before publishing fiat plans. Until charges\_enabled is true on the Connect account, plans cannot be sold for fiat. | | `BCK.PROTOCOL.0042` | 403 | integration | — | Either amount or marginPercent must be provided, but not both | Send exactly one of amount or marginPercent on a DYNAMIC plan. The two fields are mutually exclusive — pick the pricing model that fits. | | `BCK.PROTOCOL.0043` | 403 | integration | — | Plan does not have valid price configuration for margin calculation. Credits type must be DYNAMIC. | Re-publish the plan with credits.type=DYNAMIC and the required margin/cost configuration. Margin calculations are only valid for DYNAMIC plans. | | `BCK.PROTOCOL.0044` | 404 | integration | — | No Helicone request found for agent request ID | Verify the Helicone request id and that the agent invocation actually fired through the Helicone proxy. Stale ids and proxied-off agents land here. | | `BCK.PROTOCOL.0045` | 500 | integration | — | Error getting all plans | Inspect the underlying error in logs. The list-all-plans query failed — usually a DB-layer error or pagination issue. | | `BCK.PROTOCOL.0046` | 400 | integration | — | Fiat plan price exceeds the maximum allowed (\$999,999.99). Stripe does not support payment intents above this limit. | Lower the plan price below \$999,999.99 (Stripe payment-intent cap). Higher-value sales must go through Stripe Connect transfers or off-platform settlement. | | `BCK.PROTOCOL.0047` | 400 | integration | — | Fiat plan price is below the minimum allowed (\$1.00). Lower prices do not cover the payment-processor fixed fee. | Raise the plan price to at least \$1.00. Lower prices do not cover the payment-processor fixed fee and would settle at a loss. | | `BCK.PROTOCOL.0048` | 400 | business | — | Plan and agent must belong to the same organization. A Personal plan cannot be linked to an organization agent (and vice versa); plans owned by one organization cannot be linked to agents owned by a different organization. | Either move the plan or the agent so both belong to the same organization (or both to the same Personal account). Cross-org and personal-vs-org links are rejected by design. | | `BCK.PROTOCOL.0049` | 500 | integration | ❌ | On-chain submit returned without a transaction hash | The chain broadcast call succeeded at the SDK boundary but did not return a tx hash. Treat as an SDK-shape drift; the dead-letter accounting flags the row so it can be re-tried after investigation. | | `BCK.PROTOCOL.0050` | 400 | business | ❌ | Fiat plans cannot be ordered through this endpoint. Use the x402 card-delegation settle flow (POST /api/v1/x402/settle) so the buyer card delegation can be charged before credits are provisioned. | This endpoint settles stablecoin (crypto) plans only. For fiat / `nvm:card-delegation` plans, register a card delegation and call /api/v1/x402/settle — that path charges the card BEFORE credits are provisioned in the off-chain ledger. On-chain mirroring (when the plan opts in) happens asynchronously after settlement; do not assume synchronous on-chain finality. | | `BCK.PROTOCOL.0051` | 503 | integration | ✅ | Chain RPC dependency temporarily unavailable | A transient failure of the on-chain RPC provider / bundler prevented the write from completing (e.g. the provider returned 5xx or was unreachable). Retry after a short backoff. If it persists, the RPC endpoint or its credentials may be misconfigured. | | `BCK.PROTOCOL.0052` | 400 | validation | ❌ | Unsupported settlement network | The requested network (chainId) is not served by this environment. Use a supported network — sandbox serves Base Sepolia (84532) and Tempo Moderato (42431); live serves Base (8453) and Tempo (4217). Off-chain plans (org-tier) do not settle on a chain (#1929). | | `BCK.PROTOCOL.0053` | 400 | validation | ❌ | Plan and agent must settle on the same network | A plan can only be linked to an agent on the same settlement network (chainId). A Tempo plan cannot be linked to a Base agent (and vice versa). Register the plan and agent on the same network, or link a plan that already settles on the agent’s network (#1929). | | `BCK.PROTOCOL.0054` | 503 | integration | ❌ | Could not migrate the agent ownership to your current wallet | Your agent was registered by a wallet that has since been migrated, and handing it over to your current wallet failed on-chain (bundler/paymaster/RPC), or a recent attempt is in its cooldown window. Do NOT retry in a loop — wait a few minutes and try the operation again. See #2152. | | `BCK.PROTOCOL.0055` | 404 | validation | ❌ | Payment plan does not exist on-chain | The request references a planId that is not registered on the settlement network — the on-chain call reverted with PlanNotFound, or (credit mint) the plan read back with no owner before any write. Check the planId (it is a uint256 decimal string, not a DID) and that it was created on the SAME network you are writing to. `GET /api/v1/protocol/plans/{planId}` confirms whether it exists (#2163). | | `BCK.PROTOCOL.0056` | 409 | business | ❌ | This plan can only be purchased once per account, and you already own it | The plan installs the one-time-purchase hook (OneTimeCreatorHook), which allows a single agreement per (plan, buyer). Your account has already ordered it, so the on-chain call reverted with CreatorAlreadyCreatedAgreement. Nothing was charged. Use the credits you already hold, or order a different plan (#2164). | | `BCK.PROTOCOL.0057` | 400 | validation | ❌ | A value in the request could not be encoded for the on-chain call | An address or numeric value in the payload is malformed, so the call could not even be encoded — most commonly a token/receiver address whose EIP-55 checksum is wrong (mixed-case addresses are checksum-verified). Send the address all-lowercase, or with a correct checksum. `params.detail` names the offending value (#2478). | | `BCK.PROTOCOL.0058` | 500 | integration | ❌ | Payment plan is registered in our records but not on the settlement network | This is a server-side inconsistency, not a problem with your request: the plan exists in our records but is not registered on the settlement network. It usually means a plan registration did not fully land. Contact support with the planId; retrying the link will not help until the plan is (re)registered on chain. | | `BCK.PROTOCOL.0059` | 500 | integration | ❌ | The blockchain transaction relayer is temporarily rate-limited | The blockchain transaction relayer (AA bundler / RPC provider) is temporarily rate-limited, so the on-chain operation did not complete — this is a transient upstream throttle, not a bug in your request or a contract revert. Retry manually after a short backoff. If it persists, the relayer's rate-limit quota is likely exhausted and needs raising. | | `BCK.PROTOCOL.0060` | 500 | integration | ❌ | The blockchain transaction relayer timed out | The blockchain transaction relayer (AA bundler / RPC provider) timed out, so the on-chain operation did not complete in time — this is a transient upstream timeout, not a bug in your request or a contract revert. Wait a short backoff before retrying, and check whether the operation eventually landed before re-submitting (the write is not idempotent). If it persists, the relayer/RPC endpoint is likely overloaded or misconfigured. | | `BCK.PROTOCOL.0061` | 500 | integration | ❌ | The blockchain transaction relayer failed the request | The blockchain transaction relayer (AA paymaster / RPC provider) failed the request, so the on-chain operation did not complete — this is a transient upstream failure, not a bug in your request or a contract revert. Wait a short backoff before retrying, and check whether the operation eventually landed before re-submitting (the write is not idempotent). If it persists, the RPC/paymaster endpoint is likely degraded or misconfigured. | | `BCK.PROTOCOL.0062` | 400 | business | ❌ | Plan is unlisted and can no longer be purchased | params.planId was unlisted by its owner (or by an organization tier downgrade), so it can no longer be bought through checkout, crypto order or x402 (params.path names the path that refused it). Credits already bought on it can still be spent while the balance covers a call; a remainder smaller than one call cannot be spent. Buy a listed plan of the same agent instead. | ## `BCK.PURCHASES` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.PURCHASES.0001` | 400 | validation | ❌ | Invalid purchases query | `from`/`to` must be ISO-8601 timestamps (e.g. 2026-07-01T00:00:00Z). | | `BCK.PURCHASES.0002` | 400 | validation | ❌ | Unsupported purchases source filter | The `source` filter must be one of: plan\_purchase, router\_payment. | | `BCK.PURCHASES.0003` | 500 | internal | ✅ | Failed to list purchases | A source read failed while building the purchase feed. Transient; safe to retry. Inspect the API logs for the underlying error. | | `BCK.PURCHASES.0004` | 401 | auth | ❌ | Purchases feed requires an authenticated buyer | The request reached the purchase feed without a resolved buyer identity. Re-authenticate with a valid Nevermined API key. | | `BCK.PURCHASES.0005` | 400 | validation | ❌ | Unsupported purchases paidWith filter | The `paidWith` filter must be one of: card, crypto, credits. | ## `BCK.ROUTER` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.ROUTER.0001` | 400 | validation | ❌ | Invalid Router payment request | Bad input to the Router: unsupported `protocol`, a malformed/empty `target` (no `accepts`), no fundable option for the funded networks/assets, an upstream pay-to outside the delegation’s allowed recipients, a non-crypto (non-erc4337) delegation, or a missing `delegationId`. On a slug-routed call, a `path` that still holds a template placeholder (`{jobId}`, `:id`) rather than a real value. And on a catalog service whose results only the paying wallet can read (an endpoint listed with `auth: siwx`): a paid call funded by an organization wallet, a subscription or a card, which could not read the result back; or wallet-authenticated follow-ups being disabled on this deployment. Each is refused before anything is charged. Buyer identity consent also requires a plain API key, a delegation owned by the caller, an HTTPS slug target and an opted-in listing; the streaming consent header must be exactly true or false. The per-failure `details` names the specific problem. | | `BCK.ROUTER.0002` | 409 | business | ❌ | requestId already used | This `requestId` already minted a credential — that is idempotency working, not an error to route around. If this is a RETRY of the same purchase, reuse the same `requestId` and take the original `paymentId` from `params`. Use a fresh id only for a genuinely DIFFERENT purchase: it mints a second credential and is charged the routing fee again. | | `BCK.ROUTER.0003` | 402 | business | ❌ | Delegation budget exceeded, expired, or inactive | The spend would exceed the delegation cap, or the delegation is expired / exhausted / revoked. Report to the human, who can deliberately create a new delegation via POST /api/v1/delegation/create. If the delegation is held by an app connected over OAuth, they disconnect the app in Nevermined and reconnect it with a new cap instead. | | `BCK.ROUTER.0004` | 404 | business | ❌ | Router payment not found | No Router payment with that id belongs to the authenticated user. | | `BCK.ROUTER.0005` | 409 | business | ❌ | Router payment is not in a settleable state | Only an Issued payment can be marked Settled. Re-reporting the same txHash on an already-Settled payment is a no-op; a different txHash, or a non-Issued state, is rejected. | | `BCK.ROUTER.0006` | 500 | integration | ✅ | Error getting router payments summary | Transient server-side error building the payments summary; safe to retry. Inputs are validated upstream (invalid from/to return 400 BCK.ROUTER.0001, granularity is normalized), so this is not a bad-request issue. | | `BCK.ROUTER.0007` | 429 | business | ✅ | Too many concurrent routed requests | You have too many in-flight mode-B routed requests (/route, /proxy) open at once. Note a /proxy request keeps its slot for a moment AFTER you receive the response, while its routing fee settles, so you can reach this limit even calling one at a time in a tight loop. Slow the request rate, or let the previous calls settle before starting more. | | `BCK.ROUTER.0008` | 403 | business | ❌ | Router requires an EIP-7702 (v2) API key | This is a legacy (v1) API key bound to the old smart account, which cannot sign EIP-3009 from the unified funded wallet. Create a new API key — it will be issued as v2 (EIP-7702) and works with the Router. Existing v1 keys keep working for credit-based (nvm:erc4337) flows until they expire. | | `BCK.ROUTER.0009` | 402 | business | ❌ | Insufficient wallet balance to fund the payment | The funding source could not cover this charge. **On the crypto rails** (x402 / MPP-tempo, which pull from the wallet's own balance — the router never holds funds) the buyer's custodial wallet does not hold enough of the payment asset on the target network: fund the wallet on the target chain and retry. **On the card rail** (MPP-stripe) the card issuer declined the charge: use a different card or contact the issuer — there is no wallet to top up, so ignore the on-chain advice above. In both cases this is distinct from the delegation cap (BCK.ROUTER.0003), which authorizes the spend but does not provide the funds, and from a card that needs 3-D Secure authentication (BCK.ROUTER.0011), where the card is fine and merely unauthenticated. | | `BCK.ROUTER.0010` | 500 | internal | ❌ | Router could not determine the amount to charge against the delegation cap | The payment handler reported a settlement amount in cents that is not a non-negative integer, so the routing-fee arithmetic cannot compute what to reserve. This is an internal invariant violation, not a bad request — the value is produced by Nevermined, not the caller. It deliberately fails rather than defaulting to zero, which would reserve nothing and let the payment through free. DO NOT BLIND-RETRY: no budget was reserved and no payment record was written, but a payment credential WAS already minted (on the card rail, a Stripe Shared Payment Token that will auto-expire). Because no record exists, your requestId will not suppress a retry — and the cause is a deterministic defect in the rail's approxCents derivation, so a retry re-mints a fresh credential and fails identically. Report it instead. | | `BCK.ROUTER.0011` | 402 | business | ❌ | The card needs cardholder authentication (3-D Secure) before it can be used | This payment needs the cardholder to authenticate (3-D Secure / SCA) before the seller can charge it. The Router cannot complete that challenge — it needs a human at a browser, and an agent-initiated payment has none — so no usable credential was returned and NO money moved. Do NOT retry automatically: 3-D Secure is often mandated by industry rules for a given charge, in which case every retry demands it again, and each attempt creates a fresh single-use card credential that is then abandoned. It may succeed on a later attempt (whether authentication is demanded is decided per charge by the issuer, the card networks and Stripe's own risk checks), but treat that as a manual decision, not a loop. This is distinct from the delegation cap (BCK.ROUTER.0003) and from a card that was refused for lack of funds (BCK.ROUTER.0009): the card is fine, it simply has not been authenticated for this charge. The credential Stripe created is never handed to the seller and cannot be charged while it awaits authentication; it expires on its own, at the earliest of the merchant's quoted expiry, your delegation's expiry, or 89 days. | | `BCK.ROUTER.0012` | 400 | validation | ❌ | The 402 advertises an EIP-712 domain the settlement token does not sign under | Paying an x402 `exact` requirement means signing an EIP-3009 authorization under the settlement token's own EIP-712 domain, and the seller's 402 published an `extra.name`/`extra.version` that is not that token's. Nevermined signs under the domain it holds for the token, never one the counterparty supplies, so it refuses rather than produce an authorization whose published terms and signature disagree. NO money moved, no credential was issued, and no delegation budget was reserved — an authorization under the wrong domain is unspendable anyway, so nothing was lost by stopping. You only see this when EVERY option in the 402 failed the check: an option with a bad domain alongside a good one is skipped, not refused. This is the seller's bug (the values must match the token contract's `name()`/`version()` exactly, byte for byte — Base mainnet USDC is `"USD Coin"`, not `"USDC"`, and a JSON number `2` is not the string `"2"`), so report it to them and pay a different seller meanwhile; retrying will fail identically until they fix it. Distinct from BCK.ROUTER.0001, which means your request was malformed: here the request was fine and the counterparty's terms were not. Distinct from BCK.ROUTER.0013, which is the same check failing because NEVERMINED lacks the token's domain — that one is ours, not the seller's. | | `BCK.ROUTER.0013` | 500 | internal | ❌ | Nevermined holds no EIP-712 signing domain for the selected settlement token | An internal invariant broke: the funding filter selected a settlement token that Nevermined recognises as fundable, but for which it holds no EIP-712 domain (`name`/`version`) to sign the EIP-3009 authorization under. That is a gap in OUR canonical token table, not a problem with your request or with the seller — do not report it to the seller. It fails rather than falling back to the domain the seller advertised, because signing under a counterparty-supplied domain is exactly the trust this check exists to remove. NO money moved, no credential was issued and no delegation budget was reserved, so nothing needs unwinding. A retry fails identically until the table is fixed, so report it rather than looping; paying a seller that settles in a different token will work in the meantime. Distinct from BCK.ROUTER.0012, where the check failed because the SELLER advertised a domain its own token does not sign under. | | `BCK.ROUTER.0014` | 409 | business | ❌ | This target is a cataloged Nevermined service — invoke it through the broker | This target's host belongs to a cataloged Nevermined service, whose upstream URL is deliberately not exposed. The Router will not pay it by raw URL: mode A (`POST /api/v1/router/payments`) hands YOU a credential you attach to your OWN call, and a raw mode-B target relays the response off-catalog — both put the merchant's host on your wire, defeating the broker. If this IS the cataloged service, invoke it through the broker so the Router calls it server-side: `POST /api/v1/router/route` with a `slug` in the body, or `POST /api/v1/router/svc/` — find the slug on its catalog listing. If you hold an OAuth `commerce` grant, use `POST /api/v1/router/commerce/route` with a `slug` instead: the other two refuse a grant-bound credential (BCK.OAUTH.0030), so they are not a remedy you can follow. If the refused call was a QUOTE, re-quote by `slug` rather than paying: `POST /api/v1/router/quote` with a plain key, or `POST /api/v1/router/commerce/quote` with a `commerce` grant. The check matches the HOST, not the exact URL, so a different endpoint co-hosted on that same host is refused too even when it has no listing of its own; if that is your case, ask the vendor to list it or contact Nevermined. Raw URLs on hosts with no cataloged service are unaffected. | | `BCK.ROUTER.0015` | 500 | internal | ❌ | Router could not sign the aggregate fee leg for a buyer group | The accrue-and-batch fee sweep could not produce a signed aggregate leg for a (buyer, chain, token) group — no signer authority for the wallet, the wallet could not be resolved to the group buyer, the settlement token has no canonical EIP-712 domain, or the signing window was clamped below the floor. The group stays `Accrued` and is retried on the next sweep; nothing was claimed and nothing is owed back. This is an internal/operator signal, never returned to a caller — the fee is collected server-side on a timer. | | `BCK.ROUTER.0016` | 500 | internal | ❌ | A per-network fee-sweep floor (`ROUTER_FEE_SWEEP_FLOOR_`) is misconfigured | A per-network fee-sweep floor (`ROUTER_FEE_SWEEP_FLOOR_`) is set to a value that is not a positive integer (0, negative, a fraction, or unparseable). It is read as a uint256 atomic-unit threshold, so a bad value fails SAFE: no threshold sweep runs on that chain and rows keep accruing (a floor of ∞), rather than sweeping every dust group. Deduped per distinct bad value and re-emitted from RouterService.onModuleInit so it is alertable. Fix the value in the deployment (argocd) — this is an operator signal, never returned to a caller. | | `BCK.ROUTER.0017` | 500 | internal | ❌ | Router aggregate fee sweep was refused after claiming a group | The accrue-and-batch fee sweep claimed a (buyer, chain, token) group `Accrued → Submitted`, signed one aggregate leg, submitted it, and the submitter ADJUDICATED a refusal (provably not broadcast). The group is rewound `Submitted → Accrued` — NOT `Released` — because the fee is still owed: the next sweep re-aggregates and signs a fresh leg. No cap release, no double charge. Internal/operator signal, never returned to a caller. | | `BCK.ROUTER.0018` | 402 | business | ❌ | Per-call maximum is below the fee-inclusive price | The 402 quote, including the buyer fee, costs more than maxTotalCents permits — compared at 1/10,000-of-a-cent resolution, so rounding alone never triggers this. Nothing was signed, and no payment row, merchant charge or delegation reserve was made. The params field is a JSON string containing decimal strings: requiredTotalMicros is the exact fee-inclusive price in micros (1/10,000 of a cent) and requiredTotalCents is it rounded up to a whole cent; compare them with maxTotalCents, and increase the ceiling only if this additional call is intended. A retry may reuse the same requestId. | | `BCK.ROUTER.0019` | 400 | business | ❌ | The service rejected the request as invalid | The service returned a non-retryable status — a client error (4xx), or a rare 3xx the Router does not follow (a 402 re-challenge and a 429 are not this code). The Router withholds the upstream response body, which can reveal the merchant host, and returns this typed error with the original status preserved (read the exact status from the params field and the HTTP status line). Build a valid request from this service's Catalog DETAIL entry (read the service by the slug you called) — its endpoints publish requestExample and requestSchema. The bulk /catalog/ai-catalog.json discovery feed is compact: it still carries a per-endpoint requestExample, invokePath and exampleEvidence, but not the full request or response schemas. The params field is a JSON string carrying the upstream status. Do not blindly retry; correct the request first, then retry with a fresh requestId. Quote correlationId when reporting an issue. | | `BCK.ROUTER.0020` | 502 | integration | ✅ | The service could not serve the request right now | The service returned a server error (5xx), rate-limited the request (429), or did not answer an unpaid request at all (timeout or connection failure) — an upstream/transient condition, not a problem with the request body. The Router withholds the upstream response body and headers (they can reveal the merchant host — including a 429 Retry-After), and returns this typed error with the original status preserved. The params field is a JSON string carrying the upstream status (absent when the service did not answer). Retry with backoff (exponential, especially on a 429), but check whether a payment was already recorded: if NO `X-Router-Payment-Id` came back the merchant was never paid — reuse the same requestId; if one DID, a payment row already exists, so reconcile it via `GET /api/v1/router/payments` and use a NEW requestId for a fresh attempt (reusing it returns `409 BCK.ROUTER.0002`). If it persists the service may be unavailable. The Router charges no routing fee for a call that did not deliver; whether the merchant leg itself was charged is reconciled on-chain and reported as `merchantSettlementObservedAt` (read alongside `status`) on `GET /api/v1/router/payments`. Quote correlationId when reporting an issue. | | `BCK.ROUTER.0021` | 400 | validation | ❌ | The payment credential would overwrite a header you asked the Router to forward | The payment rail this service advertised carries its credential in a header you are already using — on the MPP rails that header is `Authorization`, which is also where your own merchant auth goes (`headers.Authorization` on POST /router/route, `X-Router-Upstream-Authorization` on the streaming surfaces). Sending both would silently drop yours on the paid hop, so the Router refuses instead: NO payment was minted, no delegation budget was reserved and no money moved. The `params` field is a JSON string naming the contested header. Fix it by telling the Router where your merchant wants the credential instead — `credentialHeader` in the POST /router/route body, or the `X-Router-Credential-Header` request header on /router/proxy and /router/svc — using the header name the service documents (a separate `Payment` header is the common one). If the service documents no such header, it expects the credential in `Authorization` itself and cannot also take your bearer there: drop your own auth for that call, or pay it over a rail whose credential travels elsewhere (x402 uses `PAYMENT-SIGNATURE`). Retrying unchanged fails identically. | | `BCK.ROUTER.0022` | 500 | internal | ✅ | A required Router capability is unavailable | A required Router capability is not configured on this deployment. This is a configuration/wiring fault on our side, not a problem with your request; nothing was sent to a service, minted or charged by this attempt. The details or params identify service-selection or buyer-identity. Retry after the operator restores that capability; do not loop unchanged. Quote correlationId when reporting the issue. If buyer attribution is optional for your purchase, you may deliberately omit disclosure consent and make a separate request without attribution. | | `BCK.ROUTER.0023` | 502 | integration | ❌ | The autoPay charge outcome could not be confirmed — reconcile before retrying | On autoPay, selection and payment run in one call. The charge outcome for this requestId could not be confirmed — either the downstream Router call did not complete cleanly after the payment was created, or the Router could not determine whether an earlier attempt on this requestId charged (including when there was none) — so the charge may or may not have landed. Do NOT retry with a fresh requestId (that could double-charge). Reconcile via `GET /api/v1/router/payments`, then to retry safely reuse the SAME requestId verbatim so the attempt stays idempotent. The `params` field is a JSON string carrying the paymentId when one is known. Quote correlationId when reporting an issue. | | `BCK.ROUTER.0024` | 413 | validation | ❌ | Router JSON request body exceeds the 5242880 byte limit | Reduce the request body to 5242880 bytes or less and retry. | | `BCK.ROUTER.0025` | 502 | integration | ❌ | The upstream reply was too large to deliver after a paid request; the payment may have gone through | The JSON route returns a paymentId in payment.paymentId on success; this failed JSON reply does not set X-Router-Payment-Id. Find the recorded payment by requestId via GET /api/v1/router/payments and reconcile its paymentId, status, and merchantSettlementObservedAt. Do NOT retry with a fresh requestId: the merchant may already have collected and a new requestId could double-charge. On autoPay select, the 502 carries BCK.ROUTER.0023 with paymentId in params when available. Quote correlationId when reporting an issue. | | `BCK.ROUTER.0026` | 415 | validation | ❌ | The Router cannot forward this request body | The streaming surfaces (/router/svc/:slug and /router/proxy) forward a request body only when it is JSON (`application/json`) or a URL-encoded form (`application/x-www-form-urlencoded`). Any other body — `multipart/form-data` file uploads above all, but also `text/plain`, `application/octet-stream` or a vendor `+json` type — would have reached the service EMPTY, so the Router refuses it instead — as it does any body sent on a GET or HEAD, which is never forwarded. NO payment was minted, no delegation budget was reserved and no money moved. The `params` field is a JSON string naming the content type that was refused (`contentType` is null when the request sent no Content-Type, or one that is not a plain `type/subtype`). The remedy depends on the case: for a body on GET or HEAD, send no body (or use POST/PUT if the service takes one) — changing the content type does not help; otherwise resend the body as JSON or a URL-encoded form if the service accepts one, and note that a service that only takes a file upload cannot be paid through the Router yet. Retrying unchanged fails identically. | | `BCK.ROUTER.0027` | 413 | validation | ❌ | The request body is larger than this service endpoint accepts | The catalog records a maximum request size for the endpoint you called, and your request body is larger than that. The Router refused before contacting the service: this request minted NO payment, reserved no delegation budget and moved no money (a retry whose requestId was already paid is answered with BCK.ROUTER.0002 and the original paymentId instead, never with this code). The `params` field is a JSON string carrying `bodyBytes` (the UTF-8 size of the body the Router would have sent) and `maxRequestBytes` (the endpoint's limit); the same limit is published as `maxRequestBytes` on the endpoint in the catalog service detail (GET /api/v1/catalog/services/:slug) and in the MCP `get_service` result. Shrink the body below the limit (fewer or shorter inputs, or split the work into several calls), or pick a service that takes larger requests — `POST /router/select` with the same `body` skips endpoints whose limit is below it, and answers with this code (against the largest of their limits) when every otherwise-payable match is too small. Retrying unchanged fails identically. | | `BCK.ROUTER.0028` | 503 | integration | ✅ | The Router could not price this call right now | The quote could not be computed because a read it depends on failed — for example the settlement token details on the payment network. This is a transient condition on our side, not a problem with your request or with the service. A quote never signs, mints or charges anything, so nothing needs unwinding: retry the quote with backoff. If it persists, quote correlationId when reporting an issue. The same condition would also fail a payment, so do not route the call meanwhile. | | `BCK.ROUTER.0029` | 404 | business | ❌ | Router quote not found | The quoteId is invalid or does not belong to this account. Nothing was signed, reserved or charged. Request a new quote and use the quoteId it returns. | | `BCK.ROUTER.0030` | 404 | business | ❌ | Paid result not available | There is no retained result for that paymentId under your account. A paid Router result is retained for 24 hours after the call ends, for the paying user only; after that it is deleted. Results are not retained for a streamed response that had already started when the call completed, or for a payment that was never routed through POST /router/route, /router/proxy or /router/svc. The payment record itself is unaffected: read it with GET /api/v1/router/payments. | | `BCK.ROUTER.0031` | 409 | business | ❌ | Required catalog service cannot be selected | The exact opaque catalog slug named in `filters.require` is unavailable, unhealthy, unpayable, excluded by this request, or cannot accept the requested body. The Router failed closed before payment and did not substitute another service. Inspect `params.reason`, correct the slug or request, or deliberately remove `require` to allow normal fallback selection. | | `BCK.ROUTER.0032` | 410 | business | ❌ | Router quote expired | The quoteId passed its short expiry before payment began. Nothing was signed, reserved or charged. Quote the same call again and decide against the new fee-inclusive figure. | | `BCK.ROUTER.0033` | 409 | validation | ❌ | Router quote does not match this payment | The quoted target, method, headers, body, credential header, delegation, rail or exact fee-inclusive amount differs from this payment. Nothing was reserved or charged. Send the exact quoted call unchanged, or request a new quote for the changed call. | | `BCK.ROUTER.0034` | 502 | integration | ❌ | The paid request got no response from the service; the payment may have gone through | The credential was sent to the service, but no response came back (timeout or connection failure). The service may already have redeemed the payment. The params field is a JSON string carrying the paymentId: read `GET /api/v1/router/payments/{paymentId}` and reconcile its status and merchantSettlementObservedAt. Do NOT retry with a fresh requestId: the merchant may already have collected and a new requestId could double-charge. Quote correlationId when reporting an issue. | | `BCK.ROUTER.0035` | 422 | business | ❌ | The service challenge asks for no payment | The service answered with a payment challenge for a zero amount — typically an auth-only challenge that asks the caller to sign in with a wallet rather than to pay. The Router answers one (an MPP zero-amount proof or an x402 Sign-In-With-X) only for a catalog service, on an endpoint the catalog lists with auth siwx or a declared follow-up path, when your own wallet settled a payment for that service within the follow-up window; otherwise it refuses, and nothing was signed, reserved or charged. Your request is not malformed: call the paid endpoint first, or authenticate with the service directly. | | `BCK.ROUTER.0036` | 422 | business | ❌ | This service endpoint takes longer than the Router can wait for a paid call | The endpoint you called is known to answer after the Router abandons a paid call, and the merchant charges as soon as it receives the payment — so paying through the Router would charge you and deliver nothing. The Router refused before contacting the service: this request minted NO payment, reserved no delegation budget and moved no money (a retry whose requestId was already paid is answered with BCK.ROUTER.0002 and the original paymentId instead, never with this code). The `params` field is a JSON string carrying `source`: `declared` means the refusal is permanent; `observed` means it was learned from slow paid calls and lifts at `liftsAt` (an ISO-8601 time) — retrying before then fails identically. Pick another endpoint or service for this task. | | `BCK.ROUTER.0037` | 500 | internal | ❌ | No payment handler is registered for the selected protocol | The rail selected for a quote has no registered payment handler. This is a server-side wiring defect. Operator-facing: the catalog quote refresher records the observation as indeterminate, and no client receives this code. | | `BCK.ROUTER.0038` | 502 | integration | ✅ | Fee facilitator response exceeded the read cap | A fee settlement reply from the facilitator was larger than the Router reads, so it was not parsed. The fee settlement is recorded as unknown and retried. Operator-facing; no client receives this code. | | `BCK.ROUTER.0039` | 500 | internal | ❌ | Router quote binding secret is not configured | JWT\_SECRET\_KEY is unset, so the Router cannot seal quote bindings and the API does not start. It is required by the configuration schema, so this only fires in a test double. Operator-facing; no client receives this code. | | `BCK.ROUTER.0040` | 500 | internal | ❌ | Router could not read or write its MPP session channel state consistently | The Router's record of an MPP session payment channel refused an inconsistent read or write while paying a session service: for example a second channel in a scope (payer, merchant, token, escrow and chain) that already holds one, a channel that is closing, an entry whose payer is not the channel's owner, a malformed channel value, or channel state used outside a database transaction. It is a server-side defect, not something the caller can fix. The payment was refused before its credential reached the service, so this call moved no money and reserved no delegation budget. Do not retry automatically; report it with the correlationId. | | `BCK.ROUTER.0041` | 400 | business | ❌ | This service is paid over an MPP session, which only the Router-fetched routes can pay | The service offers only an MPP `session` (a payment channel with a deposit and per-call vouchers). The Router must read the service's receipt after every call to keep the channel consistent, so it pays a session only when it fetches the service itself: call it through `POST /api/v1/router/route`, `/api/v1/router/svc/{slug}` or `/api/v1/router/proxy` instead of minting a credential with `POST /api/v1/router/payments`. Nothing was signed, reserved or charged. | | `BCK.ROUTER.0042` | 409 | business | ✅ | The payment channel with this service is closing | The Router's MPP session payment channel with this service is closing, and no payment can be signed on it until the close completes. This happens when the channel's deposit has reached its ceiling, or when the service refused the channel, a top-up of its deposit, or the payment that followed a top-up. No payment was signed, reserved or charged for this request; a top-up the Router sent the service only moves the wallet's own funds into its channel, and they come back with the rest of the deposit at close. Retry later with the same requestId: the next call after the close opens a new channel. The close refunds the unspent part of the channel's deposit to the wallet that funded it. | | `BCK.ROUTER.0043` | 503 | integration | ✅ | The payment channel with this service is busy | The Router could not sign this payment on its MPP session payment channel with this service right now: another payment on the same channel held it too long, the wallet's signer or balance read did not answer in time, or a top-up of the channel's deposit could not be completed yet. This is transient. Nothing was signed, reserved or charged for this request. Retry after a few seconds with the same requestId. `params.stage` says which step did not answer: `lock`, `sign`, `balance`, or `top-up` (a top-up of the channel was already in flight, or the service could not be reached to take one). | | `BCK.ROUTER.0044` | 422 | business | ❌ | The Router cannot collect its fee on this MPP session payment | The service is paid over an MPP `session` (a payment channel with a deposit and per-call vouchers). A session's routing fee is never charged call by call: it is added up and collected later in a single transfer from the paying wallet, and here it could not be, so the Router refuses the payment instead. Nothing was signed, reserved or charged, and no payment channel was opened. The params field is a JSON string whose `cause` says why. `org-wallet`: the payment is funded by an organization wallet, which that collection cannot draw from yet; pay this service with a delegation funded by your own wallet. `network`: this Router deployment does not collect session fees on the service's network; that is a configuration gap on our side, so retrying fails the same way until it changes. Pay a service on another network meanwhile, and quote correlationId when reporting it. | | `BCK.ROUTER.0045` | 409 | business | ❌ | The service does not offer the payment rail you pinned | You set `requireProtocol` to force this call onto one payment rail (x402 or mpp), and the service's payment challenge does not offer that rail — so the Router refused rather than pay on the other one. Nothing was signed, reserved or charged. The params field is a JSON string carrying `requireProtocol` (what you pinned) and `offered` (the rails the service's 402 actually offered, if any). Use a service that accepts your rail, or report to the human, who can deliberately drop `requireProtocol` to let the Router auto-select the rail the service offers, or pin the rail it does offer. | | `BCK.ROUTER.0046` | 400 | business | ❌ | The request body does not match the endpoint schema | You set `validateRequestBody` to have the Router check your request body before paying, and it does not match the request schema the service published for this endpoint — so the Router refused before charging, and you were not billed for a call that would have failed. Nothing was signed, reserved or charged. The params field is a JSON string carrying `endpointPath` (the endpoint whose schema the body failed). Fix the body to match the published schema (see `requestSchema` / `requestExample` on the endpoint in the catalog service detail, GET /api/v1/catalog/services/:slug, and in the MCP `get_service` result) and retry. Retrying the same body fails identically; drop `validateRequestBody` to let the call through unchecked. | | `BCK.ROUTER.0047` | 409 | business | ❌ | This delegation does not allow session payments | The Router would pay this service over an MPP `session` (a payment channel: a refundable deposit leaves the wallet at the first call, and each call is paid out of it), and this delegation was created with `allowSessionPayments: false`. Nothing was signed, reserved or charged, and no payment channel was opened. Use a service that charges per call, or report to the human, who can deliberately drop a `requireProtocol: "mpp"` pin (a service that also offers x402 is then paid there) or create a new delegation that allows session payments, since a delegation cannot be edited. If the delegation is held by an app connected over OAuth, they disconnect the app in Nevermined and reconnect it with session payments allowed instead. | ## `BCK.STRIPE` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.STRIPE.0001` | 400 | integration | — | Error creating Stripe account | Inspect Stripe dashboard logs for the request id we return in params. Account creation failed at the Stripe side — usually a missing legal entity or invalid country. | | `BCK.STRIPE.0002` | 400 | integration | — | Error creating Stripe checkout session | Inspect Stripe dashboard logs for the request id we return in params. Checkout session creation failed — verify the plan’s priceId is live and the Connect account is fully onboarded. | | `BCK.STRIPE.0003` | 400 | integration | — | Error creating Stripe payment intent | Inspect Stripe dashboard logs for the request id we return in params. PaymentIntent creation failed — usually an invalid currency/amount or missing customer. | | `BCK.STRIPE.0004` | 400 | integration | — | Error processing Stripe account webhook for updating an account | Inspect the underlying error and the Stripe event id in params. The webhook handler failed; the event will be retried by Stripe. | | `BCK.STRIPE.0005` | 400 | integration | — | Error processing Stripe connect webhook | Inspect the underlying error and Stripe event id in params. The Connect webhook handler rejected the payload — usually a schema mismatch or unsupported event type. | | `BCK.STRIPE.0006` | 500 | integration | — | Error processing Stripe checkout event with error | Inspect the underlying error and Stripe event id in params. The checkout-completed handler failed; manual reconciliation may be needed for the buyer. | | `BCK.STRIPE.0007` | 400 | integration | — | Invalid input params | Verify the request body matches the endpoint schema. Common cause: missing planId or zero amount. | | `BCK.STRIPE.0008` | 400 | integration | — | Stripe event not handled | Stripe sent an event type this deployment does not handle. Safe to ignore unless the event is one we expect to act on — in which case add the handler. | | `BCK.STRIPE.0009` | 400 | integration | — | The plan indicated is not valid for Stripe payment | Verify the planId references a fiat plan with a configured Stripe priceId. Crypto-only plans cannot be paid via Stripe. | | `BCK.STRIPE.0010` | 400 | integration | — | The plan is not a Fiat plan | Use a fiat plan for Stripe checkout. Crypto plans must be paid through the on-chain flow (/protocol/order or x402). | | `BCK.STRIPE.0011` | 400 | integration | — | Error calculating plan checkout price | Inspect the underlying error and the planId in params. Checkout-price computation failed — usually a missing/invalid price metadata or platform-fee config. | | `BCK.STRIPE.0012` | 400 | integration | — | The account selling the plan is not properly configured to accept Stripe payments | The plan seller must complete Stripe Connect onboarding (charges\_enabled + payouts\_enabled). Until then their plans cannot be sold via Stripe. | | `BCK.STRIPE.0013` | 400 | integration | — | Payment intent not succeeded | The Stripe PaymentIntent is not in a terminal success state. Check status in the Stripe dashboard; if it is processing, retry after the webhook lands. | | `BCK.STRIPE.0014` | 400 | integration | — | Invalid payment amount from payment intent | The PaymentIntent amount does not match the expected plan price. Verify currency and amount on the Stripe side; mismatched currencies are the most common cause. | | `BCK.STRIPE.0015` | 400 | integration | — | Customer not found | Verify the Stripe customerId. The customer may have been deleted in the Stripe dashboard or never created for this user. | | `BCK.STRIPE.0016` | 400 | integration | — | Subscription not found | Verify the Stripe subscriptionId. The subscription may have been canceled and pruned, or belong to a different account/environment. | | `BCK.STRIPE.0017` | 400 | integration | — | Invoices not found | Verify the Stripe subscription/customer reference. No invoices were found for the requested filters. | | `BCK.STRIPE.0018` | 400 | integration | — | Error retrieving Stripe payment metadata | Inspect Stripe dashboard logs for the request id we return in params. PaymentIntent metadata retrieval failed — usually a transient Stripe API issue. | | `BCK.STRIPE.0019` | 400 | integration | — | Error retrieving Stripe balance | Inspect Stripe dashboard logs for the request id we return in params. Balance retrieval failed — usually a Connect-account configuration or scope issue. | | `BCK.STRIPE.0020` | 500 | integration | — | Error canceling subscription | Inspect Stripe dashboard logs for the request id we return in params. Subscription cancellation failed — verify the subscription belongs to the right Connect account. | | `BCK.STRIPE.0021` | 400 | integration | — | Unable to create Stripe subscription | Inspect Stripe dashboard logs for the request id we return in params. Subscription create failed — usually a missing customer default payment method or invalid price. | | `BCK.STRIPE.0022` | 424 | integration | — | The settlement could not be executed because the seller account has not properly configured the payment service provider (Stripe) | The plan seller has not completed Stripe Connect onboarding (charges\_enabled is false). Ask the seller to finish onboarding before retrying the settlement. | | `BCK.STRIPE.0023` | 503 | integration | — | Transient failure while looking up the seller payment service provider configuration | Inspect the underlying error in logs. The seller PSP-configuration lookup failed transiently — retry; if it persists, check DB connectivity. | | `BCK.STRIPE.0024` | 424 | integration | ❌ | The organization owning the plan you are trying to purchase has not configured its payment service provider (Stripe). Contact the organization to complete the setup before retrying the purchase. | The plan is owned by an organization that has not connected Stripe (or has not completed Connect onboarding) for this environment. Surface the orgId / orgName carried in params so the buyer can identify the organization to contact. | | `BCK.STRIPE.0025` | 500 | internal | ❌ | The payment could not be routed to the seller and was not attempted | Internal defect, not a seller or buyer misconfiguration: a card charge reached the Stripe Connect split without a destination account and without an explicit platform-only opt-out, so it was refused before any PaymentIntent was created. Not reachable from any client input since #3136 removed the caller-settable merchantAccountId - if you are seeing this, a server-side caller failed to resolve a seller. No money moved. On the Visa rail a single-use VGS cryptogram and a Stripe PaymentMethod may already have been created for the attempt and are left unused - harmless, but it is not true that nothing external happened. Check the logged delegationId and how the caller resolved its merchant account. | | `BCK.STRIPE.0030` | 500 | integration | — | Application-fee true-up refund failed; row left Settled with the owed amount stored in providerMetadata.trueUpRefundOwedMicro for manual reconciliation | The Stripe application-fee true-up refund failed. The settlement row is left as Settled with the owed amount in providerMetadata.trueUpRefundOwedMicro for manual reconciliation through Stripe Dashboard. | | `BCK.STRIPE.0031` | 500 | internal | ❌ | Price conversion overflow when converting micro-units to cents | The plan price exceeds Number.MAX\_SAFE\_INTEGER after conversion. Lower the plan price or fix the unit boundary in convertMicroUnitsToCents. | | `BCK.STRIPE.0032` | 500 | integration | ❌ | Stripe checkout: user profile not found for account event | The Stripe account event referenced a user that no longer exists in our DB (deleted profile, or environment mismatch between live/sandbox). The webhook is marked permanent so Stripe stops retrying. | | `BCK.STRIPE.0033` | 500 | integration | ✅ | Stripe account webhook handler failed | Generic catch-all for the account webhook handler — inspect the cause field for the underlying error and the params for eventId/stripeAccountId/userId. | | `BCK.STRIPE.0034` | 500 | integration | ✅ | Stripe payment intent webhook handler failed | Generic catch-all for the payment intent webhook handler — inspect the cause and params.eventId. | | `BCK.STRIPE.0035` | 500 | integration | ✅ | Stripe subscription invoice webhook handler failed | Generic catch-all for the subscription invoice (recurring) webhook handler — inspect the cause and params.eventId. | | `BCK.STRIPE.0036` | 400 | business | ❌ | Stripe subscription creation: plan has no Stripe priceId | The plan DDO is missing metadata.plan.priceId. Re-publish the plan with a Stripe price configured, or use the one-shot payment intent flow. | | `BCK.STRIPE.0037` | 400 | integration | ✅ | Stripe subscription creation: no latest invoice on subscription | The newly-created subscription did not return a latest\_invoice. Retry once; if it persists, check Stripe dashboard for the subscription state. | | `BCK.STRIPE.0038` | 400 | integration | ✅ | Stripe subscription creation: no payment intent on subscription | The subscription invoice did not yield a payment\_intent. This usually means the customer has no default payment method. Confirm the SetupIntent has succeeded before creating the subscription. | | `BCK.STRIPE.0039` | 400 | business | ❌ | No Stripe account connected | The authenticated user has no personal Stripe account and belongs to no organization with one connected. Connect a Stripe account (Profile or Organization → Details) before requesting the account balance. | | `BCK.STRIPE.0040` | 424 | integration | ❌ | The seller Stripe Connect account is no longer reachable | The plan seller's Stripe Connect account was deauthorized, deleted, or its OAuth grant lapsed, so the platform can no longer pay out to it (Stripe: account\_invalid). The stale validated flag has been cleared automatically; the seller must reconnect Stripe (Profile or Organization → Details). Not retryable until they do. | | `BCK.STRIPE.0041` | 400 | integration | ❌ | This plan cannot be purchased through checkout | Checkout fulfils a purchase through the fiat payment template, and this plan is registered on a different on-chain template (see params.templateAddress). A pay-as-you-go plan is paid per request through a card delegation (x402) instead of checkout; for any other template, contact the plan owner. Nothing was charged. | | `BCK.STRIPE.0042` | 400 | validation | ❌ | A billing address is required for an organization subscription | Organization plans are billed net of tax, and VAT or sales tax is added from the billing address. Send `billingDetails.address` (at least the country) with the request. Nothing was charged. | | `BCK.STRIPE.0043` | 400 | validation | ❌ | The billing address cannot be used to calculate tax | Stripe could not resolve a tax location from the billing address (see params.country). Check the country and, for the United States or Canada, the postal code, then try again. Nothing was charged. | | `BCK.STRIPE.0044` | 400 | validation | ❌ | The tax ID is not valid | Stripe refused the tax ID for its type (see params.taxIdType) — usually a format that does not match the country. Correct it, or leave the tax ID empty to continue without one. Nothing was charged. | | `BCK.STRIPE.0045` | 409 | business | ❌ | Your organization already has an active subscription | This organization-tier checkout did not say which organization to apply to, and your current organization already has an active subscription. To create a NEW organization, use "Create new organization"; to change this organization's tier, go to Organization → Billing. Nothing was charged. | | `BCK.STRIPE.0046` | 503 | integration | ✅ | Stripe could not be reached to start the payment | A call to Stripe failed transiently (network, Stripe 5xx or rate limit) before the card was charged. Nothing was charged. Retry shortly. If it keeps failing, contact support. | ## `BCK.STRIPE.CONNECT` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.STRIPE.CONNECT.0001` | 503 | integration | — | Stripe Connect is not configured | `STRIPE_CONNECT_CLIENT_ID` is unset. Configure Stripe Connect credentials in the environment before enabling Connect features. | | `BCK.STRIPE.CONNECT.0002` | 400 | integration | — | Stripe OAuth token exchange failed | Inspect Stripe dashboard logs for the request id we return in params. The OAuth code exchange failed — usually a mismatched redirect\_uri or expired code. | | `BCK.STRIPE.CONNECT.0003` | 400 | integration | — | Stripe OAuth response missing stripe\_user\_id | Stripe returned a successful OAuth response without stripe\_user\_id. Treat as a Stripe API anomaly and restart the OAuth flow. | | `BCK.STRIPE.CONNECT.0004` | 400 | integration | — | Stripe account environment does not match platform environment | The connected account is in a different Stripe environment (sandbox vs live) than the platform. Re-connect using the platform’s matching environment. | | `BCK.STRIPE.CONNECT.0005` | 404 | integration | — | User profile not found for Stripe Connect update | Verify the user-profile id in params. The OAuth callback fired for a user that no longer has a profile row — likely a deleted account. | | `BCK.STRIPE.CONNECT.0006` | 409 | integration | — | Organization Stripe scope could not be resolved | An organization-scoped connect/disconnect was requested but the organization could not be resolved for the caller (deactivated, membership revoked mid-flow, or a transient lookup error). We refuse rather than fall back to the personal profile so the scopes stay independent — retry once the membership/org is available. | | `BCK.STRIPE.CONNECT.0007` | 400 | validation | — | Organization Stripe connect requires an organization id | An organization-origin connect was requested without an orgId. Pass the orgId of the workspace to connect (admin membership required); the personal flow is served without an orgId. | | `BCK.STRIPE.CONNECT.0008` | 400 | validation | — | orgId is not supported together with a supplied stripeAccountId | Organization scoping is applied by stamping metadata on a freshly-created Express account, which is not possible for a caller-supplied existing account. Either omit orgId (personal account) or omit stripeAccountId (let us create the org-scoped Express account). | | `BCK.STRIPE.CONNECT.0009` | 403 | auth | — | This account cannot onboard as a Stripe seller | Seller onboarding is not available for this Nevermined account: it is disabled, or its profile has not been created yet. Sign in to the Nevermined app once to create the profile, or contact Nevermined support if you believe this is a mistake. | | `BCK.STRIPE.CONNECT.0010` | 403 | business | — | Seller onboarding is not available for this email domain | Use an email address on a different domain for your Nevermined account and Stripe onboarding, or contact Nevermined support. | | `BCK.STRIPE.CONNECT.0011` | 429 | business | ✅ | Too many Stripe accounts created recently | Each Nevermined account can create a limited number of Stripe Express accounts per day. Finish onboarding the account you already started, try again later, or contact Nevermined support. | | `BCK.STRIPE.CONNECT.0012` | 403 | auth | — | Stripe onboarding account does not belong to the caller | A supplied stripeAccountId must match your saved personal Stripe account in the current environment. Omit stripeAccountId to create a new account, or use the organization onboarding flow with orgId and no stripeAccountId. | ## `BCK.SUBSCRIPTION_ACCESS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_ACCESS.0001` | 404 | business | ❌ | Not found | This route is not available to the caller. The Nevermined Subscription is dark-launched: it answers 404 when NVM\_SUBSCRIPTION\_ENABLED is off in this deployment, and otherwise — unless NVM\_SUBSCRIPTION\_OPEN admits every authenticated caller — to every caller whose user id, or whose active organization, has not been granted access. GET /api/v1/subscription/eligibility also answers it to a caller acting in an organization (X-Current-Org-Id, or an organization API key, as an active member): the subscription is for personal accounts only — call with a personal API key (one with no organization tag) and no X-Current-Org-Id. The cases are deliberately identical on the wire; the server log names which one applied. | ## `BCK.SUBSCRIPTION_BILLING` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_BILLING.0001` | 404 | business | ❌ | Subscription plan not found | params.catalogId names no Nevermined Subscription price on sale: it does not exist, has been retired (inactive), or is a legacy tax-inclusive price, which is no longer sold because prices are now tax-exclusive. Pick a current one from GET /api/v1/subscription/plans. An operator fixes a missing plan by bootstrapping a tax-exclusive price, never by re-activating a legacy one. | | `BCK.SUBSCRIPTION_BILLING.0002` | 409 | business | ❌ | A subscription already exists for this owner | The owner (params.ownerType) already holds a live Nevermined Subscription (params.status), including one whose first payment is still pending. Change plan, payment method or cancel through the Customer Portal (POST /api/v1/subscription/portal) instead of starting a second checkout. | | `BCK.SUBSCRIPTION_BILLING.0003` | 403 | auth | ❌ | Only an organization admin can manage its subscription | ownerType "org" acts on the organization the request is made in (X-Current-Org-Id, else the API key organization). The caller must be an active admin of that active organization; params.reason says which condition failed (no-org-context, not-admin or org-inactive). | | `BCK.SUBSCRIPTION_BILLING.0004` | 409 | business | ❌ | The subscription owner’s account is not fully set up | A subscription is recorded against its owner’s account address: the user account for a personal subscription, the organization’s wallet address for an organization one. params.ownerType names the owner whose address could not be resolved. An organization without a wallet must finish its setup first. | | `BCK.SUBSCRIPTION_BILLING.0005` | 502 | integration | ✅ | Stripe refused or failed a subscription billing request | A Stripe call of the checkout or portal failed (params.step: customer, live-subscriptions, expire-open-sessions, checkout-session, checkout-session-status, portal-session, or, paying with an enrolled card, customer-country, customer-tax-id, tax-preview, subscription, supersede-attempt and enrolled-card-payment). Nothing was charged, except possibly at enrolled-card-payment: a failure there can follow a payment Stripe took, so read GET /api/v1/subscription/account before paying again — a retry with the subscription still incomplete cancels it first. Retry; if it persists, check the Nevermined Subscription Stripe account (Stripe Tax and the Customer Portal must be configured on it). | | `BCK.SUBSCRIPTION_BILLING.0006` | 404 | business | ❌ | No subscription billing account for this owner | The owner (params.ownerType) has never completed a Nevermined Subscription checkout, so there is no billing account to open the Customer Portal for. Subscribe first with POST /api/v1/subscription/checkout/enrolled-card. | | `BCK.SUBSCRIPTION_BILLING.0007` | 422 | integration | ❌ | The Stripe subscription does not identify a Nevermined Subscription owner | The subscription (params.stripeSubscriptionId) bills a Nevermined Subscription catalog price but carries no valid ownerType / ownerId metadata (params.reason), so no subscriptions row can be written and no credits minted. Subscriptions created by POST /api/v1/subscription/checkout/enrolled-card (or the deprecated POST /api/v1/subscription/checkout) carry it. Fix the metadata in the Stripe dashboard, then resend the event. (A subscription billing no catalog price is another product on the same Stripe account and is ignored, not refused.) | | `BCK.SUBSCRIPTION_BILLING.0008` | 409 | integration | ❌ | The owner already holds another live Nevermined Subscription | A second live Stripe subscription (params.stripeSubscriptionId) arrived for an owner that already has one (params.existingSubscriptionId). It was not recorded and grants no credits. Cancel and refund the duplicate in the Stripe dashboard. | | `BCK.SUBSCRIPTION_BILLING.0009` | 502 | integration | ✅ | A Stripe read failed while processing a subscription event | Reading the subscription, invoice or payment behind the event from Stripe failed (params.step). Nothing was committed; Stripe redelivers the event. | | `BCK.SUBSCRIPTION_BILLING.0010` | 422 | integration | ❌ | A paid invoice bills a price that is not in the subscription catalog | The invoice (params.invoiceId) bills a Stripe price (params.stripePriceId) with no subscription\_catalog row, so its credits are unknown and none were minted. Add the price through the catalog bootstrap, then resend the event. | | `BCK.SUBSCRIPTION_BILLING.0011` | 422 | integration | ❌ | A paid subscription invoice grants no credits | The paid create/cycle invoice (params.invoiceId) has no subscription line to grant credits for, or its catalog row names no credits plan (params.reason: no-credits or no-plan). Nothing was minted. Inspect the invoice lines and the subscription\_catalog row, fix them, then resend the event. | | `BCK.SUBSCRIPTION_BILLING.0012` | 422 | integration | ❌ | The Stripe object behind a subscription event does not exist | Stripe answered 404 for the subscription, invoice or payment behind the event (params.step) — typically an event from another account or mode, or a deleted test clock. Nothing was committed. Resend the event once the object is reachable with STRIPE\_SUBSCRIPTION\_API\_KEY. | | `BCK.SUBSCRIPTION_BILLING.0013` | 422 | integration | ❌ | A dispute closed with an outcome the subscription does not handle | The dispute (params.disputeId) closed with status params.status, which is neither won nor lost (for example prevented). Its clawback and suspension were left as they are and the event unprocessed. Decide the outcome, apply it by hand, then resend the event if a handler for the status ships. | | `BCK.SUBSCRIPTION_BILLING.0014` | 403 | business | ❌ | The Nevermined Subscription is available to personal accounts only | A checkout for an organization (ownerType "org") is refused: until it is decided how the subscription works for organizations, only a personal subscription can be bought. Subscribe with ownerType "user". An organization subscription bought earlier can still be read, managed and cancelled. | | `BCK.SUBSCRIPTION_BILLING.0015` | 404 | business | ❌ | Subscription checkout session not found | params.sessionId names no Nevermined Subscription checkout of this owner (params.ownerType): it does not exist, or another owner started it. Read the status of a checkout started by POST /api/v1/subscription/checkout, with the session id Stripe put on the return URL. | | `BCK.SUBSCRIPTION_BILLING.0016` | 404 | business | ❌ | The enrolled card cannot pay the subscription | params.paymentMethodId names no active card of the caller that can pay the Nevermined Subscription: it does not exist, is revoked, or carries no active network token. Only cards listed by GET /api/v1/payment-methods/chargeable?purpose=subscription qualify: choose one of them, or enrol another card. Nothing was charged. | | `BCK.SUBSCRIPTION_BILLING.0017` | 402 | business | ❌ | The enrolled card was declined | The first payment of the subscription was refused (params.declineCode when the issuer gave one). The subscription attempt was cancelled and nothing was charged. Try another card from GET /api/v1/payment-methods/chargeable?purpose=subscription with POST /api/v1/subscription/checkout/enrolled-card. | | `BCK.SUBSCRIPTION_BILLING.0018` | 409 | business | ❌ | Tax cannot be computed for paying with an enrolled card | Paying with an enrolled card (the Nevermined Subscription, or the first credit top-up pack) taxes the purchase from the billing address given, else the buyer’s Stripe customer’s, else the payment country of the profile, and Stripe Tax could not compute the tax from it (params.taxStatus): no country, a country that also needs a postal code (the United States, Canada), or invalid-location, an address Stripe cannot place (check the postal code; params.step names the call). Nothing was charged. Send billingAddress with a country, and a postal code in the US and Canada (country and postalCode on the preview: GET /api/v1/subscription/checkout/enrolled-card/preview, or GET /api/v1/credits/topups/checkout/preview for a top-up pack). | | `BCK.SUBSCRIPTION_BILLING.0019` | 400 | validation | ❌ | The tax id was refused | The tax id given (taxId on the payment — of the Nevermined Subscription or the first credit top-up pack — taxIdType and taxIdValue on the preview) was refused: its type is not the VAT number type of the billing country (params.taxIdType, params.country), or Stripe refused its value as not a valid number of its type, or a tax id for this customer. params.step names the call. Nothing was charged. Correct the number, or pay without it. | ## `BCK.SUBSCRIPTION_CATALOG` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_CATALOG.0001` | 400 | business | ❌ | This plan is sold only as the Nevermined Subscription | params.planId is the Nevermined Subscription credits plan. Its credits are granted only by a paid invoice of the Nevermined Subscription and are spent only through the Router, so it cannot be bought or settled through fiat checkout, crypto order or x402 (params.path names the path that refused it). | | `BCK.SUBSCRIPTION_CATALOG.0002` | 400 | validation | ❌ | Invalid Nevermined Subscription catalog definition | The catalog bootstrap body is inconsistent (params.reason says how): a plan key may appear only once, and a plan may list each currency only once (the same currency across different plans is fine). Nothing was created. | | `BCK.SUBSCRIPTION_CATALOG.0003` | 409 | integration | ❌ | The Stripe catalog object differs from the requested definition | A Stripe product or price already exists for params.lookupKey (or params.productId) with different terms (params.field: params.existing vs params.requested). Stripe prices are immutable: to change a price, retire this one and publish a new plan key, or send the existing terms. Rows written earlier in this run are kept; re-running with matching terms is safe. | | `BCK.SUBSCRIPTION_CATALOG.0004` | 502 | integration | ✅ | Stripe refused or failed a Nevermined Subscription catalog call | A Stripe call of the catalog bootstrap failed (params.operation, params.lookupKey). Every step is find-or-create with an idempotency key, so re-running the bootstrap resumes where it stopped. | | `BCK.SUBSCRIPTION_CATALOG.0005` | 503 | integration | ❌ | The Nevermined Subscription plan owner is not configured (retired: no longer returned) | Retired. The Nevermined Subscription credits plan is owned by the API provider account, so no owner address is configured any more and this code is no longer returned. Only an older API deployment can still return it. | | `BCK.SUBSCRIPTION_CATALOG.0006` | 503 | internal | ✅ | Could not check the plan against the Nevermined Subscription catalog | A transient database failure prevented checking whether this plan may be bought here. Nothing was charged or ordered; retry the request. | | `BCK.SUBSCRIPTION_CATALOG.0007` | 503 | internal | ✅ | The Nevermined Subscription catalog bootstrap hit a database error | A database read or write of the catalog bootstrap failed (params.lookupKey / params.stripePriceId, params.planId for the credits plan, or params.ownerAddress while provisioning its owner, the System profile, when known). Any Stripe object already created is kept and found again, so re-running the bootstrap resumes where it stopped. A 0007 that persists across re-runs is not transient: read the API log for the original error. | | `BCK.SUBSCRIPTION_CATALOG.0008` | 409 | integration | ❌ | The plan-owner address resolves to another account | The Nevermined Subscription credits plan is owned by the API provider account (params.ownerAddress), but no profile has that address as its own: a lookup by it resolves to another account, which records it as its 7702 wallet. The credits plan was not stored (catalog rows written earlier in the run are kept). Investigate the profile recording that wallet, then re-run the bootstrap. | | `BCK.SUBSCRIPTION_CATALOG.0009` | 503 | internal | ✅ | The catalog credits could not be read | Reading catalog credits eligibility failed on our side (see the server log). Nothing was charged; retry in a moment. Coverage is unavailable, not zero. Search can be retried without funding; do not claim those results are payable with credits. Price views can show the budget (USD) price until the credits read succeeds. | ## `BCK.SUBSCRIPTION_COMPLIANCE` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_COMPLIANCE.0001` | 400 | validation | ❌ | The checkout is missing a required consent | params.missing names the consent the buyer did not give: autoRenewal (every checkout), or immediateSupplyWaiver (a personal checkout). Show the texts from GET /api/v1/subscription/consent, have the buyer tick each one, and send them back as consent. | | `BCK.SUBSCRIPTION_COMPLIANCE.0002` | 409 | business | ❌ | The consent text shown to the buyer is out of date | consent.version is not the current consent version (params.currentVersion). Reload the texts from GET /api/v1/subscription/consent, show them to the buyer again and send the new version. | | `BCK.SUBSCRIPTION_COMPLIANCE.0003` | 409 | business | ❌ | This subscription price cannot be sold to a personal buyer (retired: no longer returned) | Retired. Subscription prices are tax-exclusive and VAT is added at checkout, so every price can be sold to a personal buyer and this code is no longer returned. Only an older API deployment can still return it. | | `BCK.SUBSCRIPTION_COMPLIANCE.0004` | 404 | business | ❌ | No active subscription to cancel | The owner (params.ownerType) has no live subscription, so there is nothing to cancel. Open the Customer Portal (POST /api/v1/subscription/portal) to see past invoices. | | `BCK.SUBSCRIPTION_COMPLIANCE.0006` | 503 | integration | ✅ | A renewal reminder could not be delivered | The renewal reminder for subscription params.subscriptionId could not be emailed; Stripe redelivers the event and the reminder is retried. Check RESEND\_API\_KEY / RESEND\_EMAIL\_SENDER. | | `BCK.SUBSCRIPTION_COMPLIANCE.0007` | 500 | integration | ❌ | A subscriber has no email address for a consumer notice | Subscription params.subscriptionId has no email on its profile(s) or its Stripe customer, so the params.kind notice (params.noticeKey) was not sent, and nothing retries it: that notice is lost. Add an address for the owner so the next one reaches them (or cancel the subscription). | | `BCK.SUBSCRIPTION_COMPLIANCE.0008` | 500 | internal | ❌ | A paid subscription has no checkout consent record | Checkout session params.sessionId (subscription params.subscriptionId) completed without a linkable consent row (params.reason). The subscription has no consent evidence; investigate how the session was created. | | `BCK.SUBSCRIPTION_COMPLIANCE.0010` | 500 | internal | ❌ | The welcome-credit terms cannot be rendered from this deployment's settings | params.credits or params.expiryDays (WELCOME\_CREDITS\_AMOUNT / WELCOME\_CREDITS\_TTL\_DAYS) is not a positive integer, so the welcome-credit terms are not shown rather than shown wrong. Fix the deployment setting. | ## `BCK.SUBSCRIPTION_MCP` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_MCP.0001` | 503 | internal | ✅ | The subscription balance could not be read | Reading your Nevermined Subscription or its credits failed on our side (see the server log). Reading charges nothing and changes nothing; retry in a moment. | ## `BCK.SUBSCRIPTION_REFUND` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_REFUND.0001` | 503 | internal | ❌ | SLA grants are not configured on this deployment | SUBSCRIPTION\_SLA\_GRANT\_MAX\_CREDITS (the most credits one SLA grant may give) is unset or not a positive integer, so every SLA grant is refused. It is a policy value with no default: set it for this deployment, then retry. Nothing was granted. | | `BCK.SUBSCRIPTION_REFUND.0002` | 400 | validation | ❌ | The SLA grant exceeds the most credits one grant may give | `params.credits` is above `params.maxCredits` (SUBSCRIPTION\_SLA\_GRANT\_MAX\_CREDITS). Grant at most that many credits per request. Nothing was granted. | | `BCK.SUBSCRIPTION_REFUND.0003` | 404 | business | ❌ | No subscription payment with that id | `params.paymentId` names no Router payment funded by a Nevermined Subscription. Check the id against GET /api/v1/router/payments (`fundingSource: subscription`). Nothing was changed. | | `BCK.SUBSCRIPTION_REFUND.0004` | 409 | business | ❌ | The payment's credits were not committed, so it gets no SLA grant | An SLA grant is for a call the merchant answered 2xx (`creditsStatus: Committed`). `params.creditsStatus` says where this call's credits stand: `Refunded` calls already got them back, and `Reserved` calls are still being decided (a failed call is refunded by the refund engine, not by an SLA grant). Nothing was granted. | | `BCK.SUBSCRIPTION_REFUND.0005` | 409 | business | ❌ | The holder has no current subscription period to grant credits into | An SLA grant lands in the holder's current period and expires with it. This holder has no unexpired credits lot on the plan, so there is nothing to grant into. Nothing was granted. | | `BCK.SUBSCRIPTION_REFUND.0006` | 409 | business | ❌ | That idempotency key was already used for a different SLA grant | Each `idempotencyKey` names ONE SLA grant. A retry must repeat the original request exactly; `params.creditId` is the grant the key already made. Use a new key for a new grant. Nothing was granted. | | `BCK.SUBSCRIPTION_REFUND.0007` | 500 | internal | ❌ | The payment's credits burn is missing from the ledger | The subscription payment names a credits burn the credit ledger does not hold, so its subscriber cannot be resolved. This is a Nevermined ledger inconsistency, logged for investigation. Nothing was granted. | | `BCK.SUBSCRIPTION_REFUND.0008` | 500 | internal | ❌ | A subscription payment's credits could not be refunded | The refund engine found the payment in a state it cannot refund from (`params.reason`). The credits stay reserved and the payment stays queued for the refund sweep; this is logged for investigation, and the sweep's `CREDITS UNDECIDED` / FAILED lines name the payment. | | `BCK.SUBSCRIPTION_REFUND.0009` | 409 | business | ❌ | The payment's credits outcome is already decided | Only a subscription payment whose credits are still `Reserved` with no recorded outcome can be resolved by hand. `params.creditsStatus` and `params.decided` say where this one stands: a call already marked not-delivered is refunded by the sweep, and a `Committed` or `Refunded` call is final. Nothing was changed. | ## `BCK.SUBSCRIPTION_ROUTER` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_ROUTER.0001` | 403 | business | ❌ | This catalog endpoint cannot be paid with subscription credits | The Nevermined Subscription pays only listed, live catalog endpoints it can price. `params.reason` says which check this call failed: unlisted, credits\_excluded (Nevermined does not sell this listing or its merchant for credits, on any endpoint: quote another listing, or pay this one with a delegation, a personal crypto-wallet one for an MPP session merchant, which a card delegation cannot pay, or for a merchant that sells only to the payer’s own wallet, which neither a card nor an organization delegation can pay), moderation\_not\_live, non\_payable\_protocol, unpayable, unhealthy, wallet\_bound (the service delivers results only to the wallet that paid, and this endpoint is not a reviewed self-contained one), endpoint\_unobserved, price\_variable, no\_active\_tariff, no\_fundable\_offer (the merchant offers no payment the subscription can fund, such as an asset it does not pay in), or endpoint\_unresolved (the method and path do not name exactly one listed endpoint of the service). Nothing was reserved, signed or charged. Pay this endpoint through POST /api/v1/router/route with a delegation instead, or quote another endpoint with POST /api/v1/router/subscription/quote. | | `BCK.SUBSCRIPTION_ROUTER.0002` | 402 | business | ❌ | No spendable credits and no Nevermined Subscription in good standing | The caller has nothing to pay this call with: a personal account holds no spendable credits (welcome, top-up or a subscription’s monthly allowance) and no subscription in good standing, or has no wallet address to hold credits. A call acting in an organization (X-Current-Org-Id, or an organization API key, as an active member) is paid only from that organization’s subscription in good standing — which organizations can no longer buy — and never from the caller’s own credits. Nothing was reserved or signed for the service call. If `params.topUps` is `bought`, this call already charged a credit pack to the saved card before the holder lost standing; `params.purchaseId` names that pack and its credits remain in the account. Otherwise nothing was charged. Subscribe or top up from the Nevermined app, or call with a personal API key and no X-Current-Org-Id, then retry. | | `BCK.SUBSCRIPTION_ROUTER.0003` | 400 | validation | ❌ | This payment rail cannot be paid with subscription credits | Subscription credits pay only an EIP-3009 `exact` authorization (x402, or an MPP `evm` charge), an MPP `tempo` `charge`, and an MPP `tempo` `session` where this deployment has MPP sessions turned on. The merchant answered with another rail (for example MPP `stripe`, a card Shared Payment Token), so the call was refused before anything was reserved, signed or charged. `params.rail` names what the merchant asked for. | | `BCK.SUBSCRIPTION_ROUTER.0004` | 409 | business | ❌ | The merchant's live price cannot be paid with subscription credits | The merchant's live 402 could not be priced in credits: it asked for more than this endpoint's tariff bounds (ceiling\_exceeded), in an asset that is not the tariff's or not a known USD stablecoin (asset\_mismatch), on another network (network\_mismatch), could not be read as a price (invalid\_quote), or — for a service paid over an MPP session — asked to be paid at an address the catalog has not observed for this endpoint (payee\_unobserved). `params.reason` names which. The call was refused before anything was signed and none of the subscription’s credits were used. On ceiling\_exceeded the tariff is also flagged for re-pricing. Retry later, or pay this endpoint with a delegation through POST /api/v1/router/route. | | `BCK.SUBSCRIPTION_ROUTER.0005` | 400 | validation | ❌ | This field is not accepted on a subscription route | A subscription call addresses a catalog service by its `slug` only. A raw `url`, a `delegationId`, a `revealBuyerIdentity` field, or an `X-Router-Target-Url` / `X-Router-Target-Slug` / `X-Router-Delegation-Id` / `X-Router-Reveal-Buyer-Identity` header is refused rather than ignored, so a request that meant something else is never paid with credits. `params.field` names the offending field. | | `BCK.SUBSCRIPTION_ROUTER.0006` | 500 | internal | ✅ | The subscription payment could not be prepared consistently | The payment Nevermined signed did not match the one it priced and cleared (amount, asset, network, recipient or payer), or the call's payer and its payment request named different credentials (an OAuth grant on one and not the other, or two different grants), or, for a service paid over an MPP session, Nevermined's payment channel with it refused its own terms (a per-call price above the channel's deposit ceiling, or a channel the merchant reports that Nevermined does not hold). The reservation was rolled back: no credit was used, nothing was recorded, and anything signed was discarded without reaching the merchant. This is Nevermined's fault, not the caller's; retrying with a new requestId may succeed (not after a credential mismatch, which repeats until Nevermined fixes it). | | `BCK.SUBSCRIPTION_ROUTER.0007` | 400 | validation | ❌ | Subscription funding is not available on this route | Subscription credits never hand the caller a payment credential, so POST /api/v1/router/payments (mode A) cannot be funded by a subscription. Use POST /api/v1/router/subscription/route or ALL /api/v1/router/subscription/svc/:slug, where Nevermined pays the merchant on your behalf. Nothing was reserved, signed or charged. | | `BCK.SUBSCRIPTION_ROUTER.0009` | 402 | business | ❌ | Not enough subscription credits for this call | The subscription's unexpired credits do not cover this call (`params.credits`). Nothing was signed for the merchant and no credits were spent. The monthly allowance resets when the next billing period’s invoice is paid (`resetsAt` on GET /api/v1/router/subscription/balance); quote a cheaper endpoint with POST /api/v1/router/subscription/quote, or pay this one with a delegation (an OAuth connection needs a stablecoin spending cap for that). With credit top-ups on, a call made with your own API key charges a \$10 credit pack automatically when the credits run out, and `params.topUps` says what happened — no credits were spent for this call in any case: paused — a pack was declined or needed authentication, so top-ups are paused: buy a pack from your Nevermined dashboard (POST /api/v1/credits/topups/checkout) to resume them; limitReached — this month’s packs reached your monthly top-up limit (raise it with PUT /api/v1/credits/topups, up to the Nevermined maximum) or that maximum; pending — a pack is being charged and was not confirmed in time: your card may have been charged, and its credits land once the payment is recorded — retry in a moment; unavailable — no pack could be charged right now and none was: retry later; bought — this call charged a pack (`params.purchaseId`, the pack’s `id` in your top-up history, GET /api/v1/credits/topups/purchases), but concurrent calls spent its credits first: the credits are yours, retry. A call made with an OAuth-connected assistant’s credential, or acting in an organization, never charges a pack: its 0009 carries no `params.topUps`. Neither does a call your credits and one pack together would not cover: no pack is charged for it. | | `BCK.SUBSCRIPTION_ROUTER.0010` | 503 | internal | ❌ | Subscription calls are not available on this deployment | A subscription call whose merchant fails must give its credits back, and this deployment has no refund process bound for them, so every subscription call is refused before anything is reserved, signed or charged. This is Nevermined's configuration, not the caller's; retrying will fail the same way until it is fixed. | | `BCK.SUBSCRIPTION_ROUTER.0011` | 500 | internal | ❌ | The caller's subscription could not be resolved to its credits | The caller holds a subscription in good standing, but Nevermined's catalog no longer maps it to the plan its credits belong to. This is Nevermined's data, not the caller's: nothing was reserved, signed or charged, and buying another subscription would not help. | | `BCK.SUBSCRIPTION_ROUTER.0012` | 503 | internal | ✅ | The subscription could not be looked up | Reading the caller’s subscription failed (see the server log). Nothing was reserved, signed or charged; retry shortly. | | `BCK.SUBSCRIPTION_ROUTER.0013` | 500 | internal | ❌ | This endpoint's subscription tariff is unusable | The active tariff for this endpoint does not describe a payable price (for example a missing or non-positive merchant bound). This is Nevermined's data, not the merchant's or the caller's: nothing was reserved, signed or charged. Pay this endpoint with a delegation through POST /api/v1/router/route until it is corrected. | | `BCK.SUBSCRIPTION_ROUTER.0014` | 503 | internal | ✅ | The subscription payment could not be reserved in time | Nevermined's treasury was busy: the reservation waited too long for its lock, or the treasury's signature did not arrive in time. The reservation was rolled back, so no credit was used and no signed payment left Nevermined. Retry shortly with the same requestId. | | `BCK.SUBSCRIPTION_ROUTER.0015` | 402 | business | ❌ | Credits are frozen by a card dispute | A card dispute on a Nevermined Subscription or credit pack payment of this account freezes all of its credits until the dispute is resolved — and keeps them frozen if it is decided in the cardholder’s favour. Nothing was reserved or signed, and nothing was charged unless `params.topUps` is `bought`: this call had first run out of credits and charged a credit pack to your card (`params.purchaseId`, the pack’s `id` in your top-up history, GET /api/v1/credits/topups/purchases), whose credits are yours and frozen with the rest. Withdraw the dispute with your card issuer, or contact Nevermined support to resolve it; until then, pay with a delegation. | | `BCK.SUBSCRIPTION_ROUTER.0016` | 402 | business | ❌ | Not enough credits: the monthly allowance is frozen by an overdue renewal | This call needs more credits than the account can spend right now, because its Nevermined Subscription renewal is overdue: the monthly allowance is frozen until the payment goes through, while welcome and top-up credits stay spendable. Nothing was reserved or signed, and nothing was charged unless `params.topUps` is `bought`: this call had first run out of credits and charged a credit pack to your card (`params.purchaseId`, the pack’s `id` in your top-up history, GET /api/v1/credits/topups/purchases), and concurrent calls spent its credits first. Update the card from the subscription page of the Nevermined app (Update payment method) so the open invoice is paid, and the allowance spends again; or top up, or pay with a delegation. | | `BCK.SUBSCRIPTION_ROUTER.0017` | 402 | business | ❌ | Your daily credit limit would be exceeded | Your personal UTC daily credit limit would be exceeded. No credits were burned or payment signed for this call. Wait until midnight UTC (`params.resetsAt`) or change the limit in the Daily credit limit section of your Nevermined app’s Subscription page. Nothing was charged unless `params.topUps` is `bought`: this call first ran out of credits and charged a credit pack to your card (`params.purchaseId`), whose credits remain in your account. Never switch funding sources automatically. | | `BCK.SUBSCRIPTION_ROUTER.0018` | 503 | internal | ✅ | Your credit budget could not be read or updated | The credit budget could not be read or saved. A spend is refused before any credits are burned or a payment signed; nothing was charged unless `params.topUps` is `bought`: this call first ran out of credits and charged a credit pack to your card (`params.purchaseId`), whose credits remain in your account. Retry shortly; never retry with a different funding source automatically. | | `BCK.SUBSCRIPTION_ROUTER.0019` | 409 | business | ❌ | This call would cost more credits than one call may | At the merchant's price for this request the call costs `params.credits`, above the most one call may cost (`params.limit`). Nothing was reserved, signed or charged. Where the service prices by request, a smaller request may fit; otherwise pay this endpoint with a delegation through POST /api/v1/router/route. | | `BCK.SUBSCRIPTION_ROUTER.0020` | 409 | business | ❌ | This call would cost more credits than this request allows | This call costs `params.credits`, above the `maxCredits` this request set (`params.maxCredits`). Nothing was reserved, signed or charged. Quote the request again (POST /api/v1/router/subscription/quote) and decide whether to pay at that price. | ## `BCK.SUBSCRIPTION_STRIPE` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_STRIPE.0001` | 503 | integration | ✅ | The Nevermined Subscription Stripe account is not configured | This deployment has no Nevermined Subscription Stripe account configured (on authenticated paths params.missing names the config key; on the webhook it is logged only). Set STRIPE\_SUBSCRIPTION\_API\_KEY and STRIPE\_SUBSCRIPTION\_WEBHOOK\_SECRET for the deployment. Stripe retries a refused delivery for a limited window (about three days in live mode, less in test mode) and may disable an endpoint that keeps failing, so configure both before pointing a Stripe endpoint here. | | `BCK.SUBSCRIPTION_STRIPE.0002` | 400 | validation | ❌ | Missing Stripe signature or request body | The subscription webhook accepts only Stripe-signed deliveries: the request must carry a `stripe-signature` header and the raw event body. This endpoint is called by Stripe, not by API clients. | | `BCK.SUBSCRIPTION_STRIPE.0003` | 400 | auth | ❌ | Stripe signature verification failed | The `stripe-signature` header does not match the body under this deployment’s subscription webhook secret, or its timestamp is outside the 300 s tolerance. Check that the Stripe endpoint for this environment uses the secret in STRIPE\_SUBSCRIPTION\_WEBHOOK\_SECRET (not the platform account’s webhook secret). | | `BCK.SUBSCRIPTION_STRIPE.0004` | 409 | integration | ✅ | This Stripe event is already being processed | Another delivery of the same Stripe event id holds its claim. Stripe retries this delivery later; by then the event is usually processed (the retry is acknowledged as a duplicate) or its claim has been released. A claim left by a pod that crashed mid-processing is neither until its 10-minute lease lapses, so retries in that window get this code again. | | `BCK.SUBSCRIPTION_STRIPE.0005` | 400 | integration | ✅ | Error processing a Nevermined Subscription Stripe webhook | Processing this event failed transiently (see params.eventId and params.type): the claim could not be taken, or the handler or the processed-mark failed. Nothing was committed — the handler and the processed-mark share one transaction — and the claim was released (or never taken), so Stripe’s next redelivery processes the event from scratch. If the release itself failed, redeliveries get BCK.SUBSCRIPTION\_STRIPE.0004 until the claim lease lapses. | | `BCK.SUBSCRIPTION_STRIPE.0006` | 500 | internal | ❌ | A subscription Stripe event handler is registered twice | Two handlers were registered for the same Stripe event type when the API started, so the API does not start. This is a server-side wiring defect, not a problem with any request. | ## `BCK.SUBSCRIPTION_TARIFF` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_TARIFF.0001` | 404 | business | ❌ | Subscription tariff not found | No subscription tariff has that id. List the tariffs for the listing to find the current version. | | `BCK.SUBSCRIPTION_TARIFF.0002` | 409 | business | ❌ | That status change is not allowed for this tariff version | A draft can be activated or retired; an active version suspended or retired; a suspended one reinstated or retired. A retired version is final: create a new version instead. | | `BCK.SUBSCRIPTION_TARIFF.0003` | 409 | business | ✅ | Another change to this tariff committed first | A concurrent change to the same tariff key won. Re-read the current tariffs and retry against it. | | `BCK.SUBSCRIPTION_TARIFF.0004` | 500 | internal | ❌ | Subscription tariff policy is not configured | A tariff policy value this operation needs is unset or invalid in this deployment (see the server log for which). The values are product decisions with no default; set them in the deployment config. | | `BCK.SUBSCRIPTION_TARIFF.0005` | 400 | validation | ❌ | Credits per call must be a rung of the credit ladder | creditsPerCall must be one of the configured ladder values; a tariff never carries an off-ladder credit count. | | `BCK.SUBSCRIPTION_TARIFF.0006` | 404 | business | ❌ | Catalog listing not found | No catalog listing has that service id. Tariffs are keyed by the listing id. | | `BCK.SUBSCRIPTION_TARIFF.0007` | 400 | validation | ❌ | Invalid tariff value | params.field names the rejected value. Atomic amounts are whole digit strings, and a cost ceiling must be at least every basis price it was set from. Paths start with / (or are \*) and contain no whitespace. Methods are upper-case HTTP verbs (or \*). | | `BCK.SUBSCRIPTION_TARIFF.0008` | 409 | business | ❌ | A newer version of this tariff is already live | Activating this draft would roll the published price back to an older version. Retire the stale draft and create a new version from the current terms. | | `BCK.SUBSCRIPTION_TARIFF.0009` | 409 | business | ✅ | Another tariff engine run is in progress | Another engine run holds the run lock (a scheduled run on some replica, or another manual run). Retry shortly; a dry run needs no lock. | | `BCK.SUBSCRIPTION_TARIFF.0010` | 404 | business | ❌ | Tariff engine run not found | No recorded engine run has that id. Dry runs are never recorded; list the recent runs to find one. | | `BCK.SUBSCRIPTION_TARIFF.0011` | 500 | internal | ✅ | The tariff engine run failed | The engine could not take its run lock, read the catalog and tariff state, or record the run (see the server log for which, and how many writes had applied). Every run is idempotent: the next one reconciles whatever state this one left. | | `BCK.SUBSCRIPTION_TARIFF.0012` | 500 | internal | ❌ | Tariff arithmetic received an invalid input | A tariff computation was handed an input no caller should produce (a negative cost or basis, a zero or malformed rational, a ceiling multiplier below 1), so it refused rather than price at the lowest rung. This is a server-side defect; the details name the input. | ## `BCK.SUBSCRIPTION_TREASURY` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.SUBSCRIPTION_TREASURY.0001` | 503 | internal | ❌ | The subscription treasury is not configured for this network | Nevermined has no treasury wallet configured for the chain this listing settles on (or its configuration is invalid), so it cannot pay the merchant. The treasury refused BEFORE signing: no authorization was signed and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. This is Nevermined's configuration, not the caller's: retrying will fail the same way until an operator configures the chain. | | `BCK.SUBSCRIPTION_TREASURY.0002` | 422 | business | ❌ | The listing's payment asset is not the one the subscription treasury pays in | The merchant asked to be paid in a token other than the treasury's settlement asset on that chain (a USD stablecoin). Subscription calls are only paid in that asset. The treasury refused BEFORE signing: no authorization was signed and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. | | `BCK.SUBSCRIPTION_TREASURY.0003` | 503 | business | ✅ | The subscription treasury float cannot cover this payment right now | The treasury wallet's balance, minus the authorizations it has already signed and a merchant can still redeem, is below this payment's price — or, for a service paid over an MPP session, below the payment-channel deposit one more call needs. The treasury refused BEFORE signing: nothing was signed or sent and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. The float is topped up by an operator; retry later. | | `BCK.SUBSCRIPTION_TREASURY.0004` | 503 | business | ✅ | The subscription treasury's daily outflow limit has been reached (retired: no longer returned) | Retired. The Nevermined Subscription no longer limits how much its treasury pays out in a rolling 24 hours, so this code is no longer returned. Only an older API deployment can still return it. | | `BCK.SUBSCRIPTION_TREASURY.0005` | 429 | business | ✅ | This listing has reached its subscription spend limit for the period (retired: no longer returned) | Retired. The Nevermined Subscription no longer caps spending per listing, so this code is no longer returned. Only an older API deployment can still return it. | | `BCK.SUBSCRIPTION_TREASURY.0006` | 429 | business | ✅ | Daily subscription credit limit reached (retired: no longer returned) | Retired. The Nevermined Subscription no longer limits the credits a subscriber spends on one listing per day, so this code is no longer returned. Only an older API deployment can still return it. | | `BCK.SUBSCRIPTION_TREASURY.0007` | 429 | business | ✅ | Spending too fast for a new subscription (retired: no longer returned) | Retired. The Nevermined Subscription no longer limits how fast a subscription spends in its first billing period, so this code is no longer returned. Only an older API deployment can still return it. | | `BCK.SUBSCRIPTION_TREASURY.0008` | 403 | business | ❌ | This merchant cannot be paid by the subscription treasury | The merchant's pay-to address did not pass Nevermined's sanctions screening. The treasury refused BEFORE signing: no authorization was signed and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. This will not change on retry. | | `BCK.SUBSCRIPTION_TREASURY.0009` | 503 | integration | ✅ | The merchant's pay-to address could not be screened | Every address the subscription treasury pays is screened against the OFAC SDN list first, and screening could not answer for this one (the locally stored list is missing or too old, or the lookup failed). The treasury refused BEFORE signing: no authorization was signed and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. Retry later. | | `BCK.SUBSCRIPTION_TREASURY.0010` | 503 | integration | ✅ | The subscription treasury balance could not be read | The treasury reads its on-chain balance before every payment and the read failed (RPC error or timeout). The treasury refused BEFORE signing: no authorization was signed and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. Retry later. | | `BCK.SUBSCRIPTION_TREASURY.0011` | 500 | internal | ❌ | The subscription treasury wallet does not match its configuration | The Privy wallet configured for the treasury on this chain has a different address from the one configured beside it, so signing would pay from an unexpected wallet. The treasury refused BEFORE signing: no authorization was signed and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. This is Nevermined's configuration; an operator must fix it. | | `BCK.SUBSCRIPTION_TREASURY.0012` | 500 | internal | ❌ | The subscription treasury ledger contains a payment it cannot count | A payment row signed by the treasury has an amount that is not a plain integer, or a network the treasury does not recognise, so its exposure cannot be computed. The treasury refused BEFORE signing: no authorization was signed and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. Signing is refused while that row is inside the ledger's counting window (up to 24 hours); an operator should correct the row. | | `BCK.SUBSCRIPTION_TREASURY.0013` | 500 | internal | ❌ | Invalid subscription treasury signing request | The treasury was called with a malformed request: a non-positive or non-integer amount or credit count, an invalid pay-to or asset address, or no enclosing READ COMMITTED database transaction (none at all, or REPEATABLE READ / SERIALIZABLE). This is a Nevermined bug. The treasury refused BEFORE signing: no authorization was signed and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. | | `BCK.SUBSCRIPTION_TREASURY.0014` | 503 | internal | ❌ | A subscription treasury control is not configured (retired: no longer returned) | Retired. The Nevermined Subscription treasury no longer refuses a payment because an outflow or velocity control, or the retired-wallet list, is unconfigured, so this code is no longer returned. Only an older API deployment can still return it. | | `BCK.SUBSCRIPTION_TREASURY.0015` | 503 | integration | ✅ | The subscription treasury wallet is unavailable | The treasury wallet could not be loaded from its custody provider, or (on Tempo) its signing key could not be resolved. The treasury refused BEFORE signing: no authorization was signed and no money moved; the Router rolls the call back, so none of the subscription’s credits were used. Retry later. | ## `BCK.TRANSCODING` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.TRANSCODING.0001` | 404 | integration | — | UGC not found | Verify the UGC asset id. The asset may have been deleted, or transcoding has not finished yet for newly uploaded media. | | `BCK.TRANSCODING.0002` | 404 | business | ❌ | Transcoded asset not found for the given UGC id | Verify the UGC id in params. The queue row may have been pruned, or the upload never reached the transcoder. | | `BCK.TRANSCODING.0003` | 500 | integration | ❌ | Transcoding failed for UGC asset | Inspect the underlying error in logs. The transcoder marked this asset Errored — usually a codec/format issue or storage failure. Re-upload after fixing the source. | | `BCK.TRANSCODING.0004` | 503 | integration | ✅ | Transcoding is still in progress for UGC asset | The transcoder has not finished encoding this asset. Retry after a short backoff; the worker typically completes within seconds for small assets. | ## `BCK.TXS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.TXS.0001` | 404 | integration | — | Error searching asset transactions by id | Verify the asset/transaction id. Empty transaction lookups return 404 by design. | | `BCK.TXS.0002` | 404 | integration | — | Error searching asset consumer transactions | Verify the consumer address and asset id. Empty result sets return 404 by design. | | `BCK.TXS.0003` | 404 | integration | — | Error searching distintc asset transactions | Verify the asset id. Empty distinct-asset transaction lookups return 404. | | `BCK.TXS.0004` | 404 | integration | — | Error searching plan transactions | Verify the planId. Empty plan-transaction lookups return 404 by design. | | `BCK.TXS.0005` | 404 | integration | — | Error searching asset transactions grouped by owner | Verify the owner address. Empty owner-grouped transaction lookups return 404. | | `BCK.TXS.0006` | 404 | integration | — | Error gathering DDO Info | Verify the DID is well-formed and registered. DDO resolution failures bubble up as 404 here. | | `BCK.TXS.0007` | 404 | integration | — | Error getting active users for owner | Verify the owner address. Empty active-users lookups return 404 by design. | | `BCK.TXS.0008` | 404 | integration | — | Error getting total API calls for owner | Verify the owner address. Empty total-calls lookups return 404 by design. | | `BCK.TXS.0009` | 404 | integration | — | Error getting total revenue for owner | Verify the owner address. Empty total-revenue lookups return 404 by design. | | `BCK.TXS.0010` | 404 | integration | — | Error getting dashboard metrics for owner | Verify the owner address. Empty dashboard-metrics lookups return 404 by design. | | `BCK.TXS.0011` | 500 | integration | — | Error getting revenue time-series for owner | Transient server-side error building the revenue time-series; safe to retry. Inputs are validated upstream (invalid dates return 400, granularity is normalized), so this is not a bad-request issue. | | `BCK.TXS.0012` | 500 | integration | — | Error getting requests time-series for owner | Transient server-side error building the requests time-series; safe to retry. Inputs are validated upstream (invalid dates return 400, granularity is normalized), so this is not a bad-request issue. | | `BCK.TXS.0013` | 400 | business | — | startDate/endDate must be valid ISO-8601 timestamps | Pass startDate/endDate as ISO-8601 strings, e.g. 2024-01-01T00:00:00.000Z. | | `BCK.TXS.0014` | 500 | internal | ❌ | Owner-scoped read refused: the owner set is empty | Not caller-fixable and not retryable. The server derived an empty owner set for a tenant-scoped read and refused it rather than returning unscoped results; the correlation id in this response identifies the request in the logs. | | `BCK.TXS.0015` | 500 | integration | ✅ | Error getting the last plan created by owner | Usually a transient DB-layer fault on the last-created-plan lookup; retrying once is safe. If it persists, the owner address reaching the query is malformed, which a retry will not fix — quote the correlation id in this response. | | `BCK.TXS.0016` | 500 | internal | ❌ | Transaction search refused: the query has no scoping predicate | Not caller-fixable and not retryable. The server built a transaction search with no owner, consumer, plan or transaction id to scope it, and refused it rather than reading across every tenant; the correlation id in this response identifies the request in the logs. | ## `BCK.USER_PROFILE` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.USER_PROFILE.0001` | 500 | internal | ❌ | User profile not found | A profile lookup returned null where a row was expected. Two known throw sites: DTO mappers asserting a non-null entity, and the org-tier bootstrap requiring the node-account system user. Inspect the throw-site `details` for the specific context. Legacy callers depended on this surfacing as 500; the canonical "user profile not found for caller-supplied identifier" lookup-not-found semantics live in `BCK.USER_PROFILE.0002` (404). | | `BCK.USER_PROFILE.0002` | 404 | business | ❌ | User profile not found | Verify the user identifier. The profile may have been disabled or never created. | | `BCK.USER_PROFILE.0003` | 400 | validation | ❌ | No wallet linked to the authenticated Privy account | Complete wallet linkage in the Privy flow before calling endpoints that require a smart-account address (dashboards, profile reads, etc.). | | `BCK.USER_PROFILE.0004` | 400 | business | ❌ | User profile already exists for this address | Use the PATCH endpoint to update an existing profile, or call POST with a different address. Profiles are unique per wallet. | | `BCK.USER_PROFILE.0005` | 403 | business | ❌ | The Privy wallet does not belong to this account | A profile can only reference its own Privy wallet — the one whose address, or whose derived smart account, is the profile address. Sign in with the wallet that owns this account; if this account was never given a different wallet id, contact support. | | `BCK.USER_PROFILE.0006` | 503 | integration | ✅ | Could not verify the Privy wallet for this account | Privy or the chain RPC did not answer while checking that the wallet belongs to this account, so nothing was signed or saved. Retry after a short backoff. The upstream cause is in the server logs for this error id. | | `BCK.USER_PROFILE.0007` | 500 | internal | ❌ | The Privy wallet check failed | The check that the wallet belongs to this account failed for a reason retrying will not fix (for example a Privy credential or configuration fault), so nothing was signed or saved. Report the error id; the cause is in the server logs. | ## `BCK.VERSION` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.VERSION.0001` | 400 | validation | ❌ | Unknown or unsupported API version | Send Nevermined-Version as MAJOR.MINOR (e.g. "1.0") within the supported range. GET /api/v1/meta/versions lists the supported range; see [https://nevermined.ai/docs/development-guide/api-versioning](https://nevermined.ai/docs/development-guide/api-versioning). | | `BCK.VERSION.0002` | 500 | internal | ❌ | API version transformation failed | A server-side version gate failed to reshape the request/response for your pinned API version. This is a backend bug — quote the correlation id when reporting it. | ## `BCK.VGS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.VGS.0001` | 503 | integration | ❌ | Unified card enrolment is not available (VGS vault not configured) | #2057 item 2: VgsVaultAvailableGuard rejected the unified VGS-Collect enrol/enroll-session call because the shared VGS vault (VGS\_\* / vgsAgentic.\* env) is unconfigured. Same underlying state as BCK.VISA.0001, but VGS-namespaced so a unified-card 503 is not mis-attributed to a Visa-agentic outage. Configure the VGS vault credentials before enabling the unified card rail. | | `BCK.VGS.0002` | 502 | integration | ❌ | VGS network-token provision-on-create failed | #2151: provisioning a portable network token for a freshly enrolled unified VGS card failed. This is the internal per-rail LOG marker emitted immediately BEFORE the enrolment is rolled back — a `vgs` card is worthless without an active network token, so the failure is NO LONGER swallowed (superseded the best-effort behaviour). The client sees BCK.VGS.0004 (permanent/config), BCK.VGS.0005 (transient), BCK.VGS.0006 (card not tokenizable) or BCK.VGS.0007 (card not in vault). The unified-rail twin of BCK.VISA.0021 (Visa-agentic rail): split out so an alert can pinpoint which rail dropped a token. Inspect cardId in the log context. | | `BCK.VGS.0003` | 401 | auth | ❌ | Invalid or expired card enrolment session | #2057 item 1: the enrol-session token replayed on POST /api/v1/delegation/enroll was missing, malformed, expired, wrong-audience, or minted for a different user. The browser must first GET /api/v1/delegation/enroll-session (authenticated) and forward the returned enrollSessionToken. Message is intentionally generic — the specific jwt.verify reason is a forgery oracle and stays in the server logs only. | | `BCK.VGS.0004` | 500 | integration | ❌ | Card not enrolled — a network token could not be provisioned | The card could not be enrolled and nothing was saved. Please try again later, or contact support if the problem persists. | | `BCK.VGS.0005` | 502 | integration | ✅ | Card not enrolled — network-token provisioning is temporarily unavailable | The card could not be enrolled due to a temporary issue. Please try again shortly. | | `BCK.VGS.0006` | 422 | validation | ❌ | Card not enrolled — the card network declined to tokenize this card | This card cannot be used for network-token payments and nothing was saved. Please try a different card. | | `BCK.VGS.0007` | 400 | validation | ❌ | Card not enrolled — the card was not found in the card vault | The card details could not be found and nothing was saved. Please re-enter the card and try again. | | `BCK.VGS.0008` | 502 | integration | ✅ | Card not enrolled — card verification is temporarily unavailable | The card could not be verified due to a temporary issue and nothing was saved. Please try again shortly. | | `BCK.VGS.0009` | 422 | validation | ❌ | Card not enrolled — the card issuer did not authenticate the cardholder | Your bank could not verify this card and nothing was saved. Please try again, use a different card, or contact your bank. | | `BCK.VGS.0010` | 400 | validation | ❌ | Card not enrolled — card verification was not completed | The card verification step was not completed and nothing was saved. Please add the card again and complete the verification with your bank. | ## `BCK.VISA` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.VISA.0001` | 503 | integration | — | Visa payment provider is not configured | VGS\_\* env vars are unset. Configure the VGS vault credentials before enabling Visa Agentic Token features. | | `BCK.VISA.0002` | 502 | integration | — | Visa card enrollment failed | Inspect VGS dashboard logs for the enrollment id in params. Common causes: invalid card details, sanctions/AVS reject, or vault routing. | | `BCK.VISA.0003` | 502 | integration | — | Visa mandate creation failed | Inspect VGS dashboard logs for the mandate id in params. Mandate creation may fail when consumerPrompt/assuranceData are missing or the card is non-eligible. | | `BCK.VISA.0004` | 502 | integration | — | VGS cryptogram issuance failed | Inspect VGS dashboard logs for the cryptogram request id in params. Common causes: vault session expired, card revoked, or merchant data mismatch. | | `BCK.VISA.0005` | 400 | integration | — | Invalid VGS webhook signature | Verify the `VGS_WEBHOOK_SECRET` in env matches the secret configured in VGS dashboard. Replayed or forged webhooks land here. | | `BCK.VISA.0006` | 502 | integration | — | VGS OAuth2 client\_credentials request failed | Inspect VGS dashboard logs. The OAuth2 client\_credentials call failed — usually expired credentials or the wrong `VGS_BASE_URL`. | | `BCK.VISA.0007` | 502 | integration | — | Stripe settlement of Visa virtual card failed | Inspect Stripe dashboard for the PaymentIntent id in params. The Stripe settlement of the VGS-issued virtual card failed at the Stripe side. | | `BCK.VISA.0008` | 400 | integration | — | User has no email on file (required for Visa enrolment) | Capture or update the user email before retrying Visa enrolment. Visa requires a deliverable email for the cardholder. | | `BCK.VISA.0009` | 422 | integration | — | Visa mandate (intent) not provisioned for this delegation | Re-issue the delegation via the Visa flow so a mandate (Visa intent) is provisioned. Without it the card cannot be used for spending. | | `BCK.VISA.0010` | 404 | integration | — | VGS webhook references unknown card | Verify the VGS payload references a card our DB has registered. Stale or cross-environment webhooks land here. | | `BCK.VISA.0011` | 400 | integration | — | VGS webhook payload malformed | Inspect the underlying VGS payload structure. Required fields are missing or have the wrong shape — usually a VGS API version mismatch. | | `BCK.VISA.0012` | 400 | integration | — | VGS webhook revoke event missing card identifier | The revoke webhook is missing the card identifier we need to flip our DB state. Inspect VGS to confirm the event payload and replay manually if needed. | | `BCK.VISA.0013` | 500 | integration | — | Unable to process VGS webhook | Inspect the underlying error and webhook event id in params. The handler crashed mid-processing; VGS will retry the webhook. | | `BCK.VISA.0014` | 400 | business | — | Visa delegation creation requires consumerPrompt and assuranceData | Provide both consumerPrompt and assuranceData when creating a Visa delegation. These are required by the Visa Trusted Agent Protocol. | | `BCK.VISA.0015` | 400 | business | — | Visa delegation requires planId (retired: no longer returned) | Retired. planId is optional for Visa delegations and this code is no longer returned; a Visa mandate is not bound to a plan seller. Only an older API deployment can still return it. | | `BCK.VISA.0016` | 400 | business | — | Plan seller has not completed Stripe Connect onboarding required for Visa payments | The seller of the plan being paid has no name, website or country on its Stripe Connect account, so a Visa payment cannot name the merchant. Nothing was charged. Ask the seller to finish Stripe Connect onboarding. | | `BCK.VISA.0017` | 502 | integration | — | Stripe Connect account lookup failed while resolving Visa merchant context | Inspect Stripe dashboard logs for the connected account id in params. Connect account lookup failed transiently — retry; if it persists, check the seller’s Connect status. | | `BCK.VISA.0018` | 409 | business | — | This card is already enrolled to a different account | Deprecated: no longer thrown. Visa enrolment no longer rejects a card already on file under another account (RFC-1 relaxed uniqueness, epic #1958). | | `BCK.VISA.0019` | 500 | internal | ❌ | Visa provider misconfigured for this environment | The Visa provider is otherwise wired but VGS\_AGENTIC\_BROWSER\_CLIENT\_ID/SECRET are missing. The browser-token endpoint would silently fall back to the privileged backend service account in this state. Provision the narrower Client-Side Service Account or unset the Visa env vars to disable the provider. See VIS-011 in security audit 2026-05-27. | | `BCK.VISA.0020` | 502 | integration | ❌ | Network-token credential could not be obtained from the card vault | The card vault could not supply the network-token credential for this charge. No charge was made, so the spending reservation is rolled back. Use a different payment method for this purchase. | | `BCK.VISA.0021` | 502 | integration | ❌ | VGS network-token provision-on-create failed (best-effort) | Provisioning a portable network token for a freshly enrolled VGS-canonical card failed (epic #1958, T2.A / #1976). This is BEST-EFFORT and never surfaced to the client: enrolment completes, the credential persists with networkToken NULL, and the charge path falls back to the legacy/instrument rail. Used as a stable code on the swallowed log line so the gap is alertable and backfill-able. Inspect cardId/credentialId in the log context. | | `BCK.VISA.0022` | 402 | business | ❌ | Visa mandate declined the transaction | Visa refused to issue a cryptogram for this charge (mandate status DECLINED): the amount exceeds what the delegation mandate still allows. The decline threshold is enforced by Visa cumulatively over every cryptogram minted on the mandate, including ones whose charge later failed, so it can run out before the delegation's own remaining budget does. No charge was attempted. Create a new delegation to continue. | | `BCK.VISA.0023` | 402 | business | ❌ | The card issuer declined this Visa network-token charge | The issuer refused the authorization when the charge reached the card network. No authorization exists and nothing was captured, so the spend reservation has been released. Inspect `params.declineCode` for the network’s reason, then retry with a different card or a smaller amount. Distinct from the mandate decline (Visa refused to mint a cryptogram, before any charge was attempted) and from an ambiguous failure, where a charge may actually have landed. | | `BCK.VISA.0024` | 503 | integration | ❌ | Visa agentic card enrollment is not available in this environment | Nothing was saved and no card will succeed here until the service is enabled. Enrol the card with the standard credit/debit card option instead, or contact support. | | `BCK.VISA.0025` | 400 | business | ❌ | Visa delegation duration exceeds the maximum Visa allows | Visa mandates can last at most 7 days (params.maxDurationSecs). Choose a shorter duration and create a new delegation when it expires. | | `BCK.VISA.0026` | 422 | business | ❌ | This card's issuing country is not supported for Visa agentic payments. Use another Visa card, or add this one with the standard credit/debit card option. | Nothing was saved. Retrying with the same card will not succeed. Enrol a Visa card issued in a supported country, or use the standard credit/debit card enrolment for this one. | | `BCK.VISA.0027` | 422 | business | ✅ | Visa declined this card for agentic payments right now. Try again later, or use another Visa card. | Nothing was saved. Visa Token Service refused to tokenize this card; it may accept it later. Retry after a while, enrol another Visa card, or use the standard credit/debit card enrolment. | ## `BCK.WALLET` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.WALLET.0001` | 400 | validation | ❌ | Unsupported network pair for a balance transfer | The requested source/destination network pair is not one this deployment can move funds between. Supported pairs are Base \<-> Tempo on mainnet and Base Sepolia \<-> Tempo testnet on the sandbox, in either direction; the two networks must differ and must belong to the same environment tier. Read the available networks from GET /health. | | `BCK.WALLET.0002` | 400 | validation | ❌ | Invalid transfer amount | The amount must be a positive decimal string in standard units (e.g. "1.5" for 1.5 USDC), with at most the asset’s decimal places. Atomic units, scientific notation, negatives and zero are rejected. | | `BCK.WALLET.0003` | 409 | business | ❌ | The account has no wallet that can move funds across networks | The cross-chain transfer runs on the caller’s Privy embedded wallet, and the verified identity token carried no Privy wallet id. An externally-connected wallet cannot use this endpoint — it moves funds Nevermined custodies the signer for, never a wallet the user holds keys to elsewhere. | | `BCK.WALLET.0004` | 400 | validation | ❌ | Insufficient balance for this transfer | The wallet holds less of the source asset on the source network than the requested amount (fees are taken out of the amount, so the full balance is transferable). Refresh the balance and retry with a smaller amount. Distinct from BCK.WALLET.0005 because nothing is wrong with the route or the provider — retrying the SAME amount cannot succeed. | | `BCK.WALLET.0005` | 502 | integration | ✅ | The transfer provider could not price or route this transfer | Privy (or the bridge behind it) rejected or failed the quote/transfer for a reason that is not the caller’s balance or input — no liquidity on the route, a provider outage, or a rejected authorization. Nothing was debited when a QUOTE fails; a failed TRANSFER may still have been submitted, so re-read the wallet balance before retrying rather than assuming it did not run. | | `BCK.WALLET.0006` | 502 | integration | ❌ | The wallet provider request failed | The wallet provider failed a transfer quote, transfer or status read for a reason Nevermined could not classify (not a balance shortfall, which is BCK.WALLET.0004, nor a policy refusal, which is BCK.WALLET.0005). The provider's reply is in the server log for this error id and is never returned. A failed TRANSFER may still have been submitted, so re-read the wallet balance before retrying. | ## `BCK.WELCOME_CREDITS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.WELCOME_CREDITS.0001` | 404 | validation | ❌ | Welcome credit grant not found | No welcome\_credit\_grants row has that id. A grant id is logged on the `welcome credits: GRANTED` line (`grant=`), next to the user it was made for; GET /api/v1/ops/credits/welcome reports totals only. | | `BCK.WELCOME_CREDITS.0002` | 500 | internal | ❌ | Welcome credits are switched on but not configured | NVM\_WELCOME\_CREDITS\_ENABLED is true and the setting named in params.setting is missing or invalid (params.reason), so the API refuses to boot rather than grant without it. The settings: WELCOME\_CREDITS\_SIGNUP\_AFTER (an ISO-8601 instant with a time zone), WELCOME\_CREDITS\_AMOUNT, WELCOME\_CREDITS\_TTL\_DAYS, WELCOME\_CREDITS\_DAILY\_MAX\_GRANTS and WELCOME\_CREDITS\_TOTAL\_BUDGET\_CREDITS (positive integers; the budget at least one grant). WELCOME\_CREDITS\_MAX\_PER\_IP\_PER\_DAY is optional (unset means no IP cap) but must be a positive integer when set. Fix the setting, or switch welcome credits off. | | `BCK.WELCOME_CREDITS.0003` | 500 | internal | ❌ | No credits plan to report welcome credits on | subscription\_catalog names no Nevermined credits plan, or more than one (params.planCount), so the welcome credits ledger cannot be read. Bootstrap the subscription catalog (one credits plan per deployment) and retry. | | `BCK.WELCOME_CREDITS.0004` | 503 | internal | ✅ | Your welcome credits could not be read | Reading your welcome credits failed on our side (see the server log). Reading charges nothing and changes nothing; retry in a moment. | ## `BCK.WIDGET` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.WIDGET.0001` | 500 | business | — | Unable to store widget config | Inspect the underlying error in logs. Widget config persistence failed — usually a DB-layer or storage-layer error. | | `BCK.WIDGET.0002` | 404 | business | — | Unable to get widget config from id | Verify the widget id. The widget may have been deleted or never created. | | `BCK.WIDGET.0003` | 403 | business | ❌ | The user doesnt own this widget | Only the wallet that created the widget can edit or delete its config. Re-authenticating as the same caller will not help. | | `BCK.WIDGET.0004` | 500 | business | — | Error updating widget config | Inspect the underlying error in logs. Widget update failed — usually a DB-layer error or validation reject on the new config. | | `BCK.WIDGET.0005` | 500 | business | — | Error deleting widget config | Inspect the underlying error in logs. Widget deletion failed — usually a DB-layer error. | ## `BCK.WIDGET_KEYS` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.WIDGET_KEYS.0001` | 500 | internal | ❌ | Widget key generation failed | Inspect the underlying error in logs. Widget-key minting failed — usually a DB-write error. | | `BCK.WIDGET_KEYS.0002` | 404 | auth | — | Widget key not found | Verify the widget-key id and that it belongs to the caller organisation. Revoked keys also surface as not-found. | ## `BCK.WIDGET_SESSION` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.WIDGET_SESSION.0001` | 401 | auth | — | Invalid widget credentials | F-055: covers both "org has no active widget key" and "secret rejected". The integrator backend must send the active `wk_...` secret as `rawSecret` in `POST /widgets/session`; if the org never generated a key, create one in the admin UI first. A single error code is returned so an attacker probing the public endpoint cannot distinguish the two cases. | | `BCK.WIDGET_SESSION.0003` | 500 | auth | — | Widget JWT secret not configured | Configure `WIDGET_JWT_SECRET` in the deployment env. The widget-session JWT signer requires this secret to be set. | | `BCK.WIDGET_SESSION.0004` | 500 | auth | — | Error creating widget session user | Inspect the underlying error in logs. Widget guest-user creation failed — usually a DB-layer error. | | `BCK.WIDGET_SESSION.0005` | 401 | auth | — | Invalid or expired widget session token | Re-issue the session token via the widget refresh endpoint. Session tokens are short-lived; expired tokens land here. | | `BCK.WIDGET_SESSION.0008` | 401 | auth | — | Widget session token is missing required wallet claim | Reissue the session token after capturing the user wallet. Wallet-bound session features require the wallet claim. | | `BCK.WIDGET_SESSION.0009` | 401 | auth | — | Widget session token is missing required apiKeyHash claim | Reissue the session token with the apiKeyHash claim populated. The widget runtime expects an apiKeyHash to attribute usage. | | `BCK.WIDGET_SESSION.0010` | 401 | auth | — | Widget session token is missing required widgetKeyId claim | Reissue the session token with the widgetKeyId claim populated. The widget runtime expects a widgetKeyId for revocation checks. | | `BCK.WIDGET_SESSION.0011` | 401 | auth | — | Widget key has been revoked or no longer exists | Generate a fresh widget key in the org admin UI. Revoked keys cannot resume existing sessions; the embed must be updated. | | `BCK.WIDGET_SESSION.0012` | 403 | auth | — | Origin not allowed for this widget key | Add the requesting origin to the widget key’s allowed-origins list, or embed the widget from an approved origin. | | `BCK.WIDGET_SESSION.0013` | 400 | auth | — | Widget session request is missing the required email field | The integrator backend must forward the end-user email in the `email` field of POST /widgets/session. Email is the canonical Nevermined identity for widget users. | | `BCK.WIDGET_SESSION.0018` | 403 | auth | — | Card setup is only available to organization members | The authenticated user has no active organization membership — `POST /widgets/session/self` is the org-scoped (members-only) widget path. To enroll a card or create a delegation as a buyer/agent, use the open embedded flow instead: `POST /api/v1/embed/session` (then open the embed app card-setup page with the returned sessionToken). | | `BCK.WIDGET_SESSION.0019` | 403 | auth | — | orgId is not one of the caller’s organization memberships | Pass an `orgId` the authenticated user is a member of — list your memberships via `/organizations/my-memberships` or the org switcher in the dashboard. To enroll a card or create a delegation as a buyer/agent (no org), use the open embedded flow: `POST /api/v1/embed/session` (then open the embed app card-setup page with the returned sessionToken). | | `BCK.WIDGET_SESSION.0020` | 403 | auth | — | Agent or plan does not belong to the widget session’s organization | The embed checkout can only purchase agents/plans owned by the organization the widget session was minted for. Verify the `agentId`/`planId` in the embed URL belongs to that organization. | ## `BCK.X402` | Code | HTTP | Category | Retryable | Message | Hint | | - | - | - | - | - | - | | `BCK.X402.0001` | 404 | business | — | Agent not found | Verify the agentId in the x402 facilitator-resource URL. Agents that are deactivated or in a different environment surface as not-found here. | | `BCK.X402.0002` | 404 | business | — | Plan not found | Verify the planId in the x402 facilitator-resource URL. Plans that are deactivated or in a different environment surface as not-found here. | | `BCK.X402.0003` | 400 | business | — | The plan is not associated to the agent | Re-link the plan to the agent before retrying, or use a different plan that is already linked. x402 requires an explicit (agent, plan) edge. | | `BCK.X402.0004` | 500 | business | — | Error generating X402 access token | Inspect the underlying error in logs. x402 access-token minting failed — usually a JWT signing key issue or an upstream chain RPC error. | | `BCK.X402.0005` | 402 | business | — | Invalid access token | Mint a fresh access token via POST /api/v1/x402/permissions. Expired or tampered tokens land here. A token minted for MPP (POST /api/v1/mpp/permissions) verifies ONLY on the /api/v1/mpp/\* routes: the two protocols sign under different EIP-712 domains and are deliberately not interchangeable. | | `BCK.X402.0006` | 500 | business | — | Error verifying permissions | Inspect the underlying error in logs. The verifyPermissions call failed — usually a transient DB error; retry once. Persistent failures may indicate a stale plan-permissions cache. | | `BCK.X402.0007` | 500 | business | — | Failed to order Pay-as-you-go plan | Inspect the underlying error in logs. Pay-as-you-go plan ordering failed — usually a delegation/credit issue on the buyer side or an upstream chain RPC error. | | `BCK.X402.0008` | 500 | business | — | Failed to order crypto plan | Inspect the underlying error in logs. Crypto plan ordering failed — usually a buyer balance/approval issue or a chain RPC revert. | | `BCK.X402.0009` | 500 | business | — | Failed to redeem credits | Inspect the underlying error in logs. Credit redemption failed mid-way — the buyer may have been charged but not credited; check the activity feed and reconcile manually if needed. | | `BCK.X402.0010` | 400 | business | — | Invalid x402 access token | Mint a fresh access token via POST /api/v1/x402/permissions. The supplied token is malformed or signed by an unknown key. | | `BCK.X402.0011` | 404 | business | — | User profile not found | Verify the buyer wallet has a user-profile row. New wallets must complete the signup flow before purchasing via x402. | | `BCK.X402.0012` | 400 | business | — | resource.url is required when agentId is provided | Pass resource.url alongside agentId in the x402 settlement body. The URL is required for routing the settlement to the right merchant. | | `BCK.X402.0013` | 400 | business | — | Accepted payment method does not match requirements | Pass an accepted payment method that matches the plan’s configured currency/scheme. The combinations are documented per-plan in the plan metadata. | | `BCK.X402.0014` | 400 | business | — | Delegation restricted to a different plan | Reuse the delegation only with the planId it was originally bound to, or create a fresh delegation for the new plan. A delegation created with a planId is scoped to that plan, whatever the card provider. | | `BCK.X402.0015` | 404 | business | ❌ | Permission not found | The permission record either has been revoked or never existed for this combination of (subscriber, plan, agent). | | `BCK.X402.0016` | 400 | business | ❌ | Permission is already revoked | The permission was already revoked. No further action required. | | `BCK.X402.0017` | 500 | internal | ❌ | Failed to issue credits after card charge | The card was charged successfully but the DB-side mint of credits failed. The charge is auto-refunded when the provider supports it; otherwise a `failed_post_charge_*` delegationTransactions row is left for manual reconciliation. | | `BCK.X402.0018` | 500 | internal | ❌ | Invalid amountCents derived from order | A defensive arithmetic check in the erc4337 settlement path produced a non-finite or negative cents amount. Inspect the order amount and currency in params; this should never happen for legitimate orders. | | `BCK.X402.0019` | 402 | business | ❌ | Delegation not found | No delegation with this id is owned by the caller — it either never existed or belongs to someone else (the two are intentionally indistinguishable). Verify the delegationId, or create a fresh delegation. Revoked/expired/exhausted delegations report BCK.X402.0020/0021/0022 instead. | | `BCK.X402.0020` | 402 | business | ❌ | Delegation is revoked | This delegation has been revoked and can no longer be used. Create a new card delegation to continue. | | `BCK.X402.0021` | 402 | business | ❌ | Delegation has expired | The delegation passed its expiry. Mint a new one (omit `delegationId` and resubmit with the payment method plus `spendingLimitCents` and `durationSecs`). | | `BCK.X402.0022` | 402 | business | ❌ | Delegation budget exhausted | The delegation has reached its spending limit or maximum transaction count. Create a new delegation with a higher `spendingLimitCents` / `maxTransactions` to keep transacting. | | `BCK.X402.0023` | 402 | business | ❌ | Delegation budget insufficient for this order | The remaining delegation budget is smaller than the cost of this order. Use a smaller order, or create a new delegation with a higher `spendingLimitCents`. | | `BCK.X402.0024` | 402 | business | ❌ | No active permission found for the delegation | The delegation has no active permission backing it. Re-create the delegation so its permission and session keys are provisioned. | | `BCK.X402.0025` | 402 | business | ❌ | Permission has been revoked | The permission backing this token was revoked. Create a fresh delegation/permission and mint a new access token. | | `BCK.X402.0026` | 402 | business | ❌ | Permission has expired | The permission backing this token expired. Create a fresh delegation/permission and mint a new access token. | | `BCK.X402.0027` | 402 | business | ❌ | Payment method not found or unusable | No usable payment method was found for this request. Add or re-enable a payment method in the dashboard, then retry — optionally passing its identifier via `delegationConfig.providerPaymentMethodId` or `delegationConfig.cardId`. | | `BCK.X402.0028` | 402 | business | ❌ | Payment method is revoked | The payment method has been revoked. Add or re-enable a payment method in the dashboard and retry with its identifier. | | `BCK.X402.0029` | 402 | business | ❌ | API key not authorized for this delegation or payment method | The API key used is not in the allow-list for this delegation / payment method. Use an authorized API key, or update the payment method allowedApiKeyIds to include it. | | `BCK.X402.0030` | 402 | business | ❌ | Required token-generation input is missing or incomplete | A required input for issuing the access token is missing. Provide `accepted.planId`, and a complete `delegationConfig`: reuse with `{ delegationId }`, or create with `{ providerPaymentMethodId \| cardId, spendingLimitCents, durationSecs }` (optionally `currency`). The per-failure `details` names the specific missing field. | | `BCK.X402.0034` | 402 | business | ❌ | Unsupported scheme or currency | The requested payment scheme or currency is not supported. Check the plan configured scheme/currency (e.g. Visa delegations support only usd / eur) and resubmit with a supported combination. | | `BCK.X402.0035` | 402 | business | ❌ | No session keys found for delegation | The delegation is owned by the caller and usable, but its linked erc4337 permission is missing session keys (burnSessionKey / orderSessionKey). This is a data-integrity issue — the delegation was likely created without completing session-key provisioning. Create a fresh crypto delegation; if it recurs, report the delegationId for investigation. | | `BCK.X402.0036` | 402 | business | ❌ | Delegation not usable (unknown lifecycle state) | The delegation is in a lifecycle state the server does not recognise as usable. Create a fresh delegation to continue; if this persists, report the delegationId for investigation. | | `BCK.X402.0037` | 403 | business | ❌ | SetupIntent does not belong to the authenticated user (retired: no longer returned) | Retired. It was returned by POST /delegation/finalize-enrollment, which is removed. Only an older API deployment can still return it. | | `BCK.X402.0038` | 409 | business | ❌ | SetupIntent is not in the expected state (retired: no longer returned) | Retired. It was returned by POST /delegation/finalize-enrollment, which is removed. Only an older API deployment can still return it. | | `BCK.X402.0039` | 422 | business | ❌ | SetupIntent has no associated payment method (retired: no longer returned) | Retired. It was returned by POST /delegation/finalize-enrollment, which is removed. Only an older API deployment can still return it. | | `BCK.X402.0040` | 404 | business | ❌ | API Key not found for this user | One of the supplied `allowedApiKeyIds` does not belong to this user (the offending skId is in `params`). Remove or correct it and retry. | | `BCK.X402.0041` | 409 | business | ❌ | API Key is not active | One of the supplied `allowedApiKeyIds` is revoked/inactive (the offending skId is in `params`). Use an active key or re-enable it, then retry. | | `BCK.X402.0045` | 501 | internal | ❌ | Network-token charging is not supported by this payment provider | This provider cannot yet charge from a network token + cryptogram. Today only the Visa rail does. Stripe gains a native network-token field in #1979 (T2.D) and Braintree gains BYOT in #1978 (T2.C); until then the router must not dispatch a network-token charge to these providers. | | `BCK.X402.0046` | 500 | internal | ❌ | Charge router received no candidate provider routes | Epic #1958 T1.C: the charge-time provider router (CardPaymentProviderFactory.chargeWithFallback) was called with an empty route list. The settle handler always supplies at least the legacy delegations.provider route, so an empty list is a server-side wiring regression — never a client input error. It is also raised if the route loop ever ends without returning a charge or rethrowing the error of a route, a control-flow regression of the same kind. Report the correlationId for investigation. | | `BCK.X402.0047` | 500 | internal | ❌ | No card payment provider registered for the requested rail | Epic #1958 T1.C: CardPaymentProviderFactory.getProvider was asked for a card rail it has no provider instance for. CardProviderName aliases the growable CardSettlementProvider, so a newly-added PSP must be wired into the factory switch in the same change — an unhandled rail is a server-side wiring regression, never a client input error. Report the correlationId for investigation. | | `BCK.X402.0048` | 502 | integration | ❌ | Network-token charge failed ambiguously (may have charged) — not retried or rolled back | A card charge through the PSP failed with an AMBIGUOUS error (timeout / 5xx / network / idempotency-key reuse) — the charge may actually have gone through. To avoid a double charge the spending reservation is deliberately LEFT IN PLACE (no rollback) and no other route is attempted. Reconcile against the PSP before any manual retry; the providerTransactionId in delegation\_transactions is the breadcrumb. | | `BCK.X402.0049` | 402 | business | ❌ | Network-token charge was declined by the payment provider | The payment provider definitively declined the charge (e.g. card\_declined / insufficient\_funds). No charge was captured, so the spending reservation is rolled back. Check the funding card or use a different payment method. | | `BCK.X402.0050` | 400 | validation | ❌ | Delegation currency has no settlement token on the plan network | An on-chain (erc4337) delegation must approve a real ERC-20 for its currency on the plan’s settlement network. The requested currency has no token configured on that network — minting the session key would produce a no-op approve that can never charge, so it is rejected. Every served network carries both USDC and EURC today (Tempo gained EURC with the bridged EURC.e, #2631), so in practice this fires on a network added without a settlement token. Pick a currency supported on the plan’s network (#1929). | | `BCK.X402.0051` | 503 | integration | ✅ | Chain RPC dependency temporarily unavailable during x402 verification | A transient failure of the on-chain RPC provider / bundler (5xx or unreachable) prevented an x402 verify/settle permission check from completing. Retry after a short backoff. If it persists, the RPC endpoint or its credentials may be misconfigured. The real upstream cause is captured server-side in the logs for this error id. | | `BCK.X402.0052` | 503 | integration | ✅ | EIP-7702 delegation could not be installed on the plan network | Installing the account’s Kernel v3.3 delegation designator on the plan’s network failed (bundler/paymaster/RPC), or a recent attempt is in its fail-closed backoff window. This is a transient infrastructure fault, not a client error — retry the request. | | `BCK.X402.0053` | 404 | business | ❌ | Privy wallet no longer exists | The account’s embedded Privy wallet has been deleted, so its smart account can no longer be reconstructed. Privy states this is unrecoverable — neither Nevermined nor Privy can re-link an authentication method on the user’s behalf. The user profile survives but is no longer spendable; provision a new account. Distinct from BCK.X402.0011 ("user profile not found"), which means the profile itself is missing. | | `BCK.X402.0054` | 402 | business | ❌ | account\_access credential may only spend via the card-delegation scheme | This access token was minted for account-wide card spending, so it can only pay through the card-delegation scheme against its own pinned card delegation — not the crypto (nvm:erc4337) scheme, nor an inline-created or foreign delegation. Retry with the card-delegation scheme. #2568 §6.3. | | `BCK.X402.0055` | 500 | internal | ❌ | Internal error: account\_access binding has no delegation to spend against | A server-side data-integrity condition — an account\_access binding always carries a card delegation (funding is required at authorize time). A null here should be unreachable; inspect the API logs. #2578. | | `BCK.X402.0056` | 500 | internal | ❌ | EIP-7702 authorization was signed by a different account than the requested authority | The account recovered from the EIP-7702 authorization signature is not the authority whose on-chain nonce it was signed against, so the delegation would be rejected by the bundler or silently ignored on-chain. The usual cause is a stale stored EOA — the user profile’s `privyWalletAddress`, or an org wallet’s `address` column — pointing at a different account than the Privy wallet id actually resolves to. Retrying does not help until the stored address is repaired. The API logs for this error id name both the requested authority and the recovered signer. See #2740. | | `BCK.X402.0057` | 403 | business | ❌ | This credential does not own the referenced payment method or delegation | A card delegation must be created and spent by the SAME identity that enrolled the card. The credential you presented is not the owner of this payment method / delegation, so it can neither create nor spend it. Enroll the card, create the delegation, and spend under one identity. This is NOT a card decline, and NOT an allow-list problem — allow-listing a key cannot grant ownership (see BCK.X402.0029 for the allow-list / key-pin case). | | `BCK.X402.0058` | 502 | integration | ❌ | Payment could not be processed: the seller payment account is unavailable or the request was rejected | The payment processor rejected the request before any charge was attempted — most commonly the seller's Stripe Connect destination is missing or unreachable (`No such destination`), but also a lost BYOT entitlement or a malformed request. No charge was captured (rollback-safe), so this is NOT a card decline and retrying the same card will not help. Inspect params.stripeCode / params.stripeParam and the logged cause; a stale seller Connect account is self-healed automatically and the seller must reconnect Stripe. | | `BCK.X402.0059` | 402 | business | ❌ | Access token has already been used | This is a single-use (v3) access token and it was already settled. Mint a new token for each paid request — `POST /api/v1/x402/permissions` returns a fresh one. If you did not choose a version: API keys are stamped with the API version current at the moment they are CREATED, and keys created from 1.34 onward default to version 3, so a newly created key changes this behaviour on its own while your older keys keep working. Two ways back to the reusable token: re-pin the key to 1.33 or below (`PATCH /api/v1/api-keys` with the key hash and `apiVersion`, or the dashboard) — this needs no code change and works from any SDK; or send `tokenVersion: 2` on the mint, if your client exposes that field. This is NOT a signature or tampering failure (BCK.X402.0005) and NOT a payment decline. | | `BCK.X402.0060` | 403 | business | ❌ | This credential is not a party to the payment it is settling | verify/settle on the card rail require you to be a party to the transaction: the seller (the account that published the plan, or the organization that owns it), or the buyer the token was issued to. Presenting a valid API key for an account on neither side is refused — an API key is not a universal settle capability. Buyers do call settle for their own tokens, e.g. the plan top-up in the generated agent instructions. | | `BCK.X402.0061` | 500 | internal | ❌ | The order was rejected by the session key policy | The delegation session key was minted with a call policy that does not allow this order. Create a new delegation and retry; adding funds will not clear it. | | `BCK.X402.0062` | 403 | auth | ❌ | A commerce credential cannot generate x402 payment tokens | This credential comes from a `commerce` authorization, whose consented spend path is `POST /api/v1/router/commerce/route` — the Router derives the delegation from your grant and enforces the cap the user approved. Generating an x402 permission here would let you name a different delegation, or create a fresh one, and spend outside that cap, so it is refused. Use the commerce route instead; to mint x402 permissions, use a plain API key from the account owner. | # API error model Source: https://nevermined.ai/docs/development-guide/api-errors/overview Understand the structure, codes, and remediation hints returned by the Nevermined API when a request fails. Every error response from the Nevermined API follows a single, stable shape so your code can branch on `code`, surface a friendly message to the user, and link directly to the docs entry that explains the failure. > [!NOTE] > > Locked fields — `code`, `message`, and the HTTP status — are guaranteed for every error response. Additive fields (`hint`, `docsUrl`, `category`, `retryable`, `correlationId`) only appear when the catalogue or the throw site supplies them. Consumers that branch only on `code` and `message` ignore the rest transparently. ## Response shape ```jsonc theme={null} { // Locked — always present. SDKs read these. "code": "BCK.X402.0008", "message": "Failed to order crypto plan", // Additive — present when the catalogue or the throw site supplies them. "details": "Bundler returned execution-reverted", "hint": "Verify the wallet has sufficient balance and that the plan is active. Inspect params.planId and the bundler RPC logs around the request correlationId.", "docsUrl": "https://docs.nevermined.ai/docs/development-guide/api-errors/codes#bck-x402-0008", "category": "integration", "retryable": true, "correlationId": "a3f6b1c4-7d2e-4a9b-8e0c-12f4d8e6c5b9", "uuid": "e-550e8400-e29b-41d4-a716-446655440000", "date": "2026-05-09T12:34:56.789Z", // JSON-stringified contextual params from the throw site (parse with JSON.parse if needed). "params": "{\"planId\":\"43298432984329\"}" // Server stack — only emitted when NODE_ENV is "development" or "test". // "stackTrace": "..." } ``` ## Field reference > [card] code > > Stable identifier of the form `BCK..`. Branch on this in your error handlers — it never changes for a given failure mode. > [card] message > > Human-readable canonical reason. Safe to surface to end users; it never includes secrets. > [card] hint > > Actionable remediation. Tells you what to fix or where to look. Optional — present when the catalogue or throw site supplies one. > [card] docsUrl > > Permalink to the entry on this docs site. Surface as a "Learn more" link in your UI. > [card] category > > One of `validation`, `auth`, `business`, `integration`, `internal`. Useful for client-side fallback strategies without parsing the message. > [card] retryable > > `true` when the same call is expected to succeed after a backoff. Absent when the catalogue does not assert either way. > [card] correlationId > > Request-scoped id stamped by the global filter and echoed in the `x-correlation-id` response header. Quote this when reporting issues. > [card] params > > JSON-stringified contextual data from the throw site (IDs, state). Always a string in the wire format — parse with `JSON.parse` if you need structured access. Never includes credentials or PII. > [card] details > > Free-form technical reason supplied at the throw site (e.g. `"Bundler returned execution-reverted"`). Supplements — never replaces — the canonical `message`. Optional. > [card] uuid > > Server-generated exception id of the form `e-`. Distinct from `correlationId`; use it when correlating a specific failure event with server logs. Optional. > [card] date > > ISO-8601 timestamp the API stamped when the exception was constructed. Always present. > [card] stackTrace > > Server-side stack trace. Emitted **only** when `NODE_ENV` is `development` or `test` — never in `staging` or `production`. Do not depend on it from client code. ## Reading errors from the SDK Both first-party SDKs surface the API's `code` and `message` directly, so you can branch on the code in your application. > [tab] TypeScript > > ```typescript theme={null} > import { Payments, PaymentsError } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox', > }) > > try { > await payments.plans.orderPlan(planId) > } catch (err) { > if (err instanceof PaymentsError) { > // err.code === 'BCK.X402.0008' > // err.message === 'Failed to order crypto plan. ' > if (err.code === 'BCK.X402.0008') { > showRetryableError(err.message) > } else { > throw err > } > } > } > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments, PaymentOptions > from payments_py.common.payments_error import PaymentsError > > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_API_KEY"], > environment="sandbox", > ) > ) > > try: > payments.plans.order_plan(plan_id) > except PaymentsError as err: > if err.code == "BCK.X402.0008": > # err.args[0] / str(err) is "Failed to order crypto plan. " > show_retryable_error(str(err)) > else: > raise > ``` ## Correlation ids Every request gets a unique `correlationId`: * If you send `x-correlation-id` (or `x-request-id`) on the request, the API honours it. * Otherwise the API generates a fresh UUID. * Either way, the id is echoed back in the `x-correlation-id` response header **and** stamped into the JSON body of any error response. When you open a support ticket or file a bug, quote the `correlationId` — it lets us pull the matching server logs without you sharing the request payload. ## Categories at a glance > [card] validation > > Caller's request did not pass schema or shape validation. Fix the request and retry. **Not** retryable as-is. > [card] auth > > Caller is unauthenticated, the credentials are invalid, or the caller lacks the required role. Fix credentials or membership and retry. > [card] business > > Caller's request is well-formed and authenticated, but a business rule blocks it (e.g. user already a member, plan already deactivated, points cap exhausted). Adjust the request semantics. > [card] integration > > The API hit an upstream system that misbehaved (Stripe, Braintree, the blockchain RPC, the bundler). Often `retryable: true`. Backoff and retry. > [card] internal > > A bug or invariant violation on our side. Quote the `correlationId` in a support ticket — these need engineering attention. ## Full code catalogue The complete list of every code, its HTTP status, category, message, and remediation hint lives in the **API Errors → Codes** page under the **API** tab. > [card] [See every error code](/docs/development-guide/api-errors/codes) > > Browse all `BCK.*` codes — anchored by code so you can deep-link to a specific failure mode (`#bck-x402-0008`). > [!NOTE] > > A handful of catalogue entries return an HTTP 2xx status because they describe **informational no-op outcomes** rather than failures — for example `BCK.PROTOCOL.0018` ("agent already in the desired state") and `BCK.PROTOCOL.0019` ("plan already in the desired state") are emitted with `200 OK` when a toggle endpoint is called against state that already matches the request. The shape is identical to the error responses described above, so the same SDK handlers and `docsUrl` deep-links continue to work; consumers that branch on `code` can treat these as "already done, nothing to do". > [!TIP] > > This page is reachable from three places in the sidebar so you can find it from wherever you're working: > > * **API → API Errors** — the canonical home, alongside the endpoint reference. > * **Guides → API Errors** — for readers exploring concepts. > * **SDK → TypeScript SDK / Python SDK / CLI / OpenClaw Plugin** — at the bottom of each SDK group, since SDK consumers see these errors most often. # API Versioning Source: https://nevermined.ai/docs/development-guide/api-versioning How Nevermined versions its API with the platform release MAJOR.MINOR, how to pin a version per API key or per request, and what the compatibility guarantees are. The Nevermined API is versioned with the platform's own semantic version: **the API version identifier is the release `MAJOR.MINOR`** (for example `1.0`). There is no separate date-based scheme. When platform `X.Y.Z` ships, the API it serves natively is version `X.Y` — patch releases never change the API contract. Your integration keeps working across platform releases because every request resolves to a pinned version, and the platform reshapes requests and responses so that pin keeps seeing the wire format it was built against. ## How a request's version is resolved Each request resolves its **effective version** in this order: 1. **`Nevermined-Version` request header** — overrides everything for that single request. 2. **The API key's pinned version** — every key stores a default pin, visible and editable on the key's details page in the dashboard (API Keys → key → *API Version*). Keys created before versioning existed are pinned to the `1.0` floor; new keys are pinned to the current version at creation time. 3. **The floor (`1.0`)** — used when neither is present (unauthenticated requests without a header). Every response echoes what was applied: ```http theme={null} Nevermined-Version: 1.0 Nevermined-Version-Resolved-From: apiKey ``` `Nevermined-Version-Resolved-From` is one of `header`, `apiKey` or `fallback` — useful when debugging why you got a particular shape. ## The header ```http theme={null} GET /api/v1/x402/permissions HTTP/1.1 Authorization: Bearer Nevermined-Version: 1.0 ``` * Accepted forms: `1.0`, `v1.0`, or a full `1.0.7` — everything normalises to `MAJOR.MINOR`. The patch segment is ignored by design: patches never change the API. * An unknown or out-of-range value is rejected with `400` and a stable, machine-readable [API error code](/docs/development-guide/api-errors/overview) (`BCK.VERSION.0001`). ## Discovering the supported range Call the discovery endpoint with any API key (it is itself exempt from versioning — it always answers in its latest schema): ```bash theme={null} curl -H "Authorization: Bearer $NVM_API_KEY" \ https://api.live.nevermined.app/api/v1/meta/versions ``` ```json theme={null} { "current": "1.1", "floor": "1.0", "gatedVersions": ["1.1"], "yourPinnedVersion": "1.0", "yourEffectiveVersion": "1.0", "yourVersionResolvedFrom": "apiKey" } ``` * `current` — the newest version this deployment serves natively. * `floor` — the oldest version still supported. The floor is supported indefinitely; there are no forced sunsets. * `gatedVersions` — the versions that introduced at least one wire-shape change. A release that changed nothing in the API simply does not appear here: pinning to it behaves exactly like the previous version. * `yourPinnedVersion` — the default stored on the key you called with. A version only appears in `gatedVersions` when it changed the wire shape — `GET /api/v1/meta/versions` reports the current set, and each gate translates the difference for older pins. ## Compatibility guarantees * **Any change to the API interface ships as a minor or major platform release — never a patch.** A client pinned to `X.Y` always receives the latest `X.Y.z` behavior. * **Breaking changes are gated.** When a field is renamed, removed or restructured, clients pinned below the version that introduced the change keep receiving the old shape. Your integration only sees the new shape when you move your pin (or send a newer header). * **Additive changes are not gated.** New endpoints, new optional response fields and new enum values can appear at any minor version. Ignore fields you don't recognise. * The floor (`1.0`) is the wire shape that shipped with platform v0.5.22, frozen. ## Pinning from the SDKs `@nevermined-io/payments` and `payments-py` send `Nevermined-Version` automatically, pinned to the backend version each SDK release was built and tested against (`LOCKED_API_VERSION`). You can override it per instance: ```typescript TypeScript theme={null} import { Payments } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'live', // Optional: pin the backend API version (MAJOR.MINOR) via `version`. // Defaults to the version this SDK release targets; omit to track it. version: '1.1', }) ``` ```python Python theme={null} from payments_py import Payments, PaymentOptions payments = Payments( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment="live", # Optional: pin the backend API version (MAJOR.MINOR) via `api_version`. # Defaults to the version this SDK release targets; omit to track it. api_version="1.1", ) ) ``` ## Upgrading your pin 1. Check which versions between your pin and the target actually changed the wire shape — the `gatedVersions` list from `GET /api/v1/meta/versions`. 2. Test your integration against the target by sending `Nevermined-Version: ` on requests (no stored change needed). 3. When everything works, move the key's default pin on its details page in the dashboard — or rotate to a newly created key, which pins to current automatically. Never change a pin you don't own: pinning is a deliberate, per-integration decision. # AI Coding Skill Source: https://nevermined.ai/docs/development-guide/build-using-nvm-skill Import Nevermined payment and Router knowledge into your AI coding assistant — build agents that charge, and agents that buy. Use the **Nevermined AI Skill** to give your coding assistant deep knowledge of the Nevermined Payments SDK, the x402 payment protocol, and integration patterns for Express.js, FastAPI, Strands agents, MCP servers, and Google A2A. Instead of copy-pasting docs, you import the skill once and your AI assistant knows how to wire up payments for you. ## The Nevermined skills Which one you want depends on what you're doing. The first two are **integration skills** your assistant keeps loaded while you code; the third is an **on-demand workflow** you invoke when you have a service to list. | Skill | Your agent is… | Covers | | - | - | - | | **`nevermined-payments`** | **receiving** money, or buying a Nevermined plan | SDK integration, middleware, plans, credits — the rest of this page | | **`nevermined-router`** | **spending** money at external services | Discovering services in the catalog, creating a spending Delegation, paying any x402 or MPP endpoint through the [Nevermined Router](/docs/products/catalog/router/overview), and the guardrails an autonomous buyer must respect | | **`nevermined-catalog-onboarding`** | **listing** an external x402 service in the Catalog | Picking the routable endpoint, proving it charges with a direct wallet payment, publishing and promoting the listing, a real paid Router e2e, plus ownership/claiming and subscription-credit eligibility | Installing any mix is fine — they don't overlap. Every supported tool can now reach the Router: * **Claude Code** — install them as plugins, one command each. See the tab below. * **Cursor, Windsurf, Cline, Amazon Q** — swap `nevermined-payments` for `nevermined-router` in the paths below, or run the extra command shown in each tab. * **Codex CLI and GitHub Copilot** — `AGENTS.md` and `.github/copilot-instructions.md` are *single* files with no skill name to swap, so each one carries **both** halves: the payments guidance and a condensed Router section. Take the whole file. Codex can also install `nevermined-router` as a proper skill directory under `.agents/skills/` — see its tab. `nevermined-catalog-onboarding` is a workflow you invoke on demand ("onboard this service"), not a rule that should fire on every code edit, so it ships only as a skill **directory** — through the Claude Code marketplace, ClawHub, or a folder copy (`.agents/skills/`, `~/.claude/skills/`) — and has no always-on per-IDE rule file. ## What's Included The skills provide your coding assistant with: * **SDK initialization** patterns for TypeScript and Python * **Framework-specific middleware** (Express.js, FastAPI, Strands, MCP, Google A2A) * **x402 protocol** flow — headers, verification, settlement * **Payment plan** registration and configuration * **Client-side** integration — ordering plans, generating tokens, calling protected APIs * **Troubleshooting** for common errors (402, `-32003`, `-32002`) And, from the Router skill: * **Service discovery** in the public Agent Services Catalog * **Spending Delegations** — creating a capped budget and funding the buyer wallet * **Paid calls** over x402 and MPP through one endpoint, with the protocol auto-detected * **Guardrails** — every `BCK.ROUTER.*` code, what's retryable, and why a refusal must not be worked around ## Install the Skill Choose your AI coding tool below for step-by-step installation instructions. > [tab] Claude Code > > ### Claude Code > > Install from the Nevermined plugin marketplace — two commands, and Claude Code keeps the skills up to date for you: > > ```text theme={null} > /plugin marketplace add nevermined-io/docs > > /plugin install nevermined-payments@nevermined # charging for your agent > /plugin install nevermined-router@nevermined # buying from external services > /plugin install nevermined-catalog-onboarding@nevermined # listing a service in the Catalog > ``` > > Those are Claude Code commands — type them in Claude Code, not in a shell. > > Install either or both. The marketplace is named `nevermined` (that's the `@nevermined` suffix); `nevermined-io/docs` is just the repository it's served from. > > Claude Code loads each skill when it's relevant to your work, and refreshes it in the background when we publish changes. To update by hand it takes two steps — `/plugin marketplace update nevermined` refreshes the catalogue, then `/plugin update nevermined-router@nevermined` updates the installed plugin itself (restart to apply). > > **Alternative — copy the files directly.** Use this if you'd rather take a snapshot you control, or you're on a Claude Code build without plugin support: > > ```bash theme={null} > mkdir -p ~/.claude/skills > > tmpdir="$(mktemp -d)" > git clone --depth 1 --filter=blob:none --sparse https://github.com/nevermined-io/docs "$tmpdir" > cd "$tmpdir" > git sparse-checkout set skills/nevermined-payments skills/nevermined-router > > cp -R skills/nevermined-payments ~/.claude/skills/ > cp -R skills/nevermined-router ~/.claude/skills/ # buying through the Router > > cd - > rm -rf "$tmpdir" > ``` > > Claude Code discovers skills automatically from `~/.claude/skills/` (personal) and `.claude/skills/` (project). Copied this way they're a snapshot — you re-run the command to update. > [tab] ClawHub > > ### ClawHub > > All three skills are published to the [ClawHub](https://clawhub.ai) registry under the `nevermined-io` publisher, so any tool that reads a `skills/` directory can pull them with one command: > > ```bash theme={null} > npx clawhub install nevermined # the payments skill > npx clawhub install nevermined-router # buying through the Router > npx clawhub install nevermined-catalog-onboarding # listing a service in the Catalog > ``` > > This writes to `skills//` in the current directory. `--dir` sets a different target — it's a global flag, so it goes **before** the subcommand: > > ```bash theme={null} > npx clawhub --dir ~/.claude/skills install nevermined-router > ``` > > You don't need an account to install. `npx clawhub update --all` pulls the latest published versions (the bare `update` errors — it wants a slug or `--all`), and `npx clawhub inspect nevermined-router` shows what you'd get without installing it. > > The install lock is per working directory, so if you installed with `--dir`, run the update from that same directory with the same flag: `npx clawhub --dir ~/.claude/skills update --all`. > > > [!NOTE] > > > > Two ClawHub surprises worth knowing. The payments skill is published under the slug **`nevermined`**, not `nevermined-payments` (the Router skill's slug matches its name). And the version `clawhub inspect` reports for the payments skill won't match the `Skill version` in its own `SKILL.md` header — the registry assigns its own numbering. Trust the registry's version for "is my copy current", and the file's for what changed. > [tab] Cursor > > ### Cursor > > **Option A — Remote rule import (recommended):** > > 1. Open **Cursor Settings** (gear icon) > 2. Navigate to **Rules** section > 3. Click **Add Remote Rule** > 4. Paste the GitHub repository URL: `https://github.com/nevermined-io/docs` > 5. Cursor syncs the rules automatically > > **Option B — Copy rule files to your project:** > > Download the rule file and add it to your project: > > ```bash theme={null} > mkdir -p .cursor/rules > curl --fail -o .cursor/rules/nevermined-payments.mdc \ > https://raw.githubusercontent.com/nevermined-io/docs/main/.cursor/rules/nevermined-payments.mdc > > # Buying from external x402 / MPP services through the Router > curl --fail -o .cursor/rules/nevermined-router.mdc \ > https://raw.githubusercontent.com/nevermined-io/docs/main/.cursor/rules/nevermined-router.mdc > ``` > > The `.cursor/rules/*.mdc` format supports glob-based activation — the Nevermined rule auto-activates when you work with `.ts`, `.js`, or `.py` files. > [tab] Windsurf > > ### Windsurf (Codeium) > > Copy the rule file to your project's Windsurf rules directory: > > ```bash theme={null} > mkdir -p .windsurf/rules > curl --fail -o .windsurf/rules/nevermined-payments.md \ > https://raw.githubusercontent.com/nevermined-io/docs/main/.windsurf/rules/nevermined-payments.md > > # Buying from external x402 / MPP services through the Router > curl --fail -o .windsurf/rules/nevermined-router.md \ > https://raw.githubusercontent.com/nevermined-io/docs/main/.windsurf/rules/nevermined-router.md > ``` > > Windsurf automatically discovers rules from `.windsurf/rules/` and applies them based on their activation mode. > > > [!NOTE] > > > > Windsurf workspace rules have a 12,000-character limit per file. The Nevermined rule file stays within this limit, with its guardrails in the first 6,000 characters for older Windsurf versions that cut a rule there. For the full reference, point your assistant to the `SKILL.md`. > [tab] GitHub Copilot > > ### GitHub Copilot > > **Repository-wide instructions:** > > Add the instructions file to your project: > > ```bash theme={null} > mkdir -p .github > curl --fail -o .github/copilot-instructions.md \ > https://raw.githubusercontent.com/nevermined-io/docs/main/.github/copilot-instructions.md > ``` > > Copilot reads `.github/copilot-instructions.md` automatically for every request within the repository. > > **Path-specific instructions (optional):** > > For more targeted activation, create a file at `.github/instructions/nevermined.instructions.md`: > > ```markdown theme={null} > --- > applyTo: "**/*.ts,**/*.tsx,**/*.js,**/*.py" > --- > > When working with Nevermined payments, use the patterns from .github/copilot-instructions.md > ``` > [tab] Codex CLI > > ### OpenAI Codex CLI > > Codex CLI reads `AGENTS.md` files for project context. Add it to your project: > > ```bash theme={null} > curl --fail -o AGENTS.md \ > https://raw.githubusercontent.com/nevermined-io/docs/main/AGENTS.md > ``` > > Codex CLI discovers `AGENTS.md` automatically by scanning from the current directory up to the repository root. > > **Alternative — install as a Codex skill:** > > ```bash theme={null} > mkdir -p .agents/skills > cp -r skills/nevermined-payments .agents/skills/ > cp -r skills/nevermined-router .agents/skills/ # buying through the Router > ``` > > Codex CLI detects skills from `.agents/skills/` and loads them when relevant. > [tab] Cline > > ### Cline (VS Code) > > Copy the rule file to your project: > > ```bash theme={null} > mkdir -p .clinerules > curl --fail -o .clinerules/nevermined-payments.md \ > https://raw.githubusercontent.com/nevermined-io/docs/main/.clinerules/nevermined-payments.md > > # Buying from external x402 / MPP services through the Router > curl --fail -o .clinerules/nevermined-router.md \ > https://raw.githubusercontent.com/nevermined-io/docs/main/.clinerules/nevermined-router.md > ``` > > Cline discovers all `.md` files in the `.clinerules/` directory and applies them based on the `paths` frontmatter. The Nevermined rule activates for `.ts`, `.js`, and `.py` files. > > You can also create rules through the Cline UI: click the **+** button in the Rules popover below the chat input. > [tab] Amazon Q > > ### Amazon Q Developer > > Copy the rule file to your project: > > ```bash theme={null} > mkdir -p .amazonq/rules > curl --fail -o .amazonq/rules/nevermined-payments.md \ > https://raw.githubusercontent.com/nevermined-io/docs/main/.amazonq/rules/nevermined-payments.md > > # Buying from external x402 / MPP services through the Router > curl --fail -o .amazonq/rules/nevermined-router.md \ > https://raw.githubusercontent.com/nevermined-io/docs/main/.amazonq/rules/nevermined-router.md > ``` > > Amazon Q automatically uses rules from `.amazonq/rules/` as context. You can toggle rules on/off via the Rules button in the Amazon Q chat panel. > [tab] Other / Manual > > ### ChatGPT, Claude.ai, or any other assistant > > Share the skill content directly with your assistant: > > 1. Open the [`SKILL.md` file](https://github.com/nevermined-io/docs/blob/main/skills/nevermined-payments/SKILL.md) > 2. Copy the contents > 3. Paste into your assistant's context, knowledge base, or system prompt > > For a more concise version, use the [`AGENTS.md` file](https://github.com/nevermined-io/docs/blob/main/AGENTS.md) instead. ## Supported Tools at a Glance `` is `nevermined-payments` or `nevermined-router` — install either or both. The on-demand `nevermined-catalog-onboarding` workflow installs as a skill directory via Claude Code, ClawHub, or a folder copy (the first and last rows below); it has no always-on IDE rule file. | Tool | Config File | Router available? | Auto-Activates | | - | - | - | - | | **Claude Code** | plugin, or `~/.claude/skills//SKILL.md` | Yes | Yes — when relevant | | **Cursor** | `.cursor/rules/.mdc` | Yes | Yes — on `.ts`, `.js`, `.py` files | | **Windsurf** | `.windsurf/rules/.md` | Yes | Yes — model decides | | **GitHub Copilot** | `.github/copilot-instructions.md` | Yes — condensed, in the same single file | Yes — always | | **Codex CLI** | `AGENTS.md` or `.agents/skills//` | Yes — condensed in `AGENTS.md`, in full via `.agents/skills/` | Yes — always or when relevant | | **Cline** | `.clinerules/.md` | Yes | Yes — on `.ts`, `.js`, `.py` files | | **Amazon Q** | `.amazonq/rules/.md` | Yes | Yes — always | | **Any** (ClawHub) | `skills//SKILL.md` | Yes | Depends on the tool | > [!NOTE] > > The Copilot and Codex files are **condensed** — they carry the buy loop, the money traps and every `BCK.ROUTER.*` retry decision, but not the full reference set: they omit `0004`/`0005` and `0030` (reads of a record, with nothing to retry), `0022` (a deployment/config fault, never seen in a healthy environment) and `0023` (the autoPay `/router/select` “charge indeterminate” outcome — whose reconcile-and-reuse-`requestId` remedy the `route_by_intent` tool result delivers at runtime, and which the `0020` row already models), everything the Router refuses outright (MPP splits, internal targets, redirects, forged `X-Router-*`), and the relay limits. For the complete Router skill, install it as a directory (Claude Code plugin, ClawHub, or `.agents/skills/`). > > The IDE rule files (Cursor, Windsurf, Cline, Amazon Q) also omit `0007`. ## Example Prompts After installing the skill, try prompts like: > [card] Add payments to Express.js > > "Add Nevermined x402 payment protection to my Express.js API. I want to charge 1 credit per request on the `/ask` endpoint." > [card] Protect a FastAPI endpoint > > "Integrate Nevermined payments into my FastAPI app. Use dynamic credits based on the token count in the response." > [card] Build a paid MCP server > > "Create an MCP server with Nevermined payments. Register a weather tool that costs 5 credits per call." > [card] Add payments to a Strands agent > > "Protect my Strands agent tool with the @requires\_payment decorator. Charge 2 credits per call." ## Alternative: Use the MCP Search Server If you prefer real-time documentation search over a static skill, you can connect your coding assistant to the Nevermined MCP documentation server: ```json theme={null} { "mcpServers": { "nevermined-docs": { "url": "https://nevermined.ai/docs/mcp" } } } ``` This gives your assistant the ability to search the full Nevermined documentation on-demand. See [Build Using Nevermined MCP](/docs/mcp/docs-mcp/overview) for details. ## Skill vs. MCP Server | Approach | Best For | Tradeoff | | - | - | - | | **AI Skill** (SKILL.md) | Fast, offline-capable, consistent patterns | Static — update when SDK changes | | **MCP Search Server** | Always up-to-date, full doc coverage | Requires network, slower per-query | For the best experience, use both: install the skill for core patterns and connect the MCP server for edge cases. ## What's Next? > [card] [5-Minute Setup](/docs/integrate/quickstart/5-minute-setup) > > Register your first agent and plan > [card] [Express.js Integration](/docs/integrate/add-to-your-agent/express) > > Full Express.js payment middleware guide > [card] [FastAPI Integration](/docs/integrate/add-to-your-agent/fastapi) > > Full FastAPI payment middleware guide > [card] [MCP Integration](/docs/integrations/mcp) > > Build monetizable MCP servers # Nevermined x402 Source: https://nevermined.ai/docs/development-guide/nevermined-x402 Nevermined provides first-class support for the x402 payment protocol, enabling AI agents, APIs, and services to charge per-request using secure, locally-signed payment authorizations. # Nevermined x402 Nevermined provides first-class support for the x402 payment protocol, enabling AI agents, APIs, and services to charge per-request using secure, locally-signed payment authorizations. > [!NOTE] > > For the complete technical specification, see the [x402 Smart Accounts Extension Spec](/docs/specs/x402-smart-accounts). > [!NOTE] > > **x402 has a sibling protocol: MPP.** Nevermined also speaks the **Merchant Payment Protocol (MPP)**, which settles against the **same Payment Plans, credits, and delegation** as x402 — a request that costs 2 credits burns 2 either way. The only difference is the wire handshake. A service tells you which it speaks by its `402` response: > > * an x402 `accepts` / `payment-required` body → follow the x402 steps on this page; > * a `WWW-Authenticate: Payment …` header → follow [Paying an MPP-protected service](#paying-an-mpp-protected-service) below. > > MPP here is the **plan-model sibling of x402**, offered the same way — not the buyer-side [Router MPP rail](/docs/products/catalog/router/rails-mpp), which pays *external* merchants that were never onboarded to Nevermined. ## Overview This section explains: * The x402 HTTP 402 handshake and `PAYMENT-SIGNATURE` retry pattern * How Nevermined extends x402 with Smart Account-based settlement * How subscribers generate and sign x402 payment proofs * How delegations, session keys, and delegated execution work * How the facilitator verifies and settles requests * How to use the Python and TypeScript x402 client libraries * Advanced integration with Google A2A/AP2 For pricing and plan configuration (credits, time-based access, dynamic pricing), see: * [Payment Models](/docs/integrate/patterns/payment-models) Nevermined's x402 implementation is compatible with the standard protocol while adding programmable settlement layers powered by Nevermined smart contracts. ## Background: What x402 Solves The x402 protocol defines a payment-enforced HTTP 402 mechanism: 1. A client calls an API. 2. The server responds with HTTP 402 Payment Required and instructions. 3. The client signs a payment authorization locally (no private key leaves the device). 4. The signed authorization is included in the next request. 5. The server forwards it to a facilitator, which: * Verifies the signature * Checks balance/permissions * Settles payment on-chain (EIP-3009 or equivalent) Nevermined extends this with ERC-4337 Smart Accounts, session keys, and programmable billing models, allowing much more complex behavior than standard EIP-3009-based transfers. ## Why Nevermined Extends x402 x402 itself focuses on single ERC-20, pay-per-request flows. Nevermined introduces: | Area | x402 | Nevermined | | - | - | - | | Payment authorization | EIP-3009 | ERC-4337 UserOps + session keys | | Wallet model | EOA signatures | Smart Accounts with granular permissions | | Billing models | Pay-per-request | Subscriptions, credits, time windows, credit-burning | | Delegated execution | Basic | Fully programmable “burn”, “order”, “redeem”, plan-specific actions | | Settlement layer | ERC-20 | Nevermined smart-contract settlement | This means a subscriber can grant a server the ability to redeem credits or burn usage units while maintaining strict control over what the server can do. ## High-Level Architecture ```mermaid theme={null} flowchart LR A["Subscriber Smart Account Delegates Permissions"] --> B["Client Application"] B --> C["Server / AI Agent"] C --> D["Nevermined Facilitator"] D --> E["Blockchain\nSmart Contracts"] C -- "Delegated Permissions" --> D D -- "Settles Payment" --> E ``` Roles: * Subscriber: owns a Smart Account; delegates permissions through smart account policies * Server/Agent: exposes an API secured by x402 * Facilitator: Nevermined component that verifies and settles payments * Blockchain: executes credit burns, orders, or other plan-specific actions ## The Nevermined x402 Extensions Nevermined introduces two x402 schemes for different payment rails: | Scheme | Network | Use Case | Settlement | | - | - | - | - | | `nvm:erc4337` | `eip155:84532` | Crypto payments | ERC-4337 UserOps + session keys | | `nvm:card-delegation` | `stripe` | Fiat/credit card | Stripe PaymentIntent + credit burn | For the complete delegation specification, see the [Delegation Spec](/docs/specs/x402-card-delegation). ### `nvm:erc4337` — Smart Account Extension The `nvm:erc4337` scheme uses ERC-4337 smart accounts instead of EOA wallets, enabling programmable settlement through session keys and UserOperations. Instead of embedding an EIP-3009 transfer, the payload includes: * An EIP-712 signature * One or more session keys * Encoded UserOperations representing actions like: * order (purchase credits if balance is low) * burn (burn credits for usage) * redeem (convert plan entitlements into usage) ### PaymentRequired Response (402) When a server requires payment, it returns a `402` response with a `payment-required` header. The scheme depends on the plan's pricing configuration: > [!NOTE] > > **`network` is the settlement *rail*, not the environment.** Send `eip155:` (e.g. `eip155:84532`) for a crypto/ERC-4337 plan, or one of `stripe` / `braintree` / `visa` for a card-delegation plan. It is **not** the environment name — do **not** put `sandbox` or `live` here (that value fails validation). The environment is selected by your API key and base URL, never by this field. **Crypto plan (`nvm:erc4337`):** ```json theme={null} { "x402Version": 2, "error": "Payment required to access resource", "resource": { "url": "/api/v1/agents/80918427023170428029540261117198154464497879145267720259488529685089104529015/tasks", "description": "AI agent task execution", "mimeType": "application/json" }, "accepts": [{ "scheme": "nvm:erc4337", "network": "eip155:84532", "planId": "44742763076047497640080230236781474129970992727896593861997347135613135571071", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015" } }], "extensions": {} } ``` **Fiat plan (`nvm:card-delegation`):** ```json theme={null} { "x402Version": 2, "error": "Payment required to access resource", "resource": { "url": "/api/v1/agents/80918427023170428029540261117198154464497879145267720259488529685089104529015/tasks", "description": "AI agent task execution", "mimeType": "application/json" }, "accepts": [{ "scheme": "nvm:card-delegation", "network": "stripe", "planId": "44742763076047497640080230236781474129970992727896593861997347135613135571071", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015" } }], "extensions": {} } ``` ### PaymentPayload (Client Response) The client responds with a `payment-signature` header containing the payment payload: ```json theme={null} { "x402Version": 2, "resource": { "url": "/api/v1/agents/80918427023170428029540261117198154464497879145267720259488529685089104529015/tasks" }, "accepted": { "scheme": "nvm:erc4337", "network": "eip155:84532", "planId": "44742763076047497640080230236781474129970992727896593861997347135613135571071", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015" } }, "payload": { "signature": "0x01845ADb2C711129d4f3966735eD98a9F09fC4cE...", "authorization": { "from": "0xD4f58B60330bC59cB0A07eE6A1A66ad64244eC8c", "sessionKeysProvider": "zerodev", "sessionKeys": [ { "id": "order", "data": "0x20a13d82dd9ee289fc5e5a90f4011c8dc03f8f5d..." }, { "id": "redeem", "data": "0x68e8e34d659149087451cafc89a7320114072e49..." } ] } }, "extensions": {} } ``` ### What the subscriber delegates | Permission | Meaning | | - | - | | **order** | Allows facilitator to top-up credits (e.g., auto-purchase) | | **redeem** | Allows facilitator to deduct credits per request | | **\** | Additional session-key-scoped behaviors you define | ## Complete Payment & Execution Flow Below is the Nevermined x402 Smart Account flow (verification + settlement). ```mermaid theme={null} sequenceDiagram autonumber actor Client participant Server as Server / AI Agent participant Facilitator as Facilitator (Nevermined API) participant Chain as Blockchain Client->>Server: GET /resource Server->>Client: 402 Payment Required Client->>Client: Create x402 payload + Session Keys Client->>Server: Request + PAYMENT-SIGNATURE header Server->>Facilitator: /verify Facilitator->>Facilitator: Verify session keys ("burn", "order") Facilitator->>Chain: Check balance Chain-->>Facilitator: Balance alt invalid or insufficient permission Facilitator-->>Server: Verification FAILED Server-->>Client: 402 PAYMENT-FAILED end Facilitator-->>Server: Verification OK Server->>Server: Execute AI/compute workload Server->>Facilitator: /settle Facilitator->>Chain: Execute "order" (if needed) Facilitator->>Chain: Execute "burn" Chain-->>Facilitator: Tx result alt settlement success Facilitator-->>Server: Settlement OK Server-->>Client: Response + txHash end ``` ## Facilitator Responsibilities ### Verification The facilitator validates: * x402 envelope structure * EIP-712 signature * Session key authenticity (data or hash) * UserOperation validity (simulation) * Permission requirements (e.g., burn MUST be delegated) * Subscriber balance and plan state * If verification fails, server returns 402 PAYMENT-FAILED. ### Settlement Settlement runs after the server performs the work: * Execute order (if needed) to top up credits * Execute burn to deduct usage * Submit UserOps on-chain * Return tx hashes to the server ## Developer Guide: Subscriber Flow ### Step 1 — Discover payment requirements When the server returns 402 Payment Required, it includes the `payment-required` header (base64-encoded) with: * Supported schemes (`nvm:erc4337`) * Plan and agent IDs * Network information ### Step 2 — Build a payment payload Using Nevermined Payments libraries (Python or TS), you generate an x402 access token. The supported flow is **create-first**: create a delegation once with `createDelegation`, then request access tokens by passing its `delegationId`. A delegation captures the spending limit, duration, `provider`, and `currency`; reuse it for every token request until it expires or is exhausted. > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > import { X402_HEADERS } from '@nevermined-io/payments/express' > > const payments = Payments.getInstance({ > nvmApiKey: 'nvm:subscriber-key', > environment: 'sandbox', > }) > > // Fetch protected resource to get the payment requirements > const response = await fetch('https://api.example.com/protected') > > if (response.status === 402) { > // Decode the payment-required header > const paymentRequired = JSON.parse( > Buffer.from(response.headers.get(X402_HEADERS.PAYMENT_REQUIRED)!, 'base64').toString() > ) > > // Extract planId and agentId from accepts array > const { planId, agentId } = paymentRequired.accepts[0] > > // 1. Create a delegation once. `provider` and `currency` are required: > // 'usdc' for the crypto (erc4337) scheme, 'usd' for card providers. > const delegation = await payments.delegation.createDelegation({ > provider: 'erc4337', > spendingLimitCents: 10000, > durationSecs: 604800, > currency: 'usdc', > }) > > // 2. Request a token by delegationId. Reuse this delegation for every > // subsequent token request. > const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, { > delegationConfig: { delegationId: delegation.delegationId } > }) > } > ``` > [tab] Python > > ```python theme={null} > import base64 > import json > import requests > from payments_py import Payments, PaymentOptions > from payments_py.x402 import ( > CreateDelegationPayload, > DelegationConfig, > X402TokenOptions, > ) > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key="nvm:subscriber-key", environment="sandbox") > ) > > # Fetch protected resource to get the payment requirements > response = requests.get("https://api.example.com/protected") > > if response.status_code == 402: > # Decode the payment-required header > payment_required = json.loads( > base64.b64decode(response.headers.get("payment-required")).decode() > ) > > # Extract planId and agentId from accepts array > plan_id = payment_required["accepts"][0]["planId"] > agent_id = payment_required["accepts"][0].get("extra", {}).get("agentId") > > # 1. Create a delegation once. `provider` and `currency` are required: > # 'usdc' for the crypto (erc4337) scheme, 'usd' for card providers. > delegation = payments.delegation.create_delegation( > CreateDelegationPayload( > provider="erc4337", > spending_limit_cents=10000, > duration_secs=604800, > currency="usdc", > ) > ) > > # 2. Request a token by delegationId (reuse it for subsequent requests). > token_res = payments.x402.get_x402_access_token( > plan_id, > agent_id, > token_options=X402TokenOptions( > delegation_config=DelegationConfig( > delegation_id=delegation.delegation_id > ) > ), > ) > access_token = token_res["accessToken"] > ``` > [!NOTE] > > **The buyer-side `getX402AccessToken` / `get_x402_access_token` call does not auto-detect the scheme — it defaults to `nvm:erc4337` (crypto).** For a **fiat** plan (`isCrypto: false`) you must resolve and pass the scheme, and create the delegation with the matching card provider: > > * Detect the scheme with `resolveScheme()` (TypeScript) / `resolve_scheme()` (Python), then pass `scheme: 'nvm:card-delegation'` to the token call. > * Use `provider: 'stripe'` (or `'braintree'` / `'visa'`) with `currency: 'usd'` in the delegation; for crypto plans use `provider: 'erc4337'` with `currency: 'usdc'`. > > Server-side **middleware** (Express, FastAPI) and the **A2A clients** resolve the scheme for you automatically — see the [Express.js](/docs/integrate/add-to-your-agent/express) and [FastAPI](/docs/integrate/add-to-your-agent/fastapi) guides, and [Which payment type does this plan need?](/docs/getting-started/core-concepts#fiat-vs-crypto-what-each-plan-needs). > [!WARNING] > > **Inline create-on-the-fly is deprecated.** Passing creation fields (`spendingLimitCents`, `durationSecs`, `providerPaymentMethodId`, `cardId`, `currency`) directly in `delegationConfig` instead of a `delegationId` still works but emits a runtime deprecation warning. Create the delegation first (as above) and pass only `{ delegationId }`. Delegations are **plan-agnostic by default**; pass `planId` on `createDelegation` only to bind a delegation to a single plan. `provider` and `currency` are **required** — there is no silent default. > [!TIP] > > With a delegation in place you can skip the manual `order_plan()` / `orderPlan()` step entirely. If the subscriber's balance is short when a request settles, the facilitator tops up their credits automatically, up to the delegation's limit. See [Automatic Credit Top-Ups](/docs/integrate/patterns/top-up). ### Step 3 — Submit with HTTP header Clients include the x402 access token in the `payment-signature` header: ``` payment-signature: ``` ## Developer Guide: Agent Flow ### Quick Integration: Framework Middleware Both TypeScript (Express.js) and Python (FastAPI) have built-in middleware that handles x402 automatically: > [tab] Express.js (TypeScript) > > For Express.js applications, use the `paymentMiddleware` from `@nevermined-io/payments/express`: > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > import { paymentMiddleware } from '@nevermined-io/payments/express' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox' > }) > > // One line to protect routes > app.use( > paymentMiddleware(payments, { > 'POST /ask': { planId: PLAN_ID, credits: 1 } > }) > ) > > // Route handler - no payment logic needed > app.post('/ask', async (req, res) => { > const result = await processRequest(req.body) > res.json({ result }) > }) > ``` > > See the [Express.js Integration Guide](/docs/integrate/add-to-your-agent/express) for full details. > [tab] FastAPI (Python) > > For FastAPI applications, use the `PaymentMiddleware` from `payments_py.x402.fastapi`: > > ```python theme={null} > from fastapi import FastAPI > from payments_py import Payments, PaymentOptions > from payments_py.x402.fastapi import PaymentMiddleware > > app = FastAPI() > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ["NVM_API_KEY"], environment="sandbox") > ) > > # One line to protect routes > app.add_middleware( > PaymentMiddleware, > payments=payments, > routes={ > "POST /ask": {"plan_id": PLAN_ID, "credits": 1} > } > ) > > # Route handler - no payment logic needed > @app.post("/ask") > async def ask(request: Request): > body = await request.json() > result = await process_request(body) > return {"result": result} > ``` > > See the [FastAPI Integration Guide](/docs/integrate/add-to-your-agent/fastapi) for full details. The middleware handles verification, settlement, and all x402 headers automatically. > [!NOTE] > > The middleware automatically detects the payment scheme from plan metadata. > Plans with fiat pricing (`isCrypto: false`) use `nvm:card-delegation` (Stripe). > **No code changes are needed on the agent side.** You can explicitly override with > the `scheme` parameter in the route configuration. ### Manual Integration For other frameworks or custom implementations, follow these steps: ### Step 1 — Receive and parse * Read the x402 token from the `payment-signature` header (x402 v2). * If no token is present, return a 402 response with payment requirements. ### Step 2 — Verify with the facilitator > [tab] TypeScript > > ```typescript theme={null} > import { Payments, decodeAccessToken } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: 'nvm:agent-key', > environment: 'sandbox', > }) > > // Get token from payment-signature header > const x402Token = req.headers['payment-signature'] > > if (!x402Token) { > // Return 402 with payment requirements > return res.status(402).json({ error: 'Payment Required' }) > } > > // Verify permissions - facilitator extracts planId and subscriberAddress from token > const verification = await payments.facilitator.verifyPermissions({ > x402AccessToken: x402Token, > maxAmount: BigInt(creditsRequired), > }) > > if (!verification.isValid) { > return res.status(402).json({ error: 'Payment verification failed' }) > } > ``` > [tab] Python > > ```python theme={null} > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key="nvm:agent-key", environment="sandbox") > ) > > # Get token from payment-signature header > x402_token = request.headers.get("payment-signature") > > if not x402_token: > # Return 402 with payment requirements > return {"error": "Payment Required"}, 402 > > # Verify permissions - facilitator extracts planId and subscriberAddress from token > verification = payments.facilitator.verify_permissions( > x402_access_token=x402_token, > max_amount=credits_required, > ) > > if not verification.is_valid: > return {"error": "Payment verification failed"}, 402 > ``` ### Step 3 — Execute your workload * Perform the paid operation only after verification succeeds. ### Step 4 — Settle > [tab] TypeScript > > ```typescript theme={null} > // Settle after work is complete - burns the actual credits used > const settlement = await payments.facilitator.settlePermissions({ > x402AccessToken: x402Token, > maxAmount: BigInt(actualCreditsUsed), > }) > > // Return response with settlement receipt in payment-response header. > // Pass `billingModel` through: on a pay-as-you-go plan the credit fields are > // always "0", so without it the buyer cannot tell a real charge from a > // credits settle that burned nothing. > const settlementReceipt = Buffer.from(JSON.stringify({ > success: true, > billingModel: settlement.billingModel, > creditsRedeemed: actualCreditsUsed, > orderTx: settlement.orderTx, > transactionHash: settlement.transaction, > })).toString('base64') > > res.set('payment-response', settlementReceipt) > res.json({ result }) > ``` > [tab] Python > > ```python theme={null} > import base64 > import json > > # Settle after work is complete - burns the actual credits used > settlement = payments.facilitator.settle_permissions( > x402_access_token=x402_token, > max_amount=actual_credits_used, > ) > > # Return response with settlement receipt in payment-response header. > # Pass `billingModel` through: on a pay-as-you-go plan the credit fields are > # always "0", so without it the buyer cannot tell a real charge from a > # credits settle that burned nothing. > settlement_receipt = base64.b64encode(json.dumps({ > "success": True, > "billingModel": settlement.billing_model, > "creditsRedeemed": actual_credits_used, > "orderTx": settlement.order_tx, > "transactionHash": settlement.transaction, > }).encode()).decode() > > response.headers["payment-response"] = settlement_receipt > return {"result": result} > ``` ## Paying an MPP-protected service Some services accept **MPP (Merchant Payment Protocol)** instead of x402. MPP settles against the same Nevermined Payment Plans as x402 — same credits, same delegation, same meter — so the buyer flow mirrors the one above with `/api/v1/mpp/*` in place of `/api/v1/x402/*`. You recognise an MPP service by its `402`: it carries a `WWW-Authenticate: Payment …` header instead of an x402 `accepts` body. > [!NOTE] > > This is the **buyer** side. To make *your own* plan-protected endpoint MPP-payable, see [Accepting MPP payments](/docs/products/payments-facilitator/mpp-seller). ### Recommended: the SDK does it for you The MPP credential is an `mppx`-serialised structure (the server's challenge plus your minted access token), not a plain header value — so the practical buyer path is the SDK. `payments.mpp.fetch(...)` is a drop-in for `fetch`: it parses the challenge, mints the token, builds the credential, presents it, and reads the `Payment-Receipt` for you. It uses the **same delegation** you already created for x402. > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox', > }) > > // Reuse the delegation you created for x402 (see "Build a payment payload" above). > const { response, settled, receipt } = await payments.mpp.fetch( > 'https://api.example.com/ask', > { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: 'Hello' }) }, > { delegationConfig: { delegationId: delegation.delegationId }, planId: PLAN_ID }, > ) > > if (settled) { > console.log('Paid. Receipt reference:', receipt?.reference) > const result = await response.json() > } > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments, PaymentOptions > from payments_py.mpp import MppFetchOptions > from payments_py.x402.types import DelegationConfig > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ["NVM_API_KEY"], environment="sandbox") > ) > > # Reuse the delegation you created for x402 (see "Build a payment payload" above). > result = payments.mpp.fetch( > "POST", > "https://api.example.com/ask", > MppFetchOptions( > delegation_config=DelegationConfig(delegation_id=delegation.delegation_id), > plan_id=PLAN_ID, # optional: refuse a challenge naming another plan > max_credits="10", # optional: cap the credits for the whole call > ), > json={"prompt": "Hello"}, > ) > > if result.settled: > print("Paid. Receipt reference:", result.receipt.reference) > data = result.response.json() > ``` > [!TIP] > > `settled` (a `Payment-Receipt` came back and did not report failure) is the honest signal that credits were burned — not the HTTP status. A streaming handler can return `200` with no receipt even though the credits were burned, so never read "no receipt" as "not paid" and blindly retry. ### Under the hood (raw HTTP) If you are not using the SDK, the flow is three steps — and you do **not** pre-buy the plan: the delegation-backed settle in step 3 acquires and burns the credits in one call, exactly like the x402 `settle` flow above. **1. Call the service unpaid** It replies `402` with a `WWW-Authenticate: Payment …` challenge that names the `planId` and the `credits` the call costs. **2. Mint an MPP access token for that plan** `POST /api/v1/mpp/permissions` — the counterpart of `/api/v1/x402/permissions`, with the **same body minus `tokenVersion`**: ```json theme={null} { "resource": { "url": "" }, "accepted": { "scheme": "nvm:erc4337", "network": "", "planId": "" }, "delegationConfig": { "delegationId": "" } } ``` It returns an `accessToken` signed under the `Nevermined-MPP` domain, so it is accepted only on MPP routes (and refused on x402 routes). Use a card-delegation scheme/`network` instead for a fiat plan, exactly as in x402. **3. Present the credential** Combine the challenge with your access token into an MPP credential and re-send the request with `Authorization: Payment `. The service verifies and settles it against your plan credits and returns a `Payment-Receipt` header as your proof. Settling the same challenge twice burns once — the challenge id is the idempotency key. > [!NOTE] > > Building the credential by hand needs the `mppx` serialisation library, which is why the SDK is the recommended path above. The raw shape is documented for parity and for non-JS/Python clients. ## Summary This section provides a comprehensive guide for developers integrating Nevermined with x402: * **x402** gives a universal payment-required protocol * **Nevermined** enriches it with Smart Accounts, UserOps, and advanced billing models using the `nvm:erc4337` and `nvm:card-delegation` schemes * **Delegations** provide a unified permission model for both crypto (`nvm:erc4337`) and fiat (`nvm:card-delegation`) schemes, with auto-detection from plan metadata * **Subscribers** delegate controlled permissions using `DelegationConfig` (spending limits and duration) * **Servers** use `payment-signature` headers and verify/settle via the facilitator * **Facilitators** verify and settle on-chain * **MPP** is the sibling protocol: the same plans, credits, and delegation over a `WWW-Authenticate: Payment` / `Authorization: Payment` handshake — pay it with `payments.mpp.fetch(...)` * **Python & TypeScript libraries** provide turnkey developer tooling * **Express.js and FastAPI middleware** handle the entire flow automatically # Observability & Monitoring Source: https://nevermined.ai/docs/development-guide/observability Learn how to add comprehensive observability and monitoring to your AI agents using Nevermined Payment Libraries # Observability & Monitoring for AI Agents The Nevermined Payment Libraries include built-in observability capabilities that allow you to monitor, track, and analyze your AI agent's performance, usage patterns, and costs. This integration provides comprehensive logging and analytics for your AI operations. ## Overview The observability API provides: * **Request/Response Logging**: Automatic logging of all AI API calls with full context * **Usage Tracking**: Token usage, costs, and performance metrics * **Custom Properties**: Add custom metadata to your logs for better analysis * **Real-time Monitoring**: View logs and metrics in the Nevermined dashboard ## Basic Integration ### 1. Initialize the Observability API The observability functionality is automatically available through the `Payments` class: > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from "@nevermined-io/payments"; > > const payments = Payments.getInstance({ > nvmApiKey: "your-api-key", > environment: "sandbox", > }); > > // Access observability through payments.observability > const observability = payments.observability; > ``` > [tab] Python > > ```python theme={null} > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance(PaymentOptions( > nvm_api_key="your-api-key", > environment="sandbox", > )) > > # Access observability through payments.observability > observability = payments.observability > ``` ### 2. Configure OpenAI with Observability Logging Use the `withOpenAI` method to wrap your OpenAI client with automatic logging: > [tab] TypeScript > > ```typescript theme={null} > import OpenAI from "openai"; > > // Create OpenAI client with observability > const openai = new OpenAI( > payments.observability.withOpenAI( > "your-openai-api-key", > agentRequest, // From payment validation > { > userid: "your-user-id", // optional custom property > operation: "financial_advice", // optional custom property > } > ) > ); > > // All OpenAI calls will be automatically logged > const completion = await openai.chat.completions.create({ > model: "gpt-4o-mini", > messages: messages, > temperature: 0.3, > max_tokens: 250, > }); > ``` > [tab] Python > > ```python theme={null} > import openai > from dataclasses import asdict > > # Set up observability metadata > custom_properties = { > "userid": "your-user-id", # optional custom property > "operation": "financial_advice", # optional custom property > } > > # Create OpenAI client with observability > openai_config = payments.observability.with_openai( > "your-openai-api-key", > agent_request, # From payment validation > custom_properties > ) > > openai_client = openai.OpenAI(**asdict(openai_config)) > > # All OpenAI calls will be automatically logged > completion = openai_client.chat.completions.create( > model="gpt-4o-mini", > messages=messages, > temperature=0.3, > max_tokens=250, > ) > ``` ### 3. Configure Langchain with Observability Logging Use the `withLangchain` method to wrap your Langchain client with automatic logging: > [tab] TypeScript > > ```typescript theme={null} > import { ChatOpenAI } from "@langchain/openai"; > > const llm = new ChatOpenAI( > payments.observability.withLangchain( > "gpt-4o-mini", > "your-openai-api-key", > agentRequest, > { > userid: "your-user-id", // optional custom property > operation: "financial_advice", // optional custom property > } > ) > ); > ``` > [tab] Python > > ```python theme={null} > from dataclasses import asdict > from langchain_openai import ChatOpenAI > > # Configure Langchain with observability > langchain_config = payments.observability.with_langchain( > "gpt-4o-mini", > "your-openai-api-key", > agent_request, > { > "userid": "your-user-id", # optional custom property > "operation": "financial_advice", # optional custom property > } > ) > > llm = ChatOpenAI(**asdict(langchain_config)) > ``` ## Advanced Usage ### Manual Operation Logging > [!NOTE] > > Documentation for Manual Operation Logging is coming soon. This section will > cover how to wrap custom operations with observability logging for non-OpenAI > or Langchain services. ### Custom Properties and Metadata Add custom properties to track additional context: > [tab] TypeScript > > ```typescript theme={null} > const customProperties = { > sessionid: sessionId, > operation: "investment_analysis", > userId: "user-123", > requestType: "portfolio_review", > timestamp: new Date().toISOString(), > }; > ``` > [tab] Python > > ```python theme={null} > custom_properties = { > "sessionid": session_id, > "operation": "investment_analysis", > "userId": "user-123", > "requestType": "portfolio_review", > "timestamp": datetime.now().isoformat(), > } > ``` ### Usage Calculation Helpers > [!NOTE] > > Documentation for usage calculation helpers for video and audio operations is > coming soon. This section will cover how to calculate usage metrics for > different types of AI operations. ### Pricing Simulation The pricing simulation feature allows you to test and estimate costs without requiring agent registration, plans, or user subscriptions. This is perfect for development, testing, and cost estimation before going to production. > [tab] TypeScript > > ```typescript theme={null} > // Start a simulation request (no agent/plan needed) > const agentRequest = await payments.requests.startSimulationRequest({ > pricePerCredit: 0.01, // Optional: USD per credit (default: 0.01) > batch: false, // Optional: batch mode (default: false) > agentName: "My Test Agent", // Optional: display name > planName: "Test Plan", // Optional: plan name > }); > > // Make LLM calls with observability > const openai = new OpenAI( > payments.observability.withOpenAI( > process.env.OPENAI_API_KEY!, > agentRequest, > {} > ) > ); > > const completion = await openai.chat.completions.create({ > model: "gpt-4o-mini", > messages: [{ role: "user", content: "Hello, world!" }], > }); > > // Finish simulation with custom margin > await payments.requests.finishSimulationRequest( > agentRequest.agentRequestId, > 0.2, // 20% profit margin (default) > false // batch mode > ); > ``` > [tab] Python > > ```python theme={null} > # Start a simulation request (no agent/plan needed) > agent_request = payments.requests.start_simulation_request( > price_per_credit=0.01, # Optional: USD per credit (default: 0.01) > batch=False, # Optional: batch mode (default: False) > agent_name="My Test Agent", # Optional: display name > plan_name="Test Plan", # Optional: plan name > ) > > # Make LLM calls with observability > openai_config = payments.observability.with_openai( > os.getenv("OPENAI_API_KEY"), > agent_request, > {} > ) > > openai_client = openai.OpenAI(**asdict(openai_config)) > > completion = openai_client.chat.completions.create( > model="gpt-4o-mini", > messages=[{"role": "user", "content": "Hello, world!"}], > ) > > # Finish simulation with custom margin > payments.requests.finish_simulation_request( > agent_request.agent_request_id, > 0.2, # 20% profit margin (default) > False # batch mode > ) > ``` **Key Features:** * No agent or plan registration required * No user subscriptions needed * Automatic cost calculation with configurable profit margins * Full observability tracking included * Perfect for testing, development, and cost estimation **Learn More:** Check out the complete tutorials for full working examples: * [Pricing Simulation Tutorial (TypeScript)](https://github.com/nevermined-io/tutorials/tree/main/pricing-simulation) * [Pricing Simulation Tutorial (Python)](https://github.com/nevermined-io/tutorials/tree/main/pricing-simulation-py) ### Batch vs Regular Requests You can process requests in two modes: * **Regular Requests**: Process one request at a time. Each request gets its own unique agent request ID. * **Batch Requests**: Process multiple requests together using the same agent request ID. This is useful when you need to make multiple AI calls (e.g., multiple OpenAI requests) within a single user request, and you want to redeem credits once at the end for all operations combined. > [tab] TypeScript > > ```typescript theme={null} > // Regular request - process one request at a time > const agentRequest = await payments.requests.startProcessingRequest( > agentId, > authHeader, > requestedUrl, > httpVerb > ); > > // Batch request - process multiple requests together > const agentRequest = await payments.requests.startProcessingBatchRequest( > agentId, > authHeader, > requestedUrl, > httpVerb > ); > ``` > [tab] Python > > ```python theme={null} > # Regular request - process one request at a time > agent_request = payments.requests.start_processing_request( > agent_id, > auth_header, > requested_url, > http_verb > ) > > # Batch request - process multiple requests together > agent_request = payments.requests.start_processing_batch_request( > agent_id, > auth_header, > requested_url, > http_verb > ) > ``` ### Credit Redemption Strategies There are two ways to redeem credits after processing a request: > [!NOTE] > > **Important:** The redemption method you use must match how you started the request: > > * If you used `startProcessingRequest()`, use `redeemCreditsFromRequest()` or `redeemWithMarginFromRequest()` > * If you used `startProcessingBatchRequest()`, use `redeemCreditsFromBatchRequest()` or `redeemWithMarginFromBatchRequest()` #### Fixed Credit Redemption Charges a specific number of credits per request. Useful for predictable, pay-per-use models. The credit amount can be a static value or calculated dynamically (e.g., based on token usage, API calls made, or other metrics). > [tab] TypeScript > > ```typescript theme={null} > // Credit amount can be static or dynamically computed > const creditAmount = BigInt(10); // Static value > // OR > const creditAmount = calculateCreditAmount(tokensUsed, maxTokens); // Computed value > > // Redeem fixed credits from a regular request > const redemptionResult = await payments.requests.redeemCreditsFromRequest( > agentRequestId, > requestAccessToken, > creditAmount > ); > > // Redeem fixed credits from a batch request > const redemptionResult = await payments.requests.redeemCreditsFromBatchRequest( > agentRequestId, > requestAccessToken, > creditAmount > ); > > // Extract credits redeemed > const creditsRedeemed = redemptionResult.data?.amountOfCredits || 0; > ``` > [tab] Python > > ```python theme={null} > # Credit amount can be static or dynamically computed > credit_amount = 10 # Static value > # OR > credit_amount = calculate_credit_amount(tokens_used, max_tokens) # Computed value > > # Redeem fixed credits from a regular request > redemption_response = payments.requests.redeem_credits_from_request( > agent_request_id, > request_access_token, > credit_amount > ) > > # Redeem fixed credits from a batch request > redemption_response = payments.requests.redeem_credits_from_batch_request( > agent_request_id, > request_access_token, > credit_amount > ) > > # Extract credits redeemed > credits_redeemed = redemption_response.get("data", {}).get("amountOfCredits", 0) > ``` #### Margin-based Redemption Charges the actual API cost plus a margin percentage. Useful for adding a service fee on top of API costs. The margin percentage can be a static value or calculated dynamically (e.g., based on business logic, user tier, or market conditions). For example, if an API call costs 10 cents and you set a 20% margin (0.2), the total charge will be 10 + (10 × 0.2) = 12 cents in dollar-equivalent credits. > [tab] TypeScript > > ```typescript theme={null} > // Margin percentage can be static or dynamically computed > const marginPercent = 0.2; // Static 20% margin > // OR > const marginPercent = calculateMargin(userTier, apiCost); // Computed value > > // Redeem with margin from a regular request > const redemptionResult = await payments.requests.redeemWithMarginFromRequest( > agentRequestId, > requestAccessToken, > marginPercent > ); > > // Redeem with margin from a batch request > const redemptionResult = await payments.requests.redeemWithMarginFromBatchRequest( > agentRequestId, > requestAccessToken, > marginPercent > ); > > // Extract credits redeemed > const creditsRedeemed = redemptionResult.data?.amountOfCredits || 0; > ``` > [tab] Python > > ```python theme={null} > # Margin percentage can be static or dynamically computed > margin_percent = 0.2 # Static 20% margin > # OR > margin_percent = calculate_margin(user_tier, api_cost) # Computed value > > # Redeem with margin from a regular request > redemption_response = payments.requests.redeem_with_margin_from_request( > agent_request_id, > request_access_token, > margin_percent > ) > > # Redeem with margin from a batch request > redemption_response = payments.requests.redeem_with_margin_from_batch_request( > agent_request_id, > request_access_token, > margin_percent > ) > > # Extract credits redeemed > credits_redeemed = redemption_response.get("data", {}).get("amountOfCredits", 0) > ``` ## Complete Example Here's a complete example showing how to integrate observability into an AI agent: > [tab] TypeScript > > ```typescript theme={null} > import express from "express"; > import OpenAI from "openai"; > import { Payments } from "@nevermined-io/payments"; > > const app = express(); > app.use(express.json()); > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: "sandbox", > }); > > app.post("/ask", async (req, res) => { > try { > // Validate payment and get agent request > const agentRequest = await payments.requests.startProcessingRequest( > process.env.AGENT_ID!, > req.headers.authorization as string, > req.url, > req.method > ); > > // Check user has sufficient balance > if ( > !agentRequest.balance.isSubscriber || > agentRequest.balance.balance < 1n > ) { > return res.status(402).json({ error: "Payment Required" }); > } > > const { input_query, sessionId, userId } = req.body; > > // Set up observability metadata > const customProperties = { > sessionid: sessionId, > operation: "financial_advice", > userid: userId, > }; > > // Create OpenAI client with observability > const openai = new OpenAI( > payments.observability.withOpenAI( > process.env.OPENAI_API_KEY!, > agentRequest, > customProperties > ) > ); > > // Make the AI call (automatically logged) > const completion = await openai.chat.completions.create({ > model: "gpt-4o-mini", > messages: [ > { role: "system", content: "You are a financial advisor..." }, > { role: "user", content: input_query }, > ], > temperature: 0.3, > max_tokens: 250, > }); > > const response = completion.choices[0]?.message?.content; > > // Redeem credits > await payments.requests.redeemCreditsFromRequest( > agentRequest.agentRequestId, > req.headers.authorization?.replace("Bearer ", "")!, > BigInt(10) // Credit amount > ); > > res.json({ > output: response, > sessionId: customProperties.sessionid, > tokensUsed: completion.usage?.total_tokens, > }); > > } catch (error) { > console.error("Error:", error); > res.status(500).json({ error: "Internal server error" }); > } > }); > ``` > [tab] Python > > ```python theme={null} > import os > from dataclasses import asdict > from fastapi import FastAPI, HTTPException, Header > from pydantic import BaseModel > from typing import Optional > import openai > from payments_py import Payments, PaymentOptions > > app = FastAPI() > > payments = Payments.get_instance(PaymentOptions( > nvm_api_key=os.getenv("NVM_API_KEY"), > environment="sandbox", > )) > > class AskRequest(BaseModel): > input_query: str > sessionId: Optional[str] = None > userId: Optional[str] = None > > @app.post("/ask") > async def ask( > request: AskRequest, > authorization: Optional[str] = Header(default=None) > ): > try: > # Validate Bearer token format > if not authorization or not authorization.startswith("Bearer "): > raise HTTPException( > status_code=401, > detail="Authorization header must be in format: Bearer " > ) > > # Validate payment and get agent request > agent_request = payments.requests.start_processing_request( > os.getenv("AGENT_ID"), > authorization, > "/ask", > "POST" > ) > > # Check user has sufficient balance > if not agent_request.balance.is_subscriber or agent_request.balance.balance < 1: > raise HTTPException(status_code=402, detail="Payment Required") > > # Extract access token for credit redemption > request_access_token = authorization.replace("Bearer ", "", 1) > > # Set up observability metadata > custom_properties = { > "sessionid": request.sessionId, > "operation": "financial_advice", > "userid": request.userId, > } > > # Create OpenAI client with observability > openai_config = payments.observability.with_openai( > os.getenv("OPENAI_API_KEY"), > agent_request, > custom_properties > ) > > openai_client = openai.OpenAI(**asdict(openai_config)) > > # Make the AI call (automatically logged) > completion = openai_client.chat.completions.create( > model="gpt-4o-mini", > messages=[ > {"role": "system", "content": "You are a financial advisor..."}, > {"role": "user", "content": request.input_query}, > ], > temperature=0.3, > max_tokens=250, > ) > > response = completion.choices[0].message.content > tokens_used = completion.usage.completion_tokens if completion.usage else 0 > > # Redeem credits > payments.requests.redeem_credits_from_request( > agent_request.agent_request_id, > request_access_token, > 10 # Credit amount > ) > > return { > "output": response, > "sessionId": custom_properties["sessionid"], > "tokensUsed": tokens_used, > } > > except HTTPException: > raise > except Exception as error: > print(f"Error: {error}") > raise HTTPException(status_code=500, detail="Internal server error") > ``` ### Additional Examples > [accordion] Batch Mode > > Complete example using batch request processing. This example shows making multiple AI calls within a single batch request, all sharing the same agent request ID: > > > [tab] TypeScript > > > > ```typescript theme={null} > > // Use batch processing - all operations will share the same agent request ID > > const agentRequest = await payments.requests.startProcessingBatchRequest( > > process.env.AGENT_ID!, > > req.headers.authorization as string, > > req.url, > > req.method > > ); > > > > // Check user has sufficient balance > > if (!agentRequest.balance.isSubscriber || agentRequest.balance.balance < 1n) { > > return res.status(402).json({ error: "Payment Required" }); > > } > > > > const requestAccessToken = req.headers.authorization?.replace("Bearer ", "")!; > > > > // Create OpenAI client with observability > > const openai = new OpenAI( > > payments.observability.withOpenAI( > > process.env.OPENAI_API_KEY!, > > agentRequest, > > { operation: "batch_analysis" } > > ) > > ); > > > > // Make multiple AI calls in the same batch > > // Call 1: Analyze user query > > const analysis = await openai.chat.completions.create({ > > model: "gpt-4o-mini", > > messages: [{ role: "user", content: "Analyze this investment strategy..." }], > > max_tokens: 100, > > }); > > > > // Call 2: Generate recommendations > > const recommendations = await openai.chat.completions.create({ > > model: "gpt-4o-mini", > > messages: [{ role: "user", content: "Provide investment recommendations..." }], > > max_tokens: 100, > > }); > > > > // Call 3: Create summary > > const summary = await openai.chat.completions.create({ > > model: "gpt-4o-mini", > > messages: [{ role: "user", content: "Summarize the analysis..." }], > > max_tokens: 50, > > }); > > > > // Calculate total credits for all operations > > const totalCredits = BigInt(30); // Or calculate based on actual token usage > > > > // Redeem credits once for all operations in the batch > > await payments.requests.redeemCreditsFromBatchRequest( > > agentRequest.agentRequestId, > > requestAccessToken, > > totalCredits > > ); > > > > res.json({ > > analysis: analysis.choices[0]?.message?.content, > > recommendations: recommendations.choices[0]?.message?.content, > > summary: summary.choices[0]?.message?.content, > > }); > > ``` > > > [tab] Python > > > > ```python theme={null} > > # Use batch processing - all operations will share the same agent request ID > > agent_request = payments.requests.start_processing_batch_request( > > os.getenv("AGENT_ID"), > > authorization, > > "/ask", > > "POST" > > ) > > > > # Check user has sufficient balance > > if not agent_request.balance.is_subscriber or agent_request.balance.balance < 1: > > raise HTTPException(status_code=402, detail="Payment Required") > > > > request_access_token = authorization.replace("Bearer ", "", 1) > > > > # Create OpenAI client with observability > > openai_config = payments.observability.with_openai( > > os.getenv("OPENAI_API_KEY"), > > agent_request, > > {"operation": "batch_analysis"} > > ) > > > > openai_client = openai.OpenAI(**asdict(openai_config)) > > > > # Make multiple AI calls in the same batch > > # Call 1: Analyze user query > > analysis = openai_client.chat.completions.create( > > model="gpt-4o-mini", > > messages=[{"role": "user", "content": "Analyze this investment strategy..."}], > > max_tokens=100, > > ) > > > > # Call 2: Generate recommendations > > recommendations = openai_client.chat.completions.create( > > model="gpt-4o-mini", > > messages=[{"role": "user", "content": "Provide investment recommendations..."}], > > max_tokens=100, > > ) > > > > # Call 3: Create summary > > summary = openai_client.chat.completions.create( > > model="gpt-4o-mini", > > messages=[{"role": "user", "content": "Summarize the analysis..."}], > > max_tokens=50, > > ) > > > > # Calculate total credits for all operations > > total_credits = 30 # Or calculate based on actual token usage > > > > # Redeem credits once for all operations in the batch > > payments.requests.redeem_credits_from_batch_request( > > agent_request.agent_request_id, > > request_access_token, > > total_credits > > ) > > > > return { > > "analysis": analysis.choices[0].message.content, > > "recommendations": recommendations.choices[0].message.content, > > "summary": summary.choices[0].message.content, > > } > > ``` > [accordion] Margin-based Pricing > > Complete example using margin-based credit redemption: > > > [tab] TypeScript > > > > ```typescript theme={null} > > // Regular request processing > > const agentRequest = await payments.requests.startProcessingRequest( > > process.env.AGENT_ID!, > > req.headers.authorization as string, > > req.url, > > req.method > > ); > > > > // ... rest of your agent logic ... > > > > // Redeem with margin percentage (e.g., 20% markup on API costs) > > const marginPercent = 0.2; > > await payments.requests.redeemWithMarginFromRequest( > > agentRequest.agentRequestId, > > requestAccessToken, > > marginPercent > > ); > > ``` > > > [tab] Python > > > > ```python theme={null} > > # Regular request processing > > agent_request = payments.requests.start_processing_request( > > os.getenv("AGENT_ID"), > > authorization, > > "/ask", > > "POST" > > ) > > > > # ... rest of your agent logic ... > > > > # Redeem with margin percentage (e.g., 20% markup on API costs) > > margin_percent = 0.2 > > payments.requests.redeem_with_margin_from_request( > > agent_request.get("agent_request_id"), > > request_access_token, > > margin_percent > > ) > > ``` > [accordion] Batch Mode + Margin-based Pricing > > Complete example combining batch processing with margin-based pricing. All operations share the same agent request ID, and credits are redeemed once at the end based on actual API costs plus margin: > > > [tab] TypeScript > > > > ```typescript theme={null} > > // Use batch processing - all operations will share the same agent request ID > > const agentRequest = await payments.requests.startProcessingBatchRequest( > > process.env.AGENT_ID!, > > req.headers.authorization as string, > > req.url, > > req.method > > ); > > > > // Check user has sufficient balance > > if (!agentRequest.balance.isSubscriber || agentRequest.balance.balance < 1n) { > > return res.status(402).json({ error: "Payment Required" }); > > } > > > > const requestAccessToken = req.headers.authorization?.replace("Bearer ", "")!; > > > > // Create OpenAI client with observability > > const openai = new OpenAI( > > payments.observability.withOpenAI( > > process.env.OPENAI_API_KEY!, > > agentRequest, > > { operation: "batch_analysis" } > > ) > > ); > > > > // Make multiple AI calls in the same batch > > // Call 1: Analyze user query > > const analysis = await openai.chat.completions.create({ > > model: "gpt-4o-mini", > > messages: [{ role: "user", content: "Analyze this investment strategy..." }], > > max_tokens: 100, > > }); > > > > // Call 2: Generate recommendations > > const recommendations = await openai.chat.completions.create({ > > model: "gpt-4o-mini", > > messages: [{ role: "user", content: "Provide investment recommendations..." }], > > max_tokens: 100, > > }); > > > > // Call 3: Create summary > > const summary = await openai.chat.completions.create({ > > model: "gpt-4o-mini", > > messages: [{ role: "user", content: "Summarize the analysis..." }], > > max_tokens: 50, > > }); > > > > // Redeem with margin using batch method > > // The margin is applied to the total API cost of all three calls > > const marginPercent = 0.2; // 20% markup on total API costs > > await payments.requests.redeemWithMarginFromBatchRequest( > > agentRequest.agentRequestId, > > requestAccessToken, > > marginPercent > > ); > > > > res.json({ > > analysis: analysis.choices[0]?.message?.content, > > recommendations: recommendations.choices[0]?.message?.content, > > summary: summary.choices[0]?.message?.content, > > }); > > ``` > > > [tab] Python > > > > ```python theme={null} > > # Use batch processing - all operations will share the same agent request ID > > agent_request = payments.requests.start_processing_batch_request( > > os.getenv("AGENT_ID"), > > authorization, > > "/ask", > > "POST" > > ) > > > > # Check user has sufficient balance > > if not agent_request.balance.is_subscriber or agent_request.balance.balance < 1: > > raise HTTPException(status_code=402, detail="Payment Required") > > > > request_access_token = authorization.replace("Bearer ", "", 1) > > > > # Create OpenAI client with observability > > openai_config = payments.observability.with_openai( > > os.getenv("OPENAI_API_KEY"), > > agent_request, > > {"operation": "batch_analysis"} > > ) > > > > openai_client = openai.OpenAI(**asdict(openai_config)) > > > > # Make multiple AI calls in the same batch > > # Call 1: Analyze user query > > analysis = openai_client.chat.completions.create( > > model="gpt-4o-mini", > > messages=[{"role": "user", "content": "Analyze this investment strategy..."}], > > max_tokens=100, > > ) > > > > # Call 2: Generate recommendations > > recommendations = openai_client.chat.completions.create( > > model="gpt-4o-mini", > > messages=[{"role": "user", "content": "Provide investment recommendations..."}], > > max_tokens=100, > > ) > > > > # Call 3: Create summary > > summary = openai_client.chat.completions.create( > > model="gpt-4o-mini", > > messages=[{"role": "user", "content": "Summarize the analysis..."}], > > max_tokens=50, > > ) > > > > # Redeem with margin using batch method > > # The margin is applied to the total API cost of all three calls > > margin_percent = 0.2 # 20% markup on total API costs > > payments.requests.redeem_with_margin_from_batch_request( > > agent_request.agent_request_id, > > request_access_token, > > margin_percent > > ) > > > > return { > > "analysis": analysis.choices[0].message.content, > > "recommendations": recommendations.choices[0].message.content, > > "summary": summary.choices[0].message.content, > > } > > ``` ## Monitoring and Analytics ### Events Log Table The frontend provides a comprehensive events log table showing: ![Events Log Table](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/events-log-table.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=45f730e803fe364cf025b631d94ea90b) *Screenshot of the events log table showing detailed request information, timestamps, costs, and status* ![Events Log Table Detailed View](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/events-log-table-detailed.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=83bf536493f655084298b1616db4b647) *Screenshot of the events log table showing details of a specific request* #### Key Metrics Tracked The observability integration automatically tracks: * **Timestamp**: When each request was made * **User**: Account address and session information * **Agent**: Agent name and operation type * **Request**: Input query and context * **Response**: AI-generated response * **Cost Analysis**: Credit consumption and cost per request * **Status**: Success/failure status * **Performance Metrics**: Response times, success rates, error rates, token usage, and more ### Data Analytics Dashboard Once your agent is running with observability enabled, you can view detailed data analytics in the Nevermined dashboard: ![Data Analytics Dashboard](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/analytics-dashboard-overview.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=22097321b69edf07e81a437d76135215) *Screenshot showing the Nevermined analytics dashboard* ![Data Analytics Dashboard Cumulative Analysis](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/analytics-dashboard-cumulative-analysis.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=0019f01b3da8c6c0475c196d187605b3) *Screenshot showing the Nevermined analytics dashboard cumulative analysis* ![Data Analytics Dashboard Summary Analysis](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/analytics-dashboard-summary-analysis.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=2681bb5a634f8878290aca600e9489d2) *Screenshot showing the Nevermined analytics dashboard summary analysis* #### Key Metrics Tracked The observability integration automatically tracks: * **Per Request Analysis**: Cost, credit revenue, PnL, by agent, model, and more * **Cumulative Analysis**: Cost, credit revenue, PnL, by agent, model, and more * **Summary Analysis**: Cost, credit revenue, PnL, by agent, model, and more ### Filtering and Search Use the built-in filtering capabilities to analyze specific patterns: ![Event Log Filtering Options](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/events-log-filtering.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=4bd4d542660c9ff790267e20cdcd49a9) *Screenshot showing filtering options for date range, agent type, user, and more* ![Data Analytics Filtering Options](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/data-analytics-filtering.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=7d0c39c2566e2e55841e416deed5fd95) *Screenshot showing filtering options for agent, model, provider, and more* ## Next Steps > [card] [Process Requests](/docs/integrate/patterns/validate-requests) > > Learn how to handle and validate paid requests in your agents > [card] [Query Agents](/docs/development-guide/nevermined-x402) > > Learn how to query AI agents programmatically # Buy & Call a Paid Agent Source: https://nevermined.ai/docs/getting-started/ai-agent-purchase The subscriber path on Nevermined: buy and use a paid agent without registering anything. Get an API key, add a payment method, buy plan credits, and call the agent via x402 — as a human or an autonomous agent. This is the **subscriber path** — how you, or an autonomous agent acting for you, discover a Nevermined-monetized service and pay for it. It runs the same whether a human clicks through or a coding agent like Claude Code does it end to end. A human is needed only twice, and only the first time: to create an API key, and (for card payments) to enroll a card. Everything after that is programmatic and reusable. > [!NOTE] > > **Buying a service? You don't register anything.** Registering an agent, exposing protected endpoints, and creating a plan are all *seller* tasks — skip them. As a subscriber you need a **Nevermined API key** (created once via a one-time human sign-in — an agent can [capture it automatically via a localhost callback](/docs/agents-guide/get-api-key) — then stored and reused), a **payment method with a spending delegation** (a funded stablecoin wallet or an enrolled card, plus a capped budget the agent can charge — the steps below set this up, and minting a token requires it), and the **plan ID** you want to buy. Publishing an agent *for sale* instead? See [Register a plan & agent](/docs/agents-guide/register-plan-and-agent). > [!WARNING] > > **Always pay through the x402 flow** (`verify` → `settle`). Never call Stripe or any other payment processor directly. x402 is the only supported payment path, and it works the same whether you pay with a card or with stablecoins. ## See it in action Watch an autonomous agent run this exact flow end to end — discover an organization, get a payment method, and buy plan credits with x402: [AI agents buy access autonomously via Nevermined](https://www.youtube.com/embed/C_aIQErhs6M) An AI agent buying plan credits autonomously via Nevermined. ### Try it yourself Hand this prompt to any coding agent (Claude Code, Cursor, an OpenAI agent — anything that can read a URL and run code). It points the agent at one organization's discovery file and tells it to figure out the rest on its own, exactly as a first-time agent would: ```text theme={null} You are a user who wants to purchase the "Acme Gold Plan" for $10 via Nevermined. Here are the instructions. Try to do it, and tell me when you are able to demonstrate that you purchased the plan and received the credits: https://api.sandbox.nevermined.app/api/v1/organizations/org-9d81acea-7d38-460e-b7c0-c3b92abcbb07/agentic-instructions.md Do not use any locally installed Nevermined CLI or prior knowledge about Nevermined. It's important to simulate how an agent new to Nevermined would resolve this using only the information in the agentic-instructions.md file. ``` > [!NOTE] > > This points at **Sandbox**, so no real money moves. Swap in your own organization's `agentic-instructions.md` URL to run it against your own plans. ## What you'll do > [card] 1. Discover > > Read an organization's agent-discoverable instructions to learn its plans, agents, and which environment you're in. > [card] 2. Log in > > Get a Nevermined API Key (one-time, human), then store and reuse it. > [card] 3. Get a payment method > > Use the stablecoin method created for you, or enroll a card via the embedded flow. > [card] 4. Delegate & buy > > Authorize a spending budget, then buy plan credits with x402. ## Sandbox vs. Live Nevermined runs two environments. Develop against **Sandbox**, then switch to **Live**. | Environment | Money | API base URL | Web app | | - | - | - | - | | **Sandbox** | Test only — no real charges | `https://api.sandbox.nevermined.app/api/v1` | [nevermined.app](https://nevermined.app) | | **Live** | Real charges | `https://api.live.nevermined.app/api/v1` | [nevermined.app](https://nevermined.app) | API keys are environment-specific: Sandbox keys start with `sandbox:`, Live keys with `live:`. Use the key that matches the environment you're calling. ## The flow **1. Discover what an organization sells** Every organization exposes two agent-discoverable files. Start here — they tell you the plans, the agents, and **which environment you're in**: * `GET {API_BASE}/organizations/{orgId}/agentic-instructions.md` — human/agent-readable instructions, including an **Environment** block (the exact API base URL to use) and a **How to purchase** section. * `GET {API_BASE}/organizations/{orgId}/llms.txt` — a compact index of plans, agents, and reference links. Both are plain text and need no authentication. Use the **API base URL printed in the Environment block** for every later call, and grab the per-environment OpenAPI reference at `{API_BASE}/rest/docs-json` (human-browsable UI at `{API_BASE}/rest/docs`). **2. Get a Nevermined API Key (one-time, needs a human)** On the **self-serve** path you can't mint the first key yourself — a human creates it in the web app. Ask them to follow [Get Your API Key](/docs/agents-guide/get-api-key): sign in at [nevermined.app](https://nevermined.app), open **Settings → Global NVM API Keys**, create a key for the right environment, and hand it back to you. > [!NOTE] > > **Being onboarded by an organization?** If a business is provisioning you as a white-label customer, it creates your account and a scoped key for you **programmatically** — there's no web-app step on your side. See [White-label Customer Onboarding](/docs/solutions/organizations/white-label-onboarding). **Store it and reuse it** — you don't need a new key per request. Keep it in an environment variable and initialize the SDK once: > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY, // "sandbox:..." or "live:..." > environment: 'sandbox', > }) > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_API_KEY"], # "sandbox:..." or "live:..." > environment="sandbox", > ) > ) > ``` > [!NOTE] > > Send the key as `Authorization: Bearer ` if you're calling the REST API directly instead of the SDK. **3. Pick how you'll pay** List the payment methods available to your account: ```http theme={null} GET {API_BASE}/payment-methods Authorization: Bearer ``` * **Stablecoin (no human needed):** your account's smart-account wallet — an ERC-4337 wallet provisioned for you — appears here as a `Crypto Wallet` payment method. Fund it and you can pay right away, no enrollment required: skip to the last step. * **Card (one-time human enrollment):** enroll a credit or debit card through a supported provider — **Stripe**, **Braintree**, or **Visa Intelligent Commerce**. Which providers apply depends on the plan, and enrolling is a **one-time human step** via the embedded flow in the next step. A plan is paid either by stablecoin **or** by card — never both. To know which (and, for cards, which provider), resolve it from the plan before you choose: see [Which payment type does this plan need?](/docs/getting-started/core-concepts#fiat-vs-crypto-what-each-plan-needs). **4. Enroll a card and delegate a budget (embedded flow, no CLI)** To pay by card, a human enrolls one once and grants you a **delegation** — a spending budget with a hard limit and expiry. Drive it with the embedded redirect handshake (no CLI, any language): 1. **Mint a session** with your API key: ```http theme={null} POST {API_BASE}/embed/session Authorization: Bearer Content-Type: application/json { "returnUrl": "http://127.0.0.1:/callback" } ``` The response carries a `sessionToken`. This open endpoint needs no organization — it's the path for autonomous agents, and the card attaches to your own account. It only accepts a **localhost** `returnUrl`, so run a tiny one-shot callback server on `127.0.0.1` first. (Org members, e.g. the `nevermined` CLI, use the org-scoped `POST {API_BASE}/widgets/session/self` with `{ orgId, returnUrl }` instead.) 2. **Hand the human a URL** to complete card setup in their browser: ``` https://embed.nevermined.app/cards/setup ?sessionToken= &returnUrl=http://127.0.0.1:/callback &state= &provider=stripe ``` 3. **Receive the result.** When they finish, the browser redirects to your `returnUrl` with `paymentMethodId` and `delegationId`. Verify the `state` echo, then store the `delegationId`. > [!NOTE] > > Full handshake (callback server, `state`/CSRF, `returnUrl` rules) and the alternatives — embedding the widget in your own page, or enrolling directly in the app — are in [Card Delegation](/docs/solutions/card-delegation) and [Card Enrollment](/docs/products/payments/card-enrollment). If you can't host a localhost callback, ask the human to enroll a card and create a delegation directly at [nevermined.app](https://nevermined.app) (**Payment Methods → Enroll card → Delegate**), then continue. **5. Pay with x402** Mint an x402 access token for the plan, then send it in the `payment-signature` header. Each plan uses one of two schemes, and you tell the SDK which budget to charge through `delegationConfig`: * **`nvm:card-delegation`** (your delegated card) — pass `scheme: 'nvm:card-delegation'` and the `delegationId` you stored during enrollment. Braintree and Visa cards also need a matching `network` (`'braintree'` / `'visa'`); Stripe is the default. * **`nvm:erc4337`** (stablecoins) — the default scheme, so you can omit `scheme`. Create a delegation first with `createDelegation` (`provider: 'erc4337'`, `currency: 'usdc'`, a `spendingLimitCents` + `durationSecs` budget), then request the token by its `delegationId`. Either way the token charges through the `verify` → `settle` flow. > [tab] TypeScript > > ```typescript theme={null} > // Card (nvm:card-delegation): reuse the delegation you created during enrollment. > const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, { > scheme: 'nvm:card-delegation', > delegationConfig: { delegationId }, > }) > > // Stablecoin (nvm:erc4337, the default scheme): create a delegation first, > // then request the token by its delegationId. > // const delegation = await payments.delegation.createDelegation({ > // provider: 'erc4337', spendingLimitCents: 10000, durationSecs: 604800, currency: 'usdc', // $100 / 7 days > // }) > // const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, { > // delegationConfig: { delegationId: delegation.delegationId }, > // }) > > // Call the paid agent — x402 endpoints read the token from the payment-signature header > await fetch('https://the-agent.example.com/task', { > method: 'POST', > headers: { 'payment-signature': accessToken }, > }) > ``` > [tab] Python > > ```python theme={null} > import requests > from payments_py.x402 import CreateDelegationPayload, DelegationConfig, X402TokenOptions > > # Card (nvm:card-delegation): reuse the delegation you created during enrollment. > result = payments.x402.get_x402_access_token( > plan_id, > agent_id, > token_options=X402TokenOptions( > scheme="nvm:card-delegation", > delegation_config=DelegationConfig(delegation_id=delegation_id), > ), > ) > > # Stablecoin (nvm:erc4337, the default scheme): create a delegation first, > # then request the token by its delegation_id. > # delegation = payments.delegation.create_delegation( > # CreateDelegationPayload( > # provider="erc4337", spending_limit_cents=10000, duration_secs=604800, currency="usdc", > # ) > # ) > # result = payments.x402.get_x402_access_token( > # plan_id, > # agent_id, > # token_options=X402TokenOptions( > # delegation_config=DelegationConfig(delegation_id=delegation.delegation_id) > # ), > # ) > > # Call the paid agent — x402 endpoints read the token from the payment-signature header > requests.post( > "https://the-agent.example.com/task", > headers={"payment-signature": result["accessToken"]}, > ) > ``` The agent's x402 middleware verifies and settles each request, burning credits as you go. Check your remaining balance anytime: > [tab] TypeScript > > ```typescript theme={null} > const balance = await payments.plans.getPlanBalance(planId) > console.log(`Credits: ${balance.balance}`) // e.g. "100" > ``` > [tab] Python > > ```python theme={null} > balance = payments.plans.get_plan_balance(plan_id) > print(f"Credits: {balance['balance']}") > ``` > [!NOTE] > > Prefer to gate your *own* API, build the `payment-required` challenge, or call `verifyPermissions` / `settlePermissions` directly? See [Nevermined x402](/docs/development-guide/nevermined-x402) and [Validate Requests](/docs/integrate/patterns/validate-requests). For stablecoin plans you can also buy credits upfront with [`orderPlan`](/docs/integrate/patterns/top-up). ## Reuse and good practices * **Reuse the API key.** It doesn't expire per request — store it once and reuse it. * **Reuse the delegation.** A delegation is good until its budget is spent or it expires. Don't re-enroll a card for every purchase. * **Top up, don't re-buy.** Check `getPlanBalance` and order more credits when you run low. * **Match the environment.** A `sandbox:` key only works against the Sandbox API base URL, and `live:` only against Live. ## Related > [card] [Card Delegation](/docs/solutions/card-delegation) > > The full embedded card-enrollment + delegation handshake, in any language. > [card] [Nevermined x402](/docs/development-guide/nevermined-x402) > > The x402 payment protocol: schemes, headers, verify/settle. > [card] [Get Your API Key](/docs/agents-guide/get-api-key) > > Create and manage Nevermined API keys. > [card] [Agent-to-Agent Monetization](/docs/solutions/agent-to-agent-monetization) > > Let your own agent get paid by other agents. # Core Concepts Source: https://nevermined.ai/docs/getting-started/core-concepts Learn how Nevermined adds payments and access control to AI agents, MCP tools, and static assets with payment plans, metering, and per-request entitlement. Nevermined adds a payment and entitlement layer to any **monetizable service** (agent APIs, MCP tools, or static assets). Attach a **payment plan** and each inbound request is validated, metered, and settled in real time. No checkout flows, no manual invoicing, no distinction between human and agent callers. ## What Can You Monetize? Nevermined validates each inbound request against the caller’s entitlement before your code runs: * **Agent APIs** - AI agents exposed as HTTP endpoints (REST, webhooks, etc.) * **MCP Tools** - tool endpoints served via the Model Context Protocol * **Static Assets** - gated resources like files, datasets, or downloads Every monetizable service has: * A **public endpoint** (the URL callers hit) * A **payment plan** (pricing and access terms) * A **validation step** (Nevermined checks entitlement per request) * **Usage tracking** (automatic metering on every call) ## Standards and protocols (x402 and MPP) Nevermined supports modern payment standards used in agentic commerce. **x402** standardizes how clients and servers negotiate payment-required requests over HTTP headers. Its sibling, the **Merchant Payment Protocol (MPP)**, negotiates the same payment with an RFC 7235 `WWW-Authenticate: Payment` challenge. Both settle against the **same Payment Plans and credits** — the protocol is just the wire handshake. If you're integrating with x402- or MPP-compatible clients/servers, see the [x402 integration and its MPP sibling](/docs/development-guide/nevermined-x402). ## What is a Payment Plan? A payment plan defines how users pay and what they're entitled to consume: > [card] Payment Method > > [**Cards**](/docs/products/payments/overview) (Visa, Stripe, or Braintree) or [**Crypto**](/docs/integrate/patterns/stablecoin-payments) (USDC, EURC on-chain). > [card] Pricing Model > > **Fixed** (same cost per call) or **Dynamic** (builder-defined per request, or cost+margin). > [card] Plan Type > > **Prepaid** (buy upfront) or **Pay-as-you-go** (charge per request). > [card] Payouts > > Merchants receive fiat payouts via [Stripe Connect](https://stripe.com/connect) or crypto directly to their wallet. Connect your account in the [Nevermined App](https://nevermined.app). > [accordion] Prepaid plans > > Users buy a plan upfront. Each API call deducts from their balance: > > * **Fixed pricing**: every request costs the same (e.g., \$10 for 100 requests at \$0.10 each) > * **Dynamic pricing**: charge different amounts per request based on complexity, or apply cost+margin automatically > [accordion] Pay-as-you-go > > No upfront purchase. Charge the user's card or wallet on each request: > > * **Cards**: agents charge via [card delegation](/docs/products/payments/overview) > * **Crypto**: settle in USDC or EURC on-chain > [accordion] Time-limited plans > > Add expiration to any plan: > > * **Duration**: set expiry (days, months, years) > * **Hybrid**: combine usage limits with time limits (e.g., 1,000 requests valid for 30 days) > [accordion] Outcome-based pricing > > Charge on success: meetings booked, leads qualified, issues resolved. Only bill when your agent delivers a defined outcome or milestone. ### Examples * **Customer Support Agent**: \$49/month unlimited, or \$10 for 1,000 calls * **Dataset Access**: \$99 for 30-day access * **Agent API**: \$0.10/call prepaid, or \$0.15/call PAYG * **Sales Agent**: \$5 per qualified lead (outcome-based) ## How It All Works Together **1. Register your API** Define your service interface and metadata using the Payments SDK. **2. Create a payment plan** Set payment method, pricing model, and plan type using the Payments SDK. **3. Users or agents purchase access** Purchase a prepaid or pay-as-you-go plan, paid with [card](/docs/products/payments/overview) or crypto. **4. Validate before delivery** Validate entitlement before serving requests or granting access. **5. Track and settle** Automatically track usage per request and settle payments. ## Payment Methods > [card] [Cards](/docs/products/payments/overview) > > Pay with real Visa, Stripe, or Braintree cards via [card delegation](/docs/products/payments/overview). Agents charge against spending delegations with lifetime limits, usage caps, and (for Visa) per-delegation WebAuthn/passkey device binding. No crypto wallet needed. > [card] [Crypto](/docs/integrate/patterns/stablecoin-payments) > > USDC, EURC, or any ERC-20 token on-chain. Lowest fees and full transparency for crypto-native users. ### Fiat vs crypto: what each plan needs A plan is paid for in **one** of two ways — fiat (card) or crypto — and each needs different setup before you can pay. A plan is never both. Check the type up front, so you don't enroll a card for a crypto plan or try to pay a card plan from a wallet: | | **Fiat plan** (`nvm:card-delegation`) | **Crypto plan** (`nvm:erc4337`) | | - | - | - | | **What the buyer needs** | An enrolled card with the plan's provider | A smart account funded with the plan's token | | **Set up** | [Enroll a card](/docs/products/payments/card-enrollment) — Stripe, Braintree, or Visa | Fund the account with USDC / EURC | | **Delegation** | `provider: 'stripe'` (or `braintree` / `visa`), `currency: 'usd'` | `provider: 'erc4337'`, `currency: 'usdc'` | | **Token scheme** | pass `scheme: 'nvm:card-delegation'` | `scheme: 'nvm:erc4337'` (the default) | | **Detect in code** | `resolveScheme()` / `resolve_scheme()` → `nvm:card-delegation` | → `nvm:erc4337` | The type comes from the plan's pricing config — `registry.price.isCrypto`, and for fiat plans `metadata.plan.fiatPaymentProvider` names the provider. Rather than read that metadata yourself, let the SDK resolve it. `resolveScheme()` / `resolve_scheme()` fetches the plan (cached for 5 minutes) and returns the scheme: > [tab] TypeScript > > ```typescript theme={null} > import { Payments, resolveScheme } from '@nevermined-io/payments' > > const scheme = await resolveScheme(payments, planId) > // 'nvm:erc4337' (crypto) or 'nvm:card-delegation' (fiat) > ``` > [tab] Python > > ```python theme={null} > from payments_py.x402.resolve_scheme import resolve_scheme > > scheme = resolve_scheme(payments, plan_id) > # 'nvm:erc4337' (crypto) or 'nvm:card-delegation' (fiat) > ``` > [!NOTE] > > Server-side middleware (Express, FastAPI) and the A2A clients resolve the scheme for you. The direct `getX402AccessToken` / `get_x402_access_token` call does **not** — it defaults to `nvm:erc4337`. For a fiat plan you must pass `scheme: 'nvm:card-delegation'` and have a card enrolled with the matching provider. See [Payment method mismatch](/docs/products/payments/faq#how-do-i-fix-a-payment-method-mismatch) if a payment is rejected. ## Merchant Onboarding > [card] Payouts > > Merchants receive fiat payouts via [Stripe Connect](https://stripe.com/connect) or crypto directly to their wallet. Connect your account in the [Nevermined App](https://nevermined.app). > [card] Security & Compliance > > ISO 27001, SOC 2 Type II, PCI SAQ-D, GDPR compliant. Card data captured via PCI Level 1 infrastructure (VGS). Nevermined never stores raw card numbers. ## Next steps Building an **AI agent that needs to pay** for services? Follow [AI Agents: Buy Access Autonomously](/docs/getting-started/ai-agent-purchase) — get an API key, enroll a card, delegate a budget, and make an x402 purchase end to end. # Overview Source: https://nevermined.ai/docs/getting-started/overview Nevermined is building the financial rails for AI. Monetize agents and enable autonomous agent-to-agent payments with real cards. AI agents need to pay and get paid, but traditional payment infrastructure wasn't built for that. Three problems stand in the way: * **Agents can't spend autonomously** - no way to delegate a real payment method with controlled limits * **Sellers can't accept agentic payments** - no metering, no per-request settlement, no programmatic access control * **Everyone's locked to one provider** - rigid integrations that don't work across frameworks or payment processors Nevermined solves all three. Put a payment gate in front of any API, charge per request, and settle automatically. You handle the AI, we handle the rest. > [card] [Get started](/docs/integrate/quickstart/5-minute-setup) > > Launch an integration in 5 minutes > [card] [API Reference](/docs/api-reference/introduction) > > Explore the REST API and SDKs > [card] [For AI agents](/docs/getting-started/ai-agent-purchase) > > Go from zero to an autonomous x402 purchase ## How It Works ![Diagram: a buyer enrolls a payment method once, then their agent's request to a seller's service is verified and settled by Nevermined — credits charged, seller paid — and the response returns to the buyer's agent.](https://mintcdn.com/neverminedag/ORkCyzvqc5-Zuu91/images/payment-flow.png?fit=max\&auto=format\&n=ORkCyzvqc5-Zuu91\&q=85\&s=74c5ff09cbb849c4ff80b3e63109c542) **1. Register your API** Any HTTP endpoint your agent exposes. Nevermined gates access at the request level - if a caller isn't entitled, they get a 402 before your code even runs. **2. Create a payment plan** * **Payment method** - Fiat ([cards](/docs/products/payments/overview)) or crypto (USDC) * **Pricing model** - Fixed per call, or dynamic (seller-defined or cost+margin) * **Plan type** - Prepaid (buyers buy a plan upfront) or pay-as-you-go (charge per request) **3. Validate, deliver, settle** Entitled? Deliver and settle. Not entitled? Return **402 Payment Required**. **Sellers** register API endpoints, set pricing per call, and receive payouts. Add a few lines of validation to your server. **Buyers** purchase a plan (fiat or crypto) or go pay-as-you-go. No human in the loop. ## Use Cases > [card] [Agent Monetization](/docs/solutions/agent-to-agent-monetization) > > Meter and settle between autonomous agents > [card] [Tool Monetization](/docs/solutions/mcp-point-of-sales) > > Charge for tools and APIs with per-request billing > [card] [Agent Card Payments](/docs/products/payments/overview) > > Let agents pay with real cards via card delegation > [card] [Static Assets](/docs/solutions/access-control-monetization-static-resources) > > Gate datasets, models, and downloadable resources ## What You Can Monetize > [accordion] Customer Support Agents > > Deploy AI customer service agents with per-ticket billing, resolution-based pricing, or monthly support packages. > [accordion] Legal Assistants > > Monetize AI legal research and document analysis with per-query pricing or case-based packages. > [accordion] Sales Automation Agents > > AI sales assistants that qualify leads and schedule meetings with performance-based pricing. > [accordion] AI Chat Services > > Conversational AI with per-message billing, token packages, or subscription tiers. > [accordion] Code Analysis Tools > > AI-powered code reviews, security scans, and optimization with per-repo or subscription pricing. > [accordion] Computer Vision APIs > > Vision services with dynamic pricing based on resolution, complexity, or analysis depth. > [accordion] Translation Services > > AI translation and localization with pricing based on word count or language complexity. > [accordion] Data Analysis Agents > > Analytics services with pricing based on dataset size and analysis complexity. ## What Nevermined Handles | Concern | What you get | | - | - | | Payment processing | Fiat ([card delegation](/docs/products/payments/overview)) and crypto (USDC on-chain) | | Access control | Gate API access per request via plans and x402 | | Usage metering | Per-request tracking and settlement | | Settlement | Automatic payouts to sellers | ## Integration Options Nevermined is framework-agnostic. It works with LangChain, CrewAI, Strands, OpenAI Agents, or plain HTTP. * **Code-first** - TypeScript and Python SDKs, REST API, and CLI for full programmatic control * **[Nevermined App](https://nevermined.app)** - Card enrollment (Visa / Stripe / Braintree) and spending delegation management ### Seller Onboarding Use the [Nevermined App](https://nevermined.app) for reporting, analytics, and plan management. To receive fiat payouts, connect a Stripe Connect account there. Stablecoin payouts settle directly to your wallet. ## Next Steps > [card] [Core Concepts](/docs/getting-started/core-concepts) > > Understand the platform terminology and building blocks > [card] [5-Minute Setup](/docs/integrate/quickstart/5-minute-setup) > > Build your first integration end to end > [card] [Payments](/docs/products/payments/overview) > > Set up agent card payments with Visa, Stripe, or Braintree > [card] [SDKs & API](/docs/api-reference/introduction) > > TypeScript, Python, and REST API reference # AgentCore Source: https://nevermined.ai/docs/integrate/add-to-your-agent/agentcore Add Nevermined x402 payments to agents running on AWS Bedrock AgentCore > [!NOTE] > > **Start here:** need to register a service and create a plan first? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). Add payment protection to agents running on [Amazon Bedrock AgentCore](https://docs.aws.amazon.com/bedrock-agentcore/) using the [x402 protocol](https://github.com/coinbase/x402). The `@requires_payment` decorator handles verification and settlement automatically, wrapping verify - work - settle in a single Lambda invocation. ## x402 Payment Flow ```mermaid theme={null} sequenceDiagram autonumber actor Client participant Agent as Agent (Lambda)
@requires_payment participant Facilitator as Nevermined Facilitator Client->>Agent: Call agent — no payment-signature Agent-->>Client: 402 PaymentRequired
(payment-required header, base64 JSON) Note over Client: Decode PaymentRequired,
extract planId from accepts[] Client->>Facilitator: get_x402_access_token(plan_id) Facilitator-->>Client: accessToken Client->>Agent: Call agent with payment-signature header Agent->>Facilitator: verify_permissions(token, credits) Facilitator-->>Agent: Verification OK Note over Agent: Execute handler (agent work) Agent->>Facilitator: settle_permissions(token, credits) Facilitator-->>Agent: Settlement OK (creditsRedeemed, tx) Agent-->>Client: Response + payment-response header
(settlement receipt, base64 JSON) ``` ## MCP Event Format AgentCore communicates using [MCP JSON-RPC 2.0](https://modelcontextprotocol.io/specification/2025-03-26). The decorator expects the AgentCore Gateway interceptor event format: ```json theme={null} { "mcp": { "gatewayRequest": { "httpMethod": "POST", "headers": { "payment-signature": "", "Content-Type": "application/json" }, "body": { "jsonrpc": "2.0", "id": "req-1", "method": "tools/call", "params": { "name": "TargetName___toolName", "arguments": { "patient_id": "123" } } } } } } ``` Key points: * The x402 token travels in the `payment-signature` HTTP header * Tool names follow AgentCore convention: `TargetName___toolName` * Only `tools/call` method is billable by default ## Installation ```bash theme={null} pip install payments-py ``` See the [Python SDK installation guide](/docs/api-reference/python/installation) for full setup details. > [!NOTE] > > No extra dependencies required. The AgentCore decorator uses only the core `payments-py` package. ## Quick Start: Protecting a Lambda Handler The `@requires_payment` decorator wraps a Lambda handler with x402 payment verification and settlement. ```python filename="lambda_function.py" theme={null} import json import os from payments_py import Payments, PaymentOptions from payments_py.x402.agentcore import requires_payment # Initialize Payments payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), ) ) PLAN_ID = os.environ["NVM_PLAN_ID"] AGENT_ID = os.environ.get("NVM_AGENT_ID") @requires_payment( payments=payments, plan_id=PLAN_ID, agent_id=AGENT_ID, credits=1, endpoint="https://gateway.bedrock-agentcore.amazonaws.com/mcp", ) def lambda_handler(event, context=None): """Handler only runs when payment is verified.""" body = event["mcp"]["gatewayRequest"]["body"] tool = body["params"]["name"] args = body["params"]["arguments"] # Agent work result = process_request(tool, args) return { "content": [{"type": "text", "text": json.dumps(result)}], } ``` The decorator automatically: * Returns a `402 PaymentRequired` response when no token is provided * Verifies the x402 token via the Nevermined facilitator * Executes the handler on successful verification * Burns credits after successful execution * Adds `payment-response` header and `_meta.x402` transaction data to the response ## Response Formats The handler can return any of these formats: ### Bare MCP result (simplest) ```python theme={null} return { "content": [{"type": "text", "text": "Hello!"}], } ``` ### With credits override ```python theme={null} return { "content": [{"type": "text", "text": "Expensive result"}], "_meta": {"creditsToCharge": 5}, # Override the decorator's credits } ``` ### Full MCP response body ```python theme={null} return { "jsonrpc": "2.0", "id": "req-1", "result": { "content": [{"type": "text", "text": "Hello!"}], }, } ``` ### Complete InterceptorOutput ```python theme={null} return { "interceptorOutputVersion": "1.0", "mcp": { "transformedGatewayResponse": { "statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": {"jsonrpc": "2.0", "id": "req-1", "result": {...}}, } }, } ``` The decorator wraps and enriches all formats with payment-response headers and `_meta.x402` transaction data. ## Credits Flow ```mermaid theme={null} flowchart TD A["Decorator config: credits=1"] --> B["VERIFY: does subscriber have at least 1 credit?"] B --> C["EXECUTE: handler runs, returns response"] C --> D{"Response has
_meta.creditsToCharge?"} D -->|"Yes (e.g. 5)"| E["SETTLE: burn 5 credits"] D -->|"No"| F["SETTLE: burn 1 credit (config default)"] ``` The `credits` parameter is used for both verify (pre-flight check) and settle (default burn amount). The handler can override the settle amount by returning `_meta.creditsToCharge` in its response. ## Decorator Configuration ### Basic ```python theme={null} @requires_payment(payments=payments, plan_id="plan-123", credits=1) def handler(event, context=None): ... ``` ### With Agent ID ```python theme={null} @requires_payment( payments=payments, plan_id=PLAN_ID, credits=1, agent_id=os.environ.get("NVM_AGENT_ID"), endpoint="https://my-gateway.amazonaws.com/mcp", ) def handler(event, context=None): ... ``` ### Dynamic Credits Calculate credits based on the event: ```python theme={null} def calc_credits(event): """Charge based on request complexity.""" args = ( event.get("mcp", {}) .get("gatewayRequest", {}) .get("body", {}) .get("params", {}) .get("arguments", {}) ) return 10 if args.get("detailed") else 1 @requires_payment(payments=payments, plan_id=PLAN_ID, credits=calc_credits) def handler(event, context=None): ... ``` ### Custom Token Header ```python theme={null} @requires_payment( payments=payments, plan_id=PLAN_ID, credits=1, token_header="X-Payment", # Or a list: ["X-Payment", "Authorization"] ) def handler(event, context=None): ... ``` ### Lifecycle Hooks ```python theme={null} def on_before_verify(payment_required): print(f"Verifying payment for plan {payment_required.accepts[0].plan_id}") def on_after_verify(verification): print(f"Verified! Payer: {verification.payer}") def on_after_settle(credits_used, settlement): print(f"Settled {credits_used} credits, tx: {settlement.transaction}") def on_payment_error(error): # Return custom error response or None for default 402 return None @requires_payment( payments=payments, plan_id=PLAN_ID, credits=1, on_before_verify=on_before_verify, on_after_verify=on_after_verify, on_after_settle=on_after_settle, on_payment_error=on_payment_error, ) def handler(event, context=None): ... ``` ## Client Implementation ```python filename="client.py" theme={null} import os import requests from payments_py import Payments, PaymentOptions from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload # Initialize Payments as subscriber payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_SUBSCRIBER_API_KEY"], environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), ) ) PLAN_ID = os.environ["NVM_PLAN_ID"] AGENT_ID = os.environ.get("NVM_AGENT_ID") # Step 1: Check balance balance = payments.plans.get_plan_balance(plan_id=PLAN_ID) print(f"Balance: {balance.balance} credits") # Step 2: Get x402 access token # Create a delegation once, then reuse its id to mint tokens. delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="erc4337", # "stripe" | "braintree" | "visa" for fiat plans spending_limit_cents=10000, # $100 budget duration_secs=604800, # 7 days currency="usdc", # "usd" for fiat plans ) ) token_result = payments.x402.get_x402_access_token( plan_id=PLAN_ID, agent_id=AGENT_ID, token_options=X402TokenOptions( scheme="nvm:erc4337", # "nvm:card-delegation" for fiat plans delegation_config=DelegationConfig(delegation_id=delegation.delegation_id) ), ) access_token = token_result["accessToken"] # Step 3: Call the agent with the token in payment-signature header response = requests.post( "https://your-agent-endpoint.amazonaws.com/mcp", headers={ "Content-Type": "application/json", "payment-signature": access_token, }, json={ "jsonrpc": "2.0", "id": "1", "method": "tools/call", "params": { "name": "getPatient", "arguments": {"patient_id": "123"}, }, }, ) # Step 4: Check settlement receipt import base64, json payment_response = response.headers.get("payment-response") if payment_response: receipt = json.loads(base64.b64decode(payment_response)) print(f"Credits redeemed: {receipt['creditsRedeemed']}") print(f"Transaction: {receipt['transactionHash']}") ``` ## Decorator vs Interceptor `payments-py` provides two patterns for AgentCore payment protection: | | `@requires_payment` decorator | `AgentCoreInterceptor` class | | - | - | - | | **Invocations** | Single (verify + work + settle) | Two (REQUEST phase, RESPONSE phase) | | **Use case** | Agent IS the Lambda | Separate interceptor Lambda | | **Credits from response** | `_meta.creditsToCharge` override | `_meta.creditsToCharge` extraction | | **Complexity** | One decorator, one function | Separate interceptor + target Lambda | | **Gateway requirement** | Optional | Required (Gateway calls interceptor) | Use the **decorator** when your agent runs as a Lambda function and you want the simplest integration. Use the **interceptor** when you need a separate payment layer in front of an existing agent target (MCP server, OpenAPI, Lambda) via the AgentCore Gateway. ## Environment Variables ```bash filename=".env" theme={null} # Nevermined (required) NVM_API_KEY=sandbox:eyxxxx # sandbox:eyxxxx OR live:eyxxxx NVM_ENVIRONMENT=sandbox # sandbox OR live NVM_PLAN_ID=your-plan-id NVM_AGENT_ID=your-agent-id # Optional ``` ## Next Steps > [card] [Payment Patterns](/docs/integrate/patterns/charge-credits) > > Advanced credit charging patterns > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Deep dive into x402 payment flows > [card] [Strands Integration](/docs/integrate/add-to-your-agent/strands) > > Decorator for Strands AI agent tools > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Configure credits, subscriptions, and dynamic pricing # Deep Agents Source: https://nevermined.ai/docs/integrate/add-to-your-agent/deep-agents Charge for a capability that lives inside a Deep Agents subagent, using Nevermined x402 > [!NOTE] > > **Start here:** need to register a service and create a plan first? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). > [card] [Runnable tutorial](https://github.com/nevermined-io/tutorials/tree/main/langchain-deep-agent-py) > > **`langchain-deep-agent-py`** — a freemium market-research agent on the Deep > Agents harness, where the paid tool lives inside a subagent. Clone, fill in > `.env`, run `poetry run buyer` to watch the free path and the paid path > back to back. [Deep Agents](https://docs.langchain.com/oss/python/deepagents/overview) is LangChain's agent *harness*: `create_deep_agent()` returns a compiled LangGraph graph that already has planning, a filesystem, and subagent delegation built in. You reach for it when one agent needs to plan a job and hand pieces of it to specialists. **The Nevermined integration does not change.** `@requires_payment` works on a Deep Agents tool exactly as it does on a plain LangChain one — this page is about the one property that makes that true, and the two harness behaviours you should design around. ## The delegation hop A buyer supplies an x402 access token **once**, on the run: ```python theme={null} graph.invoke( {"messages": [{"role": "user", "content": "Research the EV market"}]}, config={"configurable": {"payment_token": access_token}}, ) ``` The supervisor never handles that token. It delegates through the built-in `task` tool, and LangGraph copies `configurable` down into the subagent's own tool calls — so the decorator finds the token one hop below where it was supplied: ``` main agent ──task()──▶ research-sub ──▶ market_research [PAID] ▲ │ └──────── x402 token supplied here ──────────┘ config.configurable.payment_token ``` This is the property the whole pattern rests on. A deep agent's premise is that the supervisor hands work to subagents; if payment context did not survive that hop, every paid tool would have to sit on the main agent and the harness would be useless for monetized capabilities. > [!NOTE] > > The buyer does not need to know the agent's internal topology. The contract is > the same one the [LangChain guide](/docs/integrate/add-to-your-agent/langchain) > describes — put the token on the run and let the graph route it. ## Quick start Give the paid tool **only** to the subagent, so every paid call has to cross a delegation boundary: ```python theme={null} from deepagents import create_deep_agent from langchain_core.runnables import RunnableConfig from langchain_core.tools import tool from payments_py import PaymentOptions, Payments from payments_py.x402.langchain import ( PaymentRequiredError, last_settlement, requires_payment, ) payments = Payments.get_instance(PaymentOptions(nvm_api_key=NVM_API_KEY)) @requires_payment(payments=payments, plan_id=PLAN_ID, credits=5) def _market_research_paid(topic: str, config: RunnableConfig) -> str: """verify_permissions runs before this body, settle_permissions after.""" return run_analyst(topic) @tool def market_research(topic: str, config: RunnableConfig) -> str: """Produce a market analysis on the given topic. PAID.""" try: # Forward `config` explicitly — the decorator reads the token from it. return _market_research_paid(topic, config=config) except PaymentRequiredError: return "PAYMENT_REQUIRED: authorize and ask again." research_subagent = { "name": "research-sub", "description": "Performs paid market research on a single topic.", "system_prompt": ( "Call `market_research` once and return its output verbatim. " "Never answer the research question from your own knowledge." ), "tools": [market_research], } graph = create_deep_agent( model="openai:gpt-4o-mini", tools=[], subagents=[research_subagent], system_prompt="Delegate every research request to `research-sub`.", ) ``` Because `create_deep_agent()` returns a compiled graph, deployment is unchanged — point `langgraph.json` at it and `langgraph dev` or LangSmith Deployment will serve it: ```json theme={null} { "dependencies": ["."], "graphs": { "deep_research": "./src/agent.py:graph" } } ``` ## Two harness behaviours to design around These are properties of the harness, not bugs. Both are worth handling before you put a deep agent in front of paying users. > [!WARNING] > > **A deep agent can bill several times per user turn.** The supervisor — not > you — decides how many subagent calls a request warrants, so a single user > message may settle credits more than once. Cap it explicitly rather than trusting the model to be frugal — but note **where a run's identity has to come from**. LangGraph does *not* put a run id in `config["configurable"]`. A tool sees only `thread_id`, checkpoint bookkeeping, and whatever the caller passed (verified against langgraph 1.2 / deepagents 0.7). Since `thread_id` is stable for a whole conversation, keying a "per-run" cap on it silently makes it per-*conversation*: after N paid calls the tool refuses forever, however many new questions the user asks. So the **caller** declares the run — it is the only party that knows where one ends: ```python theme={null} # buyer side: a fresh nonce per run, alongside the token "config": {"configurable": { "payment_token": token, "nvm_run_id": str(uuid.uuid4()), }} ``` ```python theme={null} # agent side: key on the nonce, fall back to thread_id, and say which is in force if not budget.try_consume(config): if budget.scope_of(config) == "run": return "BUDGET_EXHAUSTED: this run already used its paid-call allowance." return ("BUDGET_EXHAUSTED: this conversation already used its allowance. " "Pass a per-run `nvm_run_id` to scope the cap to one request.") ``` Two details that are easy to miss: * **Refund the reservation when a call raises `PaymentRequiredError`** — otherwise a user who authorizes mid-run gets fewer paid calls than they paid for. * **Bound the counter map.** The agent is a long-running server, so a plain dict keyed on run or thread grows for the life of the process. An LRU with a fixed ceiling is enough; evicting a key only refills that budget, so the worst case is a long-idle caller getting a fresh allowance rather than an over-charge. A browser chat UI whose proxy injects only the token will fall into the conversation-scoped case. That is the safe direction to fail — it under-spends, never over-spends — as long as the refusal message says so instead of promising a reset that will not happen. > [!NOTE] > > Counting from graph state via `InjectedState` looks like a tidier > alternative, and it does work inside a subagent tool — but it exposes the > **subagent's own** isolated conversation, which resets on every `task()` > hop. It therefore cannot see sibling delegations within a single turn, > which is exactly the case the cap exists for. > [!WARNING] > > **Two LLM layers can paraphrase the paid tool's output.** The subagent relays > to the supervisor, which relays to the user. A plain ReAct agent has one such > layer, so this is strictly worse. Instruct both system prompts to pass the tool's text through verbatim, and treat the tool's return value — not the chat reply — as the source of truth when you need the settlement receipt. There is a sharper version of the same problem worth testing for explicitly: a capable supervisor sometimes answers a research question **from its own knowledge** instead of delegating, silently giving the paid capability away for free. Forbid it in both prompts, and re-test that path whenever you change models — it is prompt-dependent, not structural. ## Version requirements `deepagents` requires the LangChain v1 stack (`langchain>=1.3.18`, `langchain-core>=1.6.1`). If your existing project pins an older `langchain-core`, give the deep agent its own virtualenv rather than upgrading around it. ```bash theme={null} pip install deepagents "payments-py[langsmith]" langchain-openai ``` ## Observability Set `LANGSMITH_TRACING=true` and `LANGSMITH_API_KEY` to emit `nvm:verify` and `nvm:settlement` spans. On a deep agent these nest under the `task` span, so you can see **which subagent hop incurred each charge** — which is exactly what you need when reasoning about the multi-billing behaviour above. ```bash theme={null} LANGSMITH_TRACING=true LANGSMITH_API_KEY=lsv2_... # Only needed if your LangSmith account is NOT in GCP US: # LANGSMITH_ENDPOINT=https://eu.api.smith.langchain.com ``` ## Which harness should I use? | | Plain LangGraph ReAct | Deep Agents | | - | - | - | | Constructor | `create_react_agent` | `create_deep_agent` | | Paid tool lives on | the agent itself | a subagent, one `task()` hop away | | LLM layers between tool and user | 1 | 2 | | Paid calls per user turn | one per tool call the model makes | supervisor decides — cap it | | Built-in planning / filesystem / subagents | no | yes | | Buyer-side contract | `config.configurable.payment_token` | **identical** | Start from the [LangChain guide](/docs/integrate/add-to-your-agent/langchain) if you want the smallest thing that works. Come here when the agent needs to plan, delegate, or manage its own context — and note that the payment integration itself does not change. ## Related * [LangChain integration](/docs/integrate/add-to-your-agent/langchain) — the decorator and HTTP-middleware approaches in full. * [LangSmith Deployment](/docs/integrate/add-to-your-agent/langsmith-deployment) — hosting a gated graph. * [`langchain-deep-agent-py`](https://github.com/nevermined-io/tutorials/tree/main/langchain-deep-agent-py) — the runnable tutorial for this page. * [`langchain-research-agent-py`](https://github.com/nevermined-io/tutorials/tree/main/langchain-research-agent-py) — the same freemium pattern on `create_react_agent`. # Express.js Source: https://nevermined.ai/docs/integrate/add-to-your-agent/express Add Nevermined x402 payments to your Express.js application with one line of code > [!NOTE] > > **Start here:** need to register a service and create a plan first? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). Add [x402](/docs/development-guide/nevermined-x402) payment protection to your Express.js API. The `paymentMiddleware` handles verification and settlement automatically. ## Installation ```bash theme={null} npm install @nevermined-io/payments express ``` ## Quick Start: One-Line Payment Protection The `paymentMiddleware` from `@nevermined-io/payments/express` handles the entire x402 flow: ```typescript filename="src/agent.ts" theme={null} import express from 'express' import { Payments } from '@nevermined-io/payments' import { paymentMiddleware } from '@nevermined-io/payments/express' const app = express() app.use(express.json()) // Initialize Payments const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: process.env.NVM_ENVIRONMENT === 'live' ? 'live' : 'sandbox' }) // Protect routes with one line app.use( paymentMiddleware(payments, { 'POST /ask': { planId: process.env.NVM_PLAN_ID!, credits: 1 } }) ) // Route handler - no payment logic needed! app.post('/ask', async (req, res) => { const { query } = req.body const response = await generateAIResponse(query) res.json({ response }) }) app.listen(3000, () => console.log('Server running on http://localhost:3000')) ``` That's it! The middleware automatically: * Returns `402` with `payment-required` header when no token is provided * Verifies the x402 token via the Nevermined facilitator * Burns credits after request completion * Returns `payment-response` header with settlement receipt ## x402 Headers The middleware follows the [x402 HTTP transport spec](https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md): | Header | Direction | Description | | - | - | - | | `payment-signature` | Client → Server | Base64-encoded x402 access token | | `payment-required` | Server → Client (402) | Base64-encoded payment requirements | | `payment-response` | Server → Client (200) | Base64-encoded settlement receipt | ## Route Configuration ### Fixed Credits ```typescript theme={null} paymentMiddleware(payments, { 'POST /ask': { planId: PLAN_ID, credits: 1 }, 'POST /generate': { planId: PLAN_ID, credits: 5 } }) ``` ### Dynamic Credits Calculate credits based on request/response: ```typescript theme={null} paymentMiddleware(payments, { 'POST /generate': { planId: PLAN_ID, credits: (req, res) => { // Charge based on token count in response const tokens = res.locals.tokenCount || 100 return Math.ceil(tokens / 100) } } }) ``` ### Path Parameters ```typescript theme={null} paymentMiddleware(payments, { 'GET /users/:id': { planId: PLAN_ID, credits: 1 }, 'POST /agents/:agentId/task': { planId: PLAN_ID, credits: 2 } }) ``` ### With Agent ID ```typescript theme={null} paymentMiddleware(payments, { 'POST /task': { planId: PLAN_ID, agentId: AGENT_ID, // Required for plans with multiple agents credits: 5 } }) ``` ### Payment Scheme (Crypto vs. Fiat) The middleware auto-detects the payment scheme from plan metadata. Plans with fiat pricing (`isCrypto: false`) automatically use `nvm:card-delegation` (Stripe), while crypto plans use `nvm:erc4337`. You can explicitly override the scheme in the route configuration: ```typescript theme={null} paymentMiddleware(payments, { 'POST /ask': { planId: PLAN_ID, credits: 1, scheme: 'nvm:card-delegation' // Force fiat/Stripe scheme } }) ``` > [!NOTE] > > The middleware automatically detects the payment scheme from plan metadata. > Plans with fiat pricing (`isCrypto: false`) use `nvm:card-delegation` (Stripe). > **No code changes are needed on the agent side.** You can explicitly override with > the `scheme` parameter. For the full card-delegation specification, see the [Card Delegation Spec](/docs/specs/x402-card-delegation). ## Middleware Options ```typescript theme={null} paymentMiddleware(payments, routes, { // Custom token header(s) - default: 'payment-signature' (x402 v2) tokenHeader: 'payment-signature', // Hook before verification onBeforeVerify: (req, paymentRequired) => { console.log(`Verifying payment for ${req.path}`) }, // Hook after verification (for observability setup) onAfterVerify: (req, verification) => { // Access agentRequest for observability const agentRequest = verification.agentRequest if (agentRequest) { console.log(`Agent: ${agentRequest.agentName}`) } }, // Hook after settlement onAfterSettle: (req, creditsUsed, settlement) => { console.log(`Settled ${creditsUsed} credits, tx: ${settlement.transaction}`) }, // Custom error handler onPaymentError: (error, req, res) => { res.status(402).json({ error: error.message }) } }) ``` ## Complete Example See the complete working example in the [http-simple-agent tutorial](https://github.com/nevermined-io/tutorials/tree/main/http-simple-agent) on GitHub. ```typescript filename="src/agent.ts" theme={null} import express from 'express' import OpenAI from 'openai' import { Payments } from '@nevermined-io/payments' import { paymentMiddleware } from '@nevermined-io/payments/express' const app = express() app.use(express.json()) // Initialize services const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' }) const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }) // Payment protection with logging app.use( paymentMiddleware(payments, { 'POST /ask': { planId: process.env.NVM_PLAN_ID!, credits: 1 } }, { onBeforeVerify: (req) => { console.log(`[Payment] Verifying request to ${req.path}`) }, onAfterSettle: (req, credits) => { console.log(`[Payment] Settled ${credits} credits`) } }) ) // Protected endpoint app.post('/ask', async (req, res) => { const { query } = req.body const completion = await openai.chat.completions.create({ model: 'gpt-4o-mini', messages: [{ role: 'user', content: query }] }) res.json({ response: completion.choices[0]?.message?.content }) }) // Public endpoint (not in route config) app.get('/health', (req, res) => { res.json({ status: 'ok' }) }) const PORT = process.env.PORT || 3000 app.listen(PORT, () => { console.log(`Agent running on http://localhost:${PORT}`) }) ``` ## Client Implementation > [!NOTE] > > For fiat plans, clients can use `resolveScheme()` to auto-detect the payment scheme before generating tokens. See the [x402 developer guide](/docs/development-guide/nevermined-x402) for details on scheme resolution and `X402TokenOptions`. Here's how clients interact with your payment-protected API: ```typescript filename="src/client.ts" theme={null} import { Payments } from '@nevermined-io/payments' import { X402_HEADERS } from '@nevermined-io/payments/express' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' }) async function callProtectedAPI() { const SERVER_URL = 'http://localhost:3000' // Step 1: Request without token → 402 const response1 = await fetch(`${SERVER_URL}/ask`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: 'What is 2+2?' }) }) if (response1.status === 402) { // Step 2: Decode payment requirements const paymentRequired = JSON.parse( Buffer.from( response1.headers.get(X402_HEADERS.PAYMENT_REQUIRED)!, 'base64' ).toString() ) const { planId, extra } = paymentRequired.accepts[0] const agentId = extra?.agentId // Step 3: Generate x402 token. Create the delegation first (provider + // currency required), then request the token by its delegationId. const delegation = await payments.delegation.createDelegation({ provider: 'erc4337', // 'stripe' | 'braintree' | 'visa' for fiat plans spendingLimitCents: 1000, durationSecs: 86_400, currency: 'usdc', // 'usd' for fiat plans }) const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, { scheme: 'nvm:erc4337', // 'nvm:card-delegation' for fiat plans delegationConfig: { delegationId: delegation.delegationId }, }) // Step 4: Request with token → 200 const response2 = await fetch(`${SERVER_URL}/ask`, { method: 'POST', headers: { 'Content-Type': 'application/json', [X402_HEADERS.PAYMENT_SIGNATURE]: accessToken }, body: JSON.stringify({ query: 'What is 2+2?' }) }) const data = await response2.json() console.log('Response:', data.response) // Step 5: Decode settlement receipt const settlement = JSON.parse( Buffer.from( response2.headers.get(X402_HEADERS.PAYMENT_RESPONSE)!, 'base64' ).toString() ) console.log('Credits used:', settlement.creditsRedeemed) } } ``` ## Environment Variables ```bash filename=".env" theme={null} # Nevermined (required) NVM_API_KEY=sandbox:your-api-key NVM_ENVIRONMENT=sandbox NVM_PLAN_ID=your-plan-id # Agent OPENAI_API_KEY=sk-your-openai-api-key PORT=3000 ``` ## Next Steps > [card] [Payment Patterns](/docs/integrate/patterns/charge-credits) > > Advanced credit charging patterns > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Deep dive into x402 payment flows > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Configure credits, subscriptions, and dynamic pricing > [card] [http-simple-agent Tutorial](https://github.com/nevermined-io/tutorials/tree/main/http-simple-agent) > > Complete working example on GitHub # FastAPI Source: https://nevermined.ai/docs/integrate/add-to-your-agent/fastapi Add Nevermined x402 payments to your FastAPI application with one line of code > [!NOTE] > > **Start here:** need to register a service and create a plan first? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). Add payment protection to your FastAPI application using the [x402 protocol](https://github.com/coinbase/x402). The `PaymentMiddleware` handles verification and settlement automatically. ## x402 Payment Flow ```mermaid theme={null} sequenceDiagram participant Client participant Agent Client->>Agent: 1. POST /ask (no token) Agent-->>Client: 2. 402 Payment Required
Header: payment-required (base64) Note over Client: 3. Generate x402 token via SDK Client->>Agent: 4. POST /ask
Header: payment-signature (token) Note over Agent: Verify permissions
Execute request
Settle (burn credits) Agent-->>Client: 5. 200 OK + AI response
Header: payment-response (base64) ``` ## Installation ```bash theme={null} pip install payments-py[fastapi] fastapi uvicorn ``` > [!NOTE] > > The `[fastapi]` extra installs FastAPI and Starlette dependencies required for the middleware. ## Quick Start: One-Line Payment Protection The `PaymentMiddleware` from `payments_py.x402.fastapi` handles the entire x402 flow: ```python filename="src/agent.py" theme={null} import os from fastapi import FastAPI, Request from payments_py import Payments, PaymentOptions from payments_py.x402.fastapi import PaymentMiddleware app = FastAPI() # Initialize Payments payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment="live" if os.environ.get("ENV") == "production" else "sandbox" ) ) # Protect routes with one line app.add_middleware( PaymentMiddleware, payments=payments, routes={ "POST /ask": {"plan_id": os.environ["NVM_PLAN_ID"], "credits": 1} } ) # Route handler - no payment logic needed! @app.post("/ask") async def ask(request: Request): body = await request.json() response = await generate_ai_response(body.get("query")) return {"response": response} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=3000) ``` That's it! The middleware automatically: * Returns `402` with `payment-required` header when no token is provided * Verifies the x402 token via the Nevermined facilitator * Burns credits after request completion * Returns `payment-response` header with settlement receipt ## x402 Headers The middleware follows the [x402 HTTP transport spec](https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md): | Header | Direction | Description | | - | - | - | | `payment-signature` | Client → Server | Base64-encoded x402 access token | | `payment-required` | Server → Client (402) | Base64-encoded payment requirements | | `payment-response` | Server → Client (200) | Base64-encoded settlement receipt | ## Route Configuration ### Fixed Credits ```python theme={null} app.add_middleware( PaymentMiddleware, payments=payments, routes={ "POST /ask": {"plan_id": PLAN_ID, "credits": 1}, "POST /generate": {"plan_id": PLAN_ID, "credits": 5} } ) ``` ### Path Parameters ```python theme={null} app.add_middleware( PaymentMiddleware, payments=payments, routes={ "GET /users/:id": {"plan_id": PLAN_ID, "credits": 1}, "POST /agents/:agentId/task": {"plan_id": PLAN_ID, "credits": 2} } ) ``` ### With Agent ID ```python theme={null} app.add_middleware( PaymentMiddleware, payments=payments, routes={ "POST /task": { "plan_id": PLAN_ID, "agent_id": AGENT_ID, # Required for plans with multiple agents "credits": 5 } } ) ``` ### Using RouteConfig For more explicit configuration, use `RouteConfig`: ```python theme={null} from payments_py.x402.fastapi import PaymentMiddleware, RouteConfig app.add_middleware( PaymentMiddleware, payments=payments, routes={ "POST /ask": RouteConfig( plan_id=PLAN_ID, credits=1, agent_id=AGENT_ID, network="eip155:84532", # Base Sepolia scheme="nvm:erc4337" # Optional: auto-detected from plan metadata ) } ) ``` > [!NOTE] > > When `scheme` is omitted, the middleware calls `resolve_scheme()` to auto-detect the correct scheme from plan metadata. Plans with fiat pricing (`isCrypto: false`) automatically use `nvm:card-delegation` (Stripe). ### Dynamic Credits Calculate credits based on request data: ```python theme={null} async def calculate_credits(request: Request) -> int: """Charge based on requested token count.""" body = await request.json() max_tokens = body.get("max_tokens", 100) return max(1, max_tokens // 100) # 1 credit per 100 tokens app.add_middleware( PaymentMiddleware, payments=payments, routes={ "POST /generate": { "plan_id": PLAN_ID, "credits": calculate_credits # Pass function instead of int } } ) ``` Sync functions also work: ```python theme={null} app.add_middleware( PaymentMiddleware, payments=payments, routes={ "POST /analyze": { "plan_id": PLAN_ID, # Simple lambda for sync calculation "credits": lambda req: 5 if req.headers.get("priority") == "high" else 1 } } ) ``` ### Payment Scheme (Crypto vs. Fiat) The middleware auto-detects the payment scheme from plan metadata. Plans with fiat pricing (`isCrypto: false`) automatically use `nvm:card-delegation` (Stripe), while crypto plans use `nvm:erc4337`. You can explicitly override the scheme in the route configuration: ```python theme={null} app.add_middleware( PaymentMiddleware, payments=payments, routes={ "POST /ask": { "plan_id": PLAN_ID, "credits": 1, "scheme": "nvm:card-delegation" # Force fiat/Stripe scheme } } ) ``` > [!NOTE] > > The middleware automatically detects the payment scheme from plan metadata. > Plans with fiat pricing (`isCrypto: false`) use `nvm:card-delegation` (Stripe). > **No code changes are needed on the agent side.** You can explicitly override with > the `scheme` parameter. For the full card-delegation specification, see the [Card Delegation Spec](/docs/specs/x402-card-delegation). ## Middleware Options ```python theme={null} from payments_py.x402.fastapi import PaymentMiddleware, PaymentMiddlewareOptions async def before_verify(request, payment_required): print(f"Verifying payment for {request.url.path}") async def after_verify(request, verification): # Access agentRequest for observability if verification.agent_request: print(f"Agent: {verification.agent_request.agent_name}") async def after_settle(request, credits_used, settlement): print(f"Settled {credits_used} credits") async def payment_error(error, request): # Return custom response or None to use default return None app.add_middleware( PaymentMiddleware, payments=payments, routes={"POST /ask": {"plan_id": PLAN_ID, "credits": 1}}, options=PaymentMiddlewareOptions( # Custom token header(s) - default: 'payment-signature' (x402 v2) token_header=["payment-signature"], # Hook before verification on_before_verify=before_verify, # Hook after verification (for observability setup) on_after_verify=after_verify, # Hook after settlement on_after_settle=after_settle, # Custom error handler on_payment_error=payment_error ) ) ``` ## Accessing Payment Context After verification, the payment context is available in `request.state.payment_context`: ```python theme={null} from payments_py.x402.fastapi import PaymentContext @app.post("/ask") async def ask(request: Request): # Access payment context for observability or logging payment_context: PaymentContext = request.state.payment_context print(f"Token: {payment_context.token}") print(f"Credits to settle: {payment_context.credits_to_settle}") print(f"Agent request ID: {payment_context.agent_request_id}") # Use agent_request for observability integration if payment_context.agent_request: print(f"Agent: {payment_context.agent_request.agent_name}") print(f"Balance: {payment_context.agent_request.balance}") body = await request.json() response = await generate_ai_response(body.get("query")) return {"response": response} ``` ## Complete Example See the complete working example in the [http-simple-agent-py tutorial](https://github.com/nevermined-io/tutorials/tree/main/http-simple-agent-py) on GitHub. ```python filename="src/agent.py" theme={null} import os from dotenv import load_dotenv load_dotenv() # Load env vars BEFORE importing payments_py from fastapi import FastAPI, Request from openai import OpenAI from payments_py import Payments, PaymentOptions from payments_py.x402.fastapi import PaymentMiddleware, PaymentMiddlewareOptions app = FastAPI(title="AI Agent with Nevermined Payments") # Initialize services payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment=os.environ.get("NVM_ENVIRONMENT", "sandbox") ) ) openai_client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) PLAN_ID = os.environ["NVM_PLAN_ID"] # Payment protection with logging app.add_middleware( PaymentMiddleware, payments=payments, routes={ "POST /ask": {"plan_id": PLAN_ID, "credits": 1} }, options=PaymentMiddlewareOptions( on_before_verify=lambda req, pr: print(f"[Payment] Verifying request to {req.url.path}"), on_after_settle=lambda req, credits, settlement: print(f"[Payment] Settled {credits} credits") ) ) # Protected endpoint @app.post("/ask") async def ask(request: Request): body = await request.json() query = body.get("query", "") completion = openai_client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": query}] ) return {"response": completion.choices[0].message.content} # Public endpoint (not in route config) @app.get("/health") async def health(): return {"status": "ok"} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 3000))) ``` ## With Observability For full observability integration with Helicone: ```python filename="src/agent_observability.py" theme={null} import os from dotenv import load_dotenv load_dotenv() # MUST be before payments_py import from fastapi import FastAPI, Request from openai import OpenAI from payments_py import Payments, PaymentOptions from payments_py.x402.fastapi import PaymentMiddleware, PaymentContext app = FastAPI() payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment=os.environ.get("NVM_ENVIRONMENT", "sandbox") ) ) PLAN_ID = os.environ["NVM_PLAN_ID"] app.add_middleware( PaymentMiddleware, payments=payments, routes={"POST /ask": {"plan_id": PLAN_ID, "credits": 1}} ) @app.post("/ask") async def ask(request: Request): body = await request.json() query = body.get("query", "") # Get payment context for observability payment_context: PaymentContext = request.state.payment_context agent_request = payment_context.agent_request # Configure OpenAI client with observability headers openai_client = payments.observability.with_openai( OpenAI(api_key=os.environ["OPENAI_API_KEY"]), agent_request ) completion = openai_client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": query}] ) return { "response": completion.choices[0].message.content, "observability": { "agent_request_id": payment_context.agent_request_id, "agent_name": agent_request.agent_name if agent_request else None } } ``` ## Client Implementation > [!NOTE] > > For fiat plans, clients can use `resolve_scheme()` to auto-detect the payment scheme before generating tokens. See the [x402 developer guide](/docs/development-guide/nevermined-x402) for details on scheme resolution and `X402TokenOptions`. Here's how clients interact with your payment-protected API: ```python filename="src/client.py" theme={null} import os import base64 import json import httpx from payments_py import Payments, PaymentOptions from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment=os.environ.get("NVM_ENVIRONMENT", "sandbox") ) ) def call_protected_api(): SERVER_URL = "http://localhost:3000" with httpx.Client(timeout=60.0) as client: # Longer timeout for settlement # Step 1: Request without token → 402 response1 = client.post( f"{SERVER_URL}/ask", json={"query": "What is 2+2?"} ) if response1.status_code == 402: # Step 2: Decode payment requirements payment_required = json.loads( base64.b64decode( response1.headers.get("payment-required") ).decode() ) plan_id = payment_required["accepts"][0]["planId"] agent_id = payment_required["accepts"][0].get("extra", {}).get("agentId") # Step 3: Generate x402 token. Create the delegation first (provider + # currency required), then request the token by its delegationId. delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="erc4337", # "stripe" | "braintree" | "visa" for fiat plans spending_limit_cents=1000, duration_secs=86_400, currency="usdc", # "usd" for fiat plans ) ) token_result = payments.x402.get_x402_access_token( plan_id, agent_id, token_options=X402TokenOptions( scheme="nvm:erc4337", # "nvm:card-delegation" for fiat plans delegation_config=DelegationConfig(delegation_id=delegation.delegation_id), ), ) access_token = token_result["accessToken"] # Step 4: Request with token → 200 response2 = client.post( f"{SERVER_URL}/ask", headers={"payment-signature": access_token}, json={"query": "What is 2+2?"} ) data = response2.json() print(f"Response: {data['response']}") # Step 5: Decode settlement receipt settlement = json.loads( base64.b64decode( response2.headers.get("payment-response") ).decode() ) print(f"Credits used: {settlement.get('creditsRedeemed')}") if __name__ == "__main__": call_protected_api() ``` ## Environment Variables ```bash filename=".env" theme={null} # Nevermined (required) NVM_API_KEY=sandbox:your-api-key NVM_ENVIRONMENT=sandbox NVM_PLAN_ID=your-plan-id # Agent OPENAI_API_KEY=sk-your-openai-api-key PORT=3000 ``` ## Alternative: Manual Dependency Injection For more control or complex scenarios, you can use FastAPI's dependency injection instead of middleware: > [accordion] Manual Dependency Injection Pattern > > ```python filename="src/dependencies/payment.py" theme={null} > from fastapi import Request, HTTPException, Depends > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox') > ) > > async def get_payment_proof(request: Request) -> str: > """Extract x402 payment proof from payment-signature header.""" > payment_proof = request.headers.get('payment-signature') > > if not payment_proof: > raise HTTPException( > status_code=402, > detail={ > 'error': 'Payment Required', > 'code': 'PAYMENT_REQUIRED', > 'plans': [{'planId': os.environ['PLAN_ID']}] > } > ) > return payment_proof > > async def validate_payment( > request: Request, > payment_proof: str = Depends(get_payment_proof) > ): > """Validate x402 payment proof.""" > verification = payments.facilitator.verify_permissions( > x402_access_token=payment_proof, > max_amount="1" > ) > > if not verification.is_valid: > raise HTTPException( > status_code=402, > detail={'error': 'Payment verification failed'} > ) > return verification > ``` > > ```python filename="src/routes/query.py" theme={null} > from fastapi import APIRouter, Depends > from src.dependencies.payment import validate_payment > > router = APIRouter() > > @router.post("/query") > async def query(request: dict, payment = Depends(validate_payment)): > # Your logic here - payment already verified > return {"result": "..."} > ``` ## Next Steps > [card] [Payment Patterns](/docs/integrate/patterns/charge-credits) > > Advanced credit charging patterns > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Deep dive into x402 payment flows > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Configure credits, subscriptions, and dynamic pricing > [card] [http-simple-agent-py Tutorial](https://github.com/nevermined-io/tutorials/tree/main/http-simple-agent-py) > > Complete working example on GitHub # Generic HTTP Source: https://nevermined.ai/docs/integrate/add-to-your-agent/generic-http Add Nevermined payments to any HTTP server > [!NOTE] > > **Start here:** need to register a service and create a plan first? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). Generic patterns for integrating Nevermined payments into any HTTP server or framework. ## The x402 Payment Flow When using x402, the client typically **doesn't start with a token**. Instead, the server advertises payment requirements via `402 Payment Required`, and the client retries with a payment proof. ```mermaid theme={null} sequenceDiagram participant Client participant YourServer participant Facilitator as Nevermined (Facilitator) Client->>YourServer: Request (no payment proof) YourServer-->>Client: 402 Payment Required + plans/requirements Client->>Client: Build x402 payment proof Client->>YourServer: Retry request + PAYMENT-SIGNATURE YourServer->>Facilitator: Verify/settle (via SDK) Facilitator-->>YourServer: OK (balance/receipt) YourServer-->>Client: 200 OK (response) ``` ## Implementation Steps ### 1. Extract the x402 token from the request x402 clients send the payment token in the `payment-signature` header (lowercase, per x402 v2 spec): ``` payment-signature: ``` ### 2. Return 402 if token is missing When no token is provided, return HTTP 402 with a base64-encoded `payment-required` header: > [tab] TypeScript > > ```typescript theme={null} > import { Payments, buildPaymentRequired } from '@nevermined-io/payments' > > const PLAN_ID = process.env.NVM_PLAN_ID! > const AGENT_ID = process.env.NVM_AGENT_ID > > // Build the payment required object > // scheme is auto-detected from plan metadata when omitted > const paymentRequired = buildPaymentRequired(PLAN_ID, { > endpoint: req.path, > agentId: AGENT_ID, > httpVerb: req.method, > scheme: 'nvm:erc4337' // Optional: omit to auto-detect from plan metadata > }) > > // Check for token > const token = req.headers['payment-signature'] > if (!token) { > const paymentRequiredBase64 = Buffer.from( > JSON.stringify(paymentRequired) > ).toString('base64') > > return res > .status(402) > .setHeader('payment-required', paymentRequiredBase64) > .json({ error: 'Payment Required', message: 'Missing x402 access token' }) > } > ``` > [tab] Python > > ```python theme={null} > import base64 > import json > from payments_py.x402.helpers import build_payment_required > > PLAN_ID = os.environ["NVM_PLAN_ID"] > AGENT_ID = os.environ.get("NVM_AGENT_ID") > > # Build the payment required object > # scheme is auto-detected from plan metadata when omitted > payment_required = build_payment_required( > plan_id=PLAN_ID, > endpoint=request.path, > agent_id=AGENT_ID, > http_verb=request.method, > scheme="nvm:erc4337" # Optional: omit to auto-detect from plan metadata > ) > > # Check for token > token = request.headers.get("payment-signature") > if not token: > payment_required_json = payment_required.model_dump_json(by_alias=True) > payment_required_base64 = base64.b64encode( > payment_required_json.encode() > ).decode() > > return JSONResponse( > status_code=402, > content={"error": "Payment Required", "message": "Missing x402 access token"}, > headers={"payment-required": payment_required_base64} > ) > ``` ### 3. Verify permissions with the Facilitator Before processing the request, verify the subscriber has sufficient credits: > [tab] TypeScript > > ```typescript theme={null} > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox' > }) > > const verification = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: token, > maxAmount: BigInt(creditsRequired) // e.g., 1n > }) > > if (!verification.isValid) { > const paymentRequiredBase64 = Buffer.from( > JSON.stringify(paymentRequired) > ).toString('base64') > > return res > .status(402) > .setHeader('payment-required', paymentRequiredBase64) > .json({ error: 'Payment Required', message: verification.invalidReason }) > } > > // Verification passed - process the request > ``` > [tab] Python > > ```python theme={null} > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ["NVM_API_KEY"], environment="sandbox") > ) > > verification = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=token, > max_amount=str(credits_required) # e.g., "1" > ) > > if not verification.is_valid: > payment_required_json = payment_required.model_dump_json(by_alias=True) > payment_required_base64 = base64.b64encode( > payment_required_json.encode() > ).decode() > > return JSONResponse( > status_code=402, > content={"error": "Payment Required", "message": verification.invalid_reason}, > headers={"payment-required": payment_required_base64} > ) > > # Verification passed - process the request > ``` ### 4. Process the request Execute your business logic after verification passes. ### 5. Settle (burn credits) after successful response After the request completes successfully, settle the credits and include the receipt in the response: > [tab] TypeScript > > ```typescript theme={null} > // After processing the request successfully... > const settlement = await payments.facilitator.settlePermissions({ > paymentRequired, > x402AccessToken: token, > maxAmount: BigInt(creditsUsed) > }) > > // Include settlement receipt in response header > const settlementBase64 = Buffer.from(JSON.stringify(settlement)).toString('base64') > > return res > .setHeader('payment-response', settlementBase64) > .json({ result: yourResponseData }) > ``` > [tab] Python > > ```python theme={null} > # After processing the request successfully... > settlement = payments.facilitator.settle_permissions( > payment_required=payment_required, > x402_access_token=token, > max_amount=str(credits_used) > ) > > # Include settlement receipt in response header > settlement_json = settlement.model_dump_json(by_alias=True) > settlement_base64 = base64.b64encode(settlement_json.encode()).decode() > > return JSONResponse( > content={"result": your_response_data}, > headers={"payment-response": settlement_base64} > ) > ``` ## x402 Headers Summary | Header | Direction | Description | | - | - | - | | `payment-signature` | Client → Server | x402 access token | | `payment-required` | Server → Client (402) | Base64-encoded payment requirements | | `payment-response` | Server → Client (200) | Base64-encoded settlement receipt | > [!NOTE] > > When the `scheme` parameter is omitted from `buildPaymentRequired` / `build_payment_required`, the network is auto-derived from the scheme (`eip155:84532` for `nvm:erc4337`, `stripe` for `nvm:card-delegation`). The middleware and helpers call `resolveScheme()` / `resolve_scheme()` to detect the correct scheme from plan metadata automatically. ## HTTP Response Codes | Code | Meaning | When to Use | | - | - | - | | `200` | Success | Valid payment proof, request processed | | `402` | Payment Required | Missing/invalid payment proof, insufficient credits | | `500` | Server Error | Validation system failure | ## Using Framework Middleware (Recommended) For Express.js and FastAPI, use the built-in middleware that handles the entire x402 flow automatically: > [tab] Express.js > > ```typescript theme={null} > import { paymentMiddleware } from '@nevermined-io/payments/express' > > app.use(paymentMiddleware(payments, { > 'POST /ask': { planId: PLAN_ID, credits: 1 } > })) > ``` > > See [Express.js Integration](/docs/integrate/add-to-your-agent/express) for details. > [tab] FastAPI > > ```python theme={null} > from payments_py.x402.fastapi import PaymentMiddleware > > app.add_middleware( > PaymentMiddleware, > payments=payments, > routes={"POST /ask": {"plan_id": PLAN_ID, "credits": 1}} > ) > ``` > > See [FastAPI Integration](/docs/integrate/add-to-your-agent/fastapi) for details. ## Best Practices > [accordion] Cache Validation Results > > For high-traffic endpoints, consider caching validation results briefly (5-30 seconds) to reduce API calls. > [accordion] Handle Timeouts > > Set reasonable timeouts for validation calls (5-10 seconds) and have a > fallback strategy. > [accordion] Log Payment Events > > Log all payment validations for debugging and analytics: - Token hash (not > full token) - Validation result - Credits consumed - Timestamp > [accordion] Return Helpful 402 Responses > > Always include plan information in 402 responses so clients know how to get access. ## Security Considerations 1. **Never log full tokens** - Hash them if you need to identify requests 2. **Use HTTPS** - Tokens should only travel over encrypted connections 3. **Validate on server** - Never trust client-side validation 4. **Set token expiration** - Accept reasonable token ages ## Next Steps > [card] [Payment Patterns](/docs/integrate/patterns/validate-requests) > > Advanced validation patterns > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Implement standard HTTP 402 flows # LangChain Source: https://nevermined.ai/docs/integrate/add-to-your-agent/langchain Add Nevermined x402 payments to your LangChain and LangGraph agents > [!NOTE] > > **Start here:** need to register a service and create a plan first? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). > [card] [Runnable tutorial](https://github.com/nevermined-io/tutorials/tree/main/langchain-paid-agent-py) > > **`langchain-paid-agent-py`** — a deliberately minimal LangChain + LangGraph agent > with a single tool gated by `@requires_payment`. Clone, fill in `.env`, run > `poetry run buyer` to see the full discovery → token-acquisition → settlement > flow in five numbered steps. The cleanest starting point if you'd rather read > working code than docs. Add payment protection to [LangChain](https://python.langchain.com/) and [LangChain.js](https://js.langchain.com/) tools using the [x402 protocol](https://github.com/coinbase/x402). The library provides two complementary approaches: | Approach | Best for | Payment layer | | - | - | - | | **`requiresPayment` wrapper/decorator** | Direct tool invocation, CLI scripts, notebooks | Per-tool wrapper | | **Payment middleware on HTTP server** | Serving the agent over HTTP | HTTP middleware | Both use the same Nevermined plan, credits, and settlement flow — choose whichever fits your deployment model. > [!NOTE] > > Building on the [Deep Agents](https://docs.langchain.com/oss/python/deepagents/overview) > harness? `@requires_payment` works there unchanged, including on a tool that > lives inside a subagent — see [Deep Agents](/docs/integrate/add-to-your-agent/deep-agents). ## Installation > [tab] TypeScript > > ```bash theme={null} > npm install @nevermined-io/payments @langchain/core @langchain/openai zod > ``` > > > [!NOTE] > > > > The `@nevermined-io/payments/langchain` sub-path export provides the `requiresPayment()` wrapper. > > For the HTTP server approach, also install `express`. > [tab] Python > > ```bash theme={null} > pip install payments-py[langchain] langchain-openai > ``` > > > [!NOTE] > > > > The `[langchain]` extra installs the LangChain dependency required for the decorator. > > For the HTTP server approach, also install `fastapi` and `uvicorn`. *** ## Approach 1: Tool Decorator / Wrapper ### x402 Payment Flow (decorator) ```mermaid theme={null} sequenceDiagram participant Client participant LLM participant Tool participant NVM as Nevermined Client->>LLM: invoke(messages) LLM->>Tool: tool_call (no token) Tool-->>LLM: PaymentRequired error (tool result) LLM-->>Client: "Payment required" Client->>NVM: get_x402_access_token(plan_id) NVM-->>Client: Access token Client->>LLM: invoke(messages, config=payment_token) LLM->>Tool: tool_call Tool->>NVM: Verify permissions NVM-->>Tool: Valid Tool->>Tool: Execute function Tool->>NVM: Settle (burn credits) NVM-->>Tool: Settled Tool-->>LLM: Result LLM-->>Client: Final answer ``` ### Quick Start > [tab] TypeScript > > In LangChain.js, `requiresPayment()` is a higher-order function that wraps the tool implementation: > > ```typescript filename="agent.ts" theme={null} > import 'dotenv/config' > import { tool } from '@langchain/core/tools' > import { z } from 'zod' > import { Payments } from '@nevermined-io/payments' > import { requiresPayment } from '@nevermined-io/payments/langchain' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: process.env.NVM_ENVIRONMENT || 'sandbox', > }) > > const PLAN_ID = process.env.NVM_PLAN_ID! > > // Protect a tool with payment — 1 credit per call > const searchData = tool( > requiresPayment( > (args) => `Results for '${args.query}': ...`, > { payments, planId: PLAN_ID, credits: 1 } > ), > { > name: 'search_data', > description: 'Search for data on a given topic. Costs 1 credit.', > schema: z.object({ query: z.string() }), > } > ) > ``` > > > [!WARNING] > > > > The payment token is read from `config.configurable.payment_token`. > > Pass it when invoking the tool or agent. > [tab] Python > > In Python, `@requires_payment` is a decorator applied before `@tool`: > > ```python filename="agent.py" theme={null} > import os > from dotenv import load_dotenv > from langchain_core.runnables import RunnableConfig > from langchain_core.tools import tool > from payments_py import Payments, PaymentOptions > from payments_py.x402.langchain import requires_payment > > load_dotenv() > > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_API_KEY"], > environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), > ) > ) > > PLAN_ID = os.environ["NVM_PLAN_ID"] > > # Protect a tool with payment — 1 credit per call > @tool > @requires_payment(payments=payments, plan_id=PLAN_ID, credits=1) > def search_data(query: str, config: RunnableConfig) -> str: > """Search for data on a given topic. Costs 1 credit.""" > return f"Results for '{query}': ..." > ``` > > > [!WARNING] > > > > The tool function **must** accept a `config: RunnableConfig` parameter. > > The decorator uses it to read the payment token from > > `config["configurable"]["payment_token"]`. ### Invoking with payment > [tab] TypeScript > > ```typescript filename="client.ts" theme={null} > import { Payments } from '@nevermined-io/payments' > > // Subscriber side — acquire token > const subscriber = Payments.getInstance({ > nvmApiKey: process.env.NVM_SUBSCRIBER_API_KEY!, > environment: process.env.NVM_ENVIRONMENT || 'sandbox', > }) > > // Create a delegation once, then reuse its id to mint tokens. > const { delegationId } = await subscriber.delegation.createDelegation({ > provider: 'erc4337', // 'stripe' | 'braintree' | 'visa' for fiat plans > spendingLimitCents: 10000, // $100 budget > durationSecs: 604800, // 7 days > currency: 'usdc', // 'usd' for fiat plans > }) > const token = await subscriber.x402.getX402AccessToken(PLAN_ID, undefined, { > scheme: 'nvm:erc4337', // 'nvm:card-delegation' for fiat plans > delegationConfig: { delegationId }, > }) > const accessToken = token.accessToken > > // Invoke tool directly > const result = await searchData.invoke( > { query: 'AI trends' }, > { configurable: { payment_token: accessToken } } > ) > ``` > [tab] Python > > ```python filename="client.py" theme={null} > from payments_py import Payments, PaymentOptions > from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload > > # Subscriber side — acquire token > subscriber = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_SUBSCRIBER_API_KEY"], > environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), > ) > ) > > # Create a delegation once, then reuse its id to mint tokens. > delegation = subscriber.delegation.create_delegation( > CreateDelegationPayload( > provider="erc4337", spending_limit_cents=10000, duration_secs=604800, currency="usdc", > ) > ) > token = subscriber.x402.get_x402_access_token( > plan_id=PLAN_ID, > token_options=X402TokenOptions( > scheme="nvm:erc4337", # "nvm:card-delegation" for fiat plans > delegation_config=DelegationConfig(delegation_id=delegation.delegation_id) > ), > ) > access_token = token["accessToken"] > > # Invoke tool directly > result = search_data.invoke( > {"query": "AI trends"}, > config={"configurable": {"payment_token": access_token}}, > ) > ``` ### LLM-driven tool calling > [tab] TypeScript > > ```typescript theme={null} > import { HumanMessage } from '@langchain/core/messages' > import { ChatOpenAI } from '@langchain/openai' > > const llm = new ChatOpenAI({ model: 'gpt-4o-mini', temperature: 0 }) > const tools = [searchData, summarizeData, researchTopic] > const llmWithTools = llm.bindTools(tools) > const toolMap = new Map(tools.map((t) => [t.name, t])) > > const messages = [new HumanMessage('Search for AI trends')] > const aiMessage = await llmWithTools.invoke(messages) > messages.push(aiMessage) > > for (const toolCall of aiMessage.tool_calls || []) { > const result = await toolMap.get(toolCall.name)!.invoke( > toolCall.args, > { configurable: { payment_token: accessToken } } > ) > } > ``` > [tab] Python > > ```python theme={null} > llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) > tools = [search_data, summarize_data, research_topic] > llm_with_tools = llm.bind_tools(tools) > tool_map = {t.name: t for t in tools} > > messages = [HumanMessage(content="Search for AI trends")] > ai_message = llm_with_tools.invoke(messages) > messages.append(ai_message) > > for tool_call in ai_message.tool_calls: > result = tool_map[tool_call["name"]].invoke( > tool_call["args"], > config={"configurable": {"payment_token": access_token}}, > ) > ``` ### LangGraph ReAct agent The same payment-protected tools work with LangGraph's `create_react_agent`. The simple case — buyer already holds a token — just threads it through `configurable`: > [tab] TypeScript > > ```typescript theme={null} > import { createReactAgent } from '@langchain/langgraph/prebuilt' > > const agent = createReactAgent({ > llm: new ChatOpenAI({ model: 'gpt-4o-mini' }), > tools: [searchData, summarizeData, researchTopic], > prompt: 'You are a helpful research assistant.', > }) > > const result = await agent.invoke( > { messages: [{ role: 'human', content: 'Research AI agents and summarize' }] }, > { configurable: { payment_token: accessToken } } > ) > ``` > [tab] Python > > ```python theme={null} > from langgraph.prebuilt import create_react_agent > > graph = create_react_agent( > ChatOpenAI(model="gpt-4o-mini"), > [search_data, summarize_data, research_topic], > prompt="You are a helpful research assistant.", > ) > > result = graph.invoke( > {"messages": [("human", "Research AI agents and summarize")]}, > config={"configurable": {"payment_token": access_token}}, > ) > ``` ### Discovery-first flow with `createPaidReactAgent` If the buyer **doesn't** know the plan id / scheme / provider up front, the x402 way is to invoke the agent without a token, let the protected tool raise `PaymentRequiredError`, and read the requirements off the exception. By default LangGraph's `ToolNode` would catch that exception and stringify it into a `ToolMessage` for the LLM — losing the `X402PaymentRequired` payload. Both SDKs ship a paid-agent helper for exactly this — `createPaidReactAgent` (TypeScript) / `create_paid_react_agent` (Python) — that builds the underlying `ToolNode` with `handleToolErrors: false` / `handle_tool_errors=False`, so the exception propagates to `agent.invoke()`'s caller with the payload intact. > [tab] TypeScript > > ```typescript theme={null} > import { tool } from '@langchain/core/tools' > import { ChatOpenAI } from '@langchain/openai' > import { z } from 'zod' > import { > PaymentRequiredError, > createPaidReactAgent, > requiresPayment, > } from '@nevermined-io/payments/langchain' > > const getMarketInsight = tool( > requiresPayment( > (args) => `Market insight for '${args.topic}': ...`, > { payments, planId: PLAN_ID, credits: 1 }, > ), > { > name: 'get_market_insight', > description: 'Return a market insight. Costs 1 credit.', > schema: z.object({ topic: z.string() }), > }, > ) > > const agent = await createPaidReactAgent( > new ChatOpenAI({ model: 'gpt-4o-mini', temperature: 0 }), > [getMarketInsight], > { prompt: 'You are a market data assistant.' }, > ) > > // 1. Discover what the agent's tool charges by invoking without a token. > let accept > try { > await agent.invoke( > { messages: [{ role: 'human', content: QUERY }] }, > { configurable: {} }, > ) > } catch (err) { > if (!(err instanceof PaymentRequiredError)) throw err > accept = err.paymentRequired!.accepts[0] > // accept.scheme → "nvm:erc4337" or "nvm:card-delegation" > // accept.network → CAIP-2 chain or provider name (stripe, braintree, …) > // accept.planId → which plan to acquire a token against > } > > // 2. Pick a payment method matching the discovered network and create a > // delegation once (provider + currency required). Reuse its delegationId > // for subsequent token requests. > const methods = await payments.delegation.listPaymentMethods() > const pm = methods.find((m) => m.provider === accept.network)! > const delegation = await payments.delegation.createDelegation({ > provider: pm.provider!, > providerPaymentMethodId: pm.id, > spendingLimitCents: 10000, > durationSecs: 3600, > currency: 'usd', > }) > > // 3. Acquire the token against the discovered plan by delegationId. > const { accessToken } = await payments.x402.getX402AccessToken( > accept.planId, > undefined, > { > scheme: accept.scheme, > delegationConfig: { delegationId: delegation.delegationId }, > }, > ) > > // 4. Retry with the token. > const result = await agent.invoke( > { messages: [{ role: 'human', content: QUERY }] }, > { configurable: { payment_token: accessToken } }, > ) > ``` > [tab] Python > > ```python theme={null} > from payments_py.x402.langchain import ( > PaymentRequiredError, > create_paid_react_agent, > requires_payment, > ) > from payments_py.x402.types import ( > CreateDelegationPayload, > DelegationConfig, > X402TokenOptions, > ) > > @tool > @requires_payment(payments=payments, plan_id=PLAN_ID, credits=1) > def get_market_insight(topic: str, config: RunnableConfig = None) -> str: > """Return a market insight. Costs 1 credit.""" > return f"Market insight for '{topic}': ..." > > agent = create_paid_react_agent( > ChatOpenAI(model="gpt-4o-mini", temperature=0), > [get_market_insight], > prompt="You are a market data assistant.", > ) > > # 1. Discover what the agent's tool charges by invoking without a token. > try: > agent.invoke({"messages": [("human", QUERY)]}, config={"configurable": {}}) > except PaymentRequiredError as err: > accept = err.payment_required.accepts[0] > # accept.scheme → "nvm:erc4337" or "nvm:card-delegation" > # accept.network → CAIP-2 chain or provider name (stripe, braintree, …) > # accept.plan_id → which plan to acquire a token against > > # 2. Pick a payment method matching the discovered network and create a > # delegation once (provider + currency required). Reuse its delegation_id > # for subsequent token requests. > pm = next(m for m in payments.delegation.list_payment_methods() > if m.provider == accept.network) > delegation = payments.delegation.create_delegation( > CreateDelegationPayload( > provider=pm.provider, > provider_payment_method_id=pm.id, > spending_limit_cents=10000, > duration_secs=3600, > currency="usd", > ) > ) > > # 3. Acquire the token against the discovered plan by delegation_id. > token = payments.x402.get_x402_access_token( > accept.plan_id, > token_options=X402TokenOptions( > scheme=accept.scheme, > delegation_config=DelegationConfig( > delegation_id=delegation.delegation_id, > ), > ), > )["accessToken"] > > # 4. Retry with the token. > result = agent.invoke( > {"messages": [("human", QUERY)]}, > config={"configurable": {"payment_token": token}}, > ) > ``` > [!NOTE] > > Create the delegation that backs the payment signature **first** (with > `createDelegation`), then pass its `delegationId` in the token's > `delegationConfig`. This applies to both card-delegation and crypto > (`nvm:erc4337`) plans. Passing creation fields inline instead of a > `delegationId` is deprecated and emits a runtime warning — see the x402 > Protocol module reference ([TypeScript](/docs/api-reference/typescript/x402) · > [Python](/docs/api-reference/python/x402-module)) for the full token-options > surface. This discovery flow covers Stripe and Braintree. For **Visa**-priced > plans, `createDelegation` from the SDK is rejected (`BCK.VISA.0014`) — create > the Visa delegation in the Nevermined app and reuse its `delegationId` here. > [!NOTE] > > `createPaidReactAgent` is **async** in TypeScript — it `await`s the lazy > `@langchain/langgraph` import so the dependency stays optional. Install > LangGraph yourself (`pnpm add @langchain/langgraph`) to use it. ### Reading the settlement receipt After a successful agent call, the buyer can read the settlement receipt — credits redeemed, remaining balance, transaction hash, network, payer — via `lastSettlement()` (TypeScript) / `last_settlement()` (Python). LangGraph copies `configurable` per node, so the in-place `payment_settlement` write is invisible to the outer scope; the accessor reads it from a module-level slot instead. > [tab] TypeScript > > ```typescript theme={null} > import { lastSettlement } from '@nevermined-io/payments/langchain' > > const result = await agent.invoke( > { messages: [{ role: 'human', content: QUERY }] }, > { configurable: { payment_token: accessToken } }, > ) > const receipt = lastSettlement() > if (receipt) { > console.log(`credits redeemed: ${receipt.creditsRedeemed}`) > console.log(`remaining balance: ${receipt.remainingBalance}`) > console.log(`tx: ${receipt.transaction}`) > } > ``` > [tab] Python > > ```python theme={null} > from payments_py.x402.langchain import last_settlement > > result = agent.invoke( > {"messages": [("human", QUERY)]}, > config={"configurable": {"payment_token": token}}, > ) > receipt = last_settlement() > if receipt: > print(f"credits redeemed: {receipt.credits_redeemed}") > print(f"remaining balance: {receipt.remaining_balance}") > print(f"tx: {receipt.transaction}") > ``` > [!WARNING] > > `lastSettlement()` / `last_settlement()` reads from a module-level slot. In > multi-tenant processes (e.g. a server handling concurrent settlements), the > value reflects whichever invocation settled most recently — there is no > per-call isolation. For multi-tenant scenarios, surface settlement via a > callback or observability layer instead. ### Trace payments in LangSmith Once payment protection is wired up, you can have every paid tool call surface as structured spans in [LangSmith](https://smith.langchain.com) — no code changes required, just two env vars and an optional dependency. **Both SDKs emit the identical `nvm:verify` / `nvm:settlement` span shape** (the cross-SDK [observability-spans-v1 contract](https://github.com/nevermined-io/nvm-monorepo/blob/main/docs/specs/observability-spans-v1.md)), so a single trace can be correlated across a TypeScript buyer and a Python seller — e.g. filter on `nvm.tx_hash`. **Install the optional dependency:** > [tab] TypeScript > > ```bash theme={null} > pnpm add langsmith > ``` > > `langsmith` is an optional peer dependency — the `requiresPayment` wrapper emits the spans automatically when it is installed and tracing is enabled. > [tab] Python > > ```bash theme={null} > pip install "payments-py[langchain,langsmith]" > ``` **Enable tracing:** ```bash filename=".env" theme={null} LANGSMITH_TRACING=true LANGSMITH_API_KEY=lsv2_pt_your-key LANGSMITH_PROJECT=nvm-langchain # optional # Only needed if your LangSmith account is NOT in GCP US: # LANGSMITH_ENDPOINT=https://eu.api.smith.langchain.com ``` That's it. Running the same agent invocation now produces a trace tree with two dedicated Nevermined child spans nested under the tool: ```text theme={null} LangGraph └── tools └── get_market_insight ├── nvm:verify 0.28s ← around the facilitator verify call └── nvm:settlement 1.88s ← around the facilitator settle call ``` Each Nevermined span carries `nvm.*` metadata for audit + reconciliation: | Span | Attributes | | - | - | | `nvm:verify` | `nvm.plan_ids`, `nvm.scheme`, `nvm.network`, `nvm.agent_id`, `nvm.payer`, `nvm.agent_request_id`, `nvm.payment_token` (abbreviated), `nvm.verify.duration_ms` | | `nvm:settlement` | `nvm.credits_redeemed`, `nvm.balance.after`, `nvm.tx_hash`, `nvm.network`, `nvm.payer`, `nvm.payment_token` (abbreviated), `nvm.settle.duration_ms` | The same `nvm.*` metadata is also attached to the parent tool span so cmd-F searches in the LangSmith UI land on either level. **Failed discovery probes are first-class too.** When the buyer's first `agent.invoke()` runs without a `payment_token` (the discovery-first flow), the `nvm:verify` span still opens, carries the static `nvm.plan_ids` / `nvm.scheme` / `nvm.network`, and is marked failed by the raised `PaymentRequiredError`. That gives you "which plan was the probe against?" filterability instead of an opaque LangChain crash. > [!WARNING] > > The `payment_token` the buyer passes in `configurable.payment_token` would normally be captured into the parent tool span's metadata by LangChain and inherited by every child span. The full token grants access to the protected tool until it expires. Both SDKs **proactively strip it from the parent span's metadata** before opening any `nvm:*` child, so the full credential never reaches a Nevermined-emitted attribute. The abbreviated `nvm.payment_token` (first 16 chars + `…` + last 4 chars) remains available for correlation. > > A too-short token (≤ 20 chars — almost always a misconfiguration, since real x402 access tokens are JWTs) is **redacted, not exported**: at most the first 4 chars are surfaced followed by a `…(short)` marker, and a token of 4 chars or fewer reveals **nothing** (just `…(short)`). A warning is logged, so a wrong value passed as the token never lands in a trace. > > Other channels (custom callbacks, an explicit metadata write that includes the token, tool signatures that contain the token) are not covered — strip them yourself or set `export LANGSMITH_HIDE_INPUTS=true` for blanket coverage. If a span failure ever occurs during metadata building or attachment, observability is silently dropped — the payment flow itself is never interrupted. Settlement receipts persist (via `lastSettlement()` in TypeScript / `last_settlement()` in Python) regardless of whether the span emit succeeded. For the full module reference, see the [Python LangChain module reference](/docs/api-reference/python/langchain-module#observability-with-langsmith). The TypeScript helper surface (`verifySpan`, `settlementSpan`, `abbreviateToken`, `addMetadata`, `redactMetadataKeys`, `activeRunTree`, plus `buildVerifyMetadata` / `buildSettleMetadata` for manual use outside the `requiresPayment` decorator) is exported from `@nevermined-io/payments/langsmith` — JSDoc on each helper documents the contract until the next `update-docs.yml` sync mirrors a dedicated TS api-reference page. ### Dynamic Credits > [!NOTE] > > The `credits` argument is sent to the facilitator as `max_amount`. The amount > actually redeemed depends on the plan's server-side credit config: > **fixed plans** (where `plan.credits.minAmount == plan.credits.maxAmount`) > always burn `plan.credits.maxAmount` and ignore the supplied value (per > [nvm-monorepo#1568](https://github.com/nevermined-io/nvm-monorepo/issues/1568)); > **range plans** clamp the value into `[minAmount, maxAmount]`. If you want > predictable per-call cost, configure the plan as fixed. > [tab] TypeScript > > Three patterns for credit calculation: > > ```typescript theme={null} > // Pattern 1: Static number — always costs 1 credit > const searchData = tool( > requiresPayment( > (args) => `Results for ${args.query}`, > { payments, planId: PLAN_ID, credits: 1 } > ), > { name: 'search_data', description: '...', schema: z.object({ query: z.string() }) } > ) > > // Pattern 2: Arrow function — cost scales with output length > const summarize = tool( > requiresPayment( > (args) => `Summary of ${args.text}`, > { > payments, planId: PLAN_ID, > credits: (ctx) => Math.max(2, Math.min(Math.floor(String(ctx.result).length / 100), 10)), > } > ), > { name: 'summarize', description: '...', schema: z.object({ text: z.string() }) } > ) > > // Pattern 3: Named function — complex logic on args + result > function calcCredits(ctx: { args: Record; result: unknown }): number { > const topic = String(ctx.args.topic || '') > const result = String(ctx.result || '') > const base = 3 > const keywordExtra = Math.max(0, topic.split(' ').length - 3) > const outputExtra = Math.floor(result.length / 200) > return Math.min(base + keywordExtra + outputExtra, 15) > } > > const research = tool( > requiresPayment( > (args) => `Report on ${args.topic}`, > { payments, planId: PLAN_ID, credits: calcCredits } > ), > { name: 'research', description: '...', schema: z.object({ topic: z.string() }) } > ) > ``` > > The credits function receives `{ args, result }` after tool execution. > [tab] Python > > Three patterns for credit calculation: > > ```python theme={null} > # Pattern 1: Static int — always costs 1 credit > @tool > @requires_payment(payments=payments, plan_id=PLAN_ID, credits=1) > def search_data(query: str, config: RunnableConfig) -> str: > ... > > # Pattern 2: Lambda — cost scales with output length > @tool > @requires_payment( > payments=payments, plan_id=PLAN_ID, > credits=lambda ctx: max(2, min(len(ctx.get("result", "")) // 100, 10)), > ) > def summarize_data(text: str, config: RunnableConfig) -> str: > ... > > # Pattern 3: Named function — complex logic on args + result > def calc_credits(ctx: dict) -> int: > args = ctx.get("args", {}) > result = ctx.get("result", "") > base = 3 > keyword_extra = max(0, len(args.get("topic", "").split()) - 3) > output_extra = len(result) // 200 > return min(base + keyword_extra + output_extra, 15) > > @tool > @requires_payment(payments=payments, plan_id=PLAN_ID, credits=calc_credits) > def research_topic(topic: str, config: RunnableConfig) -> str: > ... > ``` > > The `ctx` dict passed to the credits function contains: > > * `args` — the tool's input arguments > * `result` — the tool's return value (evaluated after execution) *** ## Approach 2: HTTP Server with Payment Middleware For serving the agent over HTTP, use payment middleware on your framework. Payment is handled at the HTTP layer — tools are plain functions with no decorators or payment config. ### x402 Payment Flow (HTTP) ```mermaid theme={null} sequenceDiagram participant Client participant Agent Client->>Agent: 1. POST /ask (no token) Agent-->>Client: 2. 402 Payment Required
Header: payment-required (base64) Note over Client: 3. Generate x402 token via SDK Client->>Agent: 4. POST /ask
Header: payment-signature (token) Note over Agent: Verify permissions
Run LLM agent
Settle (burn credits) Agent-->>Client: 5. 200 OK + AI response
Header: payment-response (base64) ``` ### Server: LangChain > [tab] TypeScript (Express) > > ```typescript filename="src/server.ts" theme={null} > import 'dotenv/config' > import express from 'express' > import { HumanMessage, ToolMessage } from '@langchain/core/messages' > import { tool } from '@langchain/core/tools' > import { ChatOpenAI } from '@langchain/openai' > import { z } from 'zod' > import { Payments } from '@nevermined-io/payments' > import { paymentMiddleware } from '@nevermined-io/payments/express' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: process.env.NVM_ENVIRONMENT || 'sandbox', > }) > > const PLAN_ID = process.env.NVM_PLAN_ID! > > // Plain tools — no requiresPayment, no config parameter > const searchData = tool( > (args) => `Results for '${args.query}': ...`, > { name: 'search_data', description: 'Search for data.', schema: z.object({ query: z.string() }) } > ) > > const summarizeData = tool( > (args) => `Summary: ...`, > { name: 'summarize_data', description: 'Summarize text.', schema: z.object({ text: z.string() }) } > ) > > // LLM + tools > const llm = new ChatOpenAI({ model: 'gpt-4o-mini', temperature: 0 }) > const tools = [searchData, summarizeData] > const llmWithTools = llm.bindTools(tools) > const toolMap = new Map(tools.map((t) => [t.name, t])) > > async function runAgent(query: string): Promise { > const messages: any[] = [new HumanMessage(query)] > for (let i = 0; i < 10; i++) { > const ai = await llmWithTools.invoke(messages) > messages.push(ai) > if (!ai.tool_calls?.length) return String(ai.content) > for (const tc of ai.tool_calls) { > const result = await (toolMap.get(tc.name) as any).invoke(tc.args) > messages.push(new ToolMessage({ content: result, tool_call_id: tc.id! })) > } > } > return String(messages.at(-1)?.content || 'No response.') > } > > // Express app with payment middleware > const app = express() > app.use(express.json()) > app.use(paymentMiddleware(payments, { > 'POST /ask': { planId: PLAN_ID, credits: 1 }, > })) > > app.post('/ask', async (req, res) => { > const response = await runAgent(req.body.query) > res.json({ response }) > }) > > app.get('/health', (_req, res) => res.json({ status: 'ok' })) > > app.listen(8000, () => console.log('Running on http://localhost:8000')) > ``` > [tab] Python (FastAPI) > > ```python filename="src/server.py" theme={null} > import os > from dotenv import load_dotenv > > load_dotenv() > > import uvicorn > from fastapi import FastAPI, Request > from fastapi.responses import JSONResponse > from langchain_core.messages import HumanMessage, ToolMessage > from langchain_core.tools import tool > from langchain_openai import ChatOpenAI > from pydantic import BaseModel > from payments_py import Payments, PaymentOptions > from payments_py.x402.fastapi import PaymentMiddleware > > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_API_KEY"], > environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), > ) > ) > > PLAN_ID = os.environ["NVM_PLAN_ID"] > AGENT_ID = os.environ.get("NVM_AGENT_ID") > > # Plain tools — no @requires_payment, no RunnableConfig > @tool > def search_data(query: str) -> str: > """Search for data on a given topic.""" > return f"Results for '{query}': ..." > > @tool > def summarize_data(text: str) -> str: > """Summarize text into bullet points.""" > return f"Summary: ..." > > # LLM + tools > llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) > tools = [search_data, summarize_data] > llm_with_tools = llm.bind_tools(tools) > tool_map = {t.name: t for t in tools} > > > def run_agent(query: str) -> str: > """Run the LangChain agent with a tool-call loop.""" > messages = [HumanMessage(content=query)] > for _ in range(10): > ai = llm_with_tools.invoke(messages) > messages.append(ai) > if not ai.tool_calls: > return ai.content > for tc in ai.tool_calls: > result = tool_map[tc["name"]].invoke(tc["args"]) > messages.append(ToolMessage(content=result, tool_call_id=tc["id"])) > return messages[-1].content > > > # FastAPI app with payment middleware > app = FastAPI(title="LangChain Agent with x402 Payments") > > app.add_middleware( > PaymentMiddleware, > payments=payments, > routes={ > "POST /ask": {"plan_id": PLAN_ID, "credits": 1, "agent_id": AGENT_ID}, > }, > ) > > > class AskRequest(BaseModel): > query: str > > > @app.post("/ask") > async def ask(body: AskRequest, request: Request) -> JSONResponse: > response = run_agent(body.query) > return JSONResponse(content={"response": response}) > > > @app.get("/health") > async def health(): > return {"status": "ok"} > > > if __name__ == "__main__": > uvicorn.run(app, host="0.0.0.0", port=8000) > ``` ### Server: LangGraph Replace the tool-call loop with LangGraph's `create_react_agent`: > [tab] TypeScript > > ```typescript theme={null} > import { tool } from '@langchain/core/tools' > import { ChatOpenAI } from '@langchain/openai' > import { createReactAgent } from '@langchain/langgraph/prebuilt' > import { z } from 'zod' > > // Plain tools — no payment wrappers > const searchData = tool( > (args) => `Results for '${args.query}': ...`, > { name: 'search_data', description: 'Search.', schema: z.object({ query: z.string() }) } > ) > > const agent = createReactAgent({ > llm: new ChatOpenAI({ model: 'gpt-4o-mini' }), > tools: [searchData, summarizeData], > }) > > async function runAgent(query: string): Promise { > const result = await agent.invoke({ messages: [{ role: 'human', content: query }] }) > const messages = result.messages || [] > return messages.at(-1)?.content || 'No response.' > } > ``` > [tab] Python > > ```python theme={null} > from langchain_core.tools import tool > from langchain_openai import ChatOpenAI > from langgraph.prebuilt import create_react_agent > > # Plain tools — no payment decorators > @tool > def search_data(query: str) -> str: > """Search for data on a given topic.""" > return f"Results for '{query}': ..." > > llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) > graph = create_react_agent(llm, [search_data, summarize_data]) > > > def run_agent(query: str) -> str: > result = graph.invoke({"messages": [("human", query)]}) > messages = result.get("messages", []) > return messages[-1].content if messages else "No response." > ``` The HTTP app, middleware, and route handlers are identical to the LangChain version above. ### Client: Full x402 HTTP Flow > [tab] TypeScript > > ```typescript filename="src/client.ts" theme={null} > import 'dotenv/config' > import { Payments } from '@nevermined-io/payments' > > const SERVER_URL = process.env.SERVER_URL || 'http://localhost:8000' > const PLAN_ID = process.env.NVM_PLAN_ID! > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_SUBSCRIBER_API_KEY!, > environment: process.env.NVM_ENVIRONMENT || 'sandbox', > }) > > // Step 1: Request without token → 402 > const resp402 = await fetch(`${SERVER_URL}/ask`, { > method: 'POST', > headers: { 'Content-Type': 'application/json' }, > body: JSON.stringify({ query: 'AI trends' }), > }) > console.log(`Status: ${resp402.status}`) // 402 > > // Step 2: Decode payment requirements > const pr = JSON.parse(Buffer.from(resp402.headers.get('payment-required')!, 'base64').toString()) > console.log(`Plan: ${pr.accepts[0].planId}`) > > // Step 3: Acquire x402 token > // Create a delegation once, then reuse its id to mint tokens. > const { delegationId } = await payments.delegation.createDelegation({ > provider: 'erc4337', // 'stripe' | 'braintree' | 'visa' for fiat plans > spendingLimitCents: 10000, // $100 budget > durationSecs: 604800, // 7 days > currency: 'usdc', // 'usd' for fiat plans > }) > const token = await payments.x402.getX402AccessToken(PLAN_ID, undefined, { > scheme: 'nvm:erc4337', // 'nvm:card-delegation' for fiat plans > delegationConfig: { delegationId }, > }) > const accessToken = token.accessToken > > // Step 4: Request with token → 200 > const resp200 = await fetch(`${SERVER_URL}/ask`, { > method: 'POST', > headers: { > 'Content-Type': 'application/json', > 'payment-signature': accessToken, > }, > body: JSON.stringify({ query: 'AI trends' }), > }) > const body = await resp200.json() > console.log(`Response: ${body.response}`) > > // Step 5: Decode settlement receipt > const settlement = JSON.parse( > Buffer.from(resp200.headers.get('payment-response')!, 'base64').toString() > ) > console.log(`Credits charged: ${settlement.creditsRedeemed}`) > console.log(`Remaining balance: ${settlement.remainingBalance}`) > console.log(`Transaction: ${settlement.transaction}`) > ``` > [tab] Python > > ```python filename="src/client.py" theme={null} > import base64 > import json > import os > import httpx > from payments_py import Payments, PaymentOptions > from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload > > SERVER_URL = os.environ.get("SERVER_URL", "http://localhost:8000") > PLAN_ID = os.environ["NVM_PLAN_ID"] > > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_SUBSCRIBER_API_KEY"], > environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), > ) > ) > > with httpx.Client(timeout=60.0) as client: > # Step 1: Request without token → 402 > resp = client.post(f"{SERVER_URL}/ask", json={"query": "AI trends"}) > assert resp.status_code == 402 > > # Step 2: Decode payment requirements > pr = json.loads(base64.b64decode(resp.headers["payment-required"])) > print(f"Plan: {pr['accepts'][0]['planId']}") > > # Step 3: Acquire x402 token > # Create a delegation once, then reuse its id to mint tokens. > delegation = payments.delegation.create_delegation( > CreateDelegationPayload( > provider="erc4337", spending_limit_cents=10000, duration_secs=604800, currency="usdc", > ) > ) > token = payments.x402.get_x402_access_token( > plan_id=PLAN_ID, > token_options=X402TokenOptions( > scheme="nvm:erc4337", # "nvm:card-delegation" for fiat plans > delegation_config=DelegationConfig(delegation_id=delegation.delegation_id) > ), > ) > access_token = token["accessToken"] > > # Step 4: Request with token → 200 > resp = client.post( > f"{SERVER_URL}/ask", > headers={"payment-signature": access_token}, > json={"query": "AI trends"}, > ) > print(f"Response: {resp.json()['response']}") > > # Step 5: Decode settlement receipt > settlement = json.loads(base64.b64decode(resp.headers["payment-response"])) > print(f"Credits charged: {settlement['creditsRedeemed']}") > print(f"Remaining balance: {settlement['remainingBalance']}") > print(f"Transaction: {settlement['transaction']}") > ``` ### x402 HTTP Headers | Header | Direction | Description | | - | - | - | | `payment-signature` | Client → Server | x402 access token | | `payment-required` | Server → Client (402) | Base64-encoded payment requirements | | `payment-response` | Server → Client (200) | Base64-encoded settlement receipt | The settlement receipt (`payment-response`) contains: | Field | Description | | - | - | | `creditsRedeemed` | Number of credits charged | | `remainingBalance` | Subscriber's remaining credit balance | | `transaction` | Blockchain transaction hash | | `network` | Blockchain network (CAIP-2 format) | | `payer` | Subscriber wallet address | *** ## Decorator Configuration ### With Agent ID > [tab] TypeScript > > ```typescript theme={null} > const myTool = tool( > requiresPayment( > (args) => `Result for ${args.query}`, > { > payments, > planId: PLAN_ID, > credits: 1, > agentId: process.env.NVM_AGENT_ID, > } > ), > { name: 'my_tool', description: '...', schema: z.object({ query: z.string() }) } > ) > ``` > [tab] Python > > ```python theme={null} > @tool > @requires_payment( > payments=payments, > plan_id=PLAN_ID, > credits=1, > agent_id=os.environ.get("NVM_AGENT_ID"), > ) > def my_tool(query: str, config: RunnableConfig) -> str: > ... > ``` ### Multiple Plans (Python only) ```python theme={null} @tool @requires_payment( payments=payments, plan_ids=["plan-basic", "plan-premium"], credits=1, ) def my_tool(query: str, config: RunnableConfig) -> str: ... ``` ### Scheme and Network > [tab] TypeScript > > ```typescript theme={null} > const myTool = tool( > requiresPayment( > (args) => `Result`, > { payments, planId: PLAN_ID, credits: 1, network: 'eip155:84532' } > ), > { name: 'my_tool', description: '...', schema: z.object({ query: z.string() }) } > ) > ``` > [tab] Python > > ```python theme={null} > # Explicit card-delegation scheme for fiat payments > @tool > @requires_payment( > payments=payments, > plan_id=PLAN_ID, > credits=1, > scheme="nvm:card-delegation", > ) > def my_fiat_tool(query: str, config: RunnableConfig) -> str: > ... > ``` > [!NOTE] > > The decorator/wrapper automatically detects the payment scheme from plan metadata. > Plans with fiat pricing (`isCrypto: false`) use `nvm:card-delegation` (Stripe). > **No code changes are needed on the agent side.** ## Complete Examples Working seller/buyer agents with LangGraph — includes both Python and TypeScript variants: > [tab] TypeScript > > * [seller-simple-agent/ts](https://github.com/nevermined-io/hackathons/tree/main/agents/seller-simple-agent/ts) — Seller with `paymentMiddleware` + `requiresPayment` demo > * [buyer-simple-agent/ts](https://github.com/nevermined-io/hackathons/tree/main/agents/buyer-simple-agent/ts) — Buyer CLI agent with x402 token generation > > Each includes: > > * `src/server.ts` / `src/agent.ts` — LangGraph `createReactAgent` with payment-protected tools > * `src/demo.ts` — `requiresPayment` wrapper demo (seller only) > * `src/client.ts` — HTTP client with full x402 payment flow > [tab] Python > > * [seller-simple-agent](https://github.com/nevermined-io/hackathons/tree/main/agents/seller-simple-agent) — `src/langgraph_agent.py` with `@requires_payment` decorator > * [buyer-simple-agent](https://github.com/nevermined-io/hackathons/tree/main/agents/buyer-simple-agent) — `src/langgraph_agent.py` with buyer tools > > Each includes: > > * `src/langgraph_agent.py` — LangGraph `create_react_agent` with payment-protected tools > * `src/agent_langgraph.py` — Interactive CLI entry point ## Environment Variables ```bash filename=".env" theme={null} # Nevermined (required) NVM_API_KEY=sandbox:your-api-key # Builder/server API key NVM_SUBSCRIBER_API_KEY=sandbox:your-key # Subscriber/client API key NVM_ENVIRONMENT=sandbox NVM_PLAN_ID=your-plan-id NVM_AGENT_ID=your-agent-id # Optional # LLM Provider OPENAI_API_KEY=sk-your-openai-key ``` ## Next Steps > [card] [Express Middleware (TS)](/docs/integrate/add-to-your-agent/express) > > Deep dive into paymentMiddleware for Express > [card] [FastAPI Middleware (Python)](/docs/integrate/add-to-your-agent/fastapi) > > Deep dive into PaymentMiddleware for FastAPI > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Deep dive into x402 payment flows > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Configure credits, subscriptions, and dynamic pricing # LangSmith Deployment Source: https://nevermined.ai/docs/integrate/add-to-your-agent/langsmith-deployment Gate a LangGraph agent deployed to LangSmith Deployment with Nevermined x402 > [!NOTE] > > **Start here:** need to register a service and create a plan first? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). > [card] [Runnable tutorial](https://github.com/nevermined-io/tutorials/tree/main/langchain-langsmith-deployment-py) > > **`langchain-langsmith-deployment-py`** — a deliberately minimal LangGraph agent > with `POST /threads/{id}/runs/wait` gated by Nevermined x402. Clone, fill in > `.env`, run `poetry run buyer` to drive the full 402 → token-acquisition → > settlement round-trip in five numbered steps. Add payment protection to a [LangGraph](https://www.langchain.com/langgraph) agent deployed to **LangSmith Deployment** (the rebrand of LangGraph Platform) using the [x402 protocol](https://github.com/coinbase/x402). This is the deployment-time alternative to the per-tool `@requires_payment` decorator covered in [LangChain](./langchain) — both can coexist; they protect different layers. | Layer | Tool-time ([LangChain](./langchain)) | Deployment-time (this page) | | - | - | - | | Code surface | `@requires_payment` on individual `@tool` functions | `PaymentMiddleware` mounted via `langgraph.json` `http.app` | | Gated unit | A single tool call inside the agent | The agent's HTTP entry point (e.g. `POST /threads/{id}/runs/wait`) | | Charge frequency | Once per tool invocation | Once per HTTP request to the deployment | | Runtime | Any LangChain / LangGraph host | LangSmith Deployment, `langgraph dev`, `langgraph up` | ## Install ```bash theme={null} pip install payments-py[langsmith] ``` The `[langsmith]` extra pulls `fastapi`, `starlette`, and `langsmith`. > [!NOTE] > > **Python only.** LangSmith Deployment's custom-app surface is documented by > LangChain as Python-only. A TypeScript variant is tracked in our LangChain > integration epic but blocked on LangChain shipping a TS runtime. ## Define the middleware app Create `nvm_app.py` next to your `langgraph.json`. Four lines of glue: ```python theme={null} # nvm_app.py import os from payments_py import Payments, PaymentOptions from payments_py.langsmith import build_payment_app, RouteConfig payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), ) ) app = build_payment_app( payments=payments, routes={ "POST /threads/{thread_id}/runs/wait": RouteConfig( plan_id=os.environ["NVM_PLAN_ID"], credits=int(os.environ.get("NVM_CREDITS_PER_INVOKE", "1")), ), }, ) ``` `build_payment_app` returns a FastAPI app pre-wired with `PaymentMiddleware`. Mount it from `langgraph.json`: ```json theme={null} { "graphs": { "my_agent": "./src/agent.py:graph" }, "http": { "app": "./nvm_app.py:app" }, "env": ".env" } ``` That's the whole integration. `langgraph dev` (local) and `langgraph up` (Docker) both honor the `http.app` field; the middleware composes around LangSmith Deployment's built-in routes (`/runs`, `/threads/{id}/runs`, `/assistants`, etc.). > [!NOTE] > > **Why FastAPI?** Some `langgraph-api` versions crash on plain Starlette `http.app` > wrappers due to an upstream OpenAPI generation bug. FastAPI takes a clean path > through `app.openapi()`. The `build_payment_app` factory returns a FastAPI app > so you do not need to know about this — `PaymentMiddleware` itself is a > `BaseHTTPMiddleware` and works on both. ## The 402 round-trip ```bash theme={null} # 1. Create a thread (unprotected) THREAD=$(curl -s -X POST http://127.0.0.1:2024/threads \ -H 'content-type: application/json' -d '{}' | jq -r .thread_id) # 2. First attempt without payment-signature → 402 + envelope curl -i -X POST "http://127.0.0.1:2024/threads/$THREAD/runs/wait" \ -H 'content-type: application/json' \ -d '{"assistant_id":"my_agent","input":{"messages":[{"type":"human","content":"hello"}]}}' # HTTP/1.1 402 Payment Required # payment-required: eyJ4NDAyVmVyc2lvbi... ← base64-encoded x402 envelope # {"error":"Payment Required","message":"Missing x402 payment token..."} # 3. Acquire an x402 token from the envelope's plan_id (via payments-py) # 4. Retry with the payment-signature header → 200 + settlement receipt curl -i -X POST "http://127.0.0.1:2024/threads/$THREAD/runs/wait" \ -H 'content-type: application/json' \ -H "payment-signature: $TOKEN" \ -d '{"assistant_id":"my_agent","input":{"messages":[{"type":"human","content":"hello"}]}}' # HTTP/1.1 200 OK # payment-response: eyJzdWNjZXNzIjp0cn... ← base64-encoded SettleResponse # {"messages":[{"type":"human","content":"hello"},{"type":"ai","content":""}]} ``` Steps 3-4 in real client code: see the [buyer script](https://github.com/nevermined-io/tutorials/blob/main/langchain-langsmith-deployment-py/src/buyer.py) in the tutorial. The buyer uses `payments_py.x402.resolve_scheme.resolve_network` to pick the right enrolled payment method from the plan metadata. ## Per-route pricing `RouteConfig` accepts a static `int` or a callable for `credits`: ```python theme={null} from payments_py.langsmith import build_payment_app, RouteConfig app = build_payment_app( payments=payments, routes={ "POST /threads/{thread_id}/runs/wait": RouteConfig( plan_id="plan-cheap", credits=1, ), # Dynamic credits — sync or async callable "POST /threads/{thread_id}/runs/stream": RouteConfig( plan_id="plan-premium", credits=lambda req: estimate_credits(req), ), }, ) ``` Path parameters work with either Starlette `:param` or FastAPI/LangGraph `{param}` syntax — both match by position. Routes not listed pass through ungated. ## Lifecycle The middleware implements the canonical x402 **verify → agent runs → settle** ordering inside one HTTP cycle. Failed agent runs (non-2xx) skip settlement so buyers are not charged. Settle failures after a successful 2xx are logged but do not surface to the client — the buyer already received the value. For the full step-by-step diagram, see [chapter 13 of the SDK docs](https://nevermined-io.github.io/payments-py/api/13-langsmith-deployment/#lifecycle). ## Why `/runs/wait` specifically LangSmith Deployment exposes three run-execution shapes: | Endpoint | Behavior | Works with this middleware? | | - | - | - | | `POST /threads/{id}/runs/wait` | Synchronous; blocks until the agent finishes, returns final state | **Yes** — the only path that fits verify-then-work-then-settle in one HTTP cycle | | `POST /threads/{id}/runs` | Background; returns 202 immediately with a `run_id` | No — settle would fire before the agent did the work | | `POST /threads/{id}/runs/stream` | Server-sent events; streams agent output | Partially — the middleware buffers the response body to attach the settlement header, which negates streaming | Gate `/runs/wait` for a clean demo. The middleware will pass through `/threads`, `/assistants/search`, `/info`, `/ok`, and other non-billable endpoints automatically. ## Observability When `LANGSMITH_TRACING=true` is set, the middleware emits two top-level traces per gated request: ``` nvm:x402-request ← middleware parent trace ├─ nvm:verify ← child, nvm.* metadata (plan_ids, scheme, network, payer, payment_token abbreviated) └─ nvm:settlement ← child, nvm.* metadata (credits_redeemed, balance.after, tx_hash) my_agent ← LangGraph's separate trace (sibling, not nested) ``` The graph's trace appears as a sibling top-level because `langgraph-api` initiates it at the graph-invocation boundary, independent of our middleware's trace context. Both nvm spans plus the parent carry searchable `nvm.*` metadata; the raw `payment-signature` token is abbreviated to `eyJ4NDAyVmVyc2lvb…bsig`-style so it can be cross-referenced without exposure. Verification failures raise `PaymentRequiredError` inside `verify_span` so LangSmith marks the parent + child as **failed** via the canonical context-manager exit path. Settle failures after a successful 2xx mark only the settle child as failed; the parent stays successful (matching the buyer-visible 200). ## Host a chat UI on top of the deployment > [card] [Runnable tutorial](https://github.com/nevermined-io/tutorials/tree/main/langchain-chat-ui-nvm) > > **`langchain-chat-ui-nvm`** — a Next.js fork of LangChain's `agent-chat-ui` > with a card-delegation popup and an x402-aware proxy. Pairs with the > **`langchain-research-agent-py`** companion (in-tool `@requires_payment`) > for a full browser demo. The CLI buyer above is enough to validate the protocol, but most demos want a face. The `langchain-chat-ui-nvm` tutorial does this by forking `langchain-ai/agent-chat-ui` and adding a handful of Next.js API routes plus a popup target. > [!NOTE] > > This section describes a chat-UI host built on top of the **in-tool** gating > pattern (`@requires_payment` from [LangChain](./langchain)) rather than the > route-level middleware on the rest of this page. The middleware gates every > HTTP request — fine for "every call is paid" pricing, but it forces users to > pay before they can ask the agent what it does. The chat-UI flow benefits > from letting the LLM act as a free concierge (introspection, capability > discovery) and only charging when a paid tool actually fires. Pick by UX: > the same `PaymentMiddleware` would work if you want a hard paywall in front > of `/runs/stream`. The flow: 1. The user opens the chat and clicks **Authorize** on a top banner. A popup opens at `https://embed./cards/setup?sessionToken=…&returnUrl=…/x402-callback&state=…` (e.g. `embed.nevermined.dev` for staging, `embed.nevermined.app` for production — the standalone embed app that replaced the webapp's removed `/embed/*` routes). 2. They enrol a card on the embed page (Stripe, Braintree, or Visa Intelligent Commerce) and pick a budget — e.g. **\$10 / 24 h** — then submit. 3. Nevermined redirects the popup back to the chat UI's callback page with `paymentMethodId`, `delegationId`, and the round-tripped `state` nonce. The callback validates `state`, `postMessage`s the IDs to `window.opener`, then closes itself. 4. The chat UI's Next.js server mints an x402 access token from the `delegationId` (`payments.x402.getX402AccessToken(planId, agentId, { delegationConfig: { delegationId } })`, pattern B in `@nevermined-io/payments`) and stores it in a `httpOnly` cookie. The browser never sees the raw token. 5. From then on, the catch-all `/api/[..._path]` proxy reads the cookie on every outgoing LangGraph run and JSON-injects it into the run body at `config.configurable.payment_token` — the contract `@requires_payment` reads from. The agent's tool runs verify → execute → settle internally; the LLM concierge handles everything else for free. The `NVM_API_KEY` lives only on the Next.js server. The browser holds, at most, the short-lived `sessionToken` for the duration of the popup. Because gating is in-graph (no `http.app` on `langgraph.json`), neither `/runs/wait` nor `/runs/stream` need to be in any `routes` map — the chat UI's `useStream` hits `/runs/stream` and the tool itself decides whether to charge. ``` Browser → Next.js proxy → LangGraph (vanilla, no middleware) └─ tool ─ @requires_payment ── facilitator Browser → /api/x402/session → POST /api/v1/widgets/session/self (mint widget session) Browser → popup → embed./cards/setup (user authorizes) Browser ← postMessage(delegationId) ← /x402-callback (popup closes) Browser → /api/x402/token → mints x402 access token, sets cookie ``` Important constraints: * The widget session uses the **self-mint** endpoint (`POST /api/v1/widgets/session/self`), which restricts `returnUrl` to `localhost` / `127.0.0.1` / `[::1]`. Deploying the chat UI to a real domain requires the [widget-key flow](/docs/integrations/organization-widgets) instead. * The agent's paid tool is bound to a **single plan** in this demo (the chat UI reads `NVM_PLAN_ID` from env, the tool uses the matching plan id in `@requires_payment(plan_id=…)`). Multi-tool agents with mixed pricing need one `accepts[]` entry per paid tool. * The popup pattern needs same-origin between the chat UI and the callback page (both served by Next.js). Full setup, troubleshooting, and architecture notes live in the [tutorial README](https://github.com/nevermined-io/tutorials/blob/main/langchain-chat-ui-nvm/README.md). ## Combining with `@requires_payment` The middleware and the [LangChain decorator](./langchain) can be used together — the middleware gates the agent's HTTP entry point, the decorator gates individual tools inside the agent. Each layer charges independently. Common pattern: charge a flat rate per agent invocation (middleware) plus dynamic per-tool credits (decorator) for expensive tool calls. The chat-UI tutorial above is an example of using the decorator **alone** at deployment-time (no middleware on the HTTP layer). That choice is driven by the UX — free introspection, paid execution — and it composes cleanly with vanilla LangSmith Deployment because the agent doesn't need a custom `http.app`. ## Limitations * **Streaming responses are buffered.** The middleware reads the downstream response body in full before attaching the `payment-response` settlement header. SSE / `/runs/stream` endpoints become blocking-then-bulk. Gate `/runs/wait` only, or accept the trade-off. * **Python only.** TypeScript variant tracked but blocked on LangChain shipping a TS runtime. * **Sync I/O is wrapped.** The four sync SDK calls (`resolve_scheme`, `resolve_network`, `verify_permissions`, `settle_permissions`) run via `asyncio.to_thread(...)` so they don't block the event loop. `langgraph dev`'s blocking-call detector treats unwrapped sync HTTP as fatal warnings. ## See also * [LangChain](./langchain) — tool-time `@requires_payment` decorator * [`payments-py[langsmith]` SDK docs (chapter 13)](https://nevermined-io.github.io/payments-py/api/13-langsmith-deployment/) — full API reference * [`langchain-langsmith-deployment-py` tutorial](https://github.com/nevermined-io/tutorials/tree/main/langchain-langsmith-deployment-py) — runnable CLI end-to-end demo of route-level middleware gating (this page) * [`langchain-research-agent-py` tutorial](https://github.com/nevermined-io/tutorials/tree/main/langchain-research-agent-py) — companion in-tool gating demo (freemium ReAct agent) used by the chat UI * [`langchain-chat-ui-nvm` tutorial](https://github.com/nevermined-io/tutorials/tree/main/langchain-chat-ui-nvm) — browser chat UI with card-delegation popup * [Card delegation — white-label redirect](/docs/solutions/card-delegation) — full reference for the embed-app `/cards/setup` flow used by the chat UI popup # Strands Source: https://nevermined.ai/docs/integrate/add-to-your-agent/strands Add Nevermined x402 payments to your Strands AI agent tools > [!NOTE] > > **Start here:** need to register a service and create a plan first? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). Add payment protection to your Strands AI agent tools using the [x402 protocol](https://github.com/coinbase/x402). The `@requires_payment` decorator handles verification and settlement automatically. ## x402 Payment Flow ```mermaid theme={null} sequenceDiagram participant Client participant Agent participant NVM as Nevermined Client->>Agent: agent(prompt) — no token Agent-->>Client: PaymentRequired error (tool result) Client->>Client: extract_payment_required(agent.messages) Client->>NVM: get_x402_access_token(plan_id, agent_id) NVM-->>Client: Access token Client->>Agent: agent(prompt, invocation_state=payment_token) Agent->>NVM: Verify permissions NVM-->>Agent: Valid Agent->>Agent: Execute tool Agent->>NVM: Settle (burn credits) NVM-->>Agent: Settled Agent-->>Client: Result ``` ## How Payment Errors Flow The `@requires_payment` decorator follows the [x402 MCP transport spec](https://github.com/coinbase/x402/blob/main/specs/transports-v2/mcp.md) — payment errors are returned as **tool results** with `status: "error"`, not raised as exceptions. Each error includes: 1. A **human-readable text block** explaining the payment requirement 2. A **structured JSON block** containing the full `PaymentRequired` object In Strands, tool errors flow through the LLM. The LLM sees the error and relays it to the user in natural language (e.g., *"I need a payment token to use this tool"*). The structured `PaymentRequired` data is preserved in `agent.messages`. Clients use `extract_payment_required(agent.messages)` to get the structured `PaymentRequired` dict from the conversation history. The `PaymentRequired` contains the `accepts` array with plan IDs, schemes, and networks needed to acquire an x402 access token. ## Installation ```bash theme={null} pip install payments-py[strands] strands-agents ``` > [!NOTE] > > The `[strands]` extra installs the Strands SDK dependency required for the decorator. ## Quick Start: Protecting a Tool The `@requires_payment` decorator wraps a Strands `@tool` function with x402 payment verification and settlement. > [!WARNING] > > You **must** use `@tool(context=True)` instead of plain `@tool`. This tells Strands to inject `tool_context` into the function, which the decorator needs to access `invocation_state` for the payment token. ```python filename="agent.py" theme={null} import os from dotenv import load_dotenv from strands import Agent, tool from payments_py import Payments, PaymentOptions from payments_py.x402.strands import requires_payment load_dotenv() # Initialize Payments payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), ) ) PLAN_ID = os.environ["NVM_PLAN_ID"] # Protect a tool with payment @tool(context=True) @requires_payment(payments=payments, plan_id=PLAN_ID, credits=1) def analyze_data(query: str, tool_context=None) -> dict: """Analyze data based on a query. Costs 1 credit per request. Args: query: The data analysis query to process. """ return { "status": "success", "content": [{"text": f"Analysis complete for: {query}"}], } # Create agent with payment-protected tools agent = Agent(tools=[analyze_data]) ``` That's it! The decorator automatically: * Returns a `PaymentRequired` error when no token is provided * Verifies the x402 token via the Nevermined facilitator * Executes the tool function on successful verification * Burns credits after successful execution ## Client-Side: Payment Discovery Clients discover payment requirements by calling the agent without a token, then extracting the `PaymentRequired` from the conversation history: ```python filename="client.py" theme={null} from payments_py import Payments, PaymentOptions from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload from payments_py.x402.strands import extract_payment_required from agent import agent, payments # Step 1: Call agent without token — triggers PaymentRequired result = agent("Analyze the latest sales trends") # Step 2: Extract PaymentRequired from conversation history payment_required = extract_payment_required(agent.messages) if payment_required: # Step 3: Choose a plan and acquire token chosen_plan = payment_required["accepts"][0] plan_id = chosen_plan["planId"] agent_id = (chosen_plan.get("extra") or {}).get("agentId") # Create a delegation once, then reuse its id to mint tokens. delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="erc4337", # "stripe" | "braintree" | "visa" for fiat plans spending_limit_cents=10000, # $100 budget duration_secs=604800, # 7 days currency="usdc", # "usd" for fiat plans ) ) token_response = payments.x402.get_x402_access_token( plan_id=plan_id, agent_id=agent_id, token_options=X402TokenOptions( scheme="nvm:erc4337", # "nvm:card-delegation" for fiat plans delegation_config=DelegationConfig(delegation_id=delegation.delegation_id) ), ) access_token = token_response["accessToken"] # Step 4: Call agent with payment token state = {"payment_token": access_token} result = agent("Analyze the latest sales trends", invocation_state=state) print(f"Result: {result}") # Step 5: Check settlement (stored in invocation_state after successful execution) settlement = state.get("payment_settlement") if settlement: print(f"Credits redeemed: {settlement.credits_redeemed}") ``` ## Decorator Configuration > [!NOTE] > > The decorator automatically detects the payment scheme from plan metadata. > Plans with fiat pricing (`isCrypto: false`) use `nvm:card-delegation` (Stripe). > **No code changes are needed on the agent side.** You can explicitly override with > the `scheme` parameter. ### Single Plan ```python theme={null} @tool(context=True) @requires_payment(payments=payments, plan_id="plan-123", credits=1) def my_tool(query: str, tool_context=None) -> dict: ... ``` ### Multiple Plans Accept multiple payment plans (e.g., basic and premium tiers): ```python theme={null} @tool(context=True) @requires_payment( payments=payments, plan_ids=["plan-basic", "plan-premium"], credits=1, ) def my_tool(query: str, tool_context=None) -> dict: ... ``` ### Dynamic Credits Calculate credits based on tool arguments: ```python theme={null} def calc_credits(kwargs): """Charge based on complexity.""" return kwargs.get("complexity", 1) * 2 @tool(context=True) @requires_payment(payments=payments, plan_id=PLAN_ID, credits=calc_credits) def my_tool(query: str, complexity: int = 1, tool_context=None) -> dict: ... ``` ### With Agent ID ```python theme={null} @tool(context=True) @requires_payment( payments=payments, plan_id=PLAN_ID, credits=1, agent_id=os.environ.get("NVM_AGENT_ID"), # Required for plans with multiple agents ) def my_tool(query: str, tool_context=None) -> dict: ... ``` ### Scheme and Network ```python theme={null} # Custom network for crypto payments @tool(context=True) @requires_payment( payments=payments, plan_id=PLAN_ID, credits=1, network="eip155:1", # Ethereum mainnet (default: eip155:84532 Base Sepolia) ) def my_crypto_tool(query: str, tool_context=None) -> dict: ... # Explicit card-delegation scheme for fiat payments @tool(context=True) @requires_payment( payments=payments, plan_id=PLAN_ID, credits=1, scheme="nvm:card-delegation", # Fiat/Stripe (network auto-set to "stripe") ) def my_fiat_tool(query: str, tool_context=None) -> dict: ... ``` ### Lifecycle Hooks ```python theme={null} def on_before_verify(payment_required): print(f"Verifying payment for {len(payment_required.accepts)} plans") def on_after_verify(verification): print(f"Verified! Request ID: {verification.agent_request_id}") def on_after_settle(credits_used, settlement): print(f"Settled {credits_used} credits") def on_payment_error(error): # Return custom error dict or None for default x402 error return None @tool(context=True) @requires_payment( payments=payments, plan_id=PLAN_ID, credits=1, on_before_verify=on_before_verify, on_after_verify=on_after_verify, on_after_settle=on_after_settle, on_payment_error=on_payment_error, ) def my_tool(query: str, tool_context=None) -> dict: ... ``` ## Accessing Payment Context After verification, the `PaymentContext` is available in `tool_context.invocation_state["payment_context"]`: ```python theme={null} from payments_py.x402.strands import PaymentContext @tool(context=True) @requires_payment(payments=payments, plan_id=PLAN_ID, credits=1) def my_tool(query: str, tool_context=None) -> dict: """Tool with payment context access.""" ctx = tool_context.invocation_state.get("payment_context") if ctx and isinstance(ctx, PaymentContext): print(f"Token: {ctx.token}") print(f"Credits: {ctx.credits_to_settle}") print(f"Request ID: {ctx.agent_request_id}") print(f"Verified: {ctx.verified}") return {"status": "success", "content": [{"text": "Done"}]} ``` ## Complete Example See the complete working example in the [strands-simple-agent](https://github.com/nevermined-io/hackathons/tree/main/agents/strands-simple-agent) directory on GitHub. It includes: * `agent.py` — Agent with payment-protected tools * `demo.py` — Full payment discovery and token acquisition flow ## Environment Variables ```bash filename=".env" theme={null} # Nevermined (required) NVM_API_KEY=sandbox:your-api-key NVM_ENVIRONMENT=sandbox NVM_PLAN_ID=your-plan-id NVM_AGENT_ID=your-agent-id # Optional # LLM Provider OPENAI_API_KEY=sk-your-openai-key # Or configure your preferred model provider ``` ## Next Steps > [card] [Payment Patterns](/docs/integrate/patterns/charge-credits) > > Advanced credit charging patterns > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Deep dive into x402 payment flows > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Configure credits, subscriptions, and dynamic pricing > [card] [strands-simple-agent](https://github.com/nevermined-io/hackathons/tree/main/agents/strands-simple-agent) > > Complete working example on GitHub # Connected Agents Source: https://nevermined.ai/docs/integrate/authentication/connections List and revoke the agents a user has authorized — the AgentBinding surface that backs both OAuth credential types. Every authorization ceremony — device flow or Authorization Code — records an **AgentBinding**: the consent receipt for what a user allowed an agent to do. "Connected agents" is the browser surface a user manages these from, and it covers **both credential types in one view**, each with a human-facing lifecycle state. > [!NOTE] > > The `/oauth/bindings` endpoints are browser-initiated and require a Nevermined API key: the subject comes from the authenticated session, so a caller only ever sees and manages **their own** bindings. `POST /oauth/revoke` (below) is the exception — it is public, because the token you present is itself the authorization to revoke it (RFC 7009). ## List connections ```http theme={null} GET /oauth/bindings?page=1&offset=50 Authorization: Bearer ``` Paginated with the API-wide convention — `page` (1-indexed) and `offset` (page size, default 50, max 100). `totalResults` is the honest total across all pages, and the applied `page`/`offset` are echoed back so you can tell when a requested page size was clamped. ```json theme={null} { "bindings": [ { "bindingId": "ab-a1b2c3d4", "clientId": "fleet", "agentId": "agent-weather-bot", "consentType": "credits_purchase", "state": "active", "createdAt": "2026-07-01T10:30:00Z" } ], "totalResults": 1, "page": 1, "offset": 50 } ``` ### Lifecycle states The `state` a user sees distinguishes *why* a binding is (or isn't) usable: | State | Meaning | | - | - | | `active` | Usable now. | | `expired` | The spend mandate's window elapsed — re-consent to renew. | | `exhausted` | The spend mandate's cap (amount or transaction count) is spent — raise the cap. | | `revoked` | Withdrawn. Shown, never hidden — it's the audit trail. | ## Revoke a connection ```http theme={null} POST /oauth/bindings/{bindingId}/revoke Authorization: Bearer ``` Returns `204`. One action kills **every credential minted from that binding**. A binding that isn't the caller's returns `404`, so a caller can't revoke — or probe — another user's bindings. ## Revoke a single credential To revoke one credential rather than a whole connection, use the RFC 7009 endpoint — it accepts either an NVM API key or an x402 access token: ```http theme={null} POST /oauth/revoke Content-Type: application/json { "token": "sandbox:eyJhbGci…" } ``` The `token_type_hint` field is advisory only; resolution doesn't depend on it. The endpoint is idempotent — revoking an already-revoked or unknown token succeeds. # Device Flow (RFC 8628) Source: https://nevermined.ai/docs/integrate/authentication/device-flow Get a Nevermined API key with a human's approval when your agent has no browser — the IETF device authorization grant, end to end. Use the **RFC 8628 device authorization grant** when your agent can't run a browser but a human can approve on its behalf. It needs no existing credential and, in the usual case, ends with an **NVM API key bound to the human who approved** — the same key you then send as `Authorization: Bearer …` on every call. ("Usual case" because the credential is actually selected by the `resource` you request — omit it (as below) or use this API's host for an API key; a non-API `resource` would mint an x402 permission instead. See [which credential you get](/docs/integrate/authentication/overview).) > [!NOTE] > > This is the "claim ceremony" an agent can use on its own. Both the `device_authorization_endpoint` and the `urn:ietf:params:oauth:grant-type:device_code` grant are advertised in the [RFC 8414 metadata](/docs/integrate/authentication/overview#discovery) — but discovery alone isn't enough to start: you still need a pre-registered `client_id` and an `agent_id` (below). ## Prerequisites * **A pre-registered `client_id`.** Connectors are onboarded out of band — there is no self-service dynamic client registration, and the metadata deliberately omits a `registration_endpoint`. An unregistered `client_id` is rejected with `BCK.OAUTH.0016`. If you don't have one, ask Nevermined to register your client. * **An `agent_id`** — the agent you want authorized. It's required today; an absent `agent_id` is rejected with `BCK.OAUTH.0018` (account-level authorization with no `agent_id` is a follow-up). ## The ceremony **1. Request a device + user code** ```http theme={null} POST /oauth/device_authorization Content-Type: application/json { "client_id": "fleet", "agent_id": "agent-123" } ``` Response: ```json theme={null} { "device_code": "a1b2c3…", "user_code": "BCDF-GHJK", "verification_uri": "https://nevermined.app/oauth/device?network=sandbox", "verification_uri_complete": "https://nevermined.app/oauth/device?network=sandbox&user_code=BCDF-GHJK", "expires_in": 600, "interval": 5 } ``` `device_code` is your machine secret (opaque — poll with it). `user_code` is what the human types. `interval` is the minimum seconds between polls. Both verification URIs carry the tier you called (`?network=sandbox|live`) — pass them on unchanged, so the human's browser opens the verification page on the tier your ceremony is pending on ([why](/docs/integrate/authentication/overview#each-tier-is-its-own-issuer-and-its-authorize-url-says-so)). **2. Send the human to approve** Show them the `verification_uri` and `user_code` (or the `verification_uri_complete` as a link/QR). They open it, sign in, review **who is asking and for what**, and approve. The verification page resolves what they see — the connector name, target agent, and scope — via `POST /oauth/device/details`. That endpoint requires the *human's* Nevermined API key (it's the browser verification surface), so your keyless agent can't call it to pre-preview; just hand off the `user_code` and poll. **3. Poll for the credential** ```http theme={null} POST /oauth/token Content-Type: application/json { "grant_type": "urn:ietf:params:oauth:grant-type:device_code", "device_code": "a1b2c3…", "client_id": "fleet" } ``` Honour the `interval` — the poll endpoint is rate-limited. Branch on the top-level `error`: | `error` | Meaning | What to do | | - | - | - | | `authorization_pending` | Human hasn't approved yet | Keep polling at `interval` | | `slow_down` | You're polling too fast | Add 5s to your interval, then continue | | `access_denied` | Human denied | **Stop** — terminal | | `expired_token` | The codes expired | **Stop** — start over | A real HTTP **`429`** (rate limit) is distinct from the `slow_down` grant error and does **not** appear in the `error` field — the poll endpoint is throttled **per client IP** (\~60/min for device polls, **shared across every concurrent ceremony from the same host**, not per `device_code`). Treat a `429` like `slow_down`: back off and resume. Note the throttler sends `Retry-After-short` / `Retry-After-long` headers rather than a plain `Retry-After`. On approval you receive your credential: ```json theme={null} { "access_token": "sandbox:eyJhbGciOiJFUzI1NksifQ…", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "nvm_rt_Zm9vYmFy…" } ``` **4. Use the key** `access_token` is your NVM API key. Send it as `Authorization: Bearer ` on every `/api/v1` call. Keep the `refresh_token` to mint a fresh key without another human step (RFC 6749 refresh grant). ## Refreshing When the key expires, exchange the refresh token — no human, no browser: ```http theme={null} POST /oauth/token Content-Type: application/json { "grant_type": "refresh_token", "refresh_token": "nvm_rt_Zm9vYmFy…", "client_id": "fleet" } ``` ## Revoking Either side can revoke (RFC 7009): ```http theme={null} POST /oauth/revoke Content-Type: application/json { "token": "sandbox:eyJhbGci…" } ``` The human can also revoke from the [Connected agents](/docs/integrate/authentication/connections) surface, which kills every credential minted from the binding. # Authentication for AI Agents Source: https://nevermined.ai/docs/integrate/authentication/for-agents If you are an AI agent, this is your entry point: fetch the machine-readable auth manifest, then follow it to obtain and use a Nevermined credential. > [!NOTE] > > **You are an agent reading this.** The single source of truth for how to authenticate — written for you, kept in lockstep with the API — is the manifest below. Fetch it and follow it. This page only orients you. ## Fetch the manifest ``` https://nevermined.app/auth.md ``` [`auth.md`](https://nevermined.app/auth.md) is the authoritative, always-current description of the **authentication ceremony**: the discovery metadata, the bearer contract, how to get a key (SDK, the RFC 8628 device flow, or — when you run inside an AI assistant such as Claude, ChatGPT or LangSmith Fleet — the OAuth **commerce consent** your host obtains for you against the Commerce MCP), what you can do without a human, and how to read errors. Everything it names exists today — follow it for the ceremony itself. For the human-in-the-loop picture and how each path maps to a credential, the [Authentication & Identity overview](/docs/integrate/authentication/overview) covers the human-gated surfaces (card enrolment, first-account creation, Visa delegation creation) and the `resource`→credential mapping. Treat the two as complementary: the manifest for the flow, the overview for the human decisions around it. When you hand a human an `authorization_endpoint` or a device-flow `verification_uri`, **keep its `?network=sandbox|live` query string intact** — the overview explains the [per-tier discovery quirk](/docs/integrate/authentication/overview#each-tier-is-its-own-issuer-and-its-authorize-url-says-so). Drop it and consent is served on whichever tier the browser last used (Live by default), so a Sandbox-only connector is then refused. Two more things the discovery document tells you. It advertises `authorization_response_iss_parameter_supported: true`: every redirect the consent screen sends back to your `redirect_uri` — success and denial — carries `iss`, equal to the document's `issuer`; compare the two and reject a mismatch before you redeem a code ([RFC 9207](/docs/integrate/authentication/overview#the-authorization-response-names-its-issuer-rfc-9207)). And it advertises no `scopes_supported` — Nevermined enforces no scope vocabulary at the API layer — with one exception the consent screen honours: if you took the authorize URL from discovery and want the **commerce** consent (an account-level spend cap for paying external services through the Router, with no `agent_id`), send `scope=commerce`; it selects that consent exactly as a hand-configured `consent_type=commerce` would ([details](/docs/integrate/authentication/oauth-authorization-code#prerequisites)). If you are an MCP host that presents an https URL as its `client_id` (ChatGPT, Claude Code), you need no registration at all for agent-specific grants; a `commerce` grant additionally needs the operator to have listed your URL — ChatGPT, Claude (the claude.ai connector) and Claude Code are listed out of the box ([details](/docs/integrate/authentication/oauth-authorization-code#self-registering-clients-identity-from-the-document-trust-from-the-operator)). # Authorization Code + PKCE Source: https://nevermined.ai/docs/integrate/authentication/oauth-authorization-code The OAuth 2.1 Authorization Code flow with PKCE — how a browser-based MCP client obtains an x402 payment permission for a specific Nevermined agent and plan. Use the **OAuth 2.1 Authorization Code flow with PKCE** when a browser-based MCP client (Cursor, Claude, and the like) connects to a paid Nevermined agent and the user approves in a browser. It's the browser-based counterpart to the no-browser [device flow](/docs/integrate/authentication/device-flow) — the two grants differ only in *how* the human approves. > [!NOTE] > > **Which credential you receive is chosen by the requested `resource`, not by the grant** ([details](/docs/integrate/authentication/overview)). To obtain an **x402 payment permission** — the credential you attach to x402 requests against the agent — request that agent's `resource`. If you omit `resource` and send only a `plan_id` (a plan-only binding with no delegation), the exchange returns an **NVM API key** instead. A `resource` matching the Nevermined API host also returns an API key. ## Prerequisites * **An authenticated user.** `POST /oauth/authorize` runs in the signed-in user's context — the browser client calls it with the user's Nevermined API key. Without an authenticated user it fails with `BCK.OAUTH.0007`. * **A `client_id` Nevermined knows.** Either a pre-registered connector — onboarded out of band, as for the device flow (no dynamic client registration; an unregistered slug is rejected with `BCK.OAUTH.0016`) — or an `https` URL naming a Client ID Metadata Document, which needs no registration for agent-specific grants (see [self-registering clients](#self-registering-clients-identity-from-the-document-trust-from-the-operator) below). The device flow accepts only the former. * **PKCE is mandatory.** Generate a `code_verifier` and its `code_challenge` (`S256`). There is no non-PKCE path. * **The right tier's authorize URL.** The browser step starts at the `authorization_endpoint` of the tier you are integrating with — `https://nevermined.app/oauth/authorize?network=sandbox` or `…?network=live` — as advertised by that tier's [RFC 8414 document](/docs/integrate/authentication/overview#each-tier-is-its-own-issuer-and-its-authorize-url-says-so). This is the **web app's consent page**, the URL a connector sends the user's browser to with `client_id`, `redirect_uri`, `code_challenge` and the rest in its **query string** — keep the `network` parameter when you add them; it is what makes the consent screen open on the tier your `client_id` is registered on. It is not the API's `POST /oauth/authorize` in Step 1 below, which the signed-in browser client calls on the API host with those same fields in a **JSON body** (and no `network` — by then the tier is fixed). The consent URL is the only one of the two an integrator ever configures by hand; if you do, paste it with its query string. * **Which consent you are asking for.** An `agent_id` on the authorize URL asks for an agent-specific grant (this page's flow). Without one, the consent is **account-level**, and its kind is named on the URL: `consent_type=commerce` for a spend cap the user funds from their Nevermined wallet for paying external services through the Router; nothing (or `consent_type=account_access`) for a card-backed account mandate. A **discovery-driven** client — one that took the endpoint from the RFC 8414 document and never saw a `consent_type` — selects the commerce consent with the standard OAuth `scope` parameter instead: `scope=commerce` (space-separated per RFC 6749 §3.3; extra scopes such as `offline_access` are tolerated and ignored) is treated as `consent_type=commerce`. An explicit `consent_type` is kept as long as `scope` does not contradict it; a contradiction — `consent_type=account_access&scope=commerce`, or `scope=commerce` together with an `agent_id` — is refused with an error rather than resolved silently. A hand-configured provider (LangSmith Fleet's Agent-Auth, say) keeps stating `?consent_type=commerce` on its authorize URL; `scope` is for clients that cannot. `scope` is not advertised in the discovery document (Nevermined publishes no `scopes_supported` — the API layer enforces no scope vocabulary) and never reaches the API: it only selects which consent screen the human sees. ## The flow **1. Request an authorization code** From the signed-in browser session, POST to the authorization endpoint with your PKCE challenge. The request is authenticated as the user (their Nevermined API key): ```http theme={null} POST /oauth/authorize Authorization: Bearer Content-Type: application/json { "client_id": "fleet", "agent_id": "agent-123", "resource": "https://mcp-server.example.com", "redirect_uri": "cursor://oauth/callback", "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "code_challenge_method": "S256", "state": "xyz", "plan_id": "105906634574379352540220884472" } ``` `client_id`, `redirect_uri`, `code_challenge`, and `code_challenge_method` are required; `agent_id`, `plan_id`, `state`, and `resource` are optional. `resource` is optional but load-bearing: the agent's `resource` here is what makes the exchange mint an **x402 payment permission** rather than an API key. Once the user approves the connection, the endpoint returns the `code` in the response body: ```json theme={null} { "code": "abc123…" } ``` Your client then completes the OAuth hand-off by redirecting the browser to `redirect_uri` with the `code` (and your `state`) appended — plus **`iss`**, the RFC 9207 issuer identifier, which equals the `issuer` of the tier's discovery document. A denial redirects the same way with `error=access_denied`, your `state`, and `iss`. Validate `iss` against the issuer you discovered before redeeming the code ([details](/docs/integrate/authentication/overview#the-authorization-response-names-its-issuer-rfc-9207)). **2. Exchange the code for the credential** Prove possession of the PKCE verifier and exchange the code: ```http theme={null} POST /oauth/token Content-Type: application/json { "grant_type": "authorization_code", "code": "abc123…", "redirect_uri": "cursor://oauth/callback", "client_id": "fleet", "code_verifier": "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" } ``` Response: ```json theme={null} { "access_token": "eyJhbGciOiJFUzI1NksifQ…", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "nvm_rt_Zm9vYmFy…" } ``` **3. Pay the agent** Because you requested the agent's `resource`, the `access_token` is an x402 payment permission for the agent+plan you were authorized against (unlike an NVM API key, it is a JWT and is **not** environment-prefixed). Use it on your x402 requests to that agent. See the [MCP integration](/docs/integrations/mcp) for how a paywalled MCP server consumes it. ## Connectors and consent The connection the user approves is recorded as an **AgentBinding** — the consent receipt. The `client_id` is the *connector* fronting the connection (Cursor, Claude, LangSmith Fleet), which is distinct from the *agent* the consent is for. Users can review and revoke these at any time from the [Connected agents](/docs/integrate/authentication/connections) surface. > [!NOTE] > > Both the `authorization_endpoint` and the `authorization_code` grant are advertised in the [RFC 8414 metadata](/docs/integrate/authentication/overview#discovery) — per tier, with the tier on the endpoint (`?network=sandbox|live`) — as is `authorization_response_iss_parameter_supported: true`, the promise that every authorization response carries `iss`. As with the device flow, discovery doesn't substitute for a `client_id` Nevermined accepts — a pre-registered connector, or a metadata-document URL for agent-specific grants; and a connector's registration (and a self-registering client's `commerce` trust) is per tier, so a client known to Sandbox is "not authorized" on Live and vice versa. ### Account-level grants are authorized per consent type Two grants ask for authority over the user's **whole account** rather than one agent, and both omit `agent_id`: | `consent_type` | What the user approves | Funded by | | - | - | - | | `account_access` (the default when `agent_id` is absent) | A capped, expiring **card mandate** — charges against a card the user enrolled | The user's saved card | | `commerce` | A capped, expiring **on-chain spending mandate** for paying external merchants through the Router | The user's own Nevermined wallet | A connector is authorized for each of these **separately** when it is registered. Being enabled for `commerce` does not enable `account_access`, and vice versa — an assistant that pays external services from the user's wallet never gains the ability to request a card mandate by asking for the other consent type. Registration carries an `accountLevelConsentTypes` list (`["commerce"]`, `["account_access"]`, or both); a connector registered before the list existed keeps both. Requesting a consent type your connector is not authorized for is refused with `BCK.OAUTH.0035` (`403`), whose `params.consentType` names the refused type — distinct from `BCK.OAUTH.0018` (your connector cannot request account-level authority at all, so `agent_id` is required) and `BCK.OAUTH.0025` (it can, but is not yet verified). The consent page checks this before it renders the spend form and tells the user which consent type was refused, so the human is never walked through a mandate the API would reject at approval. **Commerce-only connector.** The typical shape for an AI assistant that only needs to pay external services: registered with `accountLevelConsentTypes: ["commerce"]`, it starts the consent at the tier's `authorization_endpoint` with `consent_type=commerce` (and the `commerce_*` spend-cap fields — no card, no `agent_id`). A request from that same connector with neither `consent_type=commerce` nor an `agent_id` is an `account_access` request, and is refused with `BCK.OAUTH.0035`; its agent-specific grants (an `agent_id` plus `plan_id`) are unaffected. ### Self-registering clients: identity from the document, trust from the operator Not every connector is registered by hand. A client that follows the MCP authorization spec — ChatGPT, Claude Code, and hosts built on the same SDKs — presents an **https URL as its `client_id`** (a Client ID Metadata Document, CIMD). Nevermined fetches that URL, verifies the document names itself, and takes the client's name and redirect URIs from it. Ownership of the URL's domain is the identity proof, so there is nothing to register and nothing for an operator to type: every self-registering client can run the agent-specific flow on this page out of the box. What the document can **never** do is make its client trusted. Account-level grants — `commerce`, `account_access` — need `allowAccountLevel` and `trustTier: "verified"`, and a self-asserted document cannot grant itself those; a self-registering client that asks is refused with `BCK.OAUTH.0018`, exactly as an unknown static connector would be. Trust comes from the operator instead, through the same registry static connectors live in: an entry whose `clientId` is the client's `client_id` URL carries **only** `allowAccountLevel`, `trustTier` and `accountLevelConsentTypes`, and no redirect URIs (an entry that lists them is refused as malformed — redirects always come from the document). The next time that URL starts a consent, its document-derived identity is overlaid with the configured trust. Two rules differ from a static entry, both because the identity is self-asserted: `accountLevelConsentTypes` must **name** every consent type the client is granted (omitting it grants nothing, never "both"), and an entry removed from the registry stops granting at the operator's next restart — there is no lingering trust. Out of the box on every Nevermined tier, at `["commerce"]` only: | Assistant | `client_id` it presents | | - | - | | ChatGPT | `https://chatgpt.com/oauth/client.json` | | Claude (the claude.ai connector) | `https://claude.ai/oauth/mcp-oauth-client-metadata` | | Claude Code | `https://claude.ai/oauth/claude-code-client-metadata` | To enable another self-registering assistant for `commerce`, its operator adds the URL it presents as `client_id` to the registry with `allowAccountLevel: true`, `trustTier: "verified"` and `accountLevelConsentTypes: ["commerce"]` — one line, no redirect list, no code. The URL is whatever the assistant sends as `client_id` — read it off the authorize link the assistant opens (the `client_id` query parameter) or from the vendor's published client metadata; an unlisted client is refused without a log line naming it. Because a self-registering client's name is its own claim, the consent screen shows the **host of its `client_id` URL** beside that name — `ChatGPT` with `chatgpt.com` — and `POST /oauth/connect/details` returns it as `clientOrigin` (`https://chatgpt.com`; `null` for a static connector). A document that cannot be fetched, or that fails validation, is refused with `BCK.OAUTH.0031` on both the consent page and `/oauth/authorize`. # Authentication & Identity Source: https://nevermined.ai/docs/integrate/authentication/overview How agents and humans authenticate to the Nevermined API — one bearer token, and the standards-based ceremonies to obtain it with or without a browser. > [!NOTE] > > **Are you an AI agent, or building one?** > > Start with [Authentication for AI agents](/docs/integrate/authentication/for-agents) — it points to the machine-readable manifest an agent can fetch and follow on its own. Every agent-callable Nevermined endpoint is authenticated by a single bearer token. The full mechanics — the exact header, the per-tier base URLs and key prefixes (`sandbox:…` / `live:…`), what a Nevermined key actually is, and how to read a `401` — are the canonical, always-current [`auth.md`](https://nevermined.app/auth.md) manifest. This page covers the decisions around that ceremony: **which path to use, which credential each yields, and the per-tier discovery quirk.** ## Which path do I use? > [card] SDK key > > You can run an SDK and manage your own identity. The simplest path — the SDK mints a key directly. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). > [card] Device flow (RFC 8628) > > You're a headless agent with no browser, but a human can approve for you. Approval is collected without a browser on your side — typically ending in an **NVM API key** bound to the approver. See [Device flow](/docs/integrate/authentication/device-flow). > [card] Authorization Code + PKCE > > You're a browser-based MCP client (Cursor, Claude). The user approves in a browser — to obtain an **x402 payment permission** for a specific agent, or, with `scope=commerce`, an **NVM API key** plus a spending cap an AI assistant (Claude, ChatGPT) pays external services with. See [Authorization Code](/docs/integrate/authentication/oauth-authorization-code). > [!NOTE] > > **The credential you receive is chosen by the requested `resource`, not by the grant.** A `resource` (RFC 8707 audience) matching this API's host mints an **NVM API key**; any other resource mints an **x402 payment permission**. An account-level consent — `commerce` or `account_access` — always yields an API key, whatever `resource` says; with no `resource`, a delegation-backed agent-specific binding yields an x402 permission and a plan-only binding yields an API key. The two grants differ only in *how the human approves* — Authorization Code in a browser, the device flow without one — so pick the grant by your environment and the `resource` by the credential you need. ## Discovery Everything the ceremony needs is advertised in standards-based OAuth metadata — the RFC 8414 authorization-server document, the RFC 9728 protected-resource document, and the JWKS. See [`auth.md`](https://nevermined.app/auth.md) for the endpoint list and what each returns. If a capability is absent from these documents, it does not exist — don't infer it. ### Each tier is its own issuer, and its authorize URL says so Sandbox and Live are separate authorization servers with separate discovery documents (`https://api.sandbox.nevermined.app/.well-known/oauth-authorization-server` and `https://api.live.nevermined.app/…`), but both send the human to the same web app for consent. That app cannot tell from a bare `/oauth/authorize` link which issuer it is acting for, so **the human-facing endpoints carry the tier as a query parameter**: ```json theme={null} { "issuer": "https://api.sandbox.nevermined.app", "authorization_endpoint": "https://nevermined.app/oauth/authorize?network=sandbox", "token_endpoint": "https://api.sandbox.nevermined.app/oauth/token", "authorization_response_iss_parameter_supported": true } ``` `network` is `sandbox` or `live` — the same parameter the embeddable widgets take, and distinct from the x402 request body's `network` field, which names the settlement rail (`eip155:`, or `stripe` / `braintree` / `visa` — [details](/docs/development-guide/nevermined-x402#paymentrequired-response-402)), never a tier. The device flow's `verification_uri` carries it too. **Keep the query string** when you append your own parameters (RFC 6749 §3.1 requires it). Not every client does: the official Python MCP client (`mcp`, every release through 2.2.0) concatenates a second `?`, producing `…?network=sandbox?response_type=code&…` — the consent page tolerates that shape, taking the tier from the head and recovering the one swallowed parameter, so such clients still work; but do not rely on it for a client you control — extend the query with `&`. A discovery-driven client gets the right value for free; if you configure an OAuth provider **by hand** — a connector's "authorization URL" form field, say — copy the endpoint from the tier's discovery document, query string included. **The endpoint must end up as `…/oauth/authorize?network=sandbox` or `…?network=live`; if the document you fetch carries no `network`, append it yourself.** An authorize link without `network` is served on whichever tier the user's browser last used (Live by default), and a connector registered only on Sandbox is then refused as *"Connector not authorized"* until the user switches manually. ### The authorization response names its issuer (RFC 9207) Each tier advertises `authorization_response_iss_parameter_supported: true`, and the consent page appends **`iss`** to every redirect back to your `redirect_uri` — the `?code=…&state=…` success and the `?error=…&state=…` denial alike. Its value is exactly the `issuer` of the discovery document you resolved (`https://api.sandbox.nevermined.app` or `https://api.live.nevermined.app`). Compare the two by plain string equality and reject a response whose `iss` does not match, or that has none: that is what stops a code minted by one issuer being presented as another's (the mix-up attack RFC 9207 exists for), and it is also what lets a client that registers itself through its metadata document (ChatGPT, for one) present a stable identity rather than a per-connection one. The device flow has no authorization response, so nothing there carries `iss`. ## What needs a human Three things require a person in the loop — card enrolment (the card is tokenized in-browser, never reaching Nevermined), first-account creation, and creating a `provider=visa` delegation (a per-delegation FIDO/passkey device-binding ceremony). You can *use* an existing Visa delegation, and Stripe, Braintree, and crypto delegations you create yourself. [`auth.md`](https://nevermined.app/auth.md) documents each, and why, in full. ## Next steps > [card] [Authentication for AI agents](/docs/integrate/authentication/for-agents) > > The machine-readable manifest an agent fetches and follows. > [card] [Device flow (RFC 8628)](/docs/integrate/authentication/device-flow) > > Get an API key with a human's approval, no browser on your side. > [card] [Authorization Code + PKCE](/docs/integrate/authentication/oauth-authorization-code) > > Browser-based MCP clients paying for a specific agent — and AI assistants obtaining a commerce grant. > [card] [Connected agents](/docs/integrate/authentication/connections) > > List and revoke the agents a user has authorized. # Charge Credits Source: https://nevermined.ai/docs/integrate/patterns/charge-credits Patterns for charging credits when processing requests Copy-paste patterns for deducting credits from subscribers. > [!NOTE] > > **These patterns assume a `credits` plan.** A pay-as-you-go plan holds no credit balance — each > request is charged directly — so a successful settle there returns `creditsRedeemed: "0"` and > `remainingBalance: "0"`, with the charge referenced by `orderTx` (fiat rails) or `transaction` > (crypto rails). The settle response always carries `billingModel` (`credits` | `pay-as-you-go`); > read it before either credit field. Gating on `creditsRedeemed > 0` alone reports a real > pay-as-you-go charge as a decline, and on a card rail that invites a retry of a payment that > already succeeded. ## Automatic Credit Deduction With the x402 flow, verification checks permissions without burning credits. After processing, settlement burns the credits: > [tab] TypeScript > > ```typescript theme={null} > import { buildPaymentRequired } from '@nevermined-io/payments' > > const paymentRequired = buildPaymentRequired({ > planId: PLAN_ID, endpoint: '/query', agentId: AGENT_ID, httpVerb: 'POST' > }) > > // 1. Verify permissions (does NOT burn credits) > const verification = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: token, > maxAmount: BigInt(1) > }) > > if (!verification.isValid) { > throw new Error('Invalid payment') > } > > // 2. Process request... > const result = await processRequest() > > // 3. Settle (burn credits) after successful processing > const settlement = await payments.facilitator.settlePermissions({ > paymentRequired, > x402AccessToken: token, > maxAmount: BigInt(1) > }) > > console.log(`Remaining credits: ${settlement.remainingBalance}`) > ``` > [tab] Python > > ```python theme={null} > from payments_py.x402.helpers import build_payment_required > > payment_required = build_payment_required( > plan_id=PLAN_ID, endpoint="/query", agent_id=AGENT_ID, http_verb="POST" > ) > > # 1. Verify permissions (does NOT burn credits) > verification = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=token, > max_amount="1" > ) > > if not verification.is_valid: > raise Exception('Invalid payment') > > # 2. Process request... > result = process_request() > > # 3. Settle (burn credits) after successful processing > settlement = payments.facilitator.settle_permissions( > payment_required=payment_required, > x402_access_token=token, > max_amount="1" > ) > > print(f"Credits used: {settlement.credits_redeemed}") > print(f"Remaining: {settlement.remaining_balance}") > ``` ## Variable Credit Charges For operations with variable costs, use the x402 flow: > [tab] TypeScript > > ```typescript theme={null} > // Calculate cost based on request > function calculateCost(request: any): number { > const baseCredits = 1 > > // Add cost for complexity > if (request.options?.highQuality) { > return baseCredits + 5 > } > > if (request.prompt.length > 1000) { > return baseCredits + 2 > } > > return baseCredits > } > > // Use in settlement > const cost = calculateCost(req.body) > > await payments.facilitator.settlePermissions({ > planId: PLAN_ID, > maxAmount: BigInt(cost), > x402AccessToken: token, > subscriberAddress: address > }) > ``` > [tab] Python > > ```python theme={null} > def calculate_cost(request: dict) -> int: > base_credits = 1 > > # Add cost for complexity > if request.get('options', {}).get('high_quality'): > return base_credits + 5 > > if len(request.get('prompt', '')) > 1000: > return base_credits + 2 > > return base_credits > > # Use in settlement > cost = calculate_cost(request) > > await payments.facilitator.settle_permissions( > payment_required=payment_required, > x402_access_token=access_token, > max_amount=str(cost) > ) > ``` ## Credit Tracking Middleware Track credits used per request: > [tab] TypeScript > > ```typescript theme={null} > interface CreditUsage { > requestId: string > subscriberAddress: string > creditsUsed: number > creditsBefore: number > creditsAfter: number > timestamp: Date > endpoint: string > } > > async function trackCredits( > req: Request, > res: Response, > next: NextFunction > ) { > const startBalance = req.payment?.balance || 0 > > // Store original json method > const originalJson = res.json.bind(res) > > // Override to track response > res.json = (body: any) => { > const creditsUsed = body.credits?.used || 1 > const creditsAfter = body.credits?.remaining || startBalance - creditsUsed > > const usage: CreditUsage = { > requestId: req.id, > subscriberAddress: req.payment?.subscriberAddress || 'unknown', > creditsUsed, > creditsBefore: startBalance, > creditsAfter, > timestamp: new Date(), > endpoint: req.path > } > > // Log or store usage > logCreditUsage(usage) > > return originalJson(body) > } > > next() > } > > function logCreditUsage(usage: CreditUsage) { > console.log(`Credit usage: ${JSON.stringify(usage)}`) > // Or send to analytics, database, etc. > } > ``` > [tab] Python > > ```python theme={null} > from dataclasses import dataclass > from datetime import datetime > import uuid > > @dataclass > class CreditUsage: > request_id: str > subscriber_address: str > credits_used: int > credits_before: int > credits_after: int > timestamp: datetime > endpoint: str > > async def track_credits(request: Request, call_next): > # Get initial balance from payment validation > start_balance = getattr(request.state, 'credits_balance', 0) > request_id = str(uuid.uuid4()) > > response = await call_next(request) > > # Track usage after response > if hasattr(request.state, 'credits_used'): > usage = CreditUsage( > request_id=request_id, > subscriber_address=getattr(request.state, 'subscriber_address', 'unknown'), > credits_used=request.state.credits_used, > credits_before=start_balance, > credits_after=start_balance - request.state.credits_used, > timestamp=datetime.now(), > endpoint=str(request.url.path) > ) > > log_credit_usage(usage) > > return response > > def log_credit_usage(usage: CreditUsage): > print(f"Credit usage: {usage}") > # Or send to analytics, database, etc. > ``` ## Tiered Pricing Charge different amounts based on usage tiers: > [tab] TypeScript > > ```typescript theme={null} > interface PricingTier { > name: string > minTokens: number > maxTokens: number > creditsPerRequest: number > } > > const PRICING_TIERS: PricingTier[] = [ > { name: 'small', minTokens: 0, maxTokens: 100, creditsPerRequest: 1 }, > { name: 'medium', minTokens: 101, maxTokens: 500, creditsPerRequest: 3 }, > { name: 'large', minTokens: 501, maxTokens: 2000, creditsPerRequest: 5 }, > { name: 'xlarge', minTokens: 2001, maxTokens: Infinity, creditsPerRequest: 10 } > ] > > function getCreditsForTokens(tokenCount: number): number { > const tier = PRICING_TIERS.find( > t => tokenCount >= t.minTokens && tokenCount <= t.maxTokens > ) > return tier?.creditsPerRequest || 1 > } > > // Usage > async function processWithTieredPricing(prompt: string, payment: PaymentInfo) { > const estimatedTokens = estimateTokens(prompt) > const requiredCredits = getCreditsForTokens(estimatedTokens) > > if (payment.balance < requiredCredits) { > throw new Error(`Insufficient credits. Need ${requiredCredits}, have ${payment.balance}`) > } > > const result = await generateResponse(prompt) > const actualTokens = countTokens(result) > const actualCredits = getCreditsForTokens(actualTokens) > > return { > result, > credits: { > estimated: requiredCredits, > actual: actualCredits, > remaining: payment.balance - actualCredits > } > } > } > ``` > [tab] Python > > ```python theme={null} > from dataclasses import dataclass > from typing import List > > @dataclass > class PricingTier: > name: str > min_tokens: int > max_tokens: int > credits_per_request: int > > PRICING_TIERS: List[PricingTier] = [ > PricingTier('small', 0, 100, 1), > PricingTier('medium', 101, 500, 3), > PricingTier('large', 501, 2000, 5), > PricingTier('xlarge', 2001, float('inf'), 10) > ] > > def get_credits_for_tokens(token_count: int) -> int: > for tier in PRICING_TIERS: > if tier.min_tokens <= token_count <= tier.max_tokens: > return tier.credits_per_request > return 1 > > # Usage > async def process_with_tiered_pricing(prompt: str, payment: dict) -> dict: > estimated_tokens = estimate_tokens(prompt) > required_credits = get_credits_for_tokens(estimated_tokens) > > if payment['balance'] < required_credits: > raise ValueError( > f"Insufficient credits. Need {required_credits}, have {payment['balance']}" > ) > > result = await generate_response(prompt) > actual_tokens = count_tokens(result) > actual_credits = get_credits_for_tokens(actual_tokens) > > return { > 'result': result, > 'credits': { > 'estimated': required_credits, > 'actual': actual_credits, > 'remaining': payment['balance'] - actual_credits > } > } > ``` ## Pre-Authorization Pattern For long-running operations, pre-authorize credits before starting: > [tab] TypeScript > > ```typescript theme={null} > async function processLongRunningTask( > x402Token: string, > paymentRequired: string, > estimatedCredits: number > ) { > // Step 1: Verify permissions (does not burn credits) > const verification = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount: BigInt(estimatedCredits) > }) > > if (!verification.isValid) { > throw new Error('Invalid token') > } > > if (verification.balance < estimatedCredits) { > throw new Error(`Insufficient credits. Need ${estimatedCredits}, have ${verification.balance}`) > } > > // Step 2: Start the long-running task > const taskId = await startTask({}) > > try { > // Step 3: Wait for completion > const result = await waitForCompletion(taskId) > > // Step 4: Calculate actual cost and settle (burn credits) > const actualCredits = calculateActualCost(result) > > const settlement = await payments.facilitator.settlePermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount: BigInt(actualCredits) > }) > > return { > result, > credits: { > estimated: estimatedCredits, > actual: actualCredits, > remaining: settlement.remainingBalance > } > } > } catch (error) { > // Task failed - don't settle (no credits burned) > console.error('Task failed:', error) > throw error > } > } > ``` > [tab] Python > > ```python theme={null} > async def process_long_running_task( > x402_token: str, > payment_required: str, > estimated_credits: int > ) -> dict: > # Step 1: Verify permissions (does not burn credits) > verification = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount=str(estimated_credits) > ) > > if not verification.is_valid: > raise ValueError('Invalid token') > > if verification.balance < estimated_credits: > raise ValueError( > f"Insufficient credits. Need {estimated_credits}, have {verification.balance}" > ) > > # Step 2: Start the long-running task > task_id = await start_task({}) > > try: > # Step 3: Wait for completion > result = await wait_for_completion(task_id) > > # Step 4: Calculate actual cost and settle (burn credits) > actual_credits = calculate_actual_cost(result) > > settlement = payments.facilitator.settle_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount=str(actual_credits) > ) > > return { > 'result': result, > 'credits': { > 'estimated': estimated_credits, > 'actual': actual_credits, > 'remaining': settlement.remaining_balance > } > } > except Exception as error: > # Task failed - don't settle (no credits burned) > print(f'Task failed: {error}') > raise > ``` ## Credit Response Headers Include credit information in response headers: > [tab] TypeScript > > ```typescript theme={null} > function addCreditHeaders(res: Response, credits: CreditInfo) { > res.setHeader('X-Credits-Used', credits.used.toString()) > res.setHeader('X-Credits-Remaining', credits.remaining.toString()) > res.setHeader('X-Credits-Plan', credits.planId) > } > > // Usage in middleware > app.use((req, res, next) => { > const originalJson = res.json.bind(res) > > res.json = (body: any) => { > if (req.payment && body.credits) { > addCreditHeaders(res, body.credits) > } > return originalJson(body) > } > > next() > }) > ``` > [tab] Python > > ```python theme={null} > from fastapi import Response > > def add_credit_headers(response: Response, credits: dict): > response.headers['X-Credits-Used'] = str(credits['used']) > response.headers['X-Credits-Remaining'] = str(credits['remaining']) > response.headers['X-Credits-Plan'] = credits['plan_id'] > > # Usage in endpoint > @app.post("/query") > async def query(request: dict, response: Response): > result = await process_query(request) > > add_credit_headers(response, { > 'used': 1, > 'remaining': 99, > 'plan_id': PLAN_ID > }) > > return result > ``` ## Next Steps > [card] [Subscription Access](/docs/integrate/patterns/subscription-access) > > Time-based access patterns > [card] [Dynamic Pricing](/docs/integrate/patterns/dynamic-pricing) > > Variable pricing strategies # Dynamic Pricing Source: https://nevermined.ai/docs/integrate/patterns/dynamic-pricing Patterns for variable and usage-based pricing Copy-paste patterns for implementing dynamic and usage-based pricing. ## Token-Based Pricing Charge based on input/output token count (common for LLM APIs): > [tab] TypeScript > > ```typescript theme={null} > interface TokenPricing { > inputTokenPrice: number // credits per 1K input tokens > outputTokenPrice: number // credits per 1K output tokens > minimumCharge: number // minimum credits per request > } > > const PRICING: TokenPricing = { > inputTokenPrice: 1, // 1 credit per 1K input tokens > outputTokenPrice: 3, // 3 credits per 1K output tokens > minimumCharge: 1 // minimum 1 credit > } > > function calculateTokenCost( > inputTokens: number, > outputTokens: number, > pricing: TokenPricing = PRICING > ): number { > const inputCost = Math.ceil((inputTokens / 1000) * pricing.inputTokenPrice) > const outputCost = Math.ceil((outputTokens / 1000) * pricing.outputTokenPrice) > const totalCost = inputCost + outputCost > > return Math.max(totalCost, pricing.minimumCharge) > } > > // Usage > async function processLLMRequest(prompt: string, payment: PaymentInfo) { > const inputTokens = countTokens(prompt) > const estimatedOutputTokens = inputTokens * 2 // Rough estimate > > const estimatedCost = calculateTokenCost(inputTokens, estimatedOutputTokens) > > if (payment.balance < estimatedCost) { > throw new Error(`Insufficient credits. Estimated: ${estimatedCost}, Available: ${payment.balance}`) > } > > const response = await generateResponse(prompt) > const outputTokens = countTokens(response) > const actualCost = calculateTokenCost(inputTokens, outputTokens) > > return { > response, > usage: { > inputTokens, > outputTokens, > creditsUsed: actualCost, > creditsRemaining: payment.balance - actualCost > } > } > } > ``` > [tab] Python > > ```python theme={null} > from dataclasses import dataclass > import math > > @dataclass > class TokenPricing: > input_token_price: float # credits per 1K input tokens > output_token_price: float # credits per 1K output tokens > minimum_charge: int # minimum credits per request > > PRICING = TokenPricing( > input_token_price=1, # 1 credit per 1K input tokens > output_token_price=3, # 3 credits per 1K output tokens > minimum_charge=1 # minimum 1 credit > ) > > def calculate_token_cost( > input_tokens: int, > output_tokens: int, > pricing: TokenPricing = PRICING > ) -> int: > input_cost = math.ceil((input_tokens / 1000) * pricing.input_token_price) > output_cost = math.ceil((output_tokens / 1000) * pricing.output_token_price) > total_cost = input_cost + output_cost > > return max(total_cost, pricing.minimum_charge) > > # Usage > async def process_llm_request(prompt: str, payment: dict) -> dict: > input_tokens = count_tokens(prompt) > estimated_output_tokens = input_tokens * 2 # Rough estimate > > estimated_cost = calculate_token_cost(input_tokens, estimated_output_tokens) > > if payment['balance'] < estimated_cost: > raise ValueError( > f"Insufficient credits. Estimated: {estimated_cost}, Available: {payment['balance']}" > ) > > response = await generate_response(prompt) > output_tokens = count_tokens(response) > actual_cost = calculate_token_cost(input_tokens, output_tokens) > > return { > 'response': response, > 'usage': { > 'input_tokens': input_tokens, > 'output_tokens': output_tokens, > 'credits_used': actual_cost, > 'credits_remaining': payment['balance'] - actual_cost > } > } > ``` ## Complexity-Based Pricing Charge based on operation complexity: > [tab] TypeScript > > ```typescript theme={null} > enum OperationType { > SIMPLE_QUERY = 'simple_query', > COMPLEX_ANALYSIS = 'complex_analysis', > IMAGE_GENERATION = 'image_generation', > BATCH_PROCESSING = 'batch_processing' > } > > const OPERATION_COSTS: Record = { > [OperationType.SIMPLE_QUERY]: 1, > [OperationType.COMPLEX_ANALYSIS]: 5, > [OperationType.IMAGE_GENERATION]: 10, > [OperationType.BATCH_PROCESSING]: 20 > } > > function detectOperationType(request: any): OperationType { > if (request.type === 'image') { > return OperationType.IMAGE_GENERATION > } > > if (request.batch && request.batch.length > 1) { > return OperationType.BATCH_PROCESSING > } > > if (request.analysis || request.options?.detailed) { > return OperationType.COMPLEX_ANALYSIS > } > > return OperationType.SIMPLE_QUERY > } > > function calculateComplexityCost(request: any): { > operationType: OperationType > baseCost: number > multiplier: number > totalCost: number > } { > const operationType = detectOperationType(request) > const baseCost = OPERATION_COSTS[operationType] > > // Apply multipliers based on options > let multiplier = 1 > > if (request.options?.highQuality) { > multiplier *= 1.5 > } > > if (request.options?.priority) { > multiplier *= 2 > } > > if (request.batch) { > multiplier *= request.batch.length > } > > return { > operationType, > baseCost, > multiplier, > totalCost: Math.ceil(baseCost * multiplier) > } > } > ``` > [tab] Python > > ```python theme={null} > from enum import Enum > from dataclasses import dataclass > import math > > class OperationType(Enum): > SIMPLE_QUERY = 'simple_query' > COMPLEX_ANALYSIS = 'complex_analysis' > IMAGE_GENERATION = 'image_generation' > BATCH_PROCESSING = 'batch_processing' > > OPERATION_COSTS = { > OperationType.SIMPLE_QUERY: 1, > OperationType.COMPLEX_ANALYSIS: 5, > OperationType.IMAGE_GENERATION: 10, > OperationType.BATCH_PROCESSING: 20 > } > > def detect_operation_type(request: dict) -> OperationType: > if request.get('type') == 'image': > return OperationType.IMAGE_GENERATION > > if request.get('batch') and len(request['batch']) > 1: > return OperationType.BATCH_PROCESSING > > if request.get('analysis') or request.get('options', {}).get('detailed'): > return OperationType.COMPLEX_ANALYSIS > > return OperationType.SIMPLE_QUERY > > @dataclass > class ComplexityCost: > operation_type: OperationType > base_cost: int > multiplier: float > total_cost: int > > def calculate_complexity_cost(request: dict) -> ComplexityCost: > operation_type = detect_operation_type(request) > base_cost = OPERATION_COSTS[operation_type] > > # Apply multipliers based on options > multiplier = 1.0 > > options = request.get('options', {}) > if options.get('high_quality'): > multiplier *= 1.5 > > if options.get('priority'): > multiplier *= 2 > > if request.get('batch'): > multiplier *= len(request['batch']) > > return ComplexityCost( > operation_type=operation_type, > base_cost=base_cost, > multiplier=multiplier, > total_cost=math.ceil(base_cost * multiplier) > ) > ``` ## Time-Based Dynamic Pricing Adjust pricing based on demand or time of day: > [tab] TypeScript > > ```typescript theme={null} > interface DynamicPricing { > baseCredits: number > peakMultiplier: number > offPeakDiscount: number > } > > function getPricingMultiplier(): number { > const hour = new Date().getUTCHours() > > // Peak hours: 9 AM - 6 PM UTC > if (hour >= 9 && hour < 18) { > return 1.5 // 50% premium > } > > // Off-peak: 10 PM - 6 AM UTC > if (hour >= 22 || hour < 6) { > return 0.5 // 50% discount > } > > // Standard hours > return 1.0 > } > > function calculateDynamicCost( > baseCost: number, > options?: { ignorePeakPricing?: boolean } > ): number { > if (options?.ignorePeakPricing) { > return baseCost > } > > const multiplier = getPricingMultiplier() > return Math.ceil(baseCost * multiplier) > } > > // Usage > app.post('/query', requirePayment(1), async (req, res) => { > const baseCost = 1 > const actualCost = calculateDynamicCost(baseCost) > > if (req.payment!.balance < actualCost) { > return res.status(402).json({ > error: 'Insufficient credits', > required: actualCost, > available: req.payment!.balance, > note: 'Prices are higher during peak hours (9 AM - 6 PM UTC)' > }) > } > > // Process request... > }) > ``` > [tab] Python > > ```python theme={null} > from datetime import datetime > import math > > def get_pricing_multiplier() -> float: > hour = datetime.utcnow().hour > > # Peak hours: 9 AM - 6 PM UTC > if 9 <= hour < 18: > return 1.5 # 50% premium > > # Off-peak: 10 PM - 6 AM UTC > if hour >= 22 or hour < 6: > return 0.5 # 50% discount > > # Standard hours > return 1.0 > > def calculate_dynamic_cost( > base_cost: int, > ignore_peak_pricing: bool = False > ) -> int: > if ignore_peak_pricing: > return base_cost > > multiplier = get_pricing_multiplier() > return math.ceil(base_cost * multiplier) > > # Usage > @app.post("/query") > async def query(request: dict, payment: PaymentInfo = Depends(require_payment(1))): > base_cost = 1 > actual_cost = calculate_dynamic_cost(base_cost) > > if payment.balance < actual_cost: > raise HTTPException( > status_code=402, > detail={ > 'error': 'Insufficient credits', > 'required': actual_cost, > 'available': payment.balance, > 'note': 'Prices are higher during peak hours (9 AM - 6 PM UTC)' > } > ) > > # Process request... > ``` ## Usage-Based Tiers Implement tiered pricing based on monthly usage: > [tab] TypeScript > > ```typescript theme={null} > interface UsageTier { > name: string > minUsage: number > maxUsage: number > pricePerCredit: number // Discount rate > } > > const USAGE_TIERS: UsageTier[] = [ > { name: 'starter', minUsage: 0, maxUsage: 100, pricePerCredit: 1.0 }, > { name: 'growth', minUsage: 101, maxUsage: 1000, pricePerCredit: 0.8 }, > { name: 'scale', minUsage: 1001, maxUsage: 10000, pricePerCredit: 0.6 }, > { name: 'enterprise', minUsage: 10001, maxUsage: Infinity, pricePerCredit: 0.4 } > ] > > async function getEffectivePrice( > subscriberAddress: string, > baseCost: number > ): Promise<{ cost: number; tier: string; discount: number }> { > // Get monthly usage from your tracking system > const monthlyUsage = await getMonthlyUsage(subscriberAddress) > > const tier = USAGE_TIERS.find( > t => monthlyUsage >= t.minUsage && monthlyUsage <= t.maxUsage > ) || USAGE_TIERS[0] > > const effectiveCost = Math.ceil(baseCost * tier.pricePerCredit) > const discount = Math.round((1 - tier.pricePerCredit) * 100) > > return { > cost: effectiveCost, > tier: tier.name, > discount > } > } > > // Usage > const pricing = await getEffectivePrice(subscriberAddress, 10) > // { cost: 6, tier: 'scale', discount: 40 } > ``` > [tab] Python > > ```python theme={null} > @dataclass > class UsageTier: > name: str > min_usage: int > max_usage: int > price_per_credit: float # Discount rate > > USAGE_TIERS = [ > UsageTier('starter', 0, 100, 1.0), > UsageTier('growth', 101, 1000, 0.8), > UsageTier('scale', 1001, 10000, 0.6), > UsageTier('enterprise', 10001, float('inf'), 0.4) > ] > > async def get_effective_price( > subscriber_address: str, > base_cost: int > ) -> dict: > # Get monthly usage from your tracking system > monthly_usage = await get_monthly_usage(subscriber_address) > > tier = next( > (t for t in USAGE_TIERS if t.min_usage <= monthly_usage <= t.max_usage), > USAGE_TIERS[0] > ) > > effective_cost = math.ceil(base_cost * tier.price_per_credit) > discount = round((1 - tier.price_per_credit) * 100) > > return { > 'cost': effective_cost, > 'tier': tier.name, > 'discount': discount > } > > # Usage > pricing = await get_effective_price(subscriber_address, 10) > # {'cost': 6, 'tier': 'scale', 'discount': 40} > ``` ## Cost Estimation Endpoint Provide a cost estimation endpoint: > [tab] TypeScript > > ```typescript theme={null} > app.post('/estimate', async (req, res) => { > const { request, subscriberAddress } = req.body > > // Calculate various cost components > const tokenCost = calculateTokenCost( > countTokens(request.prompt), > estimateOutputTokens(request.prompt) > ) > > const complexityCost = calculateComplexityCost(request) > const dynamicMultiplier = getPricingMultiplier() > > // Get tier discount if subscriber is known > let tierDiscount = 0 > if (subscriberAddress) { > const pricing = await getEffectivePrice(subscriberAddress, 1) > tierDiscount = pricing.discount > } > > const baseCost = Math.max(tokenCost, complexityCost.totalCost) > const adjustedCost = Math.ceil(baseCost * dynamicMultiplier) > const finalCost = Math.ceil(adjustedCost * (1 - tierDiscount / 100)) > > res.json({ > estimate: { > baseCost, > adjustments: { > dynamicPricing: { > multiplier: dynamicMultiplier, > reason: dynamicMultiplier > 1 ? 'peak_hours' : dynamicMultiplier < 1 ? 'off_peak' : 'standard' > }, > tierDiscount: { > percent: tierDiscount, > reason: tierDiscount > 0 ? 'volume_discount' : 'none' > } > }, > finalCost, > breakdown: { > tokenBased: tokenCost, > complexity: complexityCost.totalCost, > operationType: complexityCost.operationType > } > } > }) > }) > ``` > [tab] Python > > ```python theme={null} > @app.post("/estimate") > async def estimate_cost(request: dict): > prompt = request.get('request', {}).get('prompt', '') > subscriber_address = request.get('subscriber_address') > > # Calculate various cost components > input_tokens = count_tokens(prompt) > estimated_output = estimate_output_tokens(prompt) > token_cost = calculate_token_cost(input_tokens, estimated_output) > > complexity = calculate_complexity_cost(request.get('request', {})) > dynamic_multiplier = get_pricing_multiplier() > > # Get tier discount if subscriber is known > tier_discount = 0 > if subscriber_address: > pricing = await get_effective_price(subscriber_address, 1) > tier_discount = pricing['discount'] > > base_cost = max(token_cost, complexity.total_cost) > adjusted_cost = math.ceil(base_cost * dynamic_multiplier) > final_cost = math.ceil(adjusted_cost * (1 - tier_discount / 100)) > > return { > 'estimate': { > 'base_cost': base_cost, > 'adjustments': { > 'dynamic_pricing': { > 'multiplier': dynamic_multiplier, > 'reason': 'peak_hours' if dynamic_multiplier > 1 else 'off_peak' if dynamic_multiplier < 1 else 'standard' > }, > 'tier_discount': { > 'percent': tier_discount, > 'reason': 'volume_discount' if tier_discount > 0 else 'none' > } > }, > 'final_cost': final_cost, > 'breakdown': { > 'token_based': token_cost, > 'complexity': complexity.total_cost, > 'operation_type': complexity.operation_type.value > } > } > } > ``` ## Next Steps > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Implement variable settlement with x402 > [card] [Charge Credits](/docs/integrate/patterns/charge-credits) > > Credit charging patterns # Fiat Payments Source: https://nevermined.ai/docs/integrate/patterns/fiat-payments Accept credit cards via Stripe, Braintree, or Visa Agentic Tokens with no crypto wallet required. The easiest path for mainstream and enterprise adoption. Accept credit cards in **USD or EUR**, with no crypto wallet required. Fiat payments are the fastest path to mainstream adoption. Your users can start paying with a card they already have, either through Stripe Checkout (one-time plan purchase) or by setting up [card delegation](/docs/products/payments/overview) for autonomous agent charging. ## When to Use Fiat Payments > [card] Enterprise Adoption > > Organizations that already pay for SaaS with corporate cards can onboard without touching crypto. > [card] Mainstream Users > > No wallet setup, no token bridging. Users pay with the card in their pocket. > [card] Regulatory Compliance > > Fiat-denominated billing simplifies accounting, invoicing, and compliance for businesses. > [card] Instant Onboarding > > Users go from discovery to first API call in seconds. No wallet funding step required. ## Fiat Payment Scenarios Nevermined supports fiat payments in two scenarios: * **Human-to-Agent**: A user visits the Nevermined App checkout page and purchases a plan with their credit card. This is the simplest flow for onboarding new customers. * **Agent-to-Agent**: An agent owner enrolls a credit card (Visa, Stripe, or Braintree) and creates a [spending delegation](/docs/products/payments/overview). The agent can then make autonomous payments on behalf of the owner, charging the card per request within the defined limits. ## Pay-per-request or a bundle of credits Nevermined offers two distinct fiat payment flows depending on whether you want upfront plan purchases or per-request charging. > [card] Plan Purchase > > One-time or recurring payment via Stripe Checkout. The user buys a plan, a webhook confirms the payment, and credits are minted on-chain. Best for human users who want a familiar checkout experience. > [card] [Card Delegation](/docs/products/payments/overview) > > Per-request charging via the x402 protocol. The user enrolls a Visa, Stripe, or Braintree card, creates a spending delegation with limits, and the agent charges it for each request. Best for automated workflows and agent-to-agent payments. ## Human-to-Agent Purchase Flow The simplest way to accept fiat. Users complete a standard Stripe Checkout session, and Nevermined handles the rest. **1. Select a plan** The user browses available plans in the Nevermined App or your custom UI and selects one priced in fiat. **2. Redirect to Stripe Checkout** Nevermined creates a Stripe Checkout session and redirects the user to complete payment with their card. **3. Payment completes** Stripe processes the charge. For recurring plans, Stripe manages subsequent billing automatically. **4. Webhook confirms payment** Nevermined receives a webhook from Stripe confirming the successful payment. **5. Credits minted on-chain** The corresponding credits are minted to the subscriber's account, and they can immediately start using the agent. Both one-time and recurring plan purchases are supported. For recurring plans, Stripe handles rebilling and Nevermined mints fresh credits each billing cycle. ## Agent-to-Agent Purchase Flow (Card Delegation) Fully autonomous agent-to-agent payments in fiat are enabled through [card delegation](/docs/products/payments/overview). This allows an agent to charge a user's card on-demand, without the user needing to pre-purchase credits. Instead of buying credits upfront, the user enrolls a card and creates a spending delegation with defined limits. Nevermined supports three card rails, all consumed through the unified `nvm:card-delegation` x402 scheme: * **Visa** — Cards tokenized as Visa Agentic Tokens via the VGS Credential Management Platform. Each delegation requires a per-delegation WebAuthn/passkey device-binding ceremony enforced by Visa VTS. Settlement runs through Stripe Connect. * **Stripe** — Cards captured via VGS Collect, vaulted at VGS and given a network token. Settlement runs through Stripe PaymentIntents. * **Braintree** — The same card enrollment as Stripe. The plan picks the rail at charge time. Settlement is one sale, with the card's network token, against an OAuth-connected seller merchant account. **1. Card Enrollment** The user enrolls a card via the [Nevermined App](https://nevermined.app). Card data is tokenized by VGS Collect and Nevermined never stores raw card numbers. See [Card Enrollment](/docs/products/payments/card-enrollment) for the full flow. **2. Create a spending delegation** The user creates a delegation that defines spending limits: lifetime amount ceiling, max transactions, and duration. Optionally, they can link it to a specific API key for automatic selection. Visa delegations require an additional per-delegation passkey approval (browser-only). See [Delegations](/docs/products/payments/mandates). **3. Agent requests payment** When the agent makes a request, it calls the Nevermined API with its NVM API key. Nevermined resolves the right delegation and generates an x402 payment token. **4. Verify and settle** The resource server verifies the payment token, executes the workload, then settles. Nevermined charges the enrolled card and records the transaction. > [!NOTE] > > Card delegation is what enables fiat-based agent-to-agent payments. An agent owner enrolls their card and sets spending limits, and the agent can autonomously pay for services from other agents, all settled in fiat. Credit top-ups are built in: if the balance runs out during a request, the facilitator charges the enrolled card within the delegation limits — see [Automatic Credit Top-Ups](/docs/integrate/patterns/top-up). For common questions, see the [Payments FAQ](/docs/products/payments/faq). > [!WARNING] > > Visa delegation creation is browser-only because of the WebAuthn/passkey device-binding ceremony. The SDK can **consume** an existing Visa delegation (by passing its `delegationId` to `DelegationConfig`) but cannot create one programmatically. ## Permission Model Delegations enforce strict spending limits to protect the cardholder. All three networks share the same controls: | Limit | Field | Notes | | - | - | - | | Lifetime spending limit | `spendingLimitCents` | Cumulative cap across all charges on the delegation | | Max transactions | `maxTransactions` | Optional; omit the field to allow unlimited transactions | | Duration | `durationSecs` | Seconds from `createdAt` | | Plan binding | `planId` | Required for Visa (Trusted Agent Protocol) | | Device binding | `consumerPrompt` + `assuranceData` | Visa-only; produced by the in-browser WebAuthn ceremony | A delegation moves through a simple lifecycle: | State | Meaning | | - | - | | **Active** | Valid and can be used for charges | | **Exhausted** | The spending limit or transaction count has been reached | | **Expired** | The expiration date has passed | | **Revoked** | The cardholder manually revoked it | Once a delegation leaves the **Active** state, a new one must be created to continue charging. See [Delegations](/docs/products/payments/mandates) for full details on spending controls and the [Delegation Selection](/docs/products/payments/mandate-selection) algorithm. ## Security and PCI Compliance Card data never reaches Nevermined servers. Depending on the provider: * **Visa path** — PAN is captured in a VGS Collect iframe and posted directly to the VGS Credential Management Platform via VGS-internal routing. CMP issues a Visa Agentic Token (`vat_…`) that replaces the PAN. Each delegation is bound to the cardholder's device via a WebAuthn/passkey ceremony enforced by Visa VTS, producing a single-use `assuranceData` blob. * **Stripe and Braintree paths** — PAN is captured in a VGS Collect iframe and goes directly to VGS, which returns a card ID (`CRD…`). The API provisions a network token for that card. The plan picks Stripe or Braintree at charge time. > [!NOTE] > > **Nevermined is PCI compliant** (PCI SAQ D level) and holds ISO 27001 and SOC 2 Type II certifications. Strong Customer Authentication is enforced per-delegation for Visa (WebAuthn/passkey, with email OTP fallback). See the [Payments FAQ](/docs/products/payments/faq) for full security details. ## Revenue Routing When a user pays with a card, Nevermined routes the revenue to the builder's connected account on the appropriate PSP: * **Stripe & Visa** — via Stripe Connect (`transfer_data.destination`). Fees are deducted automatically before the payout reaches the builder. Visa delegations always settle through the seller's Stripe Connect account. * **Braintree** — via one sale for the whole price, against the seller's OAuth-connected merchant account in the plan's currency. You receive funds directly in your PSP account — no manual transfers or reconciliation needed. ## Fees and Settlement | Item | Cost | | - | - | | Nevermined fee | 2% of the transaction amount on Stripe and Visa. On Braintree, no fee is taken from the sale; fees are agreed directly with Nevermined. | | PSP processing fee | Stripe / Braintree fixed fee + % per transaction (varies by currency/region; see PSP pricing) | | Supported currencies | USD, EUR | | Settlement | Stripe PaymentIntents (Stripe + Visa) or one Braintree sale (Braintree) to seller's connected account | > [!WARNING] > > Stripe and Visa payments carry higher fees than stablecoin payments (2% + Stripe fees vs. 1% flat). For high-volume or high-value use cases, consider [stablecoin payments](/docs/integrate/patterns/stablecoin-payments) to reduce costs. ## Supported Plan Types > [card] Credits-Based > > Prepaid credits purchased via Stripe Checkout. Credits are minted once payment confirms. > [card] Time-Based > > Subscription access for a set duration. Stripe handles recurring billing automatically. > [card] Pay-As-You-Go > > Per-request charging via card delegation. No upfront purchase needed. > [card] Recurring > > Automatic rebilling at the end of each period. Stripe manages the billing cycle. ## Next Steps > [card] [Payments](/docs/products/payments/overview) > > Enroll Visa, Stripe, or Braintree cards and create spending delegations for agent payments > [card] [Orders: Goods & Services Checkout](/docs/integrate/patterns/orders) > > Charge an arbitrary cart total by card in the browser, with no plan and no buyer account > [card] [Stablecoin Payments](/docs/integrate/patterns/stablecoin-payments) > > Accept crypto payments with the lowest fees and on-chain transparency > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Configure credits, time-based, dynamic, and hybrid plans > [card] [Manage Plans](https://nevermined.app) > > Create and manage payment plans in the Nevermined App # Orders: Goods & Services Checkout Source: https://nevermined.ai/docs/integrate/patterns/orders Charge a buyer an arbitrary cart total by card in the browser with a single server-to-server call. No plan registration, no buyer Nevermined account, no delegation. An **Order** is a first-class, off-plan charge for an arbitrary amount: the price is whatever your cart adds up to on this request. You call one endpoint from your server, state the amount, and get back a `clientSecret` the buyer's browser confirms with their card. Nothing needs to exist in advance: no plan, no buyer Nevermined account, no delegation. Orders live alongside plans; they don't replace them. Use a plan for a reusable, catalog-listed service. Use an Order when you need to charge one buyer one specific total and move on. > [!NOTE] > > An Order is not the same thing as ordering a plan. `orderPlan()` / `order_plan()` buys credits on an existing plan for a Nevermined account. An Order has no plan and no account behind it. ## When to use an Order | | Plan | Order | | - | - | - | | Price | Fixed at registration | Arbitrary, set per request | | Buyer | Agent or human; may need a Nevermined account or delegation | A human in a browser, **no** Nevermined account | | Fits | A service or subscription sold repeatedly | "Charge this cart for \$3,437.95 and forget it" | | Currency | USD, EUR, USDC | USD only (Phase 1) | ## Before you start * **An active organization account.** Orders are available to organizations only. A personal API key is refused with `BCK.ORDER.0003`. See [Organizations](/docs/solutions/organizations/overview). * **A Nevermined API key** [scoped to that organization](/docs/solutions/organizations/workspaces-and-members). The key identifies you as the Merchant of Record for every Order it creates. * **A validated Stripe Connect account.** Nevermined looks for one on your organization first, then on the API key owner's profile. Order revenue is paid out to it, the same way [fiat plan payments](/docs/integrate/patterns/fiat-payments#revenue-routing) are. Without one, `POST /api/v1/orders` fails with `BCK.ORDER.0004`. See the [Payments FAQ](/docs/products/payments/faq) for seller onboarding. Set your key once: ```bash theme={null} export NVM_API_KEY="your-organization-api-key" ``` Use `https://api.sandbox.nevermined.app` while you build and `https://api.live.nevermined.app` when you go live. ## How it works ![Diagram: a merchant creates an order server-side with its API key; Nevermined and Stripe run the checkout in three steps — Create returns a clientSecret, the buyer Confirms the card payment in the hosted checkout, and a Stripe webhook Settles the order as paid — then the paid result returns to the merchant with payout to its Connect account. The buyer needs no Nevermined account.](https://mintcdn.com/neverminedag/M__YVnYYiOj8B5v3/images/orders-flow.png?fit=max\&auto=format\&n=M__YVnYYiOj8B5v3\&q=85\&s=4a784b6db4b2679f0ed9b6fa5bf75e2b) Your server sets the price. The buyer's browser confirms the payment. A Stripe webhook tells Nevermined the money moved. Nothing buyer-facing can change the amount. **1. Create the Order from your server** Call `POST /api/v1/orders` with your API key and the amount in USD cents. Nevermined creates a Stripe PaymentIntent for that exact amount and returns an unguessable `orderId` and a `clientSecret`. No money moves yet. **2. Hand the buyer to the Nevermined checkout** Pass the buyer only the `orderId`, by redirect or by embedding the Nevermined-hosted checkout. The checkout reads the Order through `GET /api/v1/orders/{id}` and renders the amount and the card form. You don't build a card form or handle card data, and the buyer never signs in to Nevermined. **3. The buyer confirms in the browser** Stripe Elements confirms the payment client-side against the `clientSecret`, running 3D Secure if the issuer requires it. Nevermined only ever created the PaymentIntent; it never initiates the charge itself. **4. The Order becomes paid** Stripe notifies Nevermined by webhook and the Order's status flips to `paid`. Read the Order from your server and confirm the status before you fulfill. > [!NOTE] > > The hosted checkout is the buyer-facing half of Orders. You don't need your own Stripe Elements integration: the hosted checkout confirms the `clientSecret` for you. Your side is the server-to-server REST contract on this page. > [!TIP] > > Prefer to read working code? The [Fiat Checkout Chat tutorial](https://github.com/nevermined-io/tutorials/tree/main/fiat-checkout-chat) is a minimal Next.js chat UI plus a thin merchant backend that implements this exact flow — create an order, hand off the `orderId`, confirm by card in the hosted checkout, and read the paid status. It runs against a local Nevermined stack — see the tutorial's prerequisites. ## Create an Order `POST /api/v1/orders` is authenticated with your API key and is the only call that sets a price. | Field | Type | Required | Description | | - | - | - | - | | `amountMinor` | integer | Yes | Amount in USD cents, from `100` ($1.00) to `99999999` ($999,999.99). | | `currency` | string | Yes | Must be `"usd"` in Phase 1. | | `description` | string | No | Human-readable label for the charge, up to 1,024 characters. | | `buyerRef` | string | No | Your own reference for the buyer or cart, up to 255 characters. Returned on reads. | | `idempotencyKey` | string | No | Retry-safety key, up to 255 characters. See [Retries and idempotency](#retries-and-idempotency). | | `lineItems` | array | No | Cart lines, stored as you send them. Not validated or summed in Phase 1. | | `metadata` | object | No | Opaque data stored with the Order. Never returned to the buyer. | | `paymentProvider` | string | No | Defaults to `"stripe"`, the only provider in Phase 1. | | `captureMode` | string | No | Defaults to `"automatic"`, the only mode in Phase 1. | There is deliberately no field for a Stripe account, fee, or transfer destination. Nevermined resolves your Connect account server-side from the API key on every request, so a buyer-facing bug can never redirect a payout. > [tab] curl > > ```bash theme={null} > curl -X POST https://api.sandbox.nevermined.app/api/v1/orders \ > -H "Authorization: Bearer $NVM_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "amountMinor": 343795, > "currency": "usd", > "description": "Cart checkout — 3 items", > "buyerRef": "merchant-order-4821", > "idempotencyKey": "merchant-order-4821", > "lineItems": [ > { "sku": "LENS-50", "description": "50mm f/1.8 lens", "quantity": 1, "amountMinor": 299900 }, > { "sku": "FILTER-UV", "description": "UV filter", "quantity": 2, "amountMinor": 43895 } > ] > }' > ``` > [tab] TypeScript > > ```typescript theme={null} > const response = await fetch('https://api.sandbox.nevermined.app/api/v1/orders', { > method: 'POST', > headers: { > Authorization: `Bearer ${process.env.NVM_API_KEY}`, > 'Content-Type': 'application/json', > }, > body: JSON.stringify({ > amountMinor: 343795, // $3,437.95 in cents > currency: 'usd', > description: 'Cart checkout — 3 items', > buyerRef: 'merchant-order-4821', > idempotencyKey: 'merchant-order-4821', // reuse your own order id > lineItems: [ > { sku: 'LENS-50', description: '50mm f/1.8 lens', quantity: 1, amountMinor: 299900 }, > { sku: 'FILTER-UV', description: 'UV filter', quantity: 2, amountMinor: 43895 }, > ], > }), > }) > > if (!response.ok) { > const error = await response.json() > throw new Error(`Order refused: ${error.code} ${error.message}`) > } > > const { orderId, status } = await response.json() > // Hand orderId to the buyer's browser. Keep clientSecret server-side. > ``` > [tab] Python > > ```python theme={null} > import os > import requests > > response = requests.post( > "https://api.sandbox.nevermined.app/api/v1/orders", > headers={ > "Authorization": f"Bearer {os.environ['NVM_API_KEY']}", > "Content-Type": "application/json", > }, > json={ > "amountMinor": 343795, # $3,437.95 in cents > "currency": "usd", > "description": "Cart checkout — 3 items", > "buyerRef": "merchant-order-4821", > "idempotencyKey": "merchant-order-4821", # reuse your own order id > "lineItems": [ > {"sku": "LENS-50", "description": "50mm f/1.8 lens", "quantity": 1, "amountMinor": 299900}, > {"sku": "FILTER-UV", "description": "UV filter", "quantity": 2, "amountMinor": 43895}, > ], > }, > timeout=30, > ) > > if not response.ok: > error = response.json() > raise RuntimeError(f"Order refused: {error['code']} {error['message']}") > > order = response.json() > order_id = order["orderId"] > # Hand order_id to the buyer's browser. Keep clientSecret server-side. > ``` A successful call returns `201 Created`: ```json theme={null} { "orderId": "ord_9f2c1a7e-3b4d-4c8a-9e21-0a5b6c7d8e9f", "clientSecret": "pi_3PGh9k2eZvKYlo2C1abc2Def_secret_9x8y7z6w5v4u3t2s1r0q", "status": "requires_payment" } ``` The `clientSecret` is what the buyer's browser confirms against. In the standard flow you never touch it: the checkout fetches it from `GET /api/v1/orders/{id}`. It's returned here so your server can log or reconcile the PaymentIntent, and it's withheld once the Order stops being payable. ## Read an Order `GET /api/v1/orders/{id}` needs **no authentication**. The `orderId` is the access control, which is why it's a long random id and must be treated like a bearer token: share it only with the buyer it belongs to, and don't put it in logs or analytics. The endpoint is rate-limited per caller and returns `Cache-Control: no-store`. ```bash theme={null} curl https://api.sandbox.nevermined.app/api/v1/orders/ord_9f2c1a7e-3b4d-4c8a-9e21-0a5b6c7d8e9f ``` ```json theme={null} { "id": "ord_9f2c1a7e-3b4d-4c8a-9e21-0a5b6c7d8e9f", "amountMinor": 343795, "currency": "usd", "status": "paid", "amountRefundedMinor": 0, "description": "Cart checkout — 3 items", "buyerRef": "merchant-order-4821", "paymentIntentId": "pi_3PGh9k2eZvKYlo2C1abc2Def", "expiresAt": "2026-09-07T12:00:00.000Z" } ``` The response is a buyer-safe view. It never includes your identity, your Connect account, the fee, or the `metadata` you attached. `clientSecret` is present only while the status is `requires_payment` and `expiresAt` has not passed. Because the read is public, use it from your server as the source of truth before you fulfill: poll it after the buyer returns from checkout, and treat `paid` as the only status that means money moved. ### Order statuses | Status | Meaning | | - | - | | `requires_payment` | Created and awaiting the buyer. `clientSecret` is available until `expiresAt`. | | `paid` | The buyer confirmed and Stripe settled the charge. Safe to fulfill. | | `failed` | The PaymentIntent could not be created, or the buyer's payment attempt failed. Terminal: no money moved, and the Order can't be retried. | | `partially_refunded` | Part of the charge was refunded. `amountRefundedMinor` says how much. | | `refunded` | The full charge was refunded. | | `disputed` | The buyer opened a chargeback, or you lost one. A won dispute returns the Order to `paid`; a lost one stays `disputed`. Per-dispute win/loss detail is not exposed on the Order. | An Order is payable for 24 hours by default. After `expiresAt` the read stops returning `clientSecret` and the buyer can no longer pay it. Create a new Order instead. ## Retries and idempotency Network timeouts happen. Send an `idempotencyKey` (your own order id works well) and a retried `POST /api/v1/orders` with the same key returns the same `orderId`, and the same `clientSecret` while the Order is still payable, rather than creating a second charge. Behind it, Nevermined also pins the Stripe PaymentIntent to the Order, so a retry can never mint two PaymentIntents for one cart. If you reuse a key with a different **amount or currency**, the call is refused with `409` `BCK.ORDER.0007`. Reusing it with the same amount and currency returns the original Order unchanged: the `description`, `buyerRef`, `lineItems` and `metadata` of the retried request are ignored, not merged. Generate a fresh key for a genuinely new Order. ## Refunds and disputes In Phase 1 there is no refund endpoint. Orders are charged on Nevermined's Stripe platform account and paid out to your Connect account, so a refund is issued on the Stripe side by Nevermined rather than from your own Stripe Dashboard. Contact Nevermined to refund an Order. Once Stripe reports the refund by webhook, the Order moves to `refunded` or `partially_refunded` and `amountRefundedMinor` is updated. Chargebacks are recorded, not managed. When a buyer disputes a charge, the Order moves to `disputed`. If the dispute is won, the Order returns to `paid`; if it is lost, it stays `disputed`. Evidence submission through Nevermined is a later phase; in Phase 1, work with the Nevermined team on any dispute. ## Error codes Every error uses the standard [Nevermined error envelope](/docs/development-guide/api-errors/overview). Branch on `code`, not on the HTTP status alone. | Code | HTTP | Retry? | What it means | What to do | | - | - | - | - | - | | `BCK.ORDER.0001` | 400 | No | Invalid request: amount out of range, a currency other than `usd`, or an unsupported `paymentProvider` or `captureMode`. | Fix the body. | | `BCK.ORDER.0002` | 404 | No | No Order exists with that id. | Check the id you passed to `GET /api/v1/orders/{id}`. | | `BCK.ORDER.0003` | 403 | No | The API key doesn't belong to an active organization, or the amount exceeds your per-order cap. | Use an organization API key. If the cap is the blocker, contact Nevermined. | | `BCK.ORDER.0004` | 500 | No | No validated Stripe Connect account able to receive payments was found on your organization or on the API key owner's profile. | Complete Stripe Connect onboarding. | | `BCK.ORDER.0005` | 500 | No | Stripe could not create the PaymentIntent. The Order is marked `failed`; no money moved. | Create a new Order. If it persists, contact Nevermined. | | `BCK.ORDER.0007` | 409 | No | The `idempotencyKey` was reused with a different amount or currency. | Send a new key for a new Order. | | `BCK.ORDER.0010` | 429 | Yes | You created Orders faster than your velocity limit allows. | Back off and retry. | A card decline never surfaces as an API error to your server. The buyer's browser confirms the payment, so the decline is shown to the buyer in the checkout. Stripe then reports the failed attempt by webhook and the Order moves to `failed`. Create a new Order if the buyer wants to try again. ```json theme={null} { "code": "BCK.ORDER.0003", "message": "Merchant not authorized for Orders", "hint": "The order was not initiated by an active organization account, or the requested amount exceeds the merchant's per-order cap. ...", "category": "business", "retryable": false, "correlationId": "a3f6b1c4-7d2e-4a9b-8e0c-12f4d8e6c5b9" } ``` ## Phase 1 limits | | Phase 1 | | - | - | | Currency | USD only | | Amount | $1.00 to $999,999.99 per Order | | Provider | Stripe, via your organization's Connect account | | Capture | Automatic on confirmation | | Payable window | 24 hours by default | | Fees | The Nevermined fee is set on the PaymentIntent at creation and retained when Stripe pays out. Your Connect account receives the remainder. See [Fees and Settlement](/docs/integrate/patterns/fiat-payments#fees-and-settlement). | Server-side checkout by agents, a refund API, and dispute handling through Nevermined are later phases and are not available today. ## Next steps > [card] [Fiat Checkout Chat tutorial](https://github.com/nevermined-io/tutorials/tree/main/fiat-checkout-chat) > > A worked Next.js + merchant-backend example of the Orders flow. Runs against a local Nevermined stack; see its prerequisites. > [card] [Fiat Payments](/docs/integrate/patterns/fiat-payments) > > Card plans, delegations, revenue routing, and fees for the rest of the fiat rails. > [card] [Organizations](/docs/solutions/organizations/overview) > > Set up the organization account and API key that Orders require. > [card] [API Errors](/docs/development-guide/api-errors/overview) > > The error envelope, categories, and retry semantics used across the API. # Organizations & Workspaces Source: https://nevermined.ai/docs/integrate/patterns/organizations List the organizations you belong to, target a specific workspace when publishing agents and plans, and read each org's activity feed from the Payments SDK. ## Overview Every Nevermined account can belong to one or more **organizations** — first-class workspaces with their own members, agents, plans, and billing. The Payments SDK exposes three building blocks for working with them from your code: * **List your memberships** — every organization you're an active member of, with your role in each. * **Publish into a specific workspace** — when you register an agent, plan, or API key, tell the SDK which workspace should own it. * **Read the activity feed** — paginated events for everything happening in an organization (member changes, customers, subscriptions, webhook deliveries). These map to a small, focused surface on `payments.organizations` and a single optional `organizationId` argument on the publish methods you already use. > [!NOTE] > > Workspace selection is transported by the `X-Current-Org-Id` header. The backend resolves it in priority order: route path parameter → this header → the API key's organization tag → your most-recent active membership → personal account. Pinning a workspace via the SDK is the same control your webapp's workspace switcher uses. ## List the organizations you belong to Use this to drive a workspace picker in your own tools, or to confirm where a publish will land before sending it. > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox', > }) > > const memberships = await payments.organizations.getMyMemberships() > > for (const m of memberships) { > console.log(`${m.orgName} (${m.orgType}) — ${m.role}${m.isAdmin ? ' (admin)' : ''}`) > } > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_API_KEY"], > environment="sandbox", > ) > ) > > memberships = payments.organizations.get_my_memberships() > > for m in memberships: > admin = " (admin)" if m.is_admin else "" > print(f"{m.org_name} ({m.org_type.value}) — {m.role.value}{admin}") > ``` A typical response (a Premium org and an Enterprise one): ```json theme={null} [ { "orgId": "org-3f9a...", "orgName": "Acme Robotics", "role": "Admin", "orgType": "Premium", "isAdmin": true, "hasSubscriptionHistory": true }, { "orgId": "org-7d11...", "orgName": "Beta Labs", "role": "Member", "orgType": "Enterprise", "isAdmin": false, "hasSubscriptionHistory": true } ] ``` If you have no active memberships the list is empty — you're operating as a personal account. ## Publish into a specific organization Two ways to choose where a published agent, plan, or API key lands. Pick whichever fits the calling code. ### Per-call override (recommended for one-off publishes) Pass `organizationId` (TypeScript) or `organization_id=` (Python) to the publish method. The SDK sends `X-Current-Org-Id` for that call only — your instance-level workspace is untouched. > [tab] TypeScript > > ```typescript theme={null} > // Publish a single agent into Acme Robotics, without leaving Acme as your active workspace. > const { agentId } = await payments.agents.registerAgent( > { name: 'Legal Assistant', tags: ['legal', 'rag'] }, > { > authType: 'bearer', > endpoints: [{ POST: 'https://api.example.com/legal/tasks' }], > }, > [planId], > { organizationId: 'org-3f9a...' }, > ) > ``` > [tab] Python > > ```python theme={null} > # Publish a single agent into Acme Robotics, without leaving Acme as your active workspace. > from payments_py import AgentAPIAttributes, AgentMetadata, AuthType, Endpoint > > result = payments.agents.register_agent( > AgentMetadata(name="Legal Assistant", tags=["legal", "rag"]), > AgentAPIAttributes( > auth_type=AuthType.BEARER, > endpoints=[Endpoint(verb="POST", url="https://api.example.com/legal/tasks")], > ), > [plan_id], > organization_id="org-3f9a...", > ) > ``` The same `organizationId` / `organization_id` option works on `registerAgentAndPlan` / `register_agent_and_plan` and on the plan-registration helpers (`registerPlan`, `registerCreditsPlan`, `registerTimePlan` and their `register_*_plan` Python equivalents). ### Pin a workspace for the whole session Set the organization once and every subsequent call from this `Payments` instance — including all sub-APIs (`agents`, `plans`, `requests`, …) — uses it. > [tab] TypeScript > > ```typescript theme={null} > payments.setOrganizationId('org-3f9a...') > > // All of these now land in Acme Robotics: > await payments.agents.registerAgent(metadata, api, [planId]) > await payments.plans.registerCreditsPlan(planMetadata, price, credits) > > // Clear the pin when you're done — falls back to personal / API-key default. > payments.setOrganizationId(null) > ``` > [tab] Python > > ```python theme={null} > payments.set_organization_id("org-3f9a...") > > # All of these now land in Acme Robotics: > payments.agents.register_agent(metadata, api, [plan_id]) > payments.plans.register_credits_plan(plan_metadata, price_config, credits_config) > > # Clear the pin when you're done — falls back to personal / API-key default. > payments.set_organization_id(None) > ``` You can also pin from the constructor: > [tab] TypeScript > > ```typescript theme={null} > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox', > organizationId: 'org-3f9a...', > }) > ``` > [tab] Python > > ```python theme={null} > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_API_KEY"], > environment="sandbox", > organization_id="org-3f9a...", > ) > ) > ``` > [!WARNING] > > Targeting an organization you're not a member of (or an inactive membership) is rejected by the backend with a 403. The SDK surfaces this as a `PaymentsError`. ## Read the organization activity feed Paginated events for member changes, customer additions, subscription transitions, and webhook deliveries. Only members of the organization can read it; the backend enforces a Premium+ entitlement. > [tab] TypeScript > > ```typescript theme={null} > import { OrganizationActivityEventType } from '@nevermined-io/payments' > > const page = await payments.organizations.getOrganizationActivity( > 'org-3f9a...', > { > eventType: OrganizationActivityEventType.MemberInvited, > from: '2026-05-01T00:00:00Z', > to: '2026-05-31T23:59:59Z', > page: 1, > limit: 25, > }, > ) > > console.log(`${page.total} matching events`) > for (const event of page.items) { > console.log(event.occurredAt, event.eventType, event.subject.kind, event.subject.id) > } > ``` > [tab] Python > > ```python theme={null} > from payments_py import OrganizationActivityEventType, OrganizationActivityFilters > > page = payments.organizations.get_organization_activity( > "org-3f9a...", > OrganizationActivityFilters( > event_type=OrganizationActivityEventType.MEMBER_INVITED, > **{"from": "2026-05-01T00:00:00Z"}, > to="2026-05-31T23:59:59Z", > page=1, > limit=25, > ), > ) > > print(f"{page.total} matching events") > for event in page.items: > print(event.occurred_at, event.event_type, event.subject.kind, event.subject.id) > ``` All filters are optional. The `eventType` filter accepts a single value or a list of values (sent as a comma-separated list); `limit` is the page size (backend cap: 200). The known event types you can filter on: | Event type | Emitted when | | - | - | | `member.invited` / `member.joined` | An admin invites a teammate; the invitee accepts | | `member.role_changed` | A member's role flips between Admin and Member | | `member.deactivated` / `member.reactivated` / `member.removed` | Membership lifecycle transitions | | `invitation.revoked` / `invitation.expired` | Pending invitation lifecycle | | `agent.created` / `plan.created` / `plan.purchased` | Resource lifecycle inside the org | | `customer.added` / `customer.blocked` / `customer.unblocked` | External customer lifecycle | | `subscription.upgraded` / `subscription.downgraded` / `subscription.canceled` / `subscription.lapsed` | Tier subscription transitions on the org | | `webhook.delivered` / `webhook.failed` | Webhook delivery outcomes (status in `metadata`) | New event types are accepted without an SDK upgrade — the `eventType` field is a plain string in both SDKs. Each event also carries a `subject: { kind, id, …extras }` payload describing the resource it's about (e.g. invitations include `role` + `email`, members include `role` + `userId`, subscriptions include `tier`). ## How workspace context is resolved When the backend handles an authenticated request, it picks the active organization in this order — the first match wins: **1. Route path** If the URL itself includes `:orgId` (for example `/organizations/{orgId}/activity`), that organization is used directly. **2. X-Current-Org-Id header** Set by the SDK from your pin or per-call override. The backend validates that you're an active member of the requested org before honoring it. **3. API key tag** If your NVM API key was minted scoped to a specific organization, that scope is applied. **4. Fallback membership** Your most-recent active membership — preserves backwards compatibility for single-org callers that don't set anything explicitly. **5. Personal account** No active membership → resources you publish are owned by your personal account. The SDK never picks a workspace silently — if you don't set one, the backend's fallback rules apply. ## Related > [card] [Organizations on Nevermined](/docs/solutions/organizations/overview) > > Concepts, tiers, and the webapp surface for organization owners. > [card] [Quickstart — TypeScript](/docs/integrate/quickstart/typescript) > > Set up the SDK and publish your first agent. > [card] [Quickstart — Python](/docs/integrate/quickstart/python) > > Set up the Python SDK and publish your first agent. > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Fixed, usage-based, and outcome-based pricing patterns. # Payment Models Source: https://nevermined.ai/docs/integrate/patterns/payment-models Configure credits-based, time-based, and dynamic pricing using programmable x402 settlement The Payments Facilitator supports multiple payment models to match your product needs across APIs, agents/tools, and protected resources. These models are enabled by Nevermined's **programmable x402 settlement** layer (smart accounts + policies + contracts), not just single-transfer pay-per-request flows. If you’re looking for the HTTP handshake details (402 discovery → retry with `PAYMENT-SIGNATURE`), see: * [Nevermined x402](/docs/development-guide/nevermined-x402) Further reading: * [Making x402 programmable](https://nevermined.ai/blog/making-x402-programmable) * [Building Agentic Payments with Nevermined, x402, A2A, and AP2](https://nevermined.ai/blog/building-agentic-payments-with-nevermined-x402-a2a-and-ap2) ## Payment Model Types > [card] Credits-Based > > Charge per request or API call. Users purchase credits and consume them with each query. > [card] Time-Based > > Subscription access for specific durations. Unlimited usage within the time period. > [card] Dynamic > > Variable pricing based on request complexity, token count, or custom metrics. > [card] Hybrid > > Combine time-based access with credit limits for balanced monetization. ## Credits-Based Plans Charge users based on actual usage. Each request consumes a configurable number of credits. > [tab] TypeScript > > ```typescript theme={null} > import { > Payments, > getERC20PriceConfig, > getFixedCreditsConfig > } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY, > environment: 'sandbox' > }) > > // Price: 10 USDC for 100 credits > const priceConfig = getERC20PriceConfig( > 10_000_000n, // 10 USDC (6 decimals) > '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC address > process.env.BUILDER_ADDRESS // Your receiving address > ) > > // Credits: 100 total, 1 per request > const creditsConfig = getFixedCreditsConfig( > 100n, // Total credits > 1n // Credits per request > ) > > const { planId } = await payments.plans.createPlan({ > agentId: 'did:nv:agent-123', > name: 'Pro Plan - 100 Queries', > description: 'Access to AI assistant with 100 queries', > priceConfig, > creditsConfig, > accessLimit: 'credits' > }) > ``` > [tab] Python > > ```python theme={null} > from payments_py import Payments, PaymentOptions > from payments_py.plans import get_erc20_price_config, get_fixed_credits_config > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox') > ) > > # Price: 10 USDC for 100 credits > price_config = get_erc20_price_config( > 10_000_000, # 10 USDC (6 decimals) > '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', # USDC address > os.environ['BUILDER_ADDRESS'] # Your receiving address > ) > > # Credits: 100 total, 1 per request > credits_config = get_fixed_credits_config( > 100, # Total credits > 1 # Credits per request > ) > > plan = payments.plans.create_plan( > agent_id='did:nv:agent-123', > name='Pro Plan - 100 Queries', > description='Access to AI assistant with 100 queries', > price_config=price_config, > credits_config=credits_config, > access_limit='credits' > ) > ``` ## Time-Based Plans Provide unlimited access for a specific duration. Great for subscription models. > [tab] TypeScript > > ```typescript theme={null} > import { getTimeBasedConfig } from '@nevermined-io/payments' > > // Price: 50 USDC for 30 days access > const priceConfig = getERC20PriceConfig( > 50_000_000n, > '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', > process.env.BUILDER_ADDRESS > ) > > // Duration: 30 days (in seconds) > const timeConfig = getTimeBasedConfig( > 30 * 24 * 60 * 60 // 30 days in seconds > ) > > const { planId } = await payments.plans.createPlan({ > agentId: 'did:nv:agent-123', > name: 'Monthly Subscription', > description: 'Unlimited access for 30 days', > priceConfig, > timeConfig, > accessLimit: 'time' > }) > ``` > [tab] Python > > ```python theme={null} > from payments_py.plans import get_time_based_config > > # Price: 50 USDC for 30 days access > price_config = get_erc20_price_config( > 50_000_000, > '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', > os.environ['BUILDER_ADDRESS'] > ) > > # Duration: 30 days (in seconds) > time_config = get_time_based_config( > 30 * 24 * 60 * 60 # 30 days in seconds > ) > > plan = payments.plans.create_plan( > agent_id='did:nv:agent-123', > name='Monthly Subscription', > description='Unlimited access for 30 days', > price_config=price_config, > time_config=time_config, > access_limit='time' > ) > ``` ## Dynamic Pricing Charge variable amounts based on request complexity. The x402 `max_amount` field controls the maximum charge per request. > [tab] TypeScript > > ```typescript theme={null} > import { getDynamicCreditsConfig } from '@nevermined-io/payments' > > // Dynamic: charge 1-10 credits based on request > const creditsConfig = getDynamicCreditsConfig( > 1n, // Minimum credits per request > 10n // Maximum credits per request > ) > > const { planId } = await payments.plans.createPlan({ > agentId: 'did:nv:agent-123', > name: 'Pay As You Go', > description: 'Variable pricing based on complexity', > priceConfig, > creditsConfig, > accessLimit: 'credits' > }) > > // During settlement, specify actual amount > await payments.facilitator.settlePermissions({ > planId, > maxAmount: BigInt(actualCreditsUsed), // 1-10 based on request > x402AccessToken: token, > subscriberAddress: address > }) > ``` > [tab] Python > > ```python theme={null} > from payments_py.plans import get_dynamic_credits_config > > # Dynamic: charge 1-10 credits based on request > credits_config = get_dynamic_credits_config( > 1, # Minimum credits per request > 10 # Maximum credits per request > ) > > plan = payments.plans.create_plan( > agent_id='did:nv:agent-123', > name='Pay As You Go', > description='Variable pricing based on complexity', > price_config=price_config, > credits_config=credits_config, > access_limit='credits' > ) > > # During settlement, specify actual amount > await payments.facilitator.settle_permissions( > payment_required=payment_required, > x402_access_token=access_token, > max_amount=str(actual_credits_used), # 1-10 based on request > ) > ``` ## Trial Plans Offer free trials to attract new users. > [tab] TypeScript > > ```typescript theme={null} > // Free credits trial > const { planId } = await payments.plans.registerCreditsTrialPlan({ > agentId: 'did:nv:agent-123', > name: 'Free Trial', > description: '10 free queries to try the service', > credits: 10n, > creditsPerRequest: 1n > }) > > // Free time-based trial > const { planId: timePlanId } = await payments.plans.registerTimeTrialPlan({ > agentId: 'did:nv:agent-123', > name: '7-Day Trial', > description: 'Unlimited access for 7 days', > duration: 7 * 24 * 60 * 60 // 7 days in seconds > }) > ``` > [tab] Python > > ```python theme={null} > # Free credits trial > plan = payments.plans.register_credits_trial_plan( > agent_id='did:nv:agent-123', > name='Free Trial', > description='10 free queries to try the service', > credits=10, > credits_per_request=1 > ) > > # Free time-based trial > time_plan = payments.plans.register_time_trial_plan( > agent_id='did:nv:agent-123', > name='7-Day Trial', > description='Unlimited access for 7 days', > duration=7 * 24 * 60 * 60 # 7 days in seconds > ) > ``` ## Multi-Tier Pricing Create multiple plans for different user segments: ```typescript theme={null} // Basic tier const basicPlan = await payments.plans.createPlan({ agentId, name: 'Basic', priceConfig: getERC20PriceConfig(5_000_000n, usdcAddress, builderAddress), creditsConfig: getFixedCreditsConfig(50n, 1n) }) // Pro tier const proPlan = await payments.plans.createPlan({ agentId, name: 'Pro', priceConfig: getERC20PriceConfig(20_000_000n, usdcAddress, builderAddress), creditsConfig: getFixedCreditsConfig(250n, 1n) // Better value }) // Enterprise tier const enterprisePlan = await payments.plans.createPlan({ agentId, name: 'Enterprise', priceConfig: getERC20PriceConfig(100_000_000n, usdcAddress, builderAddress), creditsConfig: getFixedCreditsConfig(2000n, 1n) // Best value }) ``` ## Payment Currencies ### Cryptocurrency (ERC-20) Accept any ERC-20 token on supported networks: ```typescript theme={null} // USDC const usdcConfig = getERC20PriceConfig( 10_000_000n, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', builderAddress ) // USDT const usdtConfig = getERC20PriceConfig( 10_000_000n, '0xdAC17F958D2ee523a2206206994597C13D831ec7', builderAddress ) ``` ### Fiat (Stripe, Braintree, or Visa) Accept credit card payments via Stripe, Braintree, or the Visa Trusted Agent Protocol. The seller's `fiatPaymentProvider` metadata (`stripe` or `braintree`) selects the provider per plan at registration time; all three settle x402 charges through the same `nvm:card-delegation` scheme. Visa delegations add a per-delegation WebAuthn/passkey approval enforced by Visa VTS and settle through Stripe Connect — see the [Visa subsection](/docs/products/payments/card-enrollment) on the card enrollment page. ```typescript theme={null} const fiatConfig = await payments.plans.getFiatPriceConfig({ amount: 1000, // $10.00 currency: 'USD' }) // One-time fiat purchase via the SDK (Stripe-priced plans only): const paymentIntent = await payments.plans.orderFiatPlan(planId) ``` > [!NOTE] > > `orderFiatPlan` creates a Stripe payment for the plan and is only available for Stripe-priced plans. Braintree-priced plans are purchased in the Nevermined App with an enrolled card. Both Stripe and Braintree plans support per-request x402 settlement against credit-card delegations — see [Braintree onboarding](/docs/products/payments/braintree-onboarding) for the seller-side requirements (per-currency merchant accounts). ## Choosing the Right Model | Model | Best For | Example | | - | - | - | | Credits-based | API calls, queries, transactions | AI chatbot, image generation | | Time-based | Continuous access, subscriptions | SaaS tools, monitoring | | Dynamic | Variable workloads, token-based | LLM inference, batch processing | | Hybrid | Balanced usage with limits | Enterprise subscriptions | ## Next Steps > [card] [Register Your Agent](/docs/integrate/quickstart/5-minute-setup) > > Set up your agent with a payment plan > [card] [Validate Requests](/docs/integrate/patterns/validate-requests) > > Implement request validation in your agent # Stablecoin Payments Source: https://nevermined.ai/docs/integrate/patterns/stablecoin-payments Accept USDC, EURC, or any ERC-20 token on-chain with the lowest fees and full transparency. Accept USDC, EURC, or any ERC-20 token directly on-chain. Stablecoin payments are Nevermined's native payment method, purpose-built for crypto users and autonomous agent-to-agent commerce. ## When to Use Stablecoins > [card] Agent-to-Agent Payments > > Agents with wallets can purchase plans and pay per request autonomously, with no human in the loop. > [card] Human-to-Agent Purchases > > Users buy plans through the Nevermined App checkout page, paying with tokens from their connected wallet. > [card] Crypto-Native Users > > Your audience already holds stablecoins and prefers on-chain payments over traditional card flows. > [card] Lowest Fees > > Just 1% Nevermined fee with no additional processing surcharges. Ideal for high-volume or high-value use cases. > [card] On-Chain Transparency > > Every payment settles on-chain, giving both parties a verifiable, auditable record of every transaction. ## How It Works **1. Fund a smart account** The subscriber funds their Nevermined smart account with ERC-20 tokens (USDC, EURC, or another supported token). This account is an ERC-4337 smart account that supports programmable permissions. **2. Create a delegation** The subscriber creates a delegation that grants the facilitator permission to execute specific actions (order plans, burn credits, redeem access) on their behalf. Each delegation is scoped by spending limits and duration, following the principle of least privilege. **3. Payment settles on-chain** When the subscriber purchases a plan or makes a request, the facilitator submits a UserOperation to the smart contract. The payment settles on-chain and credits are minted to the subscriber. **4. Credits consumed per request** Each API call or agent query burns credits according to the plan configuration. If the subscriber's balance runs low, the facilitator can [top up](/docs/integrate/patterns/top-up) their credits automatically — when the wallet has sufficient balance and the delegation permits it. ## Supported Networks and Tokens Payments settle on the **Base** network. The most common tokens are: | Token | Description | Base Mainnet | Base Sepolia | | - | - | - | - | | USDC | USD-pegged stablecoin by Circle | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | | EURC | EUR-pegged stablecoin by Circle | `0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42` | `0x808456652fdb597867f38412077A9182bf77359F` | > [!TIP] > > Nevermined supports any ERC-20 token on Base. If you need to accept a custom token, you can specify its contract address when creating your plan's price configuration. ## Permission Model Delegations are the core of the stablecoin permission model. Instead of giving the facilitator full control over a wallet, subscribers create scoped delegations that limit exactly what can be done. The delegation model is shared between crypto (`erc4337`) and fiat (`stripe`) payment providers — and the same delegation backs both payment protocols: an x402 settlement and an [MPP settlement](/docs/development-guide/nevermined-x402#paying-an-mpp-protected-service) draw on one budget and one credit meter. Each delegation enforces the **principle of least privilege** through two limits: | Limit | Description | | - | - | | `spendingLimitCents` | Maximum total amount (in cents) that can be spent across all transactions | | `durationSecs` | Duration in seconds after which the delegation expires | When the spending limit is exhausted or the delegation expires, it stops working. The subscriber must create a new delegation with fresh limits to continue. Delegations are created via the SDK before generating an x402 access token: ```typescript theme={null} // Create a delegation for crypto payments const delegation = await payments.delegation.createDelegation({ provider: 'erc4337', spendingLimitCents: 10000, durationSecs: 604800, // 7 days currency: 'usdc', }) ``` > [!NOTE] > > Delegations are revocable at any time by the smart account owner. You always retain full control over your wallet. Under the hood, delegations create the appropriate session keys for the chosen provider. ## Fees and Settlement | Item | Cost | | - | - | | Nevermined fee | 1% of the plan price | | Processing surcharge | None | | Settlement | On-chain via Nevermined smart contracts on Base | Because there's no payment processor in the middle, stablecoin payments carry no additional fees beyond the 1% Nevermined fee. This makes them the most cost-effective option, especially for high-volume use cases. ## Supported Plan Types > [card] Credits-Based > > Prepaid credits consumed per request. Set total credits and cost per request when creating the plan. > [card] Time-Based > > Unlimited access for a set duration (days, months, years). Great for subscription-style access. > [card] Dynamic Pricing > > Variable credit charges based on request complexity, token count, or custom metrics. > [card] Hybrid > > Combine time-based access with credit limits for balanced monetization. > [card] Trial > > Offer free credits or time-limited trials to let users test your agent before purchasing. > [card] Pay-As-You-Go > > Per-request settlement in USDC or EURC. No prepaid credits needed -- customers pay on demand. ## Automatic Top-Ups When a subscriber's credit balance runs low, the facilitator can automatically top up their credits at settlement — no manual balance checks required. This keeps agent-to-agent workflows running without interruption, bounded by the delegation's `spendingLimitCents`. See the [Automatic Credit Top-Ups](/docs/integrate/patterns/top-up) guide for how it works, how to set up the delegation, crypto vs. fiat behavior, and failure handling. ## Next Steps > [card] [Fiat Payments](/docs/integrate/patterns/fiat-payments) > > Accept credit cards via Stripe for mainstream and enterprise users > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Configure credits, time-based, dynamic, and hybrid plans > [card] [Nevermined x402](/docs/development-guide/nevermined-x402) > > Deep dive into the x402 protocol and smart account settlement > [card] [Payment Plans API](/docs/api-reference/typescript/payment-plans) > > Create and manage plans programmatically with the TypeScript SDK # Subscription Access Source: https://nevermined.ai/docs/integrate/patterns/subscription-access Patterns for time-based subscription access control Copy-paste patterns for implementing time-based subscription access. ## Basic Time-Based Validation For subscription plans, validate that the user's access hasn't expired: > [tab] TypeScript > > ```typescript theme={null} > import { buildPaymentRequired } from '@nevermined-io/payments' > > async function validateSubscription( > x402Token: string, > planId: string, > agentId: string, > endpoint: string > ) { > const paymentRequired = buildPaymentRequired({ > planId, endpoint, agentId, httpVerb: 'POST' > }) > > const result = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount: BigInt(1) > }) > > if (!result.isValid) { > return { > valid: false, > reason: result.reason > } > } > > // For time-based plans, check expiration > if (result.expiresAt) { > const now = new Date() > const expiry = new Date(result.expiresAt) > > if (now > expiry) { > return { > valid: false, > reason: 'SUBSCRIPTION_EXPIRED', > expiredAt: expiry > } > } > > const daysRemaining = Math.ceil( > (expiry.getTime() - now.getTime()) / (1000 * 60 * 60 * 24) > ) > > return { > valid: true, > expiresAt: expiry, > daysRemaining > } > } > > return { valid: true } > } > ``` > [tab] Python > > ```python theme={null} > from datetime import datetime > from payments_py.x402.helpers import build_payment_required > > def validate_subscription( > x402_token: str, > plan_id: str, > agent_id: str, > endpoint: str > ) -> dict: > payment_required = build_payment_required( > plan_id=plan_id, endpoint=endpoint, > agent_id=agent_id, http_verb="POST" > ) > > result = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount="1" > ) > > if not result.is_valid: > return { > 'valid': False, > 'reason': getattr(result, 'reason', None) > } > > # For time-based plans, check expiration > if hasattr(result, 'expires_at') and result.expires_at: > now = datetime.now() > expiry = datetime.fromisoformat(result.expires_at) > > if now > expiry: > return { > 'valid': False, > 'reason': 'SUBSCRIPTION_EXPIRED', > 'expired_at': expiry.isoformat() > } > > days_remaining = (expiry - now).days > > return { > 'valid': True, > 'expires_at': expiry.isoformat(), > 'days_remaining': days_remaining > } > > return {'valid': True} > ``` ## Subscription Middleware Express middleware for subscription-only endpoints: ```typescript filename="middleware/subscription.ts" theme={null} import { Request, Response, NextFunction } from 'express' import { Payments, buildPaymentRequired } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' }) export interface SubscriptionInfo { valid: boolean expiresAt?: Date daysRemaining?: number planId: string } declare global { namespace Express { interface Request { subscription?: SubscriptionInfo } } } export function requireSubscription( planId: string, agentId: string, options?: { warnDaysBefore?: number } ) { const warnDays = options?.warnDaysBefore || 7 return async (req: Request, res: Response, next: NextFunction) => { const x402Token = req.headers['payment-signature'] as string if (!x402Token) { return res.status(402).json({ error: 'Subscription Required', code: 'MISSING_TOKEN' }) } try { const paymentRequired = buildPaymentRequired({ planId, endpoint: req.path, agentId, httpVerb: req.method }) const result = await payments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: x402Token, maxAmount: BigInt(1) }) if (!result.isValid) { return res.status(402).json({ error: 'Subscription Required', code: result.reason || 'INVALID_TOKEN' }) } // Check expiration for time-based plans if (result.expiresAt) { const now = new Date() const expiry = new Date(result.expiresAt) if (now > expiry) { return res.status(402).json({ error: 'Subscription Expired', code: 'SUBSCRIPTION_EXPIRED', expiredAt: expiry.toISOString() }) } const daysRemaining = Math.ceil( (expiry.getTime() - now.getTime()) / (1000 * 60 * 60 * 24) ) req.subscription = { valid: true, expiresAt: expiry, daysRemaining, planId } // Add warning header if expiring soon if (daysRemaining <= warnDays) { res.setHeader('X-Subscription-Warning', `Expires in ${daysRemaining} days`) } } else { req.subscription = { valid: true, planId } } next() } catch (error) { console.error('Subscription validation error:', error) return res.status(500).json({ error: 'Validation failed' }) } } } ``` > [!NOTE] > > For most use cases, the built-in `paymentMiddleware` from `@nevermined-io/payments/express` handles all of this automatically. Use this custom middleware only when you need fine-grained control over subscription expiration warnings. ## FastAPI Subscription Dependency ```python filename="dependencies/subscription.py" theme={null} from fastapi import Request, HTTPException from datetime import datetime from dataclasses import dataclass from typing import Optional from payments_py.x402.helpers import build_payment_required @dataclass class SubscriptionInfo: valid: bool expires_at: Optional[datetime] = None days_remaining: Optional[int] = None plan_id: Optional[str] = None def require_subscription( plan_id: str, agent_id: str, warn_days_before: int = 7 ): async def validate(request: Request) -> SubscriptionInfo: x402_token = request.headers.get('payment-signature', '') if not x402_token: raise HTTPException( status_code=402, detail={'error': 'Subscription Required', 'code': 'MISSING_TOKEN'} ) payment_required = build_payment_required( plan_id=plan_id, endpoint=str(request.url.path), agent_id=agent_id, http_verb=request.method ) result = payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=x402_token, max_amount="1" ) if not result.is_valid: raise HTTPException( status_code=402, detail={ 'error': 'Subscription Required', 'code': getattr(result, 'reason', 'INVALID_TOKEN') } ) # Check expiration for time-based plans if hasattr(result, 'expires_at') and result.expires_at: now = datetime.now() expiry = datetime.fromisoformat(result.expires_at) if now > expiry: raise HTTPException( status_code=402, detail={ 'error': 'Subscription Expired', 'code': 'SUBSCRIPTION_EXPIRED', 'expired_at': expiry.isoformat() } ) days_remaining = (expiry - now).days return SubscriptionInfo( valid=True, expires_at=expiry, days_remaining=days_remaining, plan_id=plan_id ) return SubscriptionInfo(valid=True, plan_id=plan_id) return validate ``` > [!NOTE] > > For most use cases, the built-in `PaymentMiddleware` from `payments_py.x402.fastapi` handles all of this automatically. Use this custom dependency only when you need fine-grained control over subscription expiration warnings. ## Subscription Status Endpoint Provide an endpoint for clients to check their subscription status: > [tab] TypeScript > > ```typescript theme={null} > app.get('/subscription/status', async (req, res) => { > const x402Token = req.headers['payment-signature'] as string > > if (!x402Token) { > return res.status(402).json({ error: 'Missing payment-signature header' }) > } > > try { > const paymentRequired = buildPaymentRequired({ > planId: PLAN_ID, endpoint: '/subscription/status', > agentId: AGENT_ID, httpVerb: 'GET' > }) > > const result = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount: BigInt(0) // status check, no credits consumed > }) > > if (!result.isValid) { > return res.json({ > active: false, > reason: result.reason > }) > } > > const response: any = { > active: true, > planId: PLAN_ID > } > > if (result.expiresAt) { > const expiry = new Date(result.expiresAt) > const now = new Date() > const daysRemaining = Math.ceil( > (expiry.getTime() - now.getTime()) / (1000 * 60 * 60 * 24) > ) > > response.expiresAt = expiry.toISOString() > response.daysRemaining = daysRemaining > response.status = daysRemaining <= 7 ? 'expiring_soon' : 'active' > } > > if (result.balance !== undefined) { > response.creditsRemaining = result.balance > } > > res.json(response) > } catch (error) { > res.status(500).json({ error: 'Failed to check status' }) > } > }) > ``` > [tab] Python > > ```python theme={null} > @app.get("/subscription/status") > async def subscription_status(request: Request): > x402_token = request.headers.get('payment-signature', '') > > if not x402_token: > raise HTTPException(status_code=402, detail='Missing payment-signature header') > > try: > payment_required = build_payment_required( > plan_id=PLAN_ID, endpoint="/subscription/status", > agent_id=AGENT_ID, http_verb="GET" > ) > > result = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount="0" # status check, no credits consumed > ) > > if not result.is_valid: > return { > 'active': False, > 'reason': getattr(result, 'reason', None) > } > > response = { > 'active': True, > 'plan_id': PLAN_ID > } > > if hasattr(result, 'expires_at') and result.expires_at: > expiry = datetime.fromisoformat(result.expires_at) > now = datetime.now() > days_remaining = (expiry - now).days > > response['expires_at'] = expiry.isoformat() > response['days_remaining'] = days_remaining > response['status'] = 'expiring_soon' if days_remaining <= 7 else 'active' > > if hasattr(result, 'balance') and result.balance is not None: > response['credits_remaining'] = result.balance > > return response > > except Exception as e: > raise HTTPException(status_code=500, detail='Failed to check status') > ``` ## Graceful Expiration Handling Handle subscription expiration gracefully with warnings: > [tab] TypeScript > > ```typescript theme={null} > interface ExpirationResponse { > allowed: boolean > warning?: string > action?: string > daysRemaining?: number > } > > function handleExpiration(expiresAt: Date): ExpirationResponse { > const now = new Date() > const daysRemaining = Math.ceil( > (expiresAt.getTime() - now.getTime()) / (1000 * 60 * 60 * 24) > ) > > // Already expired > if (daysRemaining <= 0) { > return { > allowed: false, > warning: 'Your subscription has expired', > action: 'renew', > daysRemaining: 0 > } > } > > // Grace period (allow access but warn) > if (daysRemaining <= 3) { > return { > allowed: true, > warning: `Your subscription expires in ${daysRemaining} day(s). Please renew to avoid interruption.`, > action: 'renew_soon', > daysRemaining > } > } > > // Warning period > if (daysRemaining <= 7) { > return { > allowed: true, > warning: `Your subscription expires in ${daysRemaining} days`, > daysRemaining > } > } > > // All good > return { > allowed: true, > daysRemaining > } > } > ``` > [tab] Python > > ```python theme={null} > from dataclasses import dataclass > from typing import Optional > > @dataclass > class ExpirationResponse: > allowed: bool > warning: Optional[str] = None > action: Optional[str] = None > days_remaining: Optional[int] = None > > def handle_expiration(expires_at: datetime) -> ExpirationResponse: > now = datetime.now() > days_remaining = (expires_at - now).days > > # Already expired > if days_remaining <= 0: > return ExpirationResponse( > allowed=False, > warning='Your subscription has expired', > action='renew', > days_remaining=0 > ) > > # Grace period (allow access but warn) > if days_remaining <= 3: > return ExpirationResponse( > allowed=True, > warning=f'Your subscription expires in {days_remaining} day(s). Please renew to avoid interruption.', > action='renew_soon', > days_remaining=days_remaining > ) > > # Warning period > if days_remaining <= 7: > return ExpirationResponse( > allowed=True, > warning=f'Your subscription expires in {days_remaining} days', > days_remaining=days_remaining > ) > > # All good > return ExpirationResponse( > allowed=True, > days_remaining=days_remaining > ) > ``` ## Hybrid Plans (Time + Credits) Handle plans that have both time limits and credit limits: > [tab] TypeScript > > ```typescript theme={null} > interface HybridValidation { > valid: boolean > reason?: string > timeRemaining?: number // days > creditsRemaining?: number > } > > async function validateHybridPlan( > x402Token: string, > paymentRequired: string, > maxAmount: bigint > ): Promise { > const result = await payments.facilitator.verifyPermissions({ > paymentRequired, x402AccessToken: x402Token, maxAmount > }) > > if (!result.isValid) { > return { valid: false, reason: result.reason } > } > > const issues: string[] = [] > > // Check time > if (result.expiresAt) { > const now = new Date() > const expiry = new Date(result.expiresAt) > const daysRemaining = Math.ceil( > (expiry.getTime() - now.getTime()) / (1000 * 60 * 60 * 24) > ) > > if (daysRemaining <= 0) { > return { valid: false, reason: 'TIME_EXPIRED' } > } > } > > // Check credits > if (result.balance !== undefined && result.balance <= 0) { > return { valid: false, reason: 'NO_CREDITS' } > } > > return { > valid: true, > timeRemaining: result.expiresAt > ? Math.ceil((new Date(result.expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24)) > : undefined, > creditsRemaining: result.balance > } > } > ``` > [tab] Python > > ```python theme={null} > @dataclass > class HybridValidation: > valid: bool > reason: Optional[str] = None > time_remaining: Optional[int] = None # days > credits_remaining: Optional[int] = None > > def validate_hybrid_plan( > x402_token: str, > payment_required: str, > max_amount: str > ) -> HybridValidation: > result = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount=max_amount > ) > > if not result.is_valid: > return HybridValidation(valid=False, reason=getattr(result, 'reason', None)) > > # Check time > expiry = None > if hasattr(result, 'expires_at') and result.expires_at: > now = datetime.now() > expiry = datetime.fromisoformat(result.expires_at) > days_remaining = (expiry - now).days > > if days_remaining <= 0: > return HybridValidation(valid=False, reason='TIME_EXPIRED') > > # Check credits > if hasattr(result, 'balance') and result.balance is not None and result.balance <= 0: > return HybridValidation(valid=False, reason='NO_CREDITS') > > return HybridValidation( > valid=True, > time_remaining=(expiry - datetime.now()).days if expiry else None, > credits_remaining=getattr(result, 'balance', None) > ) > ``` ## Next Steps > [card] [Dynamic Pricing](/docs/integrate/patterns/dynamic-pricing) > > Variable pricing strategies > [card] [Validate Requests](/docs/integrate/patterns/validate-requests) > > Request validation patterns # Automatic Credit Top-Ups Source: https://nevermined.ai/docs/integrate/patterns/top-up The x402 facilitator tops up a subscriber's credits automatically at settlement — pre-authorized once via a delegation, no manual order_plan loop. Autonomous agents shouldn't have to babysit a credit balance. Once a **delegation** is in place, you can stop calling `orderPlan()` in a loop. The x402 facilitator **tops up** the subscriber's credits automatically at settlement — the moment a paid request would otherwise fail for lack of credits — bounded by the spending limit you authorized. This is a built-in capability of the x402 flow. Many builders don't know it exists, so they write fragile balance-check-then-order loops by hand. You don't need to. ## The problem it solves Without a delegation, a subscriber has to manage credits themselves: check the balance, order more when it runs low, wait for the order to confirm, and only then make the request. In an agent-to-agent (A2A) pipeline that runs unattended, that polling loop is brittle — a mis-timed check or a slow confirmation stalls the whole workflow. ```python theme={null} # What builders write by hand — and shouldn't have to balance = payments.plans.get_plan_balance(plan_id) if balance.balance <= 0: payments.plans.order_plan(plan_id) time.sleep(5) # hope the on-chain order confirmed by now token_res = payments.x402.get_x402_access_token(plan_id, agent_id) ``` ## How top-ups work The key idea: **generating the access token doesn't buy anything — it authorizes a future top-up.** The purchase happens later, at settlement, and only if it's actually needed. 1. **Authorize once.** You create a delegation once and reference it by `delegationId` when generating the access token (`getX402AccessToken` / `get_x402_access_token`). This mints a signed token that lets the facilitator spend on the subscriber's behalf, up to the delegation's limit. No credits are bought at this point. 2. **Spend normally.** The agent sends the token in the `payment-signature` header on each paid request. 3. **Top up at settlement.** When the facilitator settles a request, it checks the subscriber's credit balance. If there are enough credits, it simply burns them. If there aren't, it **tops up first** — buying exactly the credits the request needs — then settles. * **Crypto (`nvm:erc4337`):** the facilitator executes an on-chain `order` against the subscriber's smart account to mint credits. * **Fiat (`nvm:card-delegation`):** the facilitator charges the enrolled card off-session to mint credits. 4. **Stay within the limit.** Every top-up counts against the delegation's `spendingLimitCents`. Once that budget is exhausted or the delegation expires, top-ups stop and the request fails with a `402`. > [!NOTE] > > The top-up fires at **settlement**, not when you call `getX402AccessToken`. Generating the token only pre-authorizes the spend — no money moves until the agent consumes a paid request and the balance comes up short. ## Manual flow vs. top-ups The difference is that the `orderPlan` / `order_plan` loop disappears: * **Without a delegation**, you babysit the balance — check it, order more credits when it's low, wait for the order to confirm, then make your request (the snippet above). * **With a delegation**, you authorize spending once (see below) and just make requests. There's no balance check and no explicit order: if credits run short when a request settles, the facilitator tops up automatically, within the delegation's limit. ## Set up the delegation A delegation authorizes the facilitator to spend on the subscriber's behalf. Create it once with `createDelegation` / `create_delegation`, then reference it by `delegationId` when you generate access tokens — spending is tracked cumulatively against the same limit: > [tab] TypeScript > > ```typescript theme={null} > // Create the delegation once > const delegation = await payments.delegation.createDelegation({ > provider: 'erc4337', > spendingLimitCents: 50000, // $500 total budget > durationSecs: 2592000, // 30 days > currency: 'usdc', // 'usdc' for crypto (erc4337), 'usd' for card providers > }) > > // Reference it by id on every request > const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, { > delegationConfig: { delegationId: delegation.delegationId }, > }) > ``` > [tab] Python > > ```python theme={null} > from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload > > # Create the delegation once > delegation = payments.delegation.create_delegation( > CreateDelegationPayload( > provider="erc4337", > spending_limit_cents=50000, # $500 total budget > duration_secs=2592000, # 30 days > currency="usdc", # 'usdc' for crypto (erc4337), 'usd' for card providers > ) > ) > > # Reference it by id on every request > token_res = payments.x402.get_x402_access_token( > plan_id, > agent_id, > token_options=X402TokenOptions( > delegation_config=DelegationConfig(delegation_id=delegation.delegation_id) > ), > ) > access_token = token_res["accessToken"] > ``` The two fields that scope a delegation: | Field | Description | | - | - | | `spendingLimitCents` | Total spending cap for the delegation's lifetime, in cents. `10000` = \$100. | | `durationSecs` | How long the delegation stays valid, in seconds. `604800` = 7 days. | `provider` and `currency` are required — there's no silent default. Delegations are plan-agnostic by default; pass `planId` on `createDelegation` only to bind one to a single plan. > [!WARNING] > > Passing creation fields (`spendingLimitCents`, `durationSecs`, `currency`, …) inline in `delegationConfig` instead of a `delegationId` still works but is **deprecated** and emits a runtime warning. Create the delegation first and pass only `{ delegationId }`. > [!TIP] > > Run this in `sandbox` first. A delegation grants pre-authorized spending up to `spendingLimitCents` for `durationSecs` — start with a small budget (for example `100` cents over `3600` seconds) and raise it per use case after review. ## Crypto vs. fiat Top-ups work the same way from your code regardless of how the plan is paid for — only the settlement mechanism differs: | Scheme | How a top-up settles | What bounds it | | - | - | - | | `nvm:erc4337` (crypto) | On-chain `order` against the subscriber's smart account, funded from their wallet | `spendingLimitCents` and the wallet's token balance | | `nvm:card-delegation` (fiat) | Off-session card charge through the configured provider (Stripe, Braintree, or Visa) | `spendingLimitCents` on the card delegation | For card-delegation plans the top-up is built in: there's no extra parameter to pass — enroll a card, set its spending limit, and the facilitator charges it when a request would otherwise run dry. See [Fiat Payments](/docs/integrate/patterns/fiat-payments) for card enrollment. ## When top-ups stop A top-up only happens while the delegation authorizes it **and** the funding source can cover it. The two kinds of failure surface differently: | Condition | Result | | - | - | | `spendingLimitCents` exhausted | The delegation can't authorize the spend → **`402`** (`BCK.X402.0005`). | | Delegation expired (`durationSecs` elapsed) | The delegation is no longer valid → **`402`** (`BCK.X402.0005`). | | Wallet has insufficient token balance (crypto) | The on-chain `order` reverts → server-side **`500`** (`BCK.X402.0008`, "Failed to order crypto plan"). | | Card declined (fiat) | The off-session charge fails → server-side **`500`** (`BCK.X402.0009`, "Failed to redeem credits"). | A `402` means the delegation itself is the blocker — create a fresh delegation with new limits to resume. A `500` means the delegation was valid but the underlying payment couldn't execute: top up the wallet (crypto) or fix the card (fiat). > [!WARNING] > > In A2A pipelines, branch on the error `code`, not just the HTTP status. A declined card or an under-funded wallet surfaces as a server-side `500` — not a `402` — so don't treat every failure as an exhausted delegation, and don't retry indefinitely. ## Next steps > [card] [Stablecoin Payments](/docs/integrate/patterns/stablecoin-payments) > > How crypto delegations and on-chain settlement work. > [card] [Fiat Payments](/docs/integrate/patterns/fiat-payments) > > Enroll a card and pay per request via Stripe, Braintree, or Visa. > [card] [Nevermined x402](/docs/development-guide/nevermined-x402) > > The x402 protocol, access tokens, and the settlement flow in depth. > [card] [Agent-to-Agent Monetization](/docs/solutions/agent-to-agent-monetization) > > Build autonomous agent pipelines with built-in payment rails. # Validate Requests Source: https://nevermined.ai/docs/integrate/patterns/validate-requests Patterns for validating payment tokens in your API, agent, or protected resource Copy-paste patterns for validating payment requests for APIs, agents/tools, and protected resources. > [!NOTE] > > Looking for framework-specific implementations? > > * [Express.js Integration](/docs/integrate/add-to-your-agent/express) > * [FastAPI Integration](/docs/integrate/add-to-your-agent/fastapi) > * [Generic HTTP Integration](/docs/integrate/add-to-your-agent/generic-http) ## Basic validation (framework-agnostic) At a minimum, validation has three steps: 1. Extract x402 token from the `payment-signature` header 2. Verify permissions using the facilitator 3. Return `402 Payment Required` when missing/invalid > [tab] TypeScript > > ```typescript theme={null} > import { Payments, buildPaymentRequired } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox' > }) > > export async function validateRequest( > x402Token: string, > planId: string, > agentId: string, > endpoint: string, > httpVerb: string > ) { > // Build payment requirements > const paymentRequired = buildPaymentRequired({ > planId, > endpoint, > agentId, > httpVerb > }) > > // Verify permissions > const verification = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount: BigInt(1) > }) > > return { > isValid: verification.isValid, > balance: verification.balance, > subscriberAddress: verification.subscriberAddress > } > } > > // Pseudo-usage > // - Extract token from payment-signature header > // - Call validateRequest(token, planId, agentId, endpoint, httpVerb) > // - If invalid, return 402 > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments, PaymentOptions > from payments_py.x402.helpers import build_payment_required > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox') > ) > > def validate_request( > x402_token: str, > plan_id: str, > agent_id: str, > endpoint: str, > http_verb: str > ) -> dict: > # Build payment requirements > payment_required = build_payment_required( > plan_id=plan_id, > endpoint=endpoint, > agent_id=agent_id, > http_verb=http_verb > ) > > # Verify permissions > verification = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount="1" > ) > > return { > 'is_valid': verification.is_valid, > 'balance': verification.balance, > 'subscriber_address': verification.subscriber_address > } > > # Pseudo-usage: > # - Extract token from payment-signature header > # - Call validate_request(token, plan_id, agent_id, endpoint, http_verb) > # - If invalid, return 402 > ``` ## Validation with minimum credits Check that the user has enough credits for the operation: > [tab] TypeScript > > ```typescript theme={null} > import { buildPaymentRequired } from '@nevermined-io/payments' > > export async function validateWithMinimum( > x402Token: string, > planId: string, > agentId: string, > endpoint: string, > minCredits: number > ) { > const paymentRequired = buildPaymentRequired({ > planId, endpoint, agentId, httpVerb: 'POST' > }) > > const result = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount: BigInt(minCredits) > }) > > if (!result.isValid) { > return { valid: false, reason: 'invalid_token' as const } > } > > if (result.balance < minCredits) { > return { > valid: false, > reason: 'insufficient_credits' as const, > required: minCredits, > available: result.balance > } > } > > return { valid: true, balance: result.balance } > } > > // Example: expensive operation requiring 10 credits > const validation = await validateWithMinimum(token, PLAN_ID, AGENT_ID, '/query', 10) > if (!validation.valid) { > // return 402 > } > ``` > [tab] Python > > ```python theme={null} > from payments_py.x402.helpers import build_payment_required > > async def validate_with_minimum( > x402_token: str, > plan_id: str, > agent_id: str, > endpoint: str, > min_credits: int > ) -> dict: > payment_required = build_payment_required( > plan_id=plan_id, endpoint=endpoint, > agent_id=agent_id, http_verb="POST" > ) > > result = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount=str(min_credits) > ) > > if not result.is_valid: > return {'valid': False, 'reason': 'invalid_token'} > > if result.balance < min_credits: > return { > 'valid': False, > 'reason': 'insufficient_credits', > 'required': min_credits, > 'available': result.balance > } > > return {'valid': True, 'balance': result.balance} > > # Example: expensive operation requiring 10 credits > validation = await validate_with_minimum(token, PLAN_ID, AGENT_ID, "/query", 10) > if not validation['valid']: > # return 402 > pass > ``` ## Validation response handling Handle all possible validation outcomes: > [tab] TypeScript > > ```typescript theme={null} > async function handleValidation( > x402Token: string, > paymentRequired: string, > maxAmount: bigint > ) { > try { > const result = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount > }) > > if (!result.isValid) { > // Determine specific error > switch (result.reason) { > case 'TOKEN_EXPIRED': > return { > status: 402, > error: 'Access token has expired', > code: 'TOKEN_EXPIRED', > action: 'refresh_token' > } > > case 'INSUFFICIENT_BALANCE': > return { > status: 402, > error: 'Insufficient credits', > code: 'INSUFFICIENT_BALANCE', > action: 'purchase_credits' > } > > case 'PLAN_EXPIRED': > return { > status: 402, > error: 'Plan has expired', > code: 'PLAN_EXPIRED', > action: 'renew_plan' > } > > default: > return { > status: 402, > error: 'Invalid token', > code: 'INVALID_TOKEN', > action: 'get_new_token' > } > } > } > > return { status: 200, balance: result.balance } > } catch (error) { > console.error('Validation error:', error) > return { > status: 500, > error: 'Validation service unavailable', > code: 'SERVICE_ERROR' > } > } > } > ``` > [tab] Python > > ```python theme={null} > async def handle_validation( > x402_token: str, > payment_required: str, > max_amount: str > ) -> dict: > try: > result = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount=max_amount > ) > > if not result.is_valid: > reason = getattr(result, 'reason', 'UNKNOWN') > > error_map = { > 'TOKEN_EXPIRED': { > 'status': 402, > 'error': 'Access token has expired', > 'code': 'TOKEN_EXPIRED', > 'action': 'refresh_token' > }, > 'INSUFFICIENT_BALANCE': { > 'status': 402, > 'error': 'Insufficient credits', > 'code': 'INSUFFICIENT_BALANCE', > 'action': 'purchase_credits' > }, > 'PLAN_EXPIRED': { > 'status': 402, > 'error': 'Plan has expired', > 'code': 'PLAN_EXPIRED', > 'action': 'renew_plan' > } > } > > return error_map.get(reason, { > 'status': 402, > 'error': 'Invalid token', > 'code': 'INVALID_TOKEN', > 'action': 'get_new_token' > }) > > return {'status': 200, 'balance': result.balance} > > except Exception as e: > print(f'Validation error: {e}') > return { > 'status': 500, > 'error': 'Validation service unavailable', > 'code': 'SERVICE_ERROR' > } > ``` ## Caching validation results For high-traffic endpoints, cache validation briefly: > [tab] TypeScript > > ```typescript theme={null} > import { LRUCache } from 'lru-cache' > > const validationCache = new LRUCache({ > max: 1000, > ttl: 1000 * 30 // 30 seconds > }) > > async function validateWithCache( > x402Token: string, > paymentRequired: string, > maxAmount: bigint > ) { > // Create cache key from token hash > const cacheKey = hashToken(x402Token) > const cached = validationCache.get(cacheKey) > > if (cached) { > return cached > } > > const result = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount > }) > > if (result.isValid) { > validationCache.set(cacheKey, result) > } > > return result > } > > function hashToken(token: string): string { > return crypto.createHash('sha256').update(token).digest('hex').slice(0, 16) > } > ``` > [tab] Python > > ```python theme={null} > from datetime import datetime, timedelta > import hashlib > > validation_cache = {} > CACHE_TTL = timedelta(seconds=30) > > async def validate_with_cache( > x402_token: str, > payment_required: str, > max_amount: str > ) -> dict: > cache_key = hash_token(x402_token) > > # Check cache > if cache_key in validation_cache: > cached, timestamp = validation_cache[cache_key] > if datetime.now() - timestamp < CACHE_TTL: > return cached > > result = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount=max_amount > ) > > if result.is_valid: > validation_cache[cache_key] = (result, datetime.now()) > > return result > > def hash_token(token: str) -> str: > return hashlib.sha256(token.encode()).hexdigest()[:16] > ``` ## Next steps > [card] [Charge Credits](/docs/integrate/patterns/charge-credits) > > Deduct credits for requests > [card] [Subscription Access](/docs/integrate/patterns/subscription-access) > > Time-based access patterns # 5-Minute Setup Source: https://nevermined.ai/docs/integrate/quickstart/5-minute-setup Get a paid endpoint working in 5 minutes (agent API, MCP tool, or protected resource) This guide gets you from zero to a working payment integration in 5 minutes. By the end, you’ll have a **monetizable service** set up with Nevermined — typically an **agent API**, but the same flow applies to **MCP tools/servers** and **protected assets**. > In the code below we use “agent” terminology because it maps to the underlying object model, but you can think of it as *the service/resource you’re charging for*. ## Prerequisites **1. Get Your API Key** Open [nevermined.app](https://nevermined.app), sign in, then go to **Settings > Global NVM API Keys** and click **+ New API Key**. Copy the key and set it as an environment variable: ```bash theme={null} export NVM_API_KEY="sandbox:your-api-key-here" ``` > [!TIP] > > Keys are environment-specific — the prefix matches the SDK `environment` value you must pass at init. > > | Key prefix | SDK `environment` | Backend | > | - | - | - | > | `sandbox:` | `sandbox` | `https://api.sandbox.nevermined.app` | > | `live:` | `live` | `https://api.live.nevermined.app` | > > Use `sandbox` for testing and `live` for production. If you see auth errors that look unrelated to the key, double-check that prefix and `environment` match — a `sandbox:` key against `environment: 'live'` lands at the wrong backend and fails with confusing 4xx errors. **2. Install the SDK** > [tab] TypeScript > > ```bash theme={null} > npm install @nevermined-io/payments > ``` > [tab] Python > > ```bash theme={null} > pip install payments-py > ``` ## Register Your Agent Create a script to register your agent and a payment plan. > [!NOTE] > > You can register your agent and any payment plan using the following code OR using the [Nevermined App](https://nevermined.app). No need to code this — just follow the steps in the app to create your agents and plans. If you’re monetizing an agent, MCP tool/server or a protected resource, you’ll still register the monetizable unit and attach a plan — only the **delivery step** changes. > [tab] TypeScript > > ```typescript filename="register-agent.ts" theme={null} > import { Payments } from '@nevermined-io/payments' > > // In this example we require a payment of 10 USDC for 100 requests > // For that USDC payment we use USDC on Base Sepolia, so we need its contract address: > const USDC_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' > > async function main() { > // 1. Initialize the SDK > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox' > }) > > // 2. Register service + payment plan ("agent" in the SDK) > const { agentId, planId } = await payments.agents.registerAgentAndPlan( > // Service metadata > { > name: 'My AI Assistant', > description: 'A paid service (agent API / MCP tool / protected resource)', > tags: ['ai', 'payments'], > dateCreated: new Date() > }, > // Service interface - replace with your endpoint > { > endpoints: [{ POST: 'https://your-api.com/query' }] > }, > // Plan metadata > { > name: 'Starter Plan', > description: '100 requests for $10', > dateCreated: new Date() > }, > // Price: 10 USDC > payments.plans.getERC20PriceConfig( > 10_000_000n, // 10 USDC (6 decimals) > USDC_ADDRESS, > process.env.BUILDER_ADDRESS! // Your wallet address > ), > // Credits: 100 requests, 1 credit each > payments.plans.getFixedCreditsConfig(100n, 1n) > ) > > console.log('Registered!') > console.log(`Service (agent) ID: ${agentId}`) > console.log(`Plan ID: ${planId}`) > console.log('\nSave these IDs for your integration.') > } > > main().catch(console.error) > ``` > [tab] Python > > ```python filename="register_agent.py" theme={null} > import os > from payments_py import Payments, PaymentOptions > from payments_py.plans import get_erc20_price_config, get_fixed_credits_config > > # In this example we require a payment of 10 USDC for 100 requests > # For that USDC payment we use USDC on Base Sepolia, so we need its contract address: > USDC_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' > > def main(): > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ['NVM_API_KEY'], > environment='sandbox' > ) > ) > > result = payments.agents.register_agent_and_plan( > agent_metadata={ > 'name': 'My AI Assistant', > 'description': 'A paid service (agent API / MCP tool / protected resource)', > 'tags': ['ai', 'payments'] > }, > agent_api={ > 'endpoints': [{'verb': 'POST', 'url': 'https://your-api.com/query'}] > }, > plan_metadata={ > 'name': 'Starter Plan', > 'description': '100 requests for $10' > }, > price_config=get_erc20_price_config( > 10_000_000, # 10 USDC (6 decimals) > USDC_ADDRESS, > os.environ['BUILDER_ADDRESS'] > ), > credits_config=get_fixed_credits_config(100, 1), > access_limit='credits' > ) > > print('Registered!') > print(f"Service (agent) ID: {result['agentId']}") > print(f"Plan ID: {result['planId']}") > print('\nSave these IDs for your integration.') > > if __name__ == '__main__': > main() > ``` Run it: > [tab] TypeScript > > ```bash theme={null} > npx ts-node register-agent.ts > ``` > [tab] Python > > ```bash theme={null} > python register_agent.py > ``` ## Add Payment Validation in the Agent Add this middleware to your agent to validate if a request is valid (have a payment attached) before delivering your response/resource. The example shows an HTTP API route; the same check can be used before calling an MCP tool handler or before serving a protected asset: > [tab] TypeScript > > ```typescript filename="middleware/payments.ts" theme={null} > import { Payments, buildPaymentRequired } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox', > }) > > const PLAN_ID = process.env.NVM_PLAN_ID! > const AGENT_ID = process.env.NVM_AGENT_ID! > > // Build payment required specification > const paymentRequired = buildPaymentRequired(PLAN_ID, { > endpoint: req.url, > agentId: AGENT_ID, > httpVerb: req.method, > }) > > // Get token from payment-signature header > const x402Token = req.headers['payment-signature'] as string > > if (!x402Token) { > // Return 402 with payment-required header so clients know how to pay > const paymentRequiredBase64 = Buffer.from( > JSON.stringify(paymentRequired) > ).toString('base64') > > return res > .status(402) > .setHeader('payment-required', paymentRequiredBase64) > .json({ error: 'Payment Required' }) > } > > // 1. Verify permissions (does NOT burn credits) > const verification = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount: 1n, > }) > > if (!verification.isValid) { > return res.status(402).json({ error: verification.invalidReason }) > } > > // 2. Execute your logic here — payment is verified > const result = await handleRequest(req) > > // 3. Settle (burn credits) after successful processing > await payments.facilitator.settlePermissions({ > paymentRequired, > x402AccessToken: x402Token, > maxAmount: 1n, > }) > > return res.json({ result }) > ``` > [tab] Python > > ```python filename="middleware/payments.py" theme={null} > import base64 > import os > from payments_py import Payments, PaymentOptions > from payments_py.x402.helpers import build_payment_required > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ["NVM_API_KEY"], environment="sandbox") > ) > > PLAN_ID = os.environ["NVM_PLAN_ID"] > AGENT_ID = os.environ["NVM_AGENT_ID"] > > # Build payment required specification > payment_required = build_payment_required( > plan_id=PLAN_ID, > endpoint=request.url, > agent_id=AGENT_ID, > http_verb=request.method > ) > > # Get token from payment-signature header > x402_token = request.headers.get("payment-signature") > > if not x402_token: > # Return 402 with payment-required header so clients know how to pay > pr_base64 = base64.b64encode( > payment_required.model_dump_json(by_alias=True).encode() > ).decode() > return JSONResponse( > status_code=402, > content={"error": "Payment Required"}, > headers={"payment-required": pr_base64} > ) > > # 1. Verify permissions (does NOT burn credits) > verification = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount="1", > ) > > if not verification.is_valid: > return JSONResponse( > status_code=402, > content={"error": verification.invalid_reason} > ) > > # 2. Execute your logic here — payment is verified > result = handle_request(request) > > # 3. Settle (burn credits) after successful processing > payments.facilitator.settle_permissions( > payment_required=payment_required, > x402_access_token=x402_token, > max_amount="1", > ) > > return {"result": result} > ``` ## Integrate the validation code in your agent/server Integrate the above validation code into your agent/server code at the very beginning of your request handling logic. The payment validation should occur before any processing of the request and can be complemented by any other authorization logic you may have. ## Test It **1) Try without payment (should fail)** ```bash theme={null} curl -X POST http://localhost:3000/query \ -H "Content-Type: application/json" \ -d '{"prompt": "Hello"}' ``` Response: ```json theme={null} { "error": "Payment Required", "message": "Purchase a plan to access this API", "plans": [{"planId": "did:nv:...", "agentId": "did:nv:..."}] } ``` **2) Purchase a plan and get an access token** > [tab] TypeScript > > ```typescript theme={null} > // As a subscriber > const payments = Payments.getInstance({ nvmApiKey: subscriberKey, environment: 'sandbox' }) > > // Order the plan > await payments.plans.orderPlan(PLAN_ID) > > // Get your balance about the plan you just ordered > const balance = await payments.plans.getPlanBalance(PLAN_ID) > > // Create a delegation first (provider + currency required; 'usdc' for > // erc4337), then request the token by its delegationId. `delegationConfig` > // is required for both crypto and fiat plans — omitting it surfaces > // BCK.X402.0030 at runtime. > const delegation = await payments.delegation.createDelegation({ > provider: 'erc4337', > spendingLimitCents: 1000, // $10 cap > durationSecs: 86_400, // 1 day > currency: 'usdc', > }) > const { accessToken } = await payments.x402.getX402AccessToken(PLAN_ID, AGENT_ID, { > scheme: 'nvm:erc4337', > delegationConfig: { delegationId: delegation.delegationId }, > }) > > // Use this token in the next request > // HTTP header: 'payment-signature' > // value: `${accessToken}` > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments, PaymentOptions > from payments_py.x402 import ( > CreateDelegationPayload, > DelegationConfig, > X402TokenOptions, > ) > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox') > ) > > # Order the plan > order_result = payments.plans.order_plan(plan_id) > > # Get your balance about the plan you just ordered > balance = payments.plans.get_plan_balance(plan_id) > > # Create a delegation first (provider + currency required), then request > # the token by its delegation_id. > delegation = payments.delegation.create_delegation( > CreateDelegationPayload( > provider='erc4337', > spending_limit_cents=1000, > duration_secs=86_400, > currency='usdc', > ) > ) > token_res = payments.x402.get_x402_access_token( > plan_id, > agent_id, > token_options=X402TokenOptions( > scheme='nvm:erc4337', > delegation_config=DelegationConfig( > delegation_id=delegation.delegation_id, > ), > ), > ) > access_token = token_res['accessToken'] > ``` **3) Query with payment** ```bash theme={null} curl -X POST http://localhost:3000/query \ -H "Content-Type: application/json" \ -H "payment-signature: ${accessToken}" \ -d '{"prompt": "Hello"}' ``` Response: ```json theme={null} { "result": "Hello! How can I help you today?", "creditsRemaining": 99 } ``` > [!TIP] > > Want subscribers to pay with a regular credit card instead of stablecoins? [Card delegation](/docs/products/payments/overview) lets subscribers enroll a Visa, Stripe, or Braintree card and create spending delegations that agents charge directly. ## What's Next? > [card] [Express Integration](/docs/integrate/add-to-your-agent/express) > > Complete Express.js integration guide > [card] [FastAPI Integration](/docs/integrate/add-to-your-agent/fastapi) > > Complete FastAPI integration guide > [card] [Payment Patterns](/docs/integrate/patterns/validate-requests) > > Advanced validation and charging patterns > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Implement HTTP 402 payment flows # Python Quick Start Source: https://nevermined.ai/docs/integrate/quickstart/python Get started with Nevermined payments in Python > [!NOTE] > > **Start here:** need to register a service and create a plan first or get your Nevermined API Key? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). Complete Python quick start for adding payments to your AI agent or service. ## Installation ```bash theme={null} pip install payments-py fastapi uvicorn ``` ## Environment Setup ```bash theme={null} # Your Nevermined API key (see: /docs/agents-guide/get-api-key) export NVM_API_KEY="sandbox:your-api-key" # Your wallet address to receive payments export BUILDER_ADDRESS="0xYourWalletAddress" # After registration, set these export AGENT_ID="did:nv:your-agent-id" export PLAN_ID="did:nv:your-plan-id" ``` ## Complete Example ```python filename="main.py" theme={null} import os from fastapi import FastAPI, Request, HTTPException, Depends from pydantic import BaseModel from payments_py import Payments, PaymentOptions from payments_py.plans import get_erc20_price_config, get_fixed_credits_config app = FastAPI(title="My AI Agent") # In this example we require a payment of 10 USDC for 100 requests # For that USDC payment we use USDC on Base Sepolia, so we need its contract address: USDC_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' # Initialize payments payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox' ) ) # Store IDs after registration agent_id = os.environ.get('AGENT_ID', '') plan_id = os.environ.get('PLAN_ID', '') # ============================================ # MODELS # ============================================ class QueryRequest(BaseModel): prompt: str class QueryResponse(BaseModel): result: str credits_remaining: int # ============================================ # SETUP: Run once to register your agent # ============================================ @app.post("/setup") async def register_agent(): global agent_id, plan_id result = payments.agents.register_agent_and_plan( agent_metadata={ 'name': 'My Python AI Agent', 'description': 'AI assistant built with Python', 'tags': ['ai', 'python'] }, agent_api={ 'endpoints': [{'verb': 'POST', 'url': 'http://localhost:8000/query'}] }, plan_metadata={ 'name': 'Starter Plan', 'description': '100 queries' }, price_config=get_erc20_price_config( 10_000_000, # 10 USDC USDC_ADDRESS, os.environ['BUILDER_ADDRESS'] ), credits_config=get_fixed_credits_config(100, 1), access_limit='credits' ) agent_id = result['agentId'] plan_id = result['planId'] return { 'agent_id': agent_id, 'plan_id': plan_id, 'message': 'Add these to your .env file!' } # ============================================ # MIDDLEWARE: Validate payments # ============================================ async def validate_payment(request: Request) -> int: """Validate payment and return remaining credits.""" from payments_py.x402.helpers import build_payment_required x402_token = request.headers.get("payment-signature") if not x402_token: raise HTTPException(status_code=402, detail="Payment required") # Build payment requirements payment_required = build_payment_required( plan_id=plan_id, endpoint=str(request.url), agent_id=agent_id, http_verb=request.method ) # Verify permissions verification = payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=x402_token, max_amount="1" ) if not verification.get("is_valid"): raise HTTPException(status_code=402, detail="Invalid payment") return verification.get("remaining_credits", 0) # ============================================ # ROUTES # ============================================ @app.get("/health") async def health(): """Health check (public).""" return { 'status': 'ok', 'agent_id': agent_id, 'plan_id': plan_id } @app.post("/query", response_model=QueryResponse) async def query( request: QueryRequest, credits: int = Depends(validate_payment) ): """Protected AI endpoint.""" # Your AI logic here result = f'You asked: "{request.prompt}". Here\'s my response...' return QueryResponse( result=result, credits_remaining=credits ) # ============================================ # MAIN # ============================================ if __name__ == '__main__': import uvicorn print(f"Agent ID: {agent_id or 'Not registered'}") print(f"Plan ID: {plan_id or 'Not registered'}") if not agent_id or not plan_id: print("No agent registered yet. POST to /setup to register.") uvicorn.run(app, host='0.0.0.0', port=8000) ``` ## Run the Example ```bash theme={null} # Run the server python main.py # Or with uvicorn directly uvicorn main:app --reload --port 8000 ``` ## Test the Flow **1) Register your agent (first time only)** ```bash theme={null} curl -X POST http://localhost:8000/setup ``` Save the returned `agent_id` and `plan_id` to your environment. **2) Try without payment** ```bash theme={null} curl -X POST http://localhost:8000/query \ -H "Content-Type: application/json" \ -d '{"prompt": "Hello"}' ``` **3) As a subscriber, purchase and query** ```python filename="subscriber.py" theme={null} import os import requests from payments_py import Payments, PaymentOptions from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ['SUBSCRIBER_API_KEY'], environment='sandbox' ) ) def purchase_and_query(): plan_id = os.environ['PLAN_ID'] agent_id = os.environ['AGENT_ID'] # 1. Order the plan (buys credits up front) print('Purchasing plan...') order_result = payments.plans.order_plan(plan_id) # 2. Get access token print('Getting access token...') # Create the delegation first (provider + currency required), then request # the token by its delegationId. Reuse the delegation for later requests. delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="erc4337", # "stripe" | "braintree" | "visa" for fiat plans spending_limit_cents=1000, duration_secs=86_400, currency="usdc", # "usd" for fiat plans ) ) token_res = payments.x402.get_x402_access_token( plan_id, agent_id, token_options=X402TokenOptions( scheme="nvm:erc4337", delegation_config=DelegationConfig(delegation_id=delegation.delegation_id), ), ) access_token = token_res['accessToken'] # 3. Query the agent print('Querying agent...') response = requests.post( 'http://localhost:8000/query', headers={ 'Content-Type': 'application/json', 'payment-signature': f'{access_token}' }, json={'prompt': 'What is 2+2?'} ) result = response.json() print(f'Result: {result}') if __name__ == '__main__': purchase_and_query() ``` > [!TIP] > > For agents that run continuously, set up a delegation when generating the access token — the facilitator tops up credits automatically when the balance runs out, with no manual `order_plan()` loop needed. See [Automatic Credit Top-Ups](/docs/integrate/patterns/top-up). ## Flask Alternative ```python filename="flask_app.py" theme={null} import os from flask import Flask, request, jsonify from functools import wraps from payments_py import Payments, PaymentOptions from payments_py.plans import get_erc20_price_config, get_fixed_credits_config app = Flask(__name__) USDC_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox' ) ) agent_id = os.environ.get('AGENT_ID', '') plan_id = os.environ.get('PLAN_ID', '') def require_payment(f): """Decorator to validate payment.""" from payments_py.x402.helpers import build_payment_required @wraps(f) def decorated(*args, **kwargs): x402_token = request.headers.get("payment-signature") if not x402_token: return {"error": "Payment Required"}, 402 # Get request body for validation (Flask synchronous method) body = request.get_json() # Build payment requirements payment_required = build_payment_required( plan_id=plan_id, endpoint=request.url, agent_id=agent_id, http_verb=request.method ) # Verify permissions verification = payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=x402_token, max_amount="1" ) if not verification.get("is_valid"): return {"error": "Invalid payment"}, 402 # Get balance balance = payments.plans.get_plan_balance(plan_id) # Pass credits to the handler kwargs['credits'] = balance.get('balance', 0) return f(*args, **kwargs) return decorated @app.route('/health') def health(): return jsonify({'status': 'ok', 'agent_id': agent_id, 'plan_id': plan_id}) @app.route('/query', methods=['POST']) @require_payment def query(credits=0): prompt = request.json.get('prompt', '') # Your AI logic here result = f'You asked: "{prompt}". Here\'s my response...' return jsonify({ 'result': result, 'credits_remaining': credits }) if __name__ == '__main__': app.run(port=8000, debug=True) ``` ## Project Structure ``` my-ai-agent/ ├── main.py # FastAPI server ├── requirements.txt ├── .env └── src/ ├── middleware/ │ └── payments.py # Payment validation ├── routes/ │ └── query.py # AI endpoints └── services/ └── ai.py # Your AI logic ``` ## Requirements File ```text filename="requirements.txt" theme={null} payments-py>=1.0.0 fastapi>=0.100.0 uvicorn>=0.23.0 python-dotenv>=1.0.0 ``` ## Next Steps > [card] [FastAPI Integration](/docs/integrate/add-to-your-agent/fastapi) > > Complete FastAPI patterns and best practices > [card] [Python SDK Reference](/docs/api-reference/python/installation) > > Full API documentation > [card] [Payment Patterns](/docs/integrate/patterns/validate-requests) > > Advanced patterns for production > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Implement HTTP 402 payment flows # TypeScript Quick Start Source: https://nevermined.ai/docs/integrate/quickstart/typescript Get started with Nevermined payments in TypeScript/Node.js > [!NOTE] > > **Start here:** need to register a service and create a plan first or get your Nevermined API Key? Follow the > [5-minute setup](/docs/integrate/quickstart/5-minute-setup). Complete TypeScript quick start for adding payments to your AI agent or service. ## Installation ```bash theme={null} npm install @nevermined-io/payments ``` ## Environment Setup ```bash theme={null} # Your Nevermined API key (see: /docs/agents-guide/get-api-key) export NVM_API_KEY="sandbox:your-api-key" # Your wallet address to receive payments export BUILDER_ADDRESS="0xYourWalletAddress" # After registration, set these export AGENT_ID="did:nv:your-agent-id" export PLAN_ID="did:nv:your-plan-id" ``` ## Complete Example ```typescript filename="index.ts" theme={null} import express from 'express' import { Payments, buildPaymentRequired } from '@nevermined-io/payments' const app = express() app.use(express.json()) // In this example we require a payment of 10 USDC for 100 requests // For that USDC payment we use USDC on Base Sepolia, so we need its contract address: const USDC_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' // Initialize payments const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' // or 'live' }) // Store IDs after registration let agentId: string let planId: string // ============================================ // SETUP: Run once to register your agent // ============================================ async function registerAgent() { const result = await payments.agents.registerAgentAndPlan( { name: 'My TypeScript AI Agent', description: 'AI assistant built with TypeScript', tags: ['ai', 'typescript'], dateCreated: new Date() }, { endpoints: [{ POST: `http://localhost:3000/query` }] }, { name: 'Starter Plan', description: '100 queries', dateCreated: new Date() }, payments.plans.getERC20PriceConfig(10_000_000n, USDC_ADDRESS, process.env.BUILDER_ADDRESS!), payments.plans.getFixedCreditsConfig(100n, 1n) ) agentId = result.agentId planId = result.planId console.log(`Agent ID: ${agentId}`) console.log(`Plan ID: ${planId}`) console.log('Add these to your .env file!') return result } // ============================================ // MIDDLEWARE: Validate payments // ============================================ async function validatePayment( req: express.Request, res: express.Response, next: express.NextFunction ) { // Get token from payment-signature header const x402Token = req.headers['payment-signature'] if (!x402Token) { // Return 402 with payment requirements return res.status(402).json({ error: 'Payment Required' }) } // Build payment required specification const paymentRequired = buildPaymentRequired(planId, { endpoint: req.url, agentId: agentId, httpVerb: req.method, }) // Verify permissions - facilitator extracts planId and subscriberAddress from token const verification = await payments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: x402Token, maxAmount: 1n, }) if (!verification.isValid) { return res.status(402).json({ error: 'Payment verification failed' }) } const balance = await payments.plans.getPlanBalance(planId) // Attach balance to request ;(req as any).credits = balance next() } // ============================================ // ROUTES // ============================================ // Health check (public) app.get('/health', (req, res) => { res.json({ status: 'ok', agentId, planId }) }) // Protected AI endpoint app.post('/query', validatePayment, async (req, res) => { const { prompt } = req.body // Your AI logic here const result = `You asked: "${prompt}". Here's my response...` res.json({ result, creditsRemaining: (req as any).credits }) }) // Setup endpoint (call once) app.post('/setup', async (req, res) => { try { const result = await registerAgent() res.json(result) } catch (error: any) { res.status(500).json({ error: error.message }) } }) // ============================================ // START SERVER // ============================================ const PORT = process.env.PORT || 3000 app.listen(PORT, () => { // Load IDs from environment if available agentId = process.env.AGENT_ID || '' planId = process.env.PLAN_ID || '' console.log(`Server running on http://localhost:${PORT}`) if (!agentId || !planId) { console.log('No agent registered yet. POST to /setup to register.') } else { console.log(`Agent: ${agentId}`) console.log(`Plan: ${planId}`) } }) ``` ## Run the Example ```bash theme={null} # Install dependencies npm install express @nevermined-io/payments # Run in development npx ts-node index.ts ``` ## Test the Flow **1) Register your agent (first time only)** ```bash theme={null} curl -X POST http://localhost:3000/setup ``` Save the returned `agentId` and `planId` to your environment. **2) Try without payment** ```bash theme={null} curl -X POST http://localhost:3000/query \ -H "Content-Type: application/json" \ -d '{"prompt": "Hello"}' ``` **3) As a subscriber, purchase and query** ```typescript theme={null} // subscriber.ts import { Payments } from '@nevermined-io/payments' const payments = Payments.getInstance({ nvmApiKey: process.env.SUBSCRIBER_API_KEY!, environment: 'sandbox' }) async function purchaseAndQuery() { // 1. Order the plan (buys credits up front) console.log('Purchasing plan...') await payments.plans.orderPlan(process.env.PLAN_ID!) // 2. Get access token console.log('Getting access token...') // Create the delegation first (provider + currency required), then request // the token by its delegationId. Reuse the delegation for later requests. const delegation = await payments.delegation.createDelegation({ provider: 'erc4337', spendingLimitCents: 1000, durationSecs: 86_400, currency: 'usdc', }) const { accessToken } = await payments.x402.getX402AccessToken( process.env.PLAN_ID!, process.env.AGENT_ID!, { scheme: 'nvm:erc4337', delegationConfig: { delegationId: delegation.delegationId }, }, ) // 3. Query the agent console.log('Querying agent...') const response = await fetch('http://localhost:3000/query', { method: 'POST', headers: { 'Content-Type': 'application/json', 'PAYMENT-SIGNATURE': `${accessToken}` }, body: JSON.stringify({ prompt: 'What is 2+2?' }) }) const result = await response.json() console.log('Result:', result) } purchaseAndQuery() ``` > [!TIP] > > For agents that run continuously, set up a delegation when generating the access token — the facilitator tops up credits automatically when the balance runs out, with no manual `orderPlan()` loop needed. See [Automatic Credit Top-Ups](/docs/integrate/patterns/top-up). ## Project Structure ``` my-ai-agent/ ├── src/ │ ├── index.ts # Main server │ ├── middleware/ │ │ └── payments.ts # Payment validation │ ├── routes/ │ │ └── query.ts # AI endpoints │ └── services/ │ └── ai.ts # Your AI logic ├── package.json ├── tsconfig.json └── .env ``` ## TypeScript Configuration ```json filename="tsconfig.json" theme={null} { "compilerOptions": { "target": "ES2020", "module": "commonjs", "lib": ["ES2020"], "strict": true, "esModuleInterop": true, "skipLibCheck": true, "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*"] } ``` ## Next Steps > [card] [Express Integration](/docs/integrate/add-to-your-agent/express) > > Complete Express.js patterns and best practices > [card] [TypeScript SDK Reference](/docs/api-reference/typescript/installation) > > Full API documentation > [card] [Payment Patterns](/docs/integrate/patterns/validate-requests) > > Advanced patterns for production > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Deep dive into x402 payment flows # Baselayer Source: https://nevermined.ai/docs/integrations/baselayer Pay for Baselayer KYB business searches with card delegation: a $10 x402 purchase funds 10 metered requests, fully agent-driven. [Baselayer](https://baselayer.com) accepts autonomous payments through Nevermined's [x402 card-delegation](/docs/specs/x402-card-delegation) scheme. An agent holding a Nevermined API key mints an x402 access token against the Baselayer plan and presents it to Baselayer's agentic endpoints in the `payment-signature` header. The first call provisions a Baselayer API key; every business search after that carries the token and the key together, and Baselayer verifies and settles each request against the plan. No Baselayer account or signup is needed: the payment is the identity. Machine-readable instructions for agents live at [Nevermined agentic instructions](https://api.live.nevermined.app/api/v1/organizations/org-a3c3315e-bd43-4764-8d20-6258cee652b8/agentic-instructions.md). On the Baselayer side, the same flow is documented at [docs.baselayer.com/docs/nevermined-agentic-access-x402](https://docs.baselayer.com/docs/nevermined-agentic-access-x402.md), which is listed in [Baselayer's llms.txt](https://docs.baselayer.com/llms.txt) so an agent can find it without being told. > [!NOTE] > > Baselayer's Nevermined plan ID:\ > `64016128970723825062202451177754352720194073054658343333156009220723821177122`\ > [Baselayer Startup: \$10.00 per 100 credits](https://api.live.nevermined.app/api/v1/protocol/plans/64016128970723825062202451177754352720194073054658343333156009220723821177122), and every request burns 10 credits, so one purchase funds **10 requests**. Unlike a pay-as-you-go plan, you never buy credits explicitly: the card is charged \$10 whenever a request finds fewer than 10 credits on your balance. This plan and purchase run on **live**; use a live-prefixed Nevermined API key. ## Prerequisites (one time, done by the card owner) 1. Enroll a card at [nevermined.app](https://nevermined.app) → Payment Methods. 2. Create a **delegation** on the card: the spending permission an agent pays with. The owner sets the spending limit and duration, and can scope the delegation to a specific API key (recommended; it makes discovery deterministic for that key). 3. Generate an API key and give it to the agent. Two ways: * **Embedded login flow (no copy/paste):** the agent hosts a callback on `127.0.0.1` and sends its human this URL to sign in: `https://nevermined.app/auth/cli?callback_url=http://127.0.0.1:/callback`. After sign-in, the browser redirects to the callback with `nvm_api_key=` for the agent to read. * **Manual:** [nevermined.app](https://nevermined.app) → Account → API Keys → create a key and paste it to the agent (or open `https://nevermined.app/auth/cli` with no `callback_url` and copy the key shown on screen). See the [x402 card-delegation spec](/docs/specs/x402-card-delegation) for how enrollment and delegations work. > [!NOTE] > > **Sizing the delegation for this merchant.** Every business search settles against the delegation, not only the first call, so it has to stay within budget and within its time window for the whole run. Baselayer's API is a waterfall, and a business that fails its first check costs more to investigate than one that passes: size the limit against a bad week rather than an average one. And keep an unaffordable check distinct from a passed one in your own records; a payment failure tells you nothing about the business in front of it. ## The flow Handled with the Nevermined Payments SDK (`npm install @nevermined-io/payments`; the package is ESM-only; in a fresh npm project set `"type": "module"` in `package.json`, or the import fails with `ERR_PACKAGE_PATH_NOT_EXPORTED`). The package's bundled TypeScript definitions are the authoritative call reference for every method named below. For broader context, start from the [Payments overview](/docs/products/payments/overview) and the [documentation index](https://nevermined.ai/docs/llms.txt). 1. **Initialize** the SDK with your Nevermined API key only (`Payments.getInstance({ nvmApiKey })`). The environment is derived from the key prefix; do not pass an `environment` option. 2. **Find the delegation to pay with**; see [Getting a delegation](#getting-a-delegation) below. 3. **Mint the x402 access token** for the Baselayer plan ID via `payments.x402.getX402AccessToken`, using the `nvm:card-delegation` scheme and referencing the delegation by ID (`delegationConfig: { delegationId }`). The method's arguments are `(planId, agentId?, tokenOptions?)`. Pass Baselayer's agent ID, `60798063874007247008401413456869371418449913824213519077458224260713519377086`, as the second argument, as Baselayer's own example does: it is optional, and its only effect is to attribute your requests to the [Baselayer Business Search Agent](https://api.live.nevermined.app/api/v1/protocol/agents/60798063874007247008401413456869371418449913824213519077458224260713519377086) listing. The call returns an object, `{ accessToken }`. Tokens cannot create delegations on the fly; the delegation must exist first. 4. **POST the token to Baselayer** in the `payment-signature` header to buy a key (endpoint below). Baselayer's endpoint lives on Baselayer, not on Nevermined, and it **verifies and settles the token for you**. Do not settle it yourself first. The `201` response contains the Baselayer API key. Check the HTTP status before reading the body. 5. **Run business searches** with the same token in `payment-signature` and the key in `X-API-Key`, one request per business. Each request is metered against the plan: keep the token and reuse it for the whole run. ## Without the SDK: the REST calls The Nevermined steps above map to endpoints on `https://api.live.nevermined.app`; send your Nevermined API key as `Authorization: Bearer ` on those two. The calls that follow go to Baselayer and are authenticated by the x402 token alone — do not send your Nevermined API key to a merchant. ### 1. Create a delegation ```http theme={null} POST https://api.live.nevermined.app/api/v1/delegation/create ``` Body: `{ provider, providerPaymentMethodId, spendingLimitCents, durationSecs, currency }`. A delegation authorizes spending within a fixed budget and time window. Reuse it until it is spent or expires. Field values for this flow are in the [delegation table](#getting-a-delegation) below. ### 2. Mint an x402 access token ```http theme={null} POST https://api.live.nevermined.app/api/v1/x402/permissions ``` ```json theme={null} { "accepted": { "scheme": "nvm:card-delegation", "network": "stripe", "planId": "" }, "delegationConfig": { "delegationId": "" } } ``` Returns an `accessToken`. The delegation must already exist. Tokens cannot create one on the fly. ### 3. Buy a Baselayer API key ```http theme={null} POST https://api.baselayer.com/alpha/api_keys Content-Type: application/json payment-signature: {"name": "my-agent", "default_request_mode": "sync"} ``` Baselayer's endpoint **verifies and settles the token on your behalf** and returns the key in the same call. There is nothing to settle first. ### 4. Run a business search ```http theme={null} POST https://api.baselayer.com/alpha/searches Content-Type: application/json payment-signature: X-API-Key: Prefer: wait=120 {"name": "Howard Concrete Pumping Co Inc", "address": "2327 Hill Church Houston Rd, Canonsburg PA 15317"} ``` Both headers are required: the token pays for the request, the key identifies you. Baselayer settles this call against the plan too. > [!WARNING] > > **Do not call `/x402/settle` yourself in this flow.** On this credits plan, settling directly against Nevermined burns 10 credits — and charges the card \$10 first if your balance is empty — and hands back a bare settlement receipt. Baselayer delivered nothing for that settle, and when you then send the token to a Baselayer endpoint it settles again for the request it actually serves. **You have paid for a request that never happened.** > > `/x402/settle` and `/x402/verify` exist for calling a generic Nevermined-metered resource yourself, where you construct the `paymentRequired` object and settle against it. The Baselayer flow does not use them. ### The general pattern Baselayer's endpoints are x402-protected resources, and the rule generalizes: **when a service is x402-protected, send the access token in the `payment-signature` header and let the service verify and settle.** Its own `402` response is the `paymentRequired`, so you never build one by hand. Reach for `/x402/settle` only when you are metering a resource yourself and no merchant endpoint is doing it for you. When you *are* metering a resource yourself, you construct `paymentRequired` from the plan ID and pass it to `/x402/settle` or `/x402/verify`. **`resource.url` must be a non-empty URL** identifying what is being bought; for a plain plan top-up, use the plan's own URL. ```json theme={null} { "x402Version": 2, "resource": { "url": "" }, "accepts": [{ "scheme": "nvm:card-delegation", "network": "stripe", "planId": "", "extra": {} }], "extensions": {} } ``` ```http theme={null} POST https://api.live.nevermined.app/api/v1/x402/settle ``` Body: `{ "paymentRequired": , "x402AccessToken": "" }`. Settling returns a `billingModel`. `credits` plans, like this one, mint and burn, returning `creditsRedeemed` and `remainingBalance`; pay-as-you-go plans charge per request, so both of those fields read `"0"` and the charge reference is in `orderTx` (fiat) or `transaction` (crypto). `POST /api/v1/x402/verify` with the same body is an optional dry run. Neither call belongs in the Baselayer flow. ## Getting a delegation Query the delegations accessible to your API key with `payments.delegation.getPurchasingPower()` and select one with at least 1,000 cents of remaining budget. Budget fields are returned as strings, in cents. Purchasing-power results contain only delegations that can still pay; exhausted ones are excluded. With several delegations, discovery is deterministic when the owner key-scoped one to your key; to designate a specific budget among several, reference its ID explicitly. **If discovery returns none**, the preferred path is for the card owner to create a delegation in the dashboard (Prerequisites, step 2); the agent then re-runs discovery. Nothing needs to be copied. If no operator is reachable (or the request goes unanswered), a fully autonomous agent can create one programmatically with `payments.delegation.createDelegation`. Its payload fields: | Field | Value for this flow | | - | - | | `provider` | `"stripe"` | | `providerPaymentMethodId` | The card's id from `payments.delegation.listPaymentMethods()` | | `spendingLimitCents` | N × 1000 for N expected \$10 purchases, each of which funds 10 requests. A 1,000-cent delegation covers one purchase and is exhausted after it; Baselayer's own guide sizes a working delegation at `10000` (ten purchases, 100 requests) | | `durationSecs` | Long enough to outlive the whole run, since every request settles against the delegation. `3600` is enough for a one-shot check; Baselayer's guide uses `604800` (seven days) for a queue that drains over time. Keep it as short as the work allows (least privilege) | | `currency` | `"usd"` | The response includes the `delegationId` to mint with (it also includes a `delegationToken`; not needed for this flow; treat it as a secret and do not log it). **Card selection:** `listPaymentMethods()` carries no ordering guarantee and cards may be indistinguishable by metadata; if several are enrolled and the owner's intent is unknown, prefer asking the owner; otherwise any Active card of the provider is acceptable, and you should record which payment-method id was chosen. Note the trade-off of this whole path: the agent chooses the card and sets its own budget. Prefer an owner-created delegation whenever an owner is available. ## Baselayer's agentic contract Baselayer serves the agentic flow from `https://api.baselayer.com` under the `/alpha` prefix. Only the two endpoints below exist there; anything else under `/alpha` is a `404`. Both take the x402 token in the `payment-signature` header, and Baselayer verifies and settles it server-side on every request. The settlement receipt comes back base64-encoded in the `payment-response` response header. You are charged only for successful (`2xx`) requests. ### Purchase an API key ```http theme={null} POST https://api.baselayer.com/alpha/api_keys Content-Type: application/json payment-signature: {"name": "my-agent", "default_request_mode": "sync"} ``` * **Cost:** 10 credits, the same as any other request. The key purchase is metered like a search, so a \$10 lot funds this call plus nine searches. * **Response `201`:** `{ "id": "…", "name": "my-agent", "key": "prod_…", "default_request_mode": "sync" }`. Store `key`; it is a real Baselayer production API key. * **Missing signature:** `402 Payment Required`. The base64 `payment-required` response header carries the x402 challenge naming this plan and agent (`accepts[0].planId`, `accepts[0].extra.agentId`), and the JSON body (`code: 6500`) points you at it. Decode the header to discover the plan programmatically. ### Run a business search ```http theme={null} POST https://api.baselayer.com/alpha/searches Content-Type: application/json payment-signature: X-API-Key: prod_… Prefer: wait=120 {"name": "Howard Concrete Pumping Co Inc", "address": "2327 Hill Church Houston Rd, Canonsburg PA 15317"} ``` * **Cost:** 10 credits per request, which is \$1.00 of the \$10 purchase. * **Response `201`:** the full result inline — Secretary of State registrations, officers, watchlist screening, and match verdicts such as `"business_name_match": "EXACT"`. `Prefer: wait=120` asks Baselayer to hold the connection until the search completes; set your HTTP client's timeout above that (Baselayer's example uses 180 seconds). Optional request fields include `officer_names`, `website`, `phone_number`, `email` and `tin`; see the [Search API reference](https://docs.baselayer.com/reference) for the complete schema. * **Missing or exhausted token:** `402 Payment Required` with the `payment-required` challenge header. Mint a fresh token against the same plan and delegation and retry. A token that is *malformed* is answered `502` / `6501` instead — see below. * **Settlement outcome unknown:** `502` with `code: 6501` and a `metadata.settlement_id`. Baselayer could not confirm whether the charge went through and dispatched no work. Do not retry automatically; reconcile the `settlement_id` with Baselayer support first. **When the credits run out:** nothing to do. The next request that finds fewer than 10 credits on your balance charges the card \$10 for another 100, then settles as usual. What ends a run is the delegation, not the credits: once its budget is spent or its window has closed, token minting fails and Baselayer answers `402`; create or top up a delegation to continue. ## Pricing **Baselayer sells credits in \$10 lots, and every request burns 10 of them.** The plan is `credits`, not pay-as-you-go: your card is charged \$10 when a request finds fewer than 10 credits on your balance, and that charge mints 100 credits on your Nevermined account for this plan. Requests two through ten draw the balance down without touching the card; the eleventh charges again. The cost per request works out to \$1.00, billed ten at a time. Two consequences worth knowing before you size a delegation. The very first request of a run — the key purchase — is what triggers the first \$10 charge, so a delegation needs at least 1,000 cents before an agent can get a key at all. And credits are held on the Nevermined plan, not on the Baselayer key: an agent that stops after three searches leaves 60 credits on the balance, and the same account's next run spends those before the card is charged again. Because it is a credits plan, a settle returns `creditsRedeemed: "10"` and the `remainingBalance` after the burn. Those fields are your proof of metering; the `orderTx` on a settle that charged the card is your proof of purchase. Nevermined meters the requests; what each search does inside Baselayer is Baselayer's own product and Nevermined neither sets nor observes it. ## What the key unlocks The purchase provisions a production Baselayer API key, but through this route it is used together with the x402 token, on the agentic endpoints only: today that is Business Search. Business Search is the entry point to Baselayer's KYB catalog and returns identity, registration, officer and watchlist data with match verdicts in a single synchronous response. Baselayer's wider catalog — standalone [watchlist and sanctions](https://docs.baselayer.com/docs/watchlists-sanctions-standalone-checks) checks, [litigation and bankruptcy](https://docs.baselayer.com/docs/litigation-bankruptcy-search-api-quickstart) search, [sole proprietorship verification](https://docs.baselayer.com/docs/sole-prop-verification) — is documented for account holders and is not served under `/alpha`. ```bash theme={null} curl -X POST https://api.baselayer.com/alpha/searches \ -H "payment-signature: $X402_TOKEN" \ -H "X-API-Key: $BASELAYER_API_KEY" \ -H "Prefer: wait=120" \ -H "Content-Type: application/json" \ -d '{"name": "Acme Corp", "address": "1 Main St, Dover, DE"}' ``` Baselayer publishes a Python walkthrough of the same flow with `payments-py` on its [Nevermined page](https://docs.baselayer.com/docs/nevermined-agentic-access-x402.md). ## Verifying charges Use `payments.delegation.listDelegations()` to inspect spend per delegation (`amountSpentCents`, `transactionCount`, status); the response wraps a `delegations` array. Fully spent delegations are marked `Exhausted` and no longer appear in `getPurchasingPower()` results; purchasing power lists only delegations that can still pay. On this plan a delegation's `amountSpentCents` grows in steps of 1,000 — one per \$10 purchase — rather than once per request; the per-request metering shows up as the `remainingBalance` in the settlement receipt Baselayer returns in the `payment-response` header. ## Troubleshooting | Symptom | Meaning / fix | | - | - | | Token mint fails: `Required token-generation input is missing or incomplete (HTTP 402)` | The mint referenced no existing delegation (e.g., legacy create-on-the-fly `delegationConfig` with card details). Create or discover a delegation first and pass `delegationConfig: { delegationId }`. | | `ERR_PACKAGE_PATH_NOT_EXPORTED` on import | The SDK is ESM-only. Set `"type": "module"` in `package.json` or use `.mts`. | | Console warning: `The 'environment' option is deprecated…` | Something is still passing the deprecated `environment` option (a wrapper or copied example). Remove it; the environment is derived from your key prefix. On SDK 1.10.0 the warning can also self-fire with nothing passed ([payments#416](https://github.com/nevermined-io/payments/issues/416)); if you have removed the option and still see it, that issue is why. | | The plan ID above does not resolve, or token mint fails against it | Check your key prefix: this is a **live** plan, and a `sandbox:`-prefixed key targets a different environment where the plan does not exist. | | A delegation you spent from disappears from `getPurchasingPower()` | It is exhausted. Inspect it with `listDelegations()`; create or top up a delegation to continue. | | A Baselayer endpoint returns `402` with a `payment-required` header | The token is missing, or can no longer pay: its delegation is exhausted or expired. Check the delegation with `listDelegations()`, then mint a fresh token against the same plan and delegation and retry. A malformed token is answered `502` / `6501` instead, below. | | `404` from a path under `/alpha` | Only `/alpha/api_keys` and `/alpha/searches` are served on the agentic base URL. Baselayer's other products are not reachable through this route. | | The card was charged \$10 for what looks like one \$1 search | Expected: credits are sold in \$10 lots of 100, and a request that finds fewer than 10 on the balance triggers the purchase. The next nine requests draw the balance down without a charge. | | The card was charged, or credits were burned, and nothing came back from Baselayer | You called `/x402/settle` yourself. Baselayer's endpoints settle for you. Mint the token and go straight there. | | The delegation exhausts part-way through a queue of businesses | Expected behaviour, and the reason the ceiling exists. Surface the halt and leave the remaining cases explicitly unprocessed. Never let an unaffordable check be recorded as a passed check: a payment failure and a verification result are different states and must not converge. | | A Baselayer endpoint returns `502` with `code: 6501` (`Payment outcome is unknown`) | Baselayer's call to settle the token did not return a definitive answer, so it dispatched no work and cannot tell you whether the card was charged. Do not retry on a loop: check the delegation's `amountSpentCents` with `listDelegations()`, and reconcile the `metadata.settlement_id` with Baselayer support before sending the token again. | | A search request times out on your side | `Prefer: wait=120` holds the connection for up to two minutes while the search runs. Set the HTTP client's timeout above that, and retry with the same token: you are only charged for `2xx` responses. | | `settle` rejects a hand-built `paymentRequired` | `resource.url` is required and must be a non-empty URL. For a plan top-up with no protected endpoint to call, use the plan's own URL. | | `settle` returns `creditsRedeemed: "10"` and a non-zero `remainingBalance` | Expected on this credits plan: 10 credits are burned per request and the balance after the burn is reported. A pay-as-you-go plan would report `"0"` for both. | ## References * [Payments overview](/docs/products/payments/overview) * [x402 card-delegation spec](/docs/specs/x402-card-delegation) * [Nevermined agentic instructions (machine-readable)](https://api.live.nevermined.app/api/v1/organizations/org-a3c3315e-bd43-4764-8d20-6258cee652b8/agentic-instructions.md) * [Baselayer Startup plan](https://api.live.nevermined.app/api/v1/protocol/plans/64016128970723825062202451177754352720194073054658343333156009220723821177122) and the [Baselayer Business Search Agent](https://api.live.nevermined.app/api/v1/protocol/agents/60798063874007247008401413456869371418449913824213519077458224260713519377086) listing * [x402 glossary entry](https://nevermined.ai/glossary/x402/) * [Baselayer's Nevermined page](https://docs.baselayer.com/docs/nevermined-agentic-access-x402.md) — the merchant-side counterpart to this one; listed in [Baselayer's llms.txt](https://docs.baselayer.com/llms.txt) * [Getting started with the Baselayer API](https://docs.baselayer.com/docs/getting-started) * [Baselayer Business Search](https://docs.baselayer.com/docs/business-search) * [Baselayer API reference](https://docs.baselayer.com/reference) # BuildShip Source: https://nevermined.ai/docs/integrations/buildship-integration Protect your BuildShip workflows and monetize access with Nevermined Payments Integrating Nevermined's access control and payment system with your existing BuildShip workflows is the quickest way to turn your low-code backend logic into a fully monetized API. This process requires setting up an **AI Agent** in Nevermined and configuring the **Nevermined Trigger** in BuildShip. > [!NOTE] > > This guide assumes you have an active BuildShip account and have signed up for a Nevermined account. ## The Nevermined BuildShip Trigger The Nevermined Trigger is a specialized node in BuildShip that is placed at the beginning of your workflow. Its function is to act as a security layer and payment middleware, validating subscriber access before your workflow logic executes. > [card] Primary Purpose > > To secure HTTP access to a BuildShip workflow endpoint for monetization. > [card] Security Mechanism > > It validates the user's **Access Token** (Bearer Token) and verifies their subscription status against a Nevermined plan. ## Step-by-step Tutorial: Monetizing a BuildShip Workflow The goal is to secure a BuildShip endpoint so it is only accessible by users who have purchased a **Payment Plan** and provide a valid **Access Token**. **1. Get Your API Key** To interact with the Nevermined API, you need an API key. 1. Go to the [Nevermined App](https://nevermined.app/). ![Nevermined Login Page](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-login-page.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=e27c3744406b8260778956487438ebbb) 2. Log in with your preferred method. 3. In the dashboard, click on the **API Keys** menu item. ![Nevermined API Key Generation (1)](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-dashboard-api-key.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=3b7240acbcc8f090618f00f6c352224b) 4. Click on **New API Key** button, generate a new key, give it a descriptive name, and copy it. ![Nevermined API Key Generation (2)](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-api-key-new.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=f345de863d0f7c89a8552bc410deaf61) 5. **Copy the generated key** and store it securely. ![Nevermined API Key Generation (3)](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-api-key-created.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=97e5eea85b3088ec85685dd6dd7ceef6) **2. Configure Nevermined Integration in BuildShip** You must configure the API key as a secure integration in your BuildShip workspace. 1. In your BuildShip Workspace, go to **Settings** > **Integrations**. 2. Search for **Nevermined** and click to add a new integration. ![Buildship Settings > Integrations](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/buildship/buildship-integrations.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=161ca38ca90c15747e4985b886410567) 3. Provide a **Key Name** (e.g., `NVM_API_KEY`). This name will be selectable in the Trigger later. 4. Paste your Nevermined API Key (from Step 1) into the **Value** field. ![Buildship New Integration](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/buildship/buildship-new-integration.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=4ad820544682cab0d78489b091b972d7) 5. Save the integration to activate it in your workspace. **3. 3. Initial Trigger Setup in BuildShip (Part 1)** Now, set up the entry point of your workflow using the configured integration. * Add the **Nevermined Trigger** node as the first node in your workflow. * **Authentication Key**: In the trigger's configuration, select the **Key Name** you defined in Step 2 (e.g., `NVM_API_KEY`) from the dropdown menu. * Define your desired endpoint: set the **`Path`** (e.g., `/my-backend-logic`) and the **`Method`** (e.g., `POST`). * Connect the **`prompt`** output of the trigger to the input of the next node (your core logic). > [!NOTE] > > The user's JSON request body, including the prompt, will be passed through the **`prompt`** output. Leave the **`Agent ID`** parameter empty for now. **4. 4. Create the Payment Plan and Agent in Nevermined** Define the monetization rules and register your service as an AI Agent in Nevermined. 1. **Create Plan**: Create a **Payment Plan** that defines the pricing and consumption model for your service. ![Nevermined Plan Creation (1)](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-dashboard-plan.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=87542222699b2904cd644ad1ab554154) ![Nevermined Plan Creation (2)](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-plan-new.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=22fa9312cb6794532edea3a1df150ede) ![Nevermined Plan Creation (3)](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-plan-new-2.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=d3f0667eb41a10e7db6b6c76961ef8d0) 2. **Register Agent**: Create a new **AI Agent**. ![Nevermined Agent Registration](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-dashboard-agent.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=b7a1986fb4484e8367cd07fb02393c4f) 3. **Register Endpoint**: In the Agent configuration, register the BuildShip endpoint. Ensure the **Path** and **Method** match exactly what you configured in BuildShip (Step 3). ![Nevermined Agent Endpoint Registration](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-agent-new.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=3c237cbec8bb10554d0d33209511ff1a) 4. **Associate Plan**: Attach the new Payment Plan to this Agent. ![Nevermined Agent and Plan](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/agents-and-plans/nevermined-agent-plan.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=e677b8f415e4a228093d2c34239ef366) **5. 5. Finalize the Trigger Setup in BuildShip (Part 2)** Link the configured Agent back to your BuildShip workflow. * Return to your BuildShip workflow and open the **Nevermined Payment Trigger** configuration. * In the **`Agent Name`** field, select the **Agent Name** you just registered in Nevermined from the dropdown list. ![Buildship Trigger configuration](https://mintcdn.com/neverminedag/816P0WhT1WcQ-Koj/images/buildship/buildship-select-agent.png?fit=max\&auto=format\&n=816P0WhT1WcQ-Koj\&q=85\&s=d8a248a7ede6ec46193c389e45b97e39) *If the ID does not appear*, close the configuration panel and reopen it to refresh the list of available Agents. * Click **Ship 🚀** to deploy the workflow. ## User Access Flow Once deployed, this is the complete process a subscriber must follow to successfully access your secured workflow. **1. 1. Purchase and Token Generation** The user must purchase the Payment Plan associated with your AI Agent. Upon purchase, they **generate an Access Token** (Bearer Token) from their Nevermined profile. **2. 2. Call the Secured Endpoint** The user sends an HTTP request to the deployed BuildShip endpoint with two key components: * **Header**: The **Access Token** must be included in the `Authorization` header: ` Authorization: Bearer [User's Access Token]  ` * **Body**: The input data (*prompt*) for your workflow must be sent in the request body as a **JSON object** using the key **`prompt`**: `json { "prompt": "PROMPT_TO_THE_BUILDSHIP_AGENT" } ` **3. 3. Validation and Execution** The **Nevermined Trigger** intercepts the request, validates the token, checks the subscription status, deducts the necessary credits, and allows the JSON `prompt` data to flow into your BuildShip logic for processing. # Exa Source: https://nevermined.ai/docs/integrations/exa Buy Exa API credits with card delegation: a $7 x402 purchase provisions or tops up an Exa API key, fully agent-driven. [Exa](https://exa.ai) accepts autonomous payments through Nevermined's [x402 card-delegation](/docs/specs/x402-card-delegation) scheme. An agent holding a Nevermined API key mints an x402 access token against the Exa plan and exchanges it at Exa's purchase endpoint for a working Exa API key. Repeat purchases top up the same key. > [!NOTE] > > Exa's Nevermined plan ID:\ > `27800462147494506865542649899724877617306579171265399959488097895839186996870`\ > This plan and purchase run on **live**; use a live-prefixed Nevermined API key. The purchase is for API credits, not for a single search request. \$7 covers roughly 1,000 standard searches; see [Exa pricing](https://exa.ai/pricing) for current rates. ## Prerequisites (one time, done by the card owner) 1. Enroll a card at [nevermined.app](https://nevermined.app) → Payment Methods. 2. Create a **delegation** on the card: the spending permission an agent pays with. The owner sets the spending limit and duration, and can scope the delegation to a specific API key (recommended; it makes discovery deterministic for that key). 3. Generate an API key and give it to the agent. Two ways: * **Embedded login flow (no copy/paste):** the agent hosts a callback on `127.0.0.1` and sends its human this URL to sign in: `https://nevermined.app/auth/cli?callback_url=http://127.0.0.1:/callback`. After sign-in, the browser redirects to the callback with `nvm_api_key=` for the agent to read. * **Manual:** [nevermined.app](https://nevermined.app) → Account → API Keys → create a key and paste it to the agent (or open `https://nevermined.app/auth/cli` with no `callback_url` and copy the key shown on screen). See the [x402 card-delegation spec](/docs/specs/x402-card-delegation) for how enrollment and delegations work. ## The flow Handled with the Nevermined Payments SDK (`npm install @nevermined-io/payments`; the package is ESM-only; in a fresh npm project set `"type": "module"` in `package.json`, or the import fails with `ERR_PACKAGE_PATH_NOT_EXPORTED`). The package's bundled TypeScript definitions are the authoritative call reference for every method named below. For broader context, start from the [Payments overview](/docs/products/payments/overview) and the [documentation index](https://nevermined.ai/docs/llms.txt). 1. **Initialize** the SDK with your Nevermined API key only (`Payments.getInstance({ nvmApiKey })`). The environment is derived from the key prefix; do not pass an `environment` option. 2. **Find the delegation to pay with**; see [Getting a delegation](#getting-a-delegation) below. 3. **Mint the x402 access token** for the Exa plan ID via `payments.x402.getX402AccessToken`, using the `nvm:card-delegation` scheme and referencing the delegation by ID (`delegationConfig: { delegationId }`). No agentId is needed for this flow: the method's arguments are `(planId, agentId?, tokenOptions?)`, so pass the plan ID, `undefined`, and the token options. The call returns an object, `{ accessToken }`. Tokens cannot create delegations on the fly; the delegation must exist first. 4. **POST the token to Exa** in the `payment-signature` header (endpoint below). The response contains the Exa API key. Check the HTTP status before reading the body. 5. **Use the key** against the standard [Exa Search API](https://docs.exa.ai). ## Getting a delegation Query the delegations accessible to your API key with `payments.delegation.getPurchasingPower()` and select one with at least 700 cents of remaining budget. Budget fields are returned as strings, in cents. Purchasing-power results contain only delegations that can still pay; exhausted ones are excluded. With several delegations, discovery is deterministic when the owner key-scoped one to your key; to designate a specific budget among several, reference its ID explicitly. **If discovery returns none**, the preferred path is for the card owner to create a delegation in the dashboard (Prerequisites, step 2); the agent then re-runs discovery. Nothing needs to be copied. If no operator is reachable (or the request goes unanswered), a fully autonomous agent can create one programmatically with `payments.delegation.createDelegation`. Its payload fields: | Field | Value for this flow | | - | - | | `provider` | `"stripe"` | | `providerPaymentMethodId` | The card's id from `payments.delegation.listPaymentMethods()` | | `spendingLimitCents` | N × 700 for N expected purchases; a 700-cent delegation is exhausted after a single purchase | | `durationSecs` | `3600` is a sensible default for a one-shot purchase; keep it short (least privilege) | | `currency` | `"usd"` | The response includes the `delegationId` to mint with (it also includes a `delegationToken`; not needed for this flow; treat it as a secret and do not log it). **Card selection:** `listPaymentMethods()` carries no ordering guarantee and cards may be indistinguishable by metadata; if several are enrolled and the owner's intent is unknown, prefer asking the owner; otherwise any Active card of the provider is acceptable, and you should record which payment-method id was chosen. Note the trade-off of this whole path: the agent chooses the card and sets its own budget. Prefer an owner-created delegation whenever an owner is available. ## Exa's purchase contract ```bash theme={null} POST https://admin-api.exa.ai/team-management/nevermined/purchase-key payment-signature: ``` * **Cost:** \$7 per purchase, charged to the card behind the delegation referenced by the token. * **New payer:** `{ status: "ok", apiKey: "…", expiresAt: null }`; a new Exa API key with \$7 of credits. * **Returning payer:** the same API key with \$7 more credits added. * **Replayed token:** cached result, no new charge. * **Missing/invalid signature:** `402 Payment Required` with payment requirements in the body. **When the key runs out:** Exa's regular API endpoints return `HTTP 402` with error tag `NO_MORE_CREDITS`. Mint a fresh x402 token with the same plan ID and delegation, POST it to the same endpoint, and Exa adds another \$7 of credits to the same key. ## Verifying charges Use `payments.delegation.listDelegations()` to inspect spend per delegation (`amountSpentCents`, `transactionCount`, status); the response wraps a `delegations` array. Fully spent delegations are marked `Exhausted` and no longer appear in `getPurchasingPower()` results; purchasing power lists only delegations that can still pay. ## Troubleshooting | Symptom | Meaning / fix | | - | - | | Token mint fails: `Required token-generation input is missing or incomplete (HTTP 402)` | The mint referenced no existing delegation (e.g., legacy create-on-the-fly `delegationConfig` with card details). Create or discover a delegation first and pass `delegationConfig: { delegationId }`. | | `ERR_PACKAGE_PATH_NOT_EXPORTED` on import | The SDK is ESM-only. Set `"type": "module"` in `package.json` or use `.mts`. | | Console warning: `The 'environment' option is deprecated…` | Something is still passing the deprecated `environment` option (a wrapper or copied example). Remove it; the environment is derived from your key prefix. On SDK 1.10.0 the warning can also self-fire with nothing passed ([payments#416](https://github.com/nevermined-io/payments/issues/416)); if you have removed the option and still see it, that issue is why. | | The plan ID above does not resolve, or token mint fails against it | Check your key prefix: this is a live plan, and a `sandbox:`-prefixed key targets a different environment where the plan does not exist. | | A delegation you spent from disappears from `getPurchasingPower()` | It is exhausted. Inspect it with `listDelegations()`; create or top up a delegation to continue. | | Exa search returns `402` with `NO_MORE_CREDITS` | The Exa key's credits are spent. Repeat the purchase flow to top up the same key. | ## References * [Payments overview](/docs/products/payments/overview) * [x402 card-delegation spec](/docs/specs/x402-card-delegation) * [Exa pricing](https://exa.ai/pricing) * [Exa Search API](https://docs.exa.ai) # A2A Source: https://nevermined.ai/docs/integrations/google-a2a Integrate Nevermined with Google's Agent-to-Agent (A2A) protocol to authorize and charge per request between agents, with credits validation built in. Nevermined Payments integrates with [Google A2A](https://a2a-protocol.org/) to enable heterogeneous multi-agent systems to authorize and charge per request between agents: * Discovery: publish your AI Agent Card at `/.well-known/agent.json`. * Streaming and re-subscribe: set `capabilities.streaming: true` for `message/stream` and `tasks/resubscribe`. * Authentication: credentials are sent in HTTP headers (e.g., `payment-signature: `), not in the JSON‑RPC payload. * Authorization/charging: the agent emits a final event with `metadata.creditsUsed`; Nevermined validates and burns credits accordingly. ## Architecture ```mermaid theme={null} sequenceDiagram participant Consumer participant Provider participant Nevermined Consumer->>Provider: Discover agent card Consumer->>Nevermined: Order plan and get token Consumer->>Provider: Send message with payment-signature Provider->>Nevermined: Verify permissions Provider->>Provider: Execute agent logic Provider->>Nevermined: Settle credits Provider-->>Consumer: Return response ``` ## Features The libraries provide an `a2a` module that enables seamless integration into new or existing A2A agents, including payment-signature authentication, asynchronous task management, and push notification support. Main features: * **Payment Signature Authentication**: The server extracts access tokens from the `payment-signature` header and injects them into the task context. * **Credits Validation**: Validates that the user has sufficient credits before executing a task. * **Credits Burning/Redemption**: Redeem the credits specified in the result after successful execution. * **Multi-Plan Support**: Agent cards can advertise multiple plans via `planIds`, allowing consumers to choose which plan to subscribe to. * **Scheme Auto-Detection**: Resolves `nvm:erc4337` or `nvm:card-delegation` from plan metadata automatically * **Push Notifications**: Supports the A2A standard flow for push notification configuration and delivery. * **Asynchronous Task Handling**: Supports intermediate and final state events, compatible with polling and streaming. * **Unified SDK**: Provides both agent and client integration. ## Quickstart If you already have a Google A2A agent, or you are building a new one, add the Payments Library to your agent and obtain an API key: **1. 1. Get Your API Key** To interact with the Nevermined API, you need an API key. Follow the [Get Your API Key](/docs/agents-guide/get-api-key) guide to create one. **2. 2. Install and Initialize the Payments Library** Install the Payments Library and initialize the `Payments` client with your API key. > [tab] TypeScript > > ```bash theme={null} > npm install @nevermined-io/payments > ``` > [tab] Python > > ```bash theme={null} > pip install payments-py > ``` ## Initialize the Payments Library > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from "@nevermined-io/payments" > > const payments = Payments.getInstance({ > nvmApiKey, > environment: 'sandbox', > }) > ``` > [tab] Python > > ```python theme={null} > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key="", environment="sandbox") > ) > ``` ## A2A Server > [!NOTE] > > The A2A server handles both `nvm:erc4337` and `nvm:card-delegation` schemes automatically. > The scheme is resolved from plan metadata — no server-side code changes are needed for fiat plans. ### Add the Payment Extension to the Agent Card Because your AI agent charges for requests, add a payment extension to your agent card. Add a payment extension under `capabilities.extensions` carrying Nevermined metadata: #### Single Plan ```json theme={null} { "capabilities": { "streaming": true, "pushNotifications": true, "extensions": [ { "uri": "urn:nevermined:payment", "description": "Dynamic cost per request", "required": false, "params": { "paymentType": "dynamic", "credits": 1, "planId": "", "agentId": "" } } ] }, "url": "https://your-agent.example.com/a2a/" } ``` #### Multiple Plans When your agent supports multiple plans, use `planIds` (array) instead of `planId` (string): ```json theme={null} { "capabilities": { "extensions": [ { "uri": "urn:nevermined:payment", "params": { "paymentType": "dynamic", "credits": 5, "planIds": ["", ""], "agentId": "", "costDescription": "1-5 credits depending on request complexity" } } ] } } ``` > [!NOTE] > > Provide either `planId` or `planIds`, not both. When multiple plans are configured, the 402 Payment Required response includes all plans in `accepts[]`, allowing consumers to choose. Important notes: * The `url` must match exactly the URL registered in Nevermined for the agent/plan. * The final streaming event must include `metadata.creditsUsed` with the consumed cost. ### Define the Payment Agent Card in Your A2A Agent > [tab] TypeScript > > ```typescript theme={null} > const baseAgentCard = { > name: 'My A2A Server', > description: 'A2A test server that requires payment', > capabilities: { > streaming: true, > pushNotifications: true, > stateTransitionHistory: true, > }, > defaultInputModes: ['text'], > defaultOutputModes: ['text'], > skills: [], > url: 'http://localhost:3005/a2a/', > version: '1.0.0', > } > > const agentCard = payments.a2a.buildPaymentAgentCard(baseAgentCard, { > paymentType: "dynamic", > credits: 1, > planId: process.env.PLAN_ID, > agentId: process.env.AGENT_ID, > }) > ``` > [tab] Python > > ```python theme={null} > from payments_py.a2a import build_payment_agent_card > > base_agent_card = { > "name": "Py A2A Agent", > "description": "A2A test agent", > "capabilities": { > "streaming": True, > "pushNotifications": True, > "stateTransitionHistory": True, > }, > "defaultInputModes": ["text"], > "defaultOutputModes": ["text"], > "skills": [], > "url": "https://your-agent.example.com/a2a/", > "version": "1.0.0", > } > > # Single plan > agent_card = build_payment_agent_card( > base_card=base_agent_card, > payment_metadata={ > "paymentType": "dynamic", > "credits": 1, > "costDescription": "Dynamic cost per request", > "planId": "", > "agentId": "", > }, > ) > > # Or with multiple plans > agent_card = build_payment_agent_card( > base_card=base_agent_card, > payment_metadata={ > "paymentType": "dynamic", > "credits": 5, > "costDescription": "1-5 credits per request", > "planIds": ["", ""], > "agentId": "", > }, > ) > ``` ### Start the A2A Server The agent is initialized using the Nevermined Payments Library and the A2A protocol. #### Using the Decorator (Simple) The `@a2a_requires_payment` decorator is the quickest way to create a payment-protected A2A agent in Python: > [tab] TypeScript > > ```typescript theme={null} > // Start server on port 3005 for A2A > class Executor implements AgentExecutor { > async handleTask(context, eventBus) { > // Returns { result: TaskHandlerResult, expectsMoreUpdates: boolean } > } > async cancelTask(taskId) { /* ... */ } > > // Publishes the final status-update event when no more updates are expected > async execute(requestContext, eventBus) { > const { result, expectsMoreUpdates } = await this.handleTask(requestContext, eventBus) > if (expectsMoreUpdates) return > // Publish final status-update event... > } > } > > serverResult = await paymentsBuilder.a2a.start({ > port: 3005, > basePath: '/a2a/', > agentCard: agentCard, > executor: A2AE2EFactory.createResubscribeStreamingExecutor(), > }) > > serverManager.addServer(serverResult) > ``` > [tab] Python > > ```python theme={null} > from payments_py.a2a import AgentResponse, a2a_requires_payment > > @a2a_requires_payment( > payments=payments, > agent_card=agent_card, > default_credits=1, > ) > async def my_agent(context) -> AgentResponse: > text = context.get_user_input() > return AgentResponse(text=f"Echo: {text}", credits_used=1) > > # Start serving (blocking) > my_agent.serve(port=8080) > ``` #### Using `PaymentsA2AServer` (Advanced) For more control over the executor and event lifecycle: ```python theme={null} from payments_py.a2a.server import PaymentsA2AServer from a2a.server.agent_execution import AgentExecutor from a2a.server.events.event_queue import EventQueue class MyExecutor(AgentExecutor): async def execute(self, ctx, event_queue: EventQueue): # Your agent logic — publish events to event_queue ... async def cancel(self, ctx, event_queue: EventQueue): ... result = PaymentsA2AServer.start( agent_card=agent_card, executor=MyExecutor(), payments_service=payments, port=8080, base_path="/", ) import asyncio asyncio.run(result.server.serve()) ``` ## A2A Client The client interacts with the agent using JSON-RPC requests. It discovers available plans from the agent card, purchases a plan, obtains an access token, and sends messages. ### Discovering Plans from the Agent Card ```mermaid theme={null} sequenceDiagram participant Consumer participant Provider participant Nevermined Consumer->>Provider: GET /.well-known/agent.json Provider-->>Consumer: Agent Card (planIds, agentId) Consumer->>Nevermined: order_plan(selected_plan_id) Nevermined-->>Consumer: Order confirmed Consumer->>Nevermined: get_x402_access_token(plan_id, agent_id) Nevermined-->>Consumer: accessToken Consumer->>Provider: POST / message/send (payment-signature) Provider-->>Consumer: JSON-RPC response ``` > [tab] TypeScript > > ```typescript theme={null} > > const paymentsSubscriber = Payments.getInstance({ > nvmApiKey, > environment: 'sandbox', > }) > > const client = paymentsSubscriber.a2a.getClient({ > agentBaseUrl: 'http://localhost:3005/a2a/', > agentId: process.env.AGENT_ID, > planId: process.env.PLAN_ID > }) > ``` > [tab] Python > > ```python theme={null} > import httpx > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key="", environment="sandbox") > ) > > # 1. Discover plans from the agent card > async with httpx.AsyncClient() as client: > resp = await client.get("http://agent-url/.well-known/agent.json") > card = resp.json() > > extensions = card["capabilities"]["extensions"] > payment_ext = next(e for e in extensions if e["uri"] == "urn:nevermined:payment") > plan_ids = payment_ext["params"].get("planIds") or [payment_ext["params"]["planId"]] > agent_id = payment_ext["params"]["agentId"] > ``` ### Sending a Task After [purchasing access to the payment plan](/docs/getting-started/ai-agent-purchase) associated with the AI agent, a client [can generate an access token](/docs/development-guide/nevermined-x402) and start sending tasks: > [!NOTE] > > The TypeScript example below targets a **crypto** plan. For a **fiat** plan, create the delegation with the card provider (`provider: 'stripe'`, `currency: 'usd'`) and pass `scheme: 'nvm:card-delegation'` to `getX402AccessToken` — or use the `PaymentsClient` (Python tab), which resolves the scheme for you. See [Which payment type does this plan need?](/docs/getting-started/core-concepts#fiat-vs-crypto-what-each-plan-needs). > [tab] TypeScript > > ```typescript theme={null} > // Purchase the Plan > const orderResult = await paymentsSubscriber.plans.orderPlan(planId) > // Create a delegation once, then reuse its id to mint tokens. > const { delegationId } = await paymentsSubscriber.delegation.createDelegation({ > provider: 'erc4337', // 'stripe' | 'braintree' | 'visa' for fiat plans > spendingLimitCents: 10000, // $100 budget > durationSecs: 604800, // 7 days > currency: 'usdc', // 'usd' for fiat plans > }) > // Get the X402 access token associated to the agent and plan > const { accessToken } = await paymentsSubscriber.x402.getX402AccessToken(planId, agentId, { > scheme: 'nvm:erc4337', // 'nvm:card-delegation' for fiat plans > delegationConfig: { delegationId }, > }) > > > // Test sending an A2A message with correct format > const response = await client.sendMessage( > "Testing push notification!", > accessToken > ); > const taskId = response?.result?.id > ``` > [tab] Python > > ```python theme={null} > from payments_py.a2a import PaymentsClient > > # 2. Order (purchase) the plan > payments.plans.order_plan(plan_ids[0]) > > # 3. Create the A2A client (handles token acquisition automatically) > client = PaymentsClient( > agent_base_url="http://agent-url/", > payments=payments, > agent_id=agent_id, > plan_id=plan_ids[0], > ) > > # 4. Send a simple request > result = await client.send_message({ > "message": { > "messageId": "msg-1", > "role": "user", > "parts": [{"kind": "text", "text": "Hello"}], > } > }) > > # 5. Or stream events > async for event in client.send_message_stream({ > "message": { > "messageId": "msg-2", > "role": "user", > "parts": [{"kind": "text", "text": "Stream this"}], > } > }): > print(event) > if getattr(event, "final", False): > break > ``` ## Full example code Find a complete working example in the repository: [nevermined-io/a2a-agent-client-sample](https://github.com/nevermined-io/a2a-agent-client-sample). # MCP Source: https://nevermined.ai/docs/integrations/mcp Learn how to protect your MCP servers with Nevermined Payments Library. > [!NOTE] > > This is the **seller** side — you put a paywall on *your own* MCP server so its tools get paid. If instead you want an agent to **discover and pay for** Catalog services through our hosted MCP server, that's the buyer side — see the [Catalog MCP](/docs/products/catalog/mcp). > [!NOTE] > > **Are you building with an LLM?** > > If you are using an AI assistant for development, this page provides comprehensive context to streamline the integration process. Simply share this documentation URL with your LLM or copy the page content as a knowledge base. Nevermined Payments Library provides robust tools to add a paywall to your [Model Context Protocol (MCP)](https://spec.modelcontextprotocol.io/) server. This allows you to monetize your AI tools, resources, and prompts by restricting access to subscribers with valid payment plans. The integration is designed to be seamless, whether you are using a high-level framework like the official MCP SDKs or a custom low-level JSON-RPC router. * **Paywall Protection**: Wrap your handlers with `withPaywall` to automatically verify payment tokens and check for valid subscriptions. * **Credit Burning**: Automatically burn credits after a successful API call, with support for both fixed and dynamic costs. * **Declarative Registration**: Use the `attach` method to register and protect your tools in a single, clean step. * **Framework Agnostic**: Works with both high-level servers (like the official TypeScript SDK's `McpServer` or Python's `FastMCP`) and custom low-level ASGI/Express routers. ## What is MCP? As Large Language Models (LLMs) and AI agents become more sophisticated, their greatest limitation is their isolation. By default, they lack access to real-time information, private data sources, or the ability to perform actions in the outside world. The Model Context Protocol (MCP) was designed to solve this problem by creating a standardized communication layer for AI. Think of MCP as a universal language that allows any AI agent to ask a server, "What can you do?" and "How can I use your capabilities?". It turns a closed-off model into an agent that can interact with the world through a secure and discoverable interface. An MCP server essentially publishes a "menu" of its services, which can include: * **Tools**: These are concrete actions the agent can request, like sending an email, querying a database, or fetching a weather forecast. The agent provides specific arguments (e.g., `city="Paris"`) and the server executes the action. * **Resources**: These are stable pointers to data, identified by a URI. While a tool call might give a human-readable summary, a resource link (`weather://today/Paris`) provides the raw, structured data (like a JSON object) that an agent can parse and use for further tasks. * **Prompts**: These are pre-defined templates that help guide an agent's behavior, ensuring it requests information in the correct format or follows a specific interaction pattern. ## Why integrate MCP with Nevermined Payments Library? While MCP provides a powerful standard for *what* an AI agent can do, it doesn't specify *who* is allowed to do it or *how* those services are paid for. This is where Nevermined Payments Library comes in. By integrating Nevermined, you can transform your open MCP server into a secure, monetizable platform. The core idea is to place a "paywall" in front of your MCP handlers. This paywall acts as a gatekeeper, intercepting every incoming request to a tool, resource, or prompt. Before executing your logic, it checks the user's payment token to verify they have a valid subscription and sufficient credits through the Nevermined protocol. If they don't, the request is blocked. If they do, the request proceeds, and after your handler successfully completes, the paywall automatically deducts the configured number of credits. This integration allows you to build a sustainable business model around your AI services. You can offer different subscription tiers (plans), charge dynamically based on usage, and maintain a complete audit trail of every transaction, all without cluttering your core application logic with complex payment code. ## OAuth 2.1 Support for Remote MCP Servers Nevermined Payments Library implements **complete OAuth 2.1 authentication** for MCP servers, acting as both: * **OAuth Authorization Server** (RFC 8414) * **OAuth Protected Resource Server** (RFC 8414) * **OpenID Connect Provider** (OIDC Discovery 1.0) All OAuth discovery endpoints (`/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, `/.well-known/openid-configuration`) are **automatically generated and configured**. Your MCP server becomes instantly compatible with any OAuth-enabled MCP client (Claude Desktop, custom agents, etc.) without any manual OAuth setup. ## Simplified API: Complete MCP Server in Minutes The Nevermined Payments Library provides a high-level API that handles everything for you: * ✅ MCP Server creation * ✅ Express.js setup with CORS * ✅ OAuth 2.1 endpoints (auto-generated) * ✅ HTTP transport (POST/GET/DELETE `/mcp`) * ✅ Session management for streaming * ✅ Paywall protection for all tools/resources/prompts ### Quick Example Here's how to create a complete, production-ready MCP server with OAuth authentication: > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from "@nevermined-io/payments" > import { z } from "zod" > > // 1. Initialize Payments > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: "sandbox" > }) > > // 2. Register tools with built-in paywall > payments.mcp.registerTool( > "weather.today", > { > title: "Today's Weather", > description: "Get weather for a city", > inputSchema: z.object({ > city: z.string().min(2).max(80).describe("City name") > }) > }, > async (args, extra, context) => { > // Access authentication context for observability > console.log(`Request ID: ${context?.authResult.requestId}`) > console.log(`Credits charged: ${context?.credits}`) > > // Your business logic here > const weather = await fetchWeather(args.city) > > return { > content: [{ > type: "text", > text: `Weather in ${args.city}: ${weather.description}, ${weather.temp}°C` > }] > } > }, > { credits: 5n } // Fixed credits (5 per call) > ) > > // 3. Start everything (MCP Server + Express + OAuth) > const { info, stop } = await payments.mcp.start({ > port: 3000, > planId: process.env.NVM_PLAN_ID!, // required > agentId: process.env.NVM_AGENT_ID, // optional — informational only > serverName: "my-weather-server", > version: "1.0.0", > description: "Weather MCP server with OAuth authentication" > }) > > console.log(`🚀 Server running at ${info.baseUrl}/mcp`) > console.log(`🔐 OAuth endpoints: ${info.baseUrl}/.well-known/`) > console.log(`🛠️ Tools: ${info.tools.join(", ")}`) > > // Graceful shutdown > process.on("SIGINT", async () => { > await stop() > process.exit(0) > }) > ``` > [tab] Python > > ```python theme={null} > import os > from mcp.server.fastmcp import FastMCP > from payments_py import Payments, PaymentOptions > > # 1. Initialize Payments > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_API_KEY"], > environment=os.environ.get("NVM_ENVIRONMENT", "sandbox") > ) > ) > > # 2. Create MCP server with tool > fastmcp = FastMCP(name="weather-mcp", json_response=True) > > @fastmcp.tool(name="weather.today", title="Today's Weather") > async def weather_today(city: str) -> str: > return f"Weather for {city}: Sunny, 25C." > > # 3. Start with Nevermined paywall > payments.mcp.start( > fastmcp=fastmcp, > plan_id=os.environ["NVM_PLAN_ID"], # required > agent_id=os.environ.get("NVM_AGENT_ID"), # optional — informational only > port=3000 > ) > ``` > > > [!NOTE] > > > > Requires `payments-py[mcp]`: `pip install payments-py[mcp] python-dotenv` **That's it!** Your MCP server is now: * ✅ Running with OAuth 2.1 authentication * ✅ Protected by Nevermined paywall * ✅ Compatible with Claude Desktop and any MCP client * ✅ Monetizable with automatic credit deduction ### What `payments.mcp.start()` Does for You This single function call handles: 1. **Express Server Setup**: Creates and configures an Express.js application 2. **OAuth Endpoints**: Auto-generates RFC-compliant discovery endpoints: * `/.well-known/oauth-authorization-server` * `/.well-known/oauth-protected-resource` * `/.well-known/openid-configuration` * `/register` (Dynamic Client Registration - RFC 7591) 3. **MCP Transport**: Sets up HTTP transport endpoints (POST/GET/DELETE `/mcp`) 4. **Session Management**: Handles SSE streaming and session lifecycle 5. **CORS & Middleware**: Configures CORS, JSON parsing, and HTTP logging 6. **Graceful Shutdown**: Returns a `stop()` function for clean server termination ### Complete Working Example See the full production-ready example with advanced features: * **GitHub**: [weather-mcp/src/server/main.ts](https://github.com/nevermined-io/tutorials/tree/main/mcp-examples/weather-mcp) This example includes: * Dynamic credit calculation based on response size * Resources with URI templates (`weather://today/{city}`) * Prompts for LLM guidance * OpenAI observability integration ### Dynamic Credits Instead of fixed credits, you can calculate them dynamically based on the handler's result: ```typescript theme={null} // Dynamic credits based on response complexity const weatherCreditsCalculator = (ctx: CreditsContext): bigint => { const result = ctx.result as { structuredContent?: { forecast?: string } } const forecast = result?.structuredContent?.forecast || "" // Charge 1 credit for short forecasts, 2-19 for longer ones return forecast.length <= 100 ? 1n : BigInt(Math.floor(Math.random() * 18) + 2) } payments.mcp.registerTool( "weather.today", config, handler, { credits: weatherCreditsCalculator } // Function instead of fixed value ) ``` **Important:** * **Fixed credits**: Calculated BEFORE handler execution (available in `context.credits`) * **Dynamic credits**: Calculated AFTER handler execution (based on `ctx.result`) ### Client Usage **Step 1: Get Access Token** Users need to subscribe to your agent's plan and obtain an access token: ```typescript theme={null} // As a subscriber // Create a delegation once, then reuse its id to mint tokens. const { delegationId } = await paymentsClient.delegation.createDelegation({ provider: 'erc4337', // 'stripe' | 'braintree' | 'visa' for fiat plans spendingLimitCents: 10000, // $100 budget durationSecs: 604800, // 7 days currency: 'usdc', // 'usd' for fiat plans }) const { accessToken } = await paymentsClient.x402.getX402AccessToken( planId, // The plan they subscribed to undefined, // agentId is optional — informational only // scheme defaults to 'nvm:erc4337'; pass 'nvm:card-delegation' for fiat plans { scheme: 'nvm:erc4337', delegationConfig: { delegationId } } ) ``` **Step 2: Connect with MCP Client** Payment is carried **in band** in the tool-call `_meta["x402/payment"]` field, per the [x402 v2 MCP transport spec](https://github.com/coinbase/x402/blob/main/specs/transports-v2/mcp.md). Decode the access token into its `PaymentPayload` object and attach it to each paid call: ```typescript theme={null} import { Client } from "@modelcontextprotocol/sdk/client" import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp" import { decodeAccessToken } from "@nevermined-io/payments" const transport = new StreamableHTTPClientTransport( new URL("http://localhost:3000/mcp"), // The MCP session is an OAuth-protected resource: authenticate it with the // access token (without it, `initialize` returns 401). The per-call payment // is sent in band via `_meta` below. { requestInit: { headers: { Authorization: `Bearer ${accessToken}` } } } ) const client = new Client({ name: "my-client" }) await client.connect(transport) // Carry the payment in band on each paid tool call const result = await client.callTool({ name: "weather.today", arguments: { city: "Madrid" }, _meta: { "x402/payment": decodeAccessToken(accessToken) } }) ``` > [!NOTE] > > The `Authorization: Bearer ` header authenticates the MCP **session** (it's an OAuth-protected resource — `initialize` returns `401` without it), which is why it's set on the transport above. The **payment** is sent separately, in band, via `_meta["x402/payment"]`. For backwards compatibility the server also reads the payment from the header alone (no `_meta`) as a **deprecated fallback** for one release; new integrations should use the in-band `_meta` field. **Step 3: Use in Claude Desktop** Add to Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json`): ```json theme={null} { "mcpServers": { "weather": { "url": "http://localhost:3000/mcp", "auth": { "type": "bearer", "token": "YOUR_ACCESS_TOKEN_HERE" } } } } ``` *** ## Advanced Usage: Low-Level APIs > [!NOTE] > > The sections below show **advanced, low-level APIs** for users who need custom server implementations or fine-grained control. > > **For most use cases, we recommend using the simplified API above** with `payments.mcp.start()`. This advanced tutorial covers low-level APIs for building custom MCP servers. These approaches give you full control over the server implementation, but require more manual setup compared to the simplified API. ### 0) Requirements & Installation > [tab] TypeScript > > * Node.js >= 18 > * `@nevermined-io/payments` (includes everything needed) > * `zod` for schema validation > > ```bash theme={null} > npm install @nevermined-io/payments zod dotenv > npm install -D typescript @types/node ts-node > ``` > [tab] Python > > * Python >= 3.10 > * `payments-py[mcp]` (includes MCP SDK, Uvicorn, and Nevermined SDK) > > ```bash theme={null} > pip install payments-py[mcp] python-dotenv > ``` ### 1) Create a Minimal MCP Server First, let's create a basic MCP server without any paywall to ensure the core setup is working. > [tab] TypeScript > > This server uses the official MCP SDK and exposes a single tool, `weather.today`. > > ```typescript theme={null} > // server.ts > import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; > import { z } from "zod"; > > export function createMcpServer() { > const server = new McpServer({ > name: "weather-mcp", > version: "1.0.0", > }); > > server.tool( > "weather.today", > { title: "Today's Weather", inputSchema: z.object({ city: z.string() }) }, > async (args) => ({ > content: [{ type: "text", text: `Weather for ${args.city}: Sunny, 25C.` }], > }) > ); > return server; > } > ``` > [tab] Python > > This server uses `FastMCP` from the `mcp` Python library to expose the `weather.today` tool. > > ```python theme={null} > # app_fastmcp.py > from mcp.server.fastmcp import FastMCP > > fastmcp = FastMCP(name="weather-mcp", json_response=True) > > @fastmcp.tool(name="weather.today", title="Today's Weather") > async def weather_today(city: str) -> str: > return f"Weather for {city}: Sunny, 25C." > ``` ### 2) Initialize Nevermined Payments Initialize the Nevermined Payments SDK with your builder/agent owner API key and environment. > [tab] TypeScript > > ```typescript theme={null} > // payments-setup.ts > import { Payments, EnvironmentName } from "@nevermined-io/payments"; > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: (process.env.NVM_ENVIRONMENT as EnvironmentName) || "sandbox", > }); > ``` > > > [!NOTE] > > > > When using low-level APIs, you may need to call `payments.mcp.configure()` to set defaults. > > With the simplified API (`payments.mcp.start()`), configuration is handled automatically. > [tab] Python > > ```python theme={null} > # payments_setup.py > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ["NVM_API_KEY"], environment=os.environ.get("NVM_ENV", "sandbox")) > ) > ``` ### 3) Dynamic Credits (Optional) Instead of charging fixed credits, you can calculate them dynamically based on input arguments or response content. #### Understanding CreditsContext When using a function for `credits`, it receives a `CreditsContext` object with: ```typescript theme={null} interface CreditsContext { args: unknown // Input arguments passed to the tool/resource/prompt result: any // The response returned by your handler request: { authHeader: string // Authorization Bearer token logicalUrl: string // Full MCP logical URL (e.g., "mcp://server/tools/weather") toolName: string // Name of the tool/resource/prompt } } ``` **Key Properties:** * **`ctx.args`**: The input arguments the user sent (e.g., `{ city: "London" }`) * **`ctx.result`**: The complete response your handler returned * **`ctx.request.toolName`**: The name of the tool being called * **`ctx.request.logicalUrl`**: The full logical URL for observability * **`ctx.request.authHeader`**: The auth token (for advanced logging) #### Examples > [tab] Based on Response Size > > Charge credits proportional to the response length: > > ```typescript theme={null} > import type { CreditsContext } from "@nevermined-io/payments" > > const dynamicCredits = (ctx: CreditsContext): bigint => { > // Access the result returned by your handler > const result = ctx.result as { content: Array<{ text: string }> } > const text = result.content[0]?.text || "" > > // Charge 1 credit per 100 characters > const credits = Math.ceil(text.length / 100) > return BigInt(credits) > } > > payments.mcp.registerTool( > "weather.today", > config, > handler, > { credits: dynamicCredits } > ) > ``` > [tab] Based on Input Arguments > > Charge different rates based on input complexity: > > ```typescript theme={null} > const dynamicCredits = (ctx: CreditsContext): bigint => { > // Access input arguments > const args = ctx.args as { city: string; forecast_days?: number } > > // Base cost: 5 credits > let credits = 5n > > // Add 2 credits per additional forecast day > if (args.forecast_days && args.forecast_days > 1) { > credits += BigInt((args.forecast_days - 1) * 2) > } > > return credits > } > > payments.mcp.registerTool( > "weather.forecast", > config, > handler, > { credits: dynamicCredits } > ) > ``` > [tab] Conditional Pricing > > Apply different pricing models based on result type: > > ```typescript theme={null} > const dynamicCredits = (ctx: CreditsContext): bigint => { > const result = ctx.result as { > structuredContent?: any > rawData?: any > } > > // Structured responses cost more > if (result.structuredContent) { > return 10n > } > > // Raw data costs less > if (result.rawData) { > return 3n > } > > // Default > return 5n > } > ``` > [tab] Python > > ```python theme={null} > def dynamic_credits(ctx: Dict[str, Any]) -> int: > # Access arguments > args = ctx.get("args", {}) > city = args.get("city", "") > > # Access result > result = ctx.get("result", {}) > content = result.get("content", []) > text = content[0].get("text", "") if content else "" > > # Calculate based on response length > return max(1, len(text) // 100) > > payments.mcp.registerTool( > "weather.today", > config, > handler, > {"credits": dynamic_credits} > ) > ``` **Important:** * ✅ **Fixed credits** (`credits: 5n`): Calculated BEFORE handler execution, available in `context.credits` * ✅ **Dynamic credits** (function): Calculated AFTER handler execution, based on `ctx.args` and `ctx.result` * ✅ **Return type**: Must return `bigint` (TypeScript) or `int` (Python) * ⚠️ **Performance**: Keep calculations lightweight to avoid delays ### 4) Connecting MCP Clients Once your server is running with `payments.mcp.start()`, connecting clients is straightforward. **Nevermined handles OAuth authentication automatically** - clients just need to know the server URL. #### Claude Desktop Add to your Claude Desktop config file: * **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` * **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` ```json theme={null} { "mcpServers": { "weather": { "url": "http://localhost:3000/mcp", "type": "http" } } } ``` #### Cursor IDE Add to your Cursor MCP config file: * **Location**: `~/.cursor/mcp.json` ```json theme={null} { "mcpServers": { "weather": { "url": "http://localhost:3000/mcp", "type": "http" } } } ``` #### Custom MCP Client (TypeScript/JavaScript) ```typescript theme={null} import { Client } from "@modelcontextprotocol/sdk/client" import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp" import { decodeAccessToken } from "@nevermined-io/payments" // The MCP session is an OAuth-protected resource: authenticate it with the // access token (without it, `initialize` returns 401). See "Client Usage" above // for how to obtain `accessToken`. const transport = new StreamableHTTPClientTransport( new URL("http://localhost:3000/mcp"), { requestInit: { headers: { Authorization: `Bearer ${accessToken}` } } } ) const client = new Client({ name: "my-client", version: "1.0.0" }) await client.connect(transport) // For PAID tools, carry the payment in band on each call. const result = await client.callTool({ name: "weather.today", arguments: { city: "Madrid" }, _meta: { "x402/payment": decodeAccessToken(accessToken) } }) console.log(result) ``` #### How OAuth Works Behind the Scenes When a client connects to your MCP server: 1. **Discovery**: Client reads `/.well-known/oauth-authorization-server` to find OAuth endpoints 2. **Registration**: Client registers itself via `/register` (dynamic client registration) 3. **Authorization**: Client obtains access token via OAuth 2.1 flow 4. **Authenticated Requests**: All subsequent MCP requests include the token automatically **You don't need to handle any of this manually** - `payments.mcp.start()` configures everything automatically! > [!NOTE] > > **The consent screen is per API tier.** The human approves at `https://nevermined.app/oauth/authorize`, and the Nevermined API advertises that endpoint **with the tier on it** — `?network=sandbox` from `api.sandbox.nevermined.app`, `?network=live` from `api.live.nevermined.app` — because the web app otherwise opens on whichever tier the user's browser last used (Live by default). If you wire an MCP client or an OAuth provider to Nevermined **by hand** instead of through discovery, use the tier-qualified endpoint from the tier's [`/.well-known/oauth-authorization-server`](/docs/integrate/authentication/overview#each-tier-is-its-own-issuer-and-its-authorize-url-says-so), query string included — it must end up as `…/oauth/authorize?network=sandbox` or `…?network=live`; if the document you fetch carries no `network`, append it yourself. > > The discovery document your **own** MCP server serves (step 1 above) comes from the SDK, not from the API — and until [payments#447](https://github.com/nevermined-io/payments/issues/447) / [payments-py#277](https://github.com/nevermined-io/payments-py/issues/277) ship, it still advertises a tier-blind `authorization_endpoint`. Until then, override **just that field** with the API tier's endpoint above and keep the rest of your server's document — its `token_endpoint` already names the right tier, and its `registration_endpoint` (`/register`, step 2 above) exists only there. > [!NOTE] > > **Which consent the human sees, and how the client knows who answered.** A client that reached the consent page through discovery never saw `?consent_type=` — the tier's `authorization_endpoint` carries only `network`. Such a client selects the consent with the standard `scope` parameter, which MCP clients forward from the server's `WWW-Authenticate` challenge: `scope=commerce` opens the **commerce** consent (an account-level spend cap the user funds from their Nevermined wallet, for paying external services through the Router — no `agent_id`), while a request that names an `agent_id` gets the agent-specific plan consent this page describes. An explicit `consent_type` on the URL is kept as long as `scope` does not contradict it, so a provider you configure by hand (LangSmith Fleet's Agent-Auth) keeps its `?consent_type=commerce`; a URL that contradicts itself (`consent_type=account_access&scope=commerce`, or `scope=commerce` with an `agent_id`) is refused rather than guessed. Nevermined publishes no `scopes_supported` in its own document — the API enforces no scope vocabulary; `scope` only picks the screen. > > Whichever screen it was, the redirect back to the client — the `code` on approval, the `error` on denial — carries **`iss`**, the RFC 9207 issuer identifier, equal to the tier document's `issuer`; the document advertises it with `authorization_response_iss_parameter_supported: true`. A conforming client compares it with the issuer it discovered and rejects a mismatch. ChatGPT, for one, presents its stable `https://chatgpt.com/oauth/client.json` client identity only to an authorization server that does this — see [the overview](/docs/integrate/authentication/overview#the-authorization-response-names-its-issuer-rfc-9207). > [!NOTE] > > **For production servers**, replace `http://localhost:3000` with your public domain (e.g., `https://weather-mcp.yourdomain.com`). *** ## Advanced Usage > [!NOTE] > > The methods below are for advanced use cases requiring custom server setup. For most applications, use the simplified `payments.mcp.start()` approach shown above. ### Using `withPaywall` for Custom Servers If you're building a custom MCP server and want granular control, use `withPaywall`. Call `payments.mcp.configure({ planId })` first — `withPaywall` (and `attach`) require a `planId` and throw at registration time if none is set: ```typescript theme={null} const protectedHandler = payments.mcp.withPaywall( myHandler, { kind: "tool", name: "my.tool", credits: 5n } ) ``` ### Using `attach` for Declarative Registration ```typescript theme={null} const server = new McpServer({ name: "my-server", version: "1.0.0" }) const registrar = payments.mcp.attach(server) registrar.registerTool( "weather.today", config, handler, { credits: 1n } ) ``` ### Custom Low-Level Server > [!WARNING] > > **Only for advanced use cases.** Most users should use `payments.mcp.start()`. For custom Express servers, you can use `payments.mcp.createApp()`: > [tab] TypeScript > > ```typescript theme={null} > // custom-server.ts > import { Payments } from "@nevermined-io/payments" > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: "sandbox" > }) > > payments.mcp.configure({ > planId: process.env.NVM_PLAN_ID!, // required > serverName: "custom-server", > agentId: process.env.NVM_AGENT_ID, // optional — informational only > }) > > const app = payments.mcp.createApp({ > planId: process.env.NVM_PLAN_ID!, // required > baseUrl: "http://localhost:3000", > serverName: "custom-server", > tools: ["weather.today"] > }) > > // Add your custom JSON-RPC routing > app.post("/mcp", async (req, res) => { > const { method, params } = req.body > > // Build extra object from request > const extra = { > requestInfo: { > headers: req.headers, > method: req.method, > url: req.url > } > } > > // Route to handler and pass extra > if (method === "tools/call") { > const handler = getToolHandler(params.name) > const result = await handler(params.arguments, extra) > res.json({ jsonrpc: "2.0", id: req.body.id, result }) > } > }) > > app.listen(3000, () => { > console.log("Custom server running on http://localhost:3000") > }) > ``` > [tab] Python > > For complete custom control with ASGI: > > ```python theme={null} > # lowlevel_app.py > from payments_py.mcp import build_extra_from_http_headers > > async def app(scope, receive, send): > # Parse request > headers = {k.decode(): v.decode() for k, v in scope.get("headers", [])} > extra = build_extra_from_http_headers(headers) > > # Read body... > body = await receive() > req = json.loads(body.get("body", b"{}")) > > # Route and call handler > if req.get("method") == "tools/call": > handler = get_tool_handler(req["params"]["name"]) > result = await handler(req["params"]["arguments"], extra) > # Send response... > ``` *** ## Error Handling Payment-required is signaled **in band**, not as an HTTP `402`. For **tools**, a missing/invalid token (or unmet subscription) returns an **error tool result** — `isError: true` with the `PaymentRequired` object in `structuredContent` and its JSON string in `content[0].text` — rather than throwing. **Resources and prompts** have no tool-result error channel, so they raise a JSON-RPC error with the codes below (`-32003` is also exposed on the error object for tools). | Error Code | Description | | - | - | | `-32003` | Payment Required - No token / Invalid token / Insufficient credits | | `-32002` | Misconfiguration - Server setup error | | `-32603` | Internal Error - Handler execution failed | *** ## Full Code Examples ### Production-Ready Example The **Weather MCP Server** is a complete, production-ready example that demonstrates all features: * **Repository**: [tutorials/mcp-examples/weather-mcp](https://github.com/nevermined-io/tutorials/tree/main/mcp-examples/weather-mcp) * **Main Server**: [weather-mcp/src/server/main.ts](https://github.com/nevermined-io/tutorials/blob/main/mcp-examples/weather-mcp/src/server/main.ts) **Features demonstrated:** * ✅ Complete OAuth 2.1 authentication with `payments.mcp.start()` * ✅ Tools with dynamic credit calculation based on response size * ✅ Resources with URI templates (`weather://today/{city}`) * ✅ Prompts for LLM guidance * ✅ OpenAI integration with Nevermined observability * ✅ Graceful shutdown handling * ✅ Environment-based configuration ### Additional Examples Advanced and low-level API examples: * **TypeScript (Low-level)**: [nevermined-io/weather-mcp-demo](https://github.com/nevermined-io/weather-mcp-demo) - Examples using `withPaywall` and `attach` for custom servers * **Python**: [nevermined-io/weather-mcp-demo-py](https://github.com/nevermined-io/weather-mcp-demo-py) - Python implementation with FastMCP # Nevermined x402 and Google AP2 Source: https://nevermined.ai/docs/integrations/nevermined-x402-ap2 Run the ADK demo to combine Nevermined x402 payments with Google AP2/A2A messaging—covering session tokens, facilitator verify/settle, and AP2 payment intents. This guide shows how the ADK demo wires Nevermined x402 payments into Google AP2/A2A messaging. It reuses the core primitives (plan + agent + session token + facilitator) and transports them over AP2 messages between a client agent and a merchant server. Source: [ADK demo README](https://github.com/nevermined-io/a2a-x402/tree/feat/a2a-nvm/python/examples/adk-demo#readme). ## What this covers * Uses the `python/examples/adk-demo` from `a2a-x402` ([demo repo](https://github.com/nevermined-io/a2a-x402/tree/feat/a2a-nvm)) * Client agent (subscriber) generates x402 session tokens * Merchant server verifies and settles via Nevermined facilitator over REST * AP2 carries `payment-required` and `payment-submitted` messages between agents * Real on-chain credit burns on Base Sepolia (sandbox) ## Prerequisites * Nevermined API keys: one for the merchant (`NVM_API_KEY_SERVER`), one for the subscriber (`NVM_API_KEY_CLIENT`) * A credits plan and agent registered in Nevermined (`NVM_CREDITS_PLAN_ID`, `NVM_AGENT_ID`) * Python 3.11+, `uv` (for the demo env) * Google GenAI API key (for the AP2/ADK flow) ## Configure the demo From the root of `a2a-x402`: ```bash theme={null} uv sync --directory=python/examples/adk-demo cp python/examples/adk-demo/.env.sample python/examples/adk-demo/.env ``` Set the key environment variables (sandbox defaults): ```bash theme={null} NVM_API_KEY_SERVER="nvm:merchant-jwt" NVM_API_KEY_CLIENT="nvm:subscriber-jwt" NVM_ENVIRONMENT="sandbox" NVM_CREDITS_PLAN_ID="your-plan-id" NVM_AGENT_ID="your-agent-id" NVM_PAYMENT_AMOUNT="2" NVM_NETWORK="base-sepolia" GOOGLE_GENAI_API_KEY="your-google-api-key" ``` Key roles (from the README): * **Client Agent (subscriber)**: Generates x402 session tokens using `payments_py`. * **Merchant Server (agent)**: Serves AP2 `payment-required`, verifies/settles via Nevermined facilitator. * **Facilitator**: Nevermined service that enforces permissions and burns/orders credits. * **Blockchain**: Executes the settlement transactions (Base Sepolia in sandbox). ## Run it 1. Start the merchant server (facilitator + AP2 handler): ```bash theme={null} uv --directory=python/examples/adk-demo run server ``` 2. Start the client agent + web UI: ```bash theme={null} uv --directory=python/examples/adk-demo run adk web --port=8000 ``` 3. In the UI, trigger a purchase (e.g., “buy a laptop”). The flow: * Merchant replies with AP2 `payment-required` (plan/agent/amount/network) * Client **generates x402 session token** via Nevermined (`payments_py.x402.get_x402_access_token`) * Client sends `payment-submitted` carrying the x402 payload + Nevermined extension * Merchant **verifies** with facilitator → does the work → **settles** (burns credits) * Response includes receipt + transaction hash; balance decrements (e.g., 10 → 8) ## Message shapes (adapted from the README) * `payment-required`: * Includes plan\_id, agent\_id, amount, network, scheme, and any metadata the merchant wants to expose. * `payment-submitted`: * Carries the x402 payload with `session_key` plus the copied Nevermined extension. * `payment-completed`: * Contains the facilitator’s verification/settlement result and transaction hash. ## Key SDK touchpoints * Session token generation (subscriber): ```python theme={null} from payments_py.x402 import X402TokenOptions, DelegationConfig, CreateDelegationPayload # Create a delegation once, then reuse its id to mint tokens. delegation = payments.delegation.create_delegation( CreateDelegationPayload( provider="erc4337", # "stripe" | "braintree" | "visa" for fiat plans spending_limit_cents=10000, # $100 budget duration_secs=604800, # 7 days currency="usdc", # "usd" for fiat plans ) ) token_res = payments.x402.get_x402_access_token( plan_id, agent_id, token_options=X402TokenOptions( delegation_config=DelegationConfig(delegation_id=delegation.delegation_id) ), ) session_key = token_res["accessToken"] ``` * Facilitator verification + settlement (merchant): ```python theme={null} verification = payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=access_token, ) if not verification.is_valid: raise Exception("Payment Required") payments.facilitator.settle_permissions( payment_required=payment_required, x402_access_token=access_token, ) ``` ## When to use this pattern * You need AP2/A2A messaging but want enforceable on-chain payments * You want to keep REST facilitators for verification/settlement while agents talk over AP2 * You need a working reference with real settlement (Base Sepolia) that mirrors the library E2E tests ## Links * Demo repo: [https://github.com/nevermined-io/a2a-x402/tree/feat/a2a-nvm](https://github.com/nevermined-io/a2a-x402/tree/feat/a2a-nvm) * Demo README: [https://github.com/nevermined-io/a2a-x402/tree/feat/a2a-nvm/python/examples/adk-demo#readme](https://github.com/nevermined-io/a2a-x402/tree/feat/a2a-nvm/python/examples/adk-demo#readme) # OpenClaw Source: https://nevermined.ai/docs/integrations/openclaw Integrate Nevermined payments into OpenClaw gateways to monetize AI agents from Telegram, Discord, WhatsApp, and any chat channel. Nevermined integrates with [OpenClaw](https://openclaw.ai) to bring AI agent payments directly into messaging platforms. Install the plugin on an OpenClaw gateway and every connected channel gains full access to the Nevermined payment infrastructure: * **Chat-native payments**: subscribers order plans, check balances, and query paid agents from Telegram, Discord, WhatsApp, or any other connected channel. * **x402 built in**: the plugin handles the full payment lifecycle — token acquisition, permission verification, and credit settlement — automatically. * **Builder and subscriber tools**: 7 payment tools and 2 slash commands cover both sides of the marketplace, from agent registration to paid queries. * **Paid HTTP endpoint**: enable a single config flag and the gateway exposes an x402-compatible endpoint that verifies, processes, and settles requests without custom code. ## Architecture ```mermaid theme={null} sequenceDiagram participant User participant Gateway as OpenClaw Gateway participant Nevermined User->>Gateway: Send message from chat channel Gateway->>Nevermined: getAccessToken(planId, agentId) Nevermined-->>Gateway: x402 access token Gateway->>Nevermined: POST /agent + payment-signature Nevermined->>Nevermined: verifyPermissions → settle credits Nevermined-->>Gateway: Agent response + payment-response Gateway-->>User: Return response in chat ``` ## Features The [Nevermined OpenClaw plugin](https://github.com/nevermined-io/openclaw-plugin) provides a complete set of tools for both builders and subscribers: * **Payment Signature Authentication**: the paid endpoint extracts access tokens from the `payment-signature` header and verifies them against Nevermined. * **Credit Verification and Settlement**: validates subscriber balance before processing and burns credits only after successful execution. * **Multi-Channel Support**: one plugin instance handles payments across every channel your OpenClaw gateway connects to. * **Agent Registration from Chat**: register agents and create payment plans directly from any messaging channel — no dashboard required. * **Flexible Pricing**: supports fiat (Stripe/USD), ERC20 tokens (USDC), and native cryptocurrency payment plans. * **Balance Awareness**: when configured, the plugin injects the current credit balance into the agent's context so your Claw can proactively warn users about low credits. ## Quickstart **1. 1. Get Your API Key** To interact with the Nevermined API, you need an API key. Follow the [Get Your API Key](/docs/agents-guide/get-api-key) guide to create one. **2. 2. Install the Plugin** From your OpenClaw gateway server: ```bash theme={null} openclaw plugin install @nevermined-io/openclaw-plugin ``` Restart the gateway after installation: ```bash theme={null} openclaw gateway restart ``` You should see in the logs: ``` Registered 7 Nevermined payment tools ``` **3. 3. Authenticate** Send `/nvm_login` from any connected chat channel to authenticate with your Nevermined account. ``` /nvm_login ``` This opens a browser window for authentication. The API key is captured and stored automatically. For headless servers, pass the key directly: ``` /nvm_login sandbox:eyJhbG... ``` Use `sandbox` for testing, `live` for production. ## Register an Agent and Payment Plan Once authenticated, register your agent directly from chat. Send a message like: > Register a Nevermined agent called "Legal Assistant" at URL `https://my-gateway.example.com/nevermined/agent` with a plan named "Legal Queries" priced at 1000000 to address `0xYourWalletAddress` with token `0x036CbD53842c5426634e7929541eC2318f3dCF7e` granting 10 credits. The gateway calls `nevermined_registerAgent` and returns an `agentId` and `planId`. Save these for configuration. ### Enable the Paid Endpoint Add the returned IDs to your gateway config (`~/.openclaw/openclaw.json`) and enable the paid endpoint: ```json theme={null} { "plugins": { "entries": { "nevermined": { "enabled": true, "config": { "nvmApiKey": "sandbox:eyJhbG...", "environment": "sandbox", "planId": "", "agentId": "", "enablePaidEndpoint": true, "agentEndpointPath": "/nevermined/agent", "creditsPerRequest": 1 } } } } } ``` Restart the gateway. The paid endpoint handles the full x402 lifecycle automatically: 1. Extracts the `payment-signature` header from incoming requests 2. Calls `verifyPermissions` to check the subscriber has credits 3. Processes the request through your agent handler 4. Calls `settlePermissions` to burn credits 5. Returns the response with a `payment-response` header ## Query a Paid Agent From the subscriber side (same or different gateway), the full flow works from chat: **Order a plan:** > Order the Legal Assistant plan `` The gateway calls `nevermined_orderPlan` and credits are granted. **Query the agent:** > Ask the Legal Assistant at `https://my-gateway.example.com/nevermined/agent` to summarize the latest GDPR amendments The gateway calls `nevermined_queryAgent`, which acquires an x402 token, sends the prompt with a `payment-signature` header, and returns the response — all in one step. **Check your balance:** > Check my Nevermined balance for plan `` Credits are decremented after each successful query. ## Custom Agent Handlers The plugin includes a default handler for demonstration. To use your own logic, pass a custom `agentHandler` when registering the plugin: ```typescript theme={null} import neverminedPlugin from '@nevermined-io/openclaw-plugin' neverminedPlugin.register(api, { agentHandler: async (body) => { const response = await myAIModel.generate(body.prompt) return { result: response } }, }) ``` The handler receives `{ prompt: string }` and returns any JSON-serializable object. ## Learn More > [card] [Getting Started](/docs/api-reference/openclaw-plugin/getting-started) > > Install and configure the plugin > [card] [Setup](/docs/api-reference/openclaw-plugin/setup) > > Full configuration reference > [card] [Commands](/docs/api-reference/openclaw-plugin/commands) > > All tools and slash commands > [card] [Build a Paid Agent](/docs/api-reference/openclaw-plugin/guide) > > Step-by-step tutorial # Embed Nevermined Widgets Source: https://nevermined.ai/docs/integrations/organization-widgets Drop Nevermined checkout, card enrollment, and delegation flows into your own site as iframes signed by your organization. If you run a Nevermined organization, you can embed Nevermined-hosted UI flows directly into your site instead of redirecting customers to nevermined.app. Your end-users stay on your domain; the iframe handles auth, payments, and card delegations against the Nevermined backend. > [!NOTE] > > This guide is for organization admins. If you haven't upgraded to an organization yet, see [Platform Partners](/docs/integrations/organizations) first. ## What you can embed > [card] Checkout > > Sell an agent's plans — or a standalone plan with no agent — from your own pricing page. > [card] Card enrollment > > Let users add a payment method without leaving your site. Returns the resulting `paymentMethodId`. > [card] Card delegation > > List enrolled cards, create delegations, and revoke either — without redirecting to nevermined.app. ## How it works ``` Your server → createWidgetSession({ email, orgId, rawSecret, apiBaseUrl }) → WidgetSession (2-hour JWT + bearer credential) Browser → NeverminedWidgets.initialize({ session, environment }) → mounts iframe(s) directly — no token-exchange call Iframe → postMessage events: nvm:ready, nvm:success, nvm:error, nvm:close ``` The widget secret never leaves your server. The integrator backend POSTs `{ email, orgId, rawSecret }` to the Nevermined API server-to-server; the API hashes the candidate and constant-time compares against the SHA-256 of the keys you generated in the dashboard, then returns a 2-hour `WidgetSession` your backend forwards verbatim to the browser SDK. > [!WARNING] > > The `rawSecret` is the equivalent of a password for your organization's widget surface. Anyone who has it can mint sessions as any end-user of your org. Keep it in environment variables on a server you control — never commit it, never bundle it into client-side JavaScript. The API only ever stores its SHA-256; if you lose the raw value, revoke the key in the dashboard and generate a new one. ## Setup **1. Generate a widget key** Open [Settings > Organization](https://nevermined.app/organization) in the Nevermined App and scroll to the **Widget Integration** section. ![Widget Integration section before any key exists](https://mintcdn.com/neverminedag/f7Qu2t-dWYhQ_R-j/images/widgets/widget-integration-empty.png?fit=max\&auto=format\&n=f7Qu2t-dWYhQ_R-j\&q=85\&s=d1cfcda987887780f235809e22709001) Click **Generate widget key** and fill in the dialog: * **Name** — a descriptive label, e.g. `Production website`. * **Allowed origins** — every domain where the widget will be mounted, e.g. `https://yourcompany.com` and `https://staging.yourcompany.com`. At least one origin is required. Use **Add origin** to add more rows. No path, query, fragment, or trailing slash. ![Generate widget key dialog with name and allowed origins](https://mintcdn.com/neverminedag/f7Qu2t-dWYhQ_R-j/images/widgets/generate-key-dialog.png?fit=max\&auto=format\&n=f7Qu2t-dWYhQ_R-j\&q=85\&s=7e3cb14ccd0195e10784efd7ad3b9fb0) The Nevermined backend rejects widget sessions whose `parentOrigin` doesn't match this allowlist — it's your second line of defense if the secret ever leaks. You can edit the list later from the key's actions menu without rotating the secret. Click **Generate key**. The raw secret is shown **once**. Copy it and store it as an environment variable on your server (for example, `NVM_WIDGET_SECRET`). You won't see it again. ![Widget secret shown once after creation](https://mintcdn.com/neverminedag/f7Qu2t-dWYhQ_R-j/images/widgets/key-secret-shown.png?fit=max\&auto=format\&n=f7Qu2t-dWYhQ_R-j\&q=85\&s=d7fa5b923bd02274cf59c4f70d5e7020) > [!WARNING] > > If you lose the secret, revoke the key from the dashboard and generate a new one. There's no recovery path — that's by design. **2. Mint the widget session on your server** Install the server SDK on your backend and expose a small endpoint that mints a `WidgetSession` for the currently logged-in end-user. ```bash theme={null} npm install @nevermined-io/ui-widgets-server ``` The call is the same regardless of framework: ```ts theme={null} import { createWidgetSession } from '@nevermined-io/ui-widgets-server' const session = await createWidgetSession({ email: '', orgId: '', rawSecret: process.env.NVM_WIDGET_SECRET!, apiBaseUrl: 'https://api.sandbox.nevermined.app', // or live URL }) ``` Pick the framework that matches your stack: > [tab] Vite middleware > > ```ts theme={null} > // vite.config.ts > import { defineConfig } from 'vite' > > export default defineConfig({ > plugins: [ > { > name: 'nvm-widget-session', > configureServer(server) { > // POST-only: the response carries a bearer credential, so > // the endpoint must not be cacheable / prefetch-friendly. > server.middlewares.use('/api/widget-session', async (req, res) => { > if (req.method !== 'POST') { > res.statusCode = 405 > res.setHeader('allow', 'POST') > res.end() > return > } > const { createWidgetSession } = await import('@nevermined-io/ui-widgets-server') > const session = await createWidgetSession({ > email: req.headers['x-user-email'] as string, // resolve from your auth > orgId: process.env.NVM_ORG_ID!, > rawSecret: process.env.NVM_WIDGET_SECRET!, > apiBaseUrl: process.env.NVM_API_BASE_URL!, > }) > res.setHeader('content-type', 'application/json') > res.setHeader('cache-control', 'no-store') > res.end(JSON.stringify({ session, environment: 'sandbox' })) > }) > }, > }, > ], > }) > ``` > [tab] Express > > ```ts theme={null} > import express from 'express' > import { createWidgetSession } from '@nevermined-io/ui-widgets-server' > > const app = express() > > // POST-only + `Cache-Control: no-store`: the response is a bearer > // credential and must not be cached or prefetched. > app.post('/api/widget-session', async (req, res) => { > const session = await createWidgetSession({ > email: req.user!.email, // from your auth middleware > orgId: process.env.NVM_ORG_ID!, > rawSecret: process.env.NVM_WIDGET_SECRET!, > apiBaseUrl: process.env.NVM_API_BASE_URL!, > }) > res.setHeader('cache-control', 'no-store') > res.json({ session, environment: 'sandbox' }) > }) > ``` > [tab] Next.js Route Handler > > ```ts theme={null} > // app/api/widget-session/route.ts — POST-only handler. > import { NextResponse } from 'next/server' > import { createWidgetSession } from '@nevermined-io/ui-widgets-server' > import { auth } from '@/lib/auth' > > export async function POST() { > const authSession = await auth() > if (!authSession?.user?.email) { > return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) > } > const session = await createWidgetSession({ > email: authSession.user.email, > orgId: process.env.NVM_ORG_ID!, > rawSecret: process.env.NVM_WIDGET_SECRET!, > apiBaseUrl: process.env.NVM_API_BASE_URL!, > }) > // Stop caches / prefetchers from snapshotting the bearer credential. > return NextResponse.json( > { session, environment: 'sandbox' }, > { headers: { 'cache-control': 'no-store' } }, > ) > } > ``` > [!NOTE] > > `email` identifies the **end-user of your site**, not the org admin. Resolve it from your auth session — Nevermined uses it as the canonical identity for the widget user (the same email logging in directly at nevermined.app resolves to the same Privy user, wallet and profile). **3. Mount the widget in the browser** Install the browser SDK on your frontend. ```bash theme={null} npm install @nevermined-io/ui-widgets ``` Fetch the `session` from your endpoint with a `POST` (the server side mints a bearer credential — `GET` would risk caching/prefetching it) and pass it straight to the SDK. The same `nvm` instance can mount any of the available widgets. ```ts theme={null} import { NeverminedWidgets } from '@nevermined-io/ui-widgets' const { session, environment } = await fetch('/api/widget-session', { method: 'POST', credentials: 'same-origin', // forward your app's auth cookies }).then((r) => r.json()) const nvm = await NeverminedWidgets.initialize({ session, environment }) ``` Then mount whichever widget you need into a container element on your page: Each `onSuccess` receives a single `event` object: `event.result` holds the flow's result fields and `event.handle.close()` dismisses the iframe. The widget **stays mounted on success** (showing its success state) until you call `handle.close()` — there is no auto-dismiss. > [tab] Checkout (agent) > > Sell a specific agent's plans. Pass the agent `did`; `planId` is optional — omit it to show the plan carousel. > > ```ts theme={null} > nvm.checkout.start({ > did: 'did:nv:', > planId: 'plan-', // omit to show the plan carousel > container: document.getElementById('checkout-widget')!, > onReady: () => console.log('Widget rendered'), > onSuccess: ({ result, handle }) => { > // result: { did: string; planId?: string; txHash?: string } > console.log('Purchase complete', result) > handle.close() // dismiss when your post-purchase UI is ready > }, > onError: (err) => console.error('Checkout failed', err), > onClose: () => console.log('User closed the widget'), > }) > ``` > [tab] Checkout (plan only) > > Sell a plan that isn't tied to a specific agent — mirrors the public `/checkout/plan/:planId` page. No `did` required. > > ```ts theme={null} > nvm.checkout.startPlan({ > planId: 'plan-', > container: document.getElementById('checkout-widget')!, > onSuccess: ({ result, handle }) => { > // result: { planId: string; txHash?: string } > console.log('Purchase complete', result) > handle.close() > }, > onError: (err) => console.error('Checkout failed', err), > }) > ``` > [tab] Enroll a card > > ```ts theme={null} > nvm.delegations.enrollCard({ > container: document.getElementById('enroll-widget')!, > provider: 'stripe', // 'stripe' | 'braintree' | 'visa' — defaults to 'stripe' > onSuccess: ({ result, handle }) => { > console.log('Card enrolled', result.paymentMethodId) > handle.close() > }, > onError: (err) => console.error('Enrollment failed', err), > }) > ``` > [tab] List & delegate > > ```ts theme={null} > nvm.delegations.listCards({ > container: document.getElementById('cards-widget')!, > onCardAction: ({ action, paymentMethodId }) => { > // action: 'delegate' (user wants to delegate this card) | 'revoked' (removed inline) > if (action === 'delegate') { > nvm.delegations.createDelegation({ > paymentMethodId, > container: document.getElementById('cards-widget')!, > onSuccess: ({ result, handle }) => { > console.log('Delegated', result.delegationId) > handle.close() > }, > }) > } > }, > }) > ``` > [!NOTE] > > Every iframe-mounting method also accepts optional `width` / `height` (pixels) for inline sizing — the SDK clamps them to a supported range; omit them for the default overlay. ## Available widgets | Method | Mounts iframe | Result | | - | - | - | | `nvm.checkout.start({ did, planId?, container, ... })` | yes | `onSuccess` → `event.result`: `{ did, planId?, txHash? }` | | `nvm.checkout.startPlan({ planId, container, ... })` | yes | `onSuccess` → `event.result`: `{ planId, txHash? }` | | `nvm.delegations.enrollCard({ container, provider?, ... })` | yes | `onSuccess` → `event.result`: `{ paymentMethodId }` | | `nvm.delegations.listCards({ container, onCardAction, ... })` | yes | `onCardAction`: `{ action: 'delegate' \| 'revoked', paymentMethodId }` | | `nvm.delegations.createDelegation({ paymentMethodId, container, ... })` | yes | `onSuccess` → `event.result`: `{ delegationId, paymentMethodId }` | | `await nvm.delegations.revokeCard(paymentMethodId)` | no — direct API call | resolves on 2xx | | `await nvm.delegations.revokeDelegation(delegationId)` | no — direct API call | resolves on 2xx | All iframe-mounting methods share the same lifecycle: | Callback | When | | - | - | | `onBooted` | iframe DOM mounted (auth not yet validated) | | `onReady` | session validated, widget interactive | | `onSuccess(event)` | flow succeeded — the widget **stays mounted** in its success state; call `event.handle.close()` to dismiss it | | `onError` | terminal error — widget destroys itself | | `onClose` | widget dismissed (the user closed it, or you called `event.handle.close()`) — instance destroyed | > [!NOTE] > > A widget instance is single-use. Once it reaches a terminal state — you call `event.handle.close()` after success, or it fires `onError` / `onClose` — calling its method again throws. Construct a fresh widget via the same `nvm` instance to mount another flow. ## Redirect / CLI mode (no iframe) For integrations that aren't an in-page iframe — a CLI tool, or any flow where you'd rather hand the user to a full-page Nevermined screen and get them back via a callback — open the embed route as a **top-level browser navigation** instead of mounting it through the SDK. You pass a `sessionToken` and a `returnUrl` on the query string. The page runs the same flow and, on success, redirects the browser to `returnUrl` with the result IDs (plus your `state` echo) appended as query parameters — the same shape as an OAuth callback. These pages are served by the dedicated **embed app** (`https://embed.nevermined.app` in production, `https://embed.nevermined.dev` on staging, `http://localhost:4250` in local dev) — the same origin the SDK mounts in iframe mode. Supported on the card flows and plan-only checkout; the **agent checkout (`/checkout/$did`) is iframe-only**. | Route (on the embed app) | Result params appended to `returnUrl` | | - | - | | `/cards/setup` | `paymentMethodId`, `delegationId` | | `/cards/enroll` | `paymentMethodId` | | `/cards/delegate` | `delegationId` | | `/checkout/plan/` | `planId`, `paymentIntent` | ### Minting a session for redirect mode * **CLI / logged-in Nevermined user** — `POST {apiBaseUrl}/api/v1/widgets/session/self` with the user's Nevermined credential and the `orgId` (the user must be a member of the org). Self-mint sessions only accept **localhost** `returnUrl`s — the CLI listens on a local port. * **Hosted site** — mint with the same server-side `createWidgetSession` as the iframe flow; the `returnUrl` must belong to the widget key's `allowedOrigins`. ### Example ```text theme={null} https://embed.nevermined.app/cards/setup ?sessionToken= &returnUrl=http://localhost:8976/callback &state= ``` On success the browser lands on: ```text theme={null} http://localhost:8976/callback?paymentMethodId=pm_...&delegationId=del_...&state= ``` > [!WARNING] > > `returnUrl` must be an absolute `http(s)` URL and is re-validated server-side against the session's allow-list — localhost for self-mint sessions, the widget key's `allowedOrigins` otherwise. A URL that isn't allowed refuses to mount, so result IDs are never sent to an unapproved destination. ## Identity A widget session is minted for a specific **email** (the end-user you passed to `createWidgetSession`), and that session is the **sole** identity inside the iframe. The embed app is Privy-free: it never reads the host page's Nevermined (Privy) login — which is exactly why it runs on any of your domains without that domain having to be on Nevermined's auth allow-list. There's nothing to reconcile on the host side, so no `onAuthMismatch` / host-login handling is needed; the widget always acts as the session's user. ## Environments Pick the environment that matches the Nevermined dashboard you used to mint the widget key. | Environment | API base | Webapp base | Embed app | When to use | | - | - | - | - | - | | `sandbox` | `https://api.sandbox.nevermined.app` | `https://nevermined.app` | `https://embed.nevermined.app` | Testing on Base Sepolia with sandbox credentials | | `live` | `https://api.live.nevermined.app` | `https://nevermined.app` | `https://embed.nevermined.app` | Production on Base mainnet | The SDK resolves all three for you from the `environment` you pass to `initialize` — you only need the **Embed app** origin when building a [redirect-mode](#redirect--cli-mode-no-iframe) URL by hand. A single embed deployment serves both networks of its tier; the SDK forwards the active one as a `?network=` query param when it mounts. ## Production checklist > [card] Server-side secrets only > > Keep `NVM_WIDGET_SECRET` in your runtime env vars. Never commit it, never ship it to the browser, never put it in `NEXT_PUBLIC_*` or `VITE_*` variables. > [card] Allowed origins populated > > Add every domain where you mount the widget. The backend rejects sessions from any other origin. > [card] HTTPS only > > Serve both your site and your widget-session endpoint over HTTPS in production. `parentOrigin` includes the scheme, so origins must match exactly. > [card] Real email per session > > Pass the actual end-user email from your auth — never a placeholder, never the same value for every visitor. It's the canonical identity used across Nevermined. > [card] Rotate on suspicion > > If the secret might have leaked, revoke the key from the dashboard and generate a new one. Update your env var and redeploy. The API only ever stores its SHA-256, so the only recovery path is rotation. > [card] Short session TTLs > > Widget sessions expire after 2 hours; the SDK auto-refreshes them in-place. Don't cache or share session objects across users. ## Troubleshooting | Symptom | Cause | Fix | | - | - | - | | `onError`: `UNAUTHORIZED`, apiCode `BCK.WIDGET_SESSION.0001` | `rawSecret` doesn't match any active key for the org — **or** the org has no active key at all (one code covers both cases, by design, so attackers can't probe which) | Confirm the secret in your env matches an active key in the dashboard; generate one if the org has none; rotate if leaked | | `onError`: `UNAUTHORIZED`, apiCode `BCK.WIDGET_SESSION.0005` | Session token expired (default 2h) | The SDK auto-refreshes; if it fails persistently, re-fetch a fresh session from your server | | `onError`: `UNAUTHORIZED`, apiCode `BCK.WIDGET_SESSION.0011` | The widget key was revoked while the session was alive | Re-call `createWidgetSession` with the new key's `rawSecret` | | Widget mounts but never reaches `onReady` → `onError` apiCode `BCK.WIDGET_SESSION.0012` (403) | The mount origin isn't in the key's `allowedOrigins` | Add your site's origin to the key's allowlist (mind the scheme: `https://` vs `http://`) | | `onError`: `UNAUTHORIZED`, apiCode `BCK.WIDGET_SESSION.0020` (403) | The `did` / `planId` you're checking out belongs to a **different organization** than the widget session | Embed only agents/plans owned by the org the session was minted for | | `onError`: `PAYMENT_NOT_CONFIRMED` | Came back from a Stripe redirect, but the backend couldn't confirm the payment intent | Don't trust the `redirect_status` query flag alone; if the user was actually charged, reconcile via your Stripe dashboard / support | | `onError`: `NETWORK` | Fetch failed before getting a response | Check your network, CORS, and that the `environment` matches the API you minted the key against | | `[NeverminedWidgets] initialize: invalid environment` | `environment` is not a supported value | Use `'sandbox'` or `'live'` | ## Related > [card] [White-label Onboarding](/docs/solutions/organizations/white-label-onboarding) > > The programmatic counterpart: provision customers from your backend with the SDK instead of an embedded widget. > [card] [Platform Partners](/docs/integrations/organizations) > > Background on Nevermined organizations and how to upgrade your account. > [card] [Card enrollment](/docs/products/payments/card-enrollment) > > How Nevermined card enrollment works under the hood — the widget surfaces this same flow. # Platform Partners Source: https://nevermined.ai/docs/integrations/organizations Turn your AI marketplace into a revenue-sharing network. Let your builders monetize their agents while you earn a commission on every sale. You run an AI platform. Your builders create agents. Nevermined lets you monetize both sides — builders earn from their agents, and you take a cut on every transaction. No custom billing infrastructure required. > [!NOTE] > > Platform Partners is one of the [Organizations](/docs/solutions/organizations/overview) features. For the full picture — team workspaces, tiers, customers, analytics, and events — start with the [Organizations overview](/docs/solutions/organizations/overview). ## Who is this for? Platform Partners is designed for **AI marketplaces and developer platforms** that host communities of agent builders. If you're running a platform where developers build and publish AI agents, tools, or services, this is how you turn that ecosystem into a revenue engine. > [card] Revenue Sharing > > Set your commission rate. When any builder on your platform sells a plan, you automatically receive your cut. > [card] Branded Checkout > > Your logo, your colors, your messaging on the checkout page where clients purchase plans from your builders. ## How It Works **1. Upgrade to a Platform Partner account** Go to [Settings > Organization](https://nevermined.app/organization) in the Nevermined App and subscribe to the Platform Partner plan. **2. Configure your marketplace** Set your organization name, commission rates (for both crypto and fiat payments), and customize the checkout appearance. **3. Onboard your builders** Add builders to your organization. They register agents and create plans as usual — your branding and commission apply automatically. **4. Earn on every sale** When a client purchases a plan from one of your builders, fees are deducted and your commission is disbursed automatically. ## Revenue Flow When a client purchases a plan from a builder on your platform: ``` Client pays for plan | |-> Plan value |-> Stripe fees (deducted) |-> Nevermined fees (deducted) |-> Your platform commission (sent to you) |-> Builder payout (remainder) ``` You set the commission rate. Nevermined handles the split and disbursement. ## What You Get | Feature | Description | | - | - | | **Commission control** | Set your own percentage for crypto and fiat transactions | | **Branded checkout** | Custom logo, colors, and messaging on all purchase flows | | **Builder management** | Manage who can sell through your platform | | **Automatic settlement** | No manual invoicing — commissions are calculated and disbursed per transaction | ## Getting Started > [!NOTE] > > Builder onboarding is currently handled with our team. Contact [contact@nevermined.ai](mailto:contact@nevermined.ai) to set up your organization and add your first builders. > [card] [Nevermined App](/docs/products/nevermined-app/overview) > > Manage your platform from the dashboard > [card] [Payment Patterns](/docs/integrate/patterns/fiat-payments) > > Understand how fiat payments and payouts work ## Widgets Embed Nevermined checkout, card enrollment, and delegation flows directly into your site as iframes — without redirecting your customers to nevermined.app. Generate a widget key from your organization settings and use the official SDKs to render the flows on any page you control. > [card] [Embed Nevermined Widgets](/docs/integrations/organization-widgets) > > Step-by-step guide: generate a widget key, mint widget sessions server-side, and mount checkout / card / delegation widgets on your site. ## Programmatic access from the SDKs List the organizations you belong to, target a specific workspace when publishing agents and plans, and read the org activity feed directly from TypeScript or Python. > [card] [Organizations & Workspaces (SDK guide)](/docs/integrate/patterns/organizations) > > Pin a workspace per session or per call, list `getMyMemberships()`, and page through the activity feed. # You.com Source: https://nevermined.ai/docs/integrations/youdotcom Buy You.com API credits with card delegation: a $5 x402 purchase provisions or tops up a You.com API key, fully agent-driven. [You.com](https://you.com) accepts autonomous payments through Nevermined's [x402 card-delegation](/docs/specs/x402-card-delegation) scheme. An agent holding a Nevermined API key mints an x402 access token against the You.com plan and exchanges it at You.com's purchase endpoint for a working You.com API key. Repeat purchases top up the same key. Machine-readable instructions for agents live at [Nevermined agentic instructions](https://api.live.nevermined.app/api/v1/organizations/org-cf34dc7b-ec18-48f4-98fb-1697aafe0586/agentic-instructions.md). On the You.com side, the same flow is documented at [you.com/docs/administration/machine-payments/nevermined](https://you.com/docs/administration/machine-payments/nevermined.md), which is listed in [You.com's llms.txt](https://you.com/docs/llms.txt) so an agent can find it without being told. > [!NOTE] > > You.com's Nevermined plan ID:\ > `29778596298820876231214801015161463950677497795586711453924479772330133054735`\ > [paygo: \$5.00 per request](https://api.live.nevermined.app/api/v1/protocol/plans/29778596298820876231214801015161463950677497795586711453924479772330133054735). The plan ID is used to purchase API credits, which are then spent on You.com API requests. This plan and purchase run on **live**; use a live-prefixed Nevermined API key. See [You.com pricing](https://you.com/pricing) for current rates. ## Prerequisites (one time, done by the card owner) 1. Enroll a card at [nevermined.app](https://nevermined.app) → Payment Methods. 2. Create a **delegation** on the card: the spending permission an agent pays with. The owner sets the spending limit and duration, and can scope the delegation to a specific API key (recommended; it makes discovery deterministic for that key). 3. Generate an API key and give it to the agent. Two ways: * **Embedded login flow (no copy/paste):** the agent hosts a callback on `127.0.0.1` and sends its human this URL to sign in: `https://nevermined.app/auth/cli?callback_url=http://127.0.0.1:/callback`. After sign-in, the browser redirects to the callback with `nvm_api_key=` for the agent to read. * **Manual:** [nevermined.app](https://nevermined.app) → Account → API Keys → create a key and paste it to the agent (or open `https://nevermined.app/auth/cli` with no `callback_url` and copy the key shown on screen). See the [x402 card-delegation spec](/docs/specs/x402-card-delegation) for how enrollment and delegations work. ## The flow Handled with the Nevermined Payments SDK (`npm install @nevermined-io/payments`; the package is ESM-only; in a fresh npm project set `"type": "module"` in `package.json`, or the import fails with `ERR_PACKAGE_PATH_NOT_EXPORTED`). The package's bundled TypeScript definitions are the authoritative call reference for every method named below. For broader context, start from the [Payments overview](/docs/products/payments/overview) and the [documentation index](https://nevermined.ai/docs/llms.txt). 1. **Initialize** the SDK with your Nevermined API key only (`Payments.getInstance({ nvmApiKey })`). The environment is derived from the key prefix; do not pass an `environment` option. 2. **Find the delegation to pay with**; see [Getting a delegation](#getting-a-delegation) below. 3. **Mint the x402 access token** for the You.com plan ID via `payments.x402.getX402AccessToken`, using the `nvm:card-delegation` scheme and referencing the delegation by ID (`delegationConfig: { delegationId }`). No agentId is needed for this flow: the method's arguments are `(planId, agentId?, tokenOptions?)`, so pass the plan ID, `undefined`, and the token options. The call returns an object, `{ accessToken }`. Tokens cannot create delegations on the fly; the delegation must exist first. 4. **POST the token to You.com** in the `payment-signature` header (endpoint below). The purchase endpoint for this plan lives on You.com, not on Nevermined, and it **verifies and settles the token for you**. Do not settle it yourself first, or the card is charged twice. The response contains the You.com API key. Check the HTTP status before reading the body. 5. **Use the key** in the `X-API-Key` header against any You.com API. See [Authentication](https://documentation.you.com/docs/using-the-api/authentication). ## Without the SDK: the REST calls The Nevermined steps above map to endpoints on `https://api.live.nevermined.app`; send your Nevermined API key as `Authorization: Bearer ` on those two. The third call goes to You.com and is authenticated by the x402 token alone — do not send your Nevermined API key to a merchant. ### 1. Create a delegation ```http theme={null} POST https://api.live.nevermined.app/api/v1/delegation/create ``` Body: `{ provider, providerPaymentMethodId, spendingLimitCents, durationSecs, currency }`. A delegation authorizes spending within a fixed budget and time window. Reuse it until it is spent or expires. Field values for this flow are in the [delegation table](#getting-a-delegation) below. ### 2. Mint an x402 access token ```http theme={null} POST https://api.live.nevermined.app/api/v1/x402/permissions ``` ```json theme={null} { "accepted": { "scheme": "nvm:card-delegation", "network": "stripe", "planId": "" }, "delegationConfig": { "delegationId": "" } } ``` Returns an `accessToken`. The delegation must already exist. Tokens cannot create one on the fly. ### 3. Send the token to You.com ```http theme={null} POST https://api.you.com/payments/v1/nevermined/purchase-key payment-signature: ``` That is the last step. You.com's purchase endpoint **verifies and settles the token on your behalf** and returns the key in the same call. There is nothing to settle first. > [!WARNING] > > **Do not call `/x402/settle` yourself in this flow.** On this paygo plan, settling directly against Nevermined charges the card and hands back a bare settlement receipt with no You.com API key. If you then send the same token to `/purchase-key`, **you have paid twice for one key.** > > `/x402/settle` and `/x402/verify` exist for calling a generic Nevermined-metered resource yourself, where you construct the `paymentRequired` object and settle against it. The You.com purchase flow does not use them. ### The general pattern You.com's endpoint is an x402-protected resource, and the rule generalizes: **when a service is x402-protected, send the access token in the `payment-signature` header and let the service verify and settle.** Its own `402` response is the `paymentRequired`, so you never build one by hand. Reach for `/x402/settle` only when you are metering a resource yourself and no merchant endpoint is doing it for you. When you *are* metering a resource yourself, you construct `paymentRequired` from the plan ID and pass it to `/x402/settle` or `/x402/verify`. **`resource.url` must be a non-empty URL** identifying what is being bought; for a plain plan top-up, use the plan's own URL. ```json theme={null} { "x402Version": 2, "resource": { "url": "" }, "accepts": [{ "scheme": "nvm:card-delegation", "network": "stripe", "planId": "", "extra": {} }], "extensions": {} } ``` ```http theme={null} POST https://api.live.nevermined.app/api/v1/x402/settle ``` Body: `{ "paymentRequired": , "x402AccessToken": "" }`. Settling returns a `billingModel`. `credits` plans mint and burn, returning `creditsRedeemed` and `remainingBalance`. Pay-as-you-go plans charge per request, so both of those fields read `"0"` and the charge reference is in `orderTx` (fiat) or `transaction` (crypto). `POST /api/v1/x402/verify` with the same body is an optional dry run. Neither call belongs in the You.com purchase flow. ## Getting a delegation Query the delegations accessible to your API key with `payments.delegation.getPurchasingPower()` and select one with at least 500 cents of remaining budget. Budget fields are returned as strings, in cents. Purchasing-power results contain only delegations that can still pay; exhausted ones are excluded. With several delegations, discovery is deterministic when the owner key-scoped one to your key; to designate a specific budget among several, reference its ID explicitly. **If discovery returns none**, the preferred path is for the card owner to create a delegation in the dashboard (Prerequisites, step 2); the agent then re-runs discovery. Nothing needs to be copied. If no operator is reachable (or the request goes unanswered), a fully autonomous agent can create one programmatically with `payments.delegation.createDelegation`. Its payload fields: | Field | Value for this flow | | - | - | | `provider` | `"stripe"` | | `providerPaymentMethodId` | The card's id from `payments.delegation.listPaymentMethods()` | | `spendingLimitCents` | N × 500 for N expected purchases; a 500-cent delegation is exhausted after a single purchase | | `durationSecs` | `3600` is a sensible default for a one-shot purchase; keep it short (least privilege) | | `currency` | `"usd"` | The response includes the `delegationId` to mint with (it also includes a `delegationToken`; not needed for this flow; treat it as a secret and do not log it). **Card selection:** `listPaymentMethods()` carries no ordering guarantee and cards may be indistinguishable by metadata; if several are enrolled and the owner's intent is unknown, prefer asking the owner; otherwise any Active card of the provider is acceptable, and you should record which payment-method id was chosen. Note the trade-off of this whole path: the agent chooses the card and sets its own budget. Prefer an owner-created delegation whenever an owner is available. ## You.com's purchase contract ```http theme={null} POST https://api.you.com/payments/v1/nevermined/purchase-key payment-signature: ``` * **Cost:** \$5 per purchase, charged to the card behind the delegation referenced by the token. * **New payer:** a new You.com API key with \$5 of credits — `{ "status": "ok", "apiKey": "ydc-sk-…", "toppedUp": false }`. * **Returning payer:** the existing key is topped up with \$5 more credits. The key is not returned again — `{ "status": "ok", "apiKey": null, "toppedUp": true }`. * **Replayed token:** never charges twice, but what it returns depends on the original purchase. Replaying a first purchase mints a *new* key, because the original's plaintext cannot be recovered from cache. Replaying a top-up returns the same `apiKey: null` response again. * **Missing/invalid signature:** `402 Payment Required`. **When the key runs out:** You.com's API endpoints return `HTTP 402`, indicating more funds are needed. Mint a fresh x402 token with the same plan ID and delegation, POST it to the same endpoint, and You.com adds another \$5 of credits to the same key. ## Pricing **The purchase is a flat \$5.** Every call to the purchase endpoint charges \$5 to the card behind the delegation, whether it provisions a new key or tops up an existing one. The amount does not vary by which You.com API the agent intends to call, and there is no volume tier or negotiated rate in this flow. The plan is labeled `paygo: $5.00 per request`. **"Request" there means one purchase request, not one API call.** A \$5 purchase buys You.com credits, which are then drawn down across Web Search, Contents, Answer, Research and Finance Research at You.com's own per-API rates. See [You.com pricing](https://you.com/pricing). Those rates are metered inside You.com's credit system after settlement; Nevermined neither sets nor observes them. Because the plan is typed pay-as-you-go, settle returns `creditsRedeemed: "0"` and `remainingBalance: "0"`. Those fields describe Nevermined credit plans and do *not* reflect your You.com balance. Your proof of charge is `orderTx` (fiat) or `transaction` (crypto). ## What the key unlocks The purchase redeems for a standard You.com API key, valid anywhere an account-issued key is. Every API takes the key in the same `X-API-Key` header and is a `POST` with a JSON body — but they are served from **two hosts**: Web Search and Contents from `https://ydc-index.io`, the rest from `https://api.you.com`. Refer to You.com's API documentation for each endpoint's parameters. ```bash theme={null} curl -X POST https://ydc-index.io/v1/search \ -H "X-API-Key: $YDC_API_KEY" \ -H "Content-Type: application/json" \ -d '{"query": "nvidia earnings"}' ``` * [Web Search API](https://documentation.you.com/docs/api-reference/search/v1-search) — `POST https://ydc-index.io/v1/search`: real-time web and news results for grounding LLM responses. * [Contents API](https://documentation.you.com/docs/api-reference/contents) — `POST https://ydc-index.io/v1/contents`: clean HTML or Markdown for a target webpage. * [Answer API](https://documentation.you.com/docs/api-reference/answer/v1-answer) — `POST https://api.you.com/v1/answer`: single-call cited answer to a query. * [Research API](https://documentation.you.com/docs/api-reference/research/v1-research) — `POST https://api.you.com/v1/research`: multi-step web research with a synthesized, cited answer. * [Finance Research API](https://documentation.you.com/docs/api-reference/finance-research/v1-finance_research) — `POST https://api.you.com/v1/finance_research`: the Research API's multi-step approach over a financial-data index. ## Verifying charges Use `payments.delegation.listDelegations()` to inspect spend per delegation (`amountSpentCents`, `transactionCount`, status); the response wraps a `delegations` array. Fully spent delegations are marked `Exhausted` and no longer appear in `getPurchasingPower()` results; purchasing power lists only delegations that can still pay. ## Troubleshooting | Symptom | Meaning / fix | | - | - | | Token mint fails: `Required token-generation input is missing or incomplete (HTTP 402)` | The mint referenced no existing delegation (e.g., legacy create-on-the-fly `delegationConfig` with card details). Create or discover a delegation first and pass `delegationConfig: { delegationId }`. | | `ERR_PACKAGE_PATH_NOT_EXPORTED` on import | The SDK is ESM-only. Set `"type": "module"` in `package.json` or use `.mts`. | | Console warning: `The 'environment' option is deprecated…` | Something is still passing the deprecated `environment` option (a wrapper or copied example). Remove it; the environment is derived from your key prefix. On SDK 1.10.0 the warning can also self-fire with nothing passed ([payments#416](https://github.com/nevermined-io/payments/issues/416)); if you have removed the option and still see it, that issue is why. | | The plan ID above does not resolve, or token mint fails against it | Check your key prefix: this is a **live** plan, and a `sandbox:`-prefixed key targets a different environment where the plan does not exist. | | A delegation you spent from disappears from `getPurchasingPower()` | It is exhausted. Inspect it with `listDelegations()`; create or top up a delegation to continue. | | A You.com API returns `402` | The key's credits are spent. Repeat the purchase flow to top up the same key. | | Purchase succeeded but `apiKey` is `null` | Expected for a returning payer: `toppedUp: true` means the credits went to the key you already hold. Reuse the key from your first purchase. | | Card charged twice for one key | You called `/x402/settle` and then sent the same token to `/purchase-key`. The purchase endpoint settles for you. Mint the token and go straight there. | | `settle` rejects a hand-built `paymentRequired` | `resource.url` is required and must be a non-empty URL. For a plan top-up with no protected endpoint to call, use the plan's own URL. | | `settle` returns `creditsRedeemed: "0"` and `remainingBalance: "0"` | Expected on a pay-as-you-go plan, which charges per request rather than minting credits. The charge reference is in `orderTx` (fiat) or `transaction` (crypto), not in the balance fields. | ## References * [Payments overview](/docs/products/payments/overview) * [x402 card-delegation spec](/docs/specs/x402-card-delegation) * [Nevermined agentic instructions (machine-readable)](https://api.live.nevermined.app/api/v1/organizations/org-cf34dc7b-ec18-48f4-98fb-1697aafe0586/agentic-instructions.md) * [x402 glossary entry](https://nevermined.ai/glossary/x402/) * [You.com's Nevermined page](https://you.com/docs/administration/machine-payments/nevermined.md) — the merchant-side counterpart to this one * [You.com pricing](https://you.com/pricing) * [You.com Web Search API](https://documentation.you.com/docs/api-reference/search/v1-search) # get_budget Source: https://nevermined.ai/docs/mcp/catalog-mcp/get-budget Catalog MCP tool: read the spending budget pay_service draws on — its cap, spent, remaining, payments made, and expiry. Read the spending budget [`pay_service`](/docs/mcp/catalog-mcp/pay-service) draws on: its cap, what's been spent, what remains, how many payments were made (and the limit, if any), and when it expires. Reading charges nothing. Use it whenever the human asks how much is left, or before a run of paid calls. Needs a credential. **Auth:** key / grant · **Charges:** nothing ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `delegationId` | no | string | A specific delegation to read (every paid `pay_service` result carries one). Omit to read the budget `pay_service` spends by default. | ## Returns The figures are nested under `budget`; `delegationId`, `message`, and `instructions` sit alongside it. Money is in **cents**: `capCents` is whole cents; `spentCents` and `remainingCents` can carry up to four decimals (charged per call at 1/10,000 of a cent, e.g. `"1.632"` = 1.632¢): ```json theme={null} { "delegationId": "121b880a-…", "budget": { "capCents": "500", "spentCents": "8.04", "remainingCents": "491.96", "currency": "usdc", "transactionCount": 3, "maxTransactions": null, "expiresAt": "2026-10-02T13:29:31.691Z" }, "message": "Your budget: cap 5.00 USDC, 0.08 USDC spent, 4.92 USDC remaining, valid until 2026-10-02.", "instructions": "Relay message as it stands; call pay_service to spend from this budget." } ``` * **Relay `message` as it stands** — it is written to be read to the human, and because the figures include routing fees and rounding, **never substitute a figure of your own**. * Inside `budget`: `spentCents + remainingCents = capCents` while within cap; `transactionCount` is how many payments were made and `maxTransactions` the limit (`null` when there is none). * **`lockedInChannels`**, when present, is money the wallet this budget pays from has deposited into payment channels with merchants that charge per call over an MPP session, per token (same shape as in [`wallet_balance`](/docs/mcp/catalog-mcp/wallet-balance)). It is **not spent** and **not charged to this budget**: it can pay further calls only to the merchant holding each channel, and what is unused comes back to that wallet when the channel closes, after 15 minutes without use; `message` then says so. It is that **wallet's total**, not a figure of this budget's own: every budget paying from the same wallet reports the same channels. An empty list means nothing is locked; `null` means it could not be read, and `message` says that too. * **`sessionChannels`**, when present, is the history behind that: each payment channel this budget used, newest first, with its `merchant`, `status`, what was deposited (`deposit`, or `depositAtomic` in raw units when `symbol` is null), what came back (`refund`, null until the channel has closed and the refund is confirmed) and `openedAt` / `closedAt`. It explains money leaving the wallet and coming back when no payment shows it, because a payment record carries one call's price, never the deposit. `sharedWithOtherBudgets` means the wallet's channel also served another budget, and `depositConfirmed: false` means the open isn't confirmed, so the deposit may not have landed. `sessionChannelsTruncated: true` means only the newest channels are listed and older ones exist. An empty list means none was used; `null` means it could not be read; absent means this reader can't see them, as with a member spending an organization's budget. * With no `delegationId` this reads the budget `pay_service` would use, which only includes budgets that can still pay. So `{ "status": "no_active_delegation" }` also covers a budget that ran out or expired — pass the `delegationId` from an earlier `pay_service` result to read that one anyway. ## Nevermined credits With a personal API key, the result also carries your [Nevermined credits](/docs/products/catalog/router/subscription), with or without a subscription: ```json theme={null} { "status": "no_active_delegation", "message": "There is no delegation spending budget, but your Nevermined credits cover the catalog services that carry a credits tariff: pay_service uses them by default for those, and does not fall back to a delegation when they run out. To pay merchants from a delegation instead, call setup_delegation.", "subscription": { "subscribed": false }, "subscriptionMessage": "You have no Nevermined Subscription. You have 2,000 credits. 2,000 welcome credits expire on 2026-11-26.", "credits": { "total": "2000", "spendable": "2000", "parts": [ { "kind": "welcome", "credits": "2000", "expiresAt": "2026-11-26T09:12:44.000Z", "frozen": null } ], "nextExpiry": { "credits": "2000", "at": "2026-11-26T09:12:44.000Z" } }, "creditsMessage": "You have 2,000 credits. 2,000 welcome credits expire on 2026-11-26." } ``` * `credits` is your balance as [`GET /api/v1/credits/balance`](/docs/api-reference/router/credits-balance) reports it: `spendable` is what can pay a call now, and `parts` lists the credits left by kind (`welcome` for free credits, `allowance` for a subscription's monthly allowance, `topup` for top-up credits) and expiry, with any freeze. `creditsMessage` says the same in a sentence. Relay it as it stands. * `subscription` is your Nevermined Subscription, with `subscriptionMessage` to relay as it stands. It's `{ "subscribed": false }` when you don't subscribe. A subscriber sees the plan, the reset date and `creditsLeft`. For a subscriber who also holds free or top-up credits, `subscriptionMessage` counts them in the credits "left this month" — and its "unused credits do not carry over", or "unused credits expire on …, when the subscription ends" after a cancellation, is about the allowance only — so relay `creditsMessage` for what each part is and when it expires: ```json theme={null} { "subscription": { "subscribed": true, "creditsLeft": "1240", "spendable": true, "resetsAt": "2026-10-30T00:00:00.000Z", "cancelAtPeriodEnd": false, "status": "active", "suspended": false, "plan": { "catalogId": "3f2b…", "planKey": "standard", "creditsPerCycle": "20000" } }, "subscriptionMessage": "Nevermined Subscription (standard): 1240 of 20000 credits left this month; the monthly allowance resets on 2026-10-30 and unused credits do not carry over." } ``` * **Don't count credits yourself.** `credits.spendable` is what [`pay_service`](/docs/mcp/catalog-mcp/pay-service#pay-with-subscription-credits) can spend now with a personal API key; a call made in an organization never spends them. `subscription.creditsLeft` counts your whole balance, free credits included. `subscription.spendable` is about the subscription only: `false` unless it's `active` or `trialing` and not suspended by a card dispute. While it's overdue (`past_due` or `unpaid`), only its allowance is frozen. * `credits` is `null` when your balance couldn't be read this time, and `creditsMessage` says so. That never means zero. * An OAuth connection that you [allowed to spend your credits](/docs/products/catalog/router/subscription#who-can-spend-your-credits) gets `subscription` but no `credits`: that balance takes a personal API key. Any other OAuth connection gets neither. Both are also absent when the subscription isn't available to you or when it couldn't be read this time. Absent never means zero. * With no delegation, `status: "no_active_delegation"` still carries these fields, and drops `nextTool: "setup_delegation"` when your credits can pay: `pay_service` uses them by default. An OAuth connection gets no `credits`, so without a subscription that can pay it keeps `nextTool: "setup_delegation"`, even when `pay_service` can spend its credits. ### Top-up credits Credits from [top-up packs](/docs/products/catalog/router/subscription#top-ups) are a `topup` part that never expires (`expiresAt: null`), listed last because they're spent last, and `creditsMessage` says so: ```json theme={null} { "credits": { "total": "11500", "spendable": "11500", "parts": [ { "kind": "welcome", "credits": "1500", "expiresAt": "2026-11-26T09:12:44.000Z", "frozen": null }, { "kind": "topup", "credits": "10000", "expiresAt": null, "frozen": null } ], "nextExpiry": { "credits": "1500", "at": "2026-11-26T09:12:44.000Z" } }, "creditsMessage": "You have 11,500 credits. 1,500 welcome credits expire on 2026-11-26. 10,000 top-up credits never expire." } ``` `get_budget` doesn't report the top-up settings: `credits` carries no `topups` block, so it says nothing about whether top-ups are on, the monthly limit or a pause. The human sees those in the Nevermined App's [Top-ups panel](/docs/products/catalog/router/subscription#manage-top-ups); with a personal API key, `topups` on [`GET /api/v1/credits/balance`](/docs/api-reference/router/credits-balance) has them too. When a call that goes ahead charges a pack, [`pay_service`](/docs/mcp/catalog-mcp/pay-service#when-a-call-charges-a-top-up-pack) says so. ## Try it **Ask your assistant:** > How much of my spending budget is left? **Call it directly** (charges nothing): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_budget","arguments":{}}}' ``` # get_payment_result Source: https://nevermined.ai/docs/mcp/catalog-mcp/get-payment-result Catalog MCP tool: read the result of a paid call by its paymentId — for a pending call, or a response you lost. Read the result of a paid call by its `paymentId`. Use it when [`pay_service`](/docs/mcp/catalog-mcp/pay-service) answered `{ "status": "pending" }`, or to recover a response you lost. Reading charges nothing. Needs a credential. **Auth:** key / grant · **Charges:** nothing ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `paymentId` | yes | string (uuid) | The `paymentId` a `pay_service` result returned. | ## Returns A `state` and, when ready, the service's response: ```json theme={null} { "state": "Ready", "status": 200, "bodyEncoding": "json", "body": { "…": "the vendor's response" } } ``` * `state: "Pending"` — still running; call again in a few seconds. **Don't** call `pay_service` again — it returns the same `pending`. * `state: "Ready"` — `status` is the service's HTTP status, `body` its response. `bodyEncoding` is `json`, `text`, or `base64`. * `state: "Failed"` — the call ended without a response; `failureReason` says why. * `{ "status": "not_available" }` — nothing to return. Results are kept for **24 hours**, for the account that paid. ## Try it **Ask your assistant:** > Get the result of payment `b1f9c2e4-…` (use a `paymentId` from a `pay_service` result). **Call it directly** (charges nothing): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_payment_result","arguments":{"paymentId":"b1f9c2e4-0000-0000-0000-000000000000"}}}' ``` # get_service Source: https://nevermined.ai/docs/mcp/catalog-mcp/get-service Catalog MCP tool: fetch one catalog service by slug — its metadata and a requestShape describing every callable endpoint and its pay_service arguments. Fetch one Catalog service by slug: its metadata and a **`requestShape`** block describing every callable endpoint. Read this **before** [`pay_service`](/docs/mcp/catalog-mcp/pay-service) or [`quote_service`](/docs/mcp/catalog-mcp/quote-service). **Discovery only — free, no credential, nothing charged.** An unknown slug returns an error. **Auth:** free · **Charges:** nothing ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `slug` | yes | string | The service slug (from [`search_services`](/docs/mcp/catalog-mcp/search-services)). | ## Returns A large metadata object; the fields that matter for a call are `protocol`, `priceLabel`, `network`, `healthStatus`, and `requestShape`: ```json theme={null} { "slug": "openweather-mpp", "title": "OpenWeather", "provider": "OpenWeather", "category": "Data & Enrichment", "subCategory": "Weather data", "protocol": "mpp", "priceLabel": "$0.005–$0.01", "network": "Tempo", "healthStatus": "operational", "displayPriceLabel": "$0.008", "displayPriceSource": "settled", "requestShape": { "note": "An endpoint with `requestSchema` carries the JSON Schema of its request as the merchant declares it (`requestSchemaSource` says where from); …", "endpoints": [ { "path": "/openweather/current-weather", "method": "POST", "priceLabel": "$0.006", "description": "Current Weather", "pathParams": [], "maxRequestBytes": 8000, "payServiceArgs": { "slug": "openweather-mpp", "path": "/openweather/current-weather", "method": "POST" }, "requestSchema": { "type": "object", "properties": { "body": { "type": "object", "properties": { "lat": { "type": "number" }, "lon": { "type": "number" } } } } }, "requestSchemaSource": "openapi", "verificationStatus": "unverified" } ] } } ``` Working with `requestShape.endpoints[]`: * **`payServiceArgs`** is what to hand to [`pay_service`](/docs/mcp/catalog-mcp/pay-service) or [`quote_service`](/docs/mcp/catalog-mcp/quote-service) — **send it as given; its `path` is already the one to use.** It always carries `slug` / `path` / `method`, and for an endpoint with a verified (`paid-run` or `challenge`) example it also carries a pre-filled `body` (and may carry `search` / `headers`); don't drop those and rebuild your own. When `pathParams` is non-empty and an example filled them, `path` already holds **the example's** entity — not a `{placeholder}`, so there is nothing to "replace"; swap in the entity you actually want instead of paying for the example's. * **`requestSchema`** is the merchant-declared JSON Schema of the request — **sanitised, not verified** (`requestSchemaSource` names its origin, e.g. `openapi` or `merchant`). In it, `properties.query` lists what goes in the **`search`** argument and `properties.body` what goes in **`body`** — so a `query` block belongs in `search`, not inside `body`. `verificationStatus` is separate: it reports whether Nevermined has confirmed the endpoint actually works (`unverified` until a check passes), so it speaks to the endpoint while the schema stays sanitised-not-verified. An endpoint may instead carry `noParameters: true`, or neither; build the request from the description or the provider's docs when there's no schema. * **`maxRequestBytes`** is a per-endpoint request-size cap (e.g. `8000`). A request larger than it is refused with [`BCK.ROUTER.0027`](/docs/products/catalog/router/guardrails#every-error-code) **before** the unpaid probe — nothing is minted and **no charge**; shrink the request below the cap. * A **checked invoke contract** may add `invokePath`, `requestExample`, merchant-authored `responseSchema` / `responseExample`, and `exampleEvidence`: `paid-run` (a recorded paid response), `challenge` (proves the request shape only), or `docs` (unverified provider docs). Only `paid-run` and `challenge` examples are pre-filled into `payServiceArgs`; adopt a `docs` example deliberately. * An endpoint may carry a **`quote`** — the last merchant price the Catalog observed, with the routing fee **excluded**. Good for comparing services; for the live, fee-inclusive total of your exact call use [`quote_service`](/docs/mcp/catalog-mcp/quote-service). * `endpointCheck` records a dated unpaid failure, if any. * **Subscription credits.** Called with an API key, an endpoint that [Nevermined credits](/docs/products/catalog/router/subscription) can pay also carries `subscription: { "creditsPerCall": 3, "tariffVersion": 2 }` — what one call costs in credits at the current rate — and the service row carries its default rate the same way. It describes the endpoint, not your account, so it shows whether or not you subscribe; read [`get_budget`](/docs/mcp/catalog-mcp/get-budget#nevermined-credits) for your own credits. No `subscription` means credits can't pay that endpoint, the call was anonymous, or the rates couldn't be read this time. * An endpoint with **`auth: "siwx"`** is not paid: it is the result endpoint of an async service (a job or call poll), free only for the wallet that paid an earlier call to the same service. Call it with [`pay_service`](/docs/mcp/catalog-mcp/pay-service) after that call, filling its `pathParams` with the id the paid response returned; the Router signs the wallet challenge and charges nothing. See [Getting your results](/docs/products/catalog/paid-results). ## Try it **Ask your assistant:** > Show the endpoints and price of the `openweather-mpp` service. **Call it directly** (discovery is free — no credential needed): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_service","arguments":{"slug":"openweather-mpp"}}}' ``` # list_categories Source: https://nevermined.ai/docs/mcp/catalog-mcp/list-categories Catalog MCP tool: list the categories and sub-categories of paid services in the Nevermined Agent Services Catalog, with a count each. List the Catalog's categories and sub-categories, each with a count. **Discovery only — free, no credential, nothing charged.** See the [overview](/docs/mcp/catalog-mcp/overview) for transport and conventions. **Auth:** free · **Charges:** nothing ## Arguments None. ## Returns An array of categories, each with its sub-categories: ```json theme={null} [ { "category": "AI & Media", "count": 18, "subCategories": [ { "subCategory": "Media generation", "count": 5 }, { "subCategory": "LLM inference", "count": 1 } ] }, { "category": "Crypto & Blockchain", "count": 29, "subCategories": [ { "subCategory": "Crypto market data", "count": 8 }, { "subCategory": "Blockchain data", "count": 5 } ] } ] ``` > [!NOTE] > > The category names returned here are **not** stored as tags. Passing one as the `category` filter of [`search_services`](/docs/mcp/catalog-mcp/search-services) or [`route_by_intent`](/docs/mcp/catalog-mcp/route-by-intent) matches nothing — put a category name in `query` / `intent` instead. The `category` filter matches a listing's `tags`. ## Try it **Ask your assistant:** > Using the Nevermined connector, list the catalog categories. **Call it directly** (discovery is free — no credential needed): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_categories","arguments":{}}}' ``` # list_payments Source: https://nevermined.ai/docs/mcp/catalog-mcp/list-payments Catalog MCP tool: list your Router payments — the unified ledger across every service and delegation, newest first. List your Router payments: the unified ledger across every service and delegation, newest first, at most **1000** records. Reading charges nothing. Needs a credential. This reads the same ledger the [Router ledger page](/docs/products/catalog/router/ledger) documents. **Auth:** key / grant · **Charges:** nothing ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `delegationId` | no | string | Only payments charged to this delegation. | | `from` | no | string | ISO-8601 lower bound on `createdAt`, inclusive. An unparseable value is an error. | | `to` | no | string | ISO-8601 upper bound on `createdAt`, inclusive. An unparseable value is an error. | ## Returns An array of records. `amount` is in the asset's **smallest unit** (see `assetDecimals`), not cents: ```json theme={null} [ { "id": "b1f9c2e4-…", "createdAt": "2026-10-02T13:10:04.000Z", "status": "Settled", "deliveryStatus": "delivered", "protocol": "x402", "network": "base", "requestId": "…", "delegationId": "121b880a-…", "amount": "20000", "assetDecimals": 6 } ] ``` * `id` is the `paymentId` [`get_payment_result`](/docs/mcp/catalog-mcp/get-payment-result) takes. * **`deliveryStatus`** is one of: `delivered` (request settled), `charged_not_delivered` (request failed and the merchant charge was observed), `charged_unconfirmed` (charge observed, delivery unconfirmed), `not_charged` (reconciliation proved no merchant charge), `not_delivered` (the merchant answered an x402, MPP `evm` or MPP-tempo `charge` payment with an error, so nothing was delivered, and no charge has been seen: on a delegation payment the amount usually stays reserved until reconciliation decides, after the payment authorization expires, whether the merchant charged; this status neither confirms nor rules out a charge), or `pending` (charge outcome unknown). > [!WARNING] > > On the **card rail (SPT / MPP-stripe)**, `deliveryStatus: "pending"` is **not** proof of no charge. Flag `charged_not_delivered` to the user. This tool finds a `paymentId` and reconciles an uncertain payment. It does **not** return service responses (use [`get_payment_result`](/docs/mcp/catalog-mcp/get-payment-result)) or the remaining budget (use [`get_budget`](/docs/mcp/catalog-mcp/get-budget)). ## Try it **Ask your assistant:** > List my recent Nevermined Router payments. **Call it directly** (charges nothing): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_payments","arguments":{}}}' ``` # Catalog MCP: Overview Source: https://nevermined.ai/docs/mcp/catalog-mcp/overview The complete guide to the Nevermined Catalog MCP — import it into any harness, Claude, or ChatGPT; authenticate; and discover and pay for services. Links every tool. The **Catalog MCP** (also called the Commerce MCP) is a hosted [MCP](https://modelcontextprotocol.io) server that drops the Nevermined Catalog and Router straight into the tools an AI assistant already has. Point any MCP host — Claude, ChatGPT, Cursor, a generic MCP client — at it, and your agent can **discover** paid services in the [Nevermined Catalog](/docs/products/catalog/overview) and **pay** for them through the [Router](/docs/products/catalog/router/overview), all from a budget you cap. It's the third way to reach the Catalog + Router capability, alongside the public REST API and the webapp — and the one that needs no code. The server holds no funds and stores no state: every payment draws on the **caller's own** spend-capped Delegation, using the caller's own credential, forwarded per request and never stored. > [!NOTE] > > This is the **buyer** side, packaged as MCP tools. If you instead want to put a paywall on *your own* MCP server so its tools get paid, that's the seller side — see [MCP Integration](/docs/integrations/mcp). The [Docs MCP](/docs/mcp/docs-mcp/overview) is a third, unrelated server that streams this documentation into your IDE. See [Not this MCP](#not-this-mcp) below to be sure you're on the right page. This page is the complete reference: how it fits, the full tool surface (each tool has its own page), how to import and authenticate, a walkthrough quickstart, and the result/error conventions. Jump to a tool: [discovery](#the-tool-surface), [payments](#the-tool-surface), [ledger & wallet](#the-tool-surface). ## How it fits: discover, then pay The Catalog MCP is the same two-step motion the rest of the Catalog documents, exposed as tools: > [card] Discover > > [`list_categories`](/docs/mcp/catalog-mcp/list-categories), [`search_services`](/docs/mcp/catalog-mcp/search-services), and [`get_service`](/docs/mcp/catalog-mcp/get-service) read the [Catalog](/docs/products/catalog/discover) — public, no key. Your agent finds a service and reads its protocol, endpoint, and price. > [card] Pay > > [`pay_service`](/docs/mcp/catalog-mcp/pay-service) hands the call to the [Router](/docs/products/catalog/router/overview), which reads the merchant's `402`, pays it from your Delegation, enforces the cap, and relays the vendor's response. Your agent never holds a private key, never learns a payment protocol, and never needs an account with the service it just paid. The Router, not the agent, speaks each rail — see [How the Router works](/docs/products/catalog/router/how-it-works). If your agent would rather not choose among listings at all, [`route_by_intent`](/docs/mcp/catalog-mcp/route-by-intent) does both steps in one call: describe the need, get back the best payable service, and optionally pay it — see [Let the platform pick a service](#let-the-platform-pick-a-service). ## The tool surface Discovery is **free** — no credential needed. Pricing, picking or paying for a service, reading your ledger, your budget and your wallet are **paid** tools: they need a credential, either your API key or an OAuth grant your host obtains for you. Of those, only `pay_service` and `route_by_intent` with `autoPay` move money; the rest read or price and charge nothing. **Each tool has its own reference page** — every argument, return field and refusal: > [card] Discovery (free) > > [`list_categories`](/docs/mcp/catalog-mcp/list-categories) · [`search_services`](/docs/mcp/catalog-mcp/search-services) · [`get_service`](/docs/mcp/catalog-mcp/get-service) > [card] Payments > > [`quote_service`](/docs/mcp/catalog-mcp/quote-service) · [`pay_service`](/docs/mcp/catalog-mcp/pay-service) · [`route_by_intent`](/docs/mcp/catalog-mcp/route-by-intent) · [`setup_delegation`](/docs/mcp/catalog-mcp/setup-delegation) · [`get_payment_result`](/docs/mcp/catalog-mcp/get-payment-result) > [card] Ledger & wallet > > [`list_payments`](/docs/mcp/catalog-mcp/list-payments) · [`payment_summary`](/docs/mcp/catalog-mcp/payment-summary) · [`get_budget`](/docs/mcp/catalog-mcp/get-budget) · [`wallet_balance`](/docs/mcp/catalog-mcp/wallet-balance) · [`top_up_credits`](/docs/mcp/catalog-mcp/top-up-credits) | Tool | Auth | Charges | What it does | | - | - | - | - | | [`list_categories`](/docs/mcp/catalog-mcp/list-categories) | free | — | Catalog categories and sub-categories, with a count each. | | [`search_services`](/docs/mcp/catalog-mcp/search-services) | free | — | Search listings, most relevant first (hybrid semantic + keyword ranking). `query` required; filters: `category`, `protocol`, `tag`, `prefer`, `exclude`, `pageSize`. | | [`get_service`](/docs/mcp/catalog-mcp/get-service) | free | — | One service by `slug` — protocol, price label, and a `requestShape` naming each callable endpoint and its `pay_service` arguments. | | [`quote_service`](/docs/mcp/catalog-mcp/quote-service) | key / grant | nothing | Price one call before paying it — live, fee-inclusive total, rail and network. Reaches the service unpaid. | | [`pay_service`](/docs/mcp/catalog-mcp/pay-service) | key / grant | **real funds** | Pay for a service and return the vendor's response. | | [`route_by_intent`](/docs/mcp/catalog-mcp/route-by-intent) | key / grant | **real funds if `autoPay`** | Describe a need; get the single best payable service plus a ranked shortlist, and optionally pay it. | | [`setup_delegation`](/docs/mcp/catalog-mcp/setup-delegation) | key / grant | nothing | Start the delegation ceremony — returns one URL a human opens to authorise a spending cap. | | [`get_payment_result`](/docs/mcp/catalog-mcp/get-payment-result) | key / grant | nothing | Read a paid call's result by `paymentId` — for a `pending` call, or a response you lost. | | [`list_payments`](/docs/mcp/catalog-mcp/list-payments) | key / grant | nothing | Your Router payments (unified ledger, newest first). Filters: `delegationId`, `from`, `to`. | | [`payment_summary`](/docs/mcp/catalog-mcp/payment-summary) | key / grant | nothing | Count of payments plus a daily time series. Filters: `from`, `to`. | | [`get_budget`](/docs/mcp/catalog-mcp/get-budget) | key / grant | nothing | The spending budget `pay_service` draws on — cap, spent, remaining, expiry. | | [`wallet_balance`](/docs/mcp/catalog-mcp/wallet-balance) | key / grant | nothing | What your funding wallet holds, on every network the Catalog settles on. Filter: `network`. | | [`top_up_credits`](/docs/mcp/catalog-mcp/top-up-credits) | key / grant | **the human's card** | Refill credits within the human-set monthly limit — charge one pack when your credits run low, no new approval. | > [!NOTE] > > **Paying with Nevermined credits.** With [Nevermined credits](/docs/products/catalog/router/subscription) — free credits from sign-up, top-up packs, or a Nevermined Subscription — and an API key, `pay_service` pays, and `quote_service` prices, in credits by default when your credits and the endpoint qualify — see [Pay with subscription credits](/docs/mcp/catalog-mcp/pay-service#pay-with-subscription-credits). `get_budget` and `wallet_balance` report your credits. An OAuth connection spends them only if you allowed it when you connected. Every tool declares this split in its listing (`securitySchemes`: `noauth` on the free tools, `oauth2` with the `commerce` scope on the paid ones), so a host that reads tool metadata — ChatGPT does — knows which tools need linking before it calls one. ## Import the MCP ### Environments | Environment | Server URL | What a payment costs | | - | - | - | | **Live** | `https://mcp.live.nevermined.app/mcp` | Real merchants, real money — bounded by the cap you approve. | | **Sandbox** | `https://mcp.sandbox.nevermined.app/mcp` | Testnet merchants, testnet funds — the place for a first run. | | **Live (challenge-on-connect)** | `https://mcp.api.live.nevermined.app/mcp` | For hosts that only run OAuth when challenged on connect (e.g. LangSmith Fleet). | | **Sandbox (challenge-on-connect)** | `https://mcp.api.sandbox.nevermined.app/mcp` | As above, on sandbox. | ### Instant Setup Commands Any host that can send headers takes the server URL plus your Nevermined API key on the `Authorization` header. Discovery works with no key; paying needs a Nevermined **API key** and a funded, spend-capped **Delegation**. Get a key from the [Nevermined app](https://nevermined.app) (see [Get an API key](#2-get-an-api-key)). A Delegation is a payment method plus a spend mandate: an amount, an expiry and a number of purchases. Choose your tool: > [tab] Claude Code > > Set `NVM_API_KEY` in your shell first: the command expands it once, into the stored server config. > > ```bash theme={null} > claude mcp add --transport http nevermined-catalog https://mcp.live.nevermined.app/mcp \ > --header "Authorization: Bearer ${NVM_API_KEY}" > ``` > [tab] Codex > > ```toml theme={null} > # Add to ~/.codex/config.toml > [mcp_servers.nevermined-catalog] > url = "https://mcp.live.nevermined.app/mcp" > bearer_token_env_var = "NVM_API_KEY" > ``` > > Codex reads `NVM_API_KEY` from its environment when it starts, so restart Codex after setting it. > [tab] Cursor > > Add this entry under `"mcpServers"` in `~/.cursor/mcp.json`, next to any servers already there: > > ```json theme={null} > "nevermined-catalog": { > "url": "https://mcp.live.nevermined.app/mcp", > "type": "http", > "headers": { "Authorization": "Bearer YOUR_NEVERMINED_API_KEY" } > } > ``` > > Or merge it from the shell with `jq`, which keeps your existing servers and leaves the file untouched if it cannot parse it: > > ```bash theme={null} > mkdir -p ~/.cursor && f=~/.cursor/mcp.json && { [ -s "$f" ] || echo '{}' > "$f"; } && \ > jq --arg k "$NVM_API_KEY" '.mcpServers["nevermined-catalog"] = {url: "https://mcp.live.nevermined.app/mcp", type: "http", headers: {Authorization: ("Bearer " + $k)}}' \ > "$f" > "$f.tmp" && mv "$f.tmp" "$f" > ``` > [tab] Continue > > ```json theme={null} > // Add to ~/.continue/config.json > { > "mcpServers": [ > { > "name": "nevermined-catalog", > "url": "https://mcp.live.nevermined.app/mcp", > "transport": "http", > "requestOptions": { > "headers": { "Authorization": "Bearer YOUR_NEVERMINED_API_KEY" } > } > } > ] > } > ``` > [tab] Claude Desktop > > ```json theme={null} > // Add to ~/Library/Application Support/Claude/claude_desktop_config.json > { > "mcpServers": { > "nevermined-catalog": { > "url": "https://mcp.live.nevermined.app/mcp", > "type": "http", > "headers": { "Authorization": "Bearer YOUR_NEVERMINED_API_KEY" } > } > } > } > ``` Then restart your host to activate the connection. A **stdio-only** host can bridge with [`mcp-remote`](https://www.npmjs.com/package/mcp-remote). > [!WARNING] > > These point at **live**, where `pay_service` moves real funds. Rehearse on sandbox first: use `https://mcp.sandbox.nevermined.app/mcp` with a **sandbox** API key (`sandbox:...`), because a key works only in the environment it was issued for. Then switch to live with a small Delegation cap and the cheapest sub-cent service. **Hosts that need no API key.** Claude (claude.ai), ChatGPT, Claude Code, LangSmith Fleet, and Cursor through the Nevermined plugin in the Cursor Marketplace run OAuth for you: connect by URL and approve a spending cap once. See [Connect from your assistant](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). The API-key setup above is for every other host, and for Claude Code or Cursor when you prefer a key. ## Auth & transport * **Transport:** Streamable HTTP at `POST /mcp` (stateless — each call is a self-contained JSON-RPC request; no session id). Liveness at `GET /health`; readiness — which checks the Nevermined API is reachable — at `GET /ready`. `initialize` reports the server as `nevermined-commerce`. * **Two ways to authenticate, one server.** * **API key** (any host that can send headers): put your Nevermined key on `Authorization: Bearer `. Every tool is served exactly as before; this is the path the [quickstart](#quickstart) below uses. * **OAuth** (hosts that can't be handed a key — Claude connectors, and hosts that follow the MCP authorization spec): connect with **no** header at all. The server is an OAuth 2.0 protected resource — when it needs a credential it answers `401` with a `WWW-Authenticate` challenge that points your host at the discovery document (`/.well-known/oauth-protected-resource/mcp`) and asks for the **`commerce`** scope. Your host follows it to Nevermined, you approve a spending cap once, and the host retries the call with the credential it was granted. The credential is a `commerce` grant: it spends only from the Delegation you approved, through the Router, and nothing else. * **Which hosts can be granted `commerce`.** A host that follows the MCP spec identifies itself with a URL (its Client ID Metadata Document), so it never needs registering — but a `commerce` grant is account-level authority, and Nevermined grants it only to hosts its operator has listed by that URL. **ChatGPT, Claude (the claude.ai connector) and Claude Code are listed out of the box**, and a statically registered connector (LangSmith Fleet, with a registered redirect allow-list instead of a URL) is enabled the same way; a host that is neither is refused when you press Approve (`BCK.OAUTH.0018`), never silently granted. For a self-registering host the consent screen shows its domain (`chatgpt.com`) beside the name it calls itself, so you can check who is asking; a statically registered one shows its registered name only. How an operator lists another assistant: [self-registering clients](/docs/integrate/authentication/oauth-authorization-code#self-registering-clients-identity-from-the-document-trust-from-the-operator). * The credential — key or grant — is forwarded to the Nevermined API **per request**, never stored, never logged. Never send it to the merchant you're paying; it authenticates you to Nevermined, nothing else. ### What happens without a credential The server runs on two hostnames per environment. They serve the same tools and differ only in **when** a request without a credential gets the challenge: | Host | `initialize`, `tools/list`, free tools | A paid tool call | With a credential | | - | - | - | - | | `mcp..nevermined.app` — the URL in the quickstart | Served, no credential needed | `401` + challenge — your host prompts you to connect, then retries | Served | | `mcp.api..nevermined.app` | `401` + challenge on the very first request | `401` + challenge | Served | Use the first host. It lets an assistant browse the Catalog before anyone signs in, and starts the consent only when the agent actually tries to pay — Claude shows an inline **Connect** card at that moment and retries the same call once you've approved. The second host is for clients that only look for auth when they first connect; it challenges immediately instead. An expired or revoked credential on a paid call also comes back as a `401` (`error="invalid_token"`), so a host can refresh or re-authorize on its own rather than surfacing an error to you. A host that links accounts per tool rather than per connection (ChatGPT's documented mechanism) gets the same information in-band: the paid tools carry `securitySchemes`, and a refused call returns an error result carrying the challenge under `_meta["mcp/www_authenticate"]`. > [!NOTE] > > Environments are `sandbox` and `live` — `mcp.sandbox.nevermined.app` and `mcp.live.nevermined.app`. The OAuth ceremony lands you on the same consent screen for both; on **live** the cap you approve is real money. ## See it in action [Your AI assistant can now pay for things](https://www.youtube.com/embed/EJk5ZHmd4u0) Claude, ChatGPT and a LangSmith Fleet agent each buy real services from a \$5 budget approved once — recorded on live, with real money. One-assistant walkthroughs, each showing that product's configuration in full: [Claude](https://youtu.be/ioDqtiHtOGg) · [ChatGPT](https://youtu.be/e_-bQlLdRdg) · [LangSmith Fleet](https://youtu.be/wbwrg8v0uys). ## Connect from your assistant If your assistant can run OAuth for you — Claude, ChatGPT, LangSmith Fleet — you never handle a key. The shape is the same in all three: **1. Point your assistant at the server** For **Claude** and **ChatGPT** that is the entire configuration: paste the server URL, leave the client ID and secret empty, and the assistant discovers everything else from the server. No API key either way. **LangSmith Fleet is the exception** — it does not discover, so you enter the endpoints yourself, once: an OAuth provider (ID `nevermined`, client ID `langsmith-fleet`, a placeholder secret, the authorization and token URLs, PKCE/S256) and then the MCP server pointed at it. Its tab below has the values. **2. Browse the Catalog for free** Discovery answers with no sign-in at all. Ask for the categories, search for a service, read its price. **3. Approve a spending cap, once** Nevermined's consent page opens: check the **Sandbox / Live** badge, set the **cap** and how long it is **valid for**, press **Grant access**. *When* this fires is the one thing each host does differently — Claude asks at the first paid call, ChatGPT at creation, Fleet when it connects. **4. That approval is the credential** It is a **commerce grant**: it spends only from the Delegation you just approved, only through the Router, and you can revoke it at any time. Your assistant retries the call it was blocked on. > [!TIP] > > **Ask in a way that makes the agent reach for the Catalog.** All three assistants will happily answer from their own knowledge and charge nothing — which looks like a broken connector and isn't. Three things help: > > * **Name the connector in the prompt** — *"using the Nevermined connector, …"*. > * **Ask for something only live data can answer.** Anything the model can answer from training, it will — for free, and usually correctly. > * **Describe the need, or name the service** — *"translate documents to German"*, `OpenWeather`. Catalog search ranks by meaning as well as by keyword, so a plain-language need finds services that never use your exact words. Narrow with the `category`, `tag` and `protocol` filters rather than by stacking words. ### Pick an environment | Where you point it | Server URL | What a payment costs | | - | - | - | | **Live** | `https://mcp.live.nevermined.app/mcp` | Real merchants, real money — bounded by the cap you approve | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | Sandbox test merchants, testnet funds | | **LangSmith Fleet**, on either tier | `https://mcp.api.live.nevermined.app/mcp` · `https://mcp.api.sandbox.nevermined.app/mcp` | As the matching row above — Fleet needs the `mcp.api.` host to be challenged on connect; see its tab | The click paths below are what each product shows today; the mechanics underneath are the same for any host that follows the MCP authorization spec. > [tab] Claude (claude.ai) > > **1. Add the connector** > > **Settings → Connectors → Add custom connector.** Give it a name and paste the server URL. Leave the OAuth client ID and secret **empty**. > > **2. Ask for something free** > > In a chat, enable the connector from the tools menu and ask *"list the Nevermined catalog categories"*. It answers with no sign-in. > > **3. Ask it to buy** > > *"Buy the service with slug `` through the Nevermined connector and show me the merchant's response."* The paid tool answers `401`, and Claude shows an inline **Connect** card. > > **4. Approve the cap** > > **Connect** → Nevermined's consent page opens in a popup. Check the **Sandbox / Live** badge, set the **cap** and **validity**, then **Grant access**. > > **5. Claude retries** > > It reports *Authentication complete* and **retries the same call** with the grant. The result carries the price, the fee and the merchant's response. > > > [!NOTE] > > > > There is nothing to register because Claude identifies itself to Nevermined with its own client metadata document — which is also why the client ID and secret fields stay empty. > [tab] ChatGPT > > **1. Turn on Developer mode** > > **Settings → Security and login → Developer mode.** It needs a paid plan (Plus or above). *Plugins* then appears in the sidebar. > > **2. Create an MCP app** > > **Plugins → + → Create app → Create MCP app.** > > The + menu also offers *Create plugin*, which opens an assistant that **builds** a plugin from scratch — not what you want here. > > **3. Fill in the New Plugin dialog** > > * **Name** — read the warning below first; you only get one shot at it. > * **Connection** — leave the toggle on **Server URL** and paste the URL. (*Tunnel* is for a server running on your own machine.) > * **Authentication** — **OAuth**. No client ID or secret. > * **Advanced OAuth settings** — leave it closed. It reads *"Enter a valid MCP Server URL to review discovered OAuth settings"*: ChatGPT discovers them from the server itself. > * **Icon** and **Description** are optional (PNG 256×256, 10 KB max). > * Tick **I understand and want to continue** under the red *"Custom MCP servers introduce risk"* notice. > > **4. Create — and approve the cap** > > The OAuth ceremony fires **immediately at creation**, before any tool call: ChatGPT shows *Add Nevermined … to ChatGPT?* and opens the consent page. Check the **Sandbox / Live** badge, set the **cap** and **validity**, **Grant access**. The plugin shows as connected. > > **5. Use it** > > In a new chat the plugin is available automatically — there is nothing to add from the composer. Ask for the categories, then to buy a slug. Each paid call first asks *Allow ChatGPT to use Nevermined …?* — **Allow** (once, or always). > > > [!WARNING] > > > > **Choose the name carefully — a plugin cannot be deleted.** Its ⋯ menu offers only *Download plugin ZIP* and *Upload new version*. Names are unique per account, so a name you have used is taken for good, and uninstalling does not free it. > > > [!NOTE] > > > > ChatGPT presents its **stable** identity (`https://chatgpt.com/oauth/client.json`) to Nevermined, so the grant survives reconnecting the same plugin. > [tab] LangSmith Fleet > > Fleet authenticates MCP servers through a LangSmith **OAuth provider**, so there are two objects to create. > > **1. Create the OAuth provider** > > **Settings → OAuth providers → New.** > > | Field | Live | Sandbox | > | - | - | - | > | Provider ID | `nevermined` | `nevermined` | > | Client ID | `langsmith-fleet` | `langsmith-fleet` | > | Client secret | `unused` — any placeholder | `unused` | > | Authorization URL | `https://nevermined.app/oauth/authorize?network=live&consent_type=commerce` | `https://nevermined.app/oauth/authorize?network=sandbox&consent_type=commerce` | > | Token URL | `https://api.live.nevermined.app/oauth/token` | `https://api.sandbox.nevermined.app/oauth/token` | > | PKCE | enabled, method **S256** | enabled, method **S256** | > > **2. Add the MCP server** > > **Settings → Integrations → Add custom MCP.** Name it and paste **`https://mcp.api.live.nevermined.app/mcp`** — or `https://mcp.api.sandbox.nevermined.app/mcp` when the provider points at sandbox. Choose **OAuth 2.1 (Manual)** and select the provider from step 1. Save. > > **3. Connect and approve the cap** > > Fleet asks *Connect now?* → the consent page opens. Check the **Sandbox / Live** badge, set the **cap** and **validity**, **Grant access**. Fleet reports *Authentication complete*. > > **4. Use it** > > In a new thread ask for the categories, then to buy a slug. Fleet resolves the tools through its *Find Tools* step, calls `get_service` and `pay_service`, and shows the merchant's response. > > > [accordion] Why the provider ID must be exactly `nevermined` > > > > The provider ID becomes the path of the callback LangSmith uses, and `nevermined` is the one Nevermined redirects to. A provider named anything else is refused when you press **Approve** (`BCK.OAUTH.0017`, redirect not registered). There is exactly **one** provider, and it points at one environment at a time. > > > [accordion] Why a client secret at all, when Nevermined ignores it > > > > LangSmith makes the field mandatory; Nevermined does not use it. The authorization server advertises `token_endpoint_auth_methods_supported: ["none"]`, and `/oauth/token` answers identically whether or not a secret is sent — both requests get past client authentication. Any placeholder will do. > > > > What *is* load-bearing is **PKCE with method S256**. With client authentication set to `none`, PKCE is the only proof of the client the server has — and `code_challenge_methods_supported` lists `S256` alone, so enable it and pick that method. > > > [accordion] Why `network=` is not optional > > > > `network` is what selects the tier. Without it the consent screen opens on whichever tier your browser last used (Live by default), which either dead-ends the code against the other tier's token endpoint or has you approve a real-money cap when you meant to rehearse. > > > [accordion] Why the `mcp.api.` host, on both tiers > > > > Fleet only starts the OAuth ceremony when the server challenges it **on connect**, and that is what this host does. The `mcp.` hosts answer discovery with no challenge, so Fleet would connect happily and never ask you to authenticate. > > > [accordion] Switching tiers means editing three values together > > > > The provider's authorization URL (`network=`), its token URL, and the MCP integration's server URL. Change one and the flow breaks in a way that reads like a Nevermined error. > > > [!WARNING] > > > > If the workspace already has a Nevermined MCP server configured with static headers, remove or disable it first: both servers expose the same tool names and the agent may dispatch the paid call to either one. > [tab] Any other MCP host > > A host that follows the [MCP authorization spec](https://modelcontextprotocol.io/specification/latest/basic/authorization) needs only the URL: the server's `401` challenge points it at `/.well-known/oauth-protected-resource/mcp`, which names the Nevermined authorization server, and Nevermined accepts clients that identify with a **client metadata document** (an `https` URL as `client_id`) as well as pre-registered ones. > > Discovery-driven hosts that prompt for auth only when they first connect should use the `mcp.api.` host. A host that cannot run OAuth at all uses an API key instead — that is the [quickstart](#quickstart) below. > [!NOTE] > > **Which clients can obtain a commerce grant is a per-environment allow-list**, not a self-serve setting. ChatGPT, Claude, Claude Code and LangSmith Fleet (any workspace, through the `nevermined` provider ID) are enabled today. An unknown client is refused when you press **Approve**, never silently granted. Building your own host? [Contact us](https://nevermined.ai) with its client identity — a metadata-document URL, or the client ID and redirect URIs you need registered — before you try; [how listing works](/docs/integrate/authentication/oauth-authorization-code#self-registering-clients-identity-from-the-document-trust-from-the-operator). ### What the consent page asks One screen. **What you set:** * The **spending cap**, in USDC or EURC. * How long the grant is **valid for**. * Nothing else — the **environment** badge (Sandbox or Live) and **who is asking** are shown, not chosen. The assistant's name appears with its origin beside it (`chatgpt.com`, `claude.ai`) for a self-registering client; a statically registered client such as LangSmith Fleet shows its name only. **What to read before you grant:** * On **Live**, the cap is real money. * The assistant may pay **any service it can reach, not a fixed list**. * **Nevermined's routing fee comes out of the same cap** — the cap is the total debited, not what merchants receive. * Beyond spending, the grant lets the assistant read your Router payment history, your spend totals, and the funding wallet's address and balance. **The cap bounds what it can spend, not what it can see.** Granting creates a Delegation confined to that cap and window, funded from your own wallet, and hands the assistant a credential that spends only through it. It grants no other authority on your account; in particular, it never authorizes a card mandate. ### When the grant runs out * **The credential itself is short-lived** (about an hour) and the assistant renews it silently with a refresh token for as long as the Delegation is usable **and the assistant keeps using it**: a grant left idle for 30 days can no longer be renewed silently (the renewal answers HTTP 400, `BCK.OAUTH.0011`) and has to be re-linked, even on a 90-day cap — the Delegation itself is untouched. You see nothing otherwise. * **When you disconnect**, the credential is refused on its next use — a `401` on the paid call. What the assistant then *shows* you differs by product, verified on live 2026-09-24: **Claude** renders an inline **Connect** card and, once you grant, retries the blocked call by itself; **ChatGPT** shows a **Reconnect Nevermined** card with a button (its wording says the connection "expired" even when you revoked it); **LangSmith Fleet** reports *"Authorization required"* in the thread and names Integrations, but offers no button — and needs the extra step in the troubleshooting section below. On all three the connector itself stays configured; you never remove and re-add it. **When the cap is spent or the validity window ends**, the credential itself is still valid: the paid call fails with an error naming the exhausted or expired Delegation (an in-band tool error, not a re-link prompt), and the next renewal is refused with an HTTP 400 carrying `BCK.OAUTH.0013` (budget exhausted) or `BCK.OAUTH.0012` (delegation expired). Discovery keeps working in every case. Re-run the connect step to approve a **new** cap — a Delegation is never widened or extended in place. * **To revoke early**, open **Connections** in the [Nevermined app](https://nevermined.app/connections) and disconnect the assistant. The credential stops working on its next call. ### When connecting goes wrong > [accordion] Connect completed instantly and no consent screen ever appeared > > On **LangSmith Fleet**, a grant is stored as an **account** under the integration — not on the OAuth provider or the MCP server. Deleting both of those leaves the accounts untouched, so recreating the provider with the same ID hands the old credential straight back from the account list. > > The symptom is quiet. Connect completes with no consent screen, the integration keeps showing its tools, and then paid calls fail with an authorization error while the agent falls back to its own tooling and charges nothing. If the Nevermined grant was revoked in the meantime, nothing in Fleet says so: the integration still reads **Connected** because it still holds the stored account. > > **The control is on the integration, not on the MCP servers row** — that row offers only *Refresh tools* and *Delete*. Go to **Settings → Integrations → Nevermined** and work on its **Accounts** list: remove the stale account, or use **+ Connect new account** and then **set the new one as Primary**. Read the next entry before you do — a new consent *adds* an account and does not take the **☆ Primary** star, which is the difference between this working and appearing to. > > Waiting about an hour for the access token to expire also makes the next connect prompt for consent, and a different LangSmith **organization** has its own account list (organizations are a paid-plan feature) — but neither removes the stale account, so both land you in the Primary trap below. Clearing browser storage or signing out does **not** help: the accounts are not in your browser. > [accordion] Fleet still says Authorization required after you reconnect it > > On **LangSmith Fleet** a grant is stored as an **account** under the integration, and a new consent **adds** one rather than replacing the old. The dead account stays in the list, keeps the **☆ Primary** star, and Primary is what the agent uses — so re-authorizing appears to succeed, the integration still shows **Connected**, a working credential is sitting right there, and every paid call keeps failing. > > Open **Settings → Integrations → Nevermined**, use **+ Connect new account** to grant again, then **set the new account as Primary**. Nothing in the error message, the dialog or the Connected badge points at that step. Verified on live 2026-09-24: with a fresh grant present but Primary still on the revoked account, the agent reported "Authorization required"; promoting the new account made the same call succeed immediately. > > Old accounts accumulate. They are safe to leave, but only the Primary one is used, so prune them if you cannot tell which is current — Fleet names them itself and the label says nothing about which grant it holds. > [accordion] `BCK.OAUTH.0017` when you press Approve > > The redirect is not registered. On Fleet that means the OAuth provider's ID is not exactly `nevermined` — the provider ID is what forms the callback path. Recreate the provider with the right ID, and expect the stale-account behaviour above on the next connect. > [accordion] The agent says the budget is spent, or the grant expired > > That is the Delegation, not the connection — see [When the grant runs out](#when-the-grant-runs-out). A Delegation is never widened or extended in place, so you approve a **new** cap rather than raising the old one. > > On **Claude** and **ChatGPT**, re-running the connect step opens the consent screen again. On **LangSmith Fleet** it usually will not: the server-side token is still cached and still authenticates, so Fleet reconnects silently and the paid call keeps failing against the spent Delegation. Wait for the access token to expire (about an hour) and connect again, or use a different LangSmith organization — the same two remedies as the silent-connect case above. > [accordion] It answers the question without paying anything > > Usually the prompt, not the connector. The assistant answered from its own knowledge, or Catalog search returned nothing and it fell back to its own tooling — see the phrasing tips at the top of this section. Confirm the connection separately by asking for the Catalog categories, which is a free tool call and either works or doesn't. ## Quickstart The **API-key** route, for hosts that can send headers but cannot run OAuth (a coding agent with a config file, a script, a stdio bridge). Connect a host, run a discovery call, then a paid call — end to end. Discovery works with no credentials; paying needs a Nevermined **API key** and a **funded, spend-capped Delegation**. Using Claude, ChatGPT or Fleet? You want [Connect from your assistant](#connect-from-your-assistant) instead — no key involved. ### 1. Connect your host Point an MCP client at the server URL and set the `Authorization` header to your Nevermined API key — the [Instant Setup Commands](#instant-setup-commands) above have the per-host form; the generic shape is: ```json theme={null} { "mcpServers": { "nevermined-catalog": { "url": "https://mcp.live.nevermined.app/mcp", "headers": { "Authorization": "Bearer ${NVM_API_KEY}" } } } } ``` | Environment | Server URL | Purpose | | - | - | - | | **Live** | `https://mcp.live.nevermined.app/mcp` | Discovery and real payments | | **Sandbox** | `https://mcp.sandbox.nevermined.app/mcp` | Discovery, plus free test purchases from two testnet merchants | > [!WARNING] > > **The config above points at live**, where `pay_service` moves real funds to a real merchant. Rehearse on sandbox first (below), then switch to live with the cheapest sub-cent service and keep your first Delegation cap small. > [!TIP] > > **Sandbox has something to buy.** The sandbox Router funds testnets only, so the mainnet listings the sandbox Catalog also carries — the same content seeds populate both databases; nothing propagates between tiers afterwards — can't be paid there. Two free **testnet test merchants** can, so you can run the whole loop (discover, pay, read the ledger) without spending anything — you still need a Delegation whose wallet holds the testnet asset for the rail you pick (see [step 4](#4-prepare-to-pay)): `mpp-dev-paid-ping` (MPP on Tempo Moderato, `GET`, $0.10 in testnet pathUSD) and `x402-org-protected` (x402 on Base Sepolia, `GET`, $0.01 in testnet USDC). Both are tagged `testnet` and listed last, and `pay_service` with just the `slug` settles against either. They don't exist on live. > [!NOTE] > > **Stdio-only host?** Some hosts speak MCP over stdio, not HTTP. Bridge them with [`mcp-remote`](https://www.npmjs.com/package/mcp-remote), which forwards the same URL and header to a local stdio endpoint. ### 2. Get an API key Create a **Nevermined API key** from the [Nevermined app](https://nevermined.app). Discovery tools don't need it, but `pay_service` and the ledger tools do. Older keys are rejected by the Router — see [the Router quickstart](/docs/products/catalog/router/quickstart#1-get-an-api-key) for how to tell which you have. The key is sent as a request header, forwarded to the Nevermined API per call, and never stored or logged by the MCP server. Never put it in a tool argument or send it to a merchant. ### 3. Run a discovery call Discovery is public — call these before you've set any key. Ask your host to run: * **[`list_categories`](/docs/mcp/catalog-mcp/list-categories)** — the Catalog's categories, each with a count. * **[`search_services`](/docs/mcp/catalog-mcp/search-services)** with `{ "query": "weather", "protocol": "x402" }` — weather listings on the x402 rail, most relevant first. `query` is required; also filter by `category` and `tag` (both narrow the same tag set, so passing both matches a listing tagged with either), and set `pageSize` (1–100). You get the first page only: the `pageToken` in the result can't be passed back yet, so narrow the query rather than paging. Each result is an ARD record carrying an `identifier` URN, not a `slug` — the slug is its last segment (`urn:air:api.live.nevermined.app:service:openweather-mpp` → `openweather-mpp`). * **[`get_service`](/docs/mcp/catalog-mcp/get-service)** with `{ "slug": "" }` — one service's protocol, price label, and its **`requestShape`**: every callable endpoint with its `path`, HTTP `method`, price and `pathParams`, each carrying the exact `payServiceArgs` to hand to `pay_service`. An endpoint may also carry the JSON Schema of its request (`requestSchema`, as the merchant declares it — sanitised by Nevermined, not verified) or `noParameters: true`; for one with neither, build the request from its description or the provider's docs. An endpoint with a `quote` has a live price: the merchant's price for one call, on the rail and network the Router pays it on, with the routing fee excluded — see [Price a call before paying](#price-a-call-before-paying). In natural language that's just: *"List the Nevermined categories, then find x402 services for weather."* The host picks the tools. ### 4. Prepare to pay `pay_service` moves money — real on live, testnet funds on sandbox — so it needs a funded budget on your account: a Delegation whose wallet holds the asset the rail settles in (on sandbox, testnet pathUSD on Tempo Moderato for MPP, testnet USDC on Base Sepolia for x402). **1. Create a Delegation** A hard cap and an expiry. Created once and reused. See [Create a Delegation](/docs/products/catalog/router/quickstart#2-create-a-delegation). **Or let the agent ask for one.** Calling [`setup_delegation`](/docs/mcp/catalog-mcp/setup-delegation) returns a single URL for you to open; you set the currency, cap, duration and transaction limit in the browser, and the agent carries on. The agent cannot choose those numbers — that is the point of a mandate. See [Getting a Delegation from inside the chat](#getting-a-delegation-from-inside-the-chat). **2. Fund its wallet** The **crypto** rails **pull** from your own wallet, so it must hold the payment asset on the network you'll pay on. See [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). (A card-funded Delegation has no wallet to fund — it charges the card instead.) Once funded, **[`wallet_balance`](/docs/mcp/catalog-mcp/wallet-balance)** reads it back from inside the chat — including after a payment fails for lack of funds. See [step 6](#6-check-your-spend-and-your-balance). `pay_service` uses the accessible Delegation (Active, unexpired, funded) automatically. Pass an explicit `delegationId` only to override that choice. #### Getting a Delegation from inside the chat If your agent reaches a paid call with no Delegation, `pay_service` returns `{ "error": "no_delegation", "nextTool": "setup_delegation" }` instead of stopping. Calling **[`setup_delegation`](/docs/mcp/catalog-mcp/setup-delegation)** answers with one URL: ```json theme={null} { "status": "human_action_required", "url": "https://embed.nevermined.app/cards/delegate?provider=crypto&network=live&sessionToken=…", "expiresAt": "2026-09-03T12:00:00.000Z", "instructions": "…" } ``` Open it, set your limits, and tell the agent to try again — `pay_service` picks the new Delegation up on its next call. Nothing needs to redirect back to the agent, and in a chat host nothing can: the page simply confirms and you close the tab. > [!WARNING] > > The url carries a short-lived session token bound to **your** account. Treat it like a credential — it is for you, not for sharing. If your host *can* receive a redirect — a CLI listening on `http://127.0.0.1:/…` — pass it as `returnUrl` and your browser returns there with the `delegationId`. Any other origin has to be allow-listed on the deployment first; one that isn't comes back as `{ "error": "return_url_not_allowed" }` before you open a browser, rather than failing after you've filled in the form. If a usable Delegation already exists — including the one an OAuth commerce grant just created — nobody is interrupted; the tool answers with the budget so the assistant can state it without a second call: ```json theme={null} { "status": "already_active", "delegationId": "121b880a-…", "budget": { "capCents": "500", "spentCents": "8", "remainingCents": "492", "currency": "usdc", "expiresAt": "2026-09-23T13:29:31.691Z" }, "source": "oauth_grant", "message": "Your spending budget is in place: delegation 121b880a… — cap 5.00 USDC, 0.08 USDC spent, 4.92 USDC remaining, valid until 2026-09-23T13:29:31.691Z. …", "instructions": "No human action is needed now. Call pay_service; it spends from this budget by default." } ``` `budget` carries only the figures the API reported and is omitted entirely when none did; `source` (`oauth_grant` or `account`) is omitted when the origin is unknown; `message` is the human-relayable half and `instructions` the agent-facing next step — both are always present. ### 5. Make a paid call Read `get_service` first, then call **[`pay_service`](/docs/mcp/catalog-mcp/pay-service)** with the `payServiceArgs` of the endpoint you want — pass them through as-is (they carry the `slug`, `path`, `method`, and for a verified endpoint a pre-filled `body`). For a slug-routed GET, put the query string without `?` in `search`, separate from `path`. Optional `maxTotalCents` is a non-negative safe integer that caps this call's fee-inclusive, whole-cent budget reserve; the Delegation cap still limits total spend. To learn that figure before paying, [quote the call](#price-a-call-before-paying). For example: ```json theme={null} { "slug": "dexter-x402", "path": "/quote", "body": { "pair": "ETH/USDC" } } ``` A bare `slug` reaches the service's base URL, which for a multi-endpoint API is a 404, not a purchase — `fal-ai-mpp`, for instance, needs `"path": "/fal-ai/flux/schnell"`. Only a single-endpoint service (the sandbox test merchants, say) is called by slug alone. `method` is optional: the server takes it from the Catalog endpoint matching your `path`, and falls back to `POST` when the Catalog records no method, when no Catalog endpoint matches your `path`, or when the matching ones disagree on the method. The server resolves the slug, confirms it's payable, pays the vendor's `402` from your Delegation, and relays the vendor's own response — with a `request` block showing exactly what was sent and where the `method` came from (`caller`, `catalog`, or `default`): ```json theme={null} { "paid": true, "upstreamStatus": 200, "priceLabel": "$0.02", "payment": { "paymentId": "b1f9c2e4-…", "txHash": "0xfc8af37b…" }, "request": { "method": "POST", "path": "/quote", "methodSource": "catalog", "catalogEndpoint": "/quote" }, "response": { "…": "the vendor's body, unchanged" } } ``` See the [`pay_service` reference](/docs/mcp/catalog-mcp/pay-service) for every argument, the `payable: false` shape, and all outcomes. ### 6. Check your spend and your balance * **[`list_payments`](/docs/mcp/catalog-mcp/list-payments)** — your Router payments, newest first, across every protocol. Filter by `delegationId`, `from`, `to`. * **[`payment_summary`](/docs/mcp/catalog-mcp/payment-summary)** — a count of payments plus a daily time series. (For what you've *spent*, use [`get_budget`](/docs/mcp/catalog-mcp/get-budget); for per-payment amounts, `list_payments`.) * **[`get_budget`](/docs/mcp/catalog-mcp/get-budget)** — the spending budget `pay_service` draws on: cap, spent, remaining, and expiry. Relay its `message` verbatim. * **[`wallet_balance`](/docs/mcp/catalog-mcp/wallet-balance)** — what your **personal** wallet actually *holds*. Different question: the ledger says what you've spent, the budget says what you're *allowed* to spend, but [the crypto rails pull from your wallet](/docs/products/catalog/router/how-it-works) and only this says whether the money is there. Read the network the merchant quoted, not the one with money in it — live settles on two chains (USDC on Base `8453`, USDC.e on Tempo `4217`) and most services accept only one. The ledger tools read the same unified ledger the [Router ledger page](/docs/products/catalog/router/ledger) documents, so a payment made here is reconcilable with everything else your agents spend. ### When a payment is refused Refusals come back as legible results, not exceptions. The full set is on each tool's page ([`pay_service`](/docs/mcp/catalog-mcp/pay-service#outcomes-and-refusals)); the ones to recognize: | Result | What happened | | - | - | | HTTP `401` with a `WWW-Authenticate` challenge | A paid tool was called with no credential, or with one Nevermined refused. An OAuth-capable host handles this itself; a headers-only host must set its API key (step 2). | | `{ "error": "payment_failed", "code": "BCK.ROUTER.0003", … }` | The spend would exceed your Delegation cap, or it expired. Widening the cap is almost always the wrong move — see [Guardrails](/docs/products/catalog/router/guardrails). | | `{ "error": "payment_failed", "code": "BCK.ROUTER.0009", … }` | The funding source couldn't cover the charge; nothing signed. On **MPP** the wallet is short (call [`wallet_balance`](/docs/mcp/catalog-mcp/wallet-balance)); on **card** the issuer declined; **x402** never raises this. | | `{ "status": "already_paid", "paymentId": "…" }` | A retry was deduped — not charged twice. The original may itself have `Failed`: check [`list_payments`](/docs/mcp/catalog-mcp/list-payments). | | `{ "error": "payment_indeterminate", … }` | The connection dropped mid-payment. Check `list_payments` before retrying. | | `{ "status": "pending", "paymentId": "…", "nextTool": "get_payment_result" }` | Not a refusal: the payment was made and the service is still working. Call [`get_payment_result`](/docs/mcp/catalog-mcp/get-payment-result) until it reports `Ready` or `Failed`. | | `{ "error": "no_delegation", "nextTool": "setup_delegation" }` | No Delegation yet. Call [`setup_delegation`](/docs/mcp/catalog-mcp/setup-delegation) and open the URL — see [step 4](#getting-a-delegation-from-inside-the-chat). | ## Price a call before paying [`quote_service`](/docs/mcp/catalog-mcp/quote-service) answers *"what will this one call cost?"* without paying for it. It takes the `slug`, `path`, `method`, `search`, `headers`, `body` and `delegationId` you'd pass to `pay_service` and returns the **live, fee-inclusive** price of that exact request: the rail (`protocol`), the network and merchant amount (`settlement`), and what the call would reserve against your budget (`fee`). Pin the quote by passing the `quoteId` it returns to `pay_service`. **1. Quote the call** Call `quote_service` with the arguments you'd pay with — here, the ones from [step 5](#5-make-a-paid-call): ```json theme={null} { "slug": "dexter-x402", "path": "/quote", "body": { "pair": "ETH/USDC" } } ``` ```json theme={null} { "paymentRequired": true, "upstreamStatus": 402, "optionSet": "delegation", "delegationId": "121b880a-…", "quoteId": "qt_8f2a…", "expiresAt": "2026-10-02T14:05:00.000Z", "protocol": "x402", "settlement": { "recipient": "0x2096…", "amount": "20000", "asset": "USDC", "network": "base", "approxCents": "2" }, "fee": { "bps": 200, "capChargedCents": "3", "capChargedMicros": "20400" }, "nextTool": "pay_service", "instructions": "Nothing was charged. `fee.capChargedCents` is the fee-inclusive total this call would cost." } ``` **2. Decide** `fee.capChargedCents` is the call's fee-inclusive price in whole cents, rounded **up** from `fee.capChargedMicros` (exact, in 1/10,000 of a cent). Here a \$0.02 call plus a 2% routing fee is 2.04¢, so the figure is `3`. **3. Pay with a ceiling** Call `pay_service` with the same arguments, the quoted `quoteId` and `delegationId`, and `maxTotalCents` set to that figure **as a number**: ```json theme={null} { "slug": "dexter-x402", "path": "/quote", "body": { "pair": "ETH/USDC" }, "delegationId": "121b880a-…", "quoteId": "qt_8f2a…", "maxTotalCents": 3 } ``` If the price rises between the quote and the call, the payment is refused instead of paid. A quote **charges nothing** but **does contact the service** (to read the price, the Router sends your request unpaid — so take care quoting a method with side effects) and spends the same per-service **rate limit** as a payment. See the [`quote_service` reference](/docs/mcp/catalog-mcp/quote-service) for `optionSet`, every field, and the no-charge refusals. ## Let the platform pick a service [`route_by_intent`](/docs/mcp/catalog-mcp/route-by-intent) turns a plain-language need into the **single best payable service** in the Catalog, plus the ranked shortlist it was chosen from — so your agent doesn't search, compare listings and pick one itself. The ranking is deterministic — no randomness, and no model doing the picking — but it's recomputed on every call from the live Catalog, so the pick can change as listings, health and payability change. It uses Nevermined's own relevance and quality signals, behind a payability gate (listed, not flagged unpayable, healthy, not held by moderation, on x402 or MPP). When nothing passes the gate you get an explicit refusal, never a weak match. ### Which tool to reach for | You want to… | Use | | - | - | | Get the right service for a task in one call — and optionally pay it | [`route_by_intent`](/docs/mcp/catalog-mcp/route-by-intent) | | Browse, compare, or show a person the options | [`search_services`](/docs/mcp/catalog-mcp/search-services), then [`get_service`](/docs/mcp/catalog-mcp/get-service) | | Pay a service you've already picked | [`pay_service`](/docs/mcp/catalog-mcp/pay-service) | With `autoPay: false` (the default) it returns the pick and charges nothing; with `autoPay: true` it also pays the winner (requires `requestId`, plus `delegationId` on an API key). Because an `autoPay` call ranks afresh and reaches the winner's base URL, when the exact service or endpoint matters you should propose first, read `get_service` on `chosen.slug`, then pay with `pay_service`. See the [`route_by_intent` reference](/docs/mcp/catalog-mcp/route-by-intent) for every argument (including `filters.require` / `prefer` / `exclude`), the full result shape, and the refusals. ## Result and error conventions These hold across every tool; each tool page notes only what it adds. * **One JSON object per call.** Each tool returns a single JSON object as the MCP text content. * **Refusals are legible results, not exceptions** — an object carrying an `error` (and often a `code` and `retryable`), so an agent can branch on it. * **Missing or rejected credential → `401`** with a `WWW-Authenticate` challenge (`error="invalid_token"` when refused). A host that links per tool gets the challenge in-band under `_meta["mcp/www_authenticate"]`. * **Money is in cents.** `capCents` is whole cents; `spentCents` / `remainingCents` carry up to four decimals (charged per call at 1/10,000 of a cent). The routing fee is included — never re-derive a figure by summing your own calls. Payment *amounts* in [`list_payments`](/docs/mcp/catalog-mcp/list-payments) are in the asset's smallest unit (`assetDecimals`), not cents. * **Error codes.** Router refusals carry `BCK.ROUTER.*` ([Router guardrails](/docs/products/catalog/router/guardrails#every-error-code)); OAuth refusals carry `BCK.OAUTH.*`. Full catalogue: [API error reference](/docs/development-guide/api-errors/overview). ## Not this MCP Nevermined ships three MCP servers. Make sure you want this one: | MCP | Side | What it's for | | - | - | - | | **Catalog MCP** (this page) | Buyer | Your agent discovers & pays for Catalog services. You provide just an API key and a funded budget. | | [MCP Integration](/docs/integrations/mcp) | Seller | Put a paywall on *your own* MCP server with the Payments Library (`withPaywall`), so your tools get paid. | | [Docs MCP](/docs/mcp/docs-mcp/overview) | — | Streams the Nevermined **documentation** into your IDE so an assistant can vibe-code an integration. It sells nothing. | ## Next > [card] [Catalog MCP (intro & video)](/docs/products/catalog/mcp) > > The short introduction and the "see it in action" video. > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The code-free playbook for driving discovery and payment from your agent. > [card] [Catalog: discover](/docs/products/catalog/discover) > > What's listed, how filtering works, and what "payable" means. > [card] [Router: pay](/docs/products/catalog/router/overview) > > Delegations, the spending cap, the rails, and every refusal code. # pay_service Source: https://nevermined.ai/docs/mcp/catalog-mcp/pay-service Catalog MCP tool: pay for a catalog service from your spend-capped delegation and return the vendor's response. Charges real funds. Pay for a service from your spend-capped delegation and return the vendor's response. **This charges real funds.** Needs a credential (API key or OAuth `commerce` grant). Always read [`get_service`](/docs/mcp/catalog-mcp/get-service) first and **pass its `requestShape.endpoints[].payServiceArgs` through as-is** — it carries `slug` / `path` / `method`, and for a verified endpoint a pre-filled `body` (and sometimes `search` / `headers`); don't drop those and rebuild your own. Where an example filled a path parameter, `path` already holds **that example's** entity (not a `{placeholder}`) — swap in the entity you want rather than looking for a placeholder to replace. **Auth:** key / grant · **Charges:** real funds ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `slug` | yes | string | The service slug to pay for. | | `path` | no | string | Router suffix appended to the service base (from `get_service`'s `payServiceArgs.path`). Where an example filled `pathParams`, it already holds that example's entity — swap in the one you want. A checked `invokePath` may be empty even when the display path is not. Query params go in `search`, never here. | | `search` | no | string | Query string without `?`, for a slug-routed `GET`. | | `method` | no | string | HTTP method. Omit to use the catalog method for the matching endpoint (`POST` when none). Echoed back under `request.methodSource` as `caller`, `catalog`, or `default`. | | `body` | no | any | Request payload sent to the vendor. | | `maxTotalCents` | no | integer | Maximum whole cents this call may cost, fee included (compared exactly, so rounding alone never exceeds it). The 402 price can differ from the catalog label. | | `quoteId` | no | string | An opaque quote id from [`quote_service`](/docs/mcp/catalog-mcp/quote-service). Pass only with the exact same call before its `expiresAt`; the Router then uses that cached challenge and exact total. | | `headers` | no | object | Extra headers for the vendor call. | | `delegationId` | no | string | Delegation to charge (API key only); defaults to your active one. An OAuth caller always spends from its grant. Feeds the derived idempotency key when `requestId` is omitted, so keep it the same across retries. | | `fresh` | no | boolean | Set `true` on **every poll** of an async status endpoint, **including the first**, so each poll mints a fresh idempotency key and advances. With `fresh` a retry is **not** de-duplicated and **is** charged again. Ignored when `requestId` is set. | | `requestId` | no | string | Idempotency key. Leave unset — a retry of the same call is de-duplicated automatically. Set a **new** value only for a genuinely separate, additional charge. | | `requireProtocol` | no | string | Pay only on `x402` or `mpp`; never fall back to another rail. If unavailable, returns `payment_failed` with `BCK.ROUTER.0045`, nothing charged. Omit to auto-select (MPP first). With `quoteId`, keep the quoted rail; a different rail returns `quote_mismatch`. | | `funding` | no | string | `"subscription"` or `"delegation"`: what pays this call. Omit it to pay with your [Nevermined credits](#pay-with-subscription-credits) when they can pay this call, and from your delegation otherwise. | > [!NOTE] > > **A bare slug reaches the service's base URL.** For a multi-endpoint API that is a 404, not a purchase — pass the endpoint's `path`. Only a single-endpoint service is callable by slug alone. ## Returns The vendor's response plus the payment record. A paid result also carries `delegationId` and `budget` (the spending budget after this call): ```json theme={null} { "paid": true, "upstreamStatus": 200, "priceLabel": "$0.02", "payment": { "paymentId": "b1f9c2e4-…", "txHash": "0xfc8af37b…" }, "request": { "method": "POST", "path": "/quote", "methodSource": "catalog", "catalogEndpoint": "/quote" }, "delegationId": "121b880a-…", "budget": { "capCents": "500", "spentCents": "8.04", "remainingCents": "491.96" }, "response": { "…": "the vendor's body, unchanged" } } ``` * `paid: true` with a **non-2xx** `upstreamStatus` may still have cost the merchant price. * The `request` block rides on every result that resolved the endpoint (`already_paid`, `payment_failed`, …), not only the paid one. * `budget: null` means it couldn't be read this time — **not** that it's zero; call [`get_budget`](/docs/mcp/catalog-mcp/get-budget). * `payable: false` (with `protocol`, `priceLabel`, `network`, `note`; never the upstream URL) means the service isn't on a payable rail — nothing charged. ## Outcomes and refusals | Result | Meaning | What to do | | - | - | - | | `{ "status": "pending", "paymentId": "…", "nextTool": "get_payment_result" }` | **Paid** — the service took longer than the Router waits. | Call [`get_payment_result`](/docs/mcp/catalog-mcp/get-payment-result) with the `paymentId`. Don't call `pay_service` again — it returns the same `pending`. | | `{ "status": "already_paid", "paymentId": "…" }` | This idempotency key already carries a payment; the result isn't replayed here. Nothing new charged — and it doesn't by itself say the original succeeded. | Read the original with `get_payment_result` or `list_payments`. A **new** `requestId` starts a separate charge. | | `{ "error": "payment_indeterminate" }` | The charge may or may not have landed (e.g. the connection dropped). | Check `list_payments` first; to retry, reuse the returned `requestId` **verbatim** without `fresh`. | | `{ "error": "payment_failed", "code": "BCK.ROUTER.0003" }` | The spend would exceed your delegation cap, or it expired. | Widening the cap is almost always wrong — see [Guardrails](/docs/products/catalog/router/guardrails). | | `{ "error": "payment_failed", "code": "BCK.ROUTER.0009" }` | The funding source couldn't cover the charge; nothing signed. | On **MPP** the wallet is short (call [`wallet_balance`](/docs/mcp/catalog-mcp/wallet-balance); a human funds it). On **card** the issuer declined — use another card. **x402** never raises this. | | `{ "error": "per_call_max_exceeded" }` | The price exceeds `maxTotalCents`; no charge. | Raise `maxTotalCents` only deliberately, then retry with the **same** `requestId`. | | `BCK.ROUTER.0027` — request exceeds `maxRequestBytes` | The request body is larger than the endpoint's `maxRequestBytes` cap. Raised **before** the unpaid probe, so nothing is minted and **no charge**. | Shrink the request below the cap that [`get_service`](/docs/mcp/catalog-mcp/get-service) reports for the endpoint. | | `{ "error": "quote_not_found" }` / `"quote_expired"` / `"quote_mismatch"` | Named no-charge quote refusals. | Quote again rather than paying unpinned. | | `{ "error": "service_not_found" }` | Wrong slug; no charge. | Check with `search_services`. | | `{ "error": "catalog_unavailable" }` / `"delegation_lookup_failed"` | Transient read failure; no charge. | Retry later. | | `{ "error": "no_delegation", "nextTool": "setup_delegation" }` | No delegation on the account; no charge. | Call [`setup_delegation`](/docs/mcp/catalog-mcp/setup-delegation). | | `{ "error": "router_controls_unavailable" }` | The API behind this server is too old to enforce `search`, `quoteId` or `maxTotalCents`. | Tell the human; don't retry without them. | | `{ "error": "credential_refused" }` / HTTP `401` | Credential missing or refused. | Re-authorize, or set your API key. | > [!WARNING] > > **Async services: set `fresh: true` on every poll, including the first.** An async service returns a `taskId`, then you poll a status endpoint with the same id. Without `fresh`, every later poll reuses the first poll's idempotency key and gets the first poll's stored answer (or `already_paid`) back, so the status never advances. `fresh` makes each poll a distinct, separately-billed call. Leave `fresh` **off** the submit and off any retry of a call whose outcome is unsure. ## Pay with subscription credits With [Nevermined credits](/docs/products/catalog/router/subscription) — free credits from sign-up, top-up packs, or a Nevermined Subscription's monthly allowance — `pay_service` can pay with **credits** instead of your delegation: Nevermined pays the merchant, the call costs the endpoint's rate from Nevermined's rate card, and the credits come back if the service doesn't answer with a `2xx`. Credits are spent with a personal **API key**, or through an OAuth connection you [allowed to spend them](/docs/products/catalog/router/subscription#who-can-spend-your-credits); any other OAuth connection pays from its grant. The `funding` argument decides what pays: | `funding` | What pays | | - | - | | omitted | Your credits, when a credits quote for this call succeeds: the endpoint has a rate, and you hold a subscription that can spend or enough other credits for this call (or automatic top-ups that would cover it). Otherwise your delegation, exactly as before. Passing `delegationId`, `quoteId` or `maxTotalCents` selects the delegation. | | `"subscription"` | Your credits — refused, never switched to the delegation, if they can't pay this call. | | `"delegation"` | Your delegation. | `delegationId`, `quoteId` and `maxTotalCents` only mean something to a delegation, so passing one with `funding: "subscription"` is refused (`invalid_arguments`, with the offending `fields`). For a subscriber in good standing, the default doesn't look at how many credits are left or at the merchant's live price — those are checked when the call is made, and a refusal for them is **not** moved to your delegation (see the note below). Without a subscription in good standing, the quote also checks that your credits cover this call, unless an automatic top-up would cover it. When your credits were refused for this call up front (no rate, nothing that can pay it, credits frozen by a card dispute or an overdue renewal), the delegation-funded result says so: `funding: "delegation"`, `fundingReason: "subscription_refused"`, the API's `fundingCode` and a `fundingNote` (or `fundingReason: "delegation_arguments"` when you passed a delegation-only argument). If credits aren't available to you at all — an OAuth connection you didn't allow to spend them, for example — the result carries no funding fields. And if the subscription's answer couldn't be read, the call is refused with `funding_undetermined` rather than paid from your delegation. A credits call answers with `funding: "subscription"`, the credits it cost and where they stand — and no `budget` or `delegationId`, since no delegation was charged: ```json theme={null} { "funding": "subscription", "paid": true, "upstreamStatus": 200, "creditsLeft": "11497", "creditsCharged": 3, "creditsStatus": "Committed", "payment": { "paymentId": "b1f9c2e4-…", "status": "Settled", "txHash": "0xfc8af37b…", "creditsCharged": 3, "creditsStatus": "Committed" }, "request": { "method": "POST", "path": "/scrape", "methodSource": "catalog", "catalogEndpoint": "/scrape" }, "response": { "…": "the vendor's body, unchanged" } } ``` * `creditsStatus` is `Committed` (spent), `Reserved` (still running, or marked for refund) or `Refunded` (returned). The top-level `creditsCharged` and `creditsStatus` are `null` when `paid` is `false`, or when the ledger couldn't be read at answer time (`payment` then omits them) — read the payment with [`list_payments`](/docs/mcp/catalog-mcp/list-payments) later. * `creditsLeft` is your credits after the call, as a digit string. `null` means it couldn't be read, not zero. * A `pending` answer works as for any paid call: poll [`get_payment_result`](/docs/mcp/catalog-mcp/get-payment-result). The credits stay reserved until the service answers. ### When a call charges a top-up pack With [top-ups](/docs/products/catalog/router/subscription#top-ups) on **and a personal API key**, a credits call that runs out of credits charges one pack to the human's saved card and goes ahead (a call made through an OAuth connection never charges a pack on its own — an OAuth-connected agent uses [`top_up_credits`](/docs/mcp/catalog-mcp/top-up-credits) instead). Its result then also carries `topUp` — the credits the pack added and its price in US dollars, before tax — and `topUpMessage`, a sentence to relay: ```json theme={null} { "funding": "subscription", "paid": true, "upstreamStatus": 200, "creditsLeft": "10497", "creditsCharged": 3, "creditsStatus": "Committed", "topUp": { "credits": 10000, "amountUsd": 10 }, "topUpMessage": "Your credits ran out, so this call charged a credit pack to your saved card: 10,000 credits for $10.00 plus any tax. Tell the user. Top-up credits never expire; the pack and its receipt are on the Nevermined dashboard, where the monthly top-up limit is managed." } ``` * **Relay `topUpMessage` to the human.** Their card was charged, and they should hear it from you, not only from the receipt email. * A `pending` answer carries them too. * When the pack the Router reported can't be read, `topUpMessage` comes alone, without `topUp`, saying the call **may** have charged a pack. Relay that as well. * Only a call that goes ahead carries `topUp`. A call refused after its pack was charged says so as `insufficient_credits` or `credits_frozen` with `topUps: "bought"`, the pack's `purchaseId` and a `topUpMessage` to relay; any other refusal then says nothing about the pack. The human's **Packs** list in the Nevermined App and the receipt email are the record. ### Refusals when paying with credits These spend and reserve no credits. They charge nothing either — except that with top-ups on, an `insufficient_credits` with `topUps: "pending"`, or any refusal with `topUps: "bought"`, can follow a pack charged to the human's card: tell them. A refusal with `topUps: "bought"` carries a `topUpMessage` saying so — relay it. Each carries `funding: "subscription"`, the API's `code`, `retryable` and `message`, and an `alternative` saying how to pay the same call from your delegation instead. | `error` | What happened | | - | - | | `no_active_subscription` | Nothing to pay with: no subscription in good standing, and no credits — or not enough for this call — that can be spent. Also a call made with the API key of an organization you're a member of. Without a subscription in good standing, top-ups that are paused, at their monthly limit or still charging a pack land here too, with no `topUps`: with `funding` omitted, such a call is paid from the delegation instead, so tell the human their top-ups need attention in the Nevermined App. | | `subscription_not_eligible` | This endpoint can't be paid with credits — see `reason`. With `reason: "wallet_bound"` the service sells only to the payer's own crypto wallet, so the `alternative` asks for the `delegationId` of a personal crypto-wallet delegation: a card or organization delegation can't pay it either. (With `code: null` and no `alternative`, it's the HTTP method: credits price only `GET`, `POST`, `PUT`, `PATCH` and `DELETE`.) | | `insufficient_credits` | Not enough credits left for this call (`credits` is its cost). When the call tried a pack, `topUps` says why none covered it: `paused` (a pack was declined, needed authentication, or its card can no longer pay; the human resumes top-ups in the Nevermined App), `limitReached` (the monthly top-up limit), `pending` (a pack is being charged and may already be; retry in a moment), `unavailable` (no pack was charged; retry later) or `bought` (this call charged a pack, but other calls spent it first; retry). Also an allowance an overdue renewal froze (`BCK.SUBSCRIPTION_ROUTER.0016`): the human updates the card in the Nevermined App so the open invoice is paid — a retry is refused again until then, even with `topUps: "bought"`. See [When no top-up covers the call](/docs/products/catalog/router/subscription#when-no-top-up-covers-the-call). | | `credits_frozen` | Every credit is frozen by a card dispute (`BCK.SUBSCRIPTION_ROUTER.0015`), resolved with the card issuer or Nevermined support — never by buying credits, which would be frozen too. With `topUps: "bought"`, this call charged a pack before the dispute froze it: the pack's credits are frozen with the rest. With no delegation to name as the `alternative`, it carries `nextTool: "setup_delegation"`. | | `subscription_ceiling_exceeded` | The merchant's live price is outside what the rate allows right now: above its bound, in another asset or network, or unreadable (`reason`). | | `subscription_rail_unsupported` | The merchant asked for a rail credits don't pay (`rail`). | | `subscription_payment_refused` | Nevermined's treasury couldn't make this payment; `code` and `retryable` say why and whether to retry. | | `subscription_unavailable` | Credits can't be spent from this connection or deployment — for example an OAuth connection that isn't a commerce connection. | | `subscription_credits_not_granted` | An OAuth commerce connection you didn't allow to spend your credits (`BCK.OAUTH.0037`). Reconnect and tick **Let this assistant spend my Nevermined credits**. No `alternative`. | | `personal_grant_org_refused` | An OAuth connection allowed to spend your credits, used in an organization (`BCK.OAUTH.0038`): it spends only your personal credits. No `alternative`, and a delegation-only argument doesn't avoid it: pass `funding: "delegation"` to pay from the delegation. | | `subscription_cap_reached` | Not returned today: the subscription has no spending limit beyond your credits. Retry later if you see it. | With `funding` omitted, a call whose credits a dispute or an overdue renewal froze before it was quoted is paid from your delegation instead, with `fundingCode` saying why. With `funding` omitted, `{ "error": "funding_undetermined", "retryable": true }` means what would pay this call couldn't be decided — nothing was charged; retry. Other failures of a credits call use the usual outcomes above — `payment_failed`, `payment_indeterminate`, `already_paid`, `pending` — with `funding: "subscription"`: read `code` and `retryable`. > [!NOTE] > > A credits call refused at the call because too few credits are left (`insufficient_credits`) is **not** moved to your delegation on its own — starting to spend money when your credits run out is your decision. Retry with `funding: "delegation"` if you want the delegation to pay. To have a pack of credits charged automatically instead, the human turns on [top-ups](/docs/products/catalog/router/subscription#turn-on-top-ups) in the Nevermined App; an assistant can't turn them on. ## Try it **Ask your assistant:** > Pay `openweather-mpp` for the current weather in Lisbon and show me the response. **Call it directly** (⚠️ **charges real funds** — rehearse on `https://mcp.sandbox.nevermined.app/mcp` first): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"pay_service","arguments":{"slug":"openweather-mpp","path":"/openweather/current-weather","body":{"lat":38.72,"lon":-9.14}}}}' ``` # payment_summary Source: https://nevermined.ai/docs/mcp/catalog-mcp/payment-summary Catalog MCP tool: count your Router payment requests over a period, plus a daily time series. Count your Router payment **requests** over a period. This reports numbers of payments, **not money**. Reading charges nothing. Needs a credential. **Auth:** key / grant · **Charges:** nothing ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `from` | no | string | ISO-8601 lower bound on `createdAt`, inclusive. | | `to` | no | string | ISO-8601 upper bound on `createdAt`, inclusive. | ## Returns A total, a daily series (oldest first), and a charged-not-delivered count: ```json theme={null} { "total": 42, "series": [ { "date": "2026-10-01", "value": 18 }, { "date": "2026-10-02", "value": 24 } ], "chargedNotDelivered": 0 } ``` * `total` is uncapped (unlike [`list_payments`](/docs/mcp/catalog-mcp/list-payments)'s 1000-record cap). * `chargedNotDelivered` is the count of failed payments in the period whose merchant charge was observed — **flag a non-zero count to the user**. For *amounts* use [`list_payments`](/docs/mcp/catalog-mcp/list-payments); for what's spent or left use [`get_budget`](/docs/mcp/catalog-mcp/get-budget). ## Try it **Ask your assistant:** > How many payments have I made this week? **Call it directly** (charges nothing): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"payment_summary","arguments":{}}}' ``` # quote_service Source: https://nevermined.ai/docs/mcp/catalog-mcp/quote-service Catalog MCP tool: price one call to a service without paying it — the live, fee-inclusive total, rail, and network. Price **one** call to a service **without paying it**: it charges nothing, signs nothing, and reserves no budget. Pass exactly what you'd pass to [`pay_service`](/docs/mcp/catalog-mcp/pay-service); the Router sends that request to the service unpaid, reads the price, and returns a `quoteId` plus the fee-inclusive total. Needs a credential (API key or OAuth `commerce` grant). **Auth:** key / grant · **Charges:** nothing > [!WARNING] > > **A quote contacts the service.** To read the price, the Router sends your request to the service unpaid — the same request a payment starts with. A service that doesn't charge for it **performs it**, so take care quoting a method with side effects. The service's response is never returned to you. A quote also spends the same per-service rate limit as a payment, so quote **once per decision**; don't poll. ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `slug` | yes | string | The service slug to quote. | | `path` | no | string | The same `path` you'd pass to `pay_service` (from [`get_service`](/docs/mcp/catalog-mcp/get-service)), placeholders replaced. Query params go in `search`. | | `search` | no | string | Query string without `?`, for a slug-routed `GET` (e.g. `flight_iata=AA217`). | | `method` | no | string | HTTP method. Omit to use the catalog method for the endpoint matching `path` (`POST` when none recorded). | | `body` | no | any | The request payload you'd send; some services price by it. | | `headers` | no | object | Extra headers you'd send to the vendor. | | `delegationId` | no | string | The delegation you'd pay with (API key only). A card or org-wallet delegation can select a different rail, and so a different price. An OAuth caller is always quoted for its grant. | | `requireProtocol` | no | string | Price only `x402` or `mpp`. Pass the same pin to `pay_service`; the returned `quoteId` binds that rail. If unavailable, returns `quote_failed` with `BCK.ROUTER.0045`, nothing charged. Omit to auto-select (MPP first). Subscription-credit quotes price the credit tariff without applying this pin; the paid call still enforces it. | | `funding` | no | string | `"subscription"` or `"delegation"`, as on `pay_service`. Omit it to get the [price in credits](#quote-in-subscription-credits) when your Nevermined credits can pay this call, and the delegation quote otherwise. | ## Returns The rail, the merchant amount, and the fee-inclusive total. `fee.capChargedCents` is whole cents rounded up; `fee.capChargedMicros` is exact (1/10,000 of a cent): ```json theme={null} { "paymentRequired": true, "upstreamStatus": 402, "optionSet": "delegation", "delegationId": "121b880a-…", "quoteId": "qt_8f2a…", "expiresAt": "2026-10-02T14:05:00.000Z", "protocol": "x402", "x402Version": 2, "settlement": { "recipient": "0x2096…", "amount": "20000", "asset": "USDC", "network": "base", "approxCents": "2" }, "fee": { "bps": 200, "amount": "400", "cents": "1", "capChargedCents": "3", "capChargedMicros": "20400" }, "request": { "method": "POST", "path": "/quote", "methodSource": "catalog", "catalogEndpoint": "/quote" }, "nextTool": "pay_service", "instructions": "Nothing was charged. `fee.capChargedCents` is the fee-inclusive total this call would cost." } ``` * **`optionSet: "delegation"`** — the delegation `pay_service` would charge, named in `delegationId`. * **`optionSet: "deployment"`** — you have no delegation yet, so this is what a personal crypto delegation *would* select; `nextTool` is `setup_delegation`. Set one up and **quote again** before paying — the delegation you create can select a different rail and price. * **`paymentRequired: false`** — the service didn't ask for payment for this request; `upstreamStatus` is its answer. A non-2xx usually means the `path`, `method` or `body` is wrong. * **`sessionDeposit`**, present when `settlement.scheme` is `session`, is what this call would do to your wallet on top of its price. The service is paid out of a deposit in a payment channel, and that deposit can far exceed the price of the call. It is locked, not spent, it isn't charged to your budget, and what the service doesn't use comes back when the channel closes, `idleCloseSeconds` after its last use. Tell the human before paying. | Field | Meaning | | - | - | | `action` | `open` (this call locks a deposit), `top_up` (it locks more), `none` (your channel covers it, so no new money leaves the wallet), `closing` (the call would be refused and nothing moves; quote again once it has closed), or `null` (what the call would do couldn't be stated, and `pay_service` may refuse it, so `approxCents` is only the most it could be). | | `amount` / `approxCents` | How much would move into the deposit, in the token's smallest unit and in cents, the network fee not included. | | `basis` | `sized` for this budget and wallet as they stand now, or `upper_bound`: the most it could lock. | **To pay with the quote pinned,** pass `quoteId` to [`pay_service`](/docs/mcp/catalog-mcp/pay-service) before `expiresAt` with the exact same call arguments. The quote id fixes the challenge and the exact fee-inclusive total; keep `maxTotalCents` as an independent ceiling. ## Quote in subscription credits When your [Nevermined credits](/docs/products/catalog/router/subscription) can pay this call — from a subscription, free credits or top-up packs — `quote_service` answers from Nevermined's rate card alone — **the service isn't contacted**, so the warning above doesn't apply: ```json theme={null} { "funding": "subscription", "slug": "webscrape-pro", "credits": 3, "tariffVersion": 2, "request": { "method": "POST", "path": "/scrape", "methodSource": "catalog", "catalogEndpoint": "/scrape" }, "nextTool": "pay_service", "instructions": "Nothing was charged. `credits` is the number of credits one call to this endpoint uses …" } ``` `credits` is what one call to this endpoint costs at the current rate. There's no `quoteId` or cent total: pay with `pay_service` and the same arguments. For a subscriber in good standing, the quote doesn't check the credits left (without one, it checks that they cover the call, unless an automatic [top-up](/docs/products/catalog/router/subscription#top-ups) would); it never checks the merchant's live price or Nevermined's treasury — `pay_service` checks those when it makes the call. `funding` follows the same rules as on [`pay_service`](/docs/mcp/catalog-mcp/pay-service#pay-with-subscription-credits): omitted, a call credits can't price gets the delegation quote instead, with `fundingReason`; with `funding: "subscription"`, it is refused with the same [error names](/docs/mcp/catalog-mcp/pay-service#refusals-when-paying-with-credits). ## Refusals (all charge nothing) | Result | Meaning | What to do | | - | - | - | | `{ "payable": false }` | Not payable via the Router (only x402/MPP are). | Nothing to quote. | | `{ "error": "service_not_found" }` | No listed service has that slug. | Check the slug with `search_services`. | | `{ "error": "catalog_unavailable" }` / `"delegation_lookup_failed"` | A read the quote needs failed. | Transient — retry later. | | `{ "error": "quote_unavailable", "code": … }` | No quote can be made here and retrying won't change that. | Bound the price with `pay_service`'s `maxTotalCents` instead. | | `{ "error": "quote_failed", "code": …, "retryable": … }` | The Router refused to price, or didn't answer. | Read `code` / `message` / `retryable`; a no-answer is safe to retry. | | `{ "error": "quote_failed", "code": "BCK.ROUTER.0047" }` | The delegation refuses session payments, and nothing else can pay this call. | Use a service that charges per call, or report to the human, who can deliberately drop a `requireProtocol: "mpp"` pin or create a delegation that allows them. An app connected over OAuth holds its delegation through its grant, so they disconnect the app in Nevermined and reconnect it with session payments allowed instead. | | `{ "error": "credential_refused" }` | Your credential was refused. | Re-authorize. | ## Try it **Ask your assistant:** > Quote a current-weather call to `openweather-mpp` for Lisbon before paying. **Call it directly** (charges nothing, but reaches the service — see the warning above): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"quote_service","arguments":{"slug":"openweather-mpp","path":"/openweather/current-weather","body":{"lat":38.72,"lon":-9.14}}}}' ``` # route_by_intent Source: https://nevermined.ai/docs/mcp/catalog-mcp/route-by-intent Catalog MCP tool: from a plain-language need, find — and optionally pay — the single best payable catalog service, plus a ranked shortlist. Given a plain-language need, find — and optionally pay, in the same call — the **single best payable** Catalog service, so your agent doesn't pick among listings itself. The ranking is deterministic (no model reads the listings) and runs behind a fail-closed payability gate (listed, healthy, moderated, on x402/MPP, not flagged unpayable). When nothing passes, you get an explicit refusal, never a weak match. Needs a credential; **charges real funds only with `autoPay: true`.** **Auth:** key / grant · **Charges:** real funds if `autoPay` ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `intent` | yes | string | Plain-language description of the service you need (`"translate English to German"`). | | `filters` | no | object | Structured narrowing (all optional) — see below. | | `limit` | no | integer | Shortlist size, 1–20. Default 5. | | `autoPay` | no | boolean | `true` also pays the winner in the same call (same path as `pay_service`). Default `false` → return the pick only, no charge. | | `delegationId` | with `autoPay` on API key | string | Delegation to charge. An OAuth caller spends from its grant and can omit this. | | `requestId` | with `autoPay` | string | Idempotency key — **required** when `autoPay` is true. | | `method`, `path`, `search`, `body`, `headers` | no (`autoPay` only) | — | The paid call's request, applied to whichever service wins. | | `credentialHeader` | no (`autoPay` only) | string | Header the minted payment credential rides in, when the winning service **also** needs its own auth (e.g. `"Payment"`). | | `maxTotalCents` | no (`autoPay` only) | integer | Refuse a paid quote above this (fee-inclusive), before purchase. | **`filters` fields:** `require` (exact opaque slug — returned only if payable and healthy, else fails closed with `BCK.ROUTER.0031`, never substituted), `prefer` (exact opaque slug, moved up when a payable match), `exclude` (never chosen), `category` (matches tags, not category names), `protocol` (`x402` or `mpp`), `network`, `maxPriceLabel` (e.g. `"$0.05"`, best-effort). > [!WARNING] > > **With `autoPay: true` you're shaping a request for a service you haven't seen yet.** A bare call reaches the winner's base URL, which for a multi-endpoint API is a 404, not a purchase. An `autoPay` call also ranks afresh, so it pays whatever wins *this* time. When the exact service or endpoint matters, propose first (`autoPay: false`), read [`get_service`](/docs/mcp/catalog-mcp/get-service) on `chosen.slug`, then pay with [`pay_service`](/docs/mcp/catalog-mcp/pay-service). ## Returns With `autoPay: false`, a proposal (nothing charged): ```json theme={null} { "chosen": { "slug": "openweather-mpp", "title": "OpenWeather", "priceLabel": "$0.005–$0.01", "network": "Tempo", "protocol": "mpp", "invokeUrl": "https://api.live.nevermined.app/api/v1/router/svc/openweather-mpp" }, "shortlist": [ { "slug": "openweather-mpp", "matchReason": "semantic_similarity", "rankingSource": "semantic", "healthy": true, "priceLabel": "$0.005–$0.01" } ], "rankingSource": "semantic", "instructions": "This is a proposal — nothing was charged. `chosen` is the best payable service and `shortlist` is the ranked set." } ``` * **`chosen`** is the winner; its `invokeUrl` is the Router's opaque alias, never the merchant's host. Pay it by `slug`. * **`shortlist`** is the payable candidates in pick order. Each carries a closed `matchReason`, `gateReason`, per-item `rankingSource`, and one scale-specific score. **Read the order, not the numbers** — the scores sit on different scales. `healthy` is always `true` here. * With **`autoPay: true`**, the same fields plus **`result`** (the upstream call and the payment receipt). Read the outcome from `result.payment.status` — `Settled`, `Issued` (attempted, not confirmed) or `Failed` — not from `paid` alone. `instructions` is always present and names the next step. ## Refusals | Result | Meaning | What to do | | - | - | - | | `{ "status": "no_fundable_match" }` | No listed, healthy, payable service matched; nothing charged. | Broaden or rephrase `intent`, relax `filters`, call again. | | `{ "status": "missing_autopay_fields" }` | `autoPay: true` without `requestId` (or, on an API key, without `delegationId`); nothing charged. | Add the field and call again. | | `{ "status": "payment_indeterminate", "requestId": "…" }` | On `autoPay`, the charge outcome couldn't be confirmed. | **Never retry with a fresh `requestId`.** Reconcile with `list_payments`; retry with the **same** `requestId`. | | `{ "status": "already_paid", "paymentId": "…" }` | This `requestId` already has a payment; not a new charge, and the vendor response isn't replayed. | Find `paymentId` in `list_payments`. Buying again takes a **new** `requestId`. | Any other `autoPay` refusal (cap exceeded, wallet short, card declined) comes back as a plain tool error (`isError: true`) carrying the Router's own message — see [`pay_service`'s refusals](/docs/mcp/catalog-mcp/pay-service#outcomes-and-refusals). If unsure whether it charged, check `list_payments` and retry only with the **same** `requestId`. ## Try it **Ask your assistant:** > Find the best Nevermined service for the current weather in Lisbon. **Call it directly** (`autoPay` defaults to `false`, so this proposes and charges nothing): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"route_by_intent","arguments":{"intent":"current weather for Lisbon"}}}' ``` # search_services Source: https://nevermined.ai/docs/mcp/catalog-mcp/search-services Catalog MCP tool: search the Nevermined Agent Services Catalog for paid services, ranked by hybrid semantic + keyword relevance. Search the Catalog for paid services, ranked by **ARD hybrid relevance** — semantic (meaning) matches merged with lexical (keyword) matches, most relevant first — falling back to pure lexical when the embedding provider is unavailable. **Discovery only — free, no credential, nothing charged.** To have the platform **pick** (and optionally pay) the single best service for a need instead of choosing yourself, use [`route_by_intent`](/docs/mcp/catalog-mcp/route-by-intent). **Auth:** free · **Charges:** nothing ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `query` | yes | string | What you need, in plain language (`"translate documents to German"`). Ranked semantically **and** lexically. | | `category` | no | string | Restrict to services carrying this catalog **tag** (filters on tags exactly like `tag`). Given together with `tag`, matches a service carrying **either** one. | | `protocol` | no | enum | One of `x402`, `mpp`, `rest`, `a2a`, `other`. Only `x402` and `mpp` are payable via the Router. | | `tag` | no | string | Restrict to services carrying this catalog tag (a protocol or domain keyword from a listing's `tags`). | | `prefer` | no | string | Move this opaque catalog slug to the front **when it matched the returned page**; otherwise keep the normal ranked fallback. | | `exclude` | no | string | Never return this opaque catalog slug. | | `pageSize` | no | integer | Page size, 1–100. | > [!WARNING] > > **Only the first page is returned.** The `pageToken` in the result **cannot be passed back** to this tool. To see other matches, narrow the `query` or filters, or raise `pageSize` (up to 100). ## Returns `results` (ARD records) and an opaque `pageToken` (informational only). Each result carries catalog metadata under `nvm:catalog` plus its own ranking fields. A record's `identifier` is a URN — the slug is its last segment (`urn:air:api.live.nevermined.app:service:openweather-mpp` → `openweather-mpp`): ```json theme={null} { "results": [ { "identifier": "urn:air:api.live.nevermined.app:service:openweather-mpp", "displayName": "OpenWeather", "type": "application/json", "url": "https://api.live.nevermined.app/api/v1/router/svc/openweather-mpp", "description": "Global weather data — current conditions, forecasts, air quality, geocoding", "tags": ["weather", "forecast", "conditions", "temperature"], "nvm:catalog": { "protocol": "mpp", "invokeUrl": "https://api.live.nevermined.app/api/v1/router/svc/openweather-mpp", "priceLabel": "$0.005–$0.01", "displayPriceLabel": "$0.008", "displayPriceSource": "settled", "network": "Tempo", "healthStatus": "operational", "routerPayable": true }, "rankingSource": "semantic", "matchReason": "semantic_similarity", "semanticScore": 46 } ], "pageToken": "eyJvZmZzZXQiOjJ9" } ``` Reading the ranking: * **Read the order, not the numbers.** Results come back in pick order. * `rankingSource` is per-item — `semantic` or `lexical`. `matchReason` is a closed value explaining the match. * The score field is scale-specific (`semanticScore` for a semantic match, a lexical score otherwise). The two scales are not comparable — don't re-sort across them. * `displayPriceSource: "settled"` means the `displayPriceLabel` reflects real multi-payer settlement — the service is genuinely used, not just advertised. Then read one service in full with [`get_service`](/docs/mcp/catalog-mcp/get-service). ## Try it **Ask your assistant:** > Search the Nevermined catalog for weather services. **Call it directly** (discovery is free — no credential needed): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_services","arguments":{"query":"weather","pageSize":5}}}' ``` # setup_delegation Source: https://nevermined.ai/docs/mcp/catalog-mcp/setup-delegation Catalog MCP tool: start the spending-delegation ceremony and return one URL for a human to approve a spending cap. Start the spending-delegation ceremony and return **one URL** for a human to open. Use it when [`pay_service`](/docs/mcp/catalog-mcp/pay-service) returns `{ "error": "no_delegation" }`. It sets up a **stablecoin (crypto)** delegation that spends from the human's personal wallet — it does **not** enroll a card. The human sets the currency, cap, duration, and transaction limit in the browser; the agent cannot set them and must not ask the human to pass them back. Needs a credential. **Auth:** key / grant · **Charges:** nothing ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `returnUrl` | no | string | Where the browser lands after authorising. Only a localhost callback (`http://127.0.0.1:/…`) or an origin this deployment allow-lists is accepted; a rejected value is reported, not silently dropped. **Omit it** unless you actually have somewhere to receive the redirect — in a chat host the page just shows a confirmation and the human closes the tab. | ## Returns A URL to open, or confirmation a budget already exists: ```json theme={null} { "status": "human_action_required", "url": "https://embed.nevermined.app/cards/delegate?provider=crypto&network=live&sessionToken=…", "expiresAt": "2026-10-02T14:00:00.000Z", "instructions": "Relay the url, wait for the human to confirm, then call pay_service again." } ``` ```json theme={null} { "status": "already_active", "delegationId": "121b880a-…", "budget": { "capCents": "500", "spentCents": "8", "remainingCents": "492", "currency": "usdc", "expiresAt": "2026-10-02T13:29:31.691Z" }, "source": "oauth_grant", "message": "Your spending budget is in place: cap 5.00 USDC, 0.08 USDC spent, 4.92 USDC remaining.", "instructions": "No human action is needed now. Call pay_service; it spends from this budget by default." } ``` * `already_active` means a usable budget is in place (for an OAuth caller, the grant approved on the consent screen) — relay `message` as it stands, then call `pay_service`. * `budget` carries only the figures the API reported, and is omitted when none did. `source` (`oauth_grant` or `account`) is omitted when unknown. `message` and `instructions` are always present. > [!WARNING] > > The `url` embeds a short-lived session token bound to the human's account. Treat it as a credential — give it only to the account owner, never share it. **Other outcomes (no URL):** `delegation_setup_unavailable` (this deployment can't run the ceremony), `delegation_setup_failed` (the session couldn't start), `return_url_not_allowed` (drop or fix `returnUrl`), and a `human_action_required` answer with `delegationCheck: "failed"` (an existing budget couldn't be ruled out — follow its `instructions` and try `pay_service` first). The human also chooses there whether the delegation may pay services that take a refundable deposit at the first call (see [session deposits](/docs/products/catalog/router/guardrails#session-deposits)). A delegation can't be edited, so that holds for its whole life. ## Try it **Ask your assistant:** > Set up a spending budget so I can pay for Nevermined services. **Call it directly** (charges nothing — returns a URL for a human to approve a cap): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"setup_delegation","arguments":{}}}' ``` # top_up_credits Source: https://nevermined.ai/docs/mcp/catalog-mcp/top-up-credits Catalog MCP tool: charge one credit pack to the card your human enrolled, within the monthly top-up limit they set. Charges real funds. Refill your [Nevermined credits](/docs/products/catalog/router/subscription#top-ups) within the human-set monthly limit. Charges one **pack of 10,000 credits that never expire** to the card your human enrolled — **no new human approval** — and only when your spendable credits are below the call you're about to make. **This charges the human's card.** Needs a credential (API key, or a `commerce` OAuth grant that enabled credit top-ups at consent). Turning top-ups on and setting the monthly limit stay with the human, in the [Nevermined App](https://nevermined.app) — this tool charges a pack *within* that limit, it does not create or change it. With your **own API key** and top-ups on, a credits call that runs out charges a pack on its own (see [`pay_service`](/docs/mcp/catalog-mcp/pay-service#when-a-call-charges-a-top-up-pack)). Through an **OAuth connection** it never does — so for an OAuth-connected agent (the Claude.ai, ChatGPT or Fleet connectors) `top_up_credits` is the only way to get a pack. Either way, call it to refill **before** a call, so the credits are in place when you make it. **Auth:** key / grant (grant must allow top-ups) · **Charges:** real funds, the human's card ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `requestId` | yes | string | An idempotency handle you choose for **this** top-up. Use a **new** value for each top-up you intend; reuse the **same** value only to re-send a call that may not have completed — a retry returns the pack already charged, never a second one. 8–200 chars of letters, digits and `._:-` (e.g. a run id or a UUID). | | `forCallCredits` | yes | integer | The credits the call you're about to make will spend (read it from a [`quote_service`](/docs/mcp/catalog-mcp/quote-service) or your plan's per-call cost). A pack is charged only when your spendable credits are **below** this; when they already cover it, nothing is charged (`not_needed`). 1–1,000,000. | ## Returns The pack's result and where your top-up spend stands this month. Dollar amounts are before tax. The MCP relays the API body unchanged and adds an `instructions` string — follow it. ```json theme={null} { "status": "bought", "replayed": false, "purchaseId": "9c2e4a71-…", "creditsAdded": "10000", "monthlyLimitUsd": 30, "boughtThisMonthUsd": 10, "packPriceUsd": 10, "operatorUrl": null, "message": "Added 10000 credits." } ``` * `creditsAdded` is a **decimal string**, set on every `bought` — replayed or not. Only `replayed: false` means **this** call charged the pack; `replayed: true` means this `requestId` had already bought one and nothing new was charged. * `operatorUrl` is a link to hand the human; it's set on `needs_attention` and `disabled`, `null` otherwise. * **A pack was charged** on `bought` with `replayed: false`, **is being or may have been charged** on `pending`, and **may have been charged** on a `needs_attention` whose `message` says the outcome is unconfirmed. Every other status charged nothing. Relay `message` to the human whenever a pack was or may have been charged. To read the limit before you decide, without charging anything, use `GET /api/v1/credits/topups/pack` (`enabled`, `monthlyLimitUsd`, `maxMonthlyLimitUsd`, `boughtThisMonthUsd`, `packPriceUsd`, `paused`) — it serves both credential kinds. (The `topups` block on [`GET /api/v1/credits/balance`](/docs/products/catalog/router/subscription#credits) carries the same, but balance takes a plain API key.) ## Outcomes Read `status` (see the charge rule above — `bought`/`pending`/unconfirmed `needs_attention` are the ones where the card may have been touched). | `status` | Meaning | What to do | | - | - | - | | `bought` | A pack was charged and its credits are in your balance (`creditsAdded`). If `replayed` is `true`, this `requestId` had already bought one and **nothing new** was charged. | Make your call. Use a **new** `requestId` next time. | | `pending` | Your pack **is being charged and may already be**; its credits land once the payment is confirmed. | Don't start a new top-up. Read your balance shortly, or re-send the **same** `requestId` to read the outcome. | | `busy` | Another top-up is already being charged — **nothing was charged for this request**. | Check your balance shortly; re-send the **same** `requestId` only if you still need one. | | `limit_reached` | This UTC month's top-up limit is used up; nothing charged. | Don't retry until next month, or ask the human to raise the limit. | | `not_needed` | Your spendable credits already cover `forCallCredits`; nothing charged. | Make your call — you don't need a pack. | | `needs_attention` | A human must act: the card was declined or needs 3-D Secure, a card payment is disputed, setup is unfinished, a prior top-up is stuck, or a prior top-up's outcome is unconfirmed (it **may** have been charged). | Hand the human `operatorUrl`; **never** try to confirm 3-D Secure yourself. Don't start a new top-up until they act — if the message says the outcome is unconfirmed, keep the **same** `requestId`. | | `disabled` | Top-ups aren't on; nothing charged. | Give the human `operatorUrl` to turn them on in the App. | | `unavailable` | Nothing was charged. | Retry with a **new** `requestId` — reusing this one keeps returning the same settled result. | ### Errors A refusal comes back as an `error` result, not an HTTP status (through the MCP tool you never see one) — each carries a `code`, a `message` and an `instructions` string; **follow `instructions`**: * `{ "error": "topup_failed", "code", "message", "instructions" }` — the top-up was refused. Coded consent/credential refusals: `BCK.OAUTH.0040` (the grant lacks **top-up** consent), `BCK.OAUTH.0030` (not a commerce grant), `BCK.OAUTH.0038` (an organization context), and `404 BCK.CREDIT_TOPUPS.0001` (top-ups aren't available to this account or deployment). * `{ "error": "topup_unsupported" }` — this deployment's API is too old for top-ups. * a credential-refused result — re-authorize, or set your API key. > [!WARNING] > > **A new `requestId` per top-up; the same one only to re-send.** When you drive the REST route directly, on any non-2xx other than a coded `4xx` refusal, or no response at all, re-send with the **same** `requestId` — the charge may have landed, and the id returns that pack instead of charging a second one. Even a coded pre-charge `4xx` on a **reused** id can follow an earlier call that did charge: keep the same id and read [`get_budget`](/docs/mcp/catalog-mcp/get-budget) rather than starting a new top-up (with a plain API key, `GET /api/v1/credits/topups/purchases` also lists the packs; an OAuth grant can't read it). A `needs_attention` whose message says the outcome is unconfirmed may already have charged — same rule. > [!NOTE] > > An OAuth grant needs **Let this assistant top up my Nevermined credits** ticked at consent, separately from the credit-spend box. A grant allowed to spend but not to top up is refused here with `BCK.OAUTH.0040`; a top-up-only grant can't spend (`BCK.OAUTH.0041` on the stablecoin routes, `BCK.OAUTH.0037` on the credits route). Reconnect with the right boxes — see [Who can spend your credits](/docs/products/catalog/router/subscription#who-can-spend-your-credits). ## Try it **Ask your assistant:** > My credits are low and the next call needs about 1,000. Top up within my limit, then make the call. **Call it directly** (⚠️ **charges the human's card** — rehearse on `https://mcp.sandbox.nevermined.app/mcp` first): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"top_up_credits","arguments":{"requestId":"run-7f3a9c21-topup-1","forCallCredits":1000}}}' ``` The REST equivalent is `POST /api/v1/credits/topups/pack` with the same `{ "requestId", "forCallCredits" }` body and your API key. # wallet_balance Source: https://nevermined.ai/docs/mcp/catalog-mcp/wallet-balance Catalog MCP tool: read the balances of your own personal wallet — the funding source the crypto rails pull from, per network. Read the balances of your **own personal wallet** — the funding source the crypto rails **pull from** when [`pay_service`](/docs/mcp/catalog-mcp/pay-service) charges a personal delegation. It answers *how much do I have, and on which chain*. Reading charges nothing. Needs a credential. **Auth:** key / grant · **Charges:** nothing ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `network` | no | integer | Chain id to read. **Omit it** to see every network this deployment settles on — which is what you want unless the merchant already told you which chain it settles on. | ## Returns The wallet address and, per network, its token balances and the money it has locked in payment channels: ```json theme={null} { "address": "0x1234…abcd", "networks": [ { "network": 8453, "balances": [ { "symbol": "USDC", "decimals": 6, "atomic": "1500000", "formatted": "1.5" }, { "symbol": "EURC", "decimals": 6, "atomic": "0", "formatted": "0" } ], "lockedInChannels": [] }, { "network": 4217, "balances": [ { "symbol": "USDC.e", "decimals": 6, "atomic": "4000000", "formatted": "4" }, { "symbol": "EURC.e", "decimals": 6, "atomic": "0", "formatted": "0" } ], "lockedInChannels": [ { "network": 4217, "token": "0x20C000000000000000000000b9537d11c60E8b50", "symbol": "USDC.e", "decimals": 6, "atomic": "6000000", "formatted": "6" } ] } ] } ``` > [!WARNING] > > **Read the network the merchant quoted, not the one with money in it.** Live settles on two chains with two tokens — most services accept only one. A healthy balance on one chain says nothing about a purchase on the other; that's why every chain is reported by default. * A token whose `atomic`/`formatted` is **`null`** was **not read** (the on-chain read failed) — that is **not** a zero balance. A chain that couldn't be read at all comes back as an entry with `error` instead of `balances`. * **`lockedInChannels`** is money your payer wallet (the one the Router signs MPP payments with, which is this wallet once your account is migrated) has deposited into payment channels with merchants that charge per call over an MPP session, per token, held in the channel's escrow. It is **not** part of `balances` and it is **not spent**: it can pay further calls only to the merchant holding that channel, and what is unused comes back to that wallet when the channel closes, after 15 minutes without use. Report it beside the balance, never as spending, and never count it toward paying any other merchant. A null `symbol`/`decimals`/`formatted` here means a token Nevermined does not recognise (report `atomic` as raw units of `token`), not an unread amount. An empty list means nothing is locked; **`null`** means it could not be read, not that nothing is locked. * Pass a chain id this deployment does **not** serve and you get the deployment's **primary** network back (its own chain id, not the one you asked for) with a `warning` — so those balances say nothing about the chain you asked about. ## What it doesn't cover * A delegation backed by an [organization wallet](/docs/solutions/organizations/wallets) is paid from *that* wallet, not this one. * A **card** delegation has no wallet at all — there `BCK.ROUTER.0009` is the card **issuer** declining, with nothing to top up, so this tool doesn't apply and the fix is a different card. * On **MPP** the wallet is checked before anything is signed, and `BCK.ROUTER.0009` names the wallet and chain but never **how much** is there — which is what this tool supplies. On **x402** there's no balance pre-check and `BCK.ROUTER.0009` is never raised: the credential is minted, **budget is reserved**, and a short wallet only surfaces when the merchant's on-chain transfer fails — by which point the budget is already committed, and the reserve comes back only once the reconciler sees the authorization expire unconsumed. So read the balance **before** you pay, and don't read a just-committed reserve as money lost. This tool diagnoses, it doesn't fix: there's no on-ramp and an agent can't top up its own wallet, so a genuine shortfall is a **stop condition** — report the network and amount to the human and don't retry. ## Nevermined credits With an API key, the result also carries the same `subscription`, `credits` and `creditsMessage` fields as [`get_budget`](/docs/mcp/catalog-mcp/get-budget#nevermined-credits): your [Nevermined credits](/docs/products/catalog/router/subscription), free and top-up credits included, by kind and expiry, and your subscription if you have one. Credits aren't in your wallet — Nevermined pays the merchant on a credits call, so a credits call needs no wallet balance at all. ## Try it **Ask your assistant:** > What is my wallet balance on each network? **Call it directly** (charges nothing): ```bash theme={null} curl -X POST https://mcp.live.nevermined.app/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer $NVM_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"wallet_balance","arguments":{}}}' ``` # Docs MCP Overview Source: https://nevermined.ai/docs/mcp/docs-mcp/overview Vibe-code your Nevermined payments integrations directly from your AI IDE using our MCP server. > [!NOTE] > > You can use the Nevermined Docs MCP server to vibe-code applications directly > from Claude Code, Open Code, Cursor, Continue, Zed, and other MCP-aware IDE > copilots. Point any MCP-compatible client at the server URL below to stream > up-to-date docs into your coding sessions. > [!NOTE] > > **LLM Context Files for AI Assistants** > > If you're using an AI assistant for development, you can provide comprehensive context files to streamline your integration: > > * **Concise Context**: [https://nevermined.ai/docs/llms.txt](https://nevermined.ai/docs/llms.txt) - Quick reference with key concepts and examples > * **Full Context**: [https://nevermined.ai/docs/llms-full.txt](https://nevermined.ai/docs/llms-full.txt) - Complete documentation for in-depth integration work. It is large (about 2 MB), more than most fetch tools take in one read; prefer `llms.txt` and the `.md` version of each page. > > Simply copy the contents and paste them into your LLM's input as a knowledge base. > [!NOTE] > > **MCP Configuration File** > > For quick setup with MCP-compatible IDEs, download our pre-configured MCP file: > > * **Download**: [nevermined.mcp.json](/docs/download/nevermined-mcp-config) - Ready-to-use configuration for Cursor, Continue, Claude Desktop, and other MCP clients > > Use this file as a reference or copy its contents into your IDE's MCP configuration. The Nevermined Docs MCP Server provides seamless access to all Nevermined's documentation directly within your AI development environment. By integrating this MCP server, you can build AI agents and applications with real-time access to Nevermined's payment SDKs and Libraries, API references, and development guides. > [!NOTE] > > Not the same server as the [Catalog MCP](/docs/mcp/catalog-mcp/overview). The **Docs MCP** streams this documentation into your IDE so an assistant can vibe-code an integration — it sells nothing and moves no money. The **Catalog MCP** lets an agent discover and *pay for* external services. ## Tools The Docs MCP exposes three tools. Each has its own reference page: | Tool | What it does | | - | - | | [`search_nevermined_documentation`](/docs/mcp/docs-mcp/search-documentation) | Semantic search across the documentation — returns titles, snippets, and page links. | | [`query_docs_filesystem_nevermined_documentation`](/docs/mcp/docs-mcp/query-docs-filesystem) | Read-only shell (`rg`, `cat`, `tree`, `jq`, …) over a virtual filesystem of the docs pages and OpenAPI specs. | | [`submit_feedback`](/docs/mcp/docs-mcp/submit-feedback) | Report an incorrect, outdated, or confusing documentation page to the docs team. | ## What is MCP? The Model Context Protocol (MCP) is an open standard that enables AI applications to securely connect to external data sources and tools. Think of MCP as a "USB-C for AI" - it provides a standardized way to connect AI models to different services, documentation, and APIs. **Key Benefits:** * 🔌 **Standardized Connections**: Connect any MCP-compatible AI client to our documentation * 🔄 **Real-time Access**: Always up-to-date information from our docs * 🛡️ **Secure Integration**: Built-in security and authentication * 🌍 **Remote Access**: No local installation required ## MCP Server Details **Nevermined Documentation MCP Server URL:** `https://nevermined.ai/docs/mcp` This server provides access to: * Complete Nevermined API documentation * Development guides and tutorials * Code examples in Python and TypeScript * Payment plan configuration guides * AI agent registration workflows ### Instant Setup Commands Choose your IDE and run the corresponding command for zero-friction setup: > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http nevermined-docs https://nevermined.ai/docs/mcp > ``` > [tab] Cursor > > ```bash theme={null} > mkdir -p ~/.cursor && echo '{ > "mcpServers": { > "nevermined-docs": { > "url": "https://nevermined.ai/docs/mcp", > "type": "http" > } > } > }' > ~/.cursor/mcp.json > ``` > [tab] Continue > > ```json theme={null} > // Add to ~/.continue/config.json > { > "mcpServers": [ > { > "name": "nevermined-docs", > "url": "https://nevermined.ai/docs/mcp", > "transport": "http" > } > ] > } > ``` > [tab] Claude Desktop > > ```json theme={null} > // Add to ~/Library/Application Support/Claude/claude_desktop_config.json > { > "mcpServers": { > "nevermined-docs": { > "url": "https://nevermined.ai/docs/mcp", > "type": "http" > } > } > } > ``` Then restart your IDE to activate the connection. ## Quick Setup for Vibe-Code Tools Follow these lightweight steps to attach the Nevermined Docs MCP server to popular code-native AI tools. Each tool simply needs the remote MCP endpoint `https://nevermined.ai/docs/mcp`. > [!TIP] > > **Quick Start**: Download the [nevermined.mcp.json](/docs/download/nevermined-mcp-config) configuration file and use it as a reference for your IDE's MCP setup. The file contains the complete configuration needed for most MCP-compatible tools. ### Claude Code (VS Code extension) **One-Line Setup** (Recommended): Run this command in your terminal for instant setup: ```bash theme={null} claude mcp add --transport http nevermined-docs https://nevermined.ai/docs/mcp ``` **Alternative - GUI Setup**: 1. Open the Command Palette and run "Claude: Open Settings" 2. In **Model Context Protocol** → **Custom Connectors**, click **Add** 3. Enter the server URL `https://nevermined.ai/docs/mcp` and save 4. Start chatting; the Nevermined docs source appears under available connectors ### Cursor IDE **One-Line Setup** (Recommended): ```bash theme={null} # Create or update Cursor MCP config mkdir -p ~/.cursor && echo '{ "mcpServers": { "nevermined-docs": { "url": "https://nevermined.ai/docs/mcp", "type": "http" } } }' > ~/.cursor/mcp.json ``` Then restart Cursor to activate the connection. **Alternative Methods**: 1. **Using Configuration File**: * Download [nevermined.mcp.json](/docs/download/nevermined-mcp-config) * Copy contents to `~/.cursor/mcp.json` * Reload the IDE 2. **Manual GUI Setup**: * Open Settings → search for **MCP Servers** * Add remote server: `https://nevermined.ai/docs/mcp` * Enable the connector in chat ### Open Code **Quick Setup**: Add to your MCP configuration: ```bash theme={null} # Add to your Open Code MCP settings echo '{ "mcpServers": { "nevermined-docs": { "url": "https://nevermined.ai/docs/mcp", "type": "http" } } }' >> ~/.opencode/mcp.json ``` Or manually add the server in Settings → **Model Context Protocol** ### Continue (VS Code / JetBrains) **Quick Setup**: Add to your Continue configuration (`~/.continue/config.json`): ```json theme={null} { "mcpServers": [ { "name": "nevermined-docs", "url": "https://nevermined.ai/docs/mcp", "transport": "http" } ] } ``` **Or via Continue UI**: 1. Open Continue settings and locate **MCP / Tools** 2. Add MCP server: `nevermined-docs` → `https://nevermined.ai/docs/mcp` 3. Reload Continue to activate > If your IDE supports MCP but is not listed, add a remote MCP connector pointing to > `https://nevermined.ai/docs/mcp` and enable it for chat/code actions. The server > requires no extra auth beyond your Nevermined API usage in code samples. ## Setting Up Your IDE with Nevermined MCP Server ### Option 1: Using Claude Desktop (Recommended) Claude Desktop provides excellent MCP support with a user-friendly interface for connecting to remote MCP servers. #### Step 1: Install Claude Desktop Download and install Claude Desktop from [Claude's official website](https://claude.ai/download). #### Step 2: Configure the MCP Server 1. **Open Claude Desktop** and sign in to your account 2. **Access Settings**: Click on your profile icon and select "Settings" 3. **Navigate to Connectors**: In the settings sidebar, click on "Connectors" 4. **Add Custom Connector**: Scroll to the bottom and click "Add custom connector" 5. **Enter Server URL**: In the dialog box, enter: ```text theme={null} https://nevermined.ai/docs/mcp ``` 6. **Complete Setup**: Click "Add" to establish the connection The Nevermined Documentation MCP server will now be available in your Claude conversations! > [!TIP] > > **Configuration Reference**: If you prefer to edit the configuration file directly (located at `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS), see our [nevermined.mcp.json](/docs/download/nevermined-mcp-config) for the correct format. #### Step 3: Access Nevermined Documentation 1. **Start a Conversation**: Open a new chat in Claude Desktop 2. **Access Resources**: Click the paperclip icon (📎) in the message input area 3. **Select Nevermined Resources**: You'll see available documentation resources from the Nevermined MCP server 4. **Use in Prompts**: Select relevant documentation to include context in your conversations ### Option 2: Using Claude Web (claude.ai) You can also connect to the Nevermined MCP server through Claude's web interface using Custom Connectors. #### Step 1: Access Claude Settings 1. Go to [claude.ai](https://claude.ai/) and sign in 2. Click your profile icon and select "Settings" 3. Navigate to "Connectors" in the sidebar #### Step 2: Add Nevermined MCP Server 1. Click "Add custom connector" 2. Enter the server URL: `https://nevermined.ai/docs/mcp` 3. Complete any authentication prompts 4. Configure tool permissions as needed ### Option 3: Other MCP-Compatible Clients The Nevermined MCP server works with any MCP-compatible client. For a full list of supported clients, visit the [MCP Clients page](https://modelcontextprotocol.io/clients). Popular MCP-compatible tools include: * **Continue** (VS Code extension) * **Cursor IDE** * **Zed Editor** * **Custom applications** using MCP SDKs For detailed setup instructions for other clients, refer to the [Model Context Protocol documentation](https://modelcontextprotocol.io/docs/getting-started/intro). ## Prompt Examples for Building AI Agents Once you have the Nevermined MCP server connected, you can use these example prompts to build AI agents and client applications: ### 1. Create a Basic AI Agent ```text theme={null} I want to create an AI agent that validates user requests using Nevermined. Please show me how to: 1. Register an AI agent with Nevermined 2. Set up payment plans with credits-based pricing 3. Implement request validation in TypeScript 4. Handle authorization errors properly Include complete code examples and explain each step. ``` ### 2. Build a Client Application ```text theme={null} Help me build a TypeScript client application that can: 1. Purchase access to a Nevermined AI agent 2. Send authenticated requests to the agent 3. Handle payment errors and reauthorization 4. Monitor remaining credits and subscription status Show me the complete implementation with error handling. ``` ### 3. Multi-Agent Workflow ```text theme={null} I want to create a multi-agent system where: 1. Agent A processes text analysis requests 2. Agent B generates summaries based on Agent A's output 3. Both agents use different payment plans 4. Users pay once but can access both agents How do I implement this workflow using Nevermined? Show me the agent registration, payment configuration, and orchestration code. ``` ### 4. Payment Plan Configuration ```text theme={null} Help me design payment plans for my AI service: 1. A free trial plan (100 requests, 7 days) 2. A basic plan (1000 requests per month, $10 USDC) 3. A premium plan (unlimited requests, $50 USDC per month) Show me how to implement these plans and handle upgrades/downgrades. ``` ### 5. Agent-to-Agent Payments ```text theme={null} I'm building an AI agent marketplace where agents can purchase services from other agents. Show me how to: 1. Set up autonomous agent-to-agent payments 2. Implement automatic credit management 3. Handle payment authorization between agents 4. Track revenue and usage across multiple agents Provide complete Python and TypeScript examples. ``` ### 6. Integration with Existing Services ```text theme={null} I have an existing AI service running on FastAPI. Help me integrate it with Nevermined to: 1. Add payment validation to my existing endpoints 2. Implement subscription management 3. Add usage tracking and analytics 4. Support both crypto and fiat payments Show me how to modify my existing code with minimal changes. ``` ## Advanced Use Cases ### Building Custom MCP Servers You can also create your own MCP servers that integrate with Nevermined. Here's how to get started: ```text theme={null} I want to build a custom MCP server that: 1. Exposes my company's internal AI tools 2. Uses Nevermined for access control and payments 3. Provides dynamic pricing based on tool complexity 4. Integrates with our existing authentication system Show me the architecture and implementation using the MCP SDK. ``` ### Marketplace Development ```text theme={null} Help me build an AI agent marketplace using Nevermined where: 1. Developers can register and monetize their AI agents 2. Users can discover and purchase access to agents 3. The platform takes a commission on sales 4. Agents can be combined into workflows Include the frontend, backend, and payment integration code. ``` ### Enterprise Integration ```text theme={null} I need to integrate Nevermined into our enterprise environment: 1. Connect with our existing identity provider (OAuth/SAML) 2. Implement cost allocation across departments 3. Add detailed usage reporting and analytics 4. Support both on-premise and cloud deployments Show me the architecture and configuration needed. ``` ## Best Practices When using the Nevermined MCP server, follow these best practices: ### Security Considerations * **Verify Connections**: Always ensure you're connecting to the official Nevermined MCP server * **Review Permissions**: Only grant necessary tool permissions in your MCP client * **Secure API Keys**: Store Nevermined API keys securely and never expose them in client-side code ### Development Workflow 1. **Start with Documentation**: Use the MCP server to understand Nevermined concepts 2. **Test in Sandbox**: Always test your implementations in Nevermined's sandbox environment 3. **Iterate with Examples**: Use the provided code examples as starting points 4. **Monitor Usage**: Implement proper logging and monitoring for production deployments ### Performance Optimization * **Cache Documentation**: Cache frequently accessed documentation locally when possible * **Batch Requests**: Group related operations to minimize API calls * **Implement Retries**: Add retry logic for transient failures * **Monitor Limits**: Respect rate limits and implement backoff strategies ## Troubleshooting ### Common Issues #### Connection Failed * Verify you're using the correct URL: `https://nevermined.ai/docs/mcp` * Check your internet connection * Ensure your MCP client supports remote servers #### Authentication Errors * Verify your Nevermined API key is correctly configured * Check that you're using the right environment (sandbox vs production) * Ensure your API key has the necessary permissions #### Documentation Not Loading * Try refreshing the connection in your MCP client * Check if the MCP server is accessible at: [https://nevermined.ai/docs/mcp](https://nevermined.ai/docs/mcp) * Restart your MCP client if issues persist ### Getting Help If you encounter issues or need assistance: 1. **Check the Documentation**: Use the MCP server to search for relevant guides 2. **Community Support**: Join our [Discord community](https://discord.com/invite/GZju2qScKq) for help 3. **GitHub Issues**: Report bugs or request features on our [GitHub repository](https://github.com/nevermined-io) 4. **Enterprise Support**: Contact our team for enterprise-level assistance ## Next Steps Once you have the Nevermined MCP server set up: 1. **Explore the Documentation**: Use the MCP connection to browse our complete documentation 2. **Build Your First Agent**: Follow the quickstart guide to create your first monetized AI agent 3. **Implement Payment Plans**: Design and configure payment plans that match your business model 4. **Test Integration**: Use the sandbox environment to test your implementation 5. **Go Live**: Deploy your AI agents to production with real payments The Nevermined MCP server provides the foundation for building sophisticated AI applications with built-in monetization. Start exploring and building today! # query_docs_filesystem_nevermined_documentation Source: https://nevermined.ai/docs/mcp/docs-mcp/query-docs-filesystem Docs MCP tool: run a read-only shell (rg, cat, tree, jq, …) over a virtual filesystem of the Nevermined docs pages and OpenAPI specs. Run a **read-only, shell-like** query against a virtualized, in-memory filesystem rooted at `/` that contains **only** the Nevermined documentation pages and OpenAPI specs. This is not a shell on any real machine — nothing runs on your computer, the server host, or any network; the filesystem is a sandbox backed by documentation chunks. This is how you read a page in full: there is no separate "get page" tool. See the [Docs MCP overview](/docs/mcp/docs-mcp/overview) for how to connect. **Charges:** nothing — public documentation only. ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `command` | yes | string | A shell command to run against the virtual filesystem (e.g. `rg -il "keyword" /`, `tree / -L 2`, `head -80 /path/file.mdx`). | ## How it works * **Read a page:** a page at URL path `/some/page` lives at `/some/page.mdx`. Read it with `head -200 /some/page.mdx` or `cat /some/page.mdx`. * **Discover paths — never guess them:** use `tree / -L 2`, `ls /`, or [`search_nevermined_documentation`](/docs/mcp/docs-mcp/search-documentation). A path that doesn't exist only means the guess was wrong, not that the topic is undocumented — use `rg -il "keyword" /` to find it. * **OpenAPI specs** are mounted at `/openapi/api-reference/openapi.json`, `/openapi/api-reference/oauth-openapi.json`, and `/openapi/api-reference/organizations-openapi.json`. Example: `cat /openapi/api-reference/openapi.json | jq '.paths | keys'`. **Supported commands:** `rg` (ripgrep), `grep`, `find`, `tree`, `ls`, `cat`, `head`, `tail`, `stat`, `wc`, `sort`, `uniq`, `cut`, `sed`, `awk`, `jq`, plus basic text utilities. No writes, no network, no process control. Run `--help` on any command for usage. > [!WARNING] > > **Each call is stateless.** The working directory always resets to `/` and no variables, aliases, or history carry over between calls. To operate in a subdirectory, chain commands in one call with `&&` or pass absolute paths (e.g. `cd /some-dir && ls`, or `ls /some-dir`). Output is truncated to **30 KB** per call — prefer targeted `rg -C 3 "pattern" /path/file.mdx` or `head -N` over a broad `cat` on large files, and batch multiple file reads into one `head`/`cat`. ## Returns The command's stdout, truncated to 30 KB. When referencing pages back to the user, convert filesystem paths to URL paths by removing the `.mdx` extension (`/some/page.mdx` → `/some/page`). ## Try it **Ask your assistant:** > Show the top-level structure of the Nevermined documentation. **Call it directly** (the docs server replies over SSE — `event: message` / `data: …`): ```bash theme={null} curl -X POST https://nevermined.ai/docs/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"query_docs_filesystem_nevermined_documentation","arguments":{"command":"tree / -L 2"}}}' ``` # search_nevermined_documentation Source: https://nevermined.ai/docs/mcp/docs-mcp/search-documentation Docs MCP tool: semantic search across the Nevermined documentation knowledge base, returning titles, snippets, and page links. Search across the Nevermined documentation knowledge base to find relevant information, code examples, API references, and guides. Use it to answer questions about Nevermined, find specific pages, understand how features work, or locate implementation details. The search returns contextual content with titles and direct links to the documentation pages. See the [Docs MCP overview](/docs/mcp/docs-mcp/overview) for how to connect. **Charges:** nothing — this server reads public documentation only. ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `query` | yes | string | The search query — plain language works best (`"how to authenticate"`, `"rate limiting"`). | ## Returns Ranked results, each with a title, a contextual snippet, and a link to the page. Results are the best entry point for a broad or conceptual question. To read a page in full after searching, use [`query_docs_filesystem_nevermined_documentation`](/docs/mcp/docs-mcp/query-docs-filesystem): append `.mdx` to the path a result returns and `head` or `cat` it — a result at `/some/page` is read with `head -200 /some/page.mdx`. > [!TIP] > > Use this tool for **broad or conceptual** queries. For exact keyword/regex matching, structural exploration, or reading a full page by path, reach for [`query_docs_filesystem_nevermined_documentation`](/docs/mcp/docs-mcp/query-docs-filesystem). ## Try it **Ask your assistant:** > Search the Nevermined docs for how to add payments to a FastAPI agent. **Call it directly** (the docs server replies over SSE — `event: message` / `data: …`): ```bash theme={null} curl -X POST https://nevermined.ai/docs/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_nevermined_documentation","arguments":{"query":"add payments to a FastAPI agent"}}}' ``` # submit_feedback Source: https://nevermined.ai/docs/mcp/docs-mcp/submit-feedback Docs MCP tool: report an incorrect, outdated, or confusing Nevermined documentation page to the docs team. Report a problem with the documentation site so the docs team can fix it. Use it when a page is incorrect, outdated, confusing, incomplete, or has a broken example. This is for feedback about the **documentation content itself** — not product support requests, and not feedback about the tool or assistant. See the [Docs MCP overview](/docs/mcp/docs-mcp/overview) for how to connect. **Charges:** nothing. ## Arguments | Argument | Required | Type | Description | | - | - | - | - | | `path` | yes | string | The URL path of the page the feedback is about (the page you were reading, **without** the `.mdx` extension). | | `feedback` | yes | string | A clear description of the issue or suggestion — what is incorrect, outdated, missing, or confusing. | ## Returns A confirmation that the feedback was recorded for the docs team. ## Try it **Ask your assistant:** > Report that the `pay_service` page example is missing the required path for multi-endpoint services. **Call it directly** (the docs server replies over SSE — `event: message` / `data: …`): ```bash theme={null} curl -X POST https://nevermined.ai/docs/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"submit_feedback","arguments":{"path":"/mcp/catalog-mcp/pay-service","feedback":"The pay_service example is missing the required path for multi-endpoint services."}}}' ``` # Agent Scoring — catalog indicators Source: https://nevermined.ai/docs/products/catalog/agents-scoring The authoritative reference for every indicator, cap, and band in the Nevermined Catalog readiness score. The **readiness score** measures how completely a Catalog service is prepared for an autonomous buyer to discover, evaluate, invoke, and pay for it. It is a builder-facing score from **0 to 100**, calculated with a versioned rubric (each score records its `readiness/X.Y.Z`; see [rubric versions](#rubric-versions)) from published metadata, endpoint definitions, operational guidance, and observed health. Readiness is not the service's `qualityScore`, popularity, or traction. It does not judge whether an output is insightful or whether buyers prefer the service. Instead, it identifies gaps that can prevent an otherwise useful service from being found, selected, called correctly, or purchased safely. The score is **deterministic**: fixed rules award the points described on this page; no LLM decides the result. It is also **advisory** and never gates whether a service can be listed. Individual endpoint-based checks can award partial credit according to the proportion of applicable endpoints that pass. ## How the score is calculated The rubric adds six dimensions, then applies any readiness cap triggered by a fundamental blocker: | Dimension | Maximum points | What it measures | | - | -: | - | | Metadata | 15 | Whether buyers and agents can identify, understand, and place the service. | | Endpoints & schemas | 25 | Whether every operation is callable and has an explicit request/response contract. | | Pricing clarity | 20 | Whether payable operations disclose an actionable, machine-readable cost model. | | Documentation | 15 | Whether human and automated integrators can retrieve a complete integration guide. | | Operations & preconditions | 10 | Whether callers can prepare credentials, funds, limits, and recovery behavior. | | Health | 15 | Whether live observations show a valid payment challenge, availability, and settlement readiness. | After the points are summed, the lowest triggered cap becomes the final maximum. A service with no reachable callable endpoint or a known settlement failure cannot score above **39**. A service with no discoverable payment mechanism cannot score above **59**. Caps do not remove points from the underlying dimension results; they constrain the final score until the blocker is fixed. > [!NOTE] > > The Catalog can calculate a **provisional** score before it has live probe evidence. In provisional mode, H1–H3 are marked `not_observed` and award no points, so the highest possible score is **85**. Caps are applied only to a full score, once the required operational evidence has been observed. ## Metadata — 15 points Metadata determines whether a service can be recognized and matched before an agent examines its API. Each metadata indicator is worth 3 points. ### M1 — Clear title **What it checks.** The title must contain at least three non-whitespace characters and must not be a placeholder such as `todo`, `tbd`, `n/a`, `test`, `description`, or `lorem ipsum`. A passing title earns 3 points. **Why it matters.** The title is the first identity signal in search results and comparison views. A specific, stable name lets buyers distinguish the service from alternatives and gives automated agents a reliable label to cite, rank, and remember; a blank or generic title makes even strong metadata difficult to associate with the right offer. **How to improve.** Use the product or service name buyers will recognize. Keep it specific enough to identify this offering, remove draft labels and environment names, and use the same name in your homepage and documentation so callers can confirm they reached the intended service. ### M2 — Short description **What it checks.** The short description must usefully summarize the service, must not be a recognized placeholder, and must not simply repeat the title. A passing description earns 3 points; length alone does not make a description useful. **Why it matters.** This summary is the at-a-glance explanation shown when a buyer or agent is deciding which listings deserve closer inspection. An outcome-focused sentence improves matching and prevents callers from opening a service only to learn that its capability, inputs, or result is unrelated to their task. **How to improve.** Lead with the result the caller receives, then name the key capability or audience. Write a distinct sentence rather than a slogan or restatement of the title—for example, describe that the service returns normalized company intelligence from a domain, not merely that it is a “company data API.” ### M3 — Detailed description **What it checks.** The detailed description must usefully explain the service's capability, intended use, and expected result, and must not be a recognized placeholder. A passing description earns 3 points; length alone does not make a description useful. **Why it matters.** Buyers need enough context to judge fit before integrating or spending money, while autonomous agents need explicit scope to avoid choosing a superficially similar service. A useful description reduces mismatched purchases by explaining the capability, intended use, and expected result rather than leaving those facts to inference. **How to improve.** Describe what the service does, who or what it is designed for, the main input, and the output a successful caller should expect. Add important scope boundaries—such as geography, data freshness, or supported media—when they materially affect selection, and keep endpoint-specific details in the endpoint documentation. ### M4 — Retrievable logo **What it checks.** The listing must provide a logo that the Catalog can retrieve successfully. A missing logo is `not_observed`; a configured but unretrievable logo fails. A retrievable logo earns 3 points. **Why it matters.** A consistent visual identity helps buyers recognize a provider across search, listing, and checkout surfaces. Broken images or URLs that work only in an authenticated browser weaken trust and make the listing appear abandoned even when the endpoint itself is healthy. **How to improve.** Publish the logo at a stable HTTPS URL that returns the image without cookies, authentication, expiring signatures, or referer restrictions. Use a durable production asset, verify it from outside your own network, and avoid URLs tied to temporary uploads or private object-storage permissions. ### M5 — Category and homepage **What it checks.** Both a non-empty category and a non-empty homepage URL must be present; the rule awards all 3 points only when both fields pass. The category should be meaningful and the homepage URL valid and usable. **Why it matters.** Category metadata places the service in relevant discovery results, while the homepage gives buyers a trusted destination for broader product and provider context. Supplying only one leaves either automated matching or human verification incomplete. **How to improve.** Select the most specific supported Catalog category that describes the service's primary outcome, and add the canonical public homepage for the offering or provider. Confirm the homepage uses HTTPS, loads without private access, and clearly connects the provider identity to the service in the listing. ## Endpoints & schemas — 25 points These indicators define the callable contract. Endpoint records are deduplicated by normalized HTTP method and path; E2–E5 award proportional credit across the resulting endpoints. ### E1 — At least one endpoint **What it checks.** The listing must publish at least one service endpoint. This is a binary 5-point check: one or more endpoint records pass, while an empty endpoint set fails. **Why it matters.** A listing without an endpoint can be discovered but cannot be invoked. Buyers cannot verify what operation they are purchasing, and agents have no destination on which to obtain a payment challenge or submit a correctly formed request. **How to improve.** Publish the service's primary callable operation first, including the protocol details required to address it. Prefer an endpoint that exercises the core paid outcome, then add the remaining supported operations; after publishing, verify that at least one advertised method and path is reachable from outside your infrastructure. ### E2 — Methods, paths, and descriptions **What it checks.** Every endpoint must have a non-empty HTTP method, path, and description. The rule is worth 5 points and awards proportional partial credit based on how many published endpoints contain all three values. **Why it matters.** The method and path tell an agent where and how to invoke an operation; the description tells it why that operation is the right one. Missing any of the three forces callers to guess, which commonly produces wrong routes, unsupported methods, or selection of an operation whose purpose does not match the requested task. **How to improve.** Audit every published endpoint. Set the actual HTTP verb and exact request path, then write a purpose-focused description that states the operation's result rather than repeating its URL. Remove obsolete endpoint records so incomplete legacy definitions do not continue reducing coverage. ### E3 — Request schemas **What it checks.** Every endpoint must either publish a request schema or explicitly declare that it takes no parameters. The rule is worth 5 points, awarded in proportion to covered endpoints. **Why it matters.** A machine-readable request contract lets an autonomous caller validate field names, types, required values, and nesting before making a potentially paid call. Without it, trial-and-error requests increase failure rates, support load, and the risk that a buyer pays for work triggered with unintended inputs. **How to improve.** Add a schema for path, query, header, and body inputs as applicable, marking required fields and constraints precisely. If an operation genuinely accepts no caller-supplied input, make the bare request—with no body or query—return its payment challenge so the Catalog probe can record the endpoint as parameterless. Start with payable endpoints and fields whose type or required status is easiest to misinterpret. ### E4 — Response schemas **What it checks.** Every endpoint must define a successful response schema. The rule is worth 5 points, awarded in proportion to the endpoints with a response contract. **Why it matters.** Buyers should be able to determine whether the result will be usable before they pay, and agents need field names and types to parse it safely afterwards. An undocumented response can turn a successful purchase into unusable data or brittle extraction logic. **How to improve.** Define the complete successful response shape for each operation, including required fields, types, nested objects, arrays, and nullable values. Make pagination or asynchronous result envelopes explicit, and keep the schema synchronized with production responses when fields are added or changed. ### E5 — Safe request examples **What it checks.** Every endpoint must include a valid, safe request example. The rule is worth 5 points, awarded in proportion to endpoints with an example. **Why it matters.** Examples resolve ambiguities that schemas cannot always convey, such as realistic combinations of optional fields, formatting conventions, or a minimum useful request. They also give agents a known-safe template for a first call instead of encouraging experimentation against a paid production operation. **How to improve.** Add one representative example per endpoint that conforms to its current request schema and exercises a normal, low-risk use case. Replace credentials, personal data, production account identifiers, destructive actions, and chargeable real-world targets with clearly synthetic values; test each example whenever the schema changes. ## Pricing clarity — 20 points Pricing indicators apply to endpoints identified as payable. Coverage is calculated across those endpoints; P4 applies only to dynamically priced endpoints. ### P1 — Prices or quotes **What it checks.** Every payable endpoint must expose either a current fixed price or a way to obtain a quote. The rule is worth 6 points and awards proportional credit across payable endpoints; if no payable endpoint is identified, the rule fails rather than assuming pricing is complete. **Why it matters.** A buyer should not have to attempt a transaction to discover its cost. Price or quote availability lets agents compare alternatives, check a budget, and decide whether to proceed before committing payment. **How to improve.** Publish a current fixed amount for deterministic charges and a quote path for charges that depend on inputs or usage. Cover every payable operation, not only the most common one, and ensure the disclosed cost corresponds to what the payment challenge will request. ### P2 — Machine-readable prices **What it checks.** Every payable endpoint's price or quote must be represented as structured data. A declared MPP `session` counts as machine-readable (on the full score since `readiness/1.1.0`; the provisional estimate counted it already). The Catalog reads its amount, token, and chain from the session offer's structured fields. The rule is worth 6 points and awards proportional credit; an absence of identified payable endpoints does not pass the rule. **Why it matters.** Agents cannot reliably compare budgets, currencies, or terms by extracting numbers from prose such as “about one cent.” Structured pricing removes locale and unit ambiguity and allows callers to enforce spending policies without a human interpreting the listing. **How to improve.** Encode amount, currency or asset, unit, and relevant payment terms in stable fields rather than only in descriptive text. Use one unambiguous unit convention, preserve exact precision, and expose quote results in the same structured form across all payable endpoints. ### P3 — Fixed or dynamic pricing **What it checks.** The Catalog classifies each payable endpoint as fixed or dynamic. An endpoint whose payment challenge declares an MPP `session` is dynamic (on the full score since `readiness/1.1.0`; the provisional estimate did so already). The exceptions are a fixed MPP `charge` or x402 price that the Nevermined Router pays instead, and a session the Router would not pay, for example one on a chain or in a token it does not support, billed in a unit other than per request, or with a foreign escrow, fee token or unaudited field. A declaration counts only when it was observed in the last 48 hours on an endpoint the analysis finds payable (see the [`readiness/1.1.0` entry](#readiness-1-1-0)). Otherwise the Catalog infers the model from observed quotes: consistent quoted amounts indicate fixed pricing, and differing amounts indicate dynamic pricing. The rule is worth 4 points and awards proportional credit, while no identified payable endpoints produces a failure. **Why it matters.** A fixed-price classification tells an agent that the observed amount is stable for the operation. A dynamic classification tells it that the charge can change and that it must obtain or refresh a quote; leaving the model unknown invites stale assumptions and budget surprises. **How to improve.** Return consistent, machine-readable amounts in each payable operation's payment challenge. If the price is metered, declare it as an MPP `session` offer. Otherwise, make sure representative requests produce accurate quotes so the Catalog can observe the variability. ### P4 — Dynamic price drivers **What it checks.** For each dynamically priced endpoint, the Catalog looks for an expected price range, the input or usage factor that changes the price, and the billing unit. The rule is worth 4 points and awards proportional credit. * **A declared MPP `session`** (on the full score since `readiness/1.1.0`) passes when it declares a budget cap (`suggestedDeposit`). Its unit is the request: the only unit the Router pays, whether `unitType` is `request` or absent. * **An endpoint inferred as dynamic from observed quotes** needs the observed range and the price driver. A missing price driver is incomplete rather than a hard failure until price-driver capture is available. If payable endpoints exist but none is dynamic, the rule passes as not applicable. If no payable endpoint is identified, the rule fails rather than treating an empty set as complete. **Why it matters.** “Dynamic” alone does not let a buyer estimate exposure or let an agent reason about how a request changes the bill. The range establishes likely bounds, the driver explains what varies, and the unit connects consumption to cost. **How to improve.** For a metered MPP service, set `suggestedDeposit` on the `session` offer. It is the budget a buyer locks in the channel, and it bounds what one session can cost. Give it in the token's atomic units, as a digits-only string like `amount`; an offer with a malformed deposit is not read at all. Bill per request: leave `unitType` out or set it to `request`. The Router does not pay a session metered in another unit (tokens, seconds), so such an offer earns no Pricing credit. For other dynamic operations, return accurate, machine-readable quotes across representative requests so the Catalog can observe the range and variability. A declaration form for the exact price driver, such as input tokens, output seconds, records, or compute time, arrives with price-driver capture. ## Documentation — 15 points Documentation indicators measure whether detailed integration guidance is both retrievable and complete beyond the compact Catalog record. ### D1 — Reachable documentation **What it checks.** The service must publish documentation at a location the Catalog can reach. A reachable location earns 4 points, an observed failure earns none, and documentation that has not been observed is marked `not_observed`. **Why it matters.** The Catalog summary cannot contain every integration detail. A stable public source of truth lets buyers investigate before committing and lets agents retrieve instructions when endpoint metadata alone is insufficient; private pages and broken redirect chains provide neither benefit. **How to improve.** Publish the documentation at a canonical HTTPS URL that loads without private credentials, interactive login, or expiring access tokens. Test redirects and linked assets from an unauthenticated session, and maintain the URL across documentation platform or domain migrations. ### D2 — Setup and payment walkthrough **What it checks.** The documentation must include an end-to-end walkthrough covering setup, authentication, payment, and one successful invocation. A complete walkthrough earns 4 points; missing observed content earns none, while unavailable evidence is `not_observed`. **Why it matters.** Integrators often fail at the transitions between separate reference sections: obtaining prerequisites, attaching credentials, responding to a payment challenge, and finally invoking the service. One coherent first-run path reduces abandonment and gives agents an ordered procedure they can execute and verify. **How to improve.** Write a minimal working flow from a clean environment to a successful response. List prerequisites, show how merchant authentication differs from payment authorization, demonstrate the payment exchange, and include the exact request and expected success signal. Keep optional production hardening outside the critical path. ### D3 — Per-endpoint documentation **What it checks.** Every published endpoint must be documented with its request schema, response schema, and representative examples. The rule is worth 4 points and awards proportional credit across endpoints. **Why it matters.** Complete documentation for one operation cannot safely stand in for another. Agents should not infer the inputs, outputs, side effects, or usage of an undocumented endpoint, especially when each call can incur a separate charge. **How to improve.** Inventory the endpoint list and create a dedicated operation reference for each method-and-path pair. Include the request and successful response contracts plus representative examples, then add validation to your release process so an endpoint cannot be published or changed without updating its corresponding documentation. ### D4 — Machine-readable discovery **What it checks.** The service must expose a stable, structured discovery document describing the service and its operations. A discoverable document earns 3 points; an observed absence earns none, while unavailable evidence is `not_observed`. **Why it matters.** Machine-readable discovery allows agents to inspect capabilities and contracts directly instead of scraping human-oriented prose. That improves matching, makes integrations reproducible, and reduces malformed calls when layouts or wording change. **How to improve.** Publish a maintained discovery document in an appropriate structured format, at a stable public location, covering the service identity and available operations. Ensure its methods, paths, schemas, and examples agree with the Catalog listing and production API; automate generation or consistency checks where possible. ## Operations & preconditions — 10 points Operational indicators make requirements and recovery behavior visible before a caller starts a paid workflow. ### O1 — Authentication preconditions **What it checks.** The service must declare all authentication credentials, headers, permissions, enrollment steps, and other authorization prerequisites. A complete declaration earns 3 points; an observed gap earns none, while unavailable evidence is `not_observed`. **Why it matters.** Payment authorization and merchant authentication are separate concerns. If a buyer learns about a required API token, account role, or custom header only after selecting the service, otherwise valid calls fail and an agent may incorrectly interpret an authentication refusal as a payment problem. **How to improve.** List every prerequisite before the invocation steps: credential type, where it is obtained, header or parameter name, required scopes or roles, and any enrollment requirement. State explicitly when no additional merchant authentication is required, and never put live secrets in examples. ### O2 — Network and funding requirements **What it checks.** The service must state the required payment network, accepted asset or payment rail, and funding prerequisites. A complete declaration earns 3 points; an observed gap earns none, while unavailable evidence is `not_observed`. **Why it matters.** A buyer can have sufficient value on the wrong chain or in the wrong asset and still be unable to pay. Ambiguous network and rail requirements lead directly to rejected transactions, delays, or attempts to use incompatible funds. **How to improve.** Name the exact network and environment, supported asset or card rail, and any minimum balance, wallet, allowance, or funding preparation required. Distinguish testnet from mainnet and document each supported alternative separately so callers can confirm compatibility before requesting a quote or challenge. ### O3 — Limits and timeout behavior **What it checks.** The service must document rate or usage limits, timeout expectations, and whether long-running work completes synchronously or asynchronously. A complete declaration earns 2 points; an observed gap earns none, while unavailable evidence is `not_observed`. **Why it matters.** Agents need these constraints to plan concurrency, waiting, and retries without duplicating paid work. If a request times out with no documented completion model, a caller cannot know whether the operation stopped, is still running, or will charge again when retried. **How to improve.** Publish applicable rate and quota limits, expected and maximum response times, and the response pattern for work that outlives an HTTP request. For asynchronous operations, document status polling or callbacks, terminal states, result retention, and how the original request remains correlated and idempotent. ### O4 — Errors and support **What it checks.** The service must document error responses, retry and idempotency behavior, and a reachable support or escalation channel. A complete declaration earns 2 points; an observed gap earns none, while unavailable evidence is `not_observed`. **Why it matters.** Clear failure semantics let an agent distinguish a safe retry from a duplicate purchase and help a buyer resolve cases that automated recovery cannot. Without error contracts or support, repeated attempts can increase cost while obscuring the original failure. **How to improve.** Document status codes and structured error bodies, classify failures as retryable or terminal, and state how idempotency keys behave before and after payment. Provide a monitored support path with the diagnostic identifiers a caller should include, but instruct users never to send secrets or payment credentials. ## Health — 15 points Health points come from observed behavior rather than the listing's self-description. These checks are withheld in a provisional score. ### H1 — Valid payment challenge **What it checks.** A live probe must find the endpoint reachable and observe a valid payment challenge. Both conditions are required for 5 points. If reachability or challenge evidence is unavailable, the check is `not_observed`; an observed failure of either condition earns no points. **Why it matters.** A reachable endpoint that does not issue a standards-compliant challenge still gives an agent no actionable instructions for authorization and payment. Conversely, a theoretically correct payment configuration is useless if callers cannot reach the endpoint that serves it. **How to improve.** First restore DNS, TLS, routing, deployment, and request handling until the public endpoint responds. Then make an unauthenticated request and verify that the resulting challenge is valid for the advertised protocol and contains complete payment instructions. Repeat the test from outside your infrastructure rather than relying only on local checks. ### H2 — Endpoint liveness **What it checks.** Recent liveness contributes up to 5 points and can award fractional credit. The rubric prefers observed 7-day uptime, then 30-day uptime; without uptime coverage it derives a baseline from current health (`operational`, `degraded`, `unavailable`, or `unverified`). Reported health confidence can cap the contribution, so uncertain observations cannot claim stronger liveness than their evidence supports. **Why it matters.** Autonomous workflows depend on a service being available at the moment it is selected, not merely on a correct API description. Intermittent failures waste orchestration time, break downstream steps, and make a paid operation riskier even when discovery and payment metadata are complete. **How to improve.** Investigate recent probe and uptime failures before polishing lower-impact metadata. Fix recurring capacity, routing, TLS, dependency, or timeout problems; add monitoring for the public callable path; and keep the service stable long enough for current observations to replace historical failures and low-confidence evidence. ### H3 — Settlement readiness **What it checks.** The observed settleability verdict determines this 5-point check: `settleable` earns 5 points, `unknown` earns 3.33 points and is `partial`, `unpayable` earns none, and no observation is `not_observed` with no points. A known `unpayable` verdict also triggers the 39-point `knownUnpayable` cap. **Why it matters.** Reachability and a valid challenge do not prove that authorization and settlement complete. A known failure makes the service commercially unavailable and can leave buyers uncertain about whether value moved, while an unknown result provides less assurance than a confirmed settled transaction. **How to improve.** Exercise the advertised payment path end to end: obtain the challenge, authorize with the supported mechanism, settle, and confirm delivery of the successful result. Trace failures through challenge construction, network and asset configuration, authorization verification, settlement, and post-payment response handling; retain transaction evidence that proves a completed settlement. ## Readiness caps Caps represent blockers that make a high raw completeness score misleading. All triggered caps are reported, but the lowest cap controls the final score. ### CAP-noReachableEndpoint — No reachable callable endpoint **What it checks.** This cap triggers when there are no published endpoints or when every published endpoint is marked unreachable or uncallable. After all rule points are summed, the final score is limited to **39**. **Why it matters.** Documentation and presentation cannot make a service ready when no real operation accepts a call. Buyers cannot verify the offer, and agents cannot obtain a challenge, submit input, or receive a result, so the service is blocked at the first operational step. **How to improve.** Treat this as the highest-priority blocker. Publish an endpoint if none exists; otherwise repair DNS, TLS, routing, deployment, and request handling until at least one advertised method and path accepts a real external call. Verify the exact public endpoint rather than a private health URL, then allow the Catalog's live evidence to update. ### CAP-knownUnpayable — Known settlement failure **What it checks.** This cap triggers when observed payment settleability is `unpayable`. The final score is limited to **39**, regardless of the raw score from metadata, documentation, and other checks. **Why it matters.** A known settlement failure means the advertised service cannot currently complete the commercial exchange. Agents cannot safely substitute confidence in the docs for a payment that works, and repeated attempts may create uncertainty about authorization or delivery. **How to improve.** Stop treating the issue as a documentation gap and trace one controlled payment through every stage: challenge, authorization, verification, settlement, and successful result delivery. Correct the failing handler or configuration, test on the exact advertised network and rail, and confirm at least one end-to-end settled transaction before relying on the score to recover. ### CAP-noPaymentMechanism — No discoverable payment mechanism **What it checks.** This cap triggers when the evidence says no payment mechanism is discoverable. The final score is limited to **59** even if pricing prose or other integration material is present. **Why it matters.** A payable operation cannot be purchased autonomously unless a caller can determine which protocol or rail to use. Price alone is insufficient: the agent needs machine-discoverable instructions that connect the payable endpoint to the supported payment flow. **How to improve.** Publish the supported payment protocol or rail in structured service metadata and associate it with every payable endpoint. Verify that an unauthenticated caller can discover the mechanism before invocation and that the live endpoint issues the corresponding challenge; do not rely on human-only prose as the sole payment signal. ## Bands The final, cap-adjusted score maps to one of four bands: | Band | Score | Interpretation | | - | -: | - | | **Excellent** | 90–100 | Complete discovery and integration details with strong observed readiness. | | **Ready** | 75–89 | Usable by autonomous buyers, with a limited set of improvements remaining. | | **Almost there** | 60–74 | Meaningful readiness is present, but gaps can still disrupt selection, calling, or payment. | | **Getting started** | 0–59 | Foundational information or operational capability is still missing, or a cap is active. | The band summarizes readiness; use the failed and partial indicators—and any active cap—to decide what to fix. Improvements are prioritized with blockers first, then by recoverable points, affected endpoints, effort, and indicator ID. ## Provisional vs full score A provisional score uses the 85 points available from Metadata, Endpoints & schemas, Pricing clarity, Documentation, and Operations & preconditions. H1, H2, and H3 remain `not_observed` until live evidence is available, and no cap is applied provisionally. This prevents missing probe data from being presented as an observed failure while making the **85-point ceiling** explicit. A full score includes all 100 possible points and applies every triggered cap. Compare like with like when tracking changes: moving from provisional to full can change the total because Health evidence has arrived, even when no published metadata changed. ## When scores are calculated A score is calculated when you request an analysis and when you publish or update a Catalog listing. Nevermined can also re-score listed services, for example after a rubric change. Each analysis produces a new score; a score you were shown never changes afterwards. Your agent’s page in the Nevermined app (the **Catalog** and **Status** tabs) shows the score with the rubric version and date it was calculated, and marks a full score older than 7 days as **Stale** with a **Re-analyze** link. A service’s public Catalog page shows the score, its band, and the same version and date. ## Rubric versions Every score records the rubric version that produced it, `readiness/MAJOR.MINOR.PATCH`. A released version never changes. The scoring API reports it as `rubricVersion` (for example in `GET /api/v1/catalog/scoring/public/{slug}`), so you can check which version a score used. | Version level | What changed | Effect on your score | | - | - | - | | **MAJOR** | Anything structural: dimensions or their maximum points, indicators (added, removed, or renumbered), readiness caps (added, removed, or a new value), band boundaries, or whether caps apply to provisional scores | Points and bands can change for many services | | **MINOR** | Weights or checks within the existing dimensions, or recommendations that move points | Points can shift; a band change is possible | | **PATCH** | Wording, documentation, or other changes that cannot affect any score | None; existing scores keep their version until their next analysis | A new version applies to every analysis from its release, so a score keeps the version it was calculated with until the service is analyzed again. When your score moved because of a MAJOR or MINOR rubric change rather than a change to your service, your agent’s page says “Scoring criteria updated to `readiness/X.Y.Z` — this change reflects the rubric, not your service.” and links to that version’s entry in the [changelog](#changelog). ### Changelog #### readiness/1.1.0 * **Version level:** MINOR * **Summary:** The full score now reads the MPP `session` price a listed endpoint declares. It counts when the analysis finds the endpoint payable and the declaration was observed in the last 48 hours. A declared session is a machine-readable, dynamic price, unless the Router pays a fixed charge for that endpoint or would not pay the session (its chain, token or terms). P4 credits a session only when it declares a budget cap (its unit is the request). Before this version, every payable endpoint was treated as fixed on the full score, so P4 always passed. * **Dimensions:** Pricing clarity (P2, P3, P4). Weights, caps, and bands are unchanged. * **Why:** P4 checks that a dynamic price declares its range and unit, and it could never fail on the full score. * **Effect on your score:** * **Down** by up to 4 points if a listed endpoint declares a session without a budget cap. * **Up** by up to 6 points if a declared session's price was not machine-readable before. * **Up** by up to 2 points on the provisional estimate for an observed variable price whose price driver is not declared. P4 now gives that endpoint half credit instead of failing it. * **No change** for any other service, or for an analysis of a URL that is not a Catalog listing. #### readiness/1.0.0 * **Version level:** Initial release * **Summary:** Introduces the deterministic 0–100 readiness rubric, its six dimensions, caps, bands, and prioritized recommendations. * **Dimensions:** Metadata; Endpoints & schemas; Pricing clarity; Documentation; Operations & preconditions; Health. * **Why:** Give builders an explainable measure of whether a service is ready for an autonomous buyer to discover, evaluate, invoke, and pay for it, before it has any sales history. * **Effect on your score:** Initial baseline; there is no earlier version to compare. # AI Services Source: https://nevermined.ai/docs/products/catalog/ai-services What's available in the Nevermined Catalog, and how to add your own AI service — validated healthy before it's listed. Every entry in the Catalog is an external AI service that prices each request **on the wire**, so your agent can pay per call — no signup, no API key at the provider, no subscription. This page covers what's in the Catalog today and how to get your own service into it. ## What's available Listings span a curated set of categories, each with granular sub-categories: > [card] Data & Enrichment > [card] Search & Research > [card] Crypto & Blockchain > [card] Finance & Markets > [card] AI & Media > [card] Web Scraping & Automation > [card] Communication & Voice > [card] …and more The full set also includes Sales & Business Intelligence, Social & Creator, Identity & Compliance, Infrastructure & Compute, Weather, and Travel. Browse or query the live set — the current categories and their counts come from the public feed, never a hard-coded list. See [Discovering AI Services](/docs/products/catalog/discover). Each service settles on one of two payment rails the Router can pay: | Protocol | What it is | In the Catalog | | - | - | - | | **x402** | The service answers `HTTP 402` advertising an `accepts` array | ✅ Listed | | **MPP** | The service answers `HTTP 402` with a `WWW-Authenticate: Payment` challenge | ✅ Listed | ### What gets listed The Catalog only lists services the Router can actually pay — those that price each request on the wire (**x402** and **MPP**). Services that authenticate with a long-lived API key and bill you monthly aren't listed: there's no per-call price on the wire for the Router to settle. The Catalog surfaces only what an autonomous agent can buy, so it's never handed a service it can't pay for. ## Add your AI Service The Catalog is also where you list a service **you** own so other buyers' agents discover and pay for it. From a **paid** organization (Starter or above) in the [Nevermined app](https://nevermined.app), publish one of your registered agents into the Catalog with a category, its callable endpoint, and presentation details (title, description, logo, tags, features). For the step-by-step — the two ways to submit and what each one needs — see **[Publish to the Catalog](/docs/products/catalog/publish-ai-service)**. You supply only presentation and the endpoint. Trust-sensitive facts are derived server-side rather than accepted from you — the payment **protocol** and **price** are detected from your endpoint, and ownership is taken from the agent — so a listing can't misrepresent what it charges or who runs it. ### Listed only once it's validated healthy Before your service goes live, a monitor **probes the endpoint to confirm it actually responds** — a listing is never published on your word alone. It also keeps checking after launch, so the Catalog stays a directory of services that currently work, not ones that used to. Each listing moves through a simple lifecycle: | State | Meaning | | - | - | | **Validating** | The monitor is checking that your endpoint responds before it goes live. | | **Live** | Healthy and listed in the public Catalog, discoverable by buyers. | | **Action needed** | The monitor never got a healthy response within 24h, so the agent stays unlisted. | | **Degraded** | Still listed, but failing health checks. If no healthy probe arrives within 72h the listing is **unlisted automatically** — any healthy probe inside that window restores it. | | **Removed** | The listing has been taken down. | ### Health is also judged on paid calls The monitor's probe does not pay, so it proves your endpoint answers, not that a paid call delivers. The Catalog also reads the outcome of real purchases made through the [Router](/docs/products/catalog/router/overview): * **Hidden while payments don't go through.** If none of a listing's paid calls over the last 7 days settled and at least 3 of them went undelivered, from at least 2 different buyers, it is hidden from discovery. An undelivered call is one that failed, or one where your endpoint collected the payment and then answered with an error. One settled call brings the listing back. Without one, it is shown again 3 days after it was hidden — but while the undelivered calls that hid it are still inside the 7-day window, the next hourly check hides it again. * **No uptime claim without a settled call.** If a listing has at least 3 paid calls from at least 2 buyers in the last 30 days and none of them settled, it stays listed but publishes no "operational" status, uptime or last-healthy time until a call settles — and a `status=operational` filter no longer matches it. You still see the monitor's own readings on your listing. Card payments made over MPP (Stripe) are not counted here, because that rail never records a settlement. > [!NOTE] > > Publishing requires an **active paid tier** (Starter or above) — see [Plans & Billing](/docs/solutions/organizations/plans-and-billing). See [Agentic integration](/docs/solutions/organizations/agentic-integration) for the organization API context, and [Register a plan and agent](/docs/agents-guide/register-plan-and-agent) for creating the agent you'll list. ## Next > [card] [Discovering AI Services](/docs/products/catalog/discover) > > Browse the app, or read the public feed, to find what you need. > [card] [Router quickstart](/docs/products/catalog/router/quickstart) > > From an API key to a paid call against a service you found here, in five steps. # Build Outcomes Source: https://nevermined.ai/docs/products/catalog/build-outcomes Describe an outcome and a budget; the Nevermined Catalog proposes the AI services your agent chains to solve it — with copy-paste prompts you can run today. Most integrations start the wrong way round: you pick a search API, a scraper, and an LLM, sign up for each, wire in three keys, and glue them together — before you've solved anything. The Catalog flips it. You describe the **outcome** you want, attach a **budget**, and your agent uses the [Nevermined Catalog](/docs/products/catalog/overview) to discover the building-block services and chain them into a solution. No per-vendor signup, no wiring — each service settles per call against a budget you cap. > [!NOTE] > > This is the composition mindset: an AI service is a **building block**, not a destination. A real problem — *"tell me everything the web knows about this person"* — is several blocks (search, scrape, capture, synthesis) the Catalog proposes and the [Router](/docs/products/catalog/router/overview) pays for, one call at a time. ## Services are building blocks > [card] The old way > > Choose a vendor per capability. Create an account with each. Manage a key per account. Write the glue that calls them in order. Repeat for the next problem. > [card] The Catalog way > > State the outcome and a budget. Your agent searches the Catalog for each block, proposes a chain of real services, and the Router pays per call — no accounts, no keys, no glue. The **categories** are the block types — read live from the Catalog, never a hard-coded list. Today they include: **Search & Research** · **Web Scraping & Automation** · **Data & Enrichment** · **Crypto & Blockchain** · **Finance & Markets** · **AI & Media** · **Sales & Business Intelligence** · **Communication & Voice** · **Infrastructure & Compute** · **Social & Creator** · **Identity & Compliance** · **Weather** · **Travel** Browse them in [Discovering AI Services](/docs/products/catalog/discover), or query the live set yourself — [the last section](#see-what-the-catalog-proposes) shows how. ## How an outcome comes together **1. State the problem and a budget** One prompt: the result you want, and the most you'll spend getting it. The budget is the guardrail — the agent works *within* it. **2. The agent searches the Catalog (free)** Discovery needs no key and costs nothing. The agent breaks the problem into blocks and searches for each — *search*, *scrape*, *synthesis* — reading real slugs, prices, and health. **3. The Catalog proposes a chain** Candidate services per block, ranked and priced. This is the "solution" — a concrete set of services that, chained, produce the outcome. You can see it before a cent is spent. **4. Approve a cap once, and it runs** Approve a spending cap, and the Router pays each call within it. Connecting and paying is covered in [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) and [from a harness](/docs/products/catalog/from-a-harness). Everything up to the proposal is **free and reproducible right now** — that's what this page's prompts and queries exercise. Turning a proposal into a paid run needs a connected harness and a funded budget. ## Prompts you can paste Paste any of these into a harness connected to the Catalog — [Claude Code](/docs/products/catalog/from-a-harness), [Claude.ai or ChatGPT with the Nevermined connector](/docs/products/catalog/from-your-web-assistant), or any [MCP host](/docs/products/catalog/mcp). Each states an outcome and a budget; the agent discovers the building blocks and proposes the chain before spending. The services and prices under each are **what the Live Catalog returns today** — verified, not illustrative. > [!NOTE] > > Prices are per call, **as listed today** — the Catalog is live and prices drift, so your harness reads the current label. Totals aren't fixed: a run costs the sum of the calls the agent actually makes, always bounded by the budget you set. ### 1. Everything the open web knows about a person ```text theme={null} Use the Nevermined Catalog to design and run a workflow that, given a person's name, compiles a report of everything findable about them online from multiple sources, then hand me the report. Budget: $1.00. Browse the Catalog first (discovery is free), propose the chain of services before spending, and stay within budget. ``` **What the Catalog proposes** — four blocks, four real services: | Building block | Category | Example service (live) | Per-call price | | - | - | - | - | | Web search | Search & Research | `orth-seltz` — Seltz | \$0.00625 | | Web scraping | Web Scraping & Automation | `serper-scrape` — Serper Scrape | \$0.02 | | Page capture | Web Scraping & Automation | `screenshotone` — ScreenshotOne | \$0.055 | | AI synthesis | AI & Media | `deepseek` — DeepSeek | per-model | The agent searches, scrapes the top results, captures the pages, and has the LLM write the report — each call drawn from your \$1.00 cap. ### 2. A daily brief on a crypto position, priced and sourced ```text theme={null} Use the Nevermined Catalog to design and run a workflow that gives me a daily brief on my BTC and ETH position: the current price, the 24-hour move, and the headlines driving it, each with a source. Budget: $0.50. Discover and propose the services before paying, and stay within budget. ``` **What the Catalog proposes:** | Building block | Category | Example service (live) | Per-call price | | - | - | - | - | | Token prices | Crypto & Blockchain | `coingecko-via-mpp` — CoinGecko · `coinstats-app` — CoinStats | $0.06 · $0.001 | | News & sources | Search & Research | `serper` — Serper · `you-com` — You.com | $0.002–$0.006 · \$0.005 | | AI synthesis | AI & Media | `deepseek` — DeepSeek (or any listed LLM) | per-model | ### 3. Qualify an inbound lead before you reply ```text theme={null} Use the Nevermined Catalog to design and run a workflow that, given a work email address, enriches the person and their company and tells me whether they're worth a call, with a short rationale. Budget: $0.50. Browse the Catalog and propose the chain first, then stay within budget. ``` **What the Catalog proposes:** | Building block | Category | Example service (live) | Per-call price | | - | - | - | - | | Contact & company enrichment | Data & Enrichment · Sales & Business Intelligence | `hunter-mpp` — Hunter · `ocean-io` — Ocean.io · `apollo-api-via-mpp` — Apollo | $0.003–$0.023 · $0.01 · $0.01–\$0.05 | | Company page scrape | Web Scraping & Automation | `serper-scrape` — Serper Scrape · `firecrawl-tempo-mpp` — Firecrawl | $0.02 · $0.002 | | Score & rationale | AI & Media | any listed LLM (`deepseek`, `openai`, …) | per-model | ### More outcomes, same shape Every one of these is a single prompt with a budget — no wiring, no per-service integration: * **Watch a competitor page and report what changed** — *Web Scraping* (`serper-scrape`, `screenshotone`) + *AI synthesis*. * **Check a product batch against public safety recalls** — *Data & Enrichment* + *AI synthesis*. * **Find the cheapest venue to execute a trade right now** — *Crypto & Blockchain* + *Finance & Markets* (`coingecko-via-mpp`, `crypto-data`). ## See what the Catalog proposes The discovery step is **public and free** — no key, no budget, no spend. Run these against production and you'll see the same services a harness would propose. All four are verified working as written. **Browse the whole catalog**, see the real shape of a listing (`.total` is the live count): ```bash theme={null} curl -s https://nevermined.app/catalog/ai-catalog.json | jq '{total, first: .services[0]}' ``` **List the categories** through the Catalog MCP server (Streamable HTTP, stateless — one POST, no key): ```bash theme={null} curl -s -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -X POST https://mcp.live.nevermined.app/mcp \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_categories","arguments":{}}}' \ | jq -r '.result.content[0].text' | jq . ``` **Find the building blocks for an outcome** — one search per block, top 3 hits each: ```bash theme={null} for q in "web search" scrape screenshot chat; do curl -s -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -X POST https://mcp.live.nevermined.app/mcp \ -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"search_services\",\"arguments\":{\"query\":\"$q\"}}}" \ | jq -r '.result.content[0].text' \ | jq --arg q "$q" '{query:$q, count:(.results|length), top:[.results[0:3][]|{slug:(.identifier|split(":")|last), title:.displayName, protocol:.["nvm:catalog"].protocol, priceLabel:.["nvm:catalog"].priceLabel}]}' done ``` **Read one service's callable shape** — endpoints, method, and the exact arguments to pay it: ```bash theme={null} curl -s -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -X POST https://mcp.live.nevermined.app/mcp \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_service","arguments":{"slug":"orth-seltz"}}}' \ | jq -r '.result.content[0].text' | jq '.requestShape' ``` > [!TIP] > > **Search ranks by meaning and keyword together (ARD hybrid), most relevant first** — so a plain-language need finds services that never use your exact words, and a longer, descriptive query helps rather than hurts (`weather forecast` works as well as `weather`). Each result is an ARD record: `identifier` and `displayName` are top-level (the slug is the last segment of the `identifier` URN — `urn:…:service:orth-seltz` → `orth-seltz`), while `protocol`, `priceLabel`, `healthStatus` and `uptime30d` live under `nvm:catalog` — the `jq` above pulls those out. Filter with `tag` (a keyword from a listing's `tags`; `category` also matches tags, so put a `list_categories` name in `query`, not in `category`) and `protocol` (to keep only payable rails). Prefer a service whose `healthStatus` is `operational`. ## Turn a proposal into a run The proposal is free; executing it — paying each call within your cap — is the connect-and-pay flow: > [card] [From your web assistant](/docs/products/catalog/from-your-web-assistant) > > Connect the Catalog to Claude.ai, ChatGPT, or LangSmith Fleet and approve a cap once. > [card] [From a harness](/docs/products/catalog/from-a-harness) > > The code-free playbook for driving discovery and payment from your own agent. > [card] [Catalog MCP](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > The `pay_service` tool, the spending Delegation, and every refusal code. > [card] [Payment ledger](/docs/products/catalog/router/ledger) > > Read back exactly what each call cost and how much of the cap is left. # Connect the Catalog from Google Antigravity Source: https://nevermined.ai/docs/products/catalog/connect/antigravity Connect the Nevermined Catalog to Google Antigravity — add one MCP server, approve one spending cap, and Google Antigravity pays for services as it works. No API key. Google Antigravity can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and Google Antigravity does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with Google Antigravity — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Google Antigravity at **live**. ## Add the Catalog to Google Antigravity **1. Add the server to Antigravity's MCP config** Open the raw MCP config — in the agent side panel, **… → MCP Servers → Manage MCP Servers → View raw config** (stored at `~/.gemini/config/mcp_config.json`) — and add the Catalog as a remote server, using the `serverUrl` key (Antigravity does not accept `url` or `httpUrl`): ```json theme={null} { "mcpServers": { "nevermined": { "serverUrl": "https://mcp.sandbox.nevermined.app/mcp" } } } ``` For **live**, use `https://mcp.live.nevermined.app/mcp`. Antigravity then runs an OAuth (PKCE) flow to authorize; depending on your build it may complete the flow on its own or ask for an OAuth client id / secret — we are confirming which (see the note below). **2. Authorize** When Antigravity prompts to authorize the server — use the **Authenticate** action next to it — it opens Nevermined's consent page. See [Approve the spending cap](#approve-the-spending-cap). (We are confirming at D4 whether Antigravity authorizes up front or on the first paid call — see the note below.) > [!NOTE] > > Antigravity's remote-MCP OAuth support is still settling across versions, and the config path differs between builds. We are validating the exact steps at D4 — including whether Antigravity authorizes up front or on the first paid call. If it only authorizes on connect, this page will switch to the `mcp.api.` host, which challenges on connect instead. If authorization does not complete, confirm your Antigravity build supports remote MCP servers with OAuth. ## Approve the spending cap Google Antigravity opens Nevermined's consent page when it runs the OAuth flow to authorize the server. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so Google Antigravity reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If Google Antigravity answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect Google Antigravity. The credential stops working on its next call; discovery still works. * **Remove the connector (Google Antigravity side).** Remove the Nevermined entry from Antigravity's `mcp_config.json`. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from ChatGPT Source: https://nevermined.ai/docs/products/catalog/connect/chatgpt Connect the Nevermined Catalog to ChatGPT in minutes — add one MCP app, approve one spending cap, and ChatGPT pays for services as it works. No API key. ChatGPT can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one MCP app, approve a single spending cap, and ChatGPT does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). > [!NOTE] > > This covers the **manual** connection — adding the Catalog as a custom MCP app in Developer mode, which works today. A one-click listing in ChatGPT's connector directory is still in progress — see [From the ChatGPT directory](#from-the-chatgpt-directory). ## See it in action [Connect the Catalog from ChatGPT](https://www.youtube.com/embed/e_-bQlLdRdg) Connect the Catalog from ChatGPT. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with ChatGPT — the consent cap *is* the credential. **2. A paid ChatGPT plan** Developer mode, where custom MCP apps live, needs a paid plan (Plus or above). **3. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point ChatGPT at **live**. ## Add the Catalog to ChatGPT **1. Turn on Developer mode** **Settings → Security and login → Developer mode.** *Plugins* then appears in the sidebar. **2. Create an MCP app** **Plugins → + → Create app → Create MCP app.** (The + menu's *Create plugin* builds a plugin from scratch — not what you want.) **3. Fill in the dialog** * **Name** — read the warning below first; you only get one shot at it. * **Connection** — leave it on **Server URL** and paste the URL for your environment: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | * **Authentication** — **OAuth**, with the client ID and secret **empty**. ChatGPT discovers the OAuth settings from the server itself; leave **Advanced OAuth settings** closed. * Tick **I understand and want to continue** under the *"Custom MCP servers introduce risk"* notice. > [!WARNING] > > **Choose the name carefully — a ChatGPT plugin cannot be deleted or renamed.** Names are unique per account, so a name you have used is taken for good, and uninstalling does not free it. ## Approve the spending cap ChatGPT runs Nevermined's consent **at creation** — immediately, before any tool call. It is the one place a human is required. **1. Trigger the consent** When you create the MCP app, ChatGPT shows *Add Nevermined … to ChatGPT?* and opens the consent page. **2. Check who and where** The page shows the **Sandbox / Live** badge and that **chatgpt.com** is asking. On **live**, the cap is real money. **3. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. The plugin shows as connected. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so ChatGPT reaches for it rather than answering from memory. **1. Browse for free** In a new chat the plugin is available automatically. Ask *"list the Nevermined catalog categories"* — a free call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* Each paid call first asks *Allow ChatGPT to use Nevermined …?* — **Allow** (once, or always), and it returns the merchant's response. > [!TIP] > > If ChatGPT answers without paying, it answered from its own knowledge — name the connector and ask for live data. Confirm the connection by asking for the Catalog categories, which is a free call that either works or doesn't. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect ChatGPT. The credential stops working on its next call; discovery still works. On the next paid call ChatGPT shows a **Reconnect Nevermined** card (its wording says the connection "expired" even when you revoked it). * **Remove the connector (ChatGPT side).** Uninstall the plugin from **Plugins**. Note the plugin **cannot be deleted or renamed**, and uninstalling does not free its name. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## From the ChatGPT directory > [!NOTE] > > A one-click listing in ChatGPT's app directory — so you can add the Catalog without Developer mode — is coming. Until then, use the manual path above. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Claude (claude.ai) Source: https://nevermined.ai/docs/products/catalog/connect/claude Connect the Nevermined Catalog to Claude in minutes — add one connector, approve one spending cap, and Claude pays for services as it works. No API key. Claude at [claude.ai](https://claude.ai) can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one connector, approve a single spending cap, and Claude does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## See it in action [Connect the Catalog from claude.ai](https://www.youtube.com/embed/ioDqtiHtOGg) Connect the Catalog from claude.ai. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with Claude — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Claude at **live**. ## Add the Catalog to Claude **1. Open the connector settings** **Settings → Connectors → Add custom connector.** **2. Paste the server URL** Give the connector a name and paste the URL for the environment you want: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | Leave the OAuth **client ID and secret empty**. Claude identifies itself to Nevermined with its own client metadata document, so there is nothing to register. ## Approve the spending cap Claude opens Nevermined's consent page **at the first paid call** — not when you add the connector. It is the one place a human is required. **1. Trigger the consent** Enable the connector in a chat and ask Claude to buy a service (see [the next section](#make-your-first-paid-call)). The paid call returns `401` and Claude shows an inline **Connect** card. Click **Connect** — the consent page opens in a popup. **2. Check who and where** The page shows the **Sandbox / Live** badge and that **claude.ai** is asking. On **live**, the cap is real money. **3. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. Claude reports *Authentication complete* and **retries the same call** with the grant. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so Claude reaches for it rather than answering from memory. **1. Browse for free** Enable the connector from the tools menu and ask *"list the Nevermined catalog categories"*. It answers with no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the merchant's response."* The paid call returns `401`, Claude shows the **Connect** card, and once you approve the cap it retries and returns the result — with the price, the fee and the merchant's response. > [!TIP] > > If Claude answers without paying, it answered from its own knowledge — name the connector and ask for live data. Confirm the connection by asking for the Catalog categories, which is a free call that either works or doesn't. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect Claude. The credential stops working on its next call; discovery still works. * **Remove the connector (Claude side).** In **Settings → Connectors**, open the connector and remove it. You can re-add it later with the same URL. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Cline Source: https://nevermined.ai/docs/products/catalog/connect/cline Connect the Nevermined Catalog to Cline — add one remote MCP server, paste your Nevermined API key, and Cline pays for services as it works. Cline can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works. You add one remote MCP server, paste your Nevermined API key, and Cline does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Cline connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Cline. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Cline at **live**. ## Add the Catalog to Cline **1. Open the Remote Servers tab** Click the **MCP Servers** icon in Cline's toolbar, open the **Remote Servers** tab, and give the server a name (e.g. `nevermined-catalog`). **2. Point it at the server** Paste the URL for the environment you want and set **Transport Type** to **Streamable HTTP**: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **3. Add your API key as a header** Cline stores servers in `cline_mcp_settings.json`. Add your Nevermined API key as an `Authorization` header — edit it in the **Configure MCP Servers** JSON: ```json theme={null} { "mcpServers": { "nevermined-catalog": { "type": "streamableHttp", "url": "https://mcp.live.nevermined.app/mcp", "headers": { "Authorization": "Bearer " } } } } ``` ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Paste it in place of `` and keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Cline. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Ask for something only live data can answer, and name the server so Cline reaches for it rather than answering from memory. **1. Browse for free** In Cline's chat, ask *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined server and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If Cline answers without paying, it answered from its own knowledge — name the server and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Cline off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Cline side).** In the **MCP Servers** panel delete the Nevermined server, or remove its block from `cline_mcp_settings.json`. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from Codex Source: https://nevermined.ai/docs/products/catalog/connect/codex Connect the Nevermined Catalog to Codex — add one MCP server, approve one spending cap, and Codex pays for services as it works. No API key. Codex can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and Codex does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with Codex — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Codex at **live**. ## Add the Catalog to Codex **1. Add the server to your Codex config** Add an MCP server entry to `~/.codex/config.toml` (or a project-scoped `.codex/config.toml`) pointing at the environment you want. Codex reaches remote servers over Streamable HTTP: ```toml theme={null} [mcp_servers.nevermined] url = "https://mcp.sandbox.nevermined.app/mcp" # live: https://mcp.live.nevermined.app/mcp ``` Leave any client id / secret out — Codex identifies itself to Nevermined with its own client metadata document and runs the OAuth (PKCE) flow, so there is nothing to register and no key to paste. **2. Sign in** Run `codex mcp login nevermined`. Codex opens Nevermined's consent page in your browser — see [Approve the spending cap](#approve-the-spending-cap). ## Approve the spending cap Codex opens Nevermined's consent page when you run `codex mcp login`. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so Codex reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If Codex answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect Codex. The credential stops working on its next call; discovery still works. * **Remove the connector (Codex side).** Run `codex mcp logout nevermined` first to clear the stored OAuth tokens, then remove the `[mcp_servers.nevermined]` block from your `config.toml` (or run `codex mcp remove nevermined`). To keep the entry but switch it off instead, set `enabled = false`. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Microsoft Copilot Studio Source: https://nevermined.ai/docs/products/catalog/connect/copilot-studio Add the Nevermined Catalog to a Microsoft 365 Copilot agent in Copilot Studio — one MCP tool, a plain Nevermined API key, and it pays for services as it works. A Microsoft 365 Copilot agent built in Copilot Studio can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works. You add one MCP tool, paste your Nevermined API key, and the agent does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Copilot Studio connects with a **plain Nevermined API key** in a header, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use — and not a customer Entra OAuth app. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Copilot Studio. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point the agent at **live**. ## Add the Catalog to your agent **1. Add an MCP tool** In your Copilot Studio agent, open **Tools → Add a tool → New tool → Model Context Protocol**. **2. Point it at the server** Enter a **Server name** and **Server description**, and set **Server URL** to the environment you want: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **3. Authenticate with your key** Set **Authentication** to **API key**, choose **Type = Header**, use the header name `Authorization`, and supply `Bearer ` as the value. > [!NOTE] > > If Copilot Studio adds the `Bearer ` prefix for you, supply just the key — the header that reaches the server must read `Authorization: Bearer `. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Copilot Studio. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Ask for something only live data can answer, and name the tool so the agent reaches for it rather than answering from memory. **1. Browse for free** In a test chat, ask the agent to *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined tool and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If the agent answers without paying, it answered from its own knowledge — name the tool and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut the agent off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Copilot Studio side).** In the agent's **Tools**, open the Nevermined MCP tool and remove it. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from Dify Source: https://nevermined.ai/docs/products/catalog/connect/dify How a Dify app will pay for Nevermined Catalog services with a plain API key — the funding you set up now, and the connector that's on the way. A Dify app will be able to browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services with a plain Nevermined API key. This page covers the funding you can set up now and the connector that's on the way; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Dify connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Dify. > [!WARNING] > > **The connector is on the way.** Dify's built-in **Add MCP Server (HTTP)** flow authenticates with **OAuth only** (Dynamic Client Registration, or a manual Client ID + Secret) — it has no field for a plain API-key header, which is how the Catalog accepts these hosts. So you can't yet add the Catalog through Dify's native connector. A **Nevermined Dify Marketplace plugin** that carries the key is in progress; until it lands, drive the Catalog from your own code or another host — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Dify at **live**. ## Add the Catalog to Dify The Catalog will connect through the **Nevermined Dify Marketplace plugin** (in progress — see the warning above), because Dify's built-in MCP connector authenticates with OAuth only and the Catalog uses a plain API-key header for these hosts. When the plugin is published, this section becomes: add it from the Dify Marketplace and paste your Nevermined API key. The server URLs the plugin will point at: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | In the meantime, your Nevermined account and funding are already usable from any host that accepts an API-key header, or from your own code — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Dify. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Once the plugin is connected, give your Dify app a task that needs a live, paid service, so it reaches for the Catalog tools rather than answering from memory. **1. Browse for free** Have the app call a free discovery tool first — *list the Nevermined catalog categories*, or *search the catalog for a weather service*. Discovery needs no payment. **2. Let it buy** Then have it pay a service by slug — *buy the service `` and return the response*. The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If the app answers without paying, it answered from its own knowledge — have it call a discovery tool first and ask for something only live data can answer. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Dify off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Dify side).** Once the plugin is installed, remove it from your Dify app's tools. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from Factory Droid Source: https://nevermined.ai/docs/products/catalog/connect/factory Connect the Nevermined Catalog to Factory Droid — add one MCP server, approve one spending cap, and Droid pays for services as it works. No API key. Factory Droid can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and Droid does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with Droid — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Droid at **live**. ## Add the Catalog to Factory Droid **1. Add the MCP server** Add the Nevermined Catalog as a remote HTTP MCP server with `droid mcp add`, pointing at the environment you want: ```bash theme={null} droid mcp add nevermined https://mcp.api.sandbox.nevermined.app/mcp --type http # live: https://mcp.api.live.nevermined.app/mcp ``` The entry lands in your user config at `~/.factory/mcp.json` (a project-scoped `.factory/mcp.json` works too — don't commit secrets there). Pass no `--header` and no `--no-oauth`: Droid identifies itself to Nevermined with its own client metadata document and runs the OAuth (PKCE) flow, so there is nothing to register and no key to paste. **2. Sign in** `droid mcp list` shows the server as **needs authentication** until you sign in. Run `/mcp`, select the Nevermined server and choose **Authenticate** — Droid opens Nevermined's consent page in your browser. See [Approve the spending cap](#approve-the-spending-cap). ## Approve the spending cap Factory Droid opens Nevermined's consent page when you authenticate the server — the `/mcp` → **Authenticate** step above. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so Droid reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call that doesn't draw on your cap. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If Droid answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect Factory Droid. The credential stops working on its next call; discovery still works. * **Remove the connector (Factory Droid side).** In `/mcp`, choose **Clear auth** to drop the stored OAuth credentials, then **Remove** to delete the server — or delete its entry from `~/.factory/mcp.json`. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Goose Source: https://nevermined.ai/docs/products/catalog/connect/goose Connect the Nevermined Catalog to Goose — add one MCP server, approve one spending cap, and Goose pays for services as it works. No API key. Goose can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and Goose does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with Goose — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Goose at **live**. ## Add the Catalog to Goose **1. Add the extension** Run `goose configure`, choose **Add Extension → Remote Extension (Streamable HTTP)**, name it, and enter the endpoint for your environment: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | (Goose Desktop: open the **Extensions** view and choose **Add custom extension**, then paste the same URL.) There is no key to set — Goose uses OAuth 2.0 with PKCE. **2. Sign in on first use** The first **paid** tool call opens a browser to Nevermined's consent page — see [Approve the spending cap](#approve-the-spending-cap). Browsing and free tools need no sign-in. ## Approve the spending cap Goose opens Nevermined's consent page on your first paid tool call. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so Goose reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If Goose answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect Goose. The credential stops working on its next call; discovery still works. * **Remove the connector (Goose side).** In the CLI, disable it first (`goose configure` → *Toggle Extensions*), then remove it (`goose configure` → *Remove Extension*); in Goose Desktop, use the **Extensions** view. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Gumloop Source: https://nevermined.ai/docs/products/catalog/connect/gumloop Connect the Nevermined Catalog to Gumloop — add one MCP connector, paste your Nevermined API key, and your flows pay for services as they run. Gumloop can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as a flow runs. You add one MCP connector, paste your Nevermined API key, and Gumloop does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Gumloop connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Gumloop. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Gumloop at **live**. ## Add the Catalog to Gumloop **1. Open the MCP connector dialog** In Gumloop, go to **Settings → Connectors**, click the arrow next to **Add Connector**, and choose **Add MCP Connector**. **2. Point it at the server (Public URL)** Set **Connection type** to **Public URL** and paste the URL for the environment you want: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **3. Set the authentication** Under **Configure**, set **Authentication** to **Access Token / API Key** and paste your Nevermined API key — Gumloop sends it as `Authorization: Bearer ` on every request, which is exactly what the Catalog MCP expects. > [!WARNING] > > Use the **Access Token / API Key** field, **not** the *Additional Header* field. Gumloop's docs note that Anthropic models drop custom headers, so an `Authorization` header added through *Additional Header* may not be forwarded — the **Access Token / API Key** field is. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Gumloop. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Give a flow a task that needs a live, paid service, so the agent reaches for the Catalog tools rather than answering from memory. **1. Browse for free** Have the flow call a free discovery tool first — *list the Nevermined catalog categories*, or *search the catalog for a weather service*. Discovery needs no payment. **2. Let it buy** Then have it pay a service by slug — *buy the service `` and return the response*. The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If the flow answers without paying, it answered from its own knowledge — have it call a discovery tool first and ask for something only live data can answer. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Gumloop off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the connector (Gumloop side).** In **Settings → Connectors**, open the Nevermined MCP connector and remove it. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from H Company Source: https://nevermined.ai/docs/products/catalog/connect/h-company Connect the Nevermined Catalog to H Company's Runner H: give an agent Catalog tools backed by your API key, and it discovers and pays for services as it runs. H Company's Runner H can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as an agent works, unattended and under a budget you set. You give the agent a couple of Catalog tools, resolve those tool calls in your own backend with a Nevermined API key, and the agent discovers and pays for what a task needs. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > H Company connects through a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key stays in your backend and is never handed to the agent; it spends whatever its Nevermined account funds, so you set the budget on your account, not in H Company. ## See it in action To ground the setup, here is an agent we built and ran on H Company: a **recall checker**. You hand it a product and it returns a sourced safety brief, discovering and paying for the services it needs on its own. It is a saved Runner H Agent (`recall-checker`, model `holo4-27b`) with the Catalog wired in as its tools, the same shape an n8n builder gets from the MCP Client Tool node. [A recall-checker agent on H Company, paid per call · Nevermined Catalog × H Company](https://www.youtube.com/embed/7PkMvaeUX8A) A recall-checker agent on H Company, paid per call, built on the Nevermined Catalog: given one product, the agent discovers and pays for a public-safety-recall lookup and a model to write the brief, and returns a sourced risk assessment. Every call is paid per use from the account's credits. The point is how little there is to wire up. You do not integrate a recalls provider and a model vendor, each with its own account, key, and invoice. You describe the result you want, an [Outcome](/docs/products/catalog/build-outcomes), and the Catalog composes the services at run time and pays each one per call. Given a Peloton Tread+, the agent found the real CPSC recall of 2021, wrote a HIGH-risk brief from it, and paid for exactly the two calls it needed. ## What one run looks like On a run the agent calls the Catalog more than once. For each part of the brief it searches for a service that fits, pays for that one call, and moves on, all against the same budget. | Step | Service it paid | What came back | Cost | | - | - | - | - | | 1 | `recallradar` (recall lookup) | The real **CPSC recall of 2021-05-05**: the Tread+ entrapment hazard, the remedy, and the cpsc.gov source | 150 credits, settled, upstream 200 | | 2 | `perplexity` (`sonar`) | The risk brief written from that record plus live sources, with 10 citations | 15 credits, settled, upstream 200 | The agent then emitted a sourced **HIGH-risk** brief: the active CPSC recall, the hazard, the remedy, a recommended action, and the source link. About **165 credits** in total, all from the account's **subscription credits**, with no stablecoin spend. It paid for the two calls its task needed and nothing else. The Catalog tool calls in this run were resolved by the integration's own backend, the method shown in [Add the Catalog to H Company](#add-the-catalog-to-h-company). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app (**Settings → Global NVM API Keys**) for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). Use a plain key rather than one from an OAuth consent flow: your backend needs a static bearer token and has no consent step to run. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription): the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance. It can also spend from a capped, revocable **delegation** funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. **4. An H Company agent** Access to H Company's Agents API (`https://agp.eu.hcompany.ai/api`) with your H Company API key, so you can define an agent and run a session. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point H Company at **live**. The Catalog is **Live-only for payment**: sandbox discovers services but cannot settle a real one, so run the money path on **live** with a small cap. ## Add the Catalog to H Company Runner H agents call tools, and a tool can be **client-executed**: the agent emits the call, pauses, and your integration runs it and sends the result back. That is where the Catalog lives. You give the agent a couple of Catalog tools, and your backend resolves each call against the Catalog MCP with your Nevermined API key. The key stays in your backend, so the agent never holds it. Your backend talks to the Catalog MCP endpoint for the environment you are on: | Environment | Server URL | | - | - | | **Sandbox** (connect and browse here first) | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** (real merchants, real money) | `https://mcp.live.nevermined.app/mcp` | **1. Define the agent with Catalog tools** Create an agent (`POST /v2/agents`, or pass it inline per session) whose `tools` are client-executed definitions for the Catalog, for example one to **search** services and one to **pay** a service by slug. Run sessions against it by name. **2. Run a session and watch for tool calls** Start the session (`POST /v2/sessions`) with the task, then poll `GET /v2/sessions/{id}/changes`. When the agent calls a tool, the session turns to `awaiting_tool_results` and the pending calls arrive with their name and arguments. **3. Resolve each call against the Catalog** Call the Catalog MCP (the URL above) with your key as `Authorization: Bearer `, then post the result back with `POST /v2/sessions/{id}/tool_results`. The agent resumes and, once it has what it needs, returns its answer. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. Browsing the Catalog is free; paying a service is what draws on your budget. See the [Catalog MCP page](/docs/products/catalog/mcp) for the setup, and the [full Catalog MCP reference](/docs/mcp/catalog-mcp/overview) for every tool, its arguments, and the refusal codes. The plain-key playbook your backend follows, discovery, delegations and the safety rules, is [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## The budget is the guardrail An agent runs with no human watching each call, so the account's limits do the work a person would. The key spends only what its Nevermined account funds, enforced on Nevermined's side, not inside H Company. With a plain key the Commerce MCP pays from your **credits** first whenever they can cover a call, and from a **delegation** otherwise, so know which one an agent is spending and what actually bounds it. * **A delegation is a hard, revocable cap.** Fund it once and its cap is the ceiling for every call paid from it. Revoke it any time, in one action, from [Payment methods](https://nevermined.app/payment-methods), and the next delegation-funded call fails. For a hard per-agent ceiling, have your backend send `funding: "delegation"` on every pay call, so the delegation cap is the only bound no matter what credits the account holds. (Running the agent on a separate account with no credits works too, but welcome credits and a subscription's allowance arrive on their own, so the explicit lever is simpler.) * **Credits have no cap beyond your balance.** There is no daily, per-service or per-key limit, and with [top-ups](/docs/products/catalog/router/subscription#top-ups) on, a call that runs short charges your card for a 10,000-credit pack, up to a monthly limit you set. Revoking a delegation does not stop credit spend; the Nevermined-side stop for credits is rotating or deleting the key and turning top-ups off. * **Keep the stop within reach.** Treat the backend secret that stores the key as spending authority, and know the lever before you need it: the key and top-ups for credits, the delegation cap for delegated calls. ## Make your first paid call Give the agent a task that needs a live, paid service, so it reaches for the Catalog tools rather than answering from memory. **1. Browse for free** Ask the agent to call a free discovery tool first, for example *list the Nevermined catalog categories* or *search the catalog for a recalls service*. Your backend resolves the call against the Catalog, and discovery needs no payment. **2. Let it buy** Then ask it to pay a service by slug, for example *buy the service `` and return the response*. Your backend runs the pay call against the Catalog; it draws on your Nevermined credits or delegation and returns the merchant's response. Payment is **live-only**: on sandbox the only payable services are the two testnet test merchants, `mpp-dev-paid-ping` and `x402-org-protected`, so make your first real purchase on live with a small cap. > [!TIP] > > If the agent answers without paying, it answered from its own knowledge. Have it call a discovery tool first and ask for something only live data can answer. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so **rotate or delete the key** in the app (**Settings → Global NVM API Keys**); every call made with the old key then fails, your backend's included. That is the only Nevermined-side stop for credit spend, so also turn off [top-ups](/docs/products/catalog/router/subscription#top-ups). To cap delegation-funded spend without revoking the key, revoke the delegation in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Stop resolving calls (H Company side).** Remove the Catalog tools from the agent, or retire the agent, so it can no longer reach the Catalog, and remove the key from your backend. To spend again, use a fresh key; if you revoked the delegation, create a new one. See [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [What the Catalog is](/docs/products/catalog/overview) > > The marketplace of pay-per-call services your agent can discover and buy. > [card] [Build an Outcome](/docs/products/catalog/build-outcomes) > > Describe a result and a budget; the Catalog composes and pays for the services, the pattern behind the recall checker above. > [card] [Catalog MCP reference](/docs/mcp/catalog-mcp/overview) > > Every tool, its arguments, the API-key header, and every refusal code. > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook: discovery, delegations, and the safety rules. # Connect the Catalog from Hermes Agent Source: https://nevermined.ai/docs/products/catalog/connect/hermes Connect the Nevermined Catalog to Hermes Agent — add one MCP server, approve one spending cap, and Hermes Agent pays for services as it works. No API key. Hermes Agent can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and Hermes Agent does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with Hermes Agent — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Hermes Agent at **live**. ## Add the Catalog to Hermes Agent **1. Add the server** Add the Catalog as an OAuth-protected HTTP server (no API key or client secret — OAuth with PKCE): ```bash theme={null} hermes mcp add --url https://mcp.sandbox.nevermined.app/mcp --auth oauth nevermined # live: --url https://mcp.live.nevermined.app/mcp ``` **2. Sign in** Run `hermes mcp login nevermined` from a fresh terminal. Hermes opens Nevermined's consent page (or prints a URL to paste when it runs headless). Check the tools loaded with `hermes mcp test nevermined`. ## Approve the spending cap Hermes Agent opens Nevermined's consent page when you run `hermes mcp login`. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so Hermes Agent reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If Hermes Agent answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect Hermes Agent. The credential stops working on its next call; discovery still works. * **Remove the connector (Hermes Agent side).** Run `hermes mcp remove nevermined` (or remove it from `~/.hermes/config.yaml`). To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Kilo Code Source: https://nevermined.ai/docs/products/catalog/connect/kilo Connect the Nevermined Catalog to Kilo Code — add one MCP server, approve one spending cap, and Kilo Code pays for services as it works. No API key. Kilo Code can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and Kilo Code does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with Kilo Code — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Kilo Code at **live**. ## Add the Catalog to Kilo Code **1. Add the MCP server** In Kilo Code open **Settings → MCP → Add Server**, choose **Remote (HTTP)**, and paste the URL for your environment: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | Leave the headers / client id empty — in the VS Code extension Kilo runs the OAuth (PKCE) flow for you, identifying itself with its own client metadata document, so there is nothing to register. In the Kilo **CLI**, add it instead to your Kilo config (`~/.config/kilo/kilo.json`, or `./kilo.json` / `.kilo/kilo.json` for a project) as a `type: "remote"` entry with the `url`, then run `kilo mcp auth` to authenticate. **2. Authorize** Kilo opens a browser to Nevermined's consent page on your first **paid** call — see [Approve the spending cap](#approve-the-spending-cap). Browsing and free tools need no sign-in. ## Approve the spending cap Kilo Code opens Nevermined's consent page on your first **paid** call. Discovery and free tools need no credential. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so Kilo Code reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If Kilo Code answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect Kilo Code. The credential stops working on its next call; discovery still works. * **Remove the connector (Kilo Code side).** Remove the server from Kilo's MCP settings (**Settings → MCP**), or delete its entry from the config file. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Kiro Source: https://nevermined.ai/docs/products/catalog/connect/kiro Connect the Nevermined Catalog to Kiro — add one MCP server, approve one spending cap, and Kiro pays for services as it works. No API key. Kiro can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and Kiro does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with Kiro — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Kiro at **live**. ## Add the Catalog to Kiro **1. Add the server to your Kiro MCP config** Add a remote MCP server to Kiro's MCP config — `.kiro/settings/mcp.json` in your workspace, or `~/.kiro/settings/mcp.json` for every workspace — pointing at the environment you want. Set `oauth.clientId` to `kiro` and omit `clientSecret` — the Kiro IDE supports public clients only, so there is no secret to paste: ```json theme={null} { "mcpServers": { "nevermined": { "url": "https://mcp.api.sandbox.nevermined.app/mcp", "oauth": { "clientId": "kiro" } } } } ``` For **live**, use `https://mcp.api.live.nevermined.app/mcp`. Use the `mcp.api.` host (not `mcp.`): Kiro only starts OAuth when it connects to a server that challenges, and this host challenges on the first request. You don't need `redirectUri` — Kiro's default loopback callback (path `/oauth/callback`, on a random port) is already registered for the `kiro` client, and Nevermined matches it on any port. **2. Sign in** Kiro opens Nevermined's consent page in your browser when it connects to the server — see [Approve the spending cap](#approve-the-spending-cap). ## Approve the spending cap Kiro opens Nevermined's consent page when it first connects to the server. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Once you've connected and approved the cap, name the connector so Kiro reaches for it rather than answering from memory. **1. Browse the catalog** Ask *"list the Nevermined catalog categories through the Nevermined connector"* to see what's available. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If Kiro answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect Kiro. The credential stops working on its next call; discovery still works. * **Remove the connector (Kiro side).** Remove the `nevermined` entry from the `mcpServers` block in your `mcp.json`, or set `"disabled": true` on it to switch it off without deleting it. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Lovable Source: https://nevermined.ai/docs/products/catalog/connect/lovable Connect the Nevermined Catalog to Lovable — add one MCP server, paste your Nevermined API key, and Lovable pays for services as it works. Lovable can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works. You add one MCP server, paste your Nevermined API key, and Lovable does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Lovable connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Lovable. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Lovable at **live**. ## Add the Catalog to Lovable **1. Open the MCP server dialog** In Lovable, go to **Connectors**, click **+**, and choose **MCP server**. **2. Point it at the server** Give it a **Server name**, leave **Connection** on **Direct connection**, and set **Server URL** to the environment you want: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **3. Choose Bearer-token auth** For authentication choose **Bearer token or API key** (not OAuth), paste your Nevermined API key, and click **Add server**. > [!NOTE] > > Rehearse on **sandbox** first. The Catalog MCP accepts only the exact header `Authorization: Bearer `; if Lovable sends your key in another shape, calls look connected but never pay — if that happens, ask for a free discovery call and confirm a paid one actually charges before trusting it on **live**. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Lovable. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Ask for something only live data can answer, and name the server so Lovable reaches for it rather than answering from memory. **1. Browse for free** In Lovable's chat, ask *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined server and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If Lovable answers without paying, it answered from its own knowledge — name the server and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Lovable off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Lovable side).** In **Connectors**, open the Nevermined MCP server and remove it. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from Make Source: https://nevermined.ai/docs/products/catalog/connect/make Connect the Nevermined Catalog to Make — add the MCP Client, paste your Nevermined API key, and your scenarios pay for services as they run. Make can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as a scenario runs. You add the MCP Client, paste your Nevermined API key, and Make does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Make connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Make. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Make at **live**. ## Add the Catalog to Make **1. Add the MCP Client** In a Make scenario, add the **MCP Client** app (its **Call a tool** / **Execute an action with AI** modules), and create a connection with **+ New MCP Server**. **2. Point it at the server** Set the server **URL** to the environment you want: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **3. Add your API key** For a manually-entered server Make shows an **API Key / Access token** field — paste your Nevermined API key there. > [!WARNING] > > **Verify this before relying on it.** Make's own docs don't state that the **API Key / Access token** value is sent as an `Authorization: Bearer` header, and the Catalog MCP accepts only that header. Test on **sandbox** first; if the key is rejected, the Catalog may need to be added to Make's **verified remote MCP servers** list — [reach out](https://nevermined.ai/contact-us) and we'll help. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Make. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Give a scenario a task that needs a live, paid service, so the MCP Client reaches for the Catalog tools rather than answering from memory. **1. Browse for free** Have the scenario call a free discovery tool first — *list the Nevermined catalog categories*, or *search the catalog for a weather service*. Discovery needs no payment. **2. Let it buy** Then have it pay a service by slug — *buy the service `` and return the response*. The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If the scenario answers without paying, it answered from its own knowledge — have it call a discovery tool first and ask for something only live data can answer. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Make off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Make side).** Delete the Nevermined MCP Client connection from your scenario and your connections. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from Manus Source: https://nevermined.ai/docs/products/catalog/connect/manus Connect the Nevermined Catalog to Manus — add one custom MCP server, paste your Nevermined API key, and Manus pays for services as it works. Manus can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works. You add one custom MCP server, paste your Nevermined API key, and Manus does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Manus connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Manus. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Manus at **live**. ## Add the Catalog to Manus **1. Open Custom MCP Servers** In Manus, go to **Settings → Integrations → Custom MCP Servers** and click **Add Server**. **2. Point it at the server** Give it a **Server name** and set **Server URL** to the HTTPS endpoint for the environment you want: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **3. Set the authentication** For **Authentication**, choose **Bearer token** (API key) and paste your Nevermined API key. > [!NOTE] > > Rehearse on **sandbox** first. The Catalog MCP accepts only the exact header `Authorization: Bearer `; if Manus sends your key in another shape, calls look connected but never pay — if that happens, ask for a free discovery call and confirm a paid one actually charges before trusting it on **live**. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Manus. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Ask for something only live data can answer, and name the server so Manus reaches for it rather than answering from memory. **1. Browse for free** Ask Manus to *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined server and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If Manus answers without paying, it answered from its own knowledge — name the server and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Manus off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Manus side).** In **Settings → Integrations → Custom MCP Servers**, open the Nevermined server and remove it. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from Muse Source: https://nevermined.ai/docs/products/catalog/connect/muse How Muse will reach the Nevermined Catalog — the account and funding you set up now, and the directory connector that's on the way. Muse will be able to browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services with a plain Nevermined API key. This page covers the account and funding you can set up now and the directory connector that's on the way; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Muse connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Muse. > [!WARNING] > > **The connector is on the way.** The Muse Connector Platform ([platform.muse.ai](https://platform.muse.ai)) is a **submission-and-review** directory — a connector is published by its developer and, once approved, becomes discoverable in the Muse agent and under **Settings → Connectors**. There is no self-serve "add a custom MCP server" flow for end users, so you can't add the Catalog yourself yet. Nevermined is submitting the Catalog connector for listing; until it's approved, drive the Catalog from your own code or another host — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Muse at **live**. ## Add the Catalog to Muse The Catalog will appear in Muse's **Settings → Connectors** once Nevermined's connector is approved on the Muse Connector Platform (in progress — see the warning above). When it's listed, this section becomes: find Nevermined in the connectors directory and paste your Nevermined API key. In the meantime, your Nevermined account and funding are already usable from any host that accepts an API-key header, or from your own code — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Muse. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Once the connector is listed, ask for something only live data can answer, and name the connector so Muse reaches for it rather than answering from memory. **1. Browse for free** Ask Muse to *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If Muse answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Muse off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Muse side).** Once the connector is listed, disconnect it from Muse's **Settings → Connectors**. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from n8n Source: https://nevermined.ai/docs/products/catalog/connect/n8n Connect the Nevermined Catalog to n8n — add an MCP Client Tool node, paste your Nevermined API key, and your workflows discover and pay for services as they run. n8n can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as a workflow runs — unattended, on a schedule, under a budget you set. You add one MCP Client Tool node, paste your Nevermined API key, and n8n does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > n8n connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in n8n. ## See it in action To ground the setup, here is a workflow we built and ran on n8n: a weekly **agentic-commerce research agent**. Every Monday it wakes on a schedule, researches the last seven days of agentic commerce, and returns a short brief — delivered to Slack and by email. It discovers and pays for the services it needs on its own, under a **\$2 budget** it cannot exceed. [A research agent in n8n, paid per call — Nevermined Catalog × n8n](https://www.youtube.com/embed/DEHwDbTcw-Y) A research agent in n8n, paid per call — built on the Nevermined Catalog: one prompt and a \$2 budget, the Catalog discovers and pays for the services each run needs, and a weekly brief lands in Slack and email. The point is how little there is to wire up. You don't integrate a search provider, a funding-data provider, and three social sources, each with its own account, key, and invoice. You describe the result you want and set a budget — an [Outcome](/docs/products/catalog/build-outcomes) — and the Catalog composes the services at run time and pays each one per call. ![The Outcome composition: a prompt and a \$2 budget feed a chain of catalog services grouped by job — news and web search, company and funding data, social signals, and a read-and-write step — producing one weekly report delivered to Slack and email.](https://mintcdn.com/neverminedag/isDhWLISpFtR3z4o/images/catalog/n8n/catalog-outcome.png?fit=max\&auto=format\&n=isDhWLISpFtR3z4o\&q=85\&s=5b75f93ae7e0821912da63c47617989f) One prompt and a \$2 budget go in; the Catalog discovers and chains the services it needs — news and web search, newly launched and funded companies, and social signals across X, LinkedIn and Hacker News — reads the sources, writes the report, and returns one weekly brief. Every call is paid per use against the one budget. You don't choose the services by name, and which ones a given week uses isn't fixed. The agent discovers what the prompt needs — a web-search service such as [You.com](https://you.com) for the week's news, company- and funding-data services, separate sources for X, LinkedIn and Hacker News, a scraper to read the primary links, and a model to dedupe, rank and write the brief — then pays only for the calls it makes. Discovery is free, so it re-checks what's live on every run rather than hard-coding a list. All of that reaches n8n through a single node. The finished workflow is **six nodes**: a weekly Schedule Trigger into an AI Agent that has the Nevermined Commerce MCP wired in as its one tool, which then branches to Slack and email. There is no code node and no custom plugin — n8n even runs the model, so there's no model key to add either. ![Six-node n8n workflow: Schedule Trigger, AI Agent with the Nevermined Commerce MCP as its tool, then Slack and email delivery nodes.](https://mintcdn.com/neverminedag/isDhWLISpFtR3z4o/images/catalog/n8n/workflow-canvas.png?fit=max\&auto=format\&n=isDhWLISpFtR3z4o\&q=85\&s=162b2a26ea9d565bbd4138b787b694da) The finished workflow on the n8n canvas: a weekly Schedule Trigger into an AI Agent, which has the Nevermined Commerce MCP as its only tool, branching to a Post to Slack node and an Email the Report node. ## What one run looks like On a run the agent calls the Catalog several times, not once. For each part of the brief it searches for a service that fits, reads a quote, pays for that one call, and moves on — all against the same budget. ![An n8n execution marked Succeeded in 23.7 seconds, showing three model turns, six Commerce MCP tool calls, and green Slack and email delivery nodes.](https://mintcdn.com/neverminedag/isDhWLISpFtR3z4o/images/catalog/n8n/execution.png?fit=max\&auto=format\&n=isDhWLISpFtR3z4o\&q=85\&s=342a3f57f72b02da4a162b1756b2cad7) One run, succeeded in about 24 seconds: the AI Agent called the model three times and the Nevermined Commerce MCP six times — once for each service it decided it needed — and both the Slack and email steps ran green. The run above finished in about twenty-four seconds. Inside it the model took three turns and the Catalog was called six times — each call priced and paid in the background, all of it inside the budget. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point n8n at **live**. The Catalog is **Live-only for payment** — sandbox discovers services but cannot settle a real one, so run the money path on **live** with a small cap. ## Add the Catalog to n8n **1. Add an MCP Client Tool node** In your workflow, add an **MCP Client Tool** node and connect it to your **AI Agent** node's tool input. **2. Point it at the server** Set the endpoint to the Catalog MCP URL for your environment, and choose **HTTP Streamable** as the transport: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | > [!NOTE] > > The Catalog MCP speaks **Streamable HTTP** only. If your n8n version offers only an SSE endpoint field, update n8n to a version with the HTTP Streamable transport option. **3. Set Bearer authentication** Set **Authentication** to **Bearer** and paste your Nevermined API key — or use a **Header Auth** credential with name `Authorization` and value `Bearer `. ![n8n configuration panels: the MCP Client Tool node set to the Commerce MCP endpoint with Bearer header auth (key masked), the catalog exposed as tools, and the schedule, AI Agent, Slack and Gmail nodes each with their own credential.](https://mintcdn.com/neverminedag/isDhWLISpFtR3z4o/images/catalog/n8n/n8n-config.png?fit=max\&auto=format\&n=isDhWLISpFtR3z4o\&q=85\&s=fec6cbde8df177c687f66f7d2b8d299c) The n8n-side configuration: the MCP Client Tool node points at the Commerce MCP endpoint with a single Authorization: Bearer header — the Nevermined API key, kept in an n8n credential and never written into the workflow. From there the whole Catalog is exposed to the agent as tools: search, quote, pay, and check the budget. Once the node is pointed at the server, the whole Catalog is available to the agent as tools it can call: **search** for a service, get a **quote**, **pay**, and check what's left of the **budget**. Discovery tools are free; the rest draw on your budget. See the [Catalog MCP page](/docs/products/catalog/mcp) for the setup, and the [full Catalog MCP reference](/docs/mcp/catalog-mcp/overview) for every tool, its arguments, and the refusal codes. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in n8n. Store it in an n8n credential, treat it like a password, and never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## The budget is the guardrail A scheduled workflow runs with no human watching each call, so the budget does the work a person would. Set a **delegation cap** to the most you want the workflow to spend — \$2 for the research agent above — and fund it once; every paid call settles against that cap. * **The agent cannot raise it.** The cap is enforced on Nevermined's side, not in n8n, so a runaway workflow physically cannot spend past it. When the budget is reached, calls stop. * **You can revoke it any time**, in one action, from [Payment methods](https://nevermined.app/payment-methods) — the next call simply fails, and discovery still works. * **Keep the cap tight**, and set a per-run budget if you want each run isolated. Treat the n8n credential that holds the key as spending authority. ## Make your first paid call Give your agent a task that needs a live, paid service, so it reaches for the Catalog tools rather than answering from memory. **1. Browse for free** Have the AI Agent call a free discovery tool first — *list the Nevermined catalog categories*, or *search the catalog for a weather service*. Discovery needs no payment. **2. Let it buy** Then have it pay a service by slug — *buy the service `` and return the response*. The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If the agent answers without paying, it answered from its own knowledge — have it call a discovery tool first and ask for something only live data can answer. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut n8n off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (n8n side).** Delete or disable the **MCP Client Tool** node in your workflow (and remove the stored credential if you no longer need it). To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [What the Catalog is](/docs/products/catalog/overview) > > The marketplace of pay-per-call services your agent can discover and buy. > [card] [Build an Outcome](/docs/products/catalog/build-outcomes) > > Describe a result and a budget; the Catalog composes and pays for the services — the pattern behind the research agent above. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview) > > Every tool, its arguments, the API-key header, and every refusal code. > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. # Connect the Catalog from Notion Custom Agents Source: https://nevermined.ai/docs/products/catalog/connect/notion Connect the Nevermined Catalog to a Notion Custom Agent — add one MCP connection, paste your Nevermined API key, and the agent pays for services as it works. A Notion Custom Agent can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works. You add one MCP connection, paste your Nevermined API key, and the agent does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Notion connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Notion. > [!WARNING] > > Custom MCP connections are a **Custom Agents** feature on **Business and Enterprise plans only**, and a **workspace admin must enable custom MCP servers and approve the server URL** before an agent can use it. They don't apply to the default Notion AI. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point the agent at **live**. ## Add the Catalog to your Custom Agent **1. Admin: approve the server (once)** A workspace admin enables custom MCP servers and approves the Catalog URL in **Settings → Connections**. Approve the URL for the environment you want: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **2. Add the connection to the agent** In your Custom Agent, open **Settings → Tools & Access → Add connection → Custom MCP server**, enter the same URL and a display name. **3. Authenticate with your key** Choose the **header-based** (API key / bearer token) sign-in, paste your Nevermined API key, and **Connect**. > [!NOTE] > > Rehearse on **sandbox** first. The Catalog MCP accepts only the exact header `Authorization: Bearer `; if the connection sends your key in another shape, calls look connected but never pay — if that happens, ask for a free discovery call and confirm a paid one actually charges before trusting it on **live**. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Notion. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Ask for something only live data can answer, and name the connection so the agent reaches for it rather than answering from memory. **1. Browse for free** Ask the agent to *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connection and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If the agent answers without paying, it answered from its own knowledge — name the connection and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut the agent off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Notion side).** Remove the connection from the agent's **Tools & Access**; a workspace admin can also remove the approved server in **Settings → Connections**. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from OpenClaw Source: https://nevermined.ai/docs/products/catalog/connect/openclaw Connect the Nevermined Catalog to OpenClaw — add one remote MCP server, paste your Nevermined API key, and OpenClaw pays for services as it works. OpenClaw can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works. You add one remote MCP server, paste your Nevermined API key, and OpenClaw does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > OpenClaw connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in OpenClaw. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point OpenClaw at **live**. ## Add the Catalog to OpenClaw **1. Add the server** Add the Catalog MCP server with the OpenClaw CLI, pointing at the environment you want and passing your Nevermined API key as an `Authorization` header: ```bash theme={null} openclaw mcp add nevermined-catalog \ --url https://mcp.live.nevermined.app/mcp \ --transport streamable-http \ --header "Authorization: Bearer " ``` | Environment | `--url` | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | Leave the server's `auth` unset — if you set `auth: oauth`, OpenClaw ignores the static `Authorization` header. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Paste it in place of `` and keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in OpenClaw. Treat it like a password: never commit it or paste it into a shared chat (prefer an env-var reference such as `Bearer ${MCP_TOKEN}`). Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Ask for something only live data can answer, and name the server so OpenClaw reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined server and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If OpenClaw answers without paying, it answered from its own knowledge — name the server and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut OpenClaw off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (OpenClaw side).** Remove the Nevermined server from **Settings → MCP**, or delete its block under `mcp.servers` in your `openclaw.json`. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from OpenCode Source: https://nevermined.ai/docs/products/catalog/connect/opencode Connect the Nevermined Catalog to OpenCode — add one MCP server, approve one spending cap, and OpenCode pays for services as it works. No API key. OpenCode can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and OpenCode does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with OpenCode — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point OpenCode at **live**. ## Add the Catalog to OpenCode **1. Add the server to your OpenCode config** Add a remote MCP server to your OpenCode config — the global `~/.config/opencode/opencode.json`, or `opencode.json` in a project root — pointing at the environment you want. Set the OAuth **client id** to `opencode` and leave the **secret** out — Nevermined accepts public PKCE clients only, so there is no secret to paste: ```json theme={null} { "$schema": "https://opencode.ai/config.json", "mcp": { "nevermined": { "type": "remote", "url": "https://mcp.sandbox.nevermined.app/mcp", "oauth": { "clientId": "opencode" } } } } ``` For **live**, use `https://mcp.live.nevermined.app/mcp`. You don't need to set a redirect URI — OpenCode's default loopback callback (`http://127.0.0.1:19876/mcp/oauth/callback`) is already registered for the `opencode` client, and Nevermined matches it on any port. **2. Sign in** Run `opencode mcp auth nevermined`. OpenCode opens Nevermined's consent page in your browser — see [Approve the spending cap](#approve-the-spending-cap). ## Approve the spending cap OpenCode opens Nevermined's consent page when you run `opencode mcp auth`. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so OpenCode reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If OpenCode answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect OpenCode. The credential stops working on its next call; discovery still works. * **Remove the connector (OpenCode side).** Run `opencode mcp logout nevermined` to clear the stored tokens (OpenCode keeps them in `~/.local/share/opencode/mcp-auth.json`), then remove the `nevermined` entry from the `mcp` block in your `opencode.json`. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Poke Source: https://nevermined.ai/docs/products/catalog/connect/poke Connect the Nevermined Catalog to Poke — add one integration, paste your Nevermined API key, and Poke pays for services as it works. Poke can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works. You add one integration, paste your Nevermined API key, and Poke does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Poke connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Poke. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Poke at **live**. ## Add the Catalog to Poke **1. Create an integration** Open [poke.com/integrations/new](https://poke.com/integrations/new), give it a **Name**, and set **MCP Server URL** to the environment you want: | Environment | MCP Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **2. Add your API key** Paste your Nevermined API key into the **API Key** field and click **Create Integration** — Poke includes it as an `Authorization` header on every request to the server. CLI alternative: `npx poke@latest mcp add https://mcp.live.nevermined.app/mcp -n "nevermined-catalog" -k ""`. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Poke. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Ask for something only live data can answer, and name the integration so Poke reaches for it rather than answering from memory. **1. Browse for free** Message Poke *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined integration and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If Poke answers without paying, it answered from its own knowledge — name the integration and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Poke off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Poke side).** Delete the Nevermined integration from your Poke integrations. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from Replit Source: https://nevermined.ai/docs/products/catalog/connect/replit Connect the Nevermined Catalog to Replit — add one MCP server, paste your Nevermined API key, and Replit Agent pays for services as it works. Replit Agent can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works. You add one MCP server, paste your Nevermined API key, and Replit does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Replit connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Replit. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Replit at **live**. ## Add the Catalog to Replit **1. Open the MCP Servers pane** In Replit, open the **MCP Servers** pane and click **+ Add MCP server**. **2. Point it at the server** Give it a **Display name** and set **MCP Server URL** to the environment you want: | Environment | MCP Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **3. Add your API key as a header** Expand **Advanced settings** and add a custom header — name `Authorization`, value `Bearer ` — then **Test & save**. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Paste it in place of `` and keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Replit. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Ask for something only live data can answer, and name the server so Replit reaches for it rather than answering from memory. **1. Browse for free** In the Replit Agent, ask *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined server and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If Replit answers without paying, it answered from its own knowledge — name the server and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Replit off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Replit side).** In the **MCP Servers** pane, open the Nevermined server and remove it. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from v0 Source: https://nevermined.ai/docs/products/catalog/connect/v0 Connect the Nevermined Catalog to v0 — add one MCP server, approve one spending cap, and v0 pays for services as it works. No API key. v0 can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and v0 does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with v0 — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point v0 at **live**. ## Add the Catalog to v0 **1. Add the Catalog as a custom MCP server** In a v0 chat, open the **+** menu in the prompt form and choose **MCPs → add a custom server**. Enter the server URL for your environment and pick **OAuth** as the authentication method: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **2. Authorize** Complete the **OAuth** flow v0 shows and grant the permissions it asks for — this opens Nevermined's consent page. The first **paid** call is what triggers it; browsing and free tools need no sign-in. > [!NOTE] > > If the **+ → MCPs** custom-server dialog is not available in your v0 build, check v0's current MCP docs — the custom-server UI is still rolling out. ## Approve the spending cap v0 opens Nevermined's consent page on your first **paid** call. Discovery and free tools need no credential. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so v0 reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If v0 answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect v0. The credential stops working on its next call; discovery still works. * **Remove the connector (v0 side).** Remove or disable the Nevermined custom server from the **+ → MCPs** menu in v0. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from VS Code Source: https://nevermined.ai/docs/products/catalog/connect/vscode Connect the Nevermined Catalog to VS Code — add one MCP server, approve one spending cap, and VS Code pays for services as it works. No API key. VS Code can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and VS Code does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with VS Code — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point VS Code at **live**. ## Add the Catalog to VS Code **1. Add the MCP server** Open the Command Palette and run **MCP: Add Server**, choose **HTTP (HTTP or Server-Sent Events)**, and paste the URL for your environment: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | Pick where to save it — **Global → Copilot Global** writes to `~/.copilot/mcp-config.json`; the workspace `.vscode/mcp.json` and user-profile `mcp.json` options still work but are labelled deprecated in the guided flow. Leave the OAuth client id / secret empty — VS Code identifies itself with its own client metadata document and runs the OAuth (PKCE) flow for you, so there is nothing to register. **2. Authorize** Use the Catalog from Copilot **agent mode**. Browsing and free tools need no sign-in; the first **paid** call returns `401` and VS Code opens a browser window for authorization — Nevermined's consent page. > [!NOTE] > > This covers Microsoft's official **VS Code** builds with GitHub Copilot. Other VS Code–based editors connect through their own MCP settings — see their page if listed. ## Approve the spending cap VS Code opens Nevermined's consent page on your first **paid** call — not when you add the server. Discovery and free tools need no credential. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so VS Code reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If VS Code answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect VS Code. The credential stops working on its next call; discovery still works. * **Remove the connector (VS Code side).** Remove the server from wherever you saved it (e.g. `~/.copilot/mcp-config.json`), or disable it from the MCP servers view. To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Connect the Catalog from Windsurf Source: https://nevermined.ai/docs/products/catalog/connect/windsurf Connect the Nevermined Catalog to Windsurf — add one remote MCP server, paste your Nevermined API key, and Cascade pays for services as it works. Windsurf's Cascade can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works. You add one remote MCP server, paste your Nevermined API key, and Cascade does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Windsurf connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Windsurf. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Windsurf at **live**. ## Add the Catalog to Windsurf **1. Open the MCP config file** In Cascade's **Settings**, open the MCP config file (`mcp_config.json`) — on macOS/Linux that's `~/.config/devin/mcp_config.json`. **2. Add the server with a header** Add a remote server entry with the URL for your environment and a header carrying your Nevermined API key — `headers` is a free key/value map, so add `Authorization: Bearer `: ```json theme={null} { "mcpServers": { "nevermined-catalog": { "serverUrl": "https://mcp.live.nevermined.app/mcp", "headers": { "Authorization": "Bearer " } } } } ``` | Environment | `serverUrl` | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **3. Refresh** Press **Refresh** in the MCP panel — Cascade does not reload the config on its own. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Paste it in place of `` and keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Windsurf. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Ask for something only live data can answer, and name the server so Cascade reaches for it rather than answering from memory. **1. Browse for free** In Cascade, ask *"list the Nevermined catalog categories"* — a free tool call, no payment. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined server and show me the response."* The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If Cascade answers without paying, it answered from its own knowledge — name the server and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Windsurf off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Windsurf side).** Delete the Nevermined entry from `mcp_config.json` and press **Refresh**. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from Zapier Source: https://nevermined.ai/docs/products/catalog/connect/zapier Connect the Nevermined Catalog to Zapier — add the MCP Client, paste your Nevermined API key, and your Zaps pay for services as they run. Zapier can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as a Zap runs. You add the MCP Client, paste your Nevermined API key, and Zapier does the rest. This is the per-host walkthrough; for the full tool surface and the safety model, see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > Zapier connects with a **plain Nevermined API key**, not the OAuth "approve a spending cap" flow that some assistants (Claude, ChatGPT) use. The key is your credential — it spends whatever its Nevermined account funds, so you set the budget on your account, not in Zapier. ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). **2. A Nevermined API key** Create a **plain** API key in the app — **Settings → Global NVM API Keys** — for the environment you want, and send the whole string, prefix included (`sandbox:…` or `live:…`). A key minted by an OAuth flow can't pay through the Router's delegation routes, so use a plain one. See [Get a Nevermined API key](/docs/agents-guide/get-api-key). **3. A way to pay** The key spends from your [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets when it signs up with a verified email, top-up packs, or a Nevermined Subscription's monthly allowance — or from a spending **delegation** — a capped, revocable budget funded from your own wallet ([Using the Catalog from a harness](/docs/products/catalog/from-a-harness) walks through it). Discovery is free and needs neither. > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Zapier at **live**. ## Add the Catalog to Zapier **1. Add the MCP Client** In a Zap, add the **MCP Client** (beta) and choose **Connect an Account**. **2. Point it at the server** Set **Server URL** to the Catalog MCP URL for your environment and **Transport** to **Streamable HTTP**: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | **3. Set the Bearer token** Leave **OAuth** set to **No**, and paste your Nevermined API key into the **Bearer Token** field. > [!NOTE] > > Zapier's **MCP Client is in beta** and its fields may change. ## Your Nevermined API key That key is your credential — there is no separate consent screen to approve. Keep the prefix: a `live:` key for `mcp.live`, a `sandbox:` key for `mcp.sandbox`. The key spends whatever its account funds — your [Subscription](/docs/products/catalog/router/subscription) credits, or a [spending delegation](/docs/products/catalog/from-a-harness) funded from your wallet — so the budget and the audit trail live on your Nevermined account, not in Zapier. Treat it like a password: never commit it or paste it into a shared chat. Every way to mint one: [Get a Nevermined API key](/docs/agents-guide/get-api-key). ## Make your first paid call Give a Zap a task that needs a live, paid service, so the MCP Client reaches for the Catalog tools rather than answering from memory. **1. Browse for free** Have the Zap call a free discovery tool first — *list the Nevermined catalog categories*, or *search the catalog for a weather service*. Discovery needs no payment. **2. Let it buy** Then have it pay a service by slug — *buy the service `` and return the response*. The paid call draws on your Nevermined credits or delegation and returns the merchant's response. > [!TIP] > > If the Zap answers without paying, it answered from its own knowledge — have it call a discovery tool first and ask for something only live data can answer. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect or rotate the key * **Stop the credential (Nevermined side).** The key *is* the credential, so to cut Zapier off, **rotate or delete the key** in the app (**Settings → Global NVM API Keys**) — every call with the old key then fails. To cap spending without revoking the key, revoke the delegation it spends from in [Payment methods](https://nevermined.app/payment-methods); discovery still works. * **Remove the server (Zapier side).** Remove the Nevermined MCP Client connection from your connected accounts. To spend again, paste a fresh key; if you revoked the delegation, create a new one — see [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The full plain-key playbook — discovery, delegations, and the safety rules. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#auth-&-transport) > > Every tool, the API-key header, and every refusal code. # Connect the Catalog from Zed Source: https://nevermined.ai/docs/products/catalog/connect/zed Connect the Nevermined Catalog to Zed — add one MCP server, approve one spending cap, and Zed pays for services as it works. No API key. Zed can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as it works, without you handing over an API key. You add one server, approve a single spending cap, and Zed does the rest. This is the per-host walkthrough; for the concept and the other assistants, see [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). ## Before you connect **1. A Nevermined account** Free, at [nevermined.app](https://nevermined.app). You never share an API key with Zed — the consent cap *is* the credential. **2. A funded wallet** A paid call draws on a **spending cap** you approve during connect — a [commerce grant](/docs/mcp/catalog-mcp/overview#auth-&-transport): a capped, revocable budget funded from your own wallet, not a key. Fund that wallet first with the asset the service settles in — see [Fund your wallet](/docs/products/catalog/router/quickstart#3-fund-your-wallet). You approve the cap itself in [Approve the spending cap](#approve-the-spending-cap). > [!NOTE] > > Start on **sandbox**, where you use testnet funds and nothing costs real money, before you point Zed at **live**. ## Add the Catalog to Zed **1. Add the server** Open **Settings → AI → MCP Servers** (or run the **agent: open settings** action), click **Add Server → Add Remote Server**, and enter a name and the URL for your environment: | Environment | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | Leave the headers blank — with no `Authorization` header Zed runs the standard MCP OAuth (PKCE) flow for you, identifying itself with its own client metadata document, so there is nothing to register. Zed stores the server under `context_servers` in your settings. **2. Authorize** With no `Authorization` header set, Zed runs OAuth and opens Nevermined's consent page on your first **paid** call — browsing and free tools need no sign-in. The indicator dot next to the server name turns green (**Server is active**) once it is connected. ## Approve the spending cap Zed opens Nevermined's consent page on your first **paid** call. Discovery and free tools need no credential. It is the one place a human is required. **1. Check who and where** The page shows the **Sandbox / Live** badge and **who is asking**. On **live**, the cap is real money. **2. Set the cap and validity** Set the **spending cap** (USDC or EURC) and how long the grant is **valid for**, then **Grant access**. That approval is a **commerce grant**: it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Nevermined's routing fee comes out of the same cap, and the grant can also read your payment history and wallet balance — [the cap bounds what it can spend, not what it can see](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). ## Make your first paid call Ask for something only live data can answer, and name the connector so Zed reaches for it rather than answering from memory. **1. Browse for free** Ask *"list the Nevermined catalog categories"* — a free tool call, no sign-in. **2. Ask it to buy** *"Buy the service with slug `` through the Nevermined connector and show me the response."* The paid call draws on the cap you approved and returns the merchant's response. > [!TIP] > > If Zed answers without paying, it answered from its own knowledge — name the connector and ask for live data. More on phrasing: [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Disconnect * **Revoke the budget (Nevermined side).** Open [Connections](https://nevermined.app/connections) and disconnect Zed. The credential stops working on its next call; discovery still works. * **Remove the connector (Zed side).** Remove the server from **Settings → AI → MCP Servers** (or delete its `context_servers` entry in your settings). To spend again — after you disconnect, or after a cap is used up — re-run the connect step and approve a **new** cap. A budget is never widened or extended in place. ## Next > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > The concept and the other assistants. > [card] [Catalog MCP — full reference](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every click path, the consent details, and every refusal code. # Discovering AI Services Source: https://nevermined.ai/docs/products/catalog/discover Browse the Catalog in the app, or read its public feed and search it through the Catalog MCP — then pay for what you find through the Router. A human browses the Catalog in the app. An agent reads its **public, unauthenticated** feed, or searches it through the Catalog MCP server. All three surface the same curated set of Router-payable services. ## Browse in the app Open [nevermined.app/catalog](https://nevermined.app/catalog/) to explore listings visually: * **Categories** — filter by top-level category and sub-category (Search & Research, Crypto & Blockchain, AI & Media, and more). * **Search** — free-text over a service's title and description. * **Service detail** — each listing has a page with its description, protocol, indicative price, callable endpoints, tags, and links to the provider's homepage and docs. The app is a browsing surface. To actually *buy*, an agent drives the [Router](/docs/products/catalog/router/quickstart) — the same directory, read programmatically. ## Read the feed Every listed service is in one public JSON document, **[ai-catalog.json](https://nevermined.app/catalog/ai-catalog.json)**. It's unauthenticated and cached for five minutes, so send no `Authorization` header. Fetch it once and filter on your side: ```bash theme={null} curl -s https://nevermined.app/catalog/ai-catalog.json -o ai-catalog.json jq '.total' ai-catalog.json ``` > [!NOTE] > > **`/api/v1/catalog/services` and `/api/v1/catalog/categories` aren't a public integration.** They return `403` to outside callers, by design. Read the feed instead, or use the [Catalog MCP](#search-server-side-with-the-catalog-mcp) when you want the search done for you. The feed lists the **live** Catalog, and its services are live-only for payment: they settle on mainnet and a sandbox deployment funds testnets only, so paying one from sandbox fails with `400 BCK.ROUTER.0001` (see [an agent buying on its own](/docs/products/catalog/router/agent-autonomy)). The one exception is the pair of free testnet test merchants the sandbox Catalog carries for rehearsal — see [the Commerce MCP page](/docs/mcp/catalog-mcp/overview#1-connect-your-host). ### Filter it The feed has no query parameters: it's the whole Catalog, so every filter runs on your side. These all work as written against the file you just saved. **By category and protocol:** ```bash theme={null} jq '[.services[] | select(.category == "Search & Research" and .protocol == "x402") | {slug, title, priceLabel}]' ai-catalog.json ``` **By free text** over title and description, case-insensitive: ```bash theme={null} jq --arg q "crypto" '[.services[] | select((.title + " " + .description) | ascii_downcase | contains($q | ascii_downcase)) | {slug, title, protocol, priceLabel}]' ai-catalog.json ``` **The categories in use**, with a count and the sub-categories under each: ```bash theme={null} jq '.services | group_by(.category) | map({category: .[0].category, count: length, subCategories: (map(.subCategory // empty) | unique)})' ai-catalog.json ``` **One service by slug**, with the path to send for each endpoint: ```bash theme={null} jq '.services[] | select(.slug == "superhighway") | {slug, protocol, invokeUrl, endpoints: [.endpoints[] | {method, path: (.invokePath // .path), priceLabel}]}' ai-catalog.json ``` Category names are matched verbatim — `"Search & Research"`, not `"Search"` — and a misspelt one returns an empty list, not an error. Take them from the categories recipe rather than from memory. The fields you'll actually use on each service: | Field | Use | | - | - | | `slug` | Stable, case-sensitive id — how you address the service through the Router | | `protocol` | `x402` or `mpp` — payable through the Router | | `category` / `subCategory` | Curated category and its granular label (`subCategory` is absent when there is none) | | `priceLabel` | Human string like `"$0.001"` — **indicative only**; the wire price governs | | `network` / `networks` | Display names (`"Base"`, `"Tempo"`), not chain ids | | `endpoints[]` | `{ path, method, description, priceLabel }`; some also carry `invokePath`, `requestExample` and `responseFields`. An endpoint the Router has priced in the last 48 hours also carries a `quote`: the merchant's price for one call **on the rail and network the Router actually pays it on**, read from the merchant's own 402 — `rail` (`x402` or `mpp`), `intent`, `network` (a wire id such as `eip155:8453` or `tempo`, not a display name), `asset`, `amountAtomic` with its `decimals`, `observedAt` and `variable` (a variable price adds `range` and `driver`). That endpoint's `priceLabel` then shows the same price. It excludes the Router's routing fee and assumes the Router's default rail choice; `POST /api/v1/router/quote` prices your exact call under your Delegation, fee included. An endpoint with `auth: "siwx"` is not paid: it is the result endpoint of an async service, free for the wallet that paid an earlier call to it, and listed as a template (`/api/jobs/{jobId}`) — see [Getting your results](/docs/products/catalog/paid-results) | | `invokeUrl` | The service's Router URL, `…/api/v1/router/svc/` | | `invoke` | A ready-made Router call: method, URL and the `X-Router-*` headers to send | > [!WARNING] > > **The feed carries no merchant URL, on purpose.** You pay a listed service **by its slug**: the Router resolves the merchant's host server-side and refuses a raw-URL payment to it with `409 BCK.ROUTER.0014`. For an endpoint, send its `invokePath` when present — even when it's `""`, which means "append nothing" — and its `path` otherwise. In code that's `invokePath ?? path`, not `||`: turning `""` back into the path double-stacks it, and the call 404s after the charge. ## Search server-side with the Catalog MCP The [Catalog MCP server](/docs/products/catalog/mcp) does the search for you. Its `search_services`, `get_service` and `list_categories` tools are free and need no key. One stateless POST per call: ```bash theme={null} curl -s -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -X POST https://mcp.live.nevermined.app/mcp \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_services","arguments":{"query":"crypto","protocol":"x402"}}}' \ | jq -r '.result.content[0].text' | jq . ``` Always send a `query`, and read the result as plain JSON rather than a fixed shape — search is moving to semantic ranking with a new result format (see [Run a discovery call](/docs/mcp/catalog-mcp/overview#3-run-a-discovery-call)). Don't page through it: to see the whole Catalog, use the feed. More worked calls, including `get_service`'s `requestShape`, are in [Build Outcomes](/docs/products/catalog/build-outcomes#see-what-the-catalog-proposes). ## For crawlers and registries * **[`/.well-known/ard.json`](https://nevermined.app/.well-known/ard.json)** — the [Agentic Resource Discovery](/docs/integrate/authentication/for-agents) host document: one entry per service with its Router pay-through target and health status (`nvm:catalog.healthStatus`). Its list key is `entries`, not `services`. * **[`/catalog/llms.txt`](https://nevermined.app/catalog/llms.txt)** — the plain-text entry point for an agent landing on the Catalog cold. > [!TIP] > > The full machine-facing discovery contract — the feed's fields, the slug-addressing rule, and more filter recipes — ships in the **[Router AI coding skill](/docs/development-guide/build-using-nvm-skill)** (`nevermined-router`), so your assistant already knows how to walk the Catalog. ## What "listed" means The Catalog only lists services the Router can actually pay — those that price each request on the wire (**x402** and **MPP**). Services that bill out of band aren't listed, so a browsing agent is never handed one it can't buy. More on the Catalog's contents in [AI Services](/docs/products/catalog/ai-services#what-gets-listed). ## From discovery to a paid call Once you've picked a service, buying it is the Router flow: **1. Read its slug and endpoint** Straight off the feed entry: the `slug`, plus the endpoint's `invokePath ?? path`. You don't need to know x402 from MPP — the Router probes the service and detects the protocol from its `402`. **2. Get an API key, a Delegation, and funds** A one-time setup — see the [Router quickstart](/docs/products/catalog/router/quickstart). **3. Route the call** Hand the Router the slug and the request. It pays the `402` from your wallet, enforces your cap, and relays the answer. > [card] [Router quickstart](/docs/products/catalog/router/quickstart) > > From an API key to a paid call against a service you found here, in five steps. ## Publish your own service Listing a service **you** own — and the health validation it passes before it goes live — is covered in [AI Services → Add your AI Service](/docs/products/catalog/ai-services#add-your-ai-service). # Using the Catalog from a harness Source: https://nevermined.ai/docs/products/catalog/from-a-harness A concise, code-free playbook for driving the Nevermined Catalog and Router from an agent harness — the flow, the safety principles, and every link in one place. A short, reusable manifesto for anyone driving the [Nevermined Catalog](https://nevermined.app/catalog/) from an agent harness — Claude Code, Cursor, an MCP client, or your own runtime. No code — just the flow, the principles, and the links. > [!TIP] > > This page is meant to be **handed to your agent as-is**. Point your harness at it (or share the link) and it has everything it needs to discover, pay, and reconcile safely. ## See it in action New here? Watch the **Song from the Headlines** example drive the whole flow from a harness, end to end — then read on for the machine-readable version your agent follows (the video is the one part of this page a harness can't consume). [Song from the Headlines — a Catalog use case from a harness](https://www.youtube.com/embed/Ilj93OUSxV8) Song from the Headlines — a Catalog use case driven from a harness. ## What the Catalog is The Nevermined Catalog is a curated directory of external AI services your agent can **pay for per call** — no per-vendor signup, no subscriptions. Each service settles a single request through Nevermined using the [x402](https://nevermined.ai/glossary/x402/) or MPP payment protocols. Your agent discovers a service, calls it, and the payment happens in the background against a budget you control. * Browse services: **[nevermined.app/catalog](https://nevermined.app/catalog/)** * Machine-readable feed of every service: **[ai-catalog.json](https://nevermined.app/catalog/ai-catalog.json)** * What "agentic commerce" means: [nevermined.ai/glossary/agentic-commerce](https://nevermined.ai/glossary/agentic-commerce/) ## The mental model Five pieces, and it clicks: | Piece | What it is | | - | - | | **Harness** | your agent runtime — where the agent decides what to buy | | **Catalog** | the marketplace of pay-per-call services | | **Router / Facilitator** | Nevermined's broker that reads a service's payment challenge, pays it, and returns the result — so your agent never touches a vendor account or a private key | | **Delegation** | your spending authority: a hard, time-boxed budget cap the agent pays *within* — and creates itself | | **API key** | authenticates your agent to Nevermined on every call — an assistant host that runs OAuth (Claude, ChatGPT, LangSmith Fleet) obtains one for you through the commerce consent, so your agent never handles it | The agent never holds card numbers or wallet keys and never calls Stripe or a chain directly. It holds an API key and a delegation; Nevermined does the rest. ## Who does what A human is needed only for the account, the money and the key. Everything else is the agent's job — including creating the budget it spends within. | A human, once (Step 0) | Your agent, with a plain API key | | - | - | | Creates the Nevermined account (browser sign-in) | Creates its own delegation (Step 1) | | Funds the wallet with stablecoin on Base and Tempo — or pays with [credits](#paying-with-nevermined-credits): free at sign-up, or from a subscription | Discovers services, prices a call, pays, and moves to the next service when one fails | | Creates a plain API key and hands it to the agent | Reconciles what it spent | Ask a human only for the left column. Don't wait for one to create the delegation. ## Step 0 — One-time setup (the only human steps) > [!WARNING] > > **The Catalog is Live-only for payment.** Discovery works on either host, but listed services settle on mainnet and the sandbox Router funds testnets only — so paying one from sandbox fails (`400 BCK.ROUTER.0001`). The only things a sandbox key can buy are the two free testnet test merchants kept there for rehearsal (see [the Commerce MCP page](/docs/mcp/catalog-mcp/overview#1-connect-your-host)). Every step here uses the Live network and real (if tiny) money; keep caps small and rehearse with a sub-cent service. * App (sign in, keys, delegations): [nevermined.app](https://nevermined.app) * Live API base: `https://api.live.nevermined.app` — your API key for this network is prefixed `live:` (send the whole string, prefix included). **Sign in and get a plain key.** Open [nevermined.app](https://nevermined.app), sign in, and get a plain Nevermined API Key — a one-time, human-in-the-loop step (created in the app, SDK-minted, or through the embedded `/auth/cli` login). Don't use the [device flow (RFC 8628)](/docs/integrate/authentication/device-flow) here: like every OAuth-minted key, its key can't create a delegation or pay through the Router's delegation routes (`403 BCK.OAUTH.0030`). See [Get a Nevermined API key](/docs/agents-guide/get-api-key) for the embedded-login and SDK paths, and [Authentication](/docs/integrate/authentication/overview) for the OAuth ones. Store it, reuse it, and keep it out of logs. > [!TIP] > > **The agent-facing version of this step is [`auth.md`](https://nevermined.app/auth.md)** — the machine-readable manifest kept in lockstep with the API: the discovery documents, the bearer contract and key format, every ceremony that ends in a key (SDK, device flow, and the OAuth **commerce consent**), and what needs a human. Hand it to your harness alongside this page; where the two differ, `auth.md` is the one that names endpoints that exist today. **Or let your assistant get it for you.** If your harness is an AI assistant that runs OAuth on your behalf — Claude (the claude.ai connector), ChatGPT, Claude Code, LangSmith Fleet, or another MCP host whose client Nevermined's operator has listed (following the MCP authorization spec buys a host its identity, not this authority — an unlisted host is refused at the consent screen) — you skip the key, and Step 1's delegation: add the [Catalog MCP](/docs/mcp/catalog-mcp/overview#auth-&-transport) with no key, and the assistant sends you to Nevermined to approve a **spending cap** once — when you add the server on the strict host, on the first paid call on the public one. That approval is the delegation of Step 1 *and* the credential of this step, in one screen; the assistant renews the credential silently. The cap bounds what it can *spend* — not what the grant can see or do on your account (it reads your Router payment history and wallet balance, lists and can revoke your delegations, and can start a new delegation ceremony for you to approve); `auth.md` §6 has the full list. Which host and client each assistant uses (two of the four above need the strict `mcp.api.` host), and the mechanics the host follows, are `auth.md` §6. **Funding is not skipped:** a commerce grant spends stablecoin from your own wallet, so the next bullet still applies. **Fund the stablecoin delegation.** A **stablecoin** (`erc4337`) method exists by default — fund it on the networks the Catalog settles on: **Base** and **Tempo**. Services settle on different rails (some on Base, some on Tempo), so keeping a small balance on **both** keeps any service payable — otherwise a call can fail simply because your funds are on the other network. A `commerce` grant from an assistant spends this same stablecoin from your own wallet. > [!WARNING] > > **A card does not fund Catalog calls by default.** An x402 catalog listing needs a stablecoin `erc4337` delegation, and by default the Router pays catalog calls only from one — the Stripe SPT card rail is **off by default** and enabled per deployment. (Separately, a card delegation pays Nevermined *plans* over x402/MPP — a different flow.) For the Catalog, fund the stablecoin delegation above, or spend [Nevermined credits](#paying-with-nevermined-credits). ## Step 1 — The agent creates its budget (the delegation) The [delegation](/docs/specs/x402-card-delegation) is your capped, server-enforced spending authority (see the mental model above) — the single most important safety control here. **With a plain API key, the agent creates it itself. This is not a human step.** ```http theme={null} POST https://api.live.nevermined.app/api/v1/delegation/create Authorization: Bearer Content-Type: application/json { "provider": "erc4337", "currency": "usdc", "spendingLimitCents": 100, "durationSecs": 86400, "maxTransactions": 10 } ``` The response carries the `delegationId` every paid call names (`X-Router-Delegation-Id`, or `delegationId` in a JSON body). `erc4337` is the stablecoin delegation the Catalog's rails pay from; it needs no card. * **Set the cap to the budget the user gave you** (`spendingLimitCents` is in cents: `100` above is \$1). It's your spending limit: every price, the Router fee and any retries come out of it. Keep a **soft stop** a little below it in your agent so a run halts cleanly rather than erroring at the wall. * **Count transactions for a retry.** `maxTransactions` counts every paid attempt, including one the service then refuses, so set it above the number of calls you plan — or omit it and let the cap bound the spend. A transaction limit of exactly the planned calls can't recover from one bad result. * **Reuse before you create.** `GET /api/v1/delegation?accessible=true` lists the *Active* delegations your key can spend; reuse one with enough budget left. * **Ask a human only when** creating it answers `403 BCK.OAUTH.0030` (your key was minted by OAuth — you need a plain key) or `412` with `"error": "consent_required"` (the account must accept updated terms in the app). Any other refusal here (a `401` for an invalid or expired key, for example): stop and report the exact error to the user. * **Never create another delegation to get past a cap or budget refusal** (`402 BCK.ROUTER.0003`, whatever its hint says): report it and stop. The cap is the user's decision. A human *can* set the cap instead — in the app (Payment Methods → Delegate), or through the Catalog MCP's `setup_delegation` tool, which returns a link for them to approve — but neither is required. ## Step 2 — Discover services (free, no key required) The catalog's read surface is **public** — browse or filter it before spending a cent. * Human view: [nevermined.app/catalog](https://nevermined.app/catalog/) * Full feed (all services): [ai-catalog.json](https://nevermined.app/catalog/ai-catalog.json) — for discovery; it carries no request schemas (see below) Every listing tells you what you need to choose: its **slug** (how you address it), **protocol** (x402 or MPP — handled for you), a **price label**, its **endpoints**, and **tags**/category. Filter by task (e.g. web search, email enrichment, scraping, social data) and by price, and shortlist the cheapest service that answers the need. Listings are returned in a **recommended order** — Nevermined's own quality ranking, not alphabetical — so the top of the list is a sensible default rather than something you score yourself. Treat that order as *guidance, not a contract*: it is recomputed as health and traction change. Each feed entry also carries a `displayPriceSource` of `settled` or `quoted` (a `settled` price means real, multi-payer settlement — the service is genuinely used, not just advertised) and `partner`/`featured` flags you can weigh. > [!WARNING] > > **Read an endpoint's request schema before you call it — never guess parameter names.** Discover with the feed if you like, but `ai-catalog.json` never carries request schemas, by design. Before calling an endpoint, read its `requestSchema` — the merchant-declared JSON Schema of the query or body fields it takes, and which are `required` — from a detail-shaped read: > > * **One service you already picked:** Catalog MCP `get_service` with its slug → `requestShape.endpoints[].requestSchema` (no key needed), or ARD search `POST https://api.live.nevermined.app/api/v1/ard/search` with `{ "query": { "text": "" } }` → `results[].nvm:catalog.endpoints[].requestSchema`. > * **Browsing:** ARD list `GET https://api.live.nevermined.app/api/v1/ard/agents` → `items[].nvm:catalog.endpoints[].requestSchema`. It is paged (20 per page by default, up to 100) and filters only by `type`, `tags`, `publisher` and `updatedAt`, so it cannot fetch one service by slug. > > Use the exact names the schema gives: an endpoint whose schema requires `ticker` rejects a call that sends `symbol` with a `422`. Where an endpoint has no `requestSchema`, build the request from its `requestExample` (pre-filled in `get_service`'s `payServiceArgs` when it is verified) and description, or from the provider's documentation — not from a guess. Multi-model services, for example, expect a **provider-prefixed model id** (`openai/gpt-4o-mini`, `google/gemini-2.5-flash-lite`); a bare `gpt-4o-mini` is usually rejected with a typed `400`. > [!TIP] > > **Don't know which service to pay?** Let the Router pick instead of scoring listings yourself: `POST /api/v1/router/select` with a plain-language `intent` (and optional `filters` — `category`, `protocol`, `network`, `maxPriceLabel`) returns the single best **payable** service plus a ranked `shortlist`, chosen deterministically on Nevermined's own relevance and quality signals behind a payability gate. **Take the returned order as authoritative — read the order, not the numbers**: the `relevance` scores can sit on different scales (semantic vs keyword), so re-sorting by them yourself can pick worse. Add `autoPay: true` (with `requestId` + `delegationId`) to select **and** pay in one call. This uses your API key — see the [Router quickstart](/docs/products/catalog/router/quickstart), and [Let the platform pick a service](/docs/mcp/catalog-mcp/overview#let-the-platform-pick-a-service) for the full shortlist shape. ## Step 3 — Connect the harness to the Catalog Two paths — pick one: | | **Catalog MCP** | **Router API** | | - | - | - | | Best for | harnesses that speak MCP | any harness / quick start | | How | add the Nevermined Catalog MCP server to your harness config with your API key — or, in an assistant that runs OAuth (Claude, ChatGPT, Fleet), by URL alone and approve a spending cap on the first paid call; you get discovery + payment tools natively | call Nevermined's Router to pay any service by its slug | | Note | most harnesses load MCP servers **at startup** — add it, then restart the session | works immediately, no restart | | Docs | [Catalog MCP](/docs/products/catalog/mcp) | [Router quickstart](/docs/products/catalog/router/quickstart) · [OpenAPI](https://api.live.nevermined.app/api/v1/rest/docs-json) | Either way the shape is the same: name the service (by slug), pass your delegation, get the result back. The Router reads the vendor's payment challenge, pays from your delegation, and returns the response. ### Using the Catalog MCP If your harness speaks MCP, the server drops discovery and payment in as native tools. Point your client at the server URL and put your Nevermined API key on the `Authorization` header — or, in an assistant that runs OAuth (Claude, ChatGPT, LangSmith Fleet), connect by URL alone and approve a spending cap once: ```json theme={null} { "mcpServers": { "nevermined-catalog": { "url": "https://mcp.live.nevermined.app/mcp", "headers": { "Authorization": "Bearer ${NVM_API_KEY}" } } } } ``` Use `https://mcp.sandbox.nevermined.app/mcp` to rehearse. The tools your agent then has — discovery is **free**, the rest need the credential, and `pay_service`, `route_by_intent` (with `autoPay`) and `top_up_credits` move money: | Tool | Free? | What it does | | - | - | - | | `list_categories` · `search_services` · `get_service` | free | Browse the Catalog, search it (hybrid ranking), and read one service's callable endpoints. | | `route_by_intent` | paid | Describe a need; get the single best payable service back, and optionally pay it. | | `quote_service` | paid | Price one call before paying — live, fee-inclusive total. | | `pay_service` | paid | Pay a service and return its response. | | `setup_delegation` | paid | Get a URL for a human to approve a spending cap, when none exists yet. | | `get_payment_result` | paid | Read a paid call's result by `paymentId` (for a `pending` call, or a lost response). | | `list_payments` · `payment_summary` · `get_budget` · `wallet_balance` | paid | Reconcile spend, count payments, read the budget, and check wallet funding. | | `top_up_credits` | paid | Refill [Nevermined credits](#paying-with-nevermined-credits) within the human-set monthly limit — charges one pack to their card, no new approval. | Every argument, return field and refusal is in the [Catalog MCP reference](/docs/mcp/catalog-mcp/overview); the [product page](/docs/products/catalog/mcp) has the per-assistant setup walkthroughs. ## The calling convention (one canonical shape) If you drive the Router API directly, there is **one convention in three forms** — all settle identically; they differ only in how you pass the target and where the result comes back. Pick the one that fits your client. Full copy-paste curl lives in the **[Router quickstart](/docs/products/catalog/router/quickstart)**; this is the map. | Form | Endpoint | How you name the service | Best for | | - | - | - | - | | **JSON** | `POST /api/v1/router/route` | `url` (off-catalog) **or** `slug` (cataloged) in the JSON body — exactly one | most harnesses (the quickstart uses `url`) | | **Header proxy** | `ANY /api/v1/router/proxy` | `X-Router-Target-Slug` header (cataloged) **or** `X-Router-Target-Url` (off-catalog) — exactly one | pointing an existing HTTP client at the Router transparently | | **Path** | `ANY /api/v1/router/svc/[/]` | the slug in the path — and **no** target header | a REST-shaped call that maps cleanly onto the service's sub-paths | > [!WARNING] > > **Use one form per call — never mix them.** `/router/proxy` with `X-Router-Target-Slug` reaches only the service's **base URL**. To call an endpoint under it, use `/router/svc//` and send **no** `X-Router-Target-Slug` (or `X-Router-Target-Url`) header: the Router refuses a `/svc` call that carries one with `400 BCK.ROUTER.0001`, before anything is paid. Take the `` from the listing (the endpoint's `invokePath`, or `payServiceArgs.path` in the Catalog MCP). All three forms need the same two facts — **which delegation pays** and **an idempotency id** — but they carry them differently. **The JSON form** (`/router/route`) takes them as **body fields**: `delegationId` and `requestId` (both required — a header-only `/route` call fails validation), and returns the payment in the JSON response envelope (`payment.paymentId`, `payment.status`, `payment.txHash`, `payment.failureReason`). **The two transparent forms** (`/router/proxy`, `/router/svc`) carry them as `X-Router-*` **request headers** instead, and return the payment as **response headers**: | Header | Required | Meaning | | - | - | - | | `X-Router-Delegation-Id` | yes | which delegation (budget) pays | | `X-Router-Request-Id` | yes | your idempotency id — reuse it on a retry so a hiccup never double-charges (a duplicate is refused with `409 BCK.ROUTER.0002`, the original `paymentId` in `params`); use a **fresh** one per new purchase, and per async poll (see below) | | `X-Router-Upstream-Authorization` | no | the agent's own auth to the upstream, if it needs one | | `X-Router-Forward-` | no | forward one extra header to the upstream | The transparent response carries `X-Router-Payment-Id`, `X-Router-Payment-Status`, `X-Router-Tx-Hash`, and — on a failed/unsettled payment — `X-Router-Failure-Reason`. **Two optional controls on the JSON form** (`/router/route`): put a GET's query string in **`search`** — **without** a leading `?`; the Router appends it to the resolved target. Cap one call with **`maxTotalCents`**, the most whole cents it may reserve against the delegation, **fee included** (the `402` price can differ from the catalog label; a quote above it is refused `402 BCK.ROUTER.0018`, no charge). See [Guardrails](/docs/products/catalog/router/guardrails). > [!TIP] > > Address a cataloged service by its **slug**, never a raw URL: the Router hides the vendor's host on purpose, so paying one by raw URL is refused (`409 BCK.ROUTER.0014`). Keep raw **URLs and hosts** out of the path — a security guard blocks anything there that looks like it changes the destination host. The resolved `slug` in `/svc/` is exempt, because the Router maps it to the host server-side. ## Paying with Nevermined credits If the user holds [Nevermined credits](/docs/products/catalog/router/subscription) — the free credits a new account gets (check `GET /api/v1/credits/welcome/offer`), top-up packs, or a Nevermined Subscription's monthly allowance — some catalog endpoints can be paid with them instead of the delegation: Nevermined pays the merchant, the call costs a fixed number of credits with no routing fee, and the credits come back if the service doesn't answer `2xx`. Credits pay only the endpoints that carry a rate, so keep a delegation for the rest. **Price a call in credits** — this charges nothing. A listing's USD `priceLabel` is not its credits price; don't convert one into the other. * **Catalog MCP, connected with your API key:** `get_service` shows `subscription.creditsPerCall` on each endpoint credits can pay (no `subscription` field means credits can't pay it). `quote_service` with `funding: "subscription"` prices one call. * **REST:** `GET /api/v1/subscription/catalog/credits` lists every endpoint credits can pay, with its `creditsPerCall`. `POST /api/v1/router/subscription/quote` with `slug`, `path` and `method` prices one call. * **ARD discovery, with your API key:** a keyed `POST /api/v1/ard/search` or `GET /api/v1/ard/agents` read carries `subscription.creditsPerCall` inline on each endpoint credits can pay (`nvm:catalog.endpoints[].subscription`), so the credits price comes back with discovery in one call. An **unauthenticated** read omits it — send your key to see it. **Pay with credits.** Credits are spent only through these two paths: * **The Catalog MCP connected with your API key**, or through an OAuth connection the human allowed to spend credits (below). `pay_service` pays with credits by default when the credits and the endpoint qualify, and from the delegation otherwise. Pass `funding: "subscription"` to insist on credits; the result's `funding` and `creditsCharged` say what paid. * **`POST /api/v1/router/subscription/route`** with `slug`, `path`, `method`, `body` and `requestId` — no `delegationId`, no URL. The streaming form is `/api/v1/router/subscription/svc//` with an `X-Router-Request-Id` header. The delegation routes (`/router/route`, `/router/proxy`, `/router/svc`) never spend credits. An OAuth connection (the claude.ai connector, ChatGPT, or a host connected through the OAuth consent) spends them only if the human ticked **Let this assistant spend my Nevermined credits** when connecting it; otherwise it pays from the cap the human approved, and the credits routes refuse it (`403 BCK.OAUTH.0037`, or `0030` for an OAuth key that isn't a commerce connection). Use a personal API key and no `X-Current-Org-Id` header. `GET /api/v1/credits/balance` returns the credits that can pay now. Every rule and refusal code: [Pay with Nevermined credits](/docs/products/catalog/router/subscription). **Refill before you run low.** If a human has enrolled a card and set a monthly top-up limit, the agent can charge a pack of credits itself — within that limit, no new approval. `POST /api/v1/credits/topups/pack` with a `requestId` you choose and `forCallCredits` (what the next call needs) charges one pack **only when your spendable credits are below it** (otherwise `not_needed`, nothing charged); `GET` the same path reads the limit first. The Catalog MCP wraps this as [`top_up_credits`](/docs/mcp/catalog-mcp/top-up-credits), which documents every `status` and the 3-D Secure / `operatorUrl` handling. Turning top-ups on and setting the limit stay with the human, in the App. (With **your own API key** and top-ups on, a credits call that runs out also charges a pack on its own; through an OAuth connection it never does, so an OAuth-connected agent must call `top_up_credits` — see [`pay_service`](/docs/mcp/catalog-mcp/pay-service#when-a-call-charges-a-top-up-pack).) ## Async services (generate, then poll) Some services are asynchronous — media generation, for example. The first call returns a `taskId` instead of the result, and you poll a status endpoint until the result appears. It is fully supported; keep these in mind: * **A placeholder `callBackUrl` is fine.** Some generators require the field even when you intend to poll — pass any well-formed URL; you do not need to receive the callback. * **Know whether the status endpoint is paid or free.** If it answers `402`, each poll is a paid call (see the next bullet). If it is **free** (non-`402`) on a cataloged service, the Router relays only the *status* and withholds the body by default — the free-follow-up window is off unless the deployment enabled it *and* the merchant declared the path — so a free poll can return `200` with no result. Check the endpoint on the listing. * **Give every poll a *fresh* `X-Router-Request-Id`.** The Router de-duplicates on that id, so reusing one makes each repeat a *duplicate* that is refused (`409 BCK.ROUTER.0002`, the original `paymentId` in `params`, no result) — it is **not** a new charge, but it never reaches the service either, so a naive poller stalls and never advances. A fresh id per poll advances it — and on a **paid (`402`) status endpoint** each real poll is a separately-billed call (the merchant charges per status check), so bound the number of polls against your delegation cap. (A free status endpoint relays with `paid: false` — no charge.) The [Catalog MCP](/docs/products/catalog/mcp)'s `pay_service` exposes a `fresh` flag that mints the fresh id for you. * **Read the generate and status endpoints — and the field that carries the `taskId` and the result — from the service's detail** (`requestSchema` / `requestExample` / `responseSchema`, via ARD `/search` · `/agents` or MCP `get_service`). ## The principles that make it smooth These are the habits that turn trial-and-error into a clean run. Treat them as the manifesto: 1. **Discovery is free — use it first.** Confirm a service's slug, price, and endpoints from the live feed before every task, and each endpoint's request schema from a detail read (ARD `/search` · `/agents`, or MCP `get_service`) before you call it. Prices and listings drift. 2. **A failed call is not reliably free — don't treat it as a cheap probe.** Once the payment credential is minted, the merchant leg stands even if the upstream call then errors; only the routing fee may be released, and only on specific paths. Whether the merchant leg settles before or after the upstream `2xx` depends on the call mode. Confirm how a service wants to be called from its listing and docs, not by paying to find out — see [when a fee is not collected](/docs/products/catalog/router/how-it-works#when-a-fee-is-not-collected). 3. **Judge every result — on junk or a refusal, move to the next service.** A `2xx` is not proof the answer is useful. If the result is irrelevant or empty, or the service refuses the call (a 4xx: `BCK.ROUTER.0019` on `/proxy` · `/svc`, or a 4xx `status` with `body: null` on `/route`), don't stop and don't report the junk as the answer. First tell a free refusal from a possibly paid one (see Step 4): a refusal that names no paymentId cost nothing, so fix the request and resend; a `202`, a `5xx` or any answer naming a paymentId may already have paid the merchant, so look the purchase up by its request id before doing anything else. Otherwise try the next matching service from discovery (or the next `shortlist` entry from `/router/select`) as a new purchase with a fresh idempotency id. The cap is the budget, so retries come out of it (Step 1). 4. **Address a service by its slug and let the Router resolve the endpoint.** Don't fight it with hand-assembled sub-paths — the common failure is a mis-resolved path, not a payment problem. 5. **Put target URLs in the request body, never in the path.** A security guard blocks anything in the path that looks like it changes the destination host. 6. **Give every purchase a stable idempotency id.** Reuse the same id when you retry, so a network hiccup never double-charges; use a fresh id only for a genuinely new purchase. 7. **Async services: poll, don't wait on a callback.** Synchronous services are simplest, but async ones (e.g. media generation) are fully supported — see [Async services](#async-services-generate-then-poll) above. The one trap is a naive poller: give **each poll a fresh idempotency id**. Reuse one and the Router refuses each repeat as a duplicate (`409`, no charge) so the poll never advances; a fresh id per poll advances it, and each **paid** (`402`) poll is a separately-billed call. 8. **The delegation is the source of truth for spend.** Reconcile against your delegation's remaining budget, not a local tally. 9. **Prove the flow cheaply — payment is Live-only.** Sandbox can rehearse the mechanics against its two free testnet test merchants, but no real service is payable there (its Router funds testnets only) — so validate discovery → pay → result end-to-end on Live with a **small delegation cap and the cheapest sub-cent service** before scaling spend up. ## Step 4 — Track and reconcile spend Read your delegation's remaining budget and the Nevermined payment [ledger](/docs/products/catalog/router/ledger) to see exactly what each call cost and how much of the cap is left. This is also your audit trail. See the environment's [OpenAPI reference](https://api.live.nevermined.app/api/v1/rest/docs-json) for the delegation and payment endpoints. **A refused call is not always a free one.** A refusal that names **no** paymentId — no `X-Router-Payment-Id` header, no `payment` in a `/router/route` reply, and no `paymentId` in the error's `params` — cost nothing: fix the request and resend. **Anything else may already have paid the merchant:** a `202`, any `5xx`, or any answer that names a paymentId. A paid hop that gets no response, for instance, answers `502 BCK.ROUTER.0034` (or `0025` when its reply was too large to deliver) with the paymentId only in the error's `params`. Before doing anything else, look the purchase up: `GET /api/v1/router/payments?requestId=` — `"presence": "absent"` means nothing is recorded, so resend with the same id. * **A `202` is still running** — on `/router/route`, and on `/router/proxy` · `/router/svc` before the service starts answering. Poll its `resultUrl` (the `Location` header on the streaming forms), and never buy it again. * **A paid error is undecided, not proof of a charge.** A paid call the service answers with an error other than `402` stays `Issued` until Nevermined reconciles it, with its price reserved against your cap; if the merchant never collects, that reserve is released once the payment's window closes, and if it did collect, the charge stands. A paid hop with no response is marked `Failed`, and the merchant may still have collected. Don't count either as spent or as refunded yet. * **Retry the same purchase only with the same `X-Router-Request-Id`** (or `requestId`): the Router never pays one id twice. Leave room for any held reserve when you buy elsewhere. When a call errors on `/router/proxy` or `/router/svc` (`BCK.ROUTER.0019` / `0020`) — on `/router/route` the same condition arrives as the envelope's `status` with `body: null`, no typed code — `status` is the primary read — it is what you *got* (a non-`2xx` leaves the row unsettled). On the rails that settle on a chain (x402, MPP `evm`, MPP-tempo) there is also `merchantSettlementObservedAt`: when it is **set** alongside `status: Issued`/`Failed`, the merchant collected the payment on-chain and delivered nothing (charged-but-undelivered — worth alerting on). It is `null` on a clean per-call settlement (a captured MPP-tempo `session` call carries it even once `Settled`), whenever reconciliation has no verdict, **and always on MPP-stripe** (which has no on-chain leg to observe), so `null` is *not* proof you weren't charged — when it's `null`, read `status` together with `txHash`. Either way, the Router never takes its own routing fee for a call that did not deliver. ## Safety & etiquette * **Live means real money.** The Catalog is Live-only — keep delegation caps tight and rehearse with a sub-cent service before scaling. * **Mind the data.** Some services return personal or third-party data; use them only where you have a lawful basis, and remember the query is sent to a third-party vendor. * **Protect the key.** Never commit it, log it, or paste it into a shared transcript. ## Links, in one place * Catalog (browse): [nevermined.app/catalog](https://nevermined.app/catalog/) * Catalog feed (all services): [ai-catalog.json](https://nevermined.app/catalog/ai-catalog.json) * Using the Catalog from your web assistant (the no-code counterpart to this page): [/products/catalog/from-your-web-assistant](/docs/products/catalog/from-your-web-assistant) * Catalog MCP: [/products/catalog/mcp](/docs/products/catalog/mcp) * Router quickstart: [/products/catalog/router/quickstart](/docs/products/catalog/router/quickstart) * An agent buying on its own (worked end-to-end run): [/products/catalog/router/agent-autonomy](/docs/products/catalog/router/agent-autonomy) * Nevermined app (sign in, keys, delegations): [nevermined.app](https://nevermined.app) * Get an API key / authentication: [/integrate/authentication/overview](/docs/integrate/authentication/overview) · the agent-facing manifest: [nevermined.app/auth.md](https://nevermined.app/auth.md) * x402 explained: [glossary](https://nevermined.ai/glossary/x402/) · reference: [/api-reference/typescript/x402](/docs/api-reference/typescript/x402) * Stablecoin payments: [/integrate/patterns/stablecoin-payments](/docs/integrate/patterns/stablecoin-payments) * Docs index: [/getting-started/overview](/docs/getting-started/overview) · SDK/API index: [llms.txt](https://nevermined.ai/docs/llms.txt) * API reference (OpenAPI JSON): [docs-json](https://api.live.nevermined.app/api/v1/rest/docs-json) * GitHub: [nevermined-io](https://github.com/nevermined-io) · Contact: [nevermined.ai/contact-us](https://nevermined.ai/contact-us) # Using the Catalog from your web assistant Source: https://nevermined.ai/docs/products/catalog/from-your-web-assistant Connect the Nevermined Catalog to a web AI assistant like Claude.ai or ChatGPT — paste one URL, approve one spending cap, and it pays for services as it works. Web AI assistants — **Claude.ai**, **ChatGPT**, **LangSmith Fleet** — can browse the [Nevermined Catalog](/docs/products/catalog/overview) and pay for services as they work, without you ever handing over an API key. You paste one URL, approve a single spending cap, and the assistant does the rest. This is the no-code, in-the-browser counterpart to [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). > [!NOTE] > > This is the **buyer** side — giving an assistant you already use a wallet. Driving the Catalog from your own code or a coding agent? See [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). The exhaustive per-host click paths (name warnings, Fleet's OAuth provider table, every refusal code) live on the [Catalog MCP](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) page — this page is the walkthrough that gets you there. ## See it in action Give an assistant a budget and ask it to go and buy what it needs — a search, a page fetch, a live forecast — and it pays per call, for a few cents, against a cap you set. [Your AI assistant can now pay for things](https://www.youtube.com/embed/EJk5ZHmd4u0) Your AI assistant can now pay for things. The per-assistant walkthroughs are below, and collected on the [Catalog videos](/docs/products/catalog/videos#connect-from-your-assistant) page. ## What you get * **No API key, no client secret, no vendor account.** Claude and ChatGPT discover everything from one URL; Fleet takes the endpoints once. * **One consent screen** sets who can spend, how much, and for how long. The grant *is* the credential — your assistant never holds a key. * **Every payment is on the record** — merchant, amount, transaction hash, and what's left of the cap — in your [payment ledger](/docs/products/catalog/router/ledger). * **Your assistant can pay any service it discovers**, not a fixed list you wire up in advance. * **Revoking is instant and self-service**, from [Connections](https://nevermined.app/connections) in the Nevermined app. ## How it works — three moves **1. Point your assistant at one URL** The Catalog MCP server URL. In **Claude** and **ChatGPT** that's the whole configuration — paste it, leave the OAuth client ID and secret empty, and the assistant discovers the rest. **LangSmith Fleet** doesn't discover, so you enter its endpoints once. **2. Browse the Catalog for free** Discovery needs no sign-in. Ask for the categories, search for a service, read its price — all before you approve anything. **3. Approve a spending cap, once** Nevermined's consent page opens: check the **Sandbox / Live** badge, set the **cap** and how long it's **valid for**, then **Grant access**. That approval is a **commerce grant** — it spends only from the budget you just approved, only through the [Router](/docs/products/catalog/router/overview), and you can revoke it any time. Your assistant retries the call it was blocked on. > [!TIP] > > **Ask in a way that makes the assistant reach for the Catalog.** All three will happily answer from their own knowledge and charge nothing — which looks like a broken connector and isn't. Name the connector in the prompt (*"using the Nevermined connector, …"*), ask for something only live data can answer, and name services in single words. More on phrasing in the [Catalog MCP tips](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). ## Pick your assistant The click paths differ; the mechanics underneath are identical. Each tab has the short version and a link to the full walkthrough; **Other hosts** collects the coding agents and IDEs that connect the same way. > [tab] Claude (claude.ai) > > **1. Add the connector** > > **Settings → Connectors → Add custom connector.** Name it and paste the server URL. Leave the OAuth client ID and secret **empty** — Claude identifies itself to Nevermined on its own, so there's nothing to register. > > **2. Ask for something free, then ask it to buy** > > Enable the connector and ask *"list the Nevermined catalog categories"* (no sign-in). Then ask it to buy a service — the paid call returns `401` and Claude shows an inline **Connect** card. > > **3. Approve the cap** > > **Connect** → the consent page opens. Set the **cap** and **validity**, **Grant access**, and Claude retries the call with the grant. > > [Connect to the Catalog from claude.ai](https://www.youtube.com/embed/ioDqtiHtOGg) > > Connect to the Catalog from claude.ai. > > Full walkthrough: [Connect the Catalog from Claude](/docs/products/catalog/connect/claude) — the five steps, disconnect and the caveats. Exhaustive refusal codes: [Catalog MCP → Claude](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). > [tab] ChatGPT > > **1. Turn on Developer mode** > > **Settings → Security and login → Developer mode** (needs a paid plan). *Plugins* then appears in the sidebar. > > **2. Create an MCP app** > > **Plugins → + → Create app → Create MCP app.** Paste the server URL, choose **OAuth**, and leave the client ID and secret empty — ChatGPT discovers the OAuth settings from the server. > > **3. Approve the cap at creation** > > ChatGPT runs the consent **immediately**, before any tool call. Set the **cap** and **validity**, **Grant access**, and the plugin shows as connected. > > [Connect to the Catalog from ChatGPT](https://www.youtube.com/embed/e_-bQlLdRdg) > > Connect to the Catalog from ChatGPT. > > > [!WARNING] > > > > **Choose the plugin name carefully — a ChatGPT plugin cannot be deleted or renamed.** > > Full walkthrough: [Connect the Catalog from ChatGPT](/docs/products/catalog/connect/chatgpt) — the five steps, disconnect and the caveats. Exhaustive detail and the rest of the dialog: [Catalog MCP → ChatGPT](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). > [tab] LangSmith Fleet > > Fleet doesn't discover, so you create two objects once: a LangSmith **OAuth provider** (ID exactly `nevermined`) and a **custom MCP server** pointed at the `mcp.api.` host so Fleet is challenged on connect. > > **1. Create the OAuth provider** > > **Settings → OAuth providers → New** — provider ID `nevermined`, client ID `langsmith-fleet`, a placeholder secret, the authorization and token URLs, PKCE method **S256**. The exact values are in the provider table on the Catalog MCP page. > > **2. Add the MCP server** > > **Settings → Integrations → Add custom MCP** — paste `https://mcp.api.live.nevermined.app/mcp` (or the sandbox host), choose **OAuth 2.1 (Manual)**, and select the provider from step 1. > > **3. Connect and approve the cap** > > Fleet asks *Connect now?* → the consent page opens. Set the **cap** and **validity**, **Grant access**. > > [Connect the Catalog to a LangSmith Fleet agent](https://www.youtube.com/embed/wbwrg8v0uys) > > Connect the Catalog to a LangSmith Fleet agent. > > Full provider table, the `mcp.api.` host requirement, and the cached-credential gotcha: [Catalog MCP → LangSmith Fleet](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). > [tab] Other hosts > > Any MCP host that speaks OAuth connects the same way — point it at the Catalog URL and approve one cap. These coding agents and IDEs each have a step-by-step page (walkthrough videos are still being recorded): > > * **[OpenAI Codex](/docs/products/catalog/connect/codex)** — add the server to `~/.codex/config.toml`, then `codex mcp login`. > * **[VS Code + GitHub Copilot](/docs/products/catalog/connect/vscode)** — **MCP: Add Server → HTTP**, used from Copilot agent mode. > * **[Google Antigravity](/docs/products/catalog/connect/antigravity)** — add a remote MCP server and authorize. > * **[Hermes Agent](/docs/products/catalog/connect/hermes)** — `hermes mcp add`, then `hermes mcp login`. > * **[Kilo Code](/docs/products/catalog/connect/kilo)** — **Settings → MCP → Remote (HTTP)**, or the Kilo CLI. > * **[v0](/docs/products/catalog/connect/v0)** — **+ → MCPs → add a custom server → OAuth**. > * **[Zed](/docs/products/catalog/connect/zed)** — **Settings → AI → MCP Servers → Add Remote Server**. > * **[Goose](/docs/products/catalog/connect/goose)** — `goose configure → Add Extension → Remote Extension`. > * **[Factory Droid](/docs/products/catalog/connect/factory)** — `droid mcp add`, then `/mcp` → Authenticate. > > **Prefer a plain API key to OAuth?** Some hosts take a Nevermined API key on the server's `Authorization` header instead of running the consent flow — [n8n](/docs/products/catalog/connect/n8n), [Zapier](/docs/products/catalog/connect/zapier), [Make](/docs/products/catalog/connect/make), [Gumloop](/docs/products/catalog/connect/gumloop), [Cline](/docs/products/catalog/connect/cline), [Windsurf](/docs/products/catalog/connect/windsurf), [OpenClaw](/docs/products/catalog/connect/openclaw), [Replit](/docs/products/catalog/connect/replit), [Lovable](/docs/products/catalog/connect/lovable), [Manus](/docs/products/catalog/connect/manus), [Poke](/docs/products/catalog/connect/poke), [Notion Custom Agents](/docs/products/catalog/connect/notion) and [Microsoft Copilot Studio](/docs/products/catalog/connect/copilot-studio). The budget lives on your Nevermined account, not in the host. ([Dify](/docs/products/catalog/connect/dify) and [Muse](/docs/products/catalog/connect/muse) are on the way.) > > Driving the Catalog from your own code or a coding agent instead? The concepts live on [Using the Catalog from a harness](/docs/products/catalog/from-a-harness). ### Which URL to point at | Where you point it | Server URL | | - | - | | **Sandbox** — the right place for a first run | `https://mcp.sandbox.nevermined.app/mcp` | | **Live** — real merchants, real money | `https://mcp.live.nevermined.app/mcp` | | **LangSmith Fleet** (either tier) | `https://mcp.api.sandbox.nevermined.app/mcp` · `https://mcp.api.live.nevermined.app/mcp` | Fleet needs the `mcp.api.` host so it's challenged for auth on connect; Claude and ChatGPT use the plain host and are prompted when they first try to pay. ## What the consent screen asks One screen, and it's the only place a human is required. **You set** the spending **cap** (in USDC or EURC) and how long the grant is **valid for**. The **environment** badge (Sandbox or Live) and **who is asking** are shown, not chosen. Before you grant, know that: * On **Live**, the cap is real money. * The assistant may pay **any service it can reach**, not a fixed list. * **Nevermined's routing fee comes out of the same cap** — the cap is the total debited, not what merchants receive. * The grant also lets the assistant read your payment history and wallet balance. **The cap bounds what it can spend, not what it can see.** Granting creates a budget confined to that cap and window, funded from your own wallet, and hands the assistant a credential that spends only through it — never a card mandate. Full breakdown of the consent screen: [Catalog MCP → What the consent page asks](/docs/mcp/catalog-mcp/overview#what-the-consent-page-asks). What happens once the cap is spent or the window ends: [When the grant runs out](/docs/mcp/catalog-mcp/overview#when-the-grant-runs-out). ## Revoke any time Open [Connections](https://nevermined.app/connections) in the Nevermined app and disconnect the assistant — the credential stops working on its next call. To spend again after that, or after a cap is used up, re-run the connect step and approve a **new** cap; a budget is never widened or extended in place. ## Next > [card] [Connect from Claude](/docs/products/catalog/connect/claude) > > The full claude.ai walkthrough — five steps, disconnect and the caveats. > [card] [Connect from ChatGPT](/docs/products/catalog/connect/chatgpt) > > The full ChatGPT walkthrough — five steps, disconnect and the caveats. > [card] [Catalog MCP — full click paths](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Every step for Claude, ChatGPT and Fleet, the consent details, and every refusal code. > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The code-free playbook for driving discovery and payment from your own agent or coding harness. > [card] [Catalog videos](/docs/products/catalog/videos#connect-from-your-assistant) > > The connect walkthroughs for each assistant, plus the Catalog overview and outcome examples. > [card] [Router: pay](/docs/products/catalog/router/overview) > > Delegations, the spending cap, the rails, and every refusal code. # Catalog MCP Source: https://nevermined.ai/docs/products/catalog/mcp A hosted MCP server that lets an agent in any MCP host discover and pay for Catalog services — funded by the caller's own spend-capped budget. The **Catalog MCP** (also called the Commerce MCP) is a hosted [MCP](https://modelcontextprotocol.io) server that drops the Nevermined Catalog and Router straight into the tools an AI assistant already has. Point any MCP host — Claude, ChatGPT, Cursor, a generic MCP client — at it, and your agent can **discover** paid services in the [Nevermined Catalog](/docs/products/catalog/overview) and **pay** for them through the [Router](/docs/products/catalog/router/overview), all from a budget you cap. No code, no per-vendor signup: the server holds no funds and stores no state, and every payment draws on the caller's own spend-capped Delegation. > [!NOTE] > > This is the **buyer** side, packaged as MCP tools. If you instead want to put a paywall on *your own* MCP server so its tools get paid, that's the seller side — see [MCP Integration](/docs/integrations/mcp). The [Docs MCP](/docs/mcp/docs-mcp/overview) is a third, unrelated server that streams this documentation into your IDE. A **Delegation** is a payment method plus a spend mandate: an amount, an expiry and a number of purchases. The MCP spends only inside it. ## Install | Environment | Server URL | | - | - | | **Live** | `https://mcp.live.nevermined.app/mcp` | | **Sandbox** | `https://mcp.sandbox.nevermined.app/mcp` | Discovery needs no key. Paying needs a Nevermined API key ([get one](/docs/agents-guide/get-api-key)) and a funded Delegation ([enroll a card](/docs/agents-guide/enroll-card)). For a first run, use the sandbox URL with a sandbox API key (`sandbox:...`): a key works only in the environment it was issued for. > [tab] Claude Code > > Set `NVM_API_KEY` in your shell first: the command expands it once, into the stored server config. > > ```bash theme={null} > claude mcp add --transport http nevermined-catalog https://mcp.live.nevermined.app/mcp \ > --header "Authorization: Bearer ${NVM_API_KEY}" > ``` > [tab] Codex > > ```toml theme={null} > # Add to ~/.codex/config.toml > [mcp_servers.nevermined-catalog] > url = "https://mcp.live.nevermined.app/mcp" > bearer_token_env_var = "NVM_API_KEY" > ``` > > Codex reads `NVM_API_KEY` from its environment when it starts, so restart Codex after setting it. > [tab] Cursor > > Add this entry under `"mcpServers"` in `~/.cursor/mcp.json`, next to any servers already there: > > ```json theme={null} > "nevermined-catalog": { > "url": "https://mcp.live.nevermined.app/mcp", > "type": "http", > "headers": { "Authorization": "Bearer YOUR_NEVERMINED_API_KEY" } > } > ``` > > Or merge it from the shell with `jq`, which keeps your existing servers and leaves the file untouched if it cannot parse it: > > ```bash theme={null} > mkdir -p ~/.cursor && f=~/.cursor/mcp.json && { [ -s "$f" ] || echo '{}' > "$f"; } && \ > jq --arg k "$NVM_API_KEY" '.mcpServers["nevermined-catalog"] = {url: "https://mcp.live.nevermined.app/mcp", type: "http", headers: {Authorization: ("Bearer " + $k)}}' \ > "$f" > "$f.tmp" && mv "$f.tmp" "$f" > ``` > [tab] Continue > > ```json theme={null} > // Add to ~/.continue/config.json > { > "mcpServers": [ > { > "name": "nevermined-catalog", > "url": "https://mcp.live.nevermined.app/mcp", > "transport": "http", > "requestOptions": { > "headers": { "Authorization": "Bearer YOUR_NEVERMINED_API_KEY" } > } > } > ] > } > ``` > [tab] Claude Desktop > > ```json theme={null} > // Add to ~/Library/Application Support/Claude/claude_desktop_config.json > { > "mcpServers": { > "nevermined-catalog": { > "url": "https://mcp.live.nevermined.app/mcp", > "type": "http", > "headers": { "Authorization": "Bearer YOUR_NEVERMINED_API_KEY" } > } > } > } > ``` Then restart your host to activate the connection. A **stdio-only** host can bridge with [`mcp-remote`](https://www.npmjs.com/package/mcp-remote). > [!WARNING] > > These point at **live**, where `pay_service` moves real funds. Rehearse on sandbox first: use `https://mcp.sandbox.nevermined.app/mcp` with a **sandbox** API key (`sandbox:...`), because a key works only in the environment it was issued for. Then switch to live with a small Delegation cap and the cheapest sub-cent service. **Hosts that need no API key.** Claude (claude.ai), ChatGPT, Claude Code, LangSmith Fleet, and Cursor through the Nevermined plugin in the Cursor Marketplace run OAuth for you: connect by URL and approve a spending cap once. See [Connect from your assistant](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant). The API-key setup above is for every other host, and for Claude Code or Cursor when you prefer a key. The [full guide](/docs/mcp/catalog-mcp/overview) also covers the quickstart and every tool. ## See it in action [Your AI assistant can now pay for things](https://www.youtube.com/embed/EJk5ZHmd4u0) Claude, ChatGPT and a LangSmith Fleet agent each buy real services from a \$5 budget approved once — recorded on live, with real money. One-assistant walkthroughs, each showing that product's configuration in full: [Claude](https://youtu.be/ioDqtiHtOGg) · [ChatGPT](https://youtu.be/e_-bQlLdRdg) · [LangSmith Fleet](https://youtu.be/wbwrg8v0uys). ## How it fits: discover, then pay > [card] Discover > > [`list_categories`](/docs/mcp/catalog-mcp/list-categories), [`search_services`](/docs/mcp/catalog-mcp/search-services), and [`get_service`](/docs/mcp/catalog-mcp/get-service) read the [Catalog](/docs/products/catalog/discover) — public, no key. Your agent finds a service and reads its protocol, endpoint, and price. > [card] Pay > > [`pay_service`](/docs/mcp/catalog-mcp/pay-service) hands the call to the [Router](/docs/products/catalog/router/overview), which reads the merchant's `402`, pays it from your Delegation, enforces the cap, and relays the vendor's response. [`route_by_intent`](/docs/mcp/catalog-mcp/route-by-intent) does both steps in one call. Your agent never holds a private key, never learns a payment protocol, and never needs an account with the service it just paid. The Router, not the agent, speaks each rail — see [How the Router works](/docs/products/catalog/router/how-it-works). ## Get started > [card] [Import & authenticate](/docs/mcp/catalog-mcp/overview#import-the-mcp) > > Instant setup for Claude Code, Codex, Cursor, Continue and Claude Desktop, plus the OAuth path for hosts that approve a spending cap once. > [card] [Connect from your assistant](/docs/mcp/catalog-mcp/overview#connect-from-your-assistant) > > Claude, ChatGPT and LangSmith Fleet, step by step — approve a spending cap once, no API key. > [card] [Quickstart (API key)](/docs/mcp/catalog-mcp/overview#quickstart) > > Connect a host, run a discovery call, then a paid call — end to end. > [card] [Every tool, documented](/docs/mcp/catalog-mcp/overview#the-tool-surface) > > A reference page per tool — arguments, returns, refusals, and a `curl` to test it. ## Not this MCP Nevermined ships three MCP servers. Make sure you want this one: | MCP | Side | What it's for | | - | - | - | | **Catalog MCP** (this page) | Buyer | Your agent discovers & pays for Catalog services. You provide just an API key and a funded budget. | | [MCP Integration](/docs/integrations/mcp) | Seller | Put a paywall on *your own* MCP server with the Payments Library (`withPaywall`), so your tools get paid. | | [Docs MCP](/docs/mcp/docs-mcp/overview) | — | Streams the Nevermined **documentation** into your IDE so an assistant can vibe-code an integration. It sells nothing. | ## Next > [card] [Catalog MCP Overview (full guide)](/docs/mcp/catalog-mcp/overview) > > Import, auth, quickstart, and the complete tool reference. > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The code-free playbook for driving discovery and payment from your agent. > [card] [Router: pay](/docs/products/catalog/router/overview) > > Delegations, the spending cap, the rails, and every refusal code. > [card] [Payment ledger](/docs/products/catalog/router/ledger) > > Read back everything your agents have spent, across every protocol. # Catalog Overview Source: https://nevermined.ai/docs/products/catalog/overview A curated directory of external AI services your agents can discover and pay for — through one budget, over the Nevermined Router. ![Diagram: your agent browses the Catalog to pick a service, then the Nevermined Router pays each service — x402 or MPP — on the agent's behalf, all from one shared budget.](https://mintcdn.com/neverminedag/LpsfNX4zdB31S76z/images/catalog/routing-diagram.png?fit=max\&auto=format\&n=LpsfNX4zdB31S76z\&q=85\&s=dee240e4a0d6e167c03dfbf21528f658) The **Nevermined Catalog** is a curated directory of external AI services your agents can pay for — browsable by a human at [nevermined.app/catalog](https://nevermined.app/catalog/), and readable by an agent through a public feed. Every listed service prices each request on the wire, so your agent can **find** a capability it needs and **pay** for it in the same motion, without a signup, an API key, or a subscription at the provider. The Catalog is the front door; the **[Router](/docs/products/catalog/router/overview)** is how you walk through it. You discover a service in the Catalog, then pay it through the Router from a budget you control. The two are one product read in one direction: **spending** at services that were never onboarded to Nevermined. > [!NOTE] > > The Catalog lists services you **buy from**. If instead you want your own API to *get paid* by callers, that's the seller side — see the **[Payments Facilitator](/docs/products/payments-facilitator/overview)**. You can be on both sides at once, and you can even **[add your own AI service](/docs/products/catalog/publish-ai-service)** to the Catalog so other buyers discover it. ## See it in action Watch the Catalog walkthrough — discovering a service and paying for it in one motion, with no account per provider: [Nevermined Catalog walkthrough](https://www.youtube.com/embed/0QFSy7E0cio) A walkthrough of the Nevermined Catalog. ## What's in it Every listing is an external service that charges **per request**, on one of two payment rails the Router can settle: | Protocol | What it is | Router-payable | | - | - | - | | **x402** | The service answers `HTTP 402` advertising an `accepts` array | ✅ Listed | | **MPP** | The service answers `HTTP 402` with a `WWW-Authenticate: Payment` challenge | ✅ Listed | Services that authenticate with a long-lived API key and bill you monthly aren't in the listed set — there's no per-call price on the wire for the Router to pay. The Catalog only surfaces what an autonomous agent can actually buy. Listings are organized into a curated set of categories — **Data & Enrichment**, **Search & Research**, **Crypto & Blockchain**, **Finance & Markets**, **AI & Media**, **Web Scraping & Automation**, and more — each with granular sub-categories. See [AI Services](/docs/products/catalog/ai-services) for the full offering and how to add your own, or [Discovering AI Services](/docs/products/catalog/discover) for browsing and filtering. ## How the Catalog and Router fit together One agent, one budget, one API key — reaching many independent services it never had to sign up for. Those services are unrelated to each other and to Nevermined: different providers, different payment rails, no shared account. Your agent treats them uniformly because the Router, not the agent, speaks each rail. > [card] [The Catalog: discover](/docs/products/catalog/discover) > > Browse or query the directory to find a service that does what your agent needs, and read its price, protocol, and endpoints. > [card] [The Router: pay](/docs/products/catalog/router/overview) > > Hand the Router the call you want made. It reads the merchant's payment challenge, pays from your wallet, enforces your budget cap, and relays the answer. Your agent authenticates with its Nevermined API key and spends against a **Delegation** — a budget with a hard cap and an expiry. It never holds a private key, never learns a payment protocol, and never needs an account with the service it just paid. ## What you need to buy through it **1. A Nevermined API key** Created from the [Nevermined app](https://nevermined.app). It authenticates you to Nevermined — never send it to a merchant. It must be a current-generation key; see [the Router quickstart](/docs/products/catalog/router/quickstart#1-get-an-api-key). **2. A Delegation** Your budget: a hard cap in cents and an expiry. Created once, reused for every payment until it's exhausted or expires. **3. A funded wallet** Both rails **pull** from your own wallet, so it must already hold the payment asset on the network you're paying on. Discovery itself needs none of this — the Catalog feed is public and unauthenticated. You only need a key, a Delegation, and funds at the moment you pay. ## Three ways to use it > [card] [Natural language](/docs/development-guide/build-using-nvm-skill) > > Install the AI coding skill and just ask your assistant — "find a weather API and get me tomorrow's forecast for Berlin." It discovers, funds, pays, and returns the answer. > [card] [MCP](/docs/products/catalog/mcp) > > Wire the Catalog MCP into any MCP-capable host so the Catalog and Router become tools your agent can call directly. > [card] [Plain HTTP](/docs/products/catalog/router/quickstart) > > Everything is public REST. Any agent, in any language, can query the Catalog and route a paid call with `curl` or `fetch`. > [!NOTE] > > Driving the Catalog from an agent harness — Claude Code, Cursor, an MCP client, or your own runtime? Start with **[Using the Catalog from a harness](/docs/products/catalog/from-a-harness)**: a concise, code-free playbook of the flow, the safety principles, and every link. It's written to be handed to your agent as-is. ## Environment The Catalog is **Live-only for payment**. Discovery is public and works against either host, but every listed service settles on **mainnet** (Base and Tempo), so payment goes through the live host: | Environment | API base | Purpose | | - | - | - | | **Live** | `https://api.live.nevermined.app` | Discovery and real payments | > [!WARNING] > > Both rails settle **real value on public networks** — a Catalog call moves real funds to a real merchant. The sandbox Router funds testnets only, so no listed service is payable there (paying one fails with `400 BCK.ROUTER.0001`). Rehearse with the cheapest sub-cent service and keep your first Delegation cap small. ## Next > [card] [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) > > The code-free operator's playbook — the flow, the safety principles, and every link. Hand it to your agent. > [card] [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant) > > Connect the Catalog to Claude.ai, ChatGPT, or LangSmith Fleet — paste one URL, approve one cap, no code. > [card] [Build Outcomes](/docs/products/catalog/build-outcomes) > > Describe the problem and a budget; the Catalog proposes the AI services to chain. Copy-paste prompts included. > [card] [Discovering AI Services](/docs/products/catalog/discover) > > Browse the app, read the feed, and understand what "listed" means. > [card] [Catalog videos](/docs/products/catalog/videos) > > Watch the overview, outcome examples, and the connect-from-your-assistant walkthroughs. > [card] [Router quickstart](/docs/products/catalog/router/quickstart) > > From an API key to a paid call, in five steps. > [card] [How the Router works](/docs/products/catalog/router/how-it-works) > > The payment flow, the two call modes, and where custody sits. > [card] [Guardrails](/docs/products/catalog/router/guardrails) > > What the Router enforces, what it refuses, and every error code it can return. # Getting Your Results Source: https://nevermined.ai/docs/products/catalog/paid-results Some Catalog services work in two steps: you pay to start the job, then come back for the result. Coming back is free, and only you can do it. Most Catalog services answer the paid call with what you bought. Some can't: generating an image or a video, running a long scrape or placing a phone call takes longer than one request. Those services work in **two steps**: 1. **You pay to start the job.** The service answers with a job id. 2. **You come back for the result** with that id. This step is **free**, and only you can do it, because the result belongs to whoever paid. The Router handles the second step for you. You don't sign anything or manage keys: you call the result endpoint like any other, and the Router proves to the service that you're the one who paid. ## Example StableStudio generates images this way. Pay to start the job, then check on it with the id you got back. > [tab] Catalog MCP > > Start the job with [`pay_service`](/docs/mcp/catalog-mcp/pay-service): > > ```json theme={null} > { > "slug": "merit-systems-mpp-2", > "path": "/api/generate/nano-banana/generate", > "body": { "prompt": "A lighthouse at dusk, watercolor" } > } > ``` > > Then check on it, with the job id in the path. Set `fresh: true` every time you check, so each check is a new request: > > ```json theme={null} > { > "slug": "merit-systems-mpp-2", > "path": "/api/jobs/3f6c2a9e-7b41-4d0e-9a52-c18e5f07d6b3", > "method": "GET", > "fresh": true > } > ``` > [tab] REST > > Start the job with `POST /api/v1/router/route`: > > ```json theme={null} > { > "delegationId": "5e7481c3-e972-45bd-bdc5-a0b99c4de4a1", > "slug": "merit-systems-mpp-2", > "path": "/api/generate/nano-banana/generate", > "method": "POST", > "body": { "prompt": "A lighthouse at dusk, watercolor" }, > "requestId": "lighthouse-image-v1" > } > ``` > > Then check on it, with the job id in the path and a new `requestId` each time: > > ```json theme={null} > { > "delegationId": "5e7481c3-e972-45bd-bdc5-a0b99c4de4a1", > "slug": "merit-systems-mpp-2", > "path": "/api/jobs/3f6c2a9e-7b41-4d0e-9a52-c18e5f07d6b3", > "method": "GET", > "requestId": "lighthouse-image-v1-check-1" > } > ``` The check comes back with `paid: false`, meaning nothing was charged: ```json theme={null} { "status": 200, "body": { "status": "complete", "…": "your image, exactly as the service returned it" }, "paid": false } ``` Keep checking until the job is done. The endpoint's description in the Catalog tells you what to look for, such as `status` becoming `complete`. ## How to spot these services In the Catalog, the result endpoint is marked **`auth: "siwx"`**, and its path has a placeholder for the id: ```json theme={null} { "method": "GET", "path": "/api/jobs/{jobId}", "auth": "siwx" } ``` You see it in the service's endpoints in the [Catalog feed](/docs/products/catalog/discover#read-the-feed) and in [`get_service`](/docs/mcp/catalog-mcp/get-service). Any endpoint with `auth: "siwx"` is free, and only works after you've paid that same service. ## Three things to get right * **Use the same service.** Check through the same `slug` you paid. * **Fill in the id.** Replace `{jobId}` (or `:id`) with the id the paid call returned. A path that still has the placeholder is refused. * **Pay from your own wallet.** Only the wallet that paid can read the result. If the paid call would be funded by an organization wallet or a card, it's refused **before you're charged**, because nobody could collect the result. Use a crypto Delegation on your own wallet. * **Subscription credits don't pay these services**, except a few reviewed endpoints whose paid response is already the whole result (no job to check back on, nothing you then own at the merchant). Everywhere else credits are refused with `403 BCK.SUBSCRIPTION_ROUTER.0001` with `params.reason: "wallet_bound"`, and the catalog shows the price as *own crypto wallet only*. Check back in time, too: the free check works for **1 hour** after the paid call on Nevermined's production deployments (the window is set per deployment), as long as that payment has settled by the time you check. After that hour, the check is refused. ## If it doesn't work The same code can have several causes, so read the error's `details` to tell them apart. | Error | `details` says | What it means | What to do | | - | - | - | - | | `400 BCK.ROUTER.0001` | `fill the path parameters: {jobId} is a template placeholder, not a value` | The path still has `{jobId}` or `:id` in it. | Put the real id in the path. | | `400 BCK.ROUTER.0001` | `this service delivers its results only to the personal wallet that paid; …` | You tried to pay with an organization wallet or a card. Nothing was charged. | Pay from a Delegation on your own wallet. | | `400 BCK.ROUTER.0001` | `… only through wallet-authenticated follow-ups, which are disabled on this deployment` | The deployment you're calling has result checks turned off, so it won't sell the job. Nothing was charged. | Use a deployment with them on, or ask its operator. | | `422 BCK.ROUTER.0035` | — | The Router couldn't prove you paid: there's no settled payment from your wallet for this service, or it was more than the window ago. Nothing was charged. | Pay to start the job first, then check through the same slug. | ## Under the hood The service asks for proof in its own protocol, and the Router answers with your wallet's signature: an [MPP zero-amount proof](/docs/products/catalog/router/rails-mpp#zero-amount-charges-proving-you-paid) or an [x402 Sign-In-With-X](/docs/products/catalog/router/rails-x402#sign-in-with-x-siwx). Neither one can move money. The [guardrails](/docs/products/catalog/router/guardrails#who-can-read-results) list every check the Router makes before it signs. ## Next > [card] [Discover services](/docs/products/catalog/discover) > > Find a service and read its endpoints. > [card] [How the Router works](/docs/products/catalog/router/how-it-works) > > The paid call, end to end. # Publish to the Catalog Source: https://nevermined.ai/docs/products/catalog/publish-ai-service Two ways to list your AI service in the Nevermined Catalog — self-serve from a paid organization, or email review. Listing is gated on a health probe. The Catalog is where you list a service **you** own so other buyers' agents discover and pay for it on the wire. There are two ways to get listed: a self-serve flow you drive from the app, and an email review for cases that don't fit it. > [!NOTE] > > When you publish it yourself, **listing is gated on an automated health probe** — Nevermined never lists a self-served service on your word alone. A monitor calls your endpoint and only lists it once it responds healthy, and it keeps checking **every** listing afterwards, so the Catalog stays a directory of services that currently work. See the health lifecycle in [AI Services](/docs/products/catalog/ai-services). > [!WARNING] > > Publishing is a **Live**-environment flow. The Catalog has no sandbox deployment, and a subscription applies to one environment only — a Starter bought on sandbox can't publish. Subscribe and publish on **Live**. > [card] Option A — Self-serve > > **Recommended.** Subscribe a paid org (**Starter is enough for one service**), create an organization agent, and send it to the Catalog. Published automatically once it's healthy. > [card] Option B — Email review > > Email [info@nevermined.io](mailto:info@nevermined.io). The team reviews submissions periodically — slower than self-serve, and **not guaranteed**. ## Option A — Self-serve (recommended) The fastest path, entirely in your hands. It requires a **paid organization tier** — the cheapest one that unlocks catalog publishing is **Starter**, which lists **one** service (Premium lists up to 3, Enterprise up to 10; see [Plans & Billing](/docs/solutions/organizations/plans-and-billing)). **1. Subscribe an organization** Any paid tier can publish, so **Starter is enough** for a single service. Subscribe or upgrade from the [Billing](/docs/solutions/organizations/plans-and-billing) tab of your organization dashboard — on the **Live** environment, since the Catalog has no sandbox deployment. **2. Register an organization agent** Create the agent you want to list **with your organization workspace active** — see [Register a plan and agent](/docs/agents-guide/register-plan-and-agent) and [Workspaces & Members](/docs/solutions/organizations/workspaces-and-members). A personal agent can't be published; it must belong to the organization. It must expose a callable endpoint that prices each request **on the wire** (x402 or MPP): that's what the Router pays and what the health probe checks. **3. Send it to the Catalog** From **`/organization/agents`** in the [Nevermined app](https://nevermined.app) — with the app switched to **Live** — open the agent and publish it from its **Catalog** tab: choose a category and add presentation details (title, description, logo, tags, features). You supply only presentation and the endpoint. The payment **protocol** and **price** are detected from your endpoint and ownership is taken from the agent, so a listing can't misrepresent what it charges or who runs it. **4. Nevermined validates and publishes** A monitor probes the endpoint. Once it responds healthy, the listing goes **Live** automatically — there's no manual approval step. If it never responds healthy within 24h it stays unlisted (**Action needed**). Track the state on the same page; the full health lifecycle (Validating / Live / Action needed / Degraded / Removed) is in [AI Services](/docs/products/catalog/ai-services). ## Option B — Email review If self-serve doesn't fit — you're not ready to run a paid organization, or your case needs a human look — email [info@nevermined.io](mailto:info@nevermined.io) with your service and its endpoint. The team reviews submissions **from time to time** and publishes some, but this path is **not guaranteed** and is slower than self-serve. Once a service is listed, the same monitor keeps checking it and unlists it if it stops responding. ## Related > [card] [AI Services](/docs/products/catalog/ai-services) > > What's in the Catalog, what gets listed, and the full health-status lifecycle. > [card] [Plans & Billing](/docs/solutions/organizations/plans-and-billing) > > The paid tiers — Starter is the cheapest that unlocks catalog publishing. > [card] [Register a plan and agent](/docs/agents-guide/register-plan-and-agent) > > Create the organization agent you'll send to the Catalog. > [card] [Discovering AI Services](/docs/products/catalog/discover) > > How buyers browse and query the public Catalog you're listing into. # An agent buying on its own Source: https://nevermined.ai/docs/products/catalog/router/agent-autonomy A worked end-to-end run: an agent given only an API key and a budget discovers services, buys across two payment protocols on two chains, and is then refused by its own spend cap. Every page before this one describes a piece of the Router. This one runs the whole thing, start to finish, and shows the actual output — so you can see what an autonomous agent's spending really looks like before you give one a budget. The question it answers: > Can you hand an agent an API key and a cap, and have it find services, pay for them, and be **stopped** — with no per-provider accounts, no protocol knowledge, and no keys of its own? The run below is real. Every number, hash and error on this page came from one execution against live merchants on Base mainnet and Tempo mainnet. Total cost: **\$0.08**. > [!NOTE] > > **The refusal is the interesting part.** Anyone can demo a purchase. What makes an agent safe to leave running is a spend control that says no — and keeps saying no — without you being there. That's step 6, and it's the reason this page exists. ## What the agent is given Two things. That's the whole grant: | | | | - | - | | **An API key** | Authenticates it to Nevermined. Never sent to any merchant. Must be for a **live** deployment — see below. | | **A Delegation** | A hard cap in cents, plus an expiry. Here: **9¢**, valid one hour. | It is **not** given: a wallet, a private key, a merchant account, an API key for any service it buys from, or any knowledge of which payment protocol a service speaks. > [!WARNING] > > **This run requires a live deployment.** Every service below settles on mainnet — Base `8453` and Tempo `4217` — and a sandbox deployment funds testnets only. That split is the real-money firewall and an operator cannot widen it, so pointing `$NVM_API_URL` at `api.sandbox.nevermined.app` makes step 3 fail with **`400 BCK.ROUTER.0001`**: no `accepts` entry survives the network filter. > > Watch for that code specifically. It is *not* the refusal in step 6 — that one is a `402 BCK.ROUTER.0003` and means the guardrail worked. A `400` here means the wrong deployment. See [the x402 rail](/docs/products/catalog/router/rails-x402) for the firewall itself. ## 1. Discover The catalog is public. No key, no account, no signup — one JSON feed of every listed service, filtered locally: ```bash theme={null} curl -s https://nevermined.app/catalog/ai-catalog.json \ | jq -r '.services[] | select((.title + " " + .description) | ascii_downcase | contains("crypto")) | "\(.title) [\(.protocol)] \(.priceLabel)"' ``` ``` Alpha Vantage [mpp] $0.008 CoinGecko via MPP [mpp] $0.06 Otto AI x402 [x402] From $0.001/call (USDC) AgentOracle [x402] $0.01 … ``` Every service lists its protocol, network and price up front. Each entry carries everything needed to place a call — the `slug`, each endpoint's `path` and `method`, and a `priceLabel`: ```bash theme={null} curl -s https://nevermined.app/catalog/ai-catalog.json \ | jq '.services[] | select(.slug == "coingecko-via-mpp") | {slug, title, protocol, network, priceLabel, endpoints: [.endpoints[0] | {path: (.invokePath // .path), method, priceLabel}]}' ``` ```json theme={null} { "slug": "coingecko-via-mpp", "title": "CoinGecko via MPP", "protocol": "mpp", "network": "Tempo", "priceLabel": "$0.06", "endpoints": [ { "path": "/coingecko/simple-price", "method": "POST", "priceLabel": "$0.06" } ] } ``` > [!NOTE] > > The feed is the whole catalog in one document — there are no query parameters, so filter it on your side. `/api/v1/catalog/services` isn't a public integration and returns `403`; for server-side search, use the Catalog MCP's `search_services` (see [Discovering AI Services](/docs/products/catalog/discover#search-server-side-with-the-catalog-mcp)). The agent picked two services with deliberately different plumbing: | Service | Protocol | Chain | Price | | - | - | - | - | | CoinGecko via MPP | `mpp` | Tempo mainnet (4217) | \$0.06 | | AgentOracle | `x402` | Base mainnet (8453) | \$0.01 | ## 2. Set the budget The cap is chosen so the **third** purchase cannot fit: ``` cap = 6¢ (CoinGecko) + 1¢ (AgentOracle) + 2¢ slack = 9¢ ``` ```bash theme={null} curl -sX POST "$NVM_API_URL/api/v1/delegation/create" \ -H "Authorization: Bearer $NVM_API_KEY" \ -H "Content-Type: application/json" \ -d '{"provider":"erc4337","currency":"usdc","spendingLimitCents":9,"durationSecs":3600}' ``` The 2¢ of slack matters. A merchant's real charge can exceed its advertised price, because the Router converts the on-wire amount to cents and **rounds up**: CoinGecko's \$0.06 arrives as 60001 atomic units and costs **7¢**, not 6¢. The slack absorbs that while staying far below the \~7¢ a third call needs — so the refusal in step 6 is arithmetic, not luck. ## 3. Buy over MPP The agent sends a URL and a delegation id. Nothing else: ```bash theme={null} curl -sX POST "$NVM_API_URL/api/v1/router/route" \ -H "Authorization: Bearer $NVM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "delegationId": "'"$NVM_DELEGATION_ID"'", "url": "https://coingecko.mpp.paywithlocus.com/coingecko/simple-price", "method": "POST", "body": { "ids": "bitcoin", "vs_currencies": "usd" }, "requestId": "demo-mpp-1" }' ``` ```json theme={null} { "status": 200, "paid": true, "body": { "success": true, "data": { "bitcoin": { "usd": 64794 } } }, "payment": { "status": "Settled", "txHash": "0xd25f25cc162f347e2e0374841a1270b61f7dff53d5c6af0fbcacdab2caaf5bb8", "settlement": { "scheme": "charge", "network": "tempo", "asset": "0x20c000000000000000000000b9537d11c60e8b50", "approxCents": "7" } } } ``` One call in, the data and a settled on-chain payment out. Budget left: **2¢ of 9¢**. ## 4. Buy over x402 Now the same call shape against a service on a **different protocol and a different chain**: ```bash theme={null} curl -sX POST "$NVM_API_URL/api/v1/router/route" \ -H "Authorization: Bearer $NVM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "delegationId": "'"$NVM_DELEGATION_ID"'", "url": "https://aiagentoracle.ai/api/v1/tokens", "method": "GET", "requestId": "demo-x402-1" }' ``` ```json theme={null} { "status": 200, "paid": true, "body": { "tokens": [ { "symbol": "BTC", "priceUsd": 64798 } ] }, "payment": { "status": "Settled", "txHash": "0x44136dc5348e5442770ad1ebeb9cb4e641225f8d4abdcf9e4b2f82f33a054214", "settlement": { "scheme": "exact", "network": "eip155:8453", "asset": "USDC", "approxCents": "1" } } } ``` **This is the part worth pausing on.** Steps 3 and 4 are the same request, to the same endpoint, differing only in the URL. The agent never named a protocol. The Router fetched each merchant, read `WWW-Authenticate: Payment` on one and `PAYMENT-REQUIRED` on the other, and chose the rail itself — signing an EIP-3009 authorization on Base for one and a native Tempo charge for the other. The agent does not know, and does not need to know, which chain it just paid on. > [!WARNING] > > Because the Router picks the protocol in this mode, a merchant advertising **both** rails is tried over MPP first. It's paid over x402 only when the Router refuses the MPP challenge's terms — a method, chain or asset it doesn't pay, for example. A personal Delegation like this one can't sign an MPP `evm` charge, so a merchant whose only MPP offer is `evm` is paid over its x402 offer. An underfunded wallet never moves the call to x402. Either rail can turn a run green, so a green run may be exercising the other rail entirely. > > If you're specifically verifying x402 behaviour, set `requireProtocol: "x402"` on the call. The Router then pays only x402 and never falls back; a merchant that doesn't offer it is refused with `409 BCK.ROUTER.0045` before anything is signed or charged. See [How it works](/docs/products/catalog/router/how-it-works). ## 5. Report One ledger, regardless of protocol or chain: ```bash theme={null} curl -s "$NVM_API_URL/api/v1/router/payments?delegationId=$NVM_DELEGATION_ID" \ -H "Authorization: Bearer $NVM_API_KEY" ``` | Protocol | Network | Asset | Amount | Status | Tx | | - | - | - | - | - | - | | `x402` | `eip155:8453` | `USDC` | 10000 | Settled | `0x44136dc5…` | | `mpp` | `tempo` | `0x20c0…8b50` | 60001 | Settled | `0xd25f25cc…` | Both reconcile exactly against the chains: Base **−0.010000 USDC**, Tempo **−0.060029 USDC.e** (the 0.060001 payment plus 28 units of gas, which Tempo bills in the stablecoin itself). > [!NOTE] > > On the MPP rail, `network` comes back as a name rather than a chain id, and for the two crypto MPP methods the method decides both it and `asset`: > > * **A Tempo charge** (the row above): `network` is `tempo` for mainnet (`4217`) or `tempo-moderato` for the Moderato testnet (`42431`), and `asset` is the token's **contract address**. The token addresses differ per chain and are easy to misread — see [the MPP rail](/docs/products/catalog/router/rails-mpp#the-asset-allowlist). > * **An MPP `evm` charge** settles on Base like x402, with an EIP-3009 authorization. You'll see one when [Catalog credits](/docs/products/catalog/router/subscription#what-credits-can-pay) pay, for example; a personal Delegation like this one can't sign one ([why](/docs/products/catalog/router/rails-mpp#evm-charges-on-base)). Its `network` is always the name `base` (or `base-sepolia`) and its `asset` is a symbol such as `USDC`. An x402 row keeps the merchant's own spelling of the chain instead: `eip155:8453` above, or `base`. > > So a `base` row is not necessarily x402. Read `protocol` for the rail and `network` for the chain. Add `&format=csv` for a downloadable file. This is the same record whether you spent over one protocol or five. ## 6. Refused The agent tries the CoinGecko call once more. It has **1¢** left; the call costs **7¢**: ```json theme={null} { "code": "BCK.ROUTER.0003", "message": "Delegation budget exceeded, expired, or inactive" } ``` `402`. No payment minted, no credential issued, nothing to unwind — the ledger still holds exactly two payments. The cap is enforced server-side inside the same transaction that records the spend, so an agent cannot get past it by retrying, looping, or being confidently wrong about its own remaining budget. That is the property that makes an autonomous agent something you can leave running: **the ceiling is not enforced by the agent's good behaviour.** > [!NOTE] > > `0003` covers exhausted, expired **and** revoked. Read `remainingBudgetCents` and `expiresAt` from `GET /api/v1/delegation/{id}` to tell them apart — a long-running agent that worked yesterday has very often just aged out rather than overspent. See [Guardrails](/docs/products/catalog/router/guardrails). ## What this demonstrates * **Discovery needs no account.** The catalog is public and machine-readable, and carries enough to place a call. * **One integration, many protocols.** The agent wrote no protocol-specific code. Adding a rail is the Router's problem, not the agent's. * **The agent holds nothing.** No wallet, no private key, no merchant credentials. Funds sit in a wallet it cannot reach except through a capped Delegation. * **Spending is bounded by construction.** The cap is checked server-side on every payment, and refusing costs nothing. * **Everything is auditable.** One ledger across every rail, with on-chain hashes that reconcile. ## Reproducing it **The six `curl` calls above are the whole run.** There is nothing else to install — a live API key, a Delegation, a funded wallet, and the requests on this page reproduce it end to end in any shell or language. > [!WARNING] > > **This spends real money.** There is no testnet variant, and that is structural rather than an oversight: the catalog lists mainnet merchants, so a testnet run would have nothing real to discover. Sanity-check the price on each catalog entry before you buy — a legitimate service can charge over a dollar a call — and keep the Delegation cap tight enough that a mistake is refused rather than paid. Before a first run, check the things that most often turn into a "Router bug" that was nothing of the sort: * **Read the wallet address back from the live Delegation** (`providerPaymentMethodId`), never from anything you wrote down — funding a stale address fails as `402 BCK.ROUTER.0009`. On MPP-tempo that error names the wallet and chain it checked, so compare the two; it never echoes the balance, and x402 raises no `0009` at all. * **Fund it on both chains** you intend to pay on. Base and Tempo are separate balances. * **Confirm the merchant still answers `402`** on the rail you expect. A service that stops charging is relayed with `paid: false`, and a run can otherwise "succeed" having bought nothing. * **Check the catalog is loaded**, not serving placeholder rows — compare the feed's `total` and look at the `endpoints`. If you'd rather have *your* agent do the run than drive it yourself, give it the public **`nevermined-router` skill** — the same six steps plus the guardrails, written for an assistant to act on: ```bash theme={null} /plugin marketplace add nevermined-io/docs # Claude Code /plugin install nevermined-router@nevermined ``` Other tools are covered in [AI Coding Skill](/docs/development-guide/build-using-nvm-skill). The skill teaches the loop; it does not lift the cap, and an agent following it will stop on a refusal exactly as described above. > [!NOTE] > > **Nevermined staff:** a scripted version of exactly this run — the six steps plus a preflight covering every point above — lives in the internal `nvm-monorepo` repository at `.claude/skills/nvm-router-demo/`. It adds `--dry-run` (spends nothing) and `--selfcheck` (offline). It is not public, and nothing on this page depends on it. ## Next > [card] [Guardrails](/docs/products/catalog/router/guardrails) > > Every check the Router makes before it signs, and every error code it can return. > [card] [Ledger](/docs/products/catalog/router/ledger) > > The unified payment record, its fields, and CSV export. # Router buyer identity Source: https://nevermined.ai/docs/products/catalog/router/buyer-identity Verify optional Router-signed buyer attribution, request bindings and replay protection with the version 1 seller contract. > [!WARNING] > > Availability depends on the API deployment and operator signing configuration. Check its public > seller-contract endpoint: it must answer and report a configured issuer. A 404 means the API does > not support this interface. An absent issuer means signing is disabled; earlier validation refusals > can mask missing configuration, so an individual call's error is not an availability check. Buyer identity is optional attribution carried in a signed JSON Web Token (JWT). It is not payment authority, verified agent registration, or verified person/company identity (know your customer, KYC). No claim binds this token to a payment: its presence shows neither that this request paid nor that a payment settled. Verify payment independently. Read the configured issuer from the seller-contract endpoint for the deployment you use. Pin the issuer and public-key endpoint out of band, never through a token. The seller-contract endpoint reporting a configured issuer is the reliable availability check; an earlier validation refusal can mask missing configuration. A missing endpoint (404) means this API lacks the interface. | Environment | API base | Public keys | Seller contract and configured issuer | | - | - | - | - | | live | [https://api.live.nevermined.app](https://api.live.nevermined.app) | [https://api.live.nevermined.app/api/v1/router/buyer-identity/jwks](https://api.live.nevermined.app/api/v1/router/buyer-identity/jwks) | [https://api.live.nevermined.app/api/v1/router/buyer-identity](https://api.live.nevermined.app/api/v1/router/buyer-identity) | | sandbox | [https://api.sandbox.nevermined.app](https://api.sandbox.nevermined.app) | [https://api.sandbox.nevermined.app/api/v1/router/buyer-identity/jwks](https://api.sandbox.nevermined.app/api/v1/router/buyer-identity/jwks) | [https://api.sandbox.nevermined.app/api/v1/router/buyer-identity](https://api.sandbox.nevermined.app/api/v1/router/buyer-identity) | ## Consent and supported calls A seller sets the JSON boolean receiveBuyerIdentity=true when publishing/editing its listing, including a claimed listing. The listing must have an HTTPS target. listingId below is the id in the publish/listing response, not the slug. Only literal true opts in; false or null stores false. On edit, omitting receiveBuyerIdentity preserves the setting; sending null turns an existing opt-in off. The delegation owner separately sets the JSON boolean revealBuyerIdentity=true on each direct slug /route call (or its /route/with-controls alias), or the exact string true in X-Router-Reveal-Buyer-Identity on a streaming slug call. This discloses the stable delegationId (the same identifier across sellers), plus orgId and buyer-declared agentId when present. On those supported delegation routes, false, null or omitted revealBuyerIdentity means no disclosure and no identity-owner lookup. Other JSON non-booleans fail validation with HTTP 400; malformed streaming header values fail BCK.ROUTER.0001. Runtime disclosure requires a plain API key, a caller-owned delegation, an HTTPS slug target and seller opt-in. OAuth credentials are refused by the guard on /route, /route/with-controls, /proxy and /svc with 403 BCK.OAUTH.0030, regardless of consent; disclosure consent on commerce routes is refused with BCK.ROUTER.0001. Other unsupported disclosure conditions use BCK.ROUTER.0001; ownership failure uses BCK.DELEGATION.0002. OAuth credentials, group members acting for another delegation owner, raw URL calls and subscription funding cannot disclose through this interface. Subscription route bodies/headers refuse ANY identity field, including false or null, with BCK.SUBSCRIPTION\_ROUTER.0005. Select/autoPay requests refuse the identity field whenever present, even false or null, with BCK.ROUTER.0001 once past authentication guards; select first, then call the direct slug route. Format validation can reject before request-id deduplication. For well-formed disclosure requests, retained replay and request-id deduplication precede configuration/owner checks, and those checks precede all merchant requests and free-quota consumption. Explicit consent performs that owner lookup even if the merchant later answers free. Probes and free responses never carry identity. An unavailable identity capability is the internal configuration error BCK.ROUTER.0022 (500), with capability=buyer-identity; retry only after the operator restores it, or deliberately omit consent if attribution is not needed. Existing service-selection wiring uses the same error class. ## Verification checklist The Router sends a bare compact JWT, with no Bearer prefix, in X-Router-Buyer-Identity on the paid request only. Read that header at the seller; X-Router-Reveal-Buyer-Identity is the separate buyer consent header sent to the Router and does not carry the token. The public keys form a JSON Web Key Set (JWKS); each entry is a public JSON Web Key (JWK). Request bindings use Demonstrating Proof of Possession (DPoP)-style fields, but this JWT is a distinct contract: a generic DPoP verifier alone is insufficient. 1. Require the protected JWT header alg=EdDSA and typ=nvm-buyer-identity+jwt, with a string kid. Select that Ed25519 public JWK from your PINNED JWKS URL by kid (a SHA-256 RFC 7638 thumbprint). Ignore token-supplied key URLs. Cache keys for at most 30 seconds; refetch once on unknown kid. 2. Verify the signature. Require payload claim ver to be the integer 1, and iss to equal the issuer you pinned out of band. Reject unsupported versions and missing required claims as attribution. 3. Reconstruct the external URL using the WHATWG URL Standard (for example JavaScript new URL). Require aud to equal its serialized origin: lowercase host, no default HTTPS :443 port, but retain a non-default port such as :8443. Require htm to equal the uppercase received method. 4. Require listingId to identify a listing YOU own that serves this external URL. Do not accept a different listing merely because it shares your origin and path. 5. Require htu to equal that URL's serialized origin + pathname (no query or fragment). Require querySha256 to hash its WHATWG search value, including the leading ? when nonempty. A bare trailing ? has an EMPTY search value and hashes empty bytes. Preserve serialized query order and percent encoding; do not parse/rebuild it with a query-parameter map. 6. Require bodySha256 to equal the base64url SHA-256 of received raw body bytes before JSON parsing, or empty bytes when absent. Compare against the external URL before gateway rewrites. 7. Verify exp/iat time validity with at most 5 seconds clock leeway, rejecting future iat beyond that leeway and a lifetime above 60 seconds. Tokens are issued at the paid hop, not at consent. 8. Enforce one-use (iss, jti) in a shared replay store across your replicas until exp + leeway. Replays, absent headers, unknown keys, JWKS outages and replay-store outages produce NO attribution. Fail closed for attribution; never infer or reuse claims you cannot verify. A failed identity check discards attribution, not a successfully verified payment. Whether to serve the request is decided by payment verification alone under this optional contract. If you deliberately require identity, document that separate requirement before purchase; this contract does not require sellers to deny an already-paid request for optional attribution failures. Never log the JWT/header. | Payload claim | Meaning and validation | | - | - | | ver | Required integer 1; unsupported versions provide no attribution. | | iss | Exact operator-configured issuer you pinned. | | aud | WHATWG serialized seller origin, with normalized host and port. | | iat / exp | Unix seconds; exp=iat+60. Check time validity with at most 5 seconds leeway. | | jti | Unique single-use token id; enforce shared replay protection. | | listingId | Your listing's id; it must be owned by you and serve this URL. | | delegationId | Stable authenticated-owner delegation id, shared across consenting seller calls. | | orgId | Optional organization of that delegation; no company verification implied. | | agentId | Optional buyer-entered attribution; no registry or identity verification. | | agentAttribution | buyer-declared, present only together with agentId. | | htm | Uppercase received HTTP method. | | htu | WHATWG serialized origin + pathname, excluding query and fragment. | | querySha256 | Base64url SHA-256 of WHATWG URL.search; empty for absent query or a bare ?. | | bodySha256 | Base64url SHA-256 of raw request body bytes, empty when absent. | ## Rotation and operations Operators prepublish the next public key on EVERY replica using ROUTER\_BUYER\_IDENTITY\_ADDITIONAL\_PUBLIC\_JWKS (a JSON array of public Ed25519 JWKs), leaving the old signer active. Wait at least the 30-second JWKS cache lifetime before changing active signers. Roll the active private key, retaining BOTH old and new public keys on every replica throughout the roll. Keep the retiring key at least 95 seconds after the last old-key signer stops (60-second tokens + 5-second leeway + 30-second cache), then remove it. Never put private JWKs in that array. Operators log paymentId, listingId and jti only after a paid hop has answered. They exclude the JWT, request body and the sensitive delegationId, orgId and agentId claims. This HTTP-answer record does not assert payment settlement. Signing or transport failures use failed-hop bookkeeping/fee release; a signer that failed before sending is marked not-sent for payment-channel reconciliation. ## Related guidance * [Router guardrails](https://nevermined.ai/docs/products/catalog/router/guardrails) * [Subscription funding](https://nevermined.ai/docs/products/catalog/router/subscription) # Guardrails and error codes Source: https://nevermined.ai/docs/products/catalog/router/guardrails What the Router enforces on a payment, what it refuses outright, and every error code it can return. The Router signs payments on your behalf, from your wallet, in response to instructions written by a merchant you may never have heard of. So it is deliberately suspicious. This page is the complete list of what it checks — and, more usefully, what to do when it says no. > [!NOTE] > > **A refusal is the system working.** Most Router errors mean a guardrail caught something. Before you widen a cap or drop an idempotency key to make an error go away, read what it was actually protecting you from. ## Your budget The **Delegation** is the control you own. It carries a hard cap in cents and an expiry, and it's checked server-side on every single payment. | | | | - | - | | **Cap** | The spend, converted to cents and rounded up, must fit in the remaining budget — including any [routing fee](/docs/products/catalog/router/how-it-works#the-routing-fee), which is reserved together with the merchant amount | | **Per-call ceiling** | Optional `maxTotalCents` on Router JSON calls: a non-negative safe integer. It limits one fee-inclusive, whole-cent cap reserve (merchant price plus any collectable Router fee, rounded once); the Delegation cap remains the overall limit | | **Expiry** | Set at creation via `durationSecs` — after that, nothing spends | | **Status** | Must be `Active`. `Revoked`, `Expired`, and `Exhausted` all refuse | Delegation cap, expiry, or status failures give you **`402 BCK.ROUTER.0003`**. Check the current state any time with `GET /api/v1/delegation/{id}` — `remainingBudgetCents` and `expiresAt` tell you which it was. A quote above `maxTotalCents` gives **`402 BCK.ROUTER.0018`** without a charge or budget reserve, although signing may already have occurred; raise that per-call ceiling only if the call is intended. An agent cannot spend past its cap by looping, by retrying, or by being confidently wrong about its own budget. That's the point of the mechanism, and it's why an agent should treat `0003` as a stop signal rather than something to route around. > [!WARNING] > > Delegations **expire silently**. A long-running agent that worked yesterday and fails today with `0003` has very often just aged out. Check `expiresAt` before assuming anything is broken. ## Your wallet A cap authorizes a spend; it doesn't provide funds. Both rails **pull** from your own wallet, so it has to hold the asset on the target network before you call — and what happens when it doesn't differs by rail. On **MPP-tempo**, the Router reads your on-chain balance *before* signing. If it's short you get **`402 BCK.ROUTER.0009`**, and nothing happens: no credential is minted, no budget is reserved, no partial state exists to clean up. On **MPP-stripe** no balance is read at all — the card is attempted, and a decline comes back as that *same* `402 BCK.ROUTER.0009`. The outcome matches (nothing minted, nothing reserved), but it's a real decline on your card rather than a check that spared you one. On **x402 there is no balance check anywhere.** The Router signs and reserves your budget, and the shortfall surfaces only when the transfer is attempted on-chain — the payment lands as `Failed`, and the reserved **merchant** leg is released once the reconciler has confirmed the authorization expired **unconsumed**, not at the moment of failure. Your cap stays reserved until then. Only a routing fee reserved on top of it can be credited back, and only on [the closed list of paths that release one](/docs/products/catalog/router/how-it-works#when-a-fee-is-not-collected). Fund for the merchant's amount **plus** any [routing fee](/docs/products/catalog/router/how-it-works#fund-for-the-amount-plus-the-fee), which is a second transfer from the same wallet. On any rail, read the wallet address from the live Delegation (`providerPaymentMethodId`) rather than from anything you saved earlier. Funding a stale address is the most common cause of an underfunded wallet and the one that takes longest to spot — `0009` deliberately doesn't echo the address it checked, so it can't tell you that's what happened. ## Session deposits Some services sell over an MPP **session** instead of charging per call. The first call takes a deposit from your wallet into a payment channel with that service, and each call is paid out of it. The deposit can be far larger than the price of the call: it is sized up to what your delegation may still spend, so a call costing a fraction of a cent can move most of your budget into the channel. A deposit is locked, not spent. It is not charged to your delegation's cap, and what the service doesn't use comes back to your wallet when the channel closes, after 15 minutes without use. A service that does not cooperate adds the escrow's grace period to that. * **Before you pay:** a quote's `sessionDeposit` says what the call would move into the deposit, the network fee not included. See [`quote_service`](/docs/mcp/catalog-mcp/quote-service). For an organization wallet it states only the most the call could lock. * **Afterwards:** each channel's deposit and refund are in [`get_budget`](/docs/mcp/catalog-mcp/get-budget) and on the Catalog tab of Purchases. A payment record only ever shows one call's price. * **To refuse them:** create the delegation with `allowSessionPayments: false`, or clear **Allow session payments** on the delegation form. A service that also charges per call over Tempo is paid that way regardless, and one that also offers x402 is paid there. Anything else is refused with `409 BCK.ROUTER.0047`, and nothing moves. A delegation can't be edited, so the choice is made when you create it. ## Who can be paid A Delegation **may** restrict which addresses it will pay. When it carries a recipient list, the merchant's pay-to address must be on it — checked *before* the expensive signing step, so a disallowed recipient costs you nothing. > [!NOTE] > > **Recipient scope is optional, and unset means unrestricted.** A Delegation with no recipient list can pay any merchant the Router can reach; its cap and expiry are then the only limits on it. Don't assume a Delegation is address-bound unless you deliberately made it so. Card-funded Delegations are vendor-agnostic by design and never carry one. On the MPP rail there's a related refusal worth calling out: a challenge carrying **`splits`** — additional payout recipients beyond the primary one — is rejected outright, whether or not your Delegation has a recipient list. Only the primary recipient is ever validated, so honouring splits would move real money to addresses nobody checked. The Router refuses the whole challenge rather than paying the part it can vouch for. ## Paying twice `requestId` is the idempotency key, and it's **required** in mode B — because the Router pays automatically, a retry after a dropped connection must not buy the same thing again. At most one payment is minted per `(caller, requestId)`. A duplicate returns **`409 BCK.ROUTER.0002`** carrying the original `paymentId`, which is usually what you actually wanted. Use **one stable id per logical purchase**, not per HTTP attempt: * Retrying a timed-out call with the **same** id → `409 BCK.ROUTER.0002` with the original `paymentId`, **not the resource**. Safe — but don't escape that 409 by minting a fresh id. * Retrying with a **fresh** id → buys again. Also safe, but only if that's what you meant. ## Bound quotes and required services — API 1.55+ A payment-required `POST /api/v1/router/quote` response carries an opaque `quoteId` and an `expiresAt` **60 seconds** later. Pass the id to `/route` with the exact quoted target, method, headers, body, credential header and Delegation. The Router pays the sealed merchant challenge at the exact fee-inclusive amount; `maxTotalCents` remains an independent ceiling. Invalid or wrong-account ids (`0029`), expired ids (`0032`), and any request, Delegation, rail or exact-total mismatch (`0033`) are refused before a charge. Re-quote whenever the call changes or the id expires. Clients pinned below API 1.55 receive no `quoteId`/`expiresAt` and retain the legacy re-probe flow. The same API version adds exact opaque-slug controls to `POST /router/select` and MCP `route_by_intent`: `filters.require`, `filters.prefer` and `filters.exclude`. `require` selects that slug or fails closed with `0031`; it never substitutes another service. `prefer` permits normal fallback, while `exclude` removes its slug from consideration. ## Who can read results An [async service](/docs/products/catalog/paid-results) delivers its result only to the wallet that paid for it, and checks that with a wallet challenge. The Router signs that challenge only as **your own wallet**, never as anyone else's: * **The signer is your personal wallet** — the EOA behind your crypto (`erc4337`) Delegation. Never an organization wallet: a proof signed as the org wallet would let any member of the organization read every job paid from it. * **Your wallet must have paid.** The Router signs only when that same wallet has a `Settled` payment for the same catalog slug within the follow-up window. * **Only on a follow-up.** The endpoint must be marked `auth: "siwx"` in the catalog, or be one of the service's declared follow-up paths, and you must call it by `slug`. * **Nothing is spent.** No payment, reservation, fee or ledger row. One retry with the signed answer; if that fails, the call is refused as before (`BCK.ROUTER.0035`). Because of this, the **paid** call to a service that has `auth: "siwx"` endpoints is refused with `400 BCK.ROUTER.0001` **before anything is charged** when it would be funded by an organization wallet or a card. Those payers can't read the result back, so the Router won't sell it to them. On a deployment where follow-ups are turned off, the paid call is refused the same way. Subscription credits are paid by the Nevermined treasury, so they follow the same rule per endpoint. A small reviewed allowlist of **self-contained** endpoints, whose paid response is the whole result (no job id or token to poll, nothing the payer then owns, no refund to an address), can be paid with credits. Every other endpoint of the service, including any the merchant adds later, is refused with `403 BCK.SUBSCRIPTION_ROUTER.0001` and `params.reason: "wallet_bound"` before anything is reserved. Pay those from a crypto Delegation on your own wallet. | Env var | Default | Purpose | | - | - | - | | `ROUTER_FREE_FOLLOWUP_TTL_MS` | unset (off) in code; `3600000` (1 hour) on Nevermined's production deployments | How long after the paid call its follow-ups — free result reads and wallet-challenge answers — are allowed. The window runs from when the payment was created, and the payment must have settled by the time of the follow-up. Unset or `0` turns both off, and paid calls to services with `auth: "siwx"` endpoints are refused. | ## What the Router won't fetch The Router makes server-side HTTP requests to URLs you supply, so it will not let you point it at infrastructure you shouldn't reach. Targets resolving to loopback, private (RFC 1918), link-local, or cloud-metadata addresses are blocked — both literal IPs and public hostnames that *resolve* to internal addresses, so DNS rebinding doesn't get around it. The connection is then pinned to the address that was validated, so it can't be swapped underneath. Redirects are **not followed at all**, and the `location` header is stripped from the relayed response — so a merchant can't bounce the Router toward an internal target, and can't hand your client one either. Operators can lift this for local development with `ROUTER_ALLOW_PRIVATE_TARGETS=true`. It should never be on in a shared environment. Control headers are also stripped in both directions: your `X-Router-*` headers aren't forwarded upstream, and any `X-Router-*` headers a merchant returns are removed before the response reaches you — so an upstream can't forge a payment signal that makes a free response look paid. ## What the merchant sees of you `/proxy` relays a live request, so the headers reaching it are not only the ones you set — every proxy between you and the Router appends its own (`X-Forwarded-Host`, `X-Real-Client-IP`, `traceparent`, …). Those describe **our** infrastructure, not your request, and a merchant has no business receiving them. So `/proxy` forwards an allowlist of standard request headers and drops everything else, `Cookie`, `Origin` and `Referer` included. Add what a merchant genuinely needs by stating its value — `X-Router-Forward-x-api-key: sk-…` sends `x-api-key: sk-…` upstream. That channel carries a value rather than naming a header to replay, so it can never be used to read back something our own infrastructure set: nothing replayed off the wire is forwarded except the allowlist. The Router also adds nothing of its own on the way out: no `Forwarded` or `X-Forwarded-For` is synthesised, so your IP never reaches the merchant. `POST /route` carries no such risk and applies no allowlist — its `headers` are a JSON object you wrote, so it forwards exactly what you ask for. ## Relay limits Mode B relays live traffic, so it's bounded: | Limit | Default | Env var | | - | - | - | | Concurrent routed requests per user | 10 | `ROUTER_MAX_CONCURRENT_PER_USER` | | Idle time on a streamed response | 30s | `ROUTER_STREAM_IDLE_MS` | | Total time on a streamed response | 5 min | `ROUTER_STREAM_MAX_MS` | | Relayed body size | 100 MB | `ROUTER_MAX_RELAY_BYTES` | Exceeding the concurrency limit returns **`429 BCK.ROUTER.0007`**, which *is* retryable — let some calls finish and try again. The idle timer is re-armed by your client draining the response, so a slow-but-healthy large transfer won't trip it. ### Per-endpoint request size Some services accept smaller request bodies than the Router does. The catalog records that limit as `maxRequestBytes` (UTF-8 bytes) on each endpoint of the service detail (`GET /api/v1/catalog/services/{slug}`) and in the MCP `get_service` result. Every Locus gateway (`*.mpp.paywithlocus.com`) publishes `8000`: its load balancer refuses a larger body before it ever asks for payment. When you call a service by `slug`, the Router checks your body against that limit **before contacting the service**. A larger body returns **`413 BCK.ROUTER.0027`** with `bodyBytes` and `maxRequestBytes` in `params`. Nothing was paid, so shrink the body or pick another service. `POST /router/select` (and the MCP `route_by_intent`) skips endpoints whose limit is below the `body` you send, so a long prompt is routed to a service that takes it. An endpoint without `maxRequestBytes` has no known limit, which is not the same as having none. ## Every error code Every code below also appears in the canonical [API error catalogue](/docs/development-guide/api-errors/codes#bck-router), which carries the `category` and `retryable` fields your client can branch on without parsing a message. [Error handling](/docs/development-guide/api-errors/overview) describes the envelope they arrive in. Codes `0029` and `0031`–`0033` require API 1.55+. | Code | Status | Meaning | Retry? | | - | - | - | - | | `BCK.ROUTER.0001` | 400 | Bad input: unsupported protocol, malformed or empty challenge, no fundable option, a recipient outside the Delegation's scope, a non-allowlisted asset, a wrong-provider Delegation, or a missing `delegationId`. The `details` field names the specific problem. Identity consent requires a plain key, HTTPS slug target, seller opt-in and supported direct route. OAuth credentials get `403 BCK.OAUTH.0030` on `/route`, `/route/with-controls`, `/proxy` and `/svc` before consent checks; consent on commerce routes gets this `0001`. Select refuses the field whenever present, even false or null, once past authentication guards. | No | | `BCK.ROUTER.0002` | 409 | This `requestId` already minted a payment. The original `paymentId` is in the response. | No | | `BCK.ROUTER.0003` | 402 | The Delegation is over cap, expired, exhausted, or revoked. | No | | `BCK.ROUTER.0004` | 404 | No Router payment with that id belongs to you. | No | | `BCK.ROUTER.0005` | 409 | The payment isn't in a settleable state. Only an `Issued` payment can be marked `Settled`; re-reporting the same hash is a no-op, a different hash is rejected. | No | | `BCK.ROUTER.0006` | 500 | Transient failure building the payments summary. | **Yes** | | `BCK.ROUTER.0007` | 429 | Too many concurrent routed requests in flight. | **Yes** | | `BCK.ROUTER.0008` | 403 | Legacy API key. Create a new one — see [the quickstart](/docs/products/catalog/router/quickstart#1-get-an-api-key). | No | | `BCK.ROUTER.0009` | 402 | You couldn't fund the payment. MPP only, and it covers two cases: MPP-tempo read your balance and found it short, or MPP-stripe attempted your card and it declined. Either way nothing was signed and no budget was reserved. x402 never raises this — it has no balance check, so a short wallet fails on-chain instead. | No | | `BCK.ROUTER.0010` | 500 | Internal: a rail reported a charge amount the Router can't reserve against the cap. | No — **never blind-retry** | | `BCK.ROUTER.0011` | 402 | Card rail: the charge needs cardholder 3-D Secure, and an agent has no browser to complete it. Nothing was charged and the seller got no usable credential. | No — **needs a human** | | `BCK.ROUTER.0012` | 400 | The seller's 402 advertises an EIP-712 domain its own settlement token does not sign under, so the Router refuses to sign. Nothing signed, charged or reserved — an authorization under the wrong domain is unspendable anyway. Seller-side bug | No — **report it, pay elsewhere** | | `BCK.ROUTER.0013` | 500 | Nevermined holds no EIP-712 signing domain for the token the funding filter selected — a gap in OUR canonical table, not the seller's bug and not your request. Nothing signed, charged or reserved | No — **report it to Nevermined** | | `BCK.ROUTER.0014` | 409 | The target is a cataloged Nevermined service, whose upstream URL is deliberately hidden. The Router refuses to pay it by raw URL — mode A and a raw mode-B target both put the merchant's host on your wire, defeating the broker. The match is by HOST, so a co-hosted endpoint that is not itself listed is refused too — ask the vendor to list it, or contact Nevermined; hosts with no cataloged service are unaffected. | No — **use the slug**: `POST /router/route` with a `slug`, or `POST /router/svc/` (a `commerce` grant: `POST /router/commerce/route` with a `slug`). A refused **quote** is re-quoted by slug — `POST /router/quote`, or `/router/commerce/quote` for a grant — never paid | | `BCK.ROUTER.0018` | 402 | Per-call `maxTotalCents` is below the fee-inclusive, whole-cent cap reserve. No charge or cap reserve, though signing may already have occurred; parse JSON-string `params` for `requiredTotalCents`. | No — raise the ceiling only if this call is intended; reuse the same `requestId` | | `BCK.ROUTER.0019` | 400 | Streaming surfaces only (`/proxy` · `/svc`; `/route` returns the envelope status with `body: null`). A cataloged service returned a **non-retryable** status — a 4xx client error, or a rare 3xx the Router does not follow (a 402 re-challenge and a 429 are **not** this code). The upstream body is withheld (it can name the merchant host); this typed body preserves the **real** upstream status (on the HTTP status line and in JSON-string `params`). Build a valid request from the service's Catalog detail (`requestExample` / `responseFields`). | No — **fix the request first**, then retry with a fresh `requestId` | | `BCK.ROUTER.0020` | 502 | Streaming surfaces only (`/proxy` · `/svc`; `/route` returns the envelope status with `body: null`). A cataloged service returned a server error (5xx) or rate-limited (429) — an upstream/transient condition, not your request. Body **and** headers are withheld (host oracle, including `Retry-After`); this typed body preserves the **real** status. The Router charges **no routing fee** for an undelivered call; whether the merchant leg itself charged is reported as `merchantSettlementObservedAt` (recorded by on-chain reconciliation on x402, MPP `evm` and MPP-tempo; `null` on a clean per-call settlement, whenever reconciliation has no verdict, and always on MPP-stripe, so `null` is not proof of no charge; read alongside `status`) on `GET /api/v1/router/payments`. | **Yes**, with backoff — reuse the same `requestId` only if no `X-Router-Payment-Id` came back; if one did, a payment is already recorded, so use a NEW id and reconcile via `GET /router/payments` | | `BCK.ROUTER.0021` | 400 | The rail this service advertised carries its payment credential in a header you are **already using**. On the MPP rails that header is `Authorization`, which is also where your own merchant auth goes (`headers.Authorization` on `/route`, `X-Router-Upstream-Authorization` on `/proxy` · `/svc`). Rather than silently dropping yours on the paid hop, the Router refuses: **nothing was minted, no cap was reserved and no money moved**. JSON-string `params` names the contested header. | No — **name the header the service documents** for its credential: `credentialHeader` in the `/route` body, or the `X-Router-Credential-Header` request header on `/proxy` · `/svc` (a separate `Payment` header is the common one). If the service documents none, it wants the credential in `Authorization` itself and cannot also take your bearer there: drop your own auth for that call, or pay it over an x402 endpoint (whose credential travels in `PAYMENT-SIGNATURE`). Retrying unchanged fails identically | | `BCK.ROUTER.0022` | 500 | A required Router capability is not configured: service selection or buyer identity signing. Details/params identify the capability; nothing sent, minted or charged by this attempt. | Yes — only after the operator restores the capability; do not loop unchanged. Deliberately omit disclosure consent if attribution is optional | | `BCK.ROUTER.0023` | 502 | On an autoPay `POST /router/select` (or `/router/commerce/select`): the chosen service was paid but the downstream call did not complete cleanly **after** the payment was created, so the charge outcome is **indeterminate** — the merchant leg may or may not have settled. JSON-string `params` carries the `paymentId` when one was created. | No — do **not** retry with a fresh `requestId` (that could double-charge). Reconcile via `GET /api/v1/router/payments?requestId=` (percent-encoded), then reuse the **same** `requestId` to retry safely | | `BCK.ROUTER.0024` | 413 | The request body exceeds the Router's size limit (about 5 MB). | No — reduce the request body before trying again | | `BCK.ROUTER.0025` | 502 | The upstream reply was too large to deliver after a paid request. The payment outcome is indeterminate; it may have gone through. | No — this reply has no `X-Router-Payment-Id`; JSON-string `params` may carry `paymentId`. If `params` has no `paymentId`, look the payment up by your `requestId`: `GET /api/v1/router/payments?requestId=` (percent-encoded) answers `{ presence, payments }`. A 0025 always records the payment first, so `absent` there means you queried the wrong id, account or environment — never that nothing was charged. The row reads `status: Failed` because delivery failed, not because the merchant was uncharged. A non-null `merchantSettlementObservedAt` confirms the merchant was paid on-chain; null does not prove no charge on any rail. Do not retry: the same `requestId` returns 409 `BCK.ROUTER.0002` with the original `paymentId` and cannot re-deliver the reply; a fresh id risks another charge. | | `BCK.ROUTER.0026` | 415 | The Router cannot forward this request body. The streaming surfaces (`/router/svc/:slug`, `/router/proxy`) forward only JSON (`application/json`) or URL-encoded (`application/x-www-form-urlencoded`) bodies; any other type — `multipart/form-data` above all, but also `text/plain`, `application/octet-stream` or a vendor `+json` — and any body on GET/HEAD is refused. No payment was minted and no money moved. JSON-string `params` names the refused `contentType` (null when none was sent). | No — resend the body as JSON or a URL-encoded form the service accepts; a service that only takes a file upload cannot be paid through the Router yet, and retrying unchanged fails identically | | `BCK.ROUTER.0027` | 413 | The request body is larger than the catalog endpoint accepts. The catalog records a `maxRequestBytes` per endpoint (on the service detail and in MCP `get_service`) — the Locus gateways (`*.mpp.paywithlocus.com`) take 8,000 bytes — and a slug-routed call (`/router/route`, `/router/quote`, `/router/svc/:slug`, `/router/proxy` with a slug) whose body is larger is refused before the service is contacted. No payment was minted and no money moved. JSON-string `params` carries `bodyBytes` and `maxRequestBytes`. | No — shrink the body below the limit or split the work, or pick a service that takes larger requests (`POST /router/select` with the same `body` skips endpoints whose limit is below it); retrying unchanged fails identically | | `BCK.ROUTER.0028` | 503 | `POST /router/quote` could not price the call because a read it depends on failed (for example the settlement-token details on the payment network). Nothing is signed, minted or charged on the quote path. | **Yes**, with backoff — a quote never charges, so nothing needs unwinding. The same condition would also fail a payment, so do not route the call meanwhile; if it persists, quote `correlationId` | | `BCK.ROUTER.0029` | 404 | The `quoteId` is invalid or belongs to another account. Nothing was signed, reserved or charged. | No — request a new quote and use its `quoteId`; do not retry the same invalid id | | `BCK.ROUTER.0030` | 404 | No retained paid result for that paymentId under your account. A paid Router result is retained for 24h after the call ends, for the paying user only; it is not retained for a response that had already started streaming when the call completed, or for a payment never routed through `/router/route`, `/router/proxy` or `/router/svc`. The payment record itself is unaffected. | No — the result is gone (or was never retained); read the payment with `GET /api/v1/router/payments` | | `BCK.ROUTER.0031` | 409 | The exact catalog slug in `filters.require` is unavailable, unhealthy, unpayable, excluded by this request, or cannot accept the body. The Router fails closed instead of substituting another service. | No — inspect `params.reason`; correct the slug or request, or deliberately remove `require` to allow fallback | | `BCK.ROUTER.0032` | 410 | The `quoteId` expired before payment began. Nothing was signed, reserved or charged. | No — quote the same call again and decide against the new fee-inclusive total; do not retry the expired id | | `BCK.ROUTER.0033` | 409 | The payment differs from the quote in its target, method, headers, body, credential header, delegation, rail, or exact fee-inclusive amount. Nothing was reserved or charged. | No — send the quoted call unchanged, or request a new quote for the changed call | | `BCK.ROUTER.0034` | 502 | A paid request got no response from the service (timeout or connection failure) after the credential was sent — the service may already have redeemed the payment. `params` carries the `paymentId`. | No — reconcile via `GET /api/v1/router/payments/{paymentId}`; never retry with a fresh `requestId` (it could pay twice) | | `BCK.ROUTER.0035` | 422 | The service's challenge asks for no payment (a zero amount — typically an auth-only "sign in with your wallet" challenge), and the Router could not answer it. It answers one (an MPP zero-amount proof or an x402 Sign-In-With-X) only for a catalog service, on an endpoint marked `auth: "siwx"` or a declared follow-up path, when your own wallet settled a payment for that service within the follow-up window — see [who can read results](#who-can-read-results). Your request is not malformed; nothing was signed, reserved or charged. | No — make the paid call first from your own wallet, then poll through the same slug; or authenticate with the service directly | | `BCK.ROUTER.0036` | 422 | Every catalog endpoint the call reaches is known to answer after the Router abandons a paid call (120 s), and the merchant charges on receipt — so paying would charge and deliver nothing. Refused before any payment (a retry of an already-paid `requestId` gets `0002` instead). `params.source` is `declared` (permanent) or `observed` (lifts at `params.liftsAt`). On a declared free-follow-up path it is raised only when the service answers `402`. | No — pick another endpoint or service; an `observed` refusal lifts at `liftsAt` | | `BCK.ROUTER.0040` | 500 | Internal: the Router's record of an MPP **session** payment channel refused an inconsistent read or write — a defect on our side, not your request. The payment was refused before its credential reached the service, so nothing moved. | No — **report it** with the `correlationId` | | `BCK.ROUTER.0041` | 400 | The service is paid only over an MPP **session** (a payment channel). The Router must read the service's receipt after every call to keep the channel consistent, so it pays a session only when it fetches the service itself — never through `POST /router/payments`. Nothing was signed or charged. | No — call it through `POST /router/route`, `/router/svc/` or `/router/proxy` | | `BCK.ROUTER.0042` | 409 | The MPP **session** payment channel with this service is closing — its deposit reached its ceiling, or the service refused the channel, a top-up of its deposit, or the payment after a top-up — so nothing can be signed on it until the close completes. No payment was signed, reserved or charged (a top-up the Router sent only moved your own funds into the channel; they come back at close). | **Yes**, later — reuse the same `requestId`; the next call after the close opens a new channel | | `BCK.ROUTER.0043` | 503 | The MPP **session** payment channel with this service is busy: another payment on it held it too long, your wallet's signer or balance read did not answer in time, or a top-up of the channel was in flight or the service could not be reached to take one (`params.stage`). Nothing was signed, reserved or charged. | **Yes**, after a few seconds — same `requestId` | | `BCK.ROUTER.0044` | 422 | The Router cannot collect its routing fee on this MPP **session** payment, so it refused it. A session's fee is never charged call by call: it is added up and collected later in one transfer from the paying wallet, and `params.cause` says why that cannot happen here: `org-wallet` (the payment is funded by an organization wallet, which that collection cannot draw from yet) or `network` (this deployment does not collect session fees on the service's network). Nothing was signed, reserved or charged, and no payment channel was opened. | No — `org-wallet`: pay from a delegation funded by your own wallet; `network`: pay a service on another network | | `BCK.ROUTER.0045` | 409 | The service does not offer the payment rail pinned by `requireProtocol` (`X-Router-Require-Protocol` on `/proxy` · `/svc`; x402 or mpp). `params.requireProtocol` names the pin and `params.offered` lists the rails offered by its payment challenge (empty when neither rail is offered: choose another service). Nothing was signed, reserved or charged. | No — choose a service that accepts your required rail, or deliberately change the pin; never drop it automatically | | `BCK.ROUTER.0046` | 400 | You set `validateRequestBody` (opt-in) and the request body provably fails the endpoint's published request schema, so the Router refused it before anything was signed, minted, reserved or charged. `params.endpointPath` names the endpoint whose schema the body failed. Without `validateRequestBody` the call is never refused on this basis. It is read on `/route`, `/commerce/route` (and their `/with-controls` variants) and `/router/subscription/route`, and the Commerce MCP `pay_service` forwards it to them; the streaming `/proxy` and `/svc/:slug` surfaces do not apply it. | No — fix the request body to match the endpoint's published request schema/example (the catalog service detail's `requestSchema`/`requestExample`, or the Commerce MCP `get_service`), then retry; or drop `validateRequestBody` to send it as-is | | `BCK.ROUTER.0047` | 409 | This delegation was created with `allowSessionPayments: false` and the Router would pay the service over an MPP **session** (a refundable deposit leaves the wallet at the first call). Nothing signed, reserved or charged, and no channel opened. | No — use a service that charges per call, or report to the human, who can deliberately drop a `requireProtocol: "mpp"` pin or create a delegation that allows session payments. An app connected over OAuth holds its delegation through its grant, so they disconnect the app in Nevermined and reconnect it with session payments allowed instead | Across the whole Router surface, only `0006`, `0007`, `0020`, quote-only `0028`, and the MPP session channel's `0042` (closing) and `0043` (busy) are worth retrying automatically. `0022` (500, required Router capability unavailable: service selection or buyer identity signing) is retryable only after an operator restores that capability; do not loop unchanged. The rest are decisions, and retrying them unchanged will produce the same answer. On the *paying* path the set is narrower still — see below. > [!WARNING] > > **`0010` is a 500 that must never be retried** — which makes it the exception to "retry the 5xx". In fact `0006`, the one retryable 500, is raised only by the payments *summary* read and never by a payment, so on the paying path **`0007`, `0020`, `0042` and `0043` are the only codes worth retrying** (with backoff). > > `0010` fails *after* a payment credential has already been minted, and because no payment record was written, your `requestId` can't suppress a retry. Idempotency is enforced against the record, and there isn't one — so a retry is treated as a fresh purchase, mints another credential, and then fails identically, because the cause is a deterministic defect rather than a transient blip. > > **And `0011` is its mirror image on the other side of the status code.** A card needing 3-D Secure returns a `402` that reads like a routine payment error, and is equally un-retryable: the Router can't complete the challenge, so every retry re-demands it and strands another single-use card credential. Route it to a human. The general lesson is that **the HTTP status does not tell you whether to retry** — read the code. > > Nothing was charged to your Delegation and no payment record exists. On the card rail the minted credential is a Stripe Shared Payment Token which is left stranded: there is no revoke path, so it stands until it expires, and that expiry is `min(the merchant challenge's expiry, your Delegation's expiry, 89 days)` — not necessarily soon. Nothing you can do about it from the outside, which is precisely why this should be reported rather than looped on. ## Notes for autonomous agents If you're writing an agent that spends without a human in the loop, four rules: 1. **Treat `0003` and `0009` as stop conditions.** They mean "out of budget" and "out of money". Report them; don't work around them. 2. **Never widen a Delegation in response to a refusal.** The cap is the user's decision, not a runtime obstacle. 3. **Generate one `requestId` per purchase**, and reuse it across retries of that purchase. Deriving it from the work you're doing beats a fresh UUID per HTTP attempt. 4. **Check the price before you commit.** `settlement.approxCents` on the response tells you what the merchant charged, and `fee.capChargedCents` what your cap was actually debited — the two differ when a [routing fee](/docs/products/catalog/router/how-it-works#the-routing-fee) applies. To learn the fee-inclusive price *before* paying, [quote the call](/docs/api-reference/router/quote): a quote charges nothing, but it does reach the service and spends the same rate budget as a payment, so quote once per decision. A run of sub-cent calls still burns a cent of budget each. ## Next > [card] [Payment ledger](/docs/products/catalog/router/ledger) > > What actually got spent, and how to reconcile it. > [card] [How it works](/docs/products/catalog/router/how-it-works) > > Where these checks sit in the flow. > [card] [Full error catalogue](/docs/development-guide/api-errors/codes#bck-router) > > The catalogue entry for each `BCK.ROUTER.*` code, with its category and remediation hint. > [card] [Router API reference](/docs/api-reference/router/mint-payment-credential) > > The five endpoints these rules apply to, with request and response shapes you can try. ## Optional seller attribution Never enable identity disclosure implicitly. A plain-key delegation owner can opt in per paid slug request only when the seller listing also opts in. OAuth credentials, group members acting for another delegation owner and subscription funding cannot use this interface. See the [version 1 seller contract](/docs/products/catalog/router/buyer-identity) for strict boolean consent, public keys, request bindings and replay checks. Check availability at the seller-contract endpoint: it must answer and report a configured issuer. No version or enablement is implied by this page. # How the Router works Source: https://nevermined.ai/docs/products/catalog/router/how-it-works The payment flow end to end, the two call modes, and where custody actually sits. Every Router payment follows the same five beats, whatever protocol the merchant speaks: **1. Probe** Someone requests the paid resource without payment. The merchant answers **HTTP 402** with a payment challenge. **2. Detect** The Router reads the challenge and works out which protocol it is — an `accepts` array means x402, a `WWW-Authenticate: Payment` header means MPP. **3. Mint** The Router checks the spend against your Delegation, checks your wallet actually holds the funds, signs the payment from your wallet, and reserves the amount — plus any [routing fee](#the-routing-fee) — against the cap. **4. Pay** The credential goes to the merchant as an HTTP header. The merchant verifies it, settles, and returns the resource. **5. Record** The payment lands on your [ledger](/docs/products/catalog/router/ledger) with its settlement reference. The only thing that changes between call modes is **who performs steps 1 and 4** — you, or the Router. To require a payment rail on a mode-B call, set `requireProtocol: "x402"` or `"mpp"` in `/route` or `/quote` (including commerce variants). Unlike the advisory `protocol`, this is a binding pin: the Router never falls back to another rail. If the service does not offer it, `409 BCK.ROUTER.0045` refuses the call before signing, reserving or charging. Quote and pay with the same pin; a `quoteId` bound to another rail is refused with `BCK.ROUTER.0033`. Streaming `/proxy` and `/svc` calls use `X-Router-Require-Protocol` instead. Never silently remove the pin to get past a refusal. Subscription payments enforce it too; subscription-credit quotes price the credit tariff without applying it. ## Mode B — the Router calls the merchant (recommended) You hand the Router the request you want made. It probes, detects, mints, attaches, calls, and relays the answer. One call in, one answer out; you never see the 402 and never touch a credential. ```http theme={null} POST /api/v1/router/route Authorization: Bearer Content-Type: application/json { "delegationId": "5e7481c3-e972-45bd-bdc5-a0b99c4de4a1", "url": "https://service.example/api/resource", "method": "GET", "requestId": "order-1234" } ``` ```json theme={null} { "status": 200, "body": { "…": "the paid resource" }, "paid": true, "payment": { "paymentId": "b1f9c2e4-…", "settlement": { "recipient": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", "amount": "1000", "asset": "USDC", "network": "base-sepolia", "approxCents": "1", "scheme": "exact" }, "fee": { "bps": 0, "amount": "0", "cents": "0", "capChargedCents": "1" }, "txHash": "0xfc8af37b…", "status": "Settled" } } ``` `status` and `body` are the merchant's, relayed unchanged. `paid: false` means the resource was free — the Router relayed it and there is no `payment` block. That includes the result of an [async service](/docs/products/catalog/paid-results) you already paid for. > [!NOTE] > > **`requestId` is required in mode B.** Because the Router pays automatically, a retry after a dropped connection must not buy the same thing twice. At most one payment is minted per `(caller, requestId)`. From API version 1.48 a duplicate returns the first purchase's [retained result](#slow-services-and-retained-results) (or its `202` while it is still running). Otherwise — on older versions, when nothing was kept (a `/proxy` · `/svc` response that already streamed to you), after a call that `Failed`, or when the id was reused for a different target — it returns **409** carrying the original `paymentId`. Either way nothing is paid again. Use one stable id per logical purchase, not per HTTP attempt. ### Streaming variant For large or streamed responses, use `ALL /api/v1/router/proxy` instead. It's the same engine, driven by headers rather than a JSON envelope, and the merchant's response body streams straight back to you: | Header | Purpose | | - | - | | `X-Router-Target-Url` | Absolute upstream URL to route to. Required. | | `X-Router-Delegation-Id` | The Delegation to spend against. Required. | | `X-Router-Request-Id` | Idempotency key. Required. | | `X-Router-Upstream-Authorization` | Optional — the merchant's own auth, forwarded upstream. | | `X-Router-Forward-` | Optional — send `: ` upstream (see below). | Your method, body and the standard request headers pass through. Payment metadata comes back on the response: `X-Router-Payment-Id`, `X-Router-Payment-Status` (`Issued` / `Settled` / `Failed`), and `X-Router-Tx-Hash`. > [!NOTE] > > **Not every header you send is forwarded.** `/proxy` replays your request off the wire, so the header map it sees is not only yours — every proxy in between appends its own, ours included. Forwarding those would hand a merchant our internal hostnames and IPs, so `/proxy` forwards an allowlist: `Accept`, `Accept-Language`, `Cache-Control`, `Content-Language`, `Content-Type`, `Idempotency-Key`, `If-Match`, `If-Modified-Since`, `If-None-Match`, `If-Range`, `If-Unmodified-Since`, `Range` and `User-Agent`. Everything else is dropped, `Cookie`, `Origin` and `Referer` included. > > Need another one — a merchant keyed on `X-Api-Key`, say? Send the **value**, prefixed: `X-Router-Forward-x-api-key: sk-merchant-key`, and the Router sends `x-api-key: sk-merchant-key` upstream. It carries the value rather than naming a header to replay, so it can never hand a merchant something *we* put on your request. The channel refuses `Authorization` (use `X-Router-Upstream-Authorization`), `X-Payment` / `Payment-Signature` (the Router pays through its ledger, not around it), hop-by-hop headers and re-entrant `X-Router-*` names. > > `POST /route` is different — its `headers` are a JSON object **you** wrote, so nothing can be injected into it and it forwards everything you ask for. Use `/route` when you want one structured result; use `/proxy` when you want the bytes. ### Slow services and retained results Some paid calls take a while — video generation, long crawls. The Router does not make you hold a connection open for them, and it does not lose what you paid for when a connection drops. **If the service hasn't answered within 45 seconds**, the Router answers `202` instead of making you wait: ```json theme={null} { "paymentId": "b1f9c2e4-8a3d-4f27-9c6b-5d2e17a04f8b", "resultUrl": "/api/v1/router/payments/b1f9c2e4-8a3d-4f27-9c6b-5d2e17a04f8b/result", "status": "Pending" } ``` On `/router/proxy` and `/router/svc` it's a `202` with `Location` and `X-Router-Payment-Id` headers — and only **before** the service starts responding. A response that has started streaming to you streams to the end, as before. The payment is made and the call keeps running on the Router: up to its usual 120-second limit on `/router/route`, while a streamed call waits up to 120 seconds for the service to start answering and then up to the stream deadline (5 minutes by default) for the rest of its body. The routing fee follows the same rule as a call you waited for: collected when the service answers `2xx`, released otherwise. Read the result with the same API key: ```bash theme={null} curl -s "$NVM_API_URL/api/v1/router/payments/$PAYMENT_ID/result" \ -H "Authorization: Bearer $NVM_API_KEY" ``` | Answer | Meaning | | - | - | | `202`, `state: "Pending"` | Still running. Poll again in a few seconds. | | `200`, `state: "Ready"` | `status` and `body` are the service's response, exactly as `/route` would have returned them (a cataloged service's non-`2xx` body stays withheld). `bodyEncoding` says whether `body` is parsed JSON, text or base64. | | `200`, `state: "Failed"` | The call ended without a response the Router could keep — it failed, ran past its time limit, or a streamed body outgrew 10 MiB. `failureReason` says which. | | `404` `BCK.ROUTER.0030` | Nothing to return: the result expired, was never kept, or isn't your payment. | **Every paid mode-B result is kept for 24 hours**, for the account that paid, whether or not you received it the first time. A paid `/route` response carries it as `payment.resultUrl`, so a response lost to a client timeout or a dropped connection can still be read. Results are not kept for a `/proxy` or `/svc` response that streamed to you live. > [!NOTE] > > **What is stored, and for whom.** The Router stores the service's response — status, the headers it would have relayed, and the body, up to 10 MiB — exactly as it would have returned it to you, and nothing else: not your request, not your credentials. Only the account that paid can read it, with its own API key; anyone else gets the same `404` as for a payment that doesn't exist. It is deleted 24 hours after the call ends. Retrying with the same `requestId` returns the same `202`, then the result — on `/proxy` · `/svc` too when the first call answered `202` (a retry of a response that already streamed to you gets the `409` with the `paymentId`). Never a second payment. Answering a `202` with a new `requestId` buys the call again. These behaviours apply to API keys on version **1.48 or later** (see [API versioning](/docs/development-guide/api-versioning)); a key pinned to an older version keeps waiting as before, and its results are still kept. ### Async services: pay once, then read the result for free Some services return an id from the paid call and deliver the result later, on an endpoint only the paying wallet can read. The Router answers that endpoint's wallet challenge for you and relays the result with `paid: false`, charging nothing. See [Getting your results](/docs/products/catalog/paid-results). ## Mode A — you call the merchant yourself Use mode A when your agent needs to make the upstream call itself — a client you don't control, a transport the Router doesn't proxy, or a request you want to shape by hand. **1. Probe the merchant yourself** Request the resource, get the 402, and keep the challenge exactly as it arrived — the `accepts` object for x402, or the raw `WWW-Authenticate: Payment …` header value for MPP. **2. Ask the Router for a credential** ```http theme={null} POST /api/v1/router/payments Authorization: Bearer Content-Type: application/json { "delegationId": "5e7481c3-…", "protocol": "x402", "resourceUrl": "https://service.example/api/resource", "requestId": "order-1234", "target": { "x402Version": 2, "accepts": [ … ] } } ``` You get back a `credential` — `{ transport, name, value }` — plus a `settlement` descriptor, a [`fee`](#the-routing-fee) object, and a `paymentId`. The record is created `Issued`. **3. Attach it and re-request** Set the HTTP header named by `credential.name` to `credential.value`, and send your original request again. The merchant verifies, settles, and returns the resource. **4. Close the record** Report the settlement so the ledger entry completes: ```http theme={null} POST /api/v1/router/payments/{paymentId}/settled ``` Skip this and the record stays `Issued` — a valid state meaning "paid, settlement not yet observed", not an error. In mode A the Router only *signs*. It is not in the request path, so it cannot observe whether you ever redeemed the credential — which is why the ledger needs you to close the loop. > [!TIP] > > Prefer mode B unless you have a specific reason not to. It self-settles the ledger record, it's one round trip instead of three, and it removes an entire class of "I minted a credential and forgot to use it" bugs. ## Where custody sits This is the part worth understanding properly, because it explains an error you will eventually hit. Both rails are **pull-based**. The credential the Router signs authorizes the *merchant* to take a specific amount from **your own wallet**. Nevermined never holds your funds, never fronts them, and never moves them between users. Two independent things therefore have to be true for a payment to succeed: 1. **The Delegation authorizes the spend** — enough cap remains and it hasn't expired. Otherwise: `402 BCK.ROUTER.0003`. 2. **The wallet actually holds the money** — on the specific network and in the specific asset the merchant demanded. A cap is permission, not funds. You can hold a \$50 Delegation and still fail to buy something for a penny if your wallet is empty on that chain. **What happens when you're short differs by rail** — and one `402 BCK.ROUTER.0009` covers two quite different things: | Rail | Before signing | When you're short | | - | - | - | | **MPP-tempo** | Reads your on-chain balance | `402 BCK.ROUTER.0009`. Nothing minted, no budget reserved. | | **MPP-stripe** | Reads nothing — the card is attempted | A decline comes back as the same `402 BCK.ROUTER.0009`. Nothing minted and no budget reserved, but it's a real decline on your card, not a local check. | | **x402** | No balance check at all | Nothing stops you. The credential is signed and your budget reserved; the shortfall appears on-chain afterwards. | > [!WARNING] > > **On x402 an underfunded wallet ties up budget.** With no pre-check the Router signs and reserves your cap, and the merchant's transfer then fails on-chain. The reserved **merchant leg** is not lost — it is released once the reconciler has confirmed the authorization expired **unconsumed**, which is what a failed transfer leaves behind — but your cap stays reserved until that happens, so the budget is unavailable in the meantime. A routing fee reserved on top comes back separately, and only on [the closed list of paths that release one](#when-a-fee-is-not-collected). Fund before you call; don't rely on being stopped. ## The routing fee Nevermined charges a **routing fee** on each payment the Router makes for you. It's quoted in **basis points** over the amount you're paying the merchant — 100 basis points is 1% — and it's disclosed on the payment response, alongside what the merchant charged. > [!NOTE] > > **The routing fee is 2%** — `200` basis points — of the amount you pay the merchant. It is added on top, so a $1.00 call debits your Delegation cap $1.02 and the merchant still receives \$1.00. > > The rate is resolved per payment and returned as `fee.bps` on every response, so read it from there rather than hard-coding it. Three things are worth knowing about how a fee is applied. **It's a separate movement, not a bigger one.** The credential the Router signs authorizes the merchant's exact amount and nothing more — a fee never rides the merchant's authorization, and a merchant is never paid more than it asked for. The fee is charged as its own movement. **It's reserved against your Delegation cap together with the merchant amount**, as a single combined charge. So your cap headroom drains by merchant + fee, which is why the merchant amounts on your ledger won't add up to the budget you've spent unless you count the fee too. `fee.capChargedCents` is the figure your cap was actually debited. **The atomic fee rounds down; the cap charge rounds up.** These are two different numbers, rounded in opposite directions, and conflating them will understate what a payment costs you: * `fee.amount` — the fee in the asset's smallest unit — is rounded **down**, so a fee is never rounded up in Nevermined's favour. * `fee.capChargedCents` — what your Delegation cap is debited — is a **cents** figure, and cents always round up. How much that costs depends on what the rail can tell the Router about converting its asset to cents. When it can, the merchant amount and the fee are rounded up **together**, as one figure — so a sub-cent fee only costs you an extra cent when it tips the total across a cent boundary. When it can't, the fee is rounded up **on its own**, and then **any non-zero rate costs at least one whole cent of cap per payment** — a 1-cent purchase at 2% is debited 2 cents. The one case that does *not* cost you a cent is a fee that truncates below a single atomic unit: it could never be transferred, so it is dropped outright rather than reserved, and you are charged the merchant amount alone. So don't derive the cap charge from the amount and the rate. Read `fee.capChargedCents` — it's the figure your budget actually moved by. Every mint response — `POST /payments` in mode A, `POST /route` in mode B — carries a `fee` object: | Field | What it is | | - | - | | `fee.bps` | The rate applied to this payment, in basis points over a 10,000 denominator. `0` means no routing fee was charged. | | `fee.amount` | The fee in the settlement asset's smallest unit — the same unit as `settlement.amount`, rounded **down**. Reported atomically because cents are rounded up and can't express a sub-cent fee. | | `fee.cents` | What the fee added to the cap reserve, in cents, rounded **up**. | | `fee.capChargedCents` | The total debited from your Delegation cap for this payment: merchant leg + fee. | `settlement.approxCents` remains the **merchant** leg throughout — it is not the whole cap charge. With no fee configured the two are equal. The streaming `/proxy` variant returns its payment metadata as response headers, and there is no fee header among them. For those calls, read the fee from [the ledger record](/docs/products/catalog/router/ledger#the-routing-fee-on-a-record). ### When a fee is not collected A reserved fee isn't always collected, and what happens to the reserve then differs by leg. **The merchant leg is never given back.** Once the credential is minted, the merchant may have taken the payment and then errored — so the reservation stands whatever the call did afterwards. **The fee leg can come back — but only on a closed list of paths.** A mode-B hop that never returned 2xx, a facilitator that adjudicated and refused, or a fee movement that couldn't be signed: on each of those the fee's cents are credited back to your Delegation cap and the ledger row reads [`feeStatus: "Released"`](/docs/products/catalog/router/ledger#fee-lifecycle). Nothing else releases. A fee whose outcome is *unknown* stays `Submitted` and is resolved against the chain — and **resolving is not releasing**: a row the chain shows was never consumed becomes `Failed` with its reserve **still charged**. Read `feeStatus` for the credit; never infer it from a failure. The fee is collected on **both** the x402 and MPP rails, but each rail settles it by a different mechanism — and the ledger records a different key as a result: * **x402** settles the fee as a **second settleable authorization** on the same rail — a distinct authorization from the one that pays the merchant, settled on the mode's own schedule. Its key on the ledger row is [`feeNonce`](/docs/products/catalog/router/ledger#auditing-the-fee-leg). * **MPP `tempo`** settles the fee as a **separate on-chain transfer** the Router broadcasts itself — a second native transaction from your wallet to Nevermined's fee address. Its key on the ledger row is [`feeTxHash`](/docs/products/catalog/router/ledger#auditing-the-fee-leg). An MPP `evm` fee takes the x402 path above and is keyed by `feeNonce`. Both charge the same 2% — it's one fee reached two ways, not two fees. The only rail that can't carry a fee is the **card rail**: a card payment can't produce a second fee movement, so it reserves the merchant leg alone and its row reads [`feeStatus: "None"`](/docs/products/catalog/router/ledger#fee-lifecycle). Both modes then charge on every call. `requestId` does not change *whether* you are charged — it changes whether a **retry** is charged again. Reuse one stable id across every retry of the same purchase and the retry returns the original payment instead of minting a second one — from API 1.48 the retry gets its retained result when one was kept; otherwise `409 BCK.ROUTER.0002` with the original `paymentId` — so one purchase carries one fee. Omit it, or generate a fresh id per HTTP attempt, and the retry is billed as a new purchase. Mode B requires the id already; on mode A it is optional, which is exactly why it is worth passing. The mode then decides when the fee settles. Mode B settles it only after the merchant returns 2xx, so a hop that fails releases the fee. Mode A settles it at mint, before your credential is ever presented — so on mode A a wallet holding only the merchant's price typically pays the fee and then loses the merchant leg on-chain, and there is nothing to release. ### Fund for the amount plus the fee Because the fee is its own movement, the merchant's amount and the fee are **two separate transfers** pulled from the same wallet in the same asset. A wallet holding exactly the merchant's quoted price does not cover both, and the two succeed or fail independently — one failing doesn't roll the other back. So size your funding by **amount + fee**, not by the quoted price. On x402, where [nothing checks your balance up front](#where-custody-sits), that's the difference between a shortfall being impossible and it being discovered after your budget is already committed. ## How settlement gets recorded When the merchant accepts the credential it returns a settlement reference — a `PAYMENT-RESPONSE` header on x402, a `Payment-Receipt` on MPP. In mode B the Router reads it and stores it on the record. * On success the record goes to **`Settled`** with the reference stored as `txHash`. * If the merchant paid but returned no usable reference, the record stays **`Issued`** — a normal state meaning "the hop succeeded, settlement is pending observation". It is not an error and the Router will not fail an already-paid call over it. * If the merchant rejects the credential and returns another 402, the record is marked **`Failed`**. > [!WARNING] > > The settlement reference is **merchant-controlled and stored unverified**. It's bounded in length and character set, but the Router does not confirm on-chain that the referenced transaction exists or paid what it claims. Treat it as an anchor for reconciliation, not as proof of payment. ## Next > [card] [Quickstart](/docs/products/catalog/router/quickstart) > > Run the whole flow yourself. > [card] [Guardrails](/docs/products/catalog/router/guardrails) > > Everything the Router checks before it signs. # Payment ledger Source: https://nevermined.ai/docs/products/catalog/router/ledger Query, export, and reconcile every payment your agents have made — across every protocol, in one place. Every payment the Router mints lands on one ledger, whatever protocol it used and whichever service it paid. That's most of the point of routing payments at all: instead of reconciling a dozen provider dashboards, you have a single record of what your agents bought. All ledger endpoints are scoped to the authenticated caller. You only ever see your own payments. ## List payments ```bash theme={null} curl -s "$NVM_API_URL/api/v1/router/payments" \ -H "Authorization: Bearer $NVM_API_KEY" ``` | Query | Purpose | | - | - | | `delegationId` | Only payments spent against one Delegation | | `from` | ISO-8601 lower bound on `createdAt`, inclusive | | `to` | ISO-8601 upper bound on `createdAt`, inclusive | | `format` | `json` (default) or `csv` for a downloadable file | | `requestId` | Look up the one payment you made with this idempotency key — see [Look up one payment by `requestId`](#look-up-one-payment-by-requestid). The other filters are ignored. | An invalid `from` or `to` returns `400 BCK.ROUTER.0001` rather than silently ignoring the filter. ```json theme={null} [ { "id": "b1f9c2e4-…", "createdAt": "2026-07-01T09:00:55.605Z", "status": "Settled", "protocol": "x402", "network": "base", "asset": "USDC", "amount": "1000", "merchantAddress": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", "txHash": "0xfc8af37b…", "delegationId": "5e7481c3-…", "requestId": "order-1234", "resourceUrl": "https://service.example/api/resource", "buyer": "0x8D6A5233…", "feeAtomic": "0", "feeBps": 0, "feeCents": "0", "feeStatus": "None", "feeTxHash": null, "feeNonce": null, "feeFailureReason": null, "assetSymbol": "USDC", "assetDecimals": 6 } ] ``` `amount` is in the asset's smallest unit, and `assetDecimals` is the scale to divide it by. The figure charged against your Delegation cap is the cents equivalent, **rounded up**, which is why a long run of sub-cent calls costs more budget than the raw amounts suggest. ### Look up one payment by `requestId` To find out what happened to one call — a dropped connection, a `502` that says the payment may have gone through — look it up by the `requestId` you sent with it. Percent-encode the id: one pasted into the URL raw is read as a different id if it contains `+`, `&` or `#`. ```bash theme={null} curl -s -G "$NVM_API_URL/api/v1/router/payments" \ --data-urlencode "requestId=order-1234" \ -H "Authorization: Bearer $NVM_API_KEY" ``` ```json theme={null} { "presence": "present", "payments": [ { "id": "b1f9c2e4-…", "createdAt": "2026-07-01T09:00:55.605Z", "status": "Settled", "protocol": "x402", "network": "base", "asset": "USDC", "amount": "1000", "merchantAddress": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", "txHash": "0xfc8af37b…", "delegationId": "5e7481c3-…", "requestId": "order-1234", "resourceUrl": "https://service.example/api/resource", "buyer": "0x8D6A5233…", "feeAtomic": "0", "feeBps": 0, "feeCents": "0", "feeStatus": "None", "feeTxHash": null, "feeNonce": null, "feeFailureReason": null, "assetSymbol": "USDC", "assetDecimals": 6 } ] } ``` * **Exact, and scoped to you.** `presence` is `present` with your one payment for that `requestId`, or `absent` with an empty `payments` when you have none recorded. A failed read is an error, never `absent`. * **`absent` means "not recorded yet".** A payment is recorded when the Router pays, which can be well after you sent the call while it probes the service. If the original call may still be running, `absent` doesn't mean "not charged": retry with the **same** `requestId` — the Router pays at most once per `requestId` — never with a new one. * **The list filters don't apply.** `delegationId`, `from` and `to` are ignored, and the lookup isn't limited to the newest 1000 payments. * **The id is matched exactly as you sent it**, leading or trailing whitespace included, so `" order-1234"` and `"order-1234"` are two different payments. An empty or repeated `requestId` parameter is refused with `400 BCK.ROUTER.0001`. * **Use JSON to reconcile.** With `format=csv` you get the matching row, or only the header row when there is none — the CSV carries no `presence`. ### Reading the asset Three fields describe what was paid in, because the raw one isn't the same kind of value on every rail: | Field | What it is | | - | - | | `asset` | The settlement asset **as persisted at mint**, which differs by rail: a symbol (`USDC`/`EURC`) on x402 and on an MPP `evm` charge (`network` `base` or `base-sepolia`), the ERC-20 contract address on MPP-tempo, an ISO currency code on the card rail. Kept as-is for consumers that already parse it. | | `assetSymbol` | The ticker to display, resolved from `asset` on this row's `network`. `null` **only** when the row carries no asset, or an address we don't recognise on that chain — a symbol-shaped value is echoed as-is even when it isn't one we know, so a non-null `assetSymbol` is not proof the asset was recognised. Tickers and their **casing** vary by chain, so compare case-insensitively. | | `assetDecimals` | The decimal scale of `amount` for this asset, so you never have to assume one. `null` whenever the asset isn't recognised — making this, not `assetSymbol`, the field that tells you so. | `assetSymbol` and `assetDecimals` are resolved when you read the record rather than stored on it, so rows written before they existed carry them too. > [!WARNING] > > **When `assetDecimals` is `null`, don't substitute a default.** It is the reliable "we don't recognise this" signal — `assetSymbol` can be non-null on the very same row. Treat `amount` as raw atomic units rather than assuming a scale, and render the (truncated) `asset` rather than a guessed ticker. Assuming is worse than degrading: a wrong label is visibly wrong, whereas a wrong scale renders a plausible, wrong **number** and then sits in a spend total next to correctly scaled ones. In particular, not every row is a 6-decimal stablecoin — a card-rail row's `amount` is already in cents, at scale 2. ### The routing fee on a record `amount` is the **merchant** leg only. If a [routing fee](/docs/products/catalog/router/how-it-works#the-routing-fee) applied, it was reserved against your cap on top of that amount, and the record breaks it out: | Field | What it is | | - | - | | `feeAtomic` | The fee in the settlement asset's smallest unit — the same unit as `amount`. Rounded **down**. | | `feeBps` | The rate applied, in basis points over a 10,000 denominator. Pinned per row, so a later rate change never rewrites what an old payment was charged. | | `feeCents` | The cents this fee added to the cap reserve. Rounded **up**. | | `feeStatus` | The fee's own lifecycle, tracked independently of the record's `status`. | | `feeTxHash` | The settlement reference for the **fee** movement — e.g. `"0x9c4d6f1e…"`. On an x402 or MPP `evm` fee it's normally `null`: only a fee settled through the facilitator carries a value, and one confirmed by on-chain reconciliation has no transaction to record (see below). On an MPP `tempo` fee it's the hash of the fee transaction, recorded when that transaction is submitted, so it's present while `feeStatus` is still `Submitted` and stays on rows that end `Failed` or `Released`. Read `feeStatus`, not this field, to know whether the fee settled. | | `feeNonce` | The EIP-3009 nonce the fee movement was signed with — e.g. `"0x7b1e2c…"`. `null` until the fee is submitted, and always `null` on an MPP `tempo` fee, a native transaction with no EIP-3009 nonce. | | `feeFailureReason` | Why the fee didn't collect — or, on a `None` row, why one was never quoted. Diagnostic text for a human, **not a stable contract**: branch on `feeStatus`, never on this string. `null` when no rate is configured and while a quoted fee is still on its happy path. See below. | > [!WARNING] > > **`feeCents: "0"` doesn't mean the payment carried no fee.** The two figures round in opposite directions, so a fee can apply in atomic units yet add no cent to your cap reserve — an `Accrued`, or `Released`, row can legitimately read `feeCents: "0"`. `feeAtomic` is the one that answers "did a fee apply": a fee too small to transfer is dropped outright rather than reserved, so `feeAtomic: "0"` means no routing fee was charged at all, and the row reads `feeStatus: "None"`. When a rate is configured, the routing fee is **2%** (`feeBps: 200`), and it's collected on **both** the x402 and MPP rails — by [two different mechanisms](#auditing-the-fee-leg) their keys reflect. **Mode A now applies it to every call**; mode B applies it too, but only settles once the merchant returns 2xx — otherwise it is [`Released`](#fee-lifecycle), *unless* its outcome could not be adjudicated, in which case it stays `Submitted` and charged. Three cases legitimately read `feeStatus: "None"` with a zero fee: a **card**-rail payment, since that rail can't carry a fee leg; a deployment with **no rate configured**, which is the shipped default and what the sample record above shows; and a payment whose fee rounds below one atomic unit (the case in the warning above). **`feeFailureReason` says which of those you are looking at.** A `None` row produced while a rate *was* configured carries a `fee-not-quoted: …` string naming the reason — no destination for the settlement chain, no usable fee submitter, a rail that cannot carry a fee leg, or an amount too small to transfer. A `None` row with `feeFailureReason: null` is the shipped default: no rate is configured, so no fee was ever asked for. The two used to be indistinguishable on the wire. **Use a stable `requestId`, and a retry costs you nothing extra.** Because mode A now bills every call, the way to avoid paying twice for one purchase is to make the purchase idempotent: reuse **one** `requestId` across every retry of it. A retry then returns `409 BCK.ROUTER.0002` with the original `paymentId` instead of minting a second payment, so there is only ever one fee. Derive that id from the work you are doing, not from a fresh `uuid4()` per HTTP attempt — a new id on each attempt is indistinguishable from a new purchase, and will be minted and billed as one. > [!NOTE] > > **This is why merchant amounts and spent budget don't reconcile on their own.** `amount` on this record is the merchant leg, so the combined cap charge isn't derivable from the ledger alone. It's recorded as `amountCents` on `GET /api/v1/delegation/{id}/transactions`, and that same row breaks it out as `feeCents`, `feeAtomic` and `feeBps` — so **on a Router row**, `amountCents - feeCents` is the merchant leg in cents. > > Those fields are on **every** row of that endpoint, not just Router ones, and they read zero on a plan purchase or a crypto settlement — which pay no routing fee *on top of* their price. Do not carry the formula above onto those rows: a plan purchase can carry a platform margin taken *out of* the price, which `feeCents` deliberately does not describe. That figure is `nvmMargin`, published on `POST /api/v1/transactions/search` — one value per transaction, not per plan. > > If the fee is later [`Released`](#fee-lifecycle), that row's `amountCents` is reduced by the fee and `feeReleased: true` is set — but the `feeCents` breakout **stays**. So on a released row `amountCents` is *already net of the fee*: don't subtract it a second time, and don't add it back to reconstruct a total that has moved. It does **not** follow that what remains is the merchant leg — a payment whose merchant reserve was also released has that deducted from the same field, and reads `status: "failed"`. > > One exception to the flag, and it is the [sub-cent case](#the-routing-fee-on-a-record) above: `feeReleased: true` is set only when a cent was actually reserved. A fee too small to reserve one is released without ever setting it, and leaves `amountCents` untouched — so such a row reads `false` here while `GET /router/payments` reports the fee `Released`. The arithmetic still holds; the two labels just disagree. ### Auditing the fee leg `feeTxHash` and `feeNonce` are what make the fee movement auditable on its own, and each answers a different question — and which one anchors a given fee follows the rail: an **MPP `tempo`** fee is a native transfer, keyed by `feeTxHash`; an **x402** fee is an EIP-3009 authorization, keyed by `feeNonce`, and so is an MPP `evm` fee, which takes the x402 path. **`feeTxHash` is not `txHash`.** `txHash` anchors the **merchant** leg; `feeTxHash` anchors the **fee** leg. They are independent movements that settle separately — one can land while the other hasn't — so reconcile them separately rather than reading either as evidence of the other. Like `txHash`, [treat it as an anchor to verify](#reconciling-against-the-chain) rather than as proof. A value from the facilitator is recorded verbatim as the facilitator reported it, so don't assume a `0x` shape there. **`feeNonce` is the key that ties an on-chain transfer back to this payment.** EIP-3009 records every authorization under `authorizationState(payer, nonce)`, so with the nonce you can ask the chain directly whether that specific fee movement was consumed — which is exactly how a `Submitted` x402 or MPP `evm` fee is resolved. It is **not spendable on its own**: a nonce identifies an authorization, it isn't one. The signed authorization itself is deliberately never stored. > [!NOTE] > > **A `Settled` fee can carry `feeTxHash: null`, and that isn't a bug.** When the fee is confirmed by reading `authorizationState` rather than by observing the settlement, the chain answers with a boolean — consumed or not — and there is no transaction to record. On those rows `feeNonce` is the audit key; use it rather than the missing hash. ### Fee lifecycle | `feeStatus` | Meaning | | - | - | | `None` | No fee was charged — neither an atomic fee nor a cent of cap. The normal state while no rate is configured, and also what you get when a rate *is* configured but the fee provably can't be collected on this path. Either way nothing was reserved, so there's nothing to give back later. `feeFailureReason` tells the two apart. | | `Accrued` | A fee was computed and reserved against the Delegation cap. Nothing has been submitted anywhere, so nothing can have moved. | | `Submitted` | The fee movement was submitted and its outcome isn't confirmed yet. Money **may** have moved — this is the bucket that gets reconciled against the chain, using `feeNonce`, or `feeTxHash` on an MPP `tempo` fee. | | `Settled` | The fee movement landed on-chain. | | `Failed` | Collection provably did not happen. Terminal as an outcome — retrying changes nothing — but an **adjudicated** `Failed` can still advance to `Released`; one resolved by on-chain reconciliation stays charged. | | `Released` | The fee's share of the cap reserve, **if any**, was credited back, because collection reached a terminal not-collected state. Terminal. | **`Released` is the one that returns budget to you.** It's reached when the fee provably will not be collected — the facilitator adjudicated and refused, a mode-B hop never returned 2xx, or the fee movement couldn't be signed — and the fee's cents go back on your Delegation cap and on the ledgers that mirrored it (an org group budget is corrected separately, and can lag). A fee that applied atomically but added no cent still lands here, with nothing to credit back. It's only ever reached from `Accrued` or an **adjudicated** `Failed` — never from `Submitted` or `Settled`, where money may have moved or definitely did, and handing back headroom for money that already left your wallet is the one direction this must never fail in. > [!WARNING] > > **`Failed` does not imply `Released`.** They are separate steps, and the reserve comes back only on the paths listed above. A fee that failed some other way stays charged against your cap — in particular one that on-chain reconciliation resolved as never consumed — so read `feeStatus` for the release rather than inferring it from a failure. And an *unknown* outcome is never released at all — those rows stay `Submitted` until the chain settles the question. ### Credits-funded records A call paid with [Nevermined credits](/docs/products/catalog/router/subscription) — a subscription's allowance or free credits — spends them, not your Delegation, and says so: | Field | What it is | | - | - | | `fundingSource` | `subscription` or `delegation`. Present on every record. | | `creditsCharged` | The call's rate, in credits. `null` on a Delegation record. | | `creditsStatus` | `Committed` (delivered, credits spent), `Reserved` (still running, or undelivered and being refunded) or `Refunded` (credits returned). `null` on a Delegation record. | On a credits record `delegationId` is `null` — Nevermined's treasury paid the merchant, so `amount`, `asset`, `txHash`, `buyer` (the treasury's address) and `deliveryStatus` describe **that** payment, not a charge to you — there is no routing fee (`feeBps` is `0`), and `chargedMicros` is `"0"`. `creditsCharged` is the call's rate on every credits record, refunded ones included: it counts against your credits only when `creditsStatus` is `Committed`, so filter on `creditsStatus` before adding it up. ### Export ```bash theme={null} curl -s "$NVM_API_URL/api/v1/router/payments?from=2026-07-01T00:00:00Z&to=2026-07-31T23:59:59Z&format=csv" \ -H "Authorization: Bearer $NVM_API_KEY" -o router-payments-july.csv ``` The CSV carries the same fields as the JSON, and new columns are only ever **appended** to the header row — so a consumer parsing by column index is unaffected by their arrival. `creditsStatus` is currently the last column. > [!NOTE] > > **`feeFailureReason` is normalised before it is published.** Whitespace is collapsed to single spaces — so one payment is always one CSV record, even though some of the underlying errors are multi-line — and any embedded `scheme://…` URL is replaced with `[url]`, because part of this text comes from third parties we do not control. Read it as a human-facing diagnostic, and key your logic on `feeStatus`. ## Aggregate summary For dashboards and spend monitoring, `GET /api/v1/router/payments/summary` returns a total plus a time series instead of individual rows. ```bash theme={null} curl -s "$NVM_API_URL/api/v1/router/payments/summary?granularity=day" \ -H "Authorization: Bearer $NVM_API_KEY" ``` ```json theme={null} { "total": 137, "series": [ { "date": "2026-07-01T00:00:00.000Z", "value": 12 }, { "date": "2026-07-02T00:00:00.000Z", "value": 31 } ] } ``` `granularity` is `day` (default), `week`, or `month`; an unrecognised value falls back to `day` rather than erroring. `from` and `to` work as above. Buckets are oldest first. > [!NOTE] > > The summary counts **payment requests**, not amounts. Use the list endpoint when you need money rather than volume. ## Record statuses | Status | Meaning | | - | - | | `Issued` | The credential was minted and the budget reserved. Either the call is still in flight, or it succeeded without a usable settlement reference. | | `Settled` | The merchant accepted the credential and returned a settlement reference, now stored as `txHash`. | | `Failed` | The merchant rejected the credential — it answered the paid request with another 402. | `status` describes the **merchant** leg. A routing fee has its own `feeStatus`, and the two move independently — see [the routing fee on a record](#the-routing-fee-on-a-record). > [!WARNING] > > **`Issued` is not an error.** On a paid mode-B call it means the resource came back fine but the settlement anchor didn't — a missing, oversized, or malformed receipt. The Router deliberately will not fail an already-paid hop over a bad receipt. In mode A it's simply the state a record sits in until you report the settlement yourself. ## Closing a mode-A record In [mode A](/docs/products/catalog/router/how-it-works) the Router only signs — it never sees the merchant's response, so it can't know whether you redeemed the credential. Report the settlement to close the record: ```bash theme={null} curl -sX POST "$NVM_API_URL/api/v1/router/payments/$PAYMENT_ID/settled" \ -H "Authorization: Bearer $NVM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "txHash": "0xfc8af37b…" }' ``` ```json theme={null} { "paymentId": "b1f9c2e4-…", "status": "Settled", "txHash": "0xfc8af37b…" } ``` Take the hash from the merchant's `PAYMENT-RESPONSE` header. Two things to know: * Only an `Issued` payment can be settled. Re-reporting the **same** hash is a harmless no-op; a **different** hash, or a record that isn't `Issued`, returns `409 BCK.ROUTER.0005`. * A payment id that isn't yours returns `404 BCK.ROUTER.0004`. [Mode B does this for you](/docs/products/catalog/router/how-it-works), which is one of the better reasons to prefer it. ## Reconciling against the chain The settlement reference is reported by the merchant and stored **unverified**. The Router bounds its length and character set, but it does not confirm on-chain that the transaction exists, that it paid the expected recipient, or that it moved the expected amount. So for anything that matters — accounting, disputes, anomaly detection — treat `txHash` as an **anchor to verify**, not as proof. Check it against the chain named in the record's `network` field. Note also that a non-`0x` reference is legitimate: settlement identifiers are protocol-specific, and non-blockchain rails return processor references rather than transaction hashes. Don't assume the field is always a hash. ## Next > [card] [Guardrails](/docs/products/catalog/router/guardrails) > > Every error code, and what to do about each. > [card] [Overview](/docs/products/catalog/router/overview) > > Back to the top. # Router Overview Source: https://nevermined.ai/docs/products/catalog/router/overview The Router lets your agents pay any x402 or MPP service from one budget — without those services integrating Nevermined. The **Nevermined Router** is the buyer side of Nevermined. It lets your agents **pay for external services that were never onboarded to Nevermined** — any endpoint that speaks the x402 protocol or the Merchant Payment Protocol (MPP). Your agent authenticates with its Nevermined API key and spends against a **Delegation** — a budget with a hard cap and an expiry. The Router does everything else: it reads the merchant's payment challenge, signs the payment from your wallet, enforces the cap, and records the spend on one unified ledger. Your agent never holds a private key, never learns a payment protocol, and never needs an account with the service it just paid. > [!NOTE] > > The Router is how you **pay** for services you find in the **[Nevermined Catalog](/docs/products/catalog/overview)** — the curated directory of external x402 and MPP services. Discover a service there, then route the payment here. ## What this is not Nevermined has two halves, and it's worth being precise about which one you're reading: | | **Router** (this section) | **[Payments Facilitator](/docs/products/payments-facilitator/overview)** | | - | - | - | | Role | **Buyer** — your agent pays someone else | **Seller** — your API charges its callers | | Who integrates | Only you | Only the service being paid | | The money moves | out of your wallet | into yours | If you're monetizing an API, you want the Facilitator. If you want your agent to go buy things, you're in the right place. ## Why route payments instead of paying directly > [card] One budget, every rail > > A single Delegation covers x402 and MPP alike. Your agent doesn't branch on protocol, and you don't reconcile two sets of books. > [card] No per-provider accounts > > Pay-per-call services need no signup, no API key, and no subscription. The payment *is* the authentication. > [card] A hard spending cap > > The Delegation is enforced server-side, per payment. An agent cannot exceed it — not by looping, not by retrying, not by being wrong. > [card] One audit trail > > Every payment across every protocol lands on the same ledger, exportable as JSON or CSV. ## Which services you can pay | Protocol | What it looks like | Status | | - | - | - | | **x402** | The service answers `HTTP 402` advertising an `accepts` array (in the body for v1, in a `PAYMENT-REQUIRED` header for v2) | Supported — see [the x402 rail](/docs/products/catalog/router/rails-x402) | | **MPP** | The service answers `HTTP 402` with `WWW-Authenticate: Payment …` | Supported — see [the MPP rail](/docs/products/catalog/router/rails-mpp) | You do **not** need to know which one a service speaks. In the recommended call mode the Router probes the service, detects the protocol from its 402, and pays it. The detected protocol always wins over anything you declare. Services that authenticate with a conventional API key and bill you monthly are a different shape entirely — there is no per-request price on the wire and nothing for the Router to pay. Those aren't routable today. ## What it costs A routed call can cost you more than the merchant's price, and the two are charged separately: * **The merchant's price** — whatever the service asked for in its `402`. Paid in full; the Router never takes a cut of it. * **A Nevermined routing fee of 2%** of that price. Added **on top**, so a $1.00 call debits your Delegation cap $1.02 while the merchant still receives their full \$1.00. Every payment response carries a `fee` object saying exactly what was charged, and `fee.capChargedCents` — not `settlement.approxCents` — is the figure your budget actually moved by. See [the routing fee](/docs/products/catalog/router/how-it-works#the-routing-fee) for how it is applied and rounded, and [the ledger](/docs/products/catalog/router/ledger#the-routing-fee-on-a-record) for reading it back per payment. > [!NOTE] > > The rate is returned as `fee.bps` on every payment response — `200` basis points over a 10,000 denominator. Read it from there rather than hard-coding it. ## Environment To pay Catalog services, use **Live** — every listed service settles on mainnet, and the sandbox Router funds testnets only, so no listed service is payable there. | Environment | API base | Purpose | | - | - | - | | **Live** | `https://api.live.nevermined.app` | Real payments to Catalog services | > [!WARNING] > > Both rails settle **real value on public networks**. The Router is a payment system, not a simulator — a live call moves real funds to a real merchant. Rehearse with the cheapest sub-cent service and keep your first Delegation cap small. ## What you need before you start **1. A Nevermined API key** Sent as `Authorization: Bearer ` on every Router call. It must be a current-generation key — see [the quickstart](/docs/products/catalog/router/quickstart) for how to tell. **2. A Delegation** Your budget. Created once, reused for every payment until it's exhausted or expires. **3. A funded wallet** Both rails **pull** from your own wallet, so it must already hold the payment asset on the network you're paying on. The Router never holds or moves float on your behalf. ## Let your coding assistant drive it Everything on this page is also packaged as an **AI coding skill** — the machine-readable twin of this section, carrying the same facts and the same error codes. Install it once and your assistant knows how to discover a service, create a Delegation, make the paid call, and — just as importantly — when to stop rather than route around a refusal. ```bash Claude Code theme={null} /plugin marketplace add nevermined-io/docs /plugin install nevermined-router@nevermined ``` ```bash ClawHub theme={null} npx clawhub install nevermined-router ``` Cursor, Windsurf, Cline, Amazon Q, Codex and Copilot are covered too — see [AI Coding Skill](/docs/development-guide/build-using-nvm-skill) for the per-tool instructions, or read [the skill itself](https://github.com/nevermined-io/docs/tree/main/skills/nevermined-router). > [!NOTE] > > Install `nevermined-router` when your agent is **spending** at external services. Its sibling, `nevermined-payments`, is for the opposite direction — **receiving** payments and buying Nevermined plans. Installing both is fine; they don't overlap. ## Next > [card] [Quickstart](/docs/products/catalog/router/quickstart) > > From an API key to a paid call, in five steps. > [card] [How it works](/docs/products/catalog/router/how-it-works) > > The payment flow, the two call modes, and where custody sits. > [card] [Guardrails](/docs/products/catalog/router/guardrails) > > What the Router enforces, what it refuses, and every error code it can return. > [card] [Payment ledger](/docs/products/catalog/router/ledger) > > Query, export, and reconcile everything your agents have spent. # Router quickstart Source: https://nevermined.ai/docs/products/catalog/router/quickstart From a Nevermined API key to a paid call against an external service, in five steps. By the end of this page your agent will have paid a service that has never heard of Nevermined, from a budget you control, with the spend on your ledger. Everything here is plain HTTP. The Nevermined SDKs don't expose the Router yet, so the examples use `curl` and `fetch` — which is also the point: any agent, in any language, can drive it. > [!TIP] > > **Prefer to have your coding assistant do this?** These five steps ship as an AI coding skill. In Claude Code, `/plugin marketplace add nevermined-io/docs` then `/plugin install nevermined-router@nevermined`; elsewhere, see [AI Coding Skill](/docs/development-guide/build-using-nvm-skill). It also carries the guardrails an autonomous buyer must respect, which matter more than the calls themselves. > [!NOTE] > > Driving this from an agent harness? [Using the Catalog from a harness](/docs/products/catalog/from-a-harness) is the code-free companion to this page — the same flow, plus the safety habits (idempotency across retries, soft stops below your cap, funding for merchant + fee) an autonomous buyer should follow. Set your environment once. The Catalog is **Live-only for payment** — every listed service settles on mainnet, and the sandbox Router funds testnets only (apart from two free testnet test merchants kept there for rehearsal, see [the Commerce MCP page](/docs/mcp/catalog-mcp/overview#1-connect-your-host)) — so point at the live host: ```bash theme={null} export NVM_API_URL="https://api.live.nevermined.app" export NVM_API_KEY="" ``` ## 1. Get an API key Create one from the Nevermined app. Every Router call carries it as `Authorization: Bearer $NVM_API_KEY`. > [!WARNING] > > **Older keys don't work with the Router.** If you have a key from an earlier generation, the Router rejects it with **`403 BCK.ROUTER.0008`** — it's bound to a previous account model that can't sign these payments. The fix is simply to create a new key; newly issued keys work. Existing keys keep working for credit-based flows, so there's no rush to rotate anything else. Never send this key to the service you're paying. It authenticates you to Nevermined, nothing else. ## 2. Create a Delegation A Delegation is your budget: a hard cap in cents and an expiry. Create it once and reuse the id for every payment until it's exhausted or expires. ```bash theme={null} curl -sX POST "$NVM_API_URL/api/v1/delegation/create" \ -H "Authorization: Bearer $NVM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "provider": "erc4337", "currency": "usdc", "spendingLimitCents": 500, "durationSecs": 604800 }' ``` ```json theme={null} { "delegationId": "5e7481c3-e972-45bd-bdc5-a0b99c4de4a1" } ``` ```bash theme={null} export NVM_DELEGATION_ID="5e7481c3-e972-45bd-bdc5-a0b99c4de4a1" ``` That's a \$5.00 cap for 7 days. The cap is enforced server-side on every single payment — your agent cannot spend past it by looping, retrying, or misreading its own budget. > [!NOTE] > > `provider: "erc4337"` is the crypto-funded Delegation, which is what both stablecoin rails use. A card-funded Delegation is a different provider and is not accepted on those rails. ## 3. Fund your wallet Both rails **pull**: the merchant takes the money from your own wallet. A Delegation authorizes the spend, but the wallet has to actually hold the funds. Find its address on the Delegation: ```bash theme={null} curl -s "$NVM_API_URL/api/v1/delegation/$NVM_DELEGATION_ID" \ -H "Authorization: Bearer $NVM_API_KEY" ``` ```json theme={null} { "delegationId": "5e7481c3-…", "provider": "erc4337", "providerPaymentMethodId": "0x8F60b3838e6C121FcDBdBc50e7B150F8560a670E", "status": "Active", "spendingLimitCents": "500", "amountSpentCents": "0", "remainingBudgetCents": "500", "expiresAt": "2026-08-07T00:00:00Z" } ``` `providerPaymentMethodId` is the wallet address to fund. Send it the payment asset **on the network you intend to pay on**: | Rail | Network | Asset | | - | - | - | | x402 | Base mainnet (`8453`) | USDC — `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | | x402 | Base Sepolia (`84532`) | testnet USDC, from a public faucet | | MPP | Tempo mainnet (`4217`) | USDC.e — `0x20c000000000000000000000b9537d11c60e8b50` | | MPP | Tempo Moderato (`42431`) | PathUSD — `0x20c0000000000000000000000000000000000000`, self-funded via [one RPC call](/docs/products/catalog/router/rails-mpp#funding-your-wallet) | The address is the same on every EVM chain — it's one key-derived wallet, so there is nothing extra to create on Tempo. But **the balances are per-chain**: funding Base does nothing for an MPP payment. See [the x402 rail](/docs/products/catalog/router/rails-x402) and [the MPP rail](/docs/products/catalog/router/rails-mpp) for the full picture. > [!NOTE] > > **Funding is manual today.** There is no on-ramp — you cannot top this wallet up from a card or from a Nevermined credit balance, and the agent cannot refill itself. When the wallet runs dry, payments stop until a human sends more: on MPP with a clean `402 BCK.ROUTER.0009`, on x402 [less kindly](/docs/products/catalog/router/rails-x402#funding-your-wallet), because that rail doesn't check the balance before signing. Budget for that when you decide how much to fund — and fund for the merchant's price **plus** any [routing fee](/docs/products/catalog/router/how-it-works#the-routing-fee). An agent is autonomous *after* it is funded, and only until the balance runs out. This is the on-chain **wallet** the delegation spends; Nevermined **credits** are a separate balance an agent *can* refill within a human-set limit — see [Top-ups](/docs/products/catalog/router/subscription#top-ups). > [!WARNING] > > Always read this address back from the live Delegation rather than reusing one you saved. A stale address is the single most common cause of a confusing `402 BCK.ROUTER.0009`. On MPP-tempo the error does name the wallet and the chain it checked — so compare it against the one you funded — but it never echoes the **balance**, and on x402 there is no pre-check and no `0009` at all. [`wallet_balance`](/docs/mcp/catalog-mcp/overview#6-check-your-spend-and-your-balance) in the Catalog MCP reads the amount back. ## 4. Make a paid call Hand the Router the request you want made. It probes the service, detects the protocol, pays the 402, and relays the answer. > [tab] curl > > ```bash theme={null} > curl -sX POST "$NVM_API_URL/api/v1/router/route" \ > -H "Authorization: Bearer $NVM_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "delegationId": "'"$NVM_DELEGATION_ID"'", > "url": "https://service.example/api/resource", > "method": "GET", > "requestId": "fetch-example-resource-v1" > }' > ``` > [tab] TypeScript > > ```ts theme={null} > const res = await fetch(`${process.env.NVM_API_URL}/api/v1/router/route`, { > method: 'POST', > headers: { > Authorization: `Bearer ${process.env.NVM_API_KEY}`, > 'Content-Type': 'application/json', > }, > body: JSON.stringify({ > delegationId: process.env.NVM_DELEGATION_ID, > url: 'https://service.example/api/resource', > method: 'GET', > requestId: 'fetch-example-resource-v1', > }), > }) > > const { status, body, paid, payment } = await res.json() > if (paid) console.log(`paid ${payment.settlement.approxCents}c`, payment.txHash) > ``` > [tab] Python > > ```python theme={null} > import os, requests > > res = requests.post( > f"{os.environ['NVM_API_URL']}/api/v1/router/route", > headers={"Authorization": f"Bearer {os.environ['NVM_API_KEY']}"}, > json={ > "delegationId": os.environ["NVM_DELEGATION_ID"], > "url": "https://service.example/api/resource", > "method": "GET", > "requestId": "fetch-example-resource-v1", > }, > ).json() > > if res["paid"]: > print(res["payment"]["settlement"]["approxCents"], "cents", res["payment"]["txHash"]) > ``` The response carries the merchant's `status` and `body` unchanged, plus what the call cost you: ```json theme={null} { "status": 200, "body": { "…": "the paid resource" }, "paid": true, "payment": { "paymentId": "b1f9c2e4-…", "settlement": { "amount": "1000", "asset": "USDC", "network": "base", "approxCents": "1" }, "txHash": "0xfc8af37b…", "status": "Settled" } } ``` If the resource turned out to be free, you get `paid: false` and no `payment` block — the Router relays it and charges nothing. > [!NOTE] > > **Use one stable `requestId` per logical purchase, not per HTTP attempt.** It's the idempotency key: retrying a dropped call with the same id returns the original payment instead of buying twice. Retrying with a fresh id buys twice, on purpose. > > That applies to the snippet above, which uses a fixed id: **run it a second time and you get `409 BCK.ROUTER.0002`**, carrying the original `paymentId`, rather than the response shown. That is the guarantee working, not a failure — change the id to buy again. ## 5. Check what you spent ```bash theme={null} curl -s "$NVM_API_URL/api/v1/router/payments?delegationId=$NVM_DELEGATION_ID" \ -H "Authorization: Bearer $NVM_API_KEY" ``` Every payment across every protocol is on one ledger — see [the ledger page](/docs/products/catalog/router/ledger) for filters, CSV export, and the aggregate summary. ## When something is refused Refusals are the system working. The three you're most likely to meet: | Code | Status | What happened | | - | - | - | | `BCK.ROUTER.0003` | 402 | The spend would exceed your Delegation cap, or the Delegation expired. | | `BCK.ROUTER.0009` | 402 | Your wallet doesn't hold enough of the asset on that network. MPP only — nothing was signed. x402 has no balance pre-check and fails on-chain instead. | | `BCK.ROUTER.0002` | 409 | That `requestId` already bought something. The original `paymentId` is in the response. | [Guardrails](/docs/products/catalog/router/guardrails) covers every code and, more usefully, why widening a cap in response to a refusal is almost always the wrong move. ## Next > [card] [The x402 rail](/docs/products/catalog/router/rails-x402) > > Networks, assets, and what "exact" means. > [card] [The MPP rail](/docs/products/catalog/router/rails-mpp) > > Tempo charges, receipts, and the asset allowlist. # The MPP rail Source: https://nevermined.ai/docs/products/catalog/router/rails-mpp Paying Merchant Payment Protocol services through the Router — Tempo and EVM charges, receipts, and the asset allowlist. The **Merchant Payment Protocol (MPP)** is the other pay-per-call protocol the Router speaks. Where x402 advertises its terms in an `accepts` array, an MPP merchant answers with an RFC 7235 challenge: ``` HTTP/1.1 402 Payment Required WWW-Authenticate: Payment id="…", realm="service.example", method="tempo", intent="charge", request="", expires="…" ``` The Router decodes that challenge, signs the payment, and hands back an `Authorization: Payment <…>` credential. Your agent never loads an MPP SDK and never learns the envelope. ## What's supported | | Supported | | - | - | | **Method** | `tempo` — a native Tempo transaction pulling a Tempo stablecoin. `evm` — an EIP-3009 stablecoin authorization on Base, used only when the challenge offers no `tempo` (see [EVM charges on Base](#evm-charges-on-base)) | | **Intent** | `charge` — a one-off payment for this request | | **Networks** | `tempo`: Tempo mainnet (chain `4217`) and Tempo Moderato, the public testnet (chain `42431`). `evm`: the Base chain your deployment funds for x402 | | **Assets** | `tempo`: whatever the operator has allowlisted for that chain (see below). `evm`: the tokens the x402 rail pays | Subscriptions and metered streams aren't supported, and a challenge advertising one is refused rather than approximated. **Sessions** (payment channels) are supported in production — see [Sessions](#sessions-payment-channels) below. > [!NOTE] > > **You don't have to know a service speaks MPP.** In [mode B](/docs/products/catalog/router/how-it-works) the Router detects the protocol from the 402 itself, and the detected protocol always wins over the optional `protocol` hint in your request. Send the same `/route` call you'd send for x402. ## EVM charges on Base Some MPP merchants offer `method="evm"`: an EIP-3009 stablecoin authorization on Base, the same payment x402 makes, in an MPP envelope. The merchant settles it. The Router uses it only when the challenge offers no `tempo` method. A challenge offering both goes to `tempo`, and isn't retried as `evm` if its `tempo` offer can't be paid. An `evm` charge works like the [x402 rail](/docs/products/catalog/router/rails-x402), not like the rest of this page, which describes `tempo`: * **Chain and token.** The Base chain and tokens your deployment funds for x402: Base mainnet on a live deployment, Base Sepolia on sandbox. The asset allowlist below doesn't apply. * **Funding.** The paying wallet needs the stablecoin the challenge names (USDC or EURC, as on x402) plus the [routing fee](/docs/products/catalog/router/how-it-works#fund-for-the-amount-plus-the-fee), which is collected as on x402. * **A personal Delegation can't pay it.** An `evm` merchant verifies the payment by recovering its signer, so it needs a plain ECDSA signature. Personal wallets on Nevermined are EIP-7702 smart accounts and sign differently, so the Router refuses the call with `400 BCK.ROUTER.0001` before signing. On an unpinned mode-B call, a merchant that also offers x402 is paid over x402 instead. An unpinned `/quote` moves to that x402 offer too, and its `quoteId` pays x402. Mode A and a call pinned to `mpp` get no fallback, and `/quote` refuses in the same cases as `/route`. * **[Catalog credits](/docs/products/catalog/router/subscription#what-credits-can-pay) can pay it.** * **The record looks like x402.** The ledger row is `protocol: mpp` with `network: base` (or `base-sepolia`) and a symbol `asset`, and the `/route` response reports `settlement.scheme: "exact"`. Only the ledger's `protocol` tells the two rails apart — see [reading the asset](/docs/products/catalog/router/ledger#reading-the-asset). ## The asset allowlist `tempo` challenges name their payment token by contract address, and the challenge comes from the merchant — an untrusted source. So the Router will only settle a token the operator has **explicitly allowlisted for that chain**, via `ROUTER_TEMPO_ASSETS_`. This is **fail-closed**: an unset or empty allowlist rejects *every* asset on that chain. A payment naming a token that isn't on the list is refused with **`400 BCK.ROUTER.0001`** before anything is signed. If MPP payments fail with that code on a deployment where x402 works fine, an unconfigured allowlist is the first thing to check — the two rails are configured independently. > [!WARNING] > > **A service appearing in the Agent Services Catalog does not mean your deployment can pay it.** > The catalog describes services; the allowlist is a property of the deployment. Where the MPP rail > is not enabled, *every* MPP service paid over `tempo` is refused with `400 BCK.ROUTER.0001 … not > allowlisted` while x402 services pay normally — which reads like a broken merchant and is not one. > That includes a service that also offers x402: the Router doesn't fall back over its own > configuration. An `evm`-only MPP service doesn't use the allowlist. > > Retrying will not help, and neither will trying a different Tempo-paid MPP service: they all fail > the same way. Check the allowlist for the chain, or ask whoever operates your deployment. For a > service that also offers x402, you can pin `requireProtocol: "x402"`. | Chain | Chain id | Ledger network | | - | - | - | | Tempo mainnet | `4217` | `tempo` | | Tempo Moderato (public testnet) | `42431` | `tempo-moderato` | > [!WARNING] > > The stablecoin contract address is **not the same on both chains**. Allowlisting a testnet address on mainnet, or vice versa, produces a `400` that looks like the rail is broken. The two chains settle in genuinely different tokens — the mainnet address is not derivable from the testnet one: | Chain | Token | Address | Decimals | | - | - | - | - | | Tempo mainnet (`4217`) | `USDC.e` — Bridged USDC (Stargate) | `0x20c000000000000000000000b9537d11c60e8b50` | 6 | | Tempo Moderato (`42431`) | PathUSD — a Tempo system predeploy | `0x20c0000000000000000000000000000000000000` | 6 | Both begin `0x20c0` and differ only in the tail, so they are easy to misread. Confirm against a real challenge from the service you intend to pay before sending funds anywhere. ## Funding your wallet Like x402, MPP `charge` is a **pull**: the merchant takes the amount from your own wallet on the Tempo chain in question. Fund the address on your Delegation (`providerPaymentMethodId`) with the token for that chain before you call — and fund for the merchant's amount **plus** the [routing fee](/docs/products/catalog/router/how-it-works#fund-for-the-amount-plus-the-fee). On this rail the fee is a **second on-chain transfer** the Router broadcasts from the same wallet, so the merchant's price alone doesn't cover both. An underfunded wallet fails with **`402 BCK.ROUTER.0009`**, checked *before* signing — the balance has to clear the amount **and** the fee, so a wallet holding only the quoted price is refused here. Nothing is minted and no budget is reserved. That pre-check is specific to this chain-funded rail; [card-funded MPP](#card-funded-mpp) reaches the same error by a different route. On **Moderato** you can fund yourself in one RPC call — no faucet UI, no wallet, no signing: ```bash theme={null} curl -sX POST https://rpc.moderato.tempo.xyz \ -H 'content-type: application/json' \ -d '{"jsonrpc":"2.0","id":1,"method":"tempo_fundAddress","params":["0xYOUR_WALLET"]}' ``` It returns transaction hashes and lands test tokens. The balance needs a block to appear, so a `balanceOf` read immediately afterwards can still show zero — wait a few seconds and read again before concluding it did nothing. On **mainnet there is no faucet**: you have to bridge or transfer real USDC.e in yourself. ## What the Router refuses The MPP handler validates the decoded challenge before it signs, and fails closed on anything it can't fully account for: * **Wrong method or intent** — a method other than `tempo` or `evm`, or an intent other than `charge` ([card-funded MPP](#card-funded-mpp) and [sessions](#sessions-payment-channels) are covered below). * **An `evm` charge your wallet can't sign** — see [EVM charges on Base](#evm-charges-on-base). * **Unsupported chain** — for `tempo`, a chain id outside the table above; for `evm`, a chain your deployment doesn't fund for x402. * **Malformed recipient, currency, or amount** — addresses must be valid hex; the amount must be a positive integer. A charge for `0` is not a payment: see [zero-amount charges](#zero-amount-charges-proving-you-paid). * **A non-allowlisted asset** — see above. * **Multi-recipient payouts.** A challenge that carries `splits` is refused outright. > [!WARNING] > > **Why splits are refused.** An MPP `charge` can name a primary recipient *and* a list of additional payout recipients. Only the primary one is ever validated against your Delegation, so honouring splits would move real funds to addresses nobody checked. The Router rejects any split-bearing challenge outright — unconditionally, whether or not your Delegation restricts recipients — rather than paying the part it can vouch for. After signing, the Router decodes the credential it actually produced and compares it against the challenge it validated. If they diverge, the credential is discarded and never leaves the process — so a merchant can't get one thing approved and a different thing signed. ## Zero-amount charges: proving you paid An async service may guard its result endpoint with a `tempo` `charge` for an amount of **`0`**. It isn't asking you to pay. It's asking you to prove you're the wallet that already did: ``` HTTP/1.1 402 Payment Required WWW-Authenticate: Payment id="…", realm="stablestudio.dev", method="tempo", intent="charge", request="", expires="…" ``` The Router answers it with mppx's **proof credential** instead of a payment: an EIP-712 signature over `Proof{account, challengeId, realm}`, with `source` set to `did:pkh:eip155::`. It goes back in `Authorization: Payment <…>`, and the Router retries the request once with it. Nothing moves: a proof is a fixed typed-data template, not a transaction or a transfer authorization. The response comes back with `paid: false`, and no payment, fee or ledger row is created. Before signing, the Router checks the challenge: | Check | Requirement | | - | - | | Method and intent | `tempo` / `charge`, amount `0` | | Chain and asset | [Allowlisted](#the-asset-allowlist) per chain, exactly as for a paid charge — Tempo mainnet or Moderato | | Payout terms | No `splits` or other [refused terms](#what-the-router-refuses), as for a paid charge | | `id` | Present | | `realm` | Exactly the host of the URL being called | | `expires` | Present, in the future, and at most **10 minutes** away | A challenge that fails any check isn't answered, and the call is refused with `422 BCK.ROUTER.0035`. When a service sends both an MPP proof challenge and an [x402 Sign-In-With-X](/docs/products/catalog/router/rails-x402#sign-in-with-x-siwx) challenge, the Router answers the MPP one first and falls back to SIWX only if the MPP one is refused. The proof is signed with your **own wallet's key**, and only on a call that qualifies as a follow-up of a payment that wallet made. [Getting your results](/docs/products/catalog/paid-results) lists every condition. ## Receipts and settlement On a paid response an MPP merchant returns a **`Payment-Receipt`** header. In mode B the Router decodes it and stores its `reference` as the record's `txHash` — for `tempo`, the on-chain settlement transaction hash. * Receipt present and valid → record `Settled`. * Receipt missing, oversized, or malformed → record stays **`Issued`**. The hop succeeded and you got your resource; only the settlement anchor is pending. This is a normal state, not a failure, and the Router will not fail an already-paid call over a bad receipt. * Merchant returns another 402 to the paid hop (it rejected the credential) → record `Failed`. > [!NOTE] > > In **mode A** the Router isn't in the request path, so it never sees the receipt. Closing the record means decoding the receipt yourself and reporting the reference — which needs the MPP codec. This is the main reason to prefer mode B on this rail. The reference is merchant-controlled and stored **unverified** — see [how it works](/docs/products/catalog/router/how-it-works#how-settlement-gets-recorded). ## Card-funded MPP Some MPP merchants advertise `method="stripe"` instead — a card-funded rail where the Router mints a Shared Payment Token from your enrolled card rather than pulling a stablecoin. The API surface is identical: same endpoints, same Delegation model, same ledger. The differences that matter: * It's funded by a **card** Delegation, not a crypto one. A crypto Delegation fails on this rail and vice versa. * There's **no recipient allowlist** — a card Delegation is deliberately not bound to a seller, so the guardrails are the spending cap and the expiry. * Settlement is a payment-processor reference rather than a transaction hash, and it isn't known until the merchant redeems — so the record stays `Issued` pending reconciliation. * **There's no balance to pre-check, so there isn't one.** Where the chain-funded rail reads your balance before signing, this one simply attempts the card. A decline surfaces as the same **`402 BCK.ROUTER.0009`**, and nothing is minted and no budget is reserved — but you've had a real decline on your card, not a check that spared you one. > [!WARNING] > > This rail is **feature-flagged off by default and sandbox-only** while the underlying token issuance is still in limited availability. With the flag off, a card-funded payment is refused with `400 BCK.ROUTER.0001` before anything is minted. Don't build against it in production yet. ## Sessions (payment channels) Some MPP merchants sell only over **`intent="session"`**: a one-way payment channel instead of a payment per call. Your wallet locks a **deposit** in an on-chain escrow at the first call, and every call after that carries a signed, **cumulative** voucher rather than a transaction. The merchant can take at most the highest voucher it holds, never more than the deposit, and whatever it did not take comes back to your wallet when the channel closes. > [!NOTE] > > Sessions are **on in Nevermined's production deployments.** On a deployment where they are off (`ROUTER_MPP_SESSION_ENABLED`, below), a service that offers only a session is refused with `400 BCK.ROUTER.0001`. How the Router pays a session: * **Mode B only.** `POST /router/route`, `/router/svc/` and `/router/proxy` pay a session; `POST /router/payments` refuses one with **`400 BCK.ROUTER.0041`**, because the Router has to read the merchant's receipt after every call to keep the channel consistent, and in mode A it never sees it. * **Charge first.** A service that offers both a `charge` and a `session` is paid over `charge`, whatever order it lists them in. * **One channel per merchant.** The Router keeps one channel per wallet, merchant and token, and reuses it for every call. Concurrent calls to the same merchant are signed one after the other on that channel. * **The deposit** is the smallest of the merchant's suggested deposit, **\$10** by default, your Delegation's remaining budget less what your wallet already holds unspent in its other open channels (below), and your wallet balance minus a little for gas. If even one call cannot fit, the call is refused before anything is signed: `402 BCK.ROUTER.0009` for the wallet, `402 BCK.ROUTER.0003` for the budget. * **Your budget moves by the price of each call, never by the deposit.** The deposit is locked, not spent: it leaves your wallet balance, but it is not charged to your Delegation, and it comes back at close. What it does do is hold room: the unspent deposit in your other open channels is subtracted from what a new channel, or a top-up, may lock. So `402 BCK.ROUTER.0003` can answer a first call to a new merchant while `GET /delegation/{id}` still shows budget left; that room comes back as those channels close. * **When the deposit is used up**, the Router **tops the channel up**: it sends the merchant a signed top-up of the deposit, the way the MPP client does, and pays the call once the merchant confirms it. The channel's deposit never grows past **\$10** in total by default. A top-up your Delegation or wallet cannot cover is refused like an opening deposit, `402 BCK.ROUTER.0003` or `402 BCK.ROUTER.0009`, and the channel stays open. A channel already at the \$10 limit, a merchant that refuses or does not confirm the top-up (or refuses the call right after it), or a merchant that takes no top-up at all moves the channel to **closing**, and the call is refused with **`409 BCK.ROUTER.0042`** (retryable). Retry later with the same `requestId`: the next call after the close opens a new channel, and the close refunds the unspent deposit to your wallet. * **Busy, not refused.** When another call on the same channel holds it too long, your wallet's signer or balance read does not answer in time, or a top-up of the channel is still in flight or the service could not be reached to take one, the call is refused with **`503 BCK.ROUTER.0043`** (retryable, `params.stage` says which) before anything is signed. Retry after a few seconds with the same `requestId`. * **A channel the merchant cannot use is closed, not retried forever.** If the merchant refuses the call that opened the channel, never acknowledges the channel, or the opening call never reached it, the channel moves to closing, and the next calls answer `0042` until it has closed. * **The routing fee is collected later, never per call.** A session call is charged the same [routing fee](/docs/products/catalog/router/how-it-works#fund-for-the-amount-plus-the-fee) as any other, on its price (never on the deposit), and your budget reserves it with the call. It is not a transfer of its own: the Router adds up your session fees and collects them in one transfer from your wallet, with your other Tempo routing fees, once your calls were delivered. A call the merchant did not deliver is not charged it. Where that collection cannot happen — the payment is funded by an organization wallet, or the deployment does not collect session fees on that network — the call is refused with **`422 BCK.ROUTER.0044`** (`params.cause`: `org-wallet` or `network`) before anything is signed. From an organization wallet, pay from a delegation funded by your own wallet instead. * **Settled per channel, when it closes.** A session call is no transaction of its own (the receipt's reference is the channel), so its payment record reads `Issued`, `deliveryStatus: "pending"`, until its channel closes and the Router has reconciled it: at best 15 minutes after the channel's last call plus up to 10 minutes, longer for a channel kept busy or one the merchant will not close (the escrow's grace period applies). The money moves once, at the close, and the Router then compares what the escrow paid the merchant with the channel's calls, crediting delivered calls first: * a delivered call the merchant was paid for becomes `Settled`, its `txHash` the channel's close transaction; * a call the merchant was not paid for gives its price back to your Delegation budget, and reads `Settled` if it was delivered anyway or `Failed` if not; * a call the merchant was paid for without delivering it stays charged: `deliveryStatus` `charged_not_delivered` after a refusal, `charged_unconfirmed` after an error answer. That is the merchant taking money it should not have, and the reconciliation flags each such call to Nevermined; * a call the merchant charged only part of releases the rest of its price. You cannot report a session payment settled yourself: `POST /router/payments/{id}/settled` answers `409 BCK.ROUTER.0005`, because the channel's close is its settlement. **Gas.** The merchant decides whether the transactions that open and top up the channel are gas-sponsored: it says so with `feePayer` in its `402`. When it doesn't sponsor them, your wallet pays a small amount of gas in the channel's token, a fraction of a cent of USDC.e ($0.00004 to $0.0002 per open, measured on Tempo mainnet in October 2026). That gas is **outside your Delegation's spending cap**: the cap moves only by what the calls cost and the routing fee. On the Catalog, QuickNode sponsors the gas and Conduit does not. The same checks as on a charge apply before anything is signed — method, chain, recipient, the asset allowlist, your Delegation's recipient scope — plus a few of the channel's own: the escrow must be Tempo's channel escrow, gas must be paid in the channel's token, and the service must bill per request. ### Sessions in the Catalog These merchants sell only over a session: * **QuickNode** (`quicknode-mpp`, `POST session/`): JSON-RPC, on Tempo's original channel escrow, \$0.00001 a request. Its other endpoints are paid per call. * **Conduit** (`conduit`, `POST tempo/`): JSON-RPC for Tempo mainnet, on the Tempo channel precompile, \$0.00005 a request. * **Dune** (`dune-mpp`): SQL over indexed blockchain data, on Tempo's original channel escrow. Pay it from a crypto (`erc4337`) Delegation only; Nevermined credits don't pay Dune. In production, only QuickNode's session endpoint is listed so far (see the note below); call a listed endpoint like any other slug. The channel, its deposit and its close are the Router's job, not yours. A listed Conduit or QuickNode endpoint can also be paid with [Nevermined credits](/docs/products/catalog/router/subscription): the call costs its published rate in credits, and Nevermined's treasury holds the channel. > [!NOTE] > > Dune and Conduit are not listed in the production Catalog yet, and their slugs answer `404 BCK.CATALOG.0001`. Meanwhile you can pay Conduit by its URL from a crypto Delegation, which opens and closes the channel the same way: > > ```bash theme={null} > curl -sX POST "$NVM_API_URL/api/v1/router/route" \ > -H "Authorization: Bearer $NVM_API_KEY" -H "Content-Type: application/json" \ > -d '{ "delegationId": "'"$NVM_DELEGATION_ID"'", "url": "https://mpp.conduit.xyz/tempo/", > "method": "POST", "body": { "jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": [] }, > "requestId": "conduit-block-1" }' > ``` > > Credits pay only listed endpoints, so they don't pay Conduit by URL. A Dune query is three calls, all on one channel: ```bash theme={null} # 1. Run the query: $4.00, which opens the channel (a deposit of up to $10 is locked). curl -sX POST "$NVM_API_URL/api/v1/router/route" \ -H "Authorization: Bearer $NVM_API_KEY" -H "Content-Type: application/json" \ -d '{ "delegationId": "'"$NVM_DELEGATION_ID"'", "slug": "dune-mpp", "path": "api/v1/sql/execute", "method": "POST", "body": { "sql": "SELECT 1" }, "requestId": "dune-select-1" }' # → body.execution_id # 2. Poll its status: free (a voucher that adds nothing), repeat until is_execution_finished. curl -sX POST "$NVM_API_URL/api/v1/router/route" \ -H "Authorization: Bearer $NVM_API_KEY" -H "Content-Type: application/json" \ -d '{ "delegationId": "'"$NVM_DELEGATION_ID"'", "slug": "dune-mpp", "path": "api/v1/execution//status", "method": "GET", "requestId": "dune-select-1-status-1" }' # 3. Fetch the results: priced by Dune per execution ($1.00 per MB of result data). curl -sX POST "$NVM_API_URL/api/v1/router/route" \ -H "Authorization: Bearer $NVM_API_KEY" -H "Content-Type: application/json" \ -d '{ "delegationId": "'"$NVM_DELEGATION_ID"'", "slug": "dune-mpp", "path": "api/v1/execution//results", "method": "GET", "requestId": "dune-select-1-results" }' ``` Your Delegation is charged $4.00 plus the results price and the routing fee, never the deposit. About 15 minutes after the last call the Router closes the channel: Dune is paid what the calls cost and the rest of the deposit returns to your wallet. Once the Router has reconciled the close, the three payment records read `Settled`. Quote a results call first (`POST /router/quote` with the same `slug` and `path`): Dune prices each execution, and quotes an execution id it does not know at $1,024. ## Operator configuration | Env var | Required | Purpose | | - | - | - | | `ROUTER_TEMPO_ASSETS_` | **Yes** | Comma-separated allowlist of payment-token addresses settleable on that chain. **Fail-closed** — unset rejects everything. | | `ROUTER_TEMPO_RPC_URL_` | No | Override RPC endpoint for that chain. Defaults to the chain's public RPC. | | `ROUTER_STRIPE_SPT_ENABLED` | No | Master switch for the card-funded rail. Fail-closed; sandbox only. | | `ROUTER_MPP_SESSION_ENABLED` | No | Master switch for paying session merchants. Default `false`: a session is refused as if unsupported. | | `ROUTER_MPP_SESSION_MAX_DEPOSIT` | No | The most one channel may hold in escrow, in US dollars of its stablecoin. Default `10`. | ## Next > [card] [The x402 rail](/docs/products/catalog/router/rails-x402) > > The other supported protocol. > [card] [Payment ledger](/docs/products/catalog/router/ledger) > > Reading and reconciling what you spent. # The x402 rail Source: https://nevermined.ai/docs/products/catalog/router/rails-x402 Paying x402 services through the Router — networks, assets, schemes, and how the 402 is negotiated. x402 is the HTTP-native payment protocol where a server answers an unpaid request with **HTTP 402** and an `accepts` array describing what it will take. The Router reads that array, picks an option it can fund, signs the payment from your wallet, and hands back a credential. You don't need the service to know anything about Nevermined. If it speaks x402, it's payable. ## What a challenge looks like The Router supports both protocol versions and works out which one it's talking to. > [tab] x402 v2 > > Requirements arrive base64-encoded in a **`PAYMENT-REQUIRED`** response header. The credential goes back in a **`PAYMENT-SIGNATURE`** request header. > [tab] x402 v1 > > Requirements arrive in the **JSON body** of the 402. The credential goes back in an **`X-PAYMENT`** request header. > > ```json theme={null} > { > "x402Version": 1, > "accepts": [ > { > "scheme": "exact", > "network": "base-sepolia", > "maxAmountRequired": "1000", > "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", > "payTo": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", > "maxTimeoutSeconds": 60, > "extra": { "name": "USDC", "version": "2" } > } > ] > } > ``` In [mode B](/docs/products/catalog/router/how-it-works) you never see any of this — the Router probes, negotiates the version, and pays. You only need the shape above if you're using mode A and passing the challenge yourself as `target`. ## What's supported | | Supported | | - | - | | **Scheme** | `exact` — an EIP-3009 `TransferWithAuthorization`, a single-use signed authorization the merchant redeems | | **Networks** | `base` (chain `8453`) and `base-sepolia` (chain `84532`), by name or as CAIP-2 (`eip155:8453`) | | **Assets** | `USDC` and `EURC` — 6-decimal stablecoins | Anything outside that isn't payable on this rail today: other schemes, other chains, and non-EVM networks such as Solana. > [!NOTE] > > A **mixed-chain 402 still works** as long as one option is fundable. If a service advertises both a Solana option and a Base option, the Router skips the one it can't parse and pays the Base one. It only fails if *no* entry survives the filter — that's `400 BCK.ROUTER.0001`. ### How an option gets chosen Given several fundable entries, the Router filters to `scheme: "exact"` on a funded network with a funded asset, then prefers **USDC**. The asset symbol is resolved from the entry's **`asset` address**, matched against the canonical token addresses for that chain — never from `extra.name`, which is something else entirely (see below). A token the Router doesn't recognise on that chain isn't fundable, however the entry labels it. ### `extra.name` is the EIP-712 domain, not a ticker `extra.name` and `extra.version` are the settlement token's **EIP-712 domain** — the `name()` and `version()` the token contract itself signs under, and what the payment authorization is signed against. They are frequently *not* the ticker: canonical Base-mainnet USDC signs under `"USD Coin"`, while the Base Sepolia deployment signs under `"USDC"`. Both fields are **required**, and the Router checks them **byte for byte** against the domain it holds for that token. It signs under its own value, never one taken from the 402. A service that advertises a domain its own token does not sign under gets `400 BCK.ROUTER.0012`, with nothing signed, charged or reserved — such an authorization is unspendable anyway, so there is nothing to lose by stopping. > [!NOTE] > > **If you're the seller:** copy `extra.name`/`extra.version` from the token contract's `name()` and `version()`, exactly. Guessing the ticker is the usual way to trip this. ## Money and budget Amounts are in the asset's smallest unit. USDC and EURC have 6 decimals, so: ``` 1_000_000 atomic units = 1 USDC = 100 cents 10_000 atomic units = 1 cent ``` Your Delegation cap is denominated in **cents**, so every payment is converted and **rounded up** to the next whole cent before it's checked against the cap. A payment of 5,000 atomic units (half a cent) reserves 1 cent. Sub-cent calls therefore cost you a full cent of budget each — worth knowing if you're planning a long loop of very cheap calls. The `settlement.approxCents` field on every response tells you what the merchant charged. A [routing fee](/docs/products/catalog/router/how-it-works#the-routing-fee), when one is configured, is reserved on top of it — `fee.capChargedCents` is the total that came off your cap. ## Funding your wallet The payment is a **pull**: your signature authorizes the merchant to take the amount from your own wallet. So the wallet must already hold that asset **on that chain** before you call. Get the address from your Delegation's `providerPaymentMethodId` — see [step 3 of the quickstart](/docs/products/catalog/router/quickstart#3-fund-your-wallet). > [!WARNING] > > **On x402 the Router does not check your balance before signing.** A short wallet isn't refused up front: the credential is minted, your Delegation budget is reserved, and the shortfall only appears when the merchant attempts the transfer on-chain. The payment then lands as `Failed`, and the reserved **merchant leg** comes back only once the reconciler has confirmed the authorization expired **unconsumed** — it is kept for good only if the merchant did take the money. Until then your cap stays reserved. (`402 BCK.ROUTER.0009` is an [MPP-only](/docs/products/catalog/router/rails-mpp#funding-your-wallet) error; this rail never raises it.) > > Only a routing fee reserved on top can be credited back, and only on [the closed list of paths that release one](/docs/products/catalog/router/how-it-works#when-a-fee-is-not-collected) — never the merchant leg. > > Fund for the merchant's amount **plus** any [routing fee](/docs/products/catalog/router/how-it-works#fund-for-the-amount-plus-the-fee) — the fee is a second transfer from the same wallet, so the quoted price alone doesn't cover both. The asset to send is the one the service's 402 advertises — `USDC` or `EURC`, 6 decimals, on the network in that entry. Base mainnet USDC is `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`. > [!WARNING] > > `base` is **Base mainnet** and moves real funds; `base-sepolia` is the testnet. **Which of them your deployment will fund is decided by the environment you are pointed at, not by the service.** A sandbox deployment funds testnets only and a live deployment funds mainnet only — that split is the real-money firewall and an operator cannot widen it. If you call a mainnet service from sandbox, no entry survives the filter and you get `400 BCK.ROUTER.0001`. Read `settlement.network` on the response to be sure what just happened. ## Authorization lifetime The signed authorization carries a validity window, capped by the operator (one hour by default) with a small allowance for clock skew between you and the merchant. A merchant asking for a longer window than the operator permits gets the operator's cap, not its own request. In practice this only matters in mode A: if you mint a credential and sit on it, it can expire before you redeem it. The budget stays reserved and the record stays `Issued`. Mint credentials when you're about to use them. ## Sign-In-With-X (SIWX) An async service may guard its result endpoint with an x402 `402` that offers **no payment** — an empty `accepts` — and carries a `sign-in-with-x` extension instead. It's asking you to sign in as the wallet that paid, following [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) (Sign-In with Ethereum). The Router answers it for you on a qualifying follow-up call: it signs an EIP-4361 message with your **own wallet's key** (EIP-191), sends it base64-encoded in a `Sign-In-With-X` request header, and retries once. Nothing moves — a sign-in message can't become a transfer or a permit. The response comes back with `paid: false`, and no payment, fee or ledger row is created. Before signing, the Router checks every field the service supplied: | Field | Requirement | | - | - | | `accepts` | Empty. A `402` that offers a payment is paid, never answered with a sign-in | | Chain | `eip155:8453` (Base) or `eip155:84532` (Base Sepolia), with signature type `eip191` | | `domain` | Exactly the host of the URL being called | | `uri` | Exactly the URL being called | | `version` | `1` | | `nonce` | Alphanumeric, 8–128 characters | | `issuedAt` | An ISO-8601 UTC time, no more than 10 minutes old and no more than 60 seconds in the future (tolerated clock skew) | | `expirationTime` | Present, in the future, and at most **10 minutes** away | The Router builds the message from those validated fields only. Anything else the service wrote — `statement`, `resources`, `requestId`, `notBefore` — is dropped, so no merchant-written text is ever signed. A challenge that fails any check isn't answered, and the call is refused with `422 BCK.ROUTER.0035`. **Solana SIWX is not supported**, and neither is any other EVM chain. When the service sends an [MPP zero-amount proof](/docs/products/catalog/router/rails-mpp#zero-amount-charges-proving-you-paid) challenge too, the Router answers the MPP one first. [Getting your results](/docs/products/catalog/paid-results) lists the conditions a call must meet before the Router signs anything. ## Settling the record When the merchant accepts the credential it returns a settlement reference in a `PAYMENT-RESPONSE` (or `X-PAYMENT-RESPONSE`) header — the on-chain transaction hash. * **Mode B** reads it and closes the record for you: status `Settled`, hash on the ledger. * **Mode A** leaves the record `Issued` until you report it with `POST /api/v1/router/payments/{paymentId}/settled`. See [the ledger](/docs/products/catalog/router/ledger) for what those statuses mean and how to reconcile them. ## Operator configuration These are set per deployment, not per call. You only need them if you run your own Nevermined deployment. | Env var | Default | Purpose | | - | - | - | | `ROUTER_FUNDED_NETWORKS` | derived from `ENVIRONMENT` | Networks the Router will fund a payment on. Sandbox derives the testnets, live derives mainnet; only a local/dev instance falls back to the permissive `base,base-sepolia`. On a deployed instance this variable can only **narrow** the derived set — it can never add a network, so it cannot move a box across the sandbox/live firewall. Setting it to an empty string is an explicit "fund nothing", not "use the default". | | `ROUTER_FUNDED_SYMBOLS` | `USDC,EURC` | Asset symbols it will pay in | | `ROUTER_PREFER_SYMBOL` | `USDC` | Which symbol wins when a 402 offers several | | `ROUTER_MAX_AUTH_TTL_SECS` | `3600` | Ceiling on the signed authorization's validity window | ## Next > [card] [The MPP rail](/docs/products/catalog/router/rails-mpp) > > The other supported protocol, and how it differs. > [card] [Guardrails](/docs/products/catalog/router/guardrails) > > Every check the Router runs before it signs. # Pay with Nevermined credits Source: https://nevermined.ai/docs/products/catalog/router/subscription Pay catalog services with Nevermined credits, free at sign-up, by subscription or in top-up packs: Nevermined pays the merchant and an undelivered call costs nothing. The Router normally pays a merchant from **your** money: a Delegation caps the spend and your wallet or card funds it. **Nevermined credits** are the other way to pay. When your agent calls a catalog service with credits, **Nevermined pays the merchant** from its own treasury and your call costs a fixed number of credits that Nevermined publishes for that endpoint. You get credits in three ways: * **Free credits when you sign up.** A new account that signs up with a verified email gets 2,000 credits, with no card and no subscription. See [Free credits](#free-credits). * **Top-ups.** Turn them on and a pack of 10,000 credits that never expire is charged to your card whenever your credits run out, up to a monthly limit you set — with or without a subscription. See [Top-ups](#top-ups). * **A Nevermined Subscription.** You pay Nevermined a monthly price and get a monthly allowance of credits. See [Subscribe](#subscribe). All your credits are [one balance](#credits), and they're spent the same way whatever their source. That changes three things for an agent: * **No wallet, no Delegation, no funding.** There's no wallet to fund and nothing on-chain for your agent to sign. * **A price you see before you call.** Each endpoint has a **rate** on Nevermined's rate card — credits per call — and the rate shown when you call is what the call costs, whatever the merchant charges at that moment (up to the rate's bound). * **You only pay for what's delivered.** Credits are kept only when the merchant answers with a `2xx`. Anything else and the credits come back. > [!NOTE] > > **Nevermined credits are not plan credits.** Elsewhere in these docs, *credits* are what a seller's [credits-based plan](/docs/integrate/patterns/payment-models#credits-based-plans) grants for that seller's own agent, and a *subscription* is a seller's [time-based plan](/docs/integrate/patterns/payment-models#time-based-plans). Nevermined credits and the Nevermined Subscription are neither: they're Nevermined's own, for **buyers**, and the credits are spent only through the Router, on catalog services. On this page, "credits" always means Nevermined credits. Credits and a Delegation live side by side. Some services can't be paid with credits (see [What credits can pay](#what-credits-can-pay)); keep a Delegation for those. ## Free credits A new Nevermined account that signs up with a verified email gets **2,000 free credits**, once, to try the catalog. You don't need a subscription or a card to receive them or to spend them. * **Who gets them.** A new account that signs up with a verified email address: an email code, or a Google account. Accounts that existed before free credits launched don't get them, and neither do wallet-only sign-ups or accounts created for you by an organization, an embedded widget or an SDK. * **Once.** They're granted once per account and once per email address in each environment. Addresses that differ only in letter case, in a `+` suffix or, for Gmail, in dots count as the same address. * **Nothing to claim.** They're added automatically when you first sign in — or at a later sign-in, while the offer lasts — and an email confirms how many you got and when they expire. * **Live and Sandbox.** Each environment grants its own credits. Sandbox credits pay the Sandbox test services, and Live credits pay live services. * **They expire 30 days after they're added.** Unused free credits are lost when they expire. They aren't refunded or replaced, and credits returned for an undelivered call aren't restored if they've expired by then. A reminder email goes out 5 days before they expire, if you still have some. * **One balance.** If you also subscribe, your free credits and your monthly allowance are one balance, spent earliest expiry first. See [Credits](#credits). Free credits are a promotional offer, available while the offer lasts. Nevermined may remove unused free credits obtained or used in breach of its terms, for example by opening more than one account. To check whether the offer is open, and what it grants, read the public offer. It needs no API key: ```bash theme={null} curl -s "$NVM_API_URL/api/v1/credits/welcome/offer" ``` ```json theme={null} { "offer": { "credits": "2000", "ttlDays": 30 } } ``` `offer` is `null` while the offer is closed. See the [API reference](/docs/api-reference/router/welcome-credits-offer). ### Spend your free credits **1. Sign up** Sign up in the [Nevermined Catalog](https://nevermined.app/catalog/) or the [Nevermined App](https://nevermined.app) with an email code or Google. Your credits appear in the catalog's account menu under **Credits**, and on the catalog's **Get started** page as **Your free credits**. In the Nevermined App, **Catalog Subscription** in the **Buy** view shows them with their expiry and your recent usage. **2. Create a personal API key** Credits are spent with a **personal** API key: one with no organization. The catalog's **Get started** page links to the API key generator with a personal agent key selected. **3. Connect your agent** Connect the [Catalog MCP](/docs/mcp/catalog-mcp/overview) with that key. [`pay_service`](/docs/mcp/catalog-mcp/pay-service#pay-with-subscription-credits) then pays in credits by default whenever they can pay the call. Or call the Router's [credits route](#pay-a-call-with-credits) directly. Its path says `subscription`, but it spends any Nevermined credits, with or without a subscription. An assistant you connect through OAuth, such as the Catalog MCP from Claude.ai or ChatGPT, can spend your credits too, if you allow it. See [Who can spend your credits](#who-can-spend-your-credits). ## Top-ups Top-ups keep your agent going when your credits run out. Turn them on, and each time a call needs more credits than you can spend, Nevermined charges your card for a **pack of 10,000 credits that never expire** and the call goes ahead, up to a monthly limit you set. They're for every personal account, with or without a subscription. * **A pack is USD 10 plus applicable taxes** for 10,000 credits. The tax is calculated from your billing address, and the total is shown before you pay. * **Top-up credits never expire.** They join your [one balance](#credits). The credits that expire soonest are spent first, so top-up credits are spent last, after your free credits and your subscription's allowance. * **Off by default.** You turn top-ups on by buying your first pack, and the card you pay it with pays the packs after it. * **Only when a call needs it.** While top-ups are on, a pack is charged automatically when a call costs more credits than you can spend, then the call is paid from your balance, which now includes the pack. A running call charges at most one pack, and **only a call made with your personal API key** charges one automatically — a call made through an OAuth connection never does. * **An agent can also refill ahead of a call.** Within the limit you set, an agent can charge a pack itself *before* it runs out — `POST /api/v1/credits/topups/pack`, or [`top_up_credits`](/docs/mcp/catalog-mcp/top-up-credits) on the Catalog MCP — with no new approval. For an assistant connected through OAuth this is the only way to get a pack, and only if you ticked **Let this assistant top up my Nevermined credits**. Turning top-ups on and setting the monthly limit still happen only here, in the App. * **Up to your monthly limit.** You choose a monthly limit in whole US dollars, before tax; there's no default. A pack is charged only while the packs bought this calendar month (UTC), that one included, stay within it. The lowest limit is the price of one pack, and the highest is USD 50, Nevermined's maximum. * **Not withdrawable.** When you turn top-ups on, you ask for each pack's credits to be made available immediately and give up the 14-day right of withdrawal, for your first pack and every pack charged automatically after it. See [Refunds and disputes of a pack](#refunds-and-disputes-of-a-pack). * **Live and Sandbox.** Each environment has its own top-ups, packs and limit. A Sandbox pack is paid in test mode, and its credits pay the Sandbox test services. > [!NOTE] > > These are **Nevermined credits** bought from Nevermined, spent only through the Router. They're not the [automatic credit top-ups](/docs/integrate/patterns/top-up) of a seller's plan, which a Delegation pays when a request settles. ### Turn on top-ups You turn top-ups on in the [Nevermined App](https://nevermined.app), on the same page as your credits. **1. Open the Top-ups panel** Open **Catalog Subscription** in the sidebar — it's in the **Buy** view — or go straight to [nevermined.app/subscription](https://nevermined.app/subscription). The catalog's **Get started** page links there too, with **Set up top-ups**. In the **Top-ups** panel, click **Turn on top-ups**. **2. Set your monthly limit** Type a monthly limit in US dollars, before tax. The panel says how many packs a month it allows: a USD 30 limit allows up to 3 packs a month. **3. Give the consents** Tick both boxes. The first agrees that Nevermined charges your card USD 10 plus applicable taxes for each pack of 10,000 credits that never expire: the first pack now, and another automatically each time your credits run out, up to your monthly limit. The second asks for each pack's credits to be made available immediately and acknowledges that you lose your 14-day right of withdrawal once they are, for your first pack and every pack charged automatically after it. **Top-up terms** below the boxes has the full terms. **4. Pay for your first pack** Choose a saved card, or **Add a card** and enter its details. Confirm your billing country — with a postal code in the US and Canada — and the panel shows your total, such as **Total today: $10.81, including $0.81 tax**. Click **Pay with •••• 4242**. Your bank may ask you to confirm the payment (3-D Secure). **5. Your credits arrive** Once the payment is confirmed, top-ups are on, the pack's 10,000 credits are in your balance, and an email sends you the receipt. The same card pays the packs charged automatically after this one. ### Manage top-ups The **Top-ups** panel shows what you bought this month against your limit, such as **$10 of $30 this month**, and the card that pays the packs. From there: * **Change limit** sets a new monthly limit. A limit below what you've already bought this month stops packs for the rest of the month. * **Change card** chooses another of your cards to pay the packs. * **Turn off top-ups** stops further packs. The credits you've bought stay in your balance. To turn top-ups on again, buy a pack again. * **Packs** lists your packs, newest first: when each was bought (**At checkout** or **Automatic**), its credits, price and tax, its status (**Being charged**, **Paid**, **Declined**, **Not charged** or **Refunded**), and a link to its receipt. When this month's packs reach your limit, the panel says so: no more packs are charged until the first day of next month (UTC), unless you raise the limit. While top-ups are on or paused, the catalog's account menu also shows where they stand, such as **Top-ups on, $10 of $30 this month**. Nevermined emails you a receipt for every pack, a notice when this month's packs reach 50%, 75%, 90% and 100% of your limit (only the highest, when one pack crosses several), a notice when an automatic pack can't be charged and top-ups pause, and a confirmation when Nevermined support refunds a pack. ### When top-ups pause An automatic pack is charged while you're away, so a card that can't pay it **pauses** top-ups instead of retrying. While they're paused, no pack is charged, and a call that needs more credits than you can spend is refused: a subscriber in good standing gets `402 BCK.SUBSCRIPTION_ROUTER.0009` with `params.topUps: "paused"`, and anyone else gets `402 BCK.SUBSCRIPTION_ROUTER.0002`. The panel says why: | The panel says | What happened | To resume | | - | - | - | | *your card declined the last automatic pack* | The card was declined. | **Buy a pack to resume**: pay for one pack with a card, as when you turned top-ups on. | | *your bank asked to confirm the last automatic pack* | The bank asked for 3-D Secure, and nobody was there to confirm it. | **Buy a pack to resume**. | | *the card that pays them can no longer be used* | The card was removed, or can no longer pay. | **Change card**, or **Buy a pack to resume**. | A declined pack charges nothing, and appears in **Packs** as **Declined** or **Not charged**. A card dispute stops top-ups too, but it isn't a pause you can lift from the panel: every credit is frozen and calls are refused with `0015`. A dispute on a pack shows in the panel as *Top-ups are stopped and your credits are on hold*; a dispute on your subscription doesn't show there. See [Refunds and disputes of a pack](#refunds-and-disputes-of-a-pack). ### Refunds and disputes of a pack Top-up packs can't be withdrawn: when you turned top-ups on, you asked for each pack's credits to be made available immediately and gave up the 14-day right of withdrawal, for every pack. Their credits stay in your balance and never expire. For a refund, contact Nevermined support. A refund through support removes the pack's unused credits from your balance and returns their share of what you paid, tax included. The pack then reads **Refunded** in **Packs**, and it still counts toward that month's limit. If you **dispute** a pack with your card issuer, its unused credits are removed, none of your credits — free, top-up or subscription — can be spent, and top-ups stop while the dispute is open. If it's decided in Nevermined's favour, the credits it removed are restored as top-up credits, and top-ups resume once no other dispute on a pack holds them. If it's decided in your favour, your credits stay unable to spend. ## Subscribe You buy the subscription in the [Nevermined Catalog](https://nevermined.app/catalog/), on the subscription page. **1. Open the subscription page** In the catalog, click **Subscription** in the header, or **Subscribe for \$20 a month** on the catalog's home page. Log in with your Nevermined account if the page asks you to. **2. Choose the subscription** The page compares the two ways to pay for the catalog: **Pay per call** from a budget you set up yourself, or the **Nevermined Subscription**. The subscription is **USD 20 per month plus applicable taxes**, and it grants **20,000 credits** each month. Click **Choose Subscription**. **3. Give the consents** Tick both consents. The first agrees that the subscription renews automatically every month until you cancel. The second asks for your credits to be made available immediately, and acknowledges that you lose the 14-day right of withdrawal once they are. Then click **Continue to payment**. **4. Pay on the same page** Stripe's secure payment form opens in the page. Accept the Nevermined Subscription terms in the form, then pay. VAT or sales tax is calculated from your billing address and added on top, and the total is shown before you pay; a business can add its tax ID. Your bank may ask you to confirm this first payment (3-D Secure). **5. Your credits arrive** After you pay, you land on your subscription page in the Nevermined App. Your credits appear there as soon as Stripe confirms the payment. ### Personal accounts only The Nevermined Subscription, top-ups and Nevermined credits belong to a **personal account**: an organization can't subscribe or buy top-ups. * **Spend credits with a personal API key** — one with no organization tag — and without an `X-Current-Org-Id` header. A call made in an organization you're an active member of (that header, or that organization's API key) is refused with `402 BCK.SUBSCRIPTION_ROUTER.0002`, and it **never** falls back to your personal credits. * **Sandbox and Live are billed separately.** Each workspace has its own subscription and its own credits, and the subscription page shows which workspace you're subscribing for. A Sandbox subscription is paid in Stripe's test mode, and its credits pay the testnet services listed in Sandbox — on the catalog's services page, under **Sandbox test services**. ## Manage your subscription In the [Nevermined App](https://nevermined.app), open **Catalog Subscription** in the sidebar — it's in the **Buy** view, so switch to it first if the App opens on Sell — or go straight to [nevermined.app/subscription](https://nevermined.app/subscription). (If you already subscribe, the catalog's subscription page takes you there too.) The page shows: * **Credits left this month**, your plan and monthly allowance, and the date your allowance resets. * **Credits**, when you also hold free or top-up credits: how many you can spend now, and when each part of them expires. * **Top-ups**, where you turn them on and manage them. See [Manage top-ups](#manage-top-ups). * **Manage billing**, which opens Stripe's customer portal, where you can update your payment method. * **Cancel subscription**, which opens Stripe's cancellation step. A cancellation takes effect at the end of the current billing period, and you can use the rest of this month's credits until then. * **Invoices**, with each invoice's status. An invoice that was refunded reads **Refunded** or **Partially refunded**; if its refund state can't be read, it reads **Status unavailable**. A refund can take 5–10 business days to appear on your card statement. **What your credits paid for is in Purchases.** In the Nevermined App's **Purchases** page, a call paid with credits shows **Subscription** under *Paid with* and its cost in credits (struck through when the credits came back). Filter by **Subscription credits** to see only those, and the **Credits used · this cycle** tile adds up the current billing period. ## Credits All the credits your account holds are **one balance**, whether they're free credits, top-up credits or your subscription's monthly allowance. A call costs its rate whatever the source, and **the credits that expire soonest are spent first**. * **One allowance per billing period.** Your plan includes a monthly allowance of 20,000 credits, available once each monthly invoice is paid. Changes to the price or the monthly allowance are announced in advance, and you can cancel before they apply. * **The allowance expires at the end of the period.** Unused allowance credits don't roll over; your allowance resets when the next period's invoice is paid. Free credits expire 30 days after they're added, whatever your billing period. * **Top-up credits never expire,** so they're spent last. * **An overdue renewal freezes only the allowance.** While a subscription payment is overdue, its allowance credits can't be spent until the payment goes through. Your free and top-up credits still can, and top-ups stay on. But a call that the frozen allowance would have covered is refused (`0016`) instead of charging a pack: paying the overdue invoice is what unlocks it. * **A card dispute freezes everything.** While a card payment you made to Nevermined — for the subscription or for a top-up pack — is disputed with your card issuer, none of your credits can be spent, and top-ups stop. * **They are not money.** Credits have no cash value, can't be cashed out, and can't be transferred to another account. Check your credits at any time, subscribed or not — it charges nothing: ```bash theme={null} curl -s "$NVM_API_URL/api/v1/credits/balance" \ -H "Authorization: Bearer $NVM_API_KEY" ``` ```json theme={null} { "total": "11500", "spendable": "11500", "parts": [ { "kind": "welcome", "credits": "1500", "expiresAt": "2026-11-26T09:12:44.000Z", "frozen": null }, { "kind": "topup", "credits": "10000", "expiresAt": null, "frozen": null } ], "nextExpiry": { "credits": "1500", "at": "2026-11-26T09:12:44.000Z" }, "topups": { "enabled": true, "monthlyLimitUsd": 30, "maxMonthlyLimitUsd": 50, "boughtThisMonthUsd": 10, "packPriceUsd": 10, "paused": null, "card": { "brand": "visa", "last4": "4242" } } } ``` * `spendable` is what a personal API key can pay with right now — read it rather than adding up your calls. `total` also counts frozen credits. * `parts` lists what's left by `kind` (`welcome` for free credits, `allowance` for a subscription's monthly allowance, `sla` for credits Nevermined added for a defective result, `topup` for top-up credits), in the order they're spent: earliest expiry first, never-expiring last. `expiresAt` is `null` on credits that never expire. * `frozen` is `null` on credits you can spend, `renewal_overdue` on an allowance frozen by an overdue renewal, and `dispute` on every part while a card dispute is open. * `nextExpiry` is the next credits to expire, or `null` when none of them expire. * `topups` holds your [top-up](#top-ups) settings, when top-ups are available to you. It's left out when they're not, or when they couldn't be read this time. In `topups`, amounts are US dollars before tax: * `enabled` is whether a pack is charged automatically when your credits run out. It's `false` until you buy your first pack, and after you turn top-ups off. * `monthlyLimitUsd` is your monthly limit, or `null` if you never set one. It's kept when you turn top-ups off. * `maxMonthlyLimitUsd` is the highest limit Nevermined allows. * `boughtThisMonthUsd` is what the packs bought this calendar month (UTC) cost — the figure your limit counts, refunded packs and a pack still being charged included. * `packPriceUsd` is the price of one pack, or `null` when no pack is on sale. * `paused` is `null`, or why no pack is being charged and since when: `{ "reason": "payment_failed", "since": "2026-10-19T10:00:00.000Z" }`. `reason` is `payment_failed` (the last automatic pack was declined), `action_required` (its card asked for authentication), `card_unavailable` (the card that pays packs can no longer pay; API version 1.84 or later — older versions read `payment_failed`) or `dispute` (a card dispute on a top-up pack freezes every credit). A dispute on your subscription freezes every credit too, but leaves `paused` at `null`: read `frozen` on the parts. See [When top-ups pause](#when-top-ups-pause). * `card` is the card that pays packs (`brand` and `last4`), or `null` when none is saved. You turn top-ups on and set the limit in the Nevermined App, not over the API: see [Manage top-ups](#manage-top-ups). An agent can read the limit (`GET /api/v1/credits/topups/pack`) and charge a pack within it (`POST` the same path, or [`top_up_credits`](/docs/mcp/catalog-mcp/top-up-credits)) — see [Top-ups](#top-ups). A caller with no credits gets `"total": "0"` and an empty `parts`. The balance is always your personal one: an organization tag on the key or an `X-Current-Org-Id` header is ignored. A call made in an organization never spends these credits, though (`402 BCK.SUBSCRIPTION_ROUTER.0002`). See the [API reference](/docs/api-reference/router/credits-balance). For your subscription itself — status, plan and reset date — read the subscription balance: ```bash theme={null} curl -s "$NVM_API_URL/api/v1/router/subscription/balance" \ -H "Authorization: Bearer $NVM_API_KEY" ``` ```json theme={null} { "subscribed": true, "creditsLeft": "1240", "spendable": true, "resetsAt": "2026-10-30T00:00:00.000Z", "cancelAtPeriodEnd": false, "status": "active", "suspended": false, "plan": { "catalogId": "3f2b…", "planKey": "standard", "creditsPerCycle": "20000" } } ``` `creditsLeft` counts your whole balance, free credits included, frozen or not. `spendable` is about the subscription only: `true` while it's `active` or `trialing` and not `suspended` by a card dispute on its payments, `false` otherwise. An overdue subscription (`past_due` or `unpaid`) freezes only its allowance, so your free and top-up credits can still pay a call then. And a dispute on another payment you made to Nevermined freezes every credit while this still reads `true`. Read `spendable` on [`GET /api/v1/credits/balance`](#credits) for what can pay right now. `subscribed: false` carries no other field. Called in an organization you're a member of, it reads that organization's subscription, never yours; organizations can no longer subscribe, so that's normally `subscribed: false`. ### In the catalog Signed in, the catalog shows your credits in the account menu under **Credits**, subscribed or not, and where your top-ups stand. A subscriber also sees a status bar on the catalog's home page, such as **Subscribed · 19,835 credits left this month**. When your credits can pay a call, the catalog shows service prices **in credits** instead of USD: * a service card priced like **15 credits**, or **from 15 credits** when its endpoints differ; * on a service's page, the credits one call costs and how many credits you have left, with each endpoint priced in credits — or marked **Budget only** when credits can't pay it (**Own crypto wallet only** on a service that sells only to the payer's own crypto wallet); * a switch on the services page, **Pay with your budget instead**, that turns the prices back into USD. Everyone else sees USD prices; quote a call (below) for its price in credits. ## The rate card: what a call costs Every endpoint that credits can pay has a **rate**: the number of credits one call costs. The rate shown when you make the call is what that call costs — the merchant's price at that moment doesn't change it. (The API calls a rate's version `tariffVersion`.) * **In the MCP**, `get_service` called with your API key shows `subscription.creditsPerCall` (and the `tariffVersion`) on each endpoint that credits can pay. * **Over REST**, quote the exact call. Nothing is reserved or charged, and the merchant isn't contacted: ```bash theme={null} curl -s -X POST "$NVM_API_URL/api/v1/router/subscription/quote" \ -H "Authorization: Bearer $NVM_API_KEY" -H "Content-Type: application/json" \ -d '{ "slug": "webscrape-pro", "path": "scrape", "method": "POST" }' ``` ```json theme={null} { "slug": "webscrape-pro", "credits": 3, "tariffVersion": 2 } ``` A quote refuses what the call would refuse before contacting the merchant (see [When a call is refused](#when-a-call-is-refused)). It never checks the merchant's live price or Nevermined's treasury, and for a subscriber in good standing it doesn't check how many credits are left — those are checked when the call is made. Without a subscription in good standing, it refuses a call your spendable credits can't cover (`0002`, or `0016` when only a frozen allowance would), unless an automatic top-up would cover it. ### How a rate is set Nevermined prices each endpoint from the merchant's own price. It takes what the merchant charges for a call, applies a markup, converts the result to credits at a nominal value per credit, and rounds **up** to the next step of a fixed scale of credit amounts — so every rate is a whole number of credits on that scale. Nevermined re-prices endpoints regularly as merchant prices move; between two pricings, the stored rate is what every call costs. Each rate also bounds what Nevermined will pay the merchant. If the merchant's live price rises above that bound, the call is refused before anything is paid (`BCK.SUBSCRIPTION_ROUTER.0004`), and the endpoint is flagged for re-pricing. A subscription call carries **no Router fee**: the rate is the whole cost. **The rate card is live.** It covers every catalog endpoint that credits can pay, and those services' own prices move all the time, so rates — and the markup, credit value and scale behind them — change, up or down, as soon as Nevermined updates them, without notice. Quote before you call when the cost matters; the rate in force at the time of the call is what you pay. ## Pay a call with credits Call a catalog service by its **slug**, exactly as you would through [`POST /api/v1/router/route`](/docs/api-reference/router/route-request), but on the subscription route and without a Delegation. Despite its name, the route spends any of your credits, with or without a subscription: ```bash theme={null} curl -s -X POST "$NVM_API_URL/api/v1/router/subscription/route" \ -H "Authorization: Bearer $NVM_API_KEY" -H "Content-Type: application/json" \ -d '{ "slug": "webscrape-pro", "path": "scrape", "method": "POST", "body": { "url": "https://example.com" }, "requestId": "scrape-example-com-1" }' ``` ```json theme={null} { "status": 200, "body": { "…": "the merchant's response, unchanged" }, "bodyEncoding": "json", "contentType": "application/json", "paid": true, "payment": { "paymentId": "b1f9c2e4-…", "status": "Settled", "txHash": "0xfc8af37b…", "creditsCharged": 3, "creditsStatus": "Committed", "failureReason": null, "correlationId": "…" } } ``` What's different from the Delegation route: * **A slug, never a URL.** Credits pay listed catalog services only, so the request names a `slug` (plus `path`, `method`, `search`, `headers`, `body`). A `url` or a `delegationId` is **refused** (`400 BCK.SUBSCRIPTION_ROUTER.0005`), not ignored, so a request that meant something else is never paid with credits. * **`requestId` is required**, as on every mode-B call: a retry with the same id is never paid twice — see [Paying twice](/docs/products/catalog/router/guardrails#paying-twice). * **Nothing to sign or fund.** Nevermined pays the merchant and never hands you a payment credential — there is no subscription equivalent of [minting a credential](/docs/api-reference/router/mint-payment-credential). * **No routing fee.** A subscription call costs its rate and nothing else. * **Long calls** behave as on the Delegation route: past the synchronous wait you get `202` with a `resultUrl` to poll, and the credits stay `Reserved` until the call ends. * **A top-up shows on the call that charged it.** When this call ran out of credits and, with [top-ups](#top-ups) on, charged a pack to cover itself, the response — the result, or the `202` — also carries `topUp`: the credits the pack added and its price before tax. Your card was charged, so tell the person you're acting for. ```json theme={null} { "topUp": { "credits": 10000, "amountUsd": 10 } } ``` For large or streamed responses, the streaming form is `ALL /api/v1/router/subscription/svc/{slug}/{path}`. Point your HTTP client at it with your API key and an `X-Router-Request-Id` header; the method, body and headers pass through and the response streams back with `X-Router-Credits-Charged` and `X-Router-Credits-Status` alongside the usual `X-Router-Payment-*` headers, plus `X-Router-Topup-Credits` and `X-Router-Topup-Amount-Usd` when the call charged a top-up pack. `X-Router-Target-Url`, `X-Router-Target-Slug` and `X-Router-Delegation-Id` are refused on this route. ## When a service doesn't deliver Your credits are **reserved** before the merchant is called and **kept only if it answers with a `2xx`**. An error status, a timeout, a dropped connection, or a merchant that refuses the payment all mark the call's credits for refund, and they come back automatically, with the expiry they had. If that expiry has passed by then, allowance credits come back with this period's expiry (once the subscription has ended, they're lost), and free credits are lost. A `502` with `BCK.ROUTER.0034` (no response from the service) or `BCK.ROUTER.0025` (its reply was too large to deliver) can come after the merchant was paid. The credits are refunded all the same, but don't retry with a new `requestId` — read the outcome with the same one from the [payment ledger](#in-the-ledger). On the streaming route, a `2xx` counts as delivered when its headers arrive: a body that breaks off mid-stream keeps its credits `Committed`. Contact support if that happens. `payment.creditsStatus` says where a call's credits stand: | `creditsStatus` | Meaning | | - | - | | `Committed` | The merchant delivered. The credits are spent. | | `Reserved` | The call hasn't finished, or it didn't deliver and its credits are being returned. | | `Refunded` | The credits were returned to your balance — except any that had expired by then, which are lost (see above). | A failed call's response body is `null`: you see the merchant's status, never its error body. If a service answered successfully but its result was defective, the credits are not returned automatically — contact support, and Nevermined may add credits to your current monthly allowance at its discretion (credits added this way expire at the end of the current billing period). Nevermined doesn't promise the availability or uptime of third-party services. Read the final state of any call from the [payment ledger](#in-the-ledger). In the rare case where the Router can't tell whether a call was delivered, the call is reviewed and either confirmed or refunded — its credits stay `Reserved` until then. > [!NOTE] > > **Credits never move on a refused call.** Every refusal below happens before the merchant is paid and before any credit is reserved, so there is nothing to refund. ## What credits can pay Credits pay **listed, live catalog endpoints that carry a rate**, on these rails: * **x402** merchants using the `exact` scheme, paid in USDC, * **MPP** merchants on the `tempo` method, paid in the USD stablecoin Nevermined's treasury holds there — per call (`charge`) or over a [session](/docs/products/catalog/router/rails-mpp#sessions-in-the-catalog), where the treasury opens and closes the channel, * **MPP** merchants on the `evm` method, a USDC charge on Base paid like x402, per call. Credits don't pay MPP card (`stripe` / Shared Payment Token) merchants, a raw URL that isn't in the catalog, an endpoint without a fixed price, or an endpoint whose result only the paying wallet can read back — a job you poll, or something you'd own at the merchant. Nevermined also doesn't sell some services for credits at all, on any endpoint — Dune (`dune-mpp`) is one — and refuses them with `params.reason: credits_excluded`. On a service that delivers results only to the wallet that paid, credits pay just the endpoints Nevermined has reviewed as self-contained (the paid response is the whole result); the rest are refused with `params.reason: wallet_bound`. Pay all of these from a Delegation — a `wallet_bound` endpoint only from your own crypto (`erc4337`) Delegation, since a card or organization Delegation is refused there too. ### Who can spend your credits * **A personal Nevermined API key**: one with no organization tag, used without an `X-Current-Org-Id` header. This is how an agent you run yourself spends them, through the Catalog MCP or the API. * **An assistant you connected through OAuth** (for example the [Catalog MCP](/docs/mcp/catalog-mcp/overview) from Claude.ai or ChatGPT), only if you ticked **Let this assistant spend my Nevermined credits** on the consent screen. It's off by default. With it on, the assistant can read and spend your personal credits at eligible catalog services, with no separate credit cap, until you revoke the connection. A call it makes never charges a top-up pack on its own; to let it charge one within your limit, also tick **Let this assistant top up my Nevermined credits** — then it can call [`top_up_credits`](/docs/mcp/catalog-mcp/top-up-credits). It can't start a subscription for you, turn on top-ups, or spend an organization's credits. Without it, [`pay_service`](/docs/mcp/catalog-mcp/pay-service) pays from the connection's stablecoin spending cap instead, and a call to the credits route is refused with `403 BCK.OAUTH.0037`. An existing connection never gains this permission on its own: reconnect to allow it. Any other kind of OAuth credential is refused with `403 BCK.OAUTH.0030`. An OAuth connection can't read [`GET /api/v1/credits/balance`](#credits) either, even one allowed to spend your credits: that balance takes a personal API key. ### No spending limits beyond your credits Credits have no spending limit beyond your balance — no daily, per-service or pace cap. The Router's usual per-service rate limit and concurrency limit still apply (`429`). A call can also be refused when Nevermined's treasury can't pay right now — most often because its float is low (`503 BCK.SUBSCRIPTION_TREASURY.0003`, retryable). Nothing is charged; retry later. ## When a call is refused Branch on `code`. None of these spent or reserved any credit, and none charged anything — except that with top-ups on, a `0009` can follow a top-up pack charged to your card (`params.topUps`: `bought`, or `pending`), and so can a `0015` or `0016` (`params.topUps`: `bought`), as the [table below](#when-no-top-up-covers-the-call) says. | Code | Status | What it means | What to do | | - | - | - | - | | `BCK.SUBSCRIPTION_ROUTER.0001` | 403 | This endpoint can't be paid with credits — `params.reason` says why (`no_active_tariff` — no rate yet, `price_variable`, `unhealthy`, `wallet_bound`, `endpoint_unresolved`, …). | Quote another endpoint, or pay this one from a Delegation — for `wallet_bound`, your own crypto (`erc4337`) Delegation. | | `BCK.SUBSCRIPTION_ROUTER.0002` | 402 | Nothing to pay this call with: no subscription in good standing (none bought, ended or past due), and no credits — or not enough for this call — that can be spent, with no top-up that would cover it: top-ups off, paused, at this month's limit or still charging a pack. Also the answer when you call in an organization you're a member of. | Subscribe, turn on [top-ups](#top-ups) — or resume them or raise their limit in the [Top-ups panel](#manage-top-ups) — settle the open invoice, pick a cheaper endpoint, pay from a Delegation, or call with a personal API key and no `X-Current-Org-Id`. | | `BCK.SUBSCRIPTION_ROUTER.0003` | 400 | The merchant asked for a rail credits don't pay (`params.rail`). | Pay from a Delegation. | | `BCK.SUBSCRIPTION_ROUTER.0004` | 409 | The merchant's live price is outside the rate's bound, or in another asset or network — or, for a service paid over an MPP **session**, it asked to be paid at an address Nevermined has not yet seen it use for this endpoint (`payee_unobserved`). `params.reason` says which. | Retry later, or pay from a Delegation. A `payee_unobserved` call stays refused until Nevermined has seen that address on this endpoint, so pay it from a Delegation. | | `BCK.SUBSCRIPTION_ROUTER.0005` | 400 | A field that only makes sense elsewhere (`url`, `delegationId`, a target header) — `params.field`. Also refuses any revealBuyerIdentity field (even false/null) or X-Router-Reveal-Buyer-Identity header. | Address the service by `slug` only. | | `BCK.SUBSCRIPTION_ROUTER.0007` | 400 | Mode A (`POST /router/payments`) can't be funded by a subscription — you sent it `fundingSource: "subscription"` or a `subscriptionId`. | Use the subscription route. | | `BCK.SUBSCRIPTION_ROUTER.0009` | 402 | Not enough credits left for this call (`params.credits` is its cost). Mostly what a subscriber in good standing, or an account whose top-ups would charge a pack, gets: otherwise the quote usually refuses a call your credits can't cover with `0002`. With top-ups on, `params.topUps` says why no pack covered the call — see [the table below](#when-no-top-up-covers-the-call). | Pick a cheaper endpoint, turn on [top-ups](#top-ups), or pay from a Delegation. A subscriber's allowance comes back next period. | | `BCK.SUBSCRIPTION_ROUTER.0015` | 402 | All your credits are frozen: a card payment you made to Nevermined is disputed, or a dispute was decided in the cardholder's favour. With `params.topUps: "bought"`, this call charged a pack before the dispute froze it, and that pack's credits are frozen with the rest. | Withdraw the dispute with your card issuer, or contact Nevermined support. Until then, pay from a Delegation. | | `BCK.SUBSCRIPTION_ROUTER.0016` | 402 | Your subscription's renewal payment is overdue, so its allowance is frozen, and your other credits don't cover this call (`params.credits` is its cost). With `params.topUps: "bought"`, this call charged a pack, but other calls spent its credits first. | Update your card on the subscription page so the invoice is paid, or pay from a Delegation. | | `BCK.SUBSCRIPTION_TREASURY.0002` | 422 | The merchant wants to be paid in an asset Nevermined's treasury doesn't pay in. | Pay from a Delegation. | | `BCK.SUBSCRIPTION_TREASURY.0003` | 503 | Nevermined's treasury float can't cover this payment right now. | Retry later (`retryable: true`). | | `BCK.SUBSCRIPTION_TREASURY.0008` | 403 | Nevermined's treasury can't pay this merchant. | Pay another service. | | `BCK.SUBSCRIPTION_ACCESS.0001` | 404 | The subscription isn't available on this deployment or to this account. | — | | `BCK.CATALOG.0001` | 404 | No listed, payable catalog service has that `slug`. | Check the slug in the catalog. | | `BCK.OAUTH.0030` | 403 | An OAuth credential that isn't a commerce connection. | Use your personal API key. | | `BCK.OAUTH.0037` | 403 | An OAuth commerce connection you didn't allow to spend your credits. | Reconnect, and tick **Let this assistant spend my Nevermined credits** on the consent screen. | | `BCK.OAUTH.0038` | 403 | An OAuth connection allowed to spend your credits, used in an organization. It spends only your personal credits. | Call without the organization context. | | `BCK.ROUTER.0001` | 400 | With the message *this service delivers its results only to the personal wallet that paid*: the Router's own check that a wallet-bound endpoint is one credits can pay (such calls are normally refused earlier, as `BCK.SUBSCRIPTION_ROUTER.0001` `wallet_bound`). Any other message is a malformed request. | Pay it from your own crypto (`erc4337`) Delegation. | ### When no top-up covers the call With top-ups on, a call that runs out of credits charges a pack and goes ahead. When it can't, it's refused with `402 BCK.SUBSCRIPTION_ROUTER.0009`, and `params.topUps` says why. Without a subscription in good standing, though, a call made while top-ups are paused, at the limit or still charging a pack never gets that far: it's refused `0002`, with no `params.topUps`. No credits were spent on the refused call in any case, but with `bought`, and possibly `pending`, your card was charged for a pack. | `params.topUps` | What happened | What to do | | - | - | - | | `paused` | A pack was declined or needed authentication, or its card can no longer pay — now or earlier — so top-ups are paused. | Resume them from the Top-ups panel — see [When top-ups pause](#when-top-ups-pause). | | `limitReached` | One more pack would take this month past your monthly limit, or past Nevermined's maximum. | Raise your limit in the Top-ups panel, or wait for next month (UTC). | | `pending` | A pack is being charged and wasn't confirmed in time. Your card may have been charged; its credits land once the payment is recorded. | Retry in a moment. | | `unavailable` | No pack could be charged right now, and none was. | Retry later. | | `bought` | This call charged a pack to your card (`params.purchaseId` names it), but other calls spent its credits first. The pack's credits are yours. | Tell the person you're acting for that their card was charged, then retry. | A `0009` without `params.topUps` usually tried no pack: top-ups are off, or not available to you. (It can also come after another call's pack covered this one and was spent before this call could use it.) A call that a frozen allowance would have covered (`0016`) or that a card dispute froze (`0015`) never charges a pack. One refused that way after it charged a pack (a dispute opened, or a renewal went overdue, in between) says so: `params.topUps: "bought"`, with the pack's `params.purchaseId` — tell the person you're acting for that their card was charged. Other errors with a `5xx` status (`BCK.SUBSCRIPTION_ROUTER.0006` and `0010`–`0014`, and the remaining `BCK.SUBSCRIPTION_TREASURY.*` codes) are on Nevermined's side and also charge nothing; `retryable` says whether retrying can help. The Router's common errors apply too — a reused `requestId` (`409 BCK.ROUTER.0002`), the rate and concurrency limits (`429`): see [every error code](/docs/products/catalog/router/guardrails#every-error-code). A service paid over an MPP **session** (a payment channel) can also answer `409 BCK.ROUTER.0042` or `503 BCK.ROUTER.0043`. Nevermined pays it over **one channel shared by everyone paying with credits**, so while that channel is busy, or closing — when its deposit reaches its ceiling, or when the service refuses the channel or a top-up of it; the next call after the close opens a new one — calls to that service are refused for everyone. Closing usually takes about a minute, and 15 minutes or more when the service does not accept a cooperative close. Nothing is charged; retry later with the same `requestId`. The full list is in the [error reference](/docs/development-guide/api-errors/codes). `BCK.SUBSCRIPTION_TREASURY.0004`–`0007` and `0014` are retired: they belonged to spending limits removed before launch, and the API no longer returns them. ## In the ledger Calls paid with credits land on the same [payment ledger](/docs/products/catalog/router/ledger) as everything else, with three extra fields. `fundingSource` is `subscription` on every credits call, free credits included: | Field | On a credits call | On a Delegation call | | - | - | - | | `fundingSource` | `subscription` | `delegation` | | `creditsCharged` | The call's rate, in credits — kept when the credits are refunded, so count it only when `creditsStatus` is `Committed` | `null` | | `creditsStatus` | `Committed`, `Reserved` or `Refunded` | `null` | `delegationId` is `null` on a credits call, and `feeBps` is `0`: there is no routing fee. To read one call's final state, look it up by the `requestId` you sent: ```bash theme={null} curl -s -G "$NVM_API_URL/api/v1/router/payments" \ --data-urlencode "requestId=scrape-example-com-1" \ -H "Authorization: Bearer $NVM_API_KEY" ``` ```json theme={null} { "presence": "present", "payments": [ { "paymentId": "b1f9c2e4-…", "requestId": "scrape-example-com-1", "fundingSource": "subscription", "creditsCharged": 3, "creditsStatus": "Committed", "delegationId": null, "feeBps": 0 } ] } ``` `presence: "absent"` means no payment is recorded for that `requestId` yet — while the call may still be running, retry it with the same `requestId`, never a new one. See [Look up one payment by `requestId`](/docs/products/catalog/router/ledger#look-up-one-payment-by-requestid). ## From the Catalog MCP With credits and a personal API key — or an OAuth connection [allowed to spend them](#who-can-spend-your-credits) — the [Catalog MCP](/docs/mcp/catalog-mcp/overview)'s [`pay_service`](/docs/mcp/catalog-mcp/pay-service#pay-with-subscription-credits) pays, and [`quote_service`](/docs/mcp/catalog-mcp/quote-service#quote-in-subscription-credits) prices, in credits by default when your credits and the endpoint qualify. With a personal API key, [`get_budget`](/docs/mcp/catalog-mcp/get-budget#nevermined-credits) and [`wallet_balance`](/docs/mcp/catalog-mcp/wallet-balance#nevermined-credits) report your credits. When a call that goes ahead charges a top-up pack, `pay_service` says so in [`topUpMessage`](/docs/mcp/catalog-mcp/pay-service#when-a-call-charges-a-top-up-pack), for your assistant to tell you. ## Refunds and disputes of the subscription itself These are about the monthly **fee**, not a single call. Subscription fees are **non-refundable**, except where the law requires a refund or for billing errors. * If a subscription payment is **refunded in full**, the unused credits it granted are removed. A refund can take 5–10 business days to appear on your card statement. * If you **dispute** a payment with your card issuer, its unused credits are removed and none of your credits — free and top-up credits included — can be spent while the dispute is open, so no top-up pack is charged either. If the dispute is decided in your favour, they stay unable to spend. If it's decided in Nevermined's favour, those credits are restored with their original expiry — credits whose billing period has ended by then come back already expired. ## Related > [card] [How the Router works](/docs/products/catalog/router/how-it-works) > > Mode A and mode B, and the Delegation-funded path. > [card] [Guardrails](/docs/products/catalog/router/guardrails) > > Every check on a Delegation-funded payment. > [card] [Payment ledger](/docs/products/catalog/router/ledger) > > Query and export every payment, credits included. > [card] [Catalog MCP](/docs/mcp/catalog-mcp/overview) > > Discover and pay from an AI assistant. Identity disclosure is unsupported on subscription route calls. Any `revealBuyerIdentity` field (including `false` or `null`) or `X-Router-Reveal-Buyer-Identity` header is refused with `BCK.SUBSCRIPTION_ROUTER.0005` rather than silently ignored. Omit them on subscription routes. # Catalog videos Source: https://nevermined.ai/docs/products/catalog/videos Watch the Nevermined Catalog in action: a product overview, outcome examples, and walkthroughs for connecting from Claude.ai, ChatGPT, and LangSmith Fleet. A curated set of walkthroughs for the Nevermined Catalog — start with the overview, see outcome-based agents in action, then connect the Catalog to your own AI assistant. ## Start here The best place to begin. This walkthrough introduces the Nevermined Catalog end to end: what it is, how you browse and discover services, and how an agent gets set up and then pays for and calls a service without any manual billing setup. Watch this first to get the mental model everything else builds on. (To publish your own service to the Catalog, see [Add your AI service](/docs/products/catalog/publish-ai-service).) [Nevermined Catalog — overview](https://www.youtube.com/embed/0QFSy7E0cio) Catalog overview. ## Outcome-based agents These two examples show agents priced on the outcome they deliver rather than the number of calls they make — the buyer pays for a result, and the agent redeems credits only when it produces one. The first example walks through a complete outcome-based flow, from purchasing a plan to the agent charging for the delivered result. [Outcome-based agent — example #1](https://www.youtube.com/embed/Wg-7go30WRs) Outcomes example #1. The second example applies the same outcome-based pricing to a different agent, so you can see how the pattern generalizes across use cases. [Outcome-based agent — example #2 (Song from the Headlines)](https://www.youtube.com/embed/Ilj93OUSxV8) Outcomes example #2 — Song from the Headlines. ## Connect from your assistant Give your AI assistant a wallet and it can buy from the Catalog on your behalf. These walkthroughs cover the concept and then the exact steps for the most common assistants. For the written, step-by-step version of each — including the hosts that connect with a plain Nevermined API key instead of OAuth — see the per-host connect pages: [Connect from Claude](/docs/products/catalog/connect/claude), [Connect from ChatGPT](/docs/products/catalog/connect/chatgpt), and the full set under [Using the Catalog from your web assistant](/docs/products/catalog/from-your-web-assistant). Start here for the idea: your assistant gets a wallet, and it can now pay for the services it needs to complete a task — no copy-pasting API keys, no manual checkout. [Your AI assistant can now pay for things](https://www.youtube.com/embed/EJk5ZHmd4u0) Your AI assistant can now pay for things. A step-by-step of connecting the Catalog to Claude at claude.ai over the OAuth route, so Claude can discover and pay for services directly in your chat. [Connect to the Catalog from claude.ai](https://www.youtube.com/embed/ioDqtiHtOGg) Connect to the Catalog from claude.ai. The same connection from ChatGPT: wire up the Catalog so ChatGPT can find a service, pay for it, and use the result inside a conversation. [Connect to the Catalog from ChatGPT](https://www.youtube.com/embed/e_-bQlLdRdg) Connect to the Catalog from ChatGPT. For teams running autonomous agents, this shows how to connect the Catalog to a LangSmith Fleet agent so a deployed agent can pay for services on its own, unattended. [Connect the Catalog to a LangSmith Fleet agent](https://www.youtube.com/embed/wbwrg8v0uys) Connect the Catalog to a LangSmith Fleet agent. # Manage Payment Plans Source: https://nevermined.ai/docs/products/nevermined-app/manage-plans Create and configure payment plans for your AI agents through the Nevermined App Payment plans define how subscribers pay to access your AI agents. Use the Nevermined App to create, edit, and manage plans visually. ## Creating a Payment Plan **1. Select Your Agent** From the Agents tab, click on the agent you want to add a plan to, then click **Create Plan**. **2. Choose Plan Type** Select how access will be limited: | Type | Description | Best For | | - | - | - | | **Credits-Based** | Users purchase credits, consume per request | API calls, queries | | **Time-Based** | Access expires after a duration | Subscriptions | | **Dynamic** | Variable charge per request | Complex workloads | **3. Configure Pricing** Set the price and currency: **Cryptocurrency**: * Amount (e.g., 10) * Token (USDC, USDT, or custom ERC-20) * Network (Base, Ethereum, etc.) **Fiat**: * Amount (e.g., \$10.00) * Currency (USD, EUR, etc.) * Payment via Stripe checkout **4. Set Access Parameters** Configure what subscribers get: **For Credits-Based**: * Total credits included * Credits consumed per request **For Time-Based**: * Access duration (days, weeks, months) **For Dynamic**: * Minimum credits per request * Maximum credits per request **5. Add Plan Details** | Field | Description | | - | - | | **Name** | Plan display name (e.g., "Pro Plan") | | **Description** | What's included (e.g., "100 queries per month") | **6. Create Plan** Review your configuration and click **Create Plan**. The plan will be immediately available for purchase. ## Plan Types in Detail ### Credits-Based Plans Charge per usage - subscribers buy credits that are deducted with each request. **Example Configuration**: ``` Name: Pro Plan Price: 10 USDC Credits: 100 Credits per Request: 1 → $0.10 per query ``` **Use When**: * Each request has similar cost * You want pay-as-you-go pricing * Usage varies significantly between users ### Time-Based Plans Subscription model - unlimited access for a fixed duration. **Example Configuration**: ``` Name: Monthly Subscription Price: 50 USDC Duration: 30 days → Unlimited queries for one month ``` **Use When**: * Users need continuous access * Usage is predictable * You want recurring revenue ### Dynamic Plans Variable pricing - charge different amounts based on request complexity. **Example Configuration**: ``` Name: Pay As You Go Price: 20 USDC (for 100 credits) Min Credits per Request: 1 Max Credits per Request: 10 → Simple queries: 1 credit → Complex queries: up to 10 credits ``` **Use When**: * Requests have varying costs (e.g., LLM token count) * You want fair usage-based pricing * Processing time varies significantly ## Multiple Plans Per Agent Create tiers to serve different customer segments: ``` Agent: Legal Document Analyzer Plans: 1. Free Trial (0 USDC, 5 credits) 2. Starter ($5, 25 credits) 3. Pro ($15, 100 credits) 4. Enterprise ($99, 1000 credits) ``` > [!NOTE] > > Subscribers can purchase multiple plans or repurchase to add more credits. ## Editing Plans From the Plans tab or agent detail page: 1. Click on the plan you want to edit 2. Modify settings (name, description, pricing) 3. Click **Save Changes** > [!WARNING] > > Changing plan pricing affects new purchases only. Existing subscribers keep their original terms. ## Plan Analytics Track each plan's performance: | Metric | Description | | - | - | | **Purchases** | Total times the plan was ordered | | **Revenue** | Total earnings from this plan | | **Active Subscribers** | Users with remaining credits/time | | **Usage Rate** | Average credits used per subscriber | ## Free Trial Plans Attract new users with free trials: 1. Create a new plan with **Price: 0** 2. Set limited credits (e.g., 5 queries) 3. Name it clearly (e.g., "Free Trial - 5 Queries") Users can claim the trial once per account, then must purchase a paid plan. ## Best Practices > [accordion] Offer Multiple Tiers > > Create at least 3 tiers (e.g., Starter, Pro, Enterprise) to capture different customer segments and budgets. > [accordion] Include a Free Trial > > Let users try before they buy. A small free trial (5-10 credits) can significantly increase conversions. > [accordion] Price for Value > > Consider the value your agent provides, not just your costs. Premium AI services can command premium prices. > [accordion] Clear Descriptions > > Explain exactly what subscribers get. Include credits, duration, and any limitations. ## Managing Subscribers View who has purchased each plan: 1. Go to the plan detail page 2. Click **Subscribers** tab 3. See purchase date, credits remaining, and usage history You can also: * Export subscriber data * View individual usage patterns * Contact subscribers (if they've opted in) ## Next Steps > [card] [Validate Requests](/docs/integrate/patterns/validate-requests) > > Implement access control in your agent > [card] [SDK Integration](/docs/api-reference/introduction) > > Manage plans programmatically # Nevermined App Overview Source: https://nevermined.ai/docs/products/nevermined-app/overview No-code interface for registering AI agents, managing payment plans, and monetizing your services The [Nevermined App](https://nevermined.app) is a visual interface for managing your AI agents and payment infrastructure. Register agents, create payment plans, and track revenue without writing code. ## What You Can Do > [card] Register Agents > > Add your AI agents with metadata, endpoints, and access control settings > [card] Create Payment Plans > > Define pricing with credits, subscriptions, or dynamic models > [card] Manage Access > > Generate API keys, view subscribers, and control permissions > [card] Track Revenue > > Monitor usage, payments, and analytics in real-time ## Getting Started **1. Sign In** Go to [nevermined.app](https://nevermined.app) and log in using Web3Auth. You can use social logins (Google, GitHub) or connect a crypto wallet. **2. Get Your API Key** Navigate to **Settings > API Keys** and generate a new key. Store it securely - you'll need it for SDK integration. ```bash theme={null} export NVM_API_KEY="sandbox:your-api-key-here" ``` **3. Register an Agent** Click **Agents > Register New Agent** and fill in: * Agent name and description * API endpoints (the URLs your agent exposes) * Optional: Link to OpenAPI spec, MCP manifest, or A2A agent card **4. Create a Payment Plan** Click **Create Plan** on your agent and configure: * Plan name and description * Pricing (amount and currency) * Access type (credits or time-based) * Credits per request (for credit-based plans) ## Dashboard Overview ### Agents Tab View and manage all your registered AI agents: * **Agent Details**: Name, description, endpoints, and linked plans * **Status**: Active, paused, or pending * **Analytics**: Total queries, revenue, and active subscribers ### Plans Tab Manage payment plans for your agents: * **Plan Configuration**: Price, credits, duration * **Subscribers**: View who has purchased each plan * **Revenue**: Track earnings per plan ### Settings Configure your account and API access: * **API Keys**: Generate and manage keys for SDK integration * **Payment Settings**: Configure payout addresses * **Notifications**: Set up alerts for new subscribers and payments ## When to Use the App vs SDK | Use Case | Nevermined App | Payment Libraries | | - | - | - | | Quick setup and testing | Best | Good | | Non-technical users | Best | Not recommended | | CI/CD automation | Not possible | Best | | Custom workflows | Limited | Best | | Bulk operations | Manual | Automated | ## Key Features ### No-Code Agent Registration Register agents without writing code: 1. Enter your agent's metadata (name, description, tags) 2. Add API endpoints (supports REST, OpenAPI, MCP, A2A) 3. Configure access control settings 4. Click "Register" - done! ### Visual Plan Builder Create payment plans through a guided interface: * Select plan type (credits, time, or dynamic) * Set pricing in crypto (USDC, USDT) or fiat (via Stripe) * Configure usage limits and terms * Preview how subscribers will see the plan ### Real-Time Analytics Track your agent's performance: * **Queries**: Total requests, successful vs failed * **Revenue**: Earnings by day, week, month * **Subscribers**: Active users, new signups, churn * **Credits**: Usage patterns, top consumers ## Integration with SDKs The App works seamlessly with the Payment Libraries: ```typescript theme={null} // Agents registered in the App can be accessed via SDK const agentId = 'did:nv:your-agent-id' const agent = await payments.agents.getAgent(agentId) const planId = agent.plans[0].planId // Plans created in the App work with SDK ordering await payments.plans.orderPlan(planId) // Credentials work the same way // Create a delegation once, then reuse its id to mint tokens. const { delegationId } = await payments.delegation.createDelegation({ provider: 'erc4337', // 'stripe' | 'braintree' | 'visa' for fiat plans spendingLimitCents: 10000, // $100 budget durationSecs: 604800, // 7 days currency: 'usdc', // 'usd' for fiat plans }) const { accessToken } = await payments.x402.getX402AccessToken( planId, agentId, // scheme defaults to 'nvm:erc4337'; pass 'nvm:card-delegation' for fiat plans { scheme: 'nvm:erc4337', delegationConfig: { delegationId } } ) ``` ## Security * **Web3Auth**: Secure authentication without managing private keys * **Non-Custodial**: You control your funds - payments go directly to your address * **API Key Scoping**: Create keys with limited permissions for different use cases ## Next Steps > [card] [Register Agents](/docs/products/nevermined-app/register-agents) > > Step-by-step guide to registering your first agent > [card] [Manage Plans](/docs/products/nevermined-app/manage-plans) > > Create and configure payment plans > [card] [Payment Libraries](/docs/api-reference/introduction) > > Integrate programmatically with the SDKs > [card] [5-Minute Setup](/docs/integrate/quickstart/5-minute-setup) > > Complete quickstart guide # Register Agents Source: https://nevermined.ai/docs/products/nevermined-app/register-agents Step-by-step guide to registering AI agents through the Nevermined App Register your AI agents through the Nevermined App's visual interface. This guide walks through each step of the registration process. > [!NOTE] > > Registering an agent is for **sellers/builders** — it's how you publish a service for others to pay for, and it's why this flow asks for your agent's protected endpoints. If you only want to **buy or use** an agent, you don't need to register or create a plan: see [Buy & Call a Paid Agent](/docs/getting-started/ai-agent-purchase). ## Prerequisites * A Nevermined account (sign up at [nevermined.app](https://nevermined.app)) * Your AI agent's API endpoint(s) ready to receive requests * Optional: OpenAPI spec, MCP manifest, or A2A agent card URL ## Registration Steps **1. Navigate to Agents** From the Nevermined App dashboard, click **Agents** in the sidebar, then click **Register New Agent**. **2. Enter Basic Information** Fill in your agent's metadata: | Field | Description | Example | | - | - | - | | **Name** | Display name for your agent | "Legal Document Analyzer" | | **Description** | What your agent does | "AI-powered legal document analysis and summarization" | | **Tags** | Categories for discovery | `legal`, `ai`, `documents` | **3. Configure API Endpoints** Add the endpoints your agent exposes: * **HTTP Method**: GET, POST, PUT, DELETE * **URL**: The full endpoint URL (e.g., `https://api.myservice.com/analyze`) * **Description**: What this endpoint does You can add multiple endpoints for a single agent. > [!NOTE] > > Your endpoints must be publicly accessible. Nevermined will route requests to these URLs with the subscriber's access token. **4. Add Agent Definition (Optional)** Link to a machine-readable definition of your agent: | Type | URL Format | | - | - | | **OpenAPI** | `https://api.myservice.com/openapi.json` | | **MCP Manifest** | `https://api.myservice.com/mcp.json` | | **A2A Agent Card** | `https://api.myservice.com/.well-known/agent.json` | This enables automatic discovery and integration with AI frameworks. **5. Review and Register** Review your agent configuration and click **Register Agent**. Your agent will be assigned a unique ID (`did:nv:...`). ## Agent Configuration Examples ### REST API Agent For a standard REST API: ``` Name: Data Analysis API Description: Statistical analysis and visualization service Endpoints: - POST https://api.dataservice.com/analyze - GET https://api.dataservice.com/status/{job_id} - GET https://api.dataservice.com/results/{job_id} Definition URL: https://api.dataservice.com/openapi.json ``` ### MCP Tool Agent For an MCP-compatible agent: ``` Name: Code Review Assistant Description: AI-powered code review and suggestions Endpoints: - POST https://mcp.codereviewer.com/review Definition URL: https://mcp.codereviewer.com/mcp.json ``` ### A2A Agent For Google Agent-to-Agent compatible agents: ``` Name: Travel Booking Agent Description: Autonomous travel planning and booking Endpoints: - POST https://a2a.travelbot.com/tasks Definition URL: https://a2a.travelbot.com/.well-known/agent.json ``` ## After Registration Once your agent is registered, you can: 1. **Create Payment Plans**: Add pricing to your agent 2. **View Agent ID**: Copy your `did:nv:...` for SDK integration 3. **Monitor Activity**: Track queries and usage 4. **Edit Settings**: Update endpoints or metadata ## Managing Multiple Agents The Agents tab shows all your registered agents: | Column | Description | | - | - | | **Name** | Agent display name | | **ID** | Unique identifier (did:nv:...) | | **Plans** | Number of payment plans attached | | **Queries** | Total requests received | | **Status** | Active, Paused, or Pending | Click any agent to view details, edit configuration, or create payment plans. ## Best Practices > [accordion] Use Descriptive Names > > Choose names that clearly describe what your agent does. This helps subscribers find and understand your service. > [accordion] Document Your Endpoints > > Provide clear descriptions for each endpoint. Include expected inputs, outputs, and any rate limits. > [accordion] Include Agent Definition > > Link to an OpenAPI spec, MCP manifest, or A2A card. This enables automatic integration with AI frameworks and improves discoverability. > [accordion] Use HTTPS > > All endpoints should use HTTPS for secure communication. HTTP endpoints are not supported. ## Troubleshooting > [accordion] Endpoint not reachable > > Verify your endpoint URL is correct and publicly accessible. Test with `curl` or a similar tool. > [accordion] Registration fails > > Check that all required fields are filled and your endpoint URLs are valid HTTPS URLs. > [accordion] Agent not appearing > > Refresh the Agents page. New agents may take a few seconds to appear. ## Next Steps > [card] [Manage Plans](/docs/products/nevermined-app/manage-plans) > > Create payment plans for your agent > [card] [Payment Libraries](/docs/api-reference/introduction) > > Register agents programmatically # How the Payments Facilitator Works Source: https://nevermined.ai/docs/products/payments-facilitator/how-it-works Technical deep-dive into x402 verification and programmable settlement This guide explains the end-to-end x402 flow from both the subscriber (client) and resource server (API/agent) perspectives. > [!NOTE] > > For the complete technical specification, see the [x402 Smart Accounts Extension Spec](/docs/specs/x402-smart-accounts). > [!NOTE] > > This page covers the **x402** protocol. The Payments Facilitator also speaks **MPP (Merchant Payment Protocol)** against the same plans and credits — see [Accepting MPP payments](/docs/products/payments-facilitator/mpp-seller) for the seller side and [Paying an MPP-protected service](/docs/development-guide/nevermined-x402#paying-an-mpp-protected-service) for the buyer side. If you're new to the programmable extension concepts, see: * [Making x402 programmable](https://nevermined.ai/blog/making-x402-programmable) * [Building Agentic Payments with Nevermined, x402, A2A, and AP2](https://nevermined.ai/blog/building-agentic-payments-with-nevermined-x402-a2a-and-ap2) ## The Nevermined x402 programmable extension Nevermined extends x402 with the `nvm:erc4337` scheme, enabling **programmable settlement** (credits/subscriptions/PAYG) using ERC-4337 smart accounts and session keys. ### PaymentRequired Response (402) When a server requires payment, it returns a `402` response with a `payment-required` header: ```json theme={null} { "x402Version": 2, "error": "Payment required to access resource", "resource": { "url": "/api/v1/agents/80918427.../tasks", "description": "AI agent task execution" }, "accepts": [{ "scheme": "nvm:erc4337", "network": "eip155:84532", "planId": "44742763076047497640080230236781474129970992727896593861997347135613135571071", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015" } }], "extensions": {} } ``` ### PaymentPayload (Client Response) The client responds with a `payment-signature` header containing the x402 access token: ```json theme={null} { "x402Version": 2, "accepted": { "scheme": "nvm:erc4337", "network": "eip155:84532", "planId": "44742763076047497640080230236781474129970992727896593861997347135613135571071", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015" } }, "payload": { "signature": "0x01845ADb2C711129d4f3966735eD98a9F09fC4cE...", "authorization": { "from": "0xD4f58B60330bC59cB0A07eE6A1A66ad64244eC8c", "sessionKeysProvider": "zerodev", "sessionKeys": [ { "id": "order", "data": "0x20a13d82dd9ee289..." }, { "id": "redeem", "data": "0x68e8e34d65914908..." } ] } }, "extensions": {} } ``` ## Subscriber flow (client side) ### Step 1: Discover payment requirements (HTTP 402) When calling a protected endpoint, the server returns a `402 Payment Required` response with the `payment-required` header containing the payment requirements. > [tab] TypeScript > > ```typescript theme={null} > import { X402_HEADERS } from '@nevermined-io/payments/express' > > // Call protected endpoint - get 402 response > const response = await fetch('https://api.example.com/protected') > > if (response.status === 402) { > // Decode the payment-required header > const paymentRequired = JSON.parse( > Buffer.from(response.headers.get(X402_HEADERS.PAYMENT_REQUIRED)!, 'base64').toString() > ) > > // Extract planId and agentId from accepts array > const { planId, extra } = paymentRequired.accepts[0] > const agentId = extra?.agentId > } > ``` > [tab] Python > > ```python theme={null} > import base64 > import json > import requests > > response = requests.get('https://api.example.com/protected') > > if response.status_code == 402: > # Decode the payment-required header > payment_required = json.loads( > base64.b64decode(response.headers.get('payment-required')).decode() > ) > > # Extract planId and agentId from accepts array > plan_id = payment_required['accepts'][0]['planId'] > agent_id = payment_required['accepts'][0].get('extra', {}).get('agentId') > ``` ### Step 2: Generate x402 access token Use the Nevermined SDK to generate an x402 access token. The supported flow is **create-first**: create a delegation once with `createDelegation` (`provider` and `currency` are required), then request access tokens by passing its `delegationId`. Reuse the delegation until it expires or is exhausted. > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY, > environment: 'sandbox' > }) > > // 1. Create a delegation once (provider + currency required; 'usdc' for erc4337). > const delegation = await payments.delegation.createDelegation({ > provider: 'erc4337', > spendingLimitCents: 10000, > durationSecs: 604800, > currency: 'usdc' > }) > > // 2. Request a token by delegationId (reuse it for subsequent requests). > const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, { > delegationConfig: { delegationId: delegation.delegationId } > }) > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments, PaymentOptions > from payments_py.x402 import ( > CreateDelegationPayload, > DelegationConfig, > X402TokenOptions, > ) > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox') > ) > > # 1. Create a delegation once (provider + currency required; 'usdc' for erc4337). > delegation = payments.delegation.create_delegation( > CreateDelegationPayload( > provider='erc4337', > spending_limit_cents=10000, > duration_secs=604800, > currency='usdc', > ) > ) > > # 2. Request a token by delegationId (reuse it for subsequent requests). > token_res = payments.x402.get_x402_access_token( > plan_id, > agent_id, > token_options=X402TokenOptions( > delegation_config=DelegationConfig( > delegation_id=delegation.delegation_id > ) > ), > ) > access_token = token_res['accessToken'] > ``` > [!WARNING] > > **Inline create-on-the-fly is deprecated.** Passing creation fields (`spendingLimitCents`, `durationSecs`, `providerPaymentMethodId`, `cardId`, `currency`) directly in `delegationConfig` instead of a `delegationId` still works but emits a runtime deprecation warning. Create the delegation first, then pass only `{ delegationId }`. ### Step 3: Retry request with payment header Send the x402 access token in the `payment-signature` header: > [tab] TypeScript > > ```typescript theme={null} > import { X402_HEADERS } from '@nevermined-io/payments/express' > > const result = await fetch('https://api.example.com/protected', { > method: 'POST', > headers: { > 'Content-Type': 'application/json', > [X402_HEADERS.PAYMENT_SIGNATURE]: accessToken > }, > body: JSON.stringify({ prompt: 'Hello' }) > }) > > // Decode the settlement receipt from payment-response header > if (result.ok) { > const settlement = JSON.parse( > Buffer.from(result.headers.get(X402_HEADERS.PAYMENT_RESPONSE)!, 'base64').toString() > ) > // `billingModel` says how to read this receipt — see the note below > console.log('Billing model:', settlement.billingModel) > console.log('Credits used:', settlement.creditsRedeemed) > } > ``` > [tab] Python > > ```python theme={null} > result = requests.post( > 'https://api.example.com/protected', > headers={ > 'Content-Type': 'application/json', > 'payment-signature': access_token > }, > json={'prompt': 'Hello'} > ) > > # Decode the settlement receipt from payment-response header > if result.ok: > settlement = json.loads( > base64.b64decode(result.headers.get('payment-response')).decode() > ) > # `billingModel` says how to read this receipt — see the note below > print('Billing model:', settlement.get('billingModel')) > print('Credits used:', settlement['creditsRedeemed']) > ``` > [!NOTE] > > **A `creditsRedeemed` of `"0"` does not mean the call was free.** The settle receipt carries > `billingModel`: on a `credits` plan the payment shows up as `creditsRedeemed > 0`, but on a > **pay-as-you-go** plan there is no credit balance at all, so both `creditsRedeemed` and > `remainingBalance` are always the string `"0"` — even on a charge that succeeded. There the > proof is `success: true` plus a non-empty `orderTx` (fiat rails) or `transaction` (crypto > rails). Gating on `creditsRedeemed > 0` alone reports a real charge as a decline, and on a card > rail that invites a retry of a payment that already went through. Note the values are > **strings**: `"0"` is truthy while `Number("0") > 0` is false. ## Resource server flow (API/agent side) > [!NOTE] > > **Recommended:** For Express.js applications, use the [`paymentMiddleware`](/docs/integrate/add-to-your-agent/express) which handles all of this automatically with one line of code. ### Step 1: Return 402 when payment is missing If the payment header is not present, respond with `402` and set the `payment-required` header with your payment requirements: > [tab] TypeScript > > ```typescript theme={null} > import { X402_HEADERS } from '@nevermined-io/payments/express' > > const x402Token = req.headers['payment-signature'] > > if (!x402Token) { > const paymentRequired = { > x402Version: 2, > error: 'Payment required to access resource', > resource: { url: req.path }, > accepts: [{ > scheme: 'nvm:erc4337', > network: 'eip155:84532', > planId: process.env.NVM_PLAN_ID, > extra: { > version: '1', > agentId: process.env.NVM_AGENT_ID > } > }], > extensions: {} > } > > res.set(X402_HEADERS.PAYMENT_REQUIRED, Buffer.from(JSON.stringify(paymentRequired)).toString('base64')) > return res.status(402).json({ error: 'Payment Required' }) > } > ``` > [tab] Python > > ```python theme={null} > x402_token = request.headers.get('payment-signature') > > if not x402_token: > payment_required = { > 'x402Version': 2, > 'error': 'Payment required to access resource', > 'resource': {'url': request.path}, > 'accepts': [{ > 'scheme': 'nvm:erc4337', > 'network': 'eip155:84532', > 'planId': os.environ['NVM_PLAN_ID'], > 'extra': { > 'version': '1', > 'agentId': os.environ.get('NVM_AGENT_ID') > } > }], > 'extensions': {} > } > > response = jsonify({'error': 'Payment Required'}) > response.headers['payment-required'] = base64.b64encode( > json.dumps(payment_required).encode() > ).decode() > return response, 402 > ``` ### Step 2: Verify with the facilitator Verify the x402 token with the facilitator. The facilitator extracts `planId` and subscriber address from the token: > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY, > environment: 'sandbox' > }) > > // Verify with facilitator - extracts planId/subscriberAddress from token > const verification = await payments.facilitator.verifyPermissions({ > x402AccessToken: x402Token, > maxAmount: BigInt(creditsRequired) > }) > > if (!verification.isValid) { > return res.status(402).json({ error: 'Payment verification failed' }) > } > ``` > [tab] Python > > ```python theme={null} > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox') > ) > > # Verify with facilitator - extracts planId/subscriberAddress from token > verification = payments.facilitator.verify_permissions( > x402_access_token=x402_token, > max_amount=credits_required > ) > > if not verification.is_valid: > return jsonify({'error': 'Payment verification failed'}), 402 > ``` ### Step 3: Execute Workload ```typescript theme={null} // Only execute after verification succeeds const result = await processAIRequest(req.body) ``` ### Step 4: Settle Payment Settle after work is complete and return the settlement receipt in the `payment-response` header: > [tab] TypeScript > > ```typescript theme={null} > import { X402_HEADERS } from '@nevermined-io/payments/express' > > // Settle after work is complete > const settlement = await payments.facilitator.settlePermissions({ > x402AccessToken: x402Token, > maxAmount: BigInt(actualCreditsUsed) > }) > > // Set payment-response header with settlement receipt > const settlementReceipt = { > success: true, > creditsRedeemed: actualCreditsUsed, > transactionHash: settlement.transaction > } > res.set(X402_HEADERS.PAYMENT_RESPONSE, Buffer.from(JSON.stringify(settlementReceipt)).toString('base64')) > > // Return response > res.json({ result }) > ``` > [tab] Python > > ```python theme={null} > # Settle after work is complete > settlement = payments.facilitator.settle_permissions( > x402_access_token=x402_token, > max_amount=actual_credits_used > ) > > # Set payment-response header with settlement receipt > settlement_receipt = { > 'success': True, > 'creditsRedeemed': actual_credits_used, > 'transactionHash': settlement.transaction > } > > response = jsonify({'result': result}) > response.headers['payment-response'] = base64.b64encode( > json.dumps(settlement_receipt).encode() > ).decode() > return response > ``` ## Complete Request Lifecycle ```mermaid theme={null} sequenceDiagram autonumber actor Client participant Agent as AI Agent participant Facilitator participant Chain as Blockchain Client->>Agent: GET /resource (no payment) Agent->>Client: 402 + payment-required header Client->>Client: Create delegation + generate x402 token via SDK Client->>Agent: POST /resource + payment-signature header Agent->>Facilitator: POST /verify Facilitator->>Facilitator: Validate signature & session keys Facilitator->>Chain: Check balance Chain-->>Facilitator: Balance OK Facilitator-->>Agent: Verification OK Agent->>Agent: Execute AI workload Agent->>Facilitator: POST /settle Facilitator->>Chain: Execute burn operation Chain-->>Facilitator: Tx confirmed Facilitator-->>Agent: Settlement OK + txHash Agent-->>Client: Response + payment-response header ``` ## Error Handling | Error | HTTP Status | Cause | | - | - | - | | Missing payment header | 402 | No `payment-signature` header | | Invalid signature | 402 | Signature verification failed | | Insufficient balance | 402 | User needs to purchase more credits | | Expired session | 402 | Session key has expired | | Settlement failed | 500 | On-chain transaction failed | ## Next Steps > [card] [Express.js Integration](/docs/integrate/add-to-your-agent/express) > > One-line payment protection with Express middleware > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Configure credits, subscriptions, and dynamic pricing > [card] [x402 Integration](/docs/development-guide/nevermined-x402) > > Complete integration guide with code examples > [card] [Technical Spec](/docs/specs/x402-smart-accounts) > > Full x402 Smart Accounts specification # Accepting MPP payments Source: https://nevermined.ai/docs/products/payments-facilitator/mpp-seller Advertise your plan-protected endpoint as MPP-payable, and let Nevermined meter the request exactly as it does for x402. The **Merchant Payment Protocol (MPP)** is an open HTTP-402 standard for agent-to-agent payments. If your endpoint is already protected by a Nevermined plan, you can advertise MPP as an accepted protocol on it — and every request is metered identically to x402: same plan, same credits, same delegation. > [!NOTE] > > This page is the **seller** side: your endpoint gets paid. For the opposite direction — paying an external MPP merchant through the Router — see [the MPP rail](/docs/products/catalog/router/rails-mpp). Only the wire format is shared. ## What the buyer sees An unpaid request gets an RFC 7235 challenge instead of your content: ``` HTTP/1.1 402 Payment Required WWW-Authenticate: Payment id="…", realm="api.sandbox.nevermined.app", method="nevermined", intent="charge", request="", expires="…" ``` The buyer wraps that challenge into a credential and retries: ``` Authorization: Payment ``` On success your response carries the receipt: ``` Payment-Receipt: ``` The `method="nevermined"` is the point. MPP lets a seller register a custom payment method, and paying a Nevermined endpoint is a **credit burn against a plan**, not a token transfer — so there is no wallet, no signature and no on-chain settlement in the buyer's half. The access token *is* the payment instrument. ## The three endpoints Your endpoint does not implement the protocol. It calls three routes, and the backend holds every secret: | Route | Who calls it | What it does | | - | - | - | | `POST /api/v1/mpp/challenge` | your endpoint | Mints the HMAC-bound challenge to return with the 402 | | `POST /api/v1/mpp/verify` | your endpoint | Checks a credential without burning anything | | `POST /api/v1/mpp/settle` | your endpoint | Verifies **and** burns the credits, returning the receipt | A buyer mints their access token at `POST /api/v1/mpp/permissions`, the MPP counterpart of the x402 route. > [!NOTE] > > **The signing secret never leaves the backend.** A challenge cannot be minted at your edge, which is deliberate: it means an integration ships no secret in any binary, and a compromised seller process cannot forge challenges for anyone else. ### Minting a challenge ```bash theme={null} curl -X POST https://api.sandbox.nevermined.app/api/v1/mpp/challenge \ -H "Authorization: Bearer $NVM_API_KEY" \ -H "content-type: application/json" \ -d '{ "planId": "447427630760474976400802302367814741299709927278965938619973471356131355710", "credits": "2", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015", "resource": "/api/v1/agents/:agentId/tasks", "httpVerb": "POST" }' ``` ```json theme={null} { "challenge": "Payment id=\"k7Hs…\", realm=\"api.sandbox.nevermined.app\", method=\"nevermined\", …", "id": "k7HsQ1cQ0m8bF3xw0Yy2Zr9Xv1sT4pL6nA8dC2eG0hI" } ``` Return `challenge` verbatim as your `WWW-Authenticate` header. It is HMAC-bound, so **any edit invalidates it**. ### Settling ```bash theme={null} curl -X POST https://api.sandbox.nevermined.app/api/v1/mpp/settle \ -H "Authorization: Bearer $NVM_API_KEY" \ -H "content-type: application/json" \ -d '{ "credential": "Payment eyJjaGFsbGVuZ2Ui…", "resource": "/api/v1/agents/:agentId/tasks", "httpVerb": "POST" }' ``` `resource` and `httpVerb` **must match the values the challenge was issued for**. That pair is sealed into the challenge and re-asserted here, so a credential minted for a cheap endpoint cannot be spent at an expensive one on the same plan. A mismatch is refused. ### Binding a challenge to one request body Optional, and off unless you ask for it. Pass a `digest` when you mint the challenge, and the digest of the body you actually received when you settle: ```jsonc theme={null} // POST /api/v1/mpp/challenge { "planId": "…", "credits": "2", "resource": "…", "httpVerb": "POST", "digest": "sha-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=" } // POST /api/v1/mpp/settle { "credential": "Payment …", "resource": "…", "httpVerb": "POST", "bodyDigest": "sha-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=" } ``` The digest travels inside the challenge HMAC, so the buyer cannot change which body the challenge was issued for. If the two disagree, the settle is refused with `BCK.MPP.0005` and nothing is burned. Both must be formatted `sha-256=`. A challenge minted **without** a digest binds no body — that is the seller's choice at mint time, and not something a buyer can downgrade by omitting `bodyDigest`. ## What the receipt says — and what it deliberately omits The `Payment-Receipt` attests the settlement and nothing else: ```json theme={null} { "method": "nevermined", "reference": "k7HsQ1cQ0m8bF3xw0Yy2Zr9Xv1sT4pL6nA8dC2eG0hI", "status": "success", "timestamp": "2026-08-13T10:04:11.117Z" } ``` It carries **no remaining balance**. A buyer's credit balance is not the seller's to disclose, and the receipt schema has no field it could travel in — the minimization is structural, not a matter of discipline. > [!WARNING] > > **A receipt implies no refund.** The burn is not escrowed and cannot be reversed. MPP refunds are not supported. ## Behaviour worth knowing before you integrate **Settling twice burns once.** The challenge id is the burn's idempotency key, so a retried settle is absorbed and returns success without moving credits again. That is what makes a settle safe to retry when the response is lost. **A failed settle leaves the credential spendable.** Nothing is consumed and no receipt is minted, so the buyer is never charged for a request you could not serve. **Every challenge is unique.** Two identical requests produce two distinct challenges. Since the id doubles as the settlement id, sharing one would collapse two payments into a single burn. **Credits are protocol-independent.** The same request burns the same credits whether it was paid over MPP or x402 — the two protocols share one meter and one delegation budget. ## Protocol isolation An MPP access token and an x402 one are **byte-identical on the wire**. What separates them is the EIP-712 domain they are signed under, and that is fixed by the endpoint that minted them — it is not a value a caller can select. The consequence is the property the design exists for: a token minted for MPP is refused by the x402 routes, and an x402 token is refused by the MPP routes. Posting a token to the wrong family of routes fails closed. ## Operator configuration MPP needs two deployment values, set where your other secrets live — never in application code: | Variable | What it is | | - | - | | `MPP_SECRET_KEY` | Signs and verifies the challenge HMAC. **Use a distinct value per environment** — it is the isolation boundary between them. | | `MPP_REALM` | The realm advertised in the challenge. Part of the HMAC input. | > [!WARNING] > > Rotating `MPP_SECRET_KEY` **invalidates every outstanding challenge**. Challenges are short-lived, so the blast radius is small, but roll it when traffic is quiet rather than mid-peak. When either value is missing, the MPP routes answer `BCK.MPP.0002` and **the rest of the API is unaffected** — a missing value degrades one protocol instead of causing an outage. ## Environments | Environment | API base | Key prefix | | - | - | - | | **Sandbox** | `https://api.sandbox.nevermined.app` | `sandbox:` | | **Live** | `https://api.live.nevermined.app` | `live:` | > [!WARNING] > > **The key and the host must match.** A `sandbox:` key only works against `api.sandbox.nevermined.app`, and a `live:` key only against `api.live.nevermined.app`. Crossing them fails on the very first call — see [getting an API key](/docs/agents-guide/get-api-key). ## Current scope MPP support is the Nevermined custom method — a buyer pays with a Nevermined delegation, framed as MPP. Not yet supported: * Stock MPP clients paying with native `evm` or `stripe` methods * Sessions, subscriptions and metered streams — a challenge advertising one is refused rather than approximated * MPP over MCP or A2A transports # Payments Facilitator Source: https://nevermined.ai/docs/products/payments-facilitator/overview The Nevermined Payments Facilitator verifies and settles both x402 and MPP payments against the same Nevermined Payment Plans — smart accounts, programmable contracts, and credit metering. The Nevermined Payments Facilitator is an **enforcement and settlement engine** for HTTP-native agent payments. It lets any API, agent, MCP tool, or protected resource get paid without running on-chain infrastructure — and it speaks **two sibling payment protocols that settle against the same Nevermined Payment Plans**: * **[x402](/docs/development-guide/nevermined-x402)** — payment terms travel in a `payment-required` header and the payment is presented in `payment-signature`. Covers standard "pay-per-request" x402 and Nevermined's programmable extension (`nvm:erc4337` and `nvm:card-delegation` schemes, with smart accounts, session keys, and contract settlement). * **[MPP (Merchant Payment Protocol)](/docs/products/payments-facilitator/mpp-seller)** — the same plan, credits, and delegation, negotiated with an RFC 7235 `WWW-Authenticate: Payment …` challenge and an `Authorization: Payment …` credential instead. A request that costs 2 credits burns 2 whether it was paid over x402 or MPP: **one meter, one delegation budget, two wire protocols.** > [!NOTE] > > For the complete technical specification of the x402 extension, see the [x402 Smart Accounts Extension Spec](/docs/specs/x402-smart-accounts). For the MPP seller integration, see [Accepting MPP payments](/docs/products/payments-facilitator/mpp-seller). The Facilitator sits in the payment flow — when a server receives a payment token, it delegates verification and settlement to the Facilitator rather than handling it directly. See [how the x402 flow works end to end](/docs/development-guide/nevermined-x402). ## Why use a Facilitator? A facilitator is the third party that: * verifies payment proofs * simulates/enforces what is allowed (amount, plan, merchant/agent binding) * executes settlement on-chain * returns a canonical receipt (e.g., transaction hash) This is particularly important for **programmable x402**, where settlement may be more than a single ERC-20 transfer (credits, subscriptions, policy-based settlement). ## Facilitator API ### Environments | Environment | URL | Purpose | | - | - | - | | **Sandbox** | `https://facilitator.sandbox.nevermined.app` | Testing and development with testnets | | **Production** | `https://facilitator.live.nevermined.app` | Live mainnet transactions | > [!NOTE] > > Use the sandbox environment for development and testing. Switch to production only when you're ready to process real payments. ### Core Endpoints Each protocol has its own verify/settle route pair. The plan, the credits, and the delegation underneath are identical — only the wire shape differs. **x402** — verify then settle around your workload: > [card] Verify Endpoint > > **POST** `/api/v1/x402/verify` > > Validates payment authorization, checks permissions, and simulates on-chain settlement before workload execution. > [card] Settle Endpoint > > **POST** `/api/v1/x402/settle` > > Executes on-chain settlement after workload completion and returns transaction receipt. **MPP** — a seller mints a challenge, then verifies and settles the credential the buyer returns: > [card] Challenge Endpoint > > **POST** `/api/v1/mpp/challenge` > > Mints the HMAC-bound `WWW-Authenticate: Payment` challenge to return with your `402`. > [card] Verify Endpoint > > **POST** `/api/v1/mpp/verify` > > Checks a returned credential without burning credits. > [card] Settle Endpoint > > **POST** `/api/v1/mpp/settle` > > Verifies **and** burns the credits, returning the `Payment-Receipt`. Buyers mint their access token at `POST /api/v1/x402/permissions` (x402) or `POST /api/v1/mpp/permissions` (MPP). A token minted for one protocol is refused on the other's routes — see [protocol isolation](/docs/products/payments-facilitator/mpp-seller#protocol-isolation). Full MPP seller reference: [Accepting MPP payments](/docs/products/payments-facilitator/mpp-seller). ## How it works ```mermaid theme={null} sequenceDiagram participant Client participant Server as Resource Server (API/Agent) participant Facilitator as Nevermined Payments Facilitator participant Chain as Blockchain Client->>Server: Request Server-->>Client: 402 + payment-required header Client->>Client: Generate x402 token via SDK Client->>Server: Retry + payment-signature header Server->>Facilitator: /verify (simulate + validate) Facilitator->>Chain: Policy + balance checks Facilitator-->>Server: Verification OK Server->>Server: Execute workload Server->>Facilitator: /settle (execute settlement) Facilitator->>Chain: Execute contract settlement Facilitator-->>Server: Receipt + txHash Server-->>Client: Response + payment-response header ``` ## Nevermined's programmable x402 extension Standard x402 is often implemented as an "exact transfer" authorization (e.g., EIP-3009). Nevermined extends x402 to support: * **Smart Accounts (ERC-4337)** and delegated **session keys** * **Smart-contract settlement** (credits, subscriptions, PAYG, dynamic charging) * **Policy enforcement** (merchant allowlists, spend caps, validity windows) This keeps the HTTP handshake the same, but upgrades settlement from "transfer" to **programmable execution**. ## Facilitator responsibilities ### Verification * x402 envelope structure/version * signature authenticity * session key validity + scoped permissions * plan state + subscriber balance * simulation of allowed on-chain actions (UserOps) ### Settlement After the server completes its work, the facilitator can execute the settlement action permitted by the payment payload, such as: * `order` (purchase/top-up) * `redeem` / `burn` (consume credits) * "exact" transfers (when using standard x402) ## Getting started > [card] [Express.js Integration](/docs/integrate/add-to-your-agent/express) > > One-line payment protection with Express middleware > [card] [How It Works](/docs/products/payments-facilitator/how-it-works) > > End-to-end flow (client + server) with x402 headers and facilitator calls > [card] [Accepting MPP payments](/docs/products/payments-facilitator/mpp-seller) > > Advertise your plan-protected endpoint as MPP-payable, metered exactly like x402 > [card] [Payment Models](/docs/integrate/patterns/payment-models) > > Credits, subscriptions, and dynamic pricing using programmable settlement > [card] [x402 Protocol](/docs/development-guide/nevermined-x402) > > Integrate x402 into your API/agent > [card] [Google A2A](/docs/integrations/google-a2a) > > Use x402 with A2A + AP2-style payment intent messaging # Braintree Onboarding Source: https://nevermined.ai/docs/products/payments/braintree-onboarding Connect your Braintree merchant account to Nevermined so buyers can pay your plans by card and receive funds in your supported currencies. ## Overview Nevermined supports **Braintree** as a fiat settlement provider alongside Stripe. Sellers who connect a Braintree merchant account can price their plans in Braintree-supported currencies and receive funds directly into their own Braintree gateway. This page covers the seller-side setup: connecting your Braintree account, configuring per-currency merchant accounts, and what to expect at plan creation and settlement time. If you only need to *pay* for a Braintree-priced plan as a buyer, see [Card Enrollment](/docs/products/payments/card-enrollment) instead. ## Why Braintree? Use Braintree when: * You already operate on Braintree and want funds to land directly in your existing gateway. * You need merchant-of-record relationships under your own underwriting agreements (per currency). * You want a uniform settlement on both subscription checkout and per-request x402 charges, without holding a Stripe Connected Account. Stripe remains the right choice when you want the simplest onboarding (Stripe Connect express) and don't have a multi-currency requirement that maps cleanly to Braintree's child merchant account model. The choice is per plan, not per seller — `fiatPaymentProvider` is set on each plan at creation time, so a single seller can run some plans on Stripe and others on Braintree. ## Prerequisites Before connecting Braintree to Nevermined, you need: **1. A Braintree gateway account** Sign up at [braintreepayments.com](https://www.braintreepayments.com/). Sandbox is enough for development; you'll need a production gateway before charging real cards. **2. At least one child merchant account in your target currency** Each Braintree merchant account is bound to a single currency. To accept USD-priced plans you need a USD merchant account; to accept EUR-priced plans you need an EUR merchant account. Sellers add new currencies in their own Braintree dashboard — Nevermined never creates merchant accounts on your behalf. **3. Permission to authorize OAuth applications** Nevermined uses Braintree's OAuth Connect (Braintree Auth) to talk to your gateway. The user who authorizes the connection must be able to grant gateway scopes on your account. > [!NOTE] > > Currently supported plan currencies for Braintree are **USD** and **EUR**. You can configure both, either, or just one — Nevermined gates plan creation per currency based on what your gateway actually supports. ## Connecting Your Braintree Account Connection happens once per organization, from its Organization page (you must be an Admin of the organization): **1. Open your Organization page** In the [Nevermined App](https://nevermined.app), select the organization, open its **Organization** page and find the **Braintree** card. **2. Click Connect Braintree** You'll be redirected to Braintree's OAuth consent screen, which lists the gateway scopes Nevermined needs (transaction creation, refunds, settlement management, and merchant account discovery). Approve the connection. **3. Return to Nevermined** Braintree redirects you back to Nevermined. The facilitator stores the OAuth access and refresh tokens server-side, then immediately calls Braintree to enumerate the child merchant accounts on your gateway. **4. Confirm your supported currencies** The Braintree card now shows one badge per currency Nevermined can charge on your behalf — for example **USD** and **EUR**. If a currency is missing, add the corresponding child merchant account in your Braintree dashboard, then disconnect and reconnect to re-discover. ### What gets stored After connecting, Nevermined holds three pieces of information about your account: | Stored | Purpose | | - | - | | OAuth access + refresh tokens | Authorize server-side calls to your Braintree gateway. Refresh tokens rotate automatically. | | Braintree merchant ID | Identifies your gateway when constructing per-request `BraintreeGateway` clients. | | `currency → merchantAccountId` map | Routes each charge to the right child merchant account at settlement time. | Raw card data, customer details, and transaction PII never leave Braintree — Nevermined only stores the routing handles. ### Disconnecting Click **Disconnect Braintree** on the Organization page to end the connection. Nevermined revokes the access token it held and clears all four fields above (access token, refresh token, merchant ID, and the per-currency map). Existing delegations against your account stop being chargeable on the next request. Disconnecting does **not** remove Nevermined from your Braintree account. Braintree's API can revoke an access token but not your authorization of the app, so Nevermined stays listed under **OAuth → Connected Apps** in your Braintree Control Panel. Reconnecting may reuse that authorization, so it may skip the consent screen. To remove Nevermined entirely, click **Revoke Access** next to it in the Control Panel. If Braintree does not confirm the token revoke, the Organization page warns you, and the API's `DELETE /api/v1/fiat/braintree/disconnect` response reports `accessTokenRevocation: "failed"`. Nevermined still discards the connection. ## Per-Currency Merchant Accounts Braintree binds each merchant account to a single currency. To price a plan in EUR you need an EUR merchant account on your gateway; pricing the same plan in USD additionally needs a USD merchant account. This is a Braintree-side requirement, not a Nevermined one. Adding a merchant account to your gateway is a self-service action in the Braintree dashboard for sandbox accounts; production accounts may require Braintree to complete underwriting first. After adding a new currency in Braintree: 1. Disconnect Nevermined's Braintree connection. 2. Reconnect — re-authorization usually completes in two clicks, because Braintree may skip the consent screen for an app you have already authorized. 3. The newly available currency badge appears on the Organization page. There is no manual "Refresh" button. Currency changes on your side are rare enough that the disconnect+reconnect path is the simplest way to re-trigger discovery. ## Plan Creation: Currency Guard When you create a plan with `fiatPaymentProvider: 'braintree'`, Nevermined checks the plan's currency against the merchant accounts discovered at connection time: * **Currency available** → plan creation succeeds. Buyers can purchase the plan and receive credits. * **Currency missing** → plan creation is rejected with `BCK.BRAINTREE.0008`. Add the child merchant account in your Braintree dashboard, then disconnect and reconnect Nevermined before retrying. The plan-creation form in the Nevermined App enforces this client-side too: when you select Braintree as the provider, the currency dropdown only shows the currencies your gateway supports, with a tooltip pointing you to the Organization page if none are available yet. ## Settlement Model Once a plan is live, Nevermined settles each fiat charge with **one sale** for the whole price. It runs on your OAuth-connected gateway, against your per-currency child merchant account that matches the plan's currency. The sale carries the network token of the buyer's enrolled card. Nevermined takes no fee from the sale; fees are agreed directly with Nevermined. This applies to both: * One-time **subscription checkouts** in the Nevermined App, paid with an enrolled card. * Per-request **x402 settlements** for credit top-ups when a buyer's balance is insufficient (see [the x402 card-delegation spec](/docs/specs/x402-card-delegation) for the protocol-level details). ## Limitations * **Currencies**: USD and EUR only. Reach out if you need additional currencies; we'll add them when there's a clear use case. * **Refresh tokens rotate**: long-lived CI tokens against real Braintree accounts are not feasible. Test integrations should mock the gateway or use a developer's interactive sandbox session. * **Re-discovery requires reconnect**: changing your gateway's set of merchant accounts requires disconnecting and reconnecting Nevermined. Currency changes on the seller side are rare enough that this is acceptable; let us know if it becomes a friction point. ## Troubleshooting | Symptom | Likely cause | Fix | | - | - | - | | "No currency-specific merchant accounts found" on the Organization page | Your Braintree gateway has merchant accounts but they weren't discovered (e.g. legacy OAuth scope, or all accounts are inactive) | Disconnect and reconnect; the OAuth flow re-runs discovery with the latest scope. | | Plan creation rejected with `BCK.BRAINTREE.0008` | The chosen currency has no child merchant account on your gateway | Add the merchant account in Braintree, then disconnect and reconnect Nevermined. | | x402 charge fails with `BCK.BRAINTREE.0007` at settlement time | Your gateway no longer has a merchant account in the plan's currency (e.g. it was deactivated after plan creation) | Re-add the merchant account in Braintree and reconnect. Existing credit balances on buyers' accounts can still be redeemed; only new card charges are blocked. | ## Related Pages > [card] [Card Enrollment (Buyer-Side)](/docs/products/payments/card-enrollment) > > How buyers enroll a card before purchasing your plans. > [card] [x402 Card Delegation Spec](/docs/specs/x402-card-delegation) > > Protocol-level details for per-request fiat settlement. # Card Enrollment Source: https://nevermined.ai/docs/products/payments/card-enrollment Enroll a payment card into Nevermined with PCI-compliant tokenization. ## Overview Before an agent can charge a payment card, the card must be enrolled in Nevermined. Enrollment tokenizes the card data (Nevermined never stores raw card numbers) and registers the card with the provider so future delegations can authorize off-session charges. The [Nevermined App](https://nevermined.app) has one card form, and it captures every card through VGS. You don't choose a provider to pay a Stripe-priced or a Braintree-priced plan: the plan's `fiatPaymentProvider` metadata picks the provider that charges the card, at charge time. * **Stripe-priced plans** and **Braintree-priced plans** are paid with a card enrolled through the credit/debit card form. * **Visa Trusted Agent plans** require a Visa Agentic Token (enrolled through the Visa Agentic option on the same form, where it is offered). ## Enrollment Paths > [tab] Visa > > ### Visa Enrollment > > Visa cards are enrolled as **Visa Agentic Tokens** through the VGS Credential Management Platform (CMP). Card capture happens in a VGS Collect iframe in the Nevermined webapp, so the raw PAN never reaches Nevermined infrastructure. > > **1. Capture card data** > > Enter your card details in the VGS Collect iframe rendered by the webapp. VGS Collect's `form.createCard()` posts the tokenized card directly to CMP and returns a CMP `cardId` (`CRD…`) to the browser. The PAN and CVC never transit the Nevermined backend. > > **2. Mint the Agentic Token** > > The browser sends only the `cardId` (plus BIN-derived `last4`, `brand`, and `expMonth`/`expYear`) to `POST /api/v1/delegation/enroll-visa`. The backend calls VGS Agentic `POST /cards/{cardId}/agentic-tokens` to mint the long-lived Agentic Token (`vat_…`) and persists it as the card's `providerPaymentMethodId`. > > **3. Create a delegation** > > After enrollment, create a [spending delegation](/docs/products/payments/mandates). Each Visa delegation requires a one-time WebAuthn/passkey device-binding ceremony embedded by Visa VTS — see the Visa tab on the [Delegations](/docs/products/payments/mandates) page. > > #### Visa Card Lifecycle > > ``` > PAN captured in VGS Collect iframe > | > |-> CMP card created (cardId) > | > |-> Backend enrolls Agentic Token (vat_…) > | > |-> PaymentMethodEntity persisted (provider='visa') > | > |-> Active -> Delegations can be created > | > |-> Removed (card and all delegations revoked) > ``` > > > [!NOTE] > > > > VGS Agentic Tokens are keyed on PAN globally. Re-enrolling the same physical card always resolves to the same `cardId`/`tokenId`. If the card is already enrolled under a different Nevermined account, enrollment returns `BCK.VISA.0018` (HTTP 409). > > > [!NOTE] > > > > No passkey is required at enrollment. The WebAuthn/passkey ceremony happens once per delegation, not once per card. > > > [!NOTE] > > > > Visa enrollment is only reachable from the Nevermined webapp. The `/api/v1/delegation/enroll-visa` endpoint expects a CMP `cardId` produced by VGS Collect in the browser; it cannot be driven from a server-side SDK or curl call. > [tab] Credit/debit card > > ### Credit/debit card enrollment > > A card for a Stripe-priced or a Braintree-priced plan is enrolled through the webapp's "Credit/debit card" form. The card is captured in a VGS Collect iframe and vaulted at VGS, not at Stripe or Braintree: the plan you pay picks the provider that charges it, at charge time. This is a single-step flow with no passkey requirement. > > **1. Enter card details** > > Enter your card number, expiry, and CVC into the VGS Collect iframe. VGS Collect creates the card directly at VGS and returns a card ID (`CRD…`) to the browser. The PAN and CVC never transit the Nevermined backend. > > **2. Enroll the card** > > The webapp posts the card ID to `POST /api/v1/delegation/enroll`. The API provisions a network token for the card and records it under your account. > > **3. Create a delegation** > > After enrollment, create a [spending delegation](/docs/products/payments/mandates) to define how agents can charge this card. > > #### Card Lifecycle > > ``` > PAN captured in VGS Collect iframe > | > |-> VGS card created (cardId) > | > |-> Backend provisions a network token and records the card > | > |-> Active -> Delegations can be created > | > |-> Removed (card and all delegations revoked) > ``` > > > [!NOTE] > > > > A Braintree-priced plan can only be charged when its seller has a Braintree merchant account in the plan's currency. See [Braintree onboarding](/docs/products/payments/braintree-onboarding) for the seller-side per-currency requirements. ## Card Properties All enrolled cards share these core properties: | Property | Description | | - | - | | `id` | Unique payment-method identifier (UUID) | | `userId` | Owner of the card | | `provider` | `visa`, `vgs` (a card enrolled through the credit/debit card form), or `braintree` / `stripe` (a card enrolled outside that form) | | `providerPaymentMethodId` | Provider-side card reference. Visa: `vat_…` (Agentic Token). VGS: the VGS card ID (`CRD…`). Braintree: `paymentMethodToken`. Stripe: `pm_…`. | | `last4` | Last 4 digits of the card number (for display) | | `brand` | Card brand (`visa`, `mastercard`, …) | | `alias` | User-friendly name (e.g., "Work Visa", "Dev Card") | | `status` | `active` or `inactive` | ## Managing Cards ### Via the Nevermined App The [Nevermined App](https://nevermined.app) provides a visual interface for managing your enrolled cards. All your cards appear in one list: * View all enrolled cards with their status * See active delegations per card with remaining budget * View transaction history for each card * Deactivate or remove cards ### Via the API The payment-methods endpoint is heterogeneous: it lists enrolled cards across all providers plus, when the user has a smart account configured, the ERC-4337 wallet entry that backs crypto delegations. Filter by `provider` to narrow to a single shape: a card enrolled through the credit/debit card form is `provider=vgs`, not `stripe` or `braintree`. | Endpoint | Method | Description | | - | - | - | | `/api/v1/payment-methods` | `GET` | List enrolled payment methods (cards + ERC-4337 wallet) | | `/api/v1/payment-methods/{id}` | `PATCH` | Update alias or allowed API keys | | `/api/v1/payment-methods/{id}` | `DELETE` | Remove card and revoke all delegations on it | | `/api/v1/delegation/{id}/transactions` | `GET` | Per-delegation transaction history | ## Choosing a Provider | | Visa | Credit/debit card | | - | - | - | | **Enrollment complexity** | VGS Collect capture, no passkey at enrolment | VGS Collect capture, no passkey at enrolment | | **Per-delegation auth** | WebAuthn/passkey device binding (browser-only) | API credentials only | | **Best for** | Visa Trusted Agent Protocol plans, high-security agent payments | Stripe-priced and Braintree-priced plans, quick setup, developer testing, broader card support | | **Settlement** | Stripe Connect against the seller's connected account | Set by the plan: Stripe PaymentIntents directly, or a Braintree sale with the card's network token on the seller's OAuth-connected merchant account | Both support the same spending controls (spending limits, usage limits, expiration) and API key linking. The plan's `fiatPaymentProvider` metadata decides how a credit/debit card settles, so the same card can pay a Stripe-priced and a Braintree-priced plan. A Visa Trusted Agent plan can only be paid by a Visa Agentic Token. To see which provider a plan settles on, read it from the plan. `resolveNetwork()` / `resolve_network()` returns the plan's card provider (`stripe` or `braintree`), or `undefined`/`None` if the plan sets no `fiatPaymentProvider`: > [tab] TypeScript > > ```typescript theme={null} > import { resolveNetwork } from '@nevermined-io/payments' > > const provider = await resolveNetwork(payments, planId) > // 'stripe' | 'braintree' for a fiat plan that sets fiatPaymentProvider; otherwise undefined > ``` > [tab] Python > > ```python theme={null} > from payments_py.x402.resolve_scheme import resolve_network > > provider = resolve_network(payments, plan_id) > # 'stripe' | 'braintree' for a fiat plan that sets fiatPaymentProvider; otherwise None > ``` For `stripe` or `braintree`, enroll through the credit/debit card form, then [create a delegation](/docs/products/payments/mandates) from the enrolled card. If `resolveNetwork` returns nothing, the plan sets no `fiatPaymentProvider`: it is a crypto plan, or a fiat plan registered without one. ## What's Next? Once your card is enrolled, create a spending delegation to control how agents can charge it. > [card] [Create a Delegation](/docs/products/payments/mandates) > > Define spending limits, usage caps, and expiration for agent payments # Certifications Source: https://nevermined.ai/docs/products/payments/certifications Nevermined's security certifications — SOC 2 Type II, ISO/IEC 27001:2022, and PCI SAQ-D — and how to access the reports through the Trust Center. When an agent spends money without a human in the loop, the guardrails around it are only as trustworthy as the infrastructure enforcing them. Nevermined is independently audited so you don't have to take that on trust. > [card] SOC 2 Type II > > An attestation report covering how our security controls **operated over time**, not just how they were designed. > [card] ISO/IEC 27001:2022 > > Certification of our information security management system (ISMS) against the current 2022 revision. All reports and certificates are available through the [Nevermined Trust Center](https://trustcenter.nevermined.ai). The control list is public; the reports themselves are released under NDA — see [Access the reports](#access-the-reports). ## What each one covers The two are often mentioned together, but they answer different questions. **ISO/IEC 27001:2022** certifies the *system*. It asks whether you run a real information security management system: risk assessments, defined ownership, policies that exist and are followed, and a loop that catches problems and closes them. It's issued by an accredited certification body. **SOC 2 Type II** attests to the *evidence*. It asks whether the controls you claim to have actually operated across a window of time, with proof for each one. Strictly speaking it's an attestation report from auditors rather than a certification. > [!NOTE] > > SOC 2 comes in two types, and the difference matters. **Type I** evaluates whether controls are designed correctly at a single point in time. **Type II** evaluates whether they operated effectively over a period. Nevermined holds **Type II**. ## Card data and PCI Card payments add a further requirement on top of the two above. Nevermined operates at **PCI SAQ-D** level. Raw card numbers are captured by a PCI-compliant vault and tokenized before they reach our systems, using VGS Collect. Nevermined never sees or stores the raw PAN. See [Card Enrollment](/docs/products/payments/card-enrollment) for how tokenization works in each path. ## Controls The Trust Center publishes **67 controls** under continuous monitoring, grouped into five categories: | Category | What it covers | | - | - | | Infrastructure security | Production authentication, encryption key access, account controls | | Organizational security | Code of Conduct, confidentiality agreements, anti-malware | | Product security | Data transmission encryption, vulnerability and system monitoring | | Internal security procedures | Continuity and disaster recovery, configuration management | | Data and privacy | Data retention, data classification, customer data deletion | Monitoring is continuous rather than annual, so control drift surfaces when it happens rather than at the next audit window. Each control's current status is visible on the Trust Center before you talk to anyone. ## Access the reports **1. Open the Trust Center** Go to [trustcenter.nevermined.ai](https://trustcenter.nevermined.ai). The control list and the engagement letter are public. **2. Request access** Click **Request access** to view the gated documents — the SOC 2 Type II report, the ISO/IEC 27001:2022 certificate, and the Data Management Policy. **3. Review under NDA** Gated documents are released under NDA. Access is typically granted within one business day. ## For security reviews If you're completing a vendor security assessment, the Trust Center is the fastest path: it carries the certifications, the control list, and the policies most questionnaires ask for. For questions it doesn't answer — a bespoke questionnaire, a DPA, or scope specifics — [contact the Nevermined team](https://www.nevermined.ai/contact-us/). ## Related > [card] [FAQ](/docs/products/payments/faq) > > Common questions on certifications, card delegation, and settlement. > [card] [Card Enrollment](/docs/products/payments/card-enrollment) > > How card data is tokenized before it reaches Nevermined. # FAQ Source: https://nevermined.ai/docs/products/payments/faq Frequently asked questions about Nevermined, card delegation, security certifications, Stripe Connect, Visa Agentic Tokens, and Stripe / Braintree settlement. ## Agent Payments How agents pay with your real card, within limits you control. > [accordion] How do card payments work? > > The Nevermined App lets you enroll a Visa, Stripe, or Braintree card, set spending limits, and let agents charge it directly via x402. No checkout pages, no human in the loop. Manage everything at [nevermined.app](https://nevermined.app). > [accordion] Can agents charge my card without my approval? > > Only within the limits you set. When you create a delegation, you define a lifetime spending limit, maximum number of transactions, and duration. The agent can only charge within these bounds, and you can revoke a delegation at any time. Visa delegations additionally require a one-time WebAuthn/passkey approval bound to those exact limits. > [accordion] Do I need a crypto wallet? > > Not for card payments. Nevermined works with regular Visa, Mastercard, Amex, and Discover cards through Visa, Stripe, or Braintree, and those payments settle entirely on card rails — no wallet, no stablecoins. > > A wallet is only needed if you choose to pay a plan priced in stablecoins. See [Stablecoin Payments](/docs/integrate/patterns/stablecoin-payments) for that path. > [accordion] How is this different from issuing a prepaid card for my agent? > > Card Delegation uses your real credit or debit card, not a separate prepaid balance. At enrollment, the card number is tokenized by a PCI-compliant vault (VGS Collect). Nevermined never sees or stores the raw PAN. What the agent receives is a scoped delegation that encodes identity, spending limits, and (for Visa) the device that approved it. The actual charge still runs on existing card rails, so it appears on your normal statement. No prefunding, no separate balance to manage. > [accordion] What happens if an agent tries to exceed the delegation? > > The transaction is rejected instantly before it reaches the payment processor. Delegations are enforced server-side on every verify and settle call. The agent receives a clear 402 error explaining which limit was hit (lifetime spending limit, transaction count, or duration), so it can adapt its behavior or notify the user. > [accordion] Can I use Card Delegation with any AI agent framework? > > Yes. Any software that can make an HTTP request can use x402 payments. That includes OpenAI Assistants, Anthropic Claude, LangChain, CrewAI, Strands, MCP tool servers, and custom agents. Nevermined also provides TypeScript and Python SDKs, a CLI, and an MCP server for convenience, but none are required. > [accordion] How do I revoke an agent's ability to spend? > > One click in the [dashboard](https://nevermined.app) or `DELETE /api/v1/delegation/{delegationId}`. Revocation is immediate: no grace period, no cached tokens, and no pending window. The agent loses payment capability the instant you revoke, and any in-flight verify/settle calls fail with `DELEGATION_INACTIVE`. > [accordion] What's the difference between the Visa, Stripe, and Braintree settlement paths? > > From the agent's perspective, nothing changes. It sends the same x402 payment header either way. The difference is in how settlement runs under the hood: > > * **Visa path** — Your card is tokenized as a Visa Agentic Token via the VGS Credential Management Platform. Each delegation is bound to your device with a one-time WebAuthn/passkey ceremony enforced by Visa VTS. Settlement runs through Stripe Connect against the seller's connected account. > * **Stripe path** — Your card is enrolled through VGS, and settlement runs through Stripe PaymentIntents directly. The seller connects their Stripe account when they enroll with Nevermined. > * **Braintree path** — Your card is enrolled through VGS, and settlement is one sale, with the card's network token, against the seller's per-currency OAuth-connected Braintree merchant account. > > In all three cases, sellers enroll with Nevermined to accept agent payments. Nevermined handles the x402 protocol, agent authentication, delegation enforcement, and settlement on their behalf. ## Security & Certifications Independent audits, and where to read them. > [accordion] What security and compliance standards does Card Delegation meet? > > Card data is captured via a PCI-compliant vault (VGS Collect) and tokenized before it enters the system. Nevermined holds ISO/IEC 27001:2022 certification and a SOC 2 Type II report, and operates at PCI SAQ-D level. For Visa, Strong Customer Authentication via WebAuthn/passkey (or email OTP fallback) is enforced **per delegation** by Visa VTS. Every transaction is logged with agent ID, amount, merchant, and timestamp for full auditability. See [Certifications](/docs/products/payments/certifications) for the full picture. > [accordion] Is Nevermined SOC 2 and ISO 27001 certified? > > Yes. Nevermined has completed a **SOC 2 Type II** audit and is certified against **ISO/IEC 27001:2022**. Both are published on the [Trust Center](https://trustcenter.nevermined.ai), along with 67 controls under continuous monitoring. > [accordion] What's the difference between SOC 2 Type I and Type II? > > Type I evaluates whether controls are **designed** correctly at a single point in time. Type II evaluates whether those controls **operated** effectively across a period, with evidence for each one. Nevermined holds Type II. > [accordion] How do I get a copy of the SOC 2 report or the ISO certificate? > > Both are available through the [Trust Center](https://trustcenter.nevermined.ai). The control list and engagement letter are public; the SOC 2 Type II report, the ISO/IEC 27001:2022 certificate, and the Data Management Policy are released under NDA via **Request access**. > [accordion] Do you support vendor security reviews and questionnaires? > > Yes. Start with the [Trust Center](https://trustcenter.nevermined.ai) — it carries the certifications, the control list, and the policies most questionnaires ask for. For anything it doesn't cover, including bespoke questionnaires and DPAs, [contact the team](https://www.nevermined.ai/contact-us/). > [accordion] Is Nevermined PCI compliant? > > Nevermined operates at PCI SAQ-D level. See [Card Enrollment](/docs/products/payments/card-enrollment) for how the vault tokenizes your card before it reaches us. ## Delegation Selection How agents pick which delegation to charge. > [accordion] How does my agent know which delegation to use? > > There are three ways the system resolves which delegation to charge, from simplest to most explicit: > > 1. **Automatic** — If your API key has access to exactly one active delegation, it is selected automatically. Just pass your API key and go. If there are zero or multiple delegations, you get a clear error asking you to be more specific. > 2. **Key-linked** — Link a specific delegation to a specific API key, either when you create the delegation or by revoking and recreating it. The system always routes that key to its linked delegation, even if you have multiple delegations active. Only the linked key can use that delegation. > 3. **Explicit delegation ID** — Pass `delegationId` in `delegationConfig` for full control. This is the only supported mode for Visa. > > See [Delegation Selection](/docs/products/payments/mandate-selection) for the full resolution algorithm. > [accordion] When should I link an API key to a delegation? > > If you have one delegation and one API key, you don't need to link them. Automatic selection handles it. Linking becomes useful when you have multiple delegations and want each agent (or API key) to use a specific one without passing a delegation ID on every request. It's the recommended approach for multi-agent setups on Stripe and Braintree, and a useful convenience for Visa. > [accordion] What happens if I have multiple delegations and no key linked? > > The automatic selection will fail because the system can't determine which delegation to charge. Your agent receives a 402 error explaining that multiple delegations are available. You can resolve this by either linking your API key to a specific delegation, or passing the `delegationId` explicitly. > [accordion] Can the same API key be used across Visa, Stripe, and Braintree? > > Yes. API keys are provider-agnostic. The same key works for delegations on any network. The link is stored as `apiKeyId` directly on the delegation record, so each delegation independently decides whether to honor the caller's key. > [accordion] How do I change which delegation an API key is linked to? > > Delegations are immutable. To change the link, revoke the existing delegation and create a new one with the desired `apiKeyId`. For Visa, this also requires a fresh WebAuthn/passkey device-binding ceremony. ## Stripe Settlement through Stripe's network. > [accordion] How does the Stripe settlement path work? > > When you enroll a card via Stripe, VGS Collect tokenizes the PAN and Stripe vaults it as a `pm_…` PaymentMethod. When your agent makes a payment, Nevermined creates an off-session PaymentIntent against that PaymentMethod, optionally routing to the seller's Stripe Connect account. The payment is wrapped in the x402 protocol, so the seller (or a facilitator) triggers the flow by responding with a 402 status code. > [accordion] What does a seller need to accept Stripe-path payments? > > The seller enrolls with Nevermined and connects their Stripe account via Stripe Connect. Once enrolled, they can receive payments from AI agents via the x402 protocol. The seller needs an active Stripe account since the Stripe path settles through Stripe's network. Nevermined handles agent authentication, delegation enforcement, and the x402 flow on the seller's behalf. > [accordion] Which cards work with Stripe? > > Stripe supports most Visa, Mastercard, American Express, and Discover cards. Both credit and debit cards are eligible. The card is tokenized at enrollment and charges appear on your normal statement. ## Visa Agentic Tokens Settlement through Visa's Trusted Agent Protocol. > [accordion] Is this a sandbox integration, or production Visa infrastructure? > > Production-ready. Nevermined integrates with the Visa Trusted Agent Protocol through the VGS Credential Management Platform (CMP) and Visa VTS device-binding service. Your enrolled card becomes a Visa Agentic Token bound to Nevermined as the token requestor, and every delegation captures a fresh WebAuthn/passkey approval before it can charge. > [accordion] How does VGS Credential Management Platform protect my card? > > At enrollment, your real PAN is captured by a VGS Collect iframe and posted directly to CMP. It never passes through or is stored by Nevermined. CMP mints a Visa Agentic Token (`vat_…`) bound to Nevermined as the token requestor. Even if the token were compromised, it can't be used outside the Nevermined ecosystem, and you can revoke it instantly from the dashboard. > [accordion] What is the device-binding step and why does it matter? > > Every Visa delegation requires a one-time WebAuthn/passkey ceremony — an iframe embedded by Visa VTS prompts you to approve the spending limit, duration, and merchant. Approving produces a single-use `assuranceData` blob that binds the delegation to your device. This means even if an agent is compromised, it can't widen its own spending power without your hardware key. It's purpose-built for high-frequency, autonomous agent payments. > [accordion] What if I don't have a passkey? > > Visa VTS falls back to an email OTP delivered to the address on file for your CMP cardholder. The webapp surfaces an OTP input when the SDK reports `needsOtp: true`. > [accordion] What does a seller need to accept Visa-path payments? > > The seller must have completed Stripe Connect onboarding — Visa delegations settle through Stripe Connect against the seller's connected account. The seller does not need any direct relationship with Visa or VGS; Nevermined acts as the token requestor. Visa delegations also require a `planId` so the delegation binds to a single seller per the Trusted Agent Protocol. > [accordion] Can I create a Visa delegation from the SDK or CLI? > > No. Visa delegation creation requires `consumerPrompt` and `assuranceData`, both of which can only be produced by the WebAuthn ceremony embedded in the Nevermined webapp. The SDK and CLI surface explicit errors (`BCK.VISA.0014`) when callers attempt `create_delegation(provider="visa", ...)`. You can, however, **consume** an existing Visa delegation from the SDK by passing its `delegationId` to `DelegationConfig` exactly like Stripe or Braintree. > [accordion] Which cards are eligible for Visa Agentic Tokens? > > Any Visa card whose issuer participates in the Visa Trusted Agent Protocol. During the pilot, support is concentrated on US issuers; the eligibility list is widening as more issuers integrate. ## Limits & Seller Onboarding Spending limits and accepting agent payments. > [accordion] What are the current spending limits? > > Each delegation has the spending limit, transaction limit and duration you set when you create it. > [accordion] How do I onboard as a seller? > > Contact the Nevermined team to schedule a seller onboarding call. Once enrolled, your business can accept payments from AI agents via the x402 protocol. Sellers on Stripe complete Stripe Connect; sellers on Braintree complete OAuth Connect with at least one child merchant account per accepted currency. Visa Trusted Agent plans require the seller's Stripe Connect account because Visa delegations settle through Stripe Connect. > [accordion] Do merchants need to integrate with Nevermined? > > No. Agents pay on real card rails (Visa, Mastercard). If a merchant accepts cards today, they already accept agent payments. No new SDK, no new settlement flow. ## Stripe Connect Nevermined uses [Stripe Connect](https://stripe.com/connect) to route fiat payments directly to your Stripe account. You need to connect a Stripe account before you can receive credit card payments from your users. > [accordion] What's the difference between Stripe Connect and card delegation? > > **Stripe Connect** is for *builders* receiving fiat payouts. You connect your Stripe account so Nevermined can route revenue to you. > > **Card delegation** is for *users* who want agents to pay with their card. The user enrolls a card, creates a spending delegation, and agents charge against it via x402. > > They serve different sides of the transaction: Stripe Connect handles payouts to builders, card delegation handles card-based payments from users. > [accordion] How do I connect my Stripe account? > > **1. Go to your User Profile** > > Open the [Nevermined App](https://nevermined.app) and navigate to **Settings > User Profile**. Scroll down to the **Stripe** section. > > **2. Click Connect Stripe** > > Click the **Connect Stripe** button. This opens Stripe's onboarding flow where you'll set up or link your Stripe account. > > **3. Skip phone verification (sandbox)** > > In the sandbox environment, you'll see a banner saying "You're using a test account with test data." Click **Use test phone number** to skip SMS verification. > > ![Stripe Connect phone verification step](https://mintcdn.com/neverminedag/dGqQPOVpr92RjAlB/images/faq/stripe-connect-phone-verification.png?fit=max\&auto=format\&n=dGqQPOVpr92RjAlB\&q=85\&s=7ccbe839d076d008fa84d87848eb2d21) > > **4. Skip SMS verification (sandbox)** > > Click **Use test code** to auto-fill the test code `000000` and continue. > > ![Stripe Connect test code step](https://mintcdn.com/neverminedag/dGqQPOVpr92RjAlB/images/faq/stripe-connect-test-code.png?fit=max\&auto=format\&n=dGqQPOVpr92RjAlB\&q=85\&s=9451befd3fbe2a78a3f17caaa94b68bd) > > **5. Select business type (sandbox)** > > Select **Individual** from the business type dropdown and click **Continue**. > > ![Stripe Connect business type step](https://mintcdn.com/neverminedag/dGqQPOVpr92RjAlB/images/faq/stripe-connect-business-type.png?fit=max\&auto=format\&n=dGqQPOVpr92RjAlB\&q=85\&s=f2391d28300a5c8a4d770ef68456b74e) > > **6. Fill in personal details (sandbox)** > > Use these test values: > > | Field | Test value | > | - | - | > | Legal first name | `Sarah` | > | Legal last name | `Mitchell` | > | Date of birth | `15 / 03 / 1990` | > | Address | `350 Fifth Avenue` | > | City | `New York` | > | State | `New York` | > | Zip code | `10118` | > | Last 4 SSN | `0000` | > > > [!WARNING] > > > > Use `0000` for the last 4 digits of SSN. Any other value may trigger Stripe's additional identity verification flow. > > ![Stripe Connect personal details step](https://mintcdn.com/neverminedag/dGqQPOVpr92RjAlB/images/faq/stripe-connect-personal-details.png?fit=max\&auto=format\&n=dGqQPOVpr92RjAlB\&q=85\&s=d45efd8314616a786f62fcabb7da2205) > > **7. Add bank details for payouts (sandbox)** > > Click **Use test account** to auto-fill the test routing number (`110000000`) and account number (`000123456789`), then click **Continue**. > > ![Stripe Connect bank details step](https://mintcdn.com/neverminedag/dGqQPOVpr92RjAlB/images/faq/stripe-connect-business-details.png?fit=max\&auto=format\&n=dGqQPOVpr92RjAlB\&q=85\&s=87a29b38e34d234ae745436335814680) > > **8. Review and submit** > > Review everything and click **Agree and submit**. You'll be redirected back to the Nevermined App and see a "Stripe successfully connected" confirmation. > > ![Stripe Connect review and submit step](https://mintcdn.com/neverminedag/dGqQPOVpr92RjAlB/images/faq/stripe-connect-review-submit.png?fit=max\&auto=format\&n=dGqQPOVpr92RjAlB\&q=85\&s=637551e00bd5980e0971e6806668e02d) > [accordion] Do I need a Stripe account before connecting? > > No. If you don't have one, Stripe's onboarding flow will create a new account for you. > [accordion] Is Stripe Connect required for all payment plans? > > No. Only if you want to accept fiat (credit card) payments. Plans that only accept stablecoin or crypto don't need a Stripe account. > [accordion] How do payouts work? > > When a user pays with a credit card, Nevermined routes the payment to your connected Stripe account. Fees (Nevermined's 2% + Stripe's processing fees) are deducted automatically. Stripe handles the payout schedule to your bank. > [accordion] Can I test in sandbox? > > Yes. Sandbox transactions use [Stripe test cards](https://stripe.com/docs/testing#international-cards), so no real money is charged. See the [full list of Stripe test values](https://docs.stripe.com/connect/testing?accounts-namespace=v2). > [accordion] Can I disconnect or change my Stripe account? > > Yes. Go to **Settings > Stripe Connect** in the Nevermined App. Any pending payouts will still be routed to the previously connected account. ## General > [accordion] What is Nevermined? > > Nevermined adds a payment and entitlement layer to any agent API or MCP tool. Each inbound request is validated, metered, and settled in real time. You handle the AI, we handle payments. > [accordion] What is x402? > > x402 is an open HTTP standard for agent payments. When an agent hits a paywall, the server responds with `402 Payment Required`. The agent attaches a payment credential in the next request header and the purchase completes in milliseconds. No checkout, no redirect. > [accordion] What is agentic commerce? > > Agents autonomously buy, sell, or rent services from each other. Nevermined's identity, metering, and payment infrastructure makes those machine-to-machine transactions possible. > [accordion] Why do AI payments need new infrastructure? > > AI agents fire thousands of micro-tasks and are OpEx heavy. You need per-request metering and real-time settlement. Seat-based pricing and traditional checkout flows can't keep up. > [accordion] Can't I just use Stripe? > > Stripe handles checkout but doesn't track sub-cent API calls. Nevermined adds per-request metering and settlement on top, while still letting you settle via Stripe or USDC. Stripe was built for monthly subscriptions and shopping carts. We're built for millions of micro-transactions between autonomous agents. > [accordion] Which agent frameworks are supported? > > Any framework that can make an HTTP request: OpenAI, Anthropic, LangChain, CrewAI, Strands, MCP tool servers, and custom agents. We provide TypeScript and Python SDKs, a CLI, and an MCP server. > [accordion] Usage-based vs. outcome-based pricing — what's the difference? > > Usage-based bills per API call or compute cycle. Outcome-based charges only when your agent delivers a result (lead booked, bug fixed, etc.). Nevermined supports either model, or a hybrid, out of the box. > [accordion] Do I need to register an agent if I only want to use or buy one? > > No. Registering an agent is a **seller** task — it's how you publish a service for others to pay for, which is why that flow asks for protected endpoints and a plan. As a **buyer** you don't register anything, expose endpoints, or create a plan. You need three things: a [Nevermined API key](/docs/agents-guide/get-api-key) (created once via a one-time sign-in, then stored and reused — an agent can [capture it automatically](/docs/agents-guide/get-api-key)), a payment method with a spending delegation (a funded stablecoin wallet or an enrolled card, plus a capped budget the agent can charge — minting a token requires it), and the plan ID you want to buy. Then mint a token with `getX402AccessToken` and call the agent. See [Buy & Call a Paid Agent](/docs/getting-started/ai-agent-purchase). # Delegation Selection Source: https://nevermined.ai/docs/products/payments/mandate-selection How Nevermined automatically resolves which delegation to charge when an agent makes a payment request. Three-tier priority with explicit, key-linked, and fallback modes. ## The Problem When a subscriber has multiple active delegations across their enrolled cards, the agent needs to know which one to use. Should it charge the $5 Visa delegation on Card A or the $10 Stripe delegation on Card B? Nevermined solves this with a **three-tier selection algorithm** that automatically resolves the right delegation based on priority rules. The algorithm is the same for Visa, Stripe, and Braintree — `apiKeyId` and explicit `delegationId` work identically across all three networks. > [!NOTE] > > The recommended approach is **create-first**: create the delegation with `createDelegation`, then pass its `delegationId` explicitly (Mode 1). This removes all ambiguity and is the only supported path for Visa. Auto-resolution (Modes 2–3) selects among the delegations you've already created; it does **not** create one. Inline create-on-the-fly (passing `spendingLimitCents` instead of a `delegationId`) is deprecated. ## Three-Tier Resolution When the SDK or CLI requests an x402 access token, Nevermined resolves the delegation in this order: **1. Mode 1: Explicit Delegation ID** If the caller passes a `delegationId` in `delegationConfig`, Nevermined uses that delegation directly. No ambiguity, the caller knows exactly which authorization it wants. > [tab] TypeScript > > ```typescript theme={null} > const token = await payments.x402.getX402AccessToken( > 'plan_abc123', > undefined, // agentId — pass when the plan has multiple agents > { > delegationConfig: { > delegationId: 'deleg-8f14e45f-ce34-4797-b88e-968374b0d4b6', > }, > }, > ) > ``` > [tab] Python > > ```python theme={null} > from payments_py.x402 import DelegationConfig, X402TokenOptions > > token = payments.x402.get_x402_access_token( > plan_id="plan_abc123", > token_options=X402TokenOptions( > delegation_config=DelegationConfig( > delegation_id="deleg-8f14e45f-ce34-4797-b88e-968374b0d4b6", > ), > ), > ) > ``` Nevermined validates: * The delegation exists and is `Active` (not expired, exhausted, or revoked) * The delegation has remaining budget and remaining transactions * If the delegation is linked to an API key, it must match the calling key * The associated card is active and belongs to the authenticated user > [!NOTE] > > This is the **only** supported mode for Visa delegations. Auto-creation from the SDK requires `consumerPrompt` + `assuranceData`, which the SDK cannot produce — see the [Visa enrollment notes](/docs/products/payments/card-enrollment). **2. Mode 2: Key-Linked Delegation** If no `delegationId` is passed, Nevermined checks if any delegation is **linked to the calling API key**. If exactly one key-linked delegation matches, it's selected automatically. This is the recommended approach for production setups with multiple delegations. Link each API key to a specific delegation and the routing is deterministic. Nevermined collects all delegations where `delegation.apiKeyId === calling_key.skId`, then filters for `Active`, with remaining budget, remaining transactions, and a non-expired duration. Key-linked delegations **always take priority** over unlinked ones. **3. Mode 3: Unlinked Fallback** If no key-linked delegations exist, Nevermined falls back to **unlinked delegations** (delegations with no `apiKeyId` set). If exactly one unlinked delegation matches, it's selected. This mode is convenient when you only have one delegation. You don't need to link anything. ## Decision Flowchart ``` SDK / CLI requests an x402 access token | |- delegationId in delegationConfig? | |- YES -> Use that delegation (validate ownership, status, budget, usage, expiry) | |- NO -> Continue to auto-resolution (Stripe / Braintree only) | |- Collect all user's delegations across all cards | |- Key-linked: delegation.apiKeyId === current key's skId | |- Unlinked: delegation.apiKeyId is null | |- Filter each group: Active, not expired, remaining budget > 0, remaining transactions > 0 | |- Key-linked delegations found? | |- Exactly 1 -> Use it | |- Multiple -> Error: "Multiple active delegations found" | |- None -> Fall through to unlinked | |- Unlinked delegations found? |- Exactly 1 -> Use it |- Multiple -> Error: "Multiple active delegations found" |- None -> Error: "No active delegation found" ``` ## When to Use Each Mode > [card] Explicit ID > > Multiple delegations, full control. Required for Visa. > [card] Key-Linked > > One delegation per API key. Set it once, forget it. > [card] Unlinked > > Single delegation, zero config. Just create and go. ## Linking an API Key API key linking works the same way for Visa, Stripe, and Braintree delegations through the shared `apiKeyId` field on `POST /api/v1/delegation/create`. ### When Creating In the [Nevermined App](https://nevermined.app), open the Create Delegation dialog and select an API key from the dropdown. Only active, non-browser API keys that aren't already linked to another delegation are shown. ### When Updating Delegations cannot be updated in place. To change the linked API key, revoke the existing delegation and create a new one with the desired `apiKeyId`. For Visa, this requires a fresh device-binding ceremony. > [!NOTE] > > Linking an API key is optional but recommended when you have two or more active delegations. Without it, Nevermined can't automatically determine which one to use and will return an error. ## Error Handling ### Multiple Delegations Found ``` "Multiple active delegations found. Pass a delegationId in delegationConfig, or link a delegation to your API key." ``` **Fix:** Either pass `delegationId` explicitly in `delegationConfig`, or link one of the delegations to your API key in the dashboard. ### No Active Delegation Found ``` "No active delegation found (check remaining budget, expiry, status, and key restrictions)" ``` **Possible causes:** * All delegations are exhausted (`amountSpentCents >= spendingLimitCents` or `transactionCount >= maxTransactions`) * All delegations have expired (`createdAt + durationSecs` in the past) * Delegations are linked to a different API key ### Delegation Linked to Different Key ``` "This delegation is linked to a different API key" ``` **HTTP 403.** The explicit `delegationId` you passed is linked to a different API key than the one you're authenticating with. Use the correct API key, or revoke the delegation and recreate it with the API key you want. ## API Reference ### Generate Access Token ```bash theme={null} POST /api/v1/x402/permissions Authorization: Bearer Content-Type: application/json ``` **Request:** ```json theme={null} { "planId": "plan_abc123", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015", "delegationConfig": { "delegationId": "deleg-8f14e45f-ce34-4797-b88e-968374b0d4b6" } } ``` | Field | Required | Description | | - | - | - | | `planId` | Yes | The plan you're paying for | | `agentId` | No | Agent identifier (for plans with multiple agents) | | `delegationConfig.delegationId` | Recommended | Explicit delegation ID (Mode 1) — the supported path. Omit to use auto-resolution among your existing delegations. **Required for Visa.** | | `delegationConfig.spendingLimitCents` + `durationSecs` | No | **Deprecated** — auto-create a delegation on the fly (Stripe / Braintree only). Create the delegation first with `createDelegation`, then pass `{ delegationId }` instead; the inline form emits a runtime deprecation warning. | **Response (success):** ```json theme={null} { "accessToken": "eyJ4NDAyVmVyc2lvbiI6Mi...", "permissionHash": "0x1a2b3c..." } ``` The `accessToken` value (a base64-encoded x402 PaymentPayload) goes in the `payment-signature` HTTP header when calling a protected resource. **Error responses:** | Status | Reason | | - | - | | 400 | Multiple delegations, delegation exhausted, missing required fields for Visa | | 403 | Delegation linked to a different API key, delegation doesn't belong to user | | 404 | No active delegation found, delegation ID not found | ## Best Practices 1. **Start simple.** If you have one delegation, you don't need to link API keys or pass explicit IDs. Just create the delegation and call the API. 2. **Link keys for production.** When you add a second delegation, link each API key to a specific delegation. This gives you deterministic routing without code changes. 3. **Use explicit IDs for Visa or for complex setups.** Visa delegations require `delegationId` in `delegationConfig`. The same pattern is useful when an agent works with multiple delegations dynamically (e.g., different delegations for different pricing tiers). 4. **Monitor usage.** Check `amountSpentCents` vs `spendingLimitCents` and `transactionCount` vs `maxTransactions` to know when delegations are close to exhaustion. Create new ones before the old ones run out. 5. **Set reasonable expiration times.** Don't create delegations that last indefinitely. Set `durationSecs` aligned with your billing cycles. For Visa, the `assuranceData` ceremony scales with the duration shown in the approval prompt — keep it short for higher-trust use cases. # Delegations Source: https://nevermined.ai/docs/products/payments/mandates Create scoped spending authorizations that control how much agents can charge, how many transactions they can make, and when the authorization expires. ## What Are Delegations? A delegation is a **scoped spending authorization** tied to an enrolled payment card. It defines the boundaries of what an agent can charge: the maximum amount over the delegation's lifetime, how many transactions are allowed, and when the authorization expires. Think of it as a controlled allowance: you're giving an agent permission to spend within strict limits, rather than handing over your card. > [!NOTE] > > The Visa Agentic Tokens rollout retired the previous separate "Visa mandate" object. Visa is now one of three networks (`stripe`, `braintree`, `visa`) on the unified `nvm:card-delegation` scheme, with a single create endpoint and a single record shape. Visa delegations differ only in that they require a per-delegation device-binding ceremony at create time. ## Delegation Properties All three networks share the same core fields: | Field | Description | | - | - | | `provider` | `stripe`, `braintree`, `visa`, or `erc4337` | | `providerPaymentMethodId` | PSP-side token: Stripe `pm_…`, Braintree `paymentMethodToken`, or Visa Agentic Token `vat_…` | | `spendingLimitCents` | Maximum total amount the delegation can charge over its lifetime, in cents | | `durationSecs` | How long the delegation is valid for, in seconds from creation | | `maxTransactions` | Optional cap on the number of charges. Omit the field to allow unlimited transactions. | | `currency` | ISO 4217 lowercase (`usd`, `eur`, …) | | `planId` | Optional plan binding. Required for Visa (Trusted Agent Protocol). | | `apiKeyId` | Optional NVM API key link for [automatic selection](/docs/products/payments/mandate-selection) | | `consumerPrompt` | **Visa-only**: human-readable approval text shown during device binding | | `assuranceData` | **Visa-only**: opaque blob produced by the WebAuthn ceremony | ## Creating a Delegation ### Via the Nevermined App After enrolling a card, create a delegation from the [Nevermined App](https://nevermined.app): > [tab] Stripe / Braintree > > 1. Navigate to your enrolled card > 2. Click **Create Delegation** > 3. Set the spending limit (in dollars / euros) > 4. Set the duration (e.g. 7 days) > 5. Optionally set a max-transactions cap > 6. Optionally link an NVM API key > 7. Confirm to create > [tab] Visa > > 1. Navigate to your enrolled Visa Agentic Token > > 2. Click **Create Delegation** > > 3. Set the spending limit, duration, and (optionally) max transactions > > 4. Select the plan this delegation binds to (Visa requires a `planId`) > > 5. Optionally link an NVM API key > > 6. Click **Continue to approval** — the embedded Visa VTS iframe starts the WebAuthn ceremony > > 7. Complete the passkey approval (or fall back to the email OTP that VTS sends) > > 8. The webapp captures the resulting `assuranceData` and submits the delegation > > > [!WARNING] > > > > Visa device binding is single-use and tied to the spending limit + duration + merchant context shown in the approval prompt. Changing any of those values invalidates the captured `assuranceData` — restart the approval step. > > > [!NOTE] > > > > Visa delegation creation is webapp-only. The backend rejects `POST /api/v1/delegation/create` with `provider: 'visa'` (`BCK.VISA.0014`) unless both `consumerPrompt` and `assuranceData` are present, and both can only be produced by the VTS-embedded ceremony running in a real browser. ### Via the API All providers use the same endpoint and DTO. The Visa branch adds two required fields (`consumerPrompt`, `assuranceData`) and requires a `planId`. > [tab] Stripe Delegation > > ```bash theme={null} > POST /api/v1/delegation/create > Authorization: Bearer > Content-Type: application/json > ``` > > ```json theme={null} > { > "provider": "stripe", > "providerPaymentMethodId": "pm_1Abc2Def3Ghi4Jkl", > "spendingLimitCents": 10000, > "durationSecs": 604800, > "maxTransactions": 100, > "currency": "usd", > "apiKeyId": "sk-abc123" > } > ``` > > Response includes a `delegationId` and `delegationToken` (the signed JWT) for the new authorization. > [tab] Braintree Delegation > > ```bash theme={null} > POST /api/v1/delegation/create > Authorization: Bearer > Content-Type: application/json > ``` > > ```json theme={null} > { > "provider": "braintree", > "providerPaymentMethodId": "abc123token", > "spendingLimitCents": 10000, > "durationSecs": 604800, > "maxTransactions": 100, > "currency": "usd", > "apiKeyId": "sk-abc123" > } > ``` > [tab] Visa Delegation > > ```bash theme={null} > POST /api/v1/delegation/create > Authorization: Bearer > Content-Type: application/json > ``` > > ```json theme={null} > { > "provider": "visa", > "providerPaymentMethodId": "vat_01HXYZABCDEF", > "spendingLimitCents": 5000, > "durationSecs": 86400, > "maxTransactions": 5, > "currency": "usd", > "planId": "80918427023170428029540261117198154464497879145267720259488529685089104529015", > "consumerPrompt": "Allow up to USD 50.00 over 5 transactions at example.com", > "assuranceData": [ > { > "methodResults": { "id": "…" }, > "verificationType": "DEVICE" > } > ] > } > ``` > > The `assuranceData` blob is the value returned by the VGS Agentic Auth browser SDK after the WebAuthn ceremony completes. It is opaque to Nevermined and forwarded verbatim to VGS `POST /intents`. > > > [!WARNING] > > > > Calling this endpoint with `provider: 'visa'` from a non-browser context will fail with `BCK.VISA.0014` because `assuranceData` can only be produced by the in-browser ceremony. Trying to forge or replay one yields `BCK.VISA.0003` from upstream. ## Spending Controls All delegations enforce multiple layers of spending control: ### Lifetime Spending Limit `spendingLimitCents` caps the **cumulative** amount charged over the delegation's lifetime, not per-transaction. Once `amountSpentCents >= spendingLimitCents`, the delegation transitions to `Exhausted`. ### Usage Limits `maxTransactions` caps the total number of charges. Once reached, the delegation is `Exhausted` regardless of remaining budget. ### Time-Based Expiration After `createdAt + durationSecs`, the delegation transitions to `Expired` regardless of remaining budget or usage. ## Updating a Delegation Delegations are not updated in place. To change the limit, duration, or any other parameter, revoke the existing one and create a new one. For Visa, this requires a fresh device-binding ceremony. ```bash theme={null} # 1. Revoke existing delegation DELETE /api/v1/delegation/{delegationId} # 2. Create new delegation with updated params POST /api/v1/delegation/create ``` > [!WARNING] > > Revoking and recreating a delegation means any unspent budget from the old delegation does not carry over. ## Cancelling a Delegation ```bash theme={null} DELETE /api/v1/delegation/{delegationId} Authorization: Bearer ``` No additional authentication is required beyond your API credentials. Revocation is immediate: in-flight verify/settle calls against the delegation fail with `DELEGATION_INACTIVE`. ## Status Lifecycle ``` Active -> Exhausted (spending limit or transaction count reached) | |-> Expired (past createdAt + durationSecs) | |-> Revoked (manually removed via DELETE) ``` Only `Active` delegations can be used for payments. Nevermined checks status, usage, and expiration on every verify and settle request. Each delegation tracks `amountSpentCents`, `remainingBudgetCents`, and `transactionCount`. ## API Key Linking You can optionally link a delegation to a specific NVM API key. This tells Nevermined "when this API key is used, charge this delegation." This is especially useful when you have multiple active delegations and want deterministic routing. Instead of the agent guessing which one to use, the API key determines it automatically. All three networks support API key linking through the same `apiKeyId` field. See [Delegation Selection](/docs/products/payments/mandate-selection) for the full resolution algorithm. ## Transaction History Every settled charge is recorded as a transaction: | Field | Description | | - | - | | `id` | The transaction's own identifier | | `delegationId` | The delegation this charge was made against | | `amountCents` | Amount in cents. On a Router row this is the **combined** cap deduction — the merchant leg plus the routing fee below, *unless* `feeReleased` is `true`, in which case it is already net of the fee (see below) | | `currency` | Currency code | | `status` | Usually `succeeded`, `failed` or `refunded` — the last written when an auto-refund follows a charge whose credit mint failed. Not an exhaustive list: the field is a free string, and card-rail rows can also carry the PSP's own status verbatim (e.g. Braintree's `SUBMITTED_FOR_SETTLEMENT`, or Stripe's `requires_action`) | | `providerTransactionId` | PSP charge identifier (Stripe `pi_…`, Braintree transaction id, Stripe Connect `pi_…` for Visa settlement). On a Router row it is the Router `paymentId`, which links to `GET /api/v1/router/payments` | | `failureReason` | Error details (if failed) | | `feeCents` | Nevermined's routing fee in cents, already included in `amountCents`. `"0"` on a card or crypto row, which pay no routing fee on top of their price — but `"0"` here does not by itself mean no fee applied; read `feeAtomic` | | `feeAtomic` | The same fee in the settlement asset's smallest unit. This is the field that answers "did a routing fee apply at all" | | `feeBps` | The rate applied, in basis points over a 10,000 denominator. Pinned per row | | `feeReleased` | The fee was not collected and has been credited back. `amountCents` is already net of it — do not subtract it again | | `createdAt` | When the transaction occurred | > [!NOTE] > > The routing fee applies only to payments routed through the [Nevermined Router](/docs/products/catalog/router/ledger#the-routing-fee-on-a-record). On a plan purchase over the card rails the three fee figures read zero and `feeReleased` reads `false` — note `feeCents` and `feeAtomic` are strings (`"0"`), while `feeBps` is a number and `feeReleased` a boolean. Nevermined's cut on such a purchase is carved *out* of the plan price rather than added on top, and is published separately as `nvmMargin` on `POST /api/v1/transactions/search` — one value per transaction, not per plan. ```bash theme={null} GET /api/v1/delegation/{delegationId}/transactions?offset=0 ``` ## Network Comparison | | Visa | Stripe | Braintree | | - | - | - | - | | **Create endpoint** | `POST /api/v1/delegation/create` (`provider: 'visa'`) | `POST /api/v1/delegation/create` (`provider: 'stripe'`) | `POST /api/v1/delegation/create` (`provider: 'braintree'`) | | **Per-delegation auth** | WebAuthn/passkey device binding (browser-only) | API credentials only | API credentials only | | **Required extras** | `consumerPrompt`, `assuranceData`, `planId` | — | — (the seller must have a Braintree child merchant account in `currency`; Nevermined resolves it) | | **Cancel** | `DELETE /api/v1/delegation/{id}` | `DELETE /api/v1/delegation/{id}` | `DELETE /api/v1/delegation/{id}` | | **Settlement** | Stripe Connect against seller's connected account | Stripe PaymentIntents | Braintree `transaction.sale` against vaulted token | ## What's Next? If you have multiple delegations, learn how Nevermined decides which one to use for a given payment request. > [card] [Delegation Selection](/docs/products/payments/mandate-selection) > > How Nevermined resolves which delegation to charge # Payments Source: https://nevermined.ai/docs/products/payments/overview The three Nevermined payment types (Catalog, Embedded Web Flow, Merchant Plans), and the card enrollment and delegation model that lets agents pay with Visa, Stripe, or Braintree. Nevermined has three payment types: three ways money reaches a merchant. Pick the type first, because it decides who the buyer is, what they pay with, and how much you integrate. The rest of this page covers the card mechanics that agent payments run on. ## Three payment types ![Three ways to get paid on Nevermined: the Catalog (agents pay per call in stablecoin), the Embedded Web Flow (people pay by card on your site), and Merchant Plans (agents buy credits/time/PAYG) — all settling to the merchant, minus a small Nevermined fee.](https://mintcdn.com/neverminedag/HTSlqJHCy4sED2NN/images/payments/three-ways-to-get-paid.png?fit=max\&auto=format\&n=HTSlqJHCy4sED2NN\&q=85\&s=744bade5a5b5ba97ac65533be8df4bd8) > [card] [Catalog](/docs/products/catalog/overview) > > AI agents discover your listed service and pay per call in stablecoin over x402 + mpp. You enroll nothing. > [card] [Embedded Web Flow](/docs/integrate/patterns/orders) > > A person pays any cart total by card through a checkout embedded on your site. No plan, no buyer account, no delegation. > [card] [Merchant Plans](/docs/solutions/agent-to-agent-monetization#merchant-plans) > > AI agents buy credits, time, or pay-as-you-go access to your service at a fixed price, paying by card or stablecoin. | | Catalog | Embedded Web Flow | Merchant Plans | | - | - | - | - | | **Who pays** | An AI agent or harness | A person, in a browser | An AI agent or harness | | **Pay with** | Stablecoin | Card (fiat) | Card or stablecoin | | **Pricing** | Dynamic — quoted per request | Dynamic — any cart total | Fixed — set per plan | | **Merchant enrolls?** | No — Nevermined discovers and lists your service | Yes — you control an Org | Yes — you integrate NVM | The full comparison (rails, plans, buyer accounts, who integrates what) is on [Monetize Your AI](/docs/solutions/agent-to-agent-monetization#three-ways-to-get-paid). ## Card payments for agents Everything below is the mechanism behind **card-paid agent payments**, which is how a Merchant Plan gets paid by card. Enroll a Visa, Stripe, or Braintree card. Create a delegation that caps how much can be spent. Your agents charge it directly via x402 — no checkout pages, no human in the loop. > [!NOTE] > > **Three payment types and three card networks are different things.** Catalog, Embedded Web Flow, and Merchant Plans are *what you sell and who buys*. Visa, Stripe, and Braintree are *card networks*: the providers an enrolled card and its delegation settle through. Delegations apply to Merchant Plans paid by card. The Embedded Web Flow settles through the same PSPs, but the buyer confirms each charge in the browser, so there is no enrollment and no delegation. Catalog payments are stablecoin and never touch a card. Manage everything at [nevermined.app](https://nevermined.app). > [card] [Card Enrollment](/docs/products/payments/card-enrollment) > > Enroll Visa, Stripe, or Braintree cards > [card] [Delegations](/docs/products/payments/mandates) > > Set spending limits and expiration > [card] [Delegation Selection](/docs/products/payments/mandate-selection) > > Auto-resolve which card to charge ## How It Works **1. Enroll a card** Add a card at [nevermined.app](https://nevermined.app). Card data is tokenized in the browser by a PCI-compliant capture (VGS Collect). Nevermined never stores raw card numbers. **2. Create a delegation** Set the spending limit, duration, and (optionally) max transactions. Visa delegations also require a per-delegation passkey approval that binds the limits to your device. Optionally link the delegation to a specific API key for automatic routing. **3. Agents charge it** Agents call the Nevermined API with their API key. Nevermined resolves the right delegation and generates an x402 token. The resource server verifies, executes, and settles. ## Payment Flow ``` Agent (no token) | |-> Resource Server returns 402 + payment-required header | |-> Agent calls Nevermined: POST /api/v1/x402/permissions | |-> Resolves delegation -> generates x402 token (scheme: nvm:card-delegation) | |-> Agent retries with payment-signature header | |-> Resource Server: |-> POST /verify -> validates token, delegation, usage |-> Executes workload |-> POST /settle -> charges card, returns payment-response ``` ## One delegation model, three card networks All three providers share the same `nvm:card-delegation` x402 scheme and the same `POST /api/v1/delegation/create` endpoint. The `network` field on the delegation (`stripe`, `braintree`, or `visa`) is set by the card you choose and routes settlement to the right PSP. > [card] Visa > > PAN tokenized by VGS Credential Management Platform (CMP) into a Visa Agentic Token. Each delegation requires a one-time WebAuthn/passkey device-binding ceremony enforced by Visa VTS. Settlement runs through Stripe Connect against the seller's connected account. > [card] Stripe > > Card captured via VGS Collect and given a network token. No passkey. Settlement runs through Stripe PaymentIntents directly. > [card] Braintree > > The same card enrollment as Stripe. Settlement is one sale, with the card's network token, against the seller's per-currency OAuth-connected Braintree merchant account. > [!NOTE] > > The Visa Agentic Tokens flow replaces the earlier VTS/VIC + mandate endpoints. There is no longer a separate "mandate" object — a Visa delegation is just a `nvm:card-delegation` record with `provider: 'visa'`. ## Key Concepts | Concept | Description | | - | - | | **Delegation** | A scoped spending authorization on an enrolled card. Defines the spending limit, max transactions, and expiration. Same concept across Visa, Stripe, and Braintree. | | **Visa Agentic Token** | The CMP-issued identifier (`vat_…`) that replaces the real PAN. Stored as the delegation's `providerPaymentMethodId` for Visa cards. | | **Device binding** | A per-delegation WebAuthn/passkey ceremony required by Visa VTS. Produces a single-use `assuranceData` blob bound to the spending limit, duration, and merchant context. Browser-only. | | **API Key Linking** | Link a delegation to a specific API key so agents automatically use the right one. | | **x402 Token** | Payment token used in the `payment-signature` HTTP header (`nvm:card-delegation` scheme). | ## SDK consumption The TypeScript and Python SDKs treat all three networks identically. Pass the `delegationId` to `DelegationConfig` and the SDK auto-resolves the scheme + network from the plan and the delegation record: > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY, > environment: 'sandbox', > }) > > // Works the same for Stripe, Braintree, and Visa delegations. > const token = await payments.x402.getX402AccessToken( > 'plan_abc123', > undefined, // agentId — pass when the plan has multiple agents > { > delegationConfig: { > delegationId: 'deleg-8f14e45f-ce34-4797-b88e-968374b0d4b6', > }, > }, > ) > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments > from payments_py.x402 import DelegationConfig, X402TokenOptions > > payments = Payments( > api_key=os.environ.get("NVM_API_KEY"), > environment="sandbox", > ) > > # Works the same for Stripe, Braintree, and Visa delegations. > token = payments.x402.get_x402_access_token( > plan_id="plan_abc123", > token_options=X402TokenOptions( > delegation_config=DelegationConfig( > delegation_id="deleg-8f14e45f-ce34-4797-b88e-968374b0d4b6", > ), > ), > ) > ``` > [!WARNING] > > For Visa, `delegationId` reuse is the **only** SDK path. `createDelegation` with `provider='visa'` cannot run from a non-browser context — the backend rejects it without `consumerPrompt` + `assuranceData`, both of which require the WebAuthn ceremony embedded by Visa VTS in the webapp. The SDK rejection surfaces as `PaymentsError.code = 'BCK.VISA.0014'`. ## Environments * **Sandbox** — Testing and development. Visa runs against VGS sandbox + VTS test PANs; Stripe in test mode; Braintree on sandbox merchants. * **Live** — Production. Real payments through Visa, Stripe, and Braintree. > [!NOTE] > > You need an [NVM API Key](/docs/agents-guide/get-api-key). Set it as `NVM_API_KEY`. ## What's Next? > [card] [Enroll a Card](/docs/products/payments/card-enrollment) > > Set up your first payment card > [card] [Create a Delegation](/docs/products/payments/mandates) > > Define spending limits, usage caps, and expiration > [card] [Compare the three payment types](/docs/solutions/agent-to-agent-monetization#three-ways-to-get-paid) > > Catalog, Embedded Web Flow, and Merchant Plans side by side > [card] [Orders: Goods & Services Checkout](/docs/integrate/patterns/orders) > > The Embedded Web Flow contract, and its current availability # Monetize Static Assets Source: https://nevermined.ai/docs/solutions/access-control-monetization-static-resources Gate and monetize datasets, models, or APIs using Nevermined’s transparent HTTP Proxy with flexible payment plans. Monetize static assets—like datasets, files, pre-trained models, or HTTP URLs without restructuring your infrastructure. Nevermined provides a transparent HTTP Proxy and access control, enabling you to define who can access which resources and under what conditions. ## How It Works * **Transparent Proxy**: Requests pass through Nevermined’s proxy, which validates access tokens and credit balances before forwarding to your asset. * **Payment Plans**: Offer subscriptions or credit-based plans priced in stablecoins or fiat. * **Fine-Grained Access**: Control access per resource, route, or method; enforce rate limits and usage caps. ## Benefits * **Minimal changes**: Keep your existing storage/API; add a proxy in front. * **Secure access**: Bearer-token validation and metered usage. * **Flexible payments**: Stablecoin and fiat support with configurable pricing. * **Operational clarity**: Audit logs and usage metrics per resource. ## Implementation Steps 1. **Model your Resource as an Agent**: Register a resource-representing agent with endpoints/paths. 2. **Create a Payment Plan**: Choose subscription or credits and set pricing. 3. **Enable the HTTP Proxy**: Configure the proxy to protect your resource and validate incoming requests. 4. **Publish & Monitor**: Make the resource available; track usage and revenue in the App. ## Learn More * [Register Agents](/docs/products/nevermined-app/register-agents) in the Nevermined App * [5-Minute Setup](/docs/integrate/quickstart/5-minute-setup) to get started # Monetize Your AI Source: https://nevermined.ai/docs/solutions/agent-to-agent-monetization Three ways to get paid on Nevermined: the Catalog, the Embedded Web Flow, and Merchant Plans. Stablecoin and fiat settlement, no bespoke integrations required. Nevermined gives you three ways to get paid. Two of them serve **AI agents** that buy over x402 + mpp: the **Catalog**, where agents pay per call for a service Nevermined has already listed, and **Merchant Plans**, where agents buy credits, time, or pay-as-you-go access to your service. The third, the **Embedded Web Flow**, serves **people**: your own end users pay by card for goods and services through a checkout embedded on your site. ## Three ways to get paid ![Three ways to get paid on Nevermined: the Catalog (agents pay per call in stablecoin), the Embedded Web Flow (people pay by card on your site), and Merchant Plans (agents buy credits/time/PAYG) — all settling to the merchant, minus a small Nevermined fee.](https://mintcdn.com/neverminedag/HTSlqJHCy4sED2NN/images/payments/three-ways-to-get-paid.png?fit=max\&auto=format\&n=HTSlqJHCy4sED2NN\&q=85\&s=744bade5a5b5ba97ac65533be8df4bd8) | | Catalog | Embedded Web Flow | Merchant Plans | | - | - | - | - | | **Who pays** | An AI agent or harness (x402 + mpp) | A person, in a browser | An AI agent or harness (x402 + mpp) | | **Best for** | Listing an AI service and monetizing every call | Selling goods & services to your end users | Subscriptions / credits / metered access to your AI service | | **Rails / protocol** | x402 + mpp | Embedded PSP checkout — Stripe, Braintree, … | NVM plans over x402 + mpp (fiat or crypto) | | **Merchant enrolls?** | No — we discover & catalog your service | Yes — you control an Org | Yes — you integrate NVM | | **Payment plan?** | No | No — a one-off Order | Yes — credits / time / pay-as-you-go | | **Buyer needs an NVM account?** | Yes — pays from their NVM wallet | No — none required | Yes | | **Pay with** | Stablecoin | Card (fiat) | Card or stablecoin — most flexible | | **Pricing** | Dynamic — quoted per request | Dynamic — any cart total | Fixed — set per plan | | **Who has to integrate** | Neither the merchant · the buyer needs an account + funded wallet | Merchant embeds a checkout · the buyer does nothing | Both sides integrate NVM — most flexible, most setup | > [card] [Catalog](/docs/products/catalog/overview) > > Nevermined discovers and lists your AI service. Agents find it and pay per call in stablecoin. Nothing to enroll. > [card] [Embedded Web Flow](/docs/integrate/patterns/orders) > > Charge your own end users any cart total by card, through a checkout embedded on your site. No plan, no buyer account. > [card] [Merchant Plans](#merchant-plans) > > Sell credits, time, or pay-as-you-go access to your AI service. Agents buy the plan and call your endpoints with an access token. > [!NOTE] > > Not sure which one? If the buyer is an agent and you want zero setup, use the **Catalog**. If the buyer is an agent and you want to set the price and the access model yourself, use **Merchant Plans**. If the buyer is a person on your website, use the **Embedded Web Flow**. ## Catalog The Catalog is the zero-setup option. Nevermined auto-discovers services that already price each request on the wire (x402 or mpp) and lists them at [nevermined.app/catalog](https://nevermined.app/catalog/). Buyers are agents with a Nevermined account. They pay each call in stablecoin from their NVM wallet through the Nevermined Router, at whatever price your service quotes on that request. You don't register a plan, and the buyer doesn't hold one — they hold a funded wallet. Read the [Catalog overview](/docs/products/catalog/overview) for the buyer's view, or [add your AI service](/docs/products/catalog/ai-services#add-your-ai-service) so buyers can find it. ## Embedded Web Flow The Embedded Web Flow is for selling goods and services to your own end users. You control an [organization](/docs/solutions/organizations/overview), you set the price per checkout (any cart total, as a one-off **Order**), and your buyer pays by card through an embedded PSP checkout on your site. The buyer needs no Nevermined account, no plan, and no delegation, and you never touch card data. This is the newest of the three. The [Orders guide](/docs/integrate/patterns/orders) documents the contract and tracks its availability in `sandbox` and `live`. ## Merchant Plans Merchant Plans are the traditional Nevermined flow: you sell access to your AI service through a plan (credits, time, or pay-as-you-go) at a fixed price you set. Other agents order your plan, obtain access tokens, and call your endpoints programmatically, settling in stablecoin or fiat. Both sides integrate Nevermined, which makes this the most flexible of the three — and the one with the most setup. ### How It Works * **Register your Agent & Plan**: Create a payment plan in the [Nevermined App](https://nevermined.app) and link it to your AI agent (endpoints, metadata, pricing). * **Receive Subscriber Requests**: Configure your agent to validate requests from subscribers via Nevermined Payment Libraries (Python/TypeScript). No additional servers or custom gateways needed. * **Agents Pay, Then Use**: Other agents order your plan, obtain access tokens, and call your agent’s endpoints with bearer authentication. * **Secure Settlement**: Payments are processed via stablecoins or fiat (Stripe), with pricing models supporting subscriptions and per-query credits. ### Payment Methods Merchant Plans support two payment methods: > [card] [Fiat Payments](/docs/integrate/patterns/fiat-payments) > > Accept credit cards via Stripe. Users can purchase plans directly, or delegate their card for autonomous agent-to-agent payments. > [card] [Stablecoin Payments](/docs/integrate/patterns/stablecoin-payments) > > Accept USDC or other ERC-20 tokens on-chain. The native method for agent-to-agent commerce with the lowest fees (1%). ### Benefits * **Simple setup**: Create a plan, link your agent—done. * **Programmable access**: Agents can buy and use services autonomously. * **Flexible pricing**: Subscriptions, credits, and metered usage. * **Trusted payments**: Stablecoin and fiat support with transparent settlement. ### Implementation Steps 1. **Create a Payment Plan** in the Nevermined App (price, duration, credits). 2. **Register your Agent**: Provide endpoint URLs and capabilities. 3. **Link Plan → Agent**: Ensure the plan grants access to your agent. 4. **Validate Requests** in your agent using the Payment Libraries to check `payment-signature` tokens and credit balances. 5. **Publish** your agent so other agents can discover and subscribe. ## Learn More * [Register Agents](/docs/products/nevermined-app/register-agents) in the Nevermined App * [Manage Plans](/docs/products/nevermined-app/manage-plans) for pricing and access * [5-Minute Setup](/docs/integrate/quickstart/5-minute-setup) to get your first paid request working * [Catalog Overview](/docs/products/catalog/overview) for how agents discover and pay listed services * [Orders: Goods & Services Checkout](/docs/integrate/patterns/orders) for the Embedded Web Flow contract * [Payments](/docs/products/payments/overview) for card enrollment and delegations behind card-paid flows * Blog: [Making x402 Programmable](https://nevermined.ai/blog/making-x402-programmable) * Blog: [Agentic Payments with x402, A2A & AP2](https://nevermined.ai/blog/building-agentic-payments-with-nevermined-x402-a2a-and-ap2) # Cost Observability Source: https://nevermined.ai/docs/solutions/ai-agents-observability Track incoming requests, usage, and revenue for your AI agents using Nevermined’s observability tools. Nevermined provides end-to-end observability for your AI agents. Track incoming requests, measure credit redemption, and monitor revenue to understand how your services are used and optimize performance. ## How It Works * **Request Tracking**: Each call is validated and logged (success/failure, credits used, caller identity). * **Usage Metrics**: Monitor per-agent and per-plan usage, remaining balances, and redemption history. * **Revenue Analytics**: See plan purchases, settlements, and trends. ## Benefits * **Operational visibility**: Clear overview of traffic and usage. * **Optimization**: Identify hot endpoints and improve performance. * **Compliance & auditing**: Traceable records for paid access. ## Implementation Steps 1. **Enable Observability** via Payment Libraries configuration in your agent. 2. **Create Plans & Link Agents** to ensure paid calls are tracked. 3. **Monitor in the App**: Use dashboards to review usage and revenue. 4. **Export Data**: Pull metrics via API for custom dashboards. ## Learn More * Development Guide: [Observability Development Guide](/docs/development-guide/observability) # API Providers Source: https://nevermined.ai/docs/solutions/api-providers Let AI agents buy and top up your API autonomously. One server-side endpoint, settled on a delegated card via x402, no human in the loop. Agents are a new buyer of your API, and they don't onboard the way humans do. They don't sit at a browser, fill out a Stripe Checkout, or remember to top up a credit balance. Today they either stall at your paywall or hardcode a human's API key. Nevermined turns that failure mode into revenue with a small server-side integration. Agents holding a delegated card mint an [x402](/docs/development-guide/nevermined-x402) access token, send it to your endpoint, and you provision or top up access in response. You verify and settle through Nevermined's [Payments Facilitator](/docs/products/payments-facilitator/overview); the buyer's card is charged through Stripe, Braintree, or the Visa Trusted Agent Protocol depending on how it was enrolled. All three settle x402 charges through the same `nvm:card-delegation` scheme — your endpoint code doesn't change. ## Featured providers [**Exa**](https://exa.ai) is the live reference. Agents pay Exa \$7 via a Nevermined-delegated card and receive an Exa API key with \$7 of credits. When the key runs out, the agent tops up through the same endpoint. Same key, more credits, no human touched it. * Exa integration guide: [/integrations/exa](/docs/integrations/exa) [**You.com**](https://you.com) runs the same flow at \$5 a purchase, provisioning or topping up a You.com API key that works across every You.com API — Web Search, Contents, Answer, Research and Finance Research. It also publishes the agent-facing `.md` mirror described below, listed in its own `llms.txt`. * You.com integration guide: [/integrations/youdotcom](/docs/integrations/youdotcom) [**Baselayer**](https://baselayer.com) shows the metered variant. Its plan is a `credits` plan rather than pay-as-you-go: a \$10 purchase mints 100 credits, and every request an agent makes — the key purchase included — burns 10 of them, so the card is charged once per ten requests instead of once per key. The agent presents the same x402 token on every call, and Baselayer verifies and settles each one — the first call provisions the API key, the next nine are KYB business searches. It also publishes the agent-facing `.md` mirror described below, listed in its own `llms.txt`. * Baselayer integration guide: [/integrations/baselayer](/docs/integrations/baselayer) ## What you build, in five steps **1. Create a pay-as-you-go plan** On the [Nevermined App](https://nevermined.app/), choose **pay-as-you-go** pricing (one charge per purchase) and set your price (e.g. \$7). That's it: the App doesn't ask about credits on PAYG, and one call to your purchase endpoint = one card charge of your plan price. See [Manage Plans](/docs/products/nevermined-app/manage-plans). **2. Expose one endpoint** Accept a `payment-signature` header on a new route or an existing one. Existing customers keep their flow unchanged. **3. Verify with the facilitator** Call `payments.facilitator.verifyPermissions(...)`. Missing or invalid token returns `402 Payment Required` with the payment requirements body. **4. Run your business logic** Provision an API key, top up credits, unlock a resource, whatever your product is. **5. Settle** Call `payments.facilitator.settlePermissions(...)`. The card is charged and you get paid. (On credits-bundle plans, settle also burns credits from the buyer's balance; on PAYG, there's no credit movement.) ## Server-side handler Your handler does three things: read the `payment-signature` header, verify the token with the Nevermined facilitator, and settle after running your business logic. Examples below for TypeScript, Python, and raw HTTP. > [tab] TypeScript > > ```typescript theme={null} > import { Payments, buildPaymentRequired } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'live', > }) > > const paymentRequired = buildPaymentRequired(process.env.NVM_PLAN_ID!, { > endpoint: '/purchase-key', > httpVerb: 'POST', > scheme: 'nvm:card-delegation', > }) > > // Pre-encode for the `payment-required` response header (per x402 spec §4.3). > const paymentRequiredHeader = Buffer.from( > JSON.stringify(paymentRequired), > ).toString('base64') > > const send402 = (res) => > res > .status(402) > .setHeader('payment-required', paymentRequiredHeader) > .json(paymentRequired) > > app.post('/purchase-key', async (req, res) => { > const token = req.header('payment-signature') > if (!token) return send402(res) > > const verification = await payments.facilitator.verifyPermissions({ > paymentRequired, > x402AccessToken: token, > }) > if (!verification.isValid) return send402(res) > > const apiKey = await provisionOrTopUp(req) > > const settlement = await payments.facilitator.settlePermissions({ > paymentRequired, > x402AccessToken: token, > }) > > // Settlement receipt in the `payment-response` header (per x402 spec §4.3). > res > .setHeader( > 'payment-response', > Buffer.from(JSON.stringify(settlement)).toString('base64'), > ) > .json({ apiKey }) > }) > ``` > [tab] Python > > ```python theme={null} > import base64 > import os > from fastapi import FastAPI, Request > from fastapi.responses import JSONResponse > from payments_py import Payments, PaymentOptions > from payments_py.x402.helpers import build_payment_required > > app = FastAPI() > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='live') > ) > > payment_required = build_payment_required( > plan_id=os.environ['NVM_PLAN_ID'], > endpoint='/purchase-key', > http_verb='POST', > scheme='nvm:card-delegation', > ) > > # Pre-encode for the `payment-required` response header (per x402 spec §4.3). > payment_required_header = base64.b64encode( > payment_required.model_dump_json(by_alias=True).encode() > ).decode() > > def send_402() -> JSONResponse: > return JSONResponse( > status_code=402, > content=payment_required.model_dump(by_alias=True), > headers={'payment-required': payment_required_header}, > ) > > @app.post('/purchase-key') > async def purchase_key(request: Request): > token = request.headers.get('payment-signature') > if not token: > return send_402() > > verification = payments.facilitator.verify_permissions( > payment_required=payment_required, > x402_access_token=token, > ) > if not verification.is_valid: > return send_402() > > api_key = await provision_or_top_up(request) > > settlement = payments.facilitator.settle_permissions( > payment_required=payment_required, > x402_access_token=token, > ) > > # Settlement receipt in the `payment-response` header (per x402 spec §4.3). > settlement_header = base64.b64encode( > settlement.model_dump_json(by_alias=True).encode() > ).decode() > return JSONResponse( > content={'apiKey': api_key}, > headers={'payment-response': settlement_header}, > ) > ``` > [tab] HTTP (any language) > > The facilitator API is plain HTTP, no SDK required. Pseudo-code below > shows the verify/settle calls your handler needs to make. > > **Endpoints** (no `Authorization` header, auth is in the x402 access token): > > ``` > POST https://api.live.nevermined.app/api/v1/x402/verify > POST https://api.live.nevermined.app/api/v1/x402/settle > ``` > > Use `https://api.sandbox.nevermined.app/api/v1/...` for sandbox. > > **Verify request body:** > > ```json theme={null} > { > "paymentRequired": { > "x402Version": 2, > "resource": { "url": "/purchase-key", "mimeType": "application/json" }, > "accepts": [{ > "scheme": "nvm:card-delegation", > "network": "stripe", > "planId": "", > "extra": { "version": "1", "httpVerb": "POST" } > }], > "extensions": {} > }, > "x402AccessToken": "" > } > ``` > > Response: `{ "isValid": true, ... }` or `{ "isValid": false, "invalidReason": "..." }`. > > **Settle** uses the same body shape posted to `/x402/settle`. Response > contains `billingModel`, `creditsRedeemed`, `remainingBalance`, > `transaction`, and `orderTx`. Read `billingModel` before the credit > fields: on a `pay-as-you-go` plan both read `"0"` even on a charge that > succeeded, and the charge is referenced by `orderTx` (fiat) or > `transaction` (crypto). On a `credits` plan `orderTx` is present only when > auto top-up fired. > > **Your response headers** (per x402 spec §4.3): > > * On 402: set `payment-required: ` so buyer-side > clients can discover requirements > * On 200: set `payment-response: ` so buyers > have a structured settlement receipt > > **Pseudo-handler** (curl-style): > > ```bash theme={null} > # 0. Pre-build the PaymentRequired JSON for your endpoint (see body shape above) > PAYMENT_REQUIRED='{"x402Version":2,"resource":{"url":"/purchase-key","mimeType":"application/json"},"accepts":[{"scheme":"nvm:card-delegation","network":"stripe","planId":"","extra":{"version":"1","httpVerb":"POST"}}],"extensions":{}}' > > # 1. On request: read the payment-signature header > TOKEN="$(http_header payment-signature)" > > # 2. Verify > curl -s -X POST https://api.live.nevermined.app/api/v1/x402/verify \ > -H 'Content-Type: application/json' \ > -d "$(jq -n --arg pr "$PAYMENT_REQUIRED" --arg t "$TOKEN" '{ > paymentRequired: ($pr | fromjson), > x402AccessToken: $t > }')" > # → on isValid=false, return 402 with payment-required header set > > # 3. Run business logic (provision/top-up the API key) > > # 4. Settle > curl -s -X POST https://api.live.nevermined.app/api/v1/x402/settle \ > -H 'Content-Type: application/json' \ > -d "$(jq -n --arg pr "$PAYMENT_REQUIRED" --arg t "$TOKEN" '{ > paymentRequired: ($pr | fromjson), > x402AccessToken: $t > }')" > > # 5. Return 200 with the credential > ``` > > See the [Verify](/docs/api-reference/x402/verify-permission) and > [Settle](/docs/api-reference/x402/settle-permission) API references for > full request/response schemas, and the > [card-delegation spec](/docs/specs/x402-card-delegation) §3.2 for the > PaymentRequired JSON shape. > [!NOTE] > > The handlers above set the `payment-required` (on 402) and `payment-response` > (on 200) response headers per the > [card-delegation spec](/docs/specs/x402-card-delegation) §4.3. The optional > middleware below handles this for you automatically. ### Optional: middleware (recommended) If you're on Express or FastAPI, the SDK ships a payment middleware that handles the verify/settle dance and the spec-correct response headers for you. One config line gates your endpoint, your handler stays focused on business logic. > [!TIP] > > The route config also accepts an optional `credits` field (default `1`). > It's inert on PAYG plans and is the per-request burn amount on credits-bundle > plans. Omitted in the snippets below for the PAYG happy path. > [tab] TypeScript (Express) > > ```typescript theme={null} > import express from 'express' > import { Payments } from '@nevermined-io/payments' > import { paymentMiddleware } from '@nevermined-io/payments/express' > > const app = express() > app.use(express.json()) > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'live', > }) > > app.use( > paymentMiddleware(payments, { > 'POST /purchase-key': { > planId: process.env.NVM_PLAN_ID!, > scheme: 'nvm:card-delegation', > }, > }), > ) > > app.post('/purchase-key', async (req, res) => { > const apiKey = await provisionOrTopUp(req) > res.json({ apiKey }) > }) > ``` > [tab] Python (FastAPI) > > ```python theme={null} > import os > from fastapi import FastAPI, Request > from payments_py import Payments, PaymentOptions > from payments_py.x402.fastapi import PaymentMiddleware > > app = FastAPI() > > payments = Payments.get_instance( > PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='live') > ) > > app.add_middleware( > PaymentMiddleware, > payments=payments, > routes={ > 'POST /purchase-key': { > 'plan_id': os.environ['NVM_PLAN_ID'], > 'scheme': 'nvm:card-delegation', > }, > }, > ) > > @app.post('/purchase-key') > async def purchase_key(request: Request): > api_key = await provision_or_top_up(request) > return {'apiKey': api_key} > ``` The middleware reads the `payment-signature` header, calls `verifyPermissions`, runs your handler, then calls `settlePermissions` and attaches the `payment-response` header before sending the response. See the [Express](/docs/integrate/add-to-your-agent/express) and [FastAPI](/docs/integrate/add-to-your-agent/fastapi) integration pages for middleware options (dynamic credits, hooks, custom error handlers). ### Two things to remember > [!WARNING] > > **Idempotency.** Agents retry. Cache `token → result` so a replayed token > returns the same response without re-running your business logic or > re-charging the card. > [!NOTE] > > **402 on your regular endpoints.** When the agent's credits run dry, return > `402` with a top-up hint on the resource endpoints (not just the purchase > endpoint). The agent loops back, mints a fresh token, and pays again on the > same purchase route. ## Vend-the-key vs full metering Two patterns are supported. Pick whichever matches how you already meter usage. > [card] Vend-the-key > > A Nevermined purchase returns a credential (e.g. an API key with \$X of > credits). You meter ongoing usage internally with your existing > infrastructure. Exa works this way. Best when you already have per-key > billing. > [card] Full metering > > Nevermined settles each underlying API call. Best when you don't have > internal billing infra or prefer per-request settlement. Use the > [validate-requests](/docs/integrate/patterns/validate-requests) and > [charge-credits](/docs/integrate/patterns/charge-credits) patterns directly > on your resource endpoints. ## Make it agent-discoverable Agents don't read your HTML. They read your `llms.txt` and the `.md` mirrors next to your docs pages. Whichever path you took above, you still need these published on your own domain so crawlers find them under your brand. > [tab] Organization path > > A Premium org auto-generates both files for you, served live from the Nevermined facilitator: > > ``` > GET https://api.live.nevermined.app/api/v1/organizations/{orgId}/llms.txt > GET https://api.live.nevermined.app/api/v1/organizations/{orgId}/agentic-instructions.md > ``` > > Swap `api.live` for `api.sandbox` for the sandbox environment. Copy the rendered output to your own domain at whatever path your `llms.txt` references — `your-api.com/integrations/nevermined.md` is the common convention (Exa uses `/docs/integrations/nevermined.md` under their docs subpath). The org endpoint gives you the canonical content; you pick the publication URL and the filename agents discover, as long as the `llms.txt` entry on your side matches. Updates are picked up on next render (5-minute cache). > [tab] DIY path > > Publish two files on your own domain: > > 1. **A line in your `llms.txt`** (under an `## Integrations` heading or similar): > > ``` > - [Nevermined](/integrations/nevermined.md): Accept autonomous agent payments via x402 card delegation. Plan ID, endpoint, and SDK usage in the link. > ``` > > 2. **A `.md` mirror** describing your plan ID, endpoint, and response shape. Common locations: `your-domain.com/integrations/nevermined.md` or `your-domain.com/docs/integrations/nevermined.md` (Exa uses the latter). Match whatever the `llms.txt` entry above points to. > > > [card] [Copy the mirror template](https://nevermined.ai/integrations/api-provider-template.md) > > > > Plain-text markdown skeleton with placeholders. Drop it wherever your docs live and fill in your plan ID, endpoint, and response shape. > > Live example of the full flow: the [Exa integration guide](/docs/integrations/exa). Updating your human-facing HTML docs is optional and less agent-native. ## Agent-side call (for context) What the agent runs to mint a token and call your endpoint: > [tab] TypeScript > > ```typescript theme={null} > // Create a card delegation first (provider + currency required), then > // request the token by its delegationId. > const delegation = await payments.delegation.createDelegation({ > provider: 'stripe', > providerPaymentMethodId: 'pm_...', > spendingLimitCents: 700, > durationSecs: 3600, > currency: 'usd', > }) > const { accessToken } = await payments.x402.getX402AccessToken( > YOUR_PLAN_ID, > undefined, > { > scheme: 'nvm:card-delegation', > delegationConfig: { delegationId: delegation.delegationId }, > }, > ) > > const res = await fetch('https://your-api.com/purchase-key', { > method: 'POST', > headers: { 'payment-signature': accessToken }, > }) > ``` > [tab] Python > > ```python theme={null} > from payments_py.x402 import ( > CreateDelegationPayload, > DelegationConfig, > X402TokenOptions, > ) > > # Create a card delegation first (provider + currency required), then > # request the token by its delegation_id. > delegation = payments.delegation.create_delegation( > CreateDelegationPayload( > provider='stripe', > provider_payment_method_id='pm_...', > spending_limit_cents=700, > duration_secs=3600, > currency='usd', > ) > ) > token_res = payments.x402.get_x402_access_token( > YOUR_PLAN_ID, > None, > token_options=X402TokenOptions( > scheme='nvm:card-delegation', > delegation_config=DelegationConfig( > delegation_id=delegation.delegation_id > ), > ), > ) > access_token = token_res['accessToken'] > > res = requests.post( > 'https://your-api.com/purchase-key', > headers={'payment-signature': access_token}, > ) > ``` ## FAQ > [accordion] When do I get paid out? > > Settled funds are paid out via your connected payout provider on the > provider's standard schedule: Stripe Connect for Stripe and Visa Trusted > Agent Protocol delegations (Visa settlement runs through Stripe Connect); > your Braintree OAuth merchant account for Braintree delegations. > [accordion] Do my existing customers see any change? > > No. Your existing API and billing surface stay as-is. Agent-payable signup > is a parallel path you opt into with a new endpoint. > [accordion] Can I keep my current pricing model? > > Yes. Per-call, top-ups, and credit bundles map cleanly to Nevermined plans. > For subscriptions, talk to us, recurring billing is supported case-by-case. > [accordion] What card rails are supported? > > Three rails today, all consumed through the same `nvm:card-delegation` > x402 scheme: > > * **[Stripe](/docs/products/payments/overview)** — direct card enrollment > and Stripe PaymentIntents settlement > * **[Braintree](/docs/products/payments/braintree-onboarding)** — card enrollment > through VGS and settlement against OAuth-connected > seller merchants > * **Visa Trusted Agent Protocol** — Visa Agentic Token enrollment via VGS > Credential Management Platform, per-delegation WebAuthn/passkey device > binding, settlement through Stripe Connect > > The x402 token your endpoint verifies is the same regardless of rail; > Nevermined handles the rail-specific details. See the > [card-delegation spec](/docs/specs/x402-card-delegation) for the > underlying flow. > [accordion] Is there a sandbox? > > Yes, on the Stripe and Braintree rails. Integrate, run end-to-end test > transactions, and validate your handler before flipping to live. The Visa > Trusted Agent Protocol uses VGS sandbox with VTS-registered test PANs; > Visa delegations require a real device that can run a WebAuthn ceremony > (or fall back to the email OTP that VTS sends). > [accordion] What languages and frameworks are supported? > > TypeScript and Python SDKs ship today, with framework helpers for > [Express.js](/docs/integrate/add-to-your-agent/express) and > [FastAPI](/docs/integrate/add-to-your-agent/fastapi). The facilitator API > is plain HTTP, so any language can call verify/settle directly. See the > [Generic HTTP guide](/docs/integrate/add-to-your-agent/generic-http). > [accordion] Do I need a Stripe account? > > A Stripe Connect account is required for Stripe and Visa Trusted Agent > Protocol delegations (Visa settlement runs through Stripe Connect). For > Braintree delegations, you connect a Braintree OAuth merchant account > instead (see > [Braintree onboarding](/docs/products/payments/braintree-onboarding)). > Nevermined handles card acquisition and PCI scope on the buyer side; you > just bring your payout destination. > [accordion] Who is the merchant of record? > > **You are.** Nevermined creates each card charge with Stripe's > `on_behalf_of` parameter set to your connected account, which makes your > account the merchant of record: your statement descriptor appears on your > buyers' card statements, and the charge settles in your country and > currency. Nevermined takes its fee as a Stripe application fee and > transfers the remainder to your connected account. > [accordion] How are chargebacks handled? > > Even though you are the merchant of record, Stripe debits **Nevermined's** > balance for disputes on these charges — so chargeback exposure sits with > us, not with you. We surface the chargeback or charge reference so you can > match a dispute back to the specific agent transaction that caused it. > [accordion] Multi-currency? > > Stripe Connect handles currency conversion to your destination account, > so non-USD payouts work for Stripe and Visa delegations. Braintree > requires the seller to have a child merchant account per accepted > currency. The Visa Trusted Agent Protocol currently supports > predominantly US-based issuers, with the eligibility list expanding > through the pilot. ## Want a shortcut? Become a Nevermined Organization A Premium Organization bundles the agent-discovery work above and adds tooling on top: an embeddable PCI-compliant card-capture widget for your domain, auto-generated `llms.txt` and `agentic-instructions.md` rendered live from your plans, webhooks, analytics, an activity feed, and multi-seat access. The DIY recipe above stays fully supported and is what powers Exa today; pick whichever fits your operational model. See [Platform Partners (Organizations)](/docs/integrations/organizations) for the org-specific guide. ## Pricing Every account starts on the free **Personal** tier. Upgrading that workspace to a paid organization tier — **Premium** or **Enterprise** — happens from the [Billing page](https://nevermined.app/organization), and you can change tier later. | Plan | Cost | What's included | | - | - | - | | **Personal** | Free | Publish up to 20 agents and 10 plans on a single-seat account. Unlimited customers. No org features (no widgets, no auto-generated agent docs, no analytics). | | **Premium** ⭐ **Recommended** | **\$250 / month** | Up to 100 agents and 50 plans, 5 invitable seats, widget card capture, auto-generated `llms.txt` / `agentic-instructions.md`, webhooks, analytics, activity feed. | | **Enterprise** | **\$500 / month** | Premium + unlimited agents, plans, and seats, plus the [customer CRM](/docs/solutions/organizations/customers) and the realtime activity stream (WebSocket). | The caps count what *you* publish — agents are your registered services, plans are your pricing packages. The number of customers buying them is unlimited on every tier. See [Tiers at a glance](/docs/solutions/organizations/overview#tiers-at-a-glance) for the full comparison. > [!WARNING] > > **A subscription covers one environment only.** Upgrading your **sandbox** > workspace does not upgrade **live**, and vice versa — so a provider running > both is subscribing twice. Trial a tier on sandbox, then subscribe > separately on live. See [Plans & Billing](/docs/solutions/organizations/plans-and-billing). Prices above are indicative; the live price for each tier is shown on the upgrade screen. Settlement fees on agent payments are documented in the [Payments overview](/docs/products/payments/overview). > [!NOTE] > > **Pilot / whitelist / fee waiver.** Talk to us before you ship if you're a launch > partner, an early-stage API provider, or running a closed pilot. We can waive > or reduce Organization plan fees and settlement fees in select circumstances. > Email [hello@nevermined.io](mailto:hello@nevermined.io) or > [contact us](https://nevermined.ai/contact-us/). ## Related * [x402 Card Delegation Spec](/docs/specs/x402-card-delegation) - full verify/settle protocol with JWT claims, error codes, and the four-phase flow * [Payments Facilitator: How it works](/docs/products/payments-facilitator/how-it-works) * end-to-end walk-through of the facilitator API * [Validate Requests](/docs/integrate/patterns/validate-requests) and [Charge Credits](/docs/integrate/patterns/charge-credits) - copy-paste patterns for the verify and settle steps * [Manage Plans](/docs/products/nevermined-app/manage-plans) - set up a pay-as-you-go plan * [Payments overview](/docs/products/payments/overview) - how buyers enroll cards and create delegations * [API provider mirror template](https://nevermined.ai/integrations/api-provider-template.md) * copy-paste skeleton for the `.md` you publish on your own domain * [Platform Partners (Organizations)](/docs/integrations/organizations) - the recommended org path with widgets, analytics, and webhooks # Card Delegation Source: https://nevermined.ai/docs/solutions/card-delegation Let users enroll a credit or debit card once and delegate a spending budget to AI agents — directly in the app, via a white-labeled redirect, or embedded as a widget. Credit-card delegation is how a human user authorizes an AI agent to spend on their behalf, within an explicit budget and expiry, without handing over the card itself. The card is tokenized once via Stripe, Braintree, or Visa Intelligent Commerce, and the delegation defines exactly how much the agent can charge, for how long, and against which API key. Nevermined ships **three ways** to drive that flow, all built on the same backend. Pick the one that matches where your users live. > [card] [Directly in the App](#1-directly-in-the-nevermined-app) > > Users go to **nevermined.app**, sign in, enroll a card, and create a delegation. Zero integration work. > [card] [White-label redirect (CLI)](#2-white-label-redirect-cli--top-level-tab) > > Your CLI or backend prints a URL. The user clicks it, completes the flow in a chromeless page, and your process receives the IDs at a localhost callback. > [card] [Embedded widgets](#3-embedded-widgets-iframe) > > Drop a Nevermined-hosted iframe straight into your own pricing page. Users never leave your domain. > [!NOTE] > > Only the **embedded widgets** (option 3, iframe) are organization-scoped — they need an active [Nevermined organization](/docs/integrations/organizations) with a widget key. Options **1** and **2** work for **anyone**: option 1 for any signed-in user, and option 2 for any holder of an NVM API key. The redirect flow has an **open path for autonomous agents** (`POST /api/v1/embed/session`, no organization required) and an org-scoped path (`POST /api/v1/widgets/session/self`) used by the `nevermined` CLI and org members. > [!TIP] > > Building an autonomous agent that needs to pay end to end? See [AI Agents: Buy Access Autonomously](/docs/getting-started/ai-agent-purchase) for the full login → card → delegation → x402 path. ## 1. Directly in the Nevermined App The fastest path for end-users and the natural fit when your users are already a part of the Nevermined community. No code, no integration. **1. Sign in to Nevermined** Open [nevermined.app](https://nevermined.app) and sign in with email, Google, or GitHub. First-time users land on a short onboarding flow. **2. Open Settings > Payment Methods** In the Nevermined App, navigate to **Settings > Payment Methods**. This is the dashboard for every card you have enrolled and every active delegation. **3. Enroll a card** Click **Add payment method** and fill in the card form. Where it is offered, Visa Agentic is an option on that form. Card data is captured in a PCI-compliant iframe and tokenized before submission — Nevermined never stores the raw card number. The plan you pay picks the provider — [check it with `resolveNetwork()` / `resolve_network()`](/docs/products/payments/card-enrollment#choosing-a-provider). See [Card Enrollment](/docs/products/payments/card-enrollment) for the differences between the card paths (Visa requires a passkey or OTP). **4. Create a delegation** On the enrolled card row, click **Delegate**. Set: * **Spending limit** in dollars (minimum \$0.50). The delegation is rejected once the agent has charged this amount in total. * **Duration** — 1 hour, 24 hours, 7 days, 30 days, or a custom value. The delegation expires automatically. * **Max transactions** (optional) — hard cap on how many times the agent can charge the card. * **API key restriction** (optional) — scope the delegation to a single API key so a compromised key can only spend the budget allowed to it. See [Mandates](/docs/products/payments/mandates) for the underlying lifecycle and revocation semantics. **5. Revoke at any time** Both cards and delegations can be revoked from the same dashboard. Revocation takes effect on the next agent request — no waiting period. ## 2. White-label redirect (CLI / top-level tab) For tools that run **outside the browser** — CLIs, terminal-based agents, desktop apps — but still need to authorize a card. The pattern mirrors `nevermined login`: print a URL, the user clicks it, the browser handles the chromeless card setup, and your process receives the result at a localhost callback. > [!NOTE] > > This flow works **with or without an organization**, depending on which session you mint: > > * **Autonomous agents / buyers (no org):** mint an open embedded session with `POST /api/v1/embed/session` — any valid NVM API key, no organization needed. This is the path for AI agents purchasing on a user's behalf. > * **Org members (e.g. the `nevermined` CLI):** mint an org-scoped session with `POST /api/v1/widgets/session/self`, which requires membership in the target organization. > > Both produce a `sessionToken` of the same shape that the embed app accepts; what differs is **who can mint it** and **what the card/delegation attach to** — your own Nevermined account via the embedded path, or the organization via the widget path. See [Platform Partners](/docs/integrations/organizations) for the organization features. ### How the handshake works ``` Agent / CLI Nevermined API Embed app (browser) Local callback │ │ │ │ │ start one-shot │ │ │ │ bind /callback on │ │ │ │ 127.0.0.1:0 (random) │ │ │──── listening │ │ │ │ │ POST /api/v1/embed/session │ │ │ Bearer │ │ │ │ { returnUrl } │ │ │ │─────────────────────────▶│ │ │ │◀─────────────────────────│ mint a session │ │ │ { sessionToken, │ bound to the │ │ │ isReturnUrlAllowed } │ caller's identity │ │ │ │ (no org needed) │ │ │ │ │ │ │ open {embed}/cards/setup │ │ │ │ ?sessionToken=…&returnUrl=…&state=&provider=stripe │ │────────────────────────────────────────────────▶│ chromeless page: │ │ │ │ - validate session │ │ │ │ - enroll card │ │ │ │ (VGS Collect) │ │ │ │ - create delegation │ │ │ │ - redirect to │ │ │ │ returnUrl + ids + │ │ │ │ state │ │ │ │──────────────────────▶│ GET /callback?paymentMethodId=… │◀──────────────────────────────────────────────────────── resolved &delegationId=…&state=… │ │ │ │ │ verify state matches │ │ │ │ → resolve, close │ │ │ ``` Org members (e.g. the `nevermined` CLI) mint the session with `POST /api/v1/widgets/session/self` (`{ orgId, returnUrl }`) instead — same handshake, but it requires membership in the target organization. ### The shortest possible integration The Nevermined Payments CLI ships ready-made commands for this flow: ```bash theme={null} # Combined: enroll a card AND create a delegation. Returns both IDs. nevermined cards setup [--org ] [--provider stripe|braintree|visa] # Single-purpose: only enroll a card. nevermined cards enroll [--org ] [--provider …] # Single-purpose: only create a delegation against an already-enrolled card. nevermined cards delegate --card [--org ] ``` Each command opens the browser at `{embed}/cards/?…` — the standalone embed app (`embed.nevermined.app` for live, `embed.nevermined.dev` for staging), not the old webapp `/embed/*` routes — waits up to 5 minutes for the user to complete the flow, then exits cleanly with the resulting IDs. `--no-browser` prints the URL instead of opening it — useful over SSH or in CI. ### Build your own (any language) If you are writing a CLI in a language other than TypeScript, or you want this baked into your own backend, follow the four steps below. **1. Start a one-shot localhost callback server** Bind to `127.0.0.1:0` (the OS picks a free port). Listen on `/callback`. Note the port for step 3. **Never bind to `0.0.0.0`** — the callback should not be reachable from the network. **2. Mint a session** Authenticate the request with the user's own NVM API key. **Autonomous agents and buyers should use the open embedded session** — it needs no organization: ```http theme={null} POST {api}/api/v1/embed/session Authorization: Bearer Content-Type: application/json { "returnUrl": "http://localhost:54321/callback" } ``` Response (200 OK): ```json theme={null} { "sessionToken": "eyJ…", "userId": "us-…", "userWallet": "0x…", "apiKeyHash": "sandbox:eyJ…", "expiresAt": "2026-05-22T19:00:00.000Z", "isReturnUrlAllowed": true } ``` The card and delegation attach to the caller's own account. There is no org-membership check, so the failure modes are only: | HTTP | Meaning | | - | - | | 400 | `returnUrl` is not a valid `http`/`https` URL (DTO validation). | | 401 `BCK.APIKEY.0004` | The NVM API key is invalid or expired — run `nevermined login` again. | | 429 | Rate limited — the endpoint allows 30 mint calls per minute. Back off and retry. | > [accordion] Org-scoped alternative: POST /api/v1/widgets/session/self > > Org members (and the `nevermined` CLI) can instead mint an **org-scoped** session. It returns the same `sessionToken` shape, but requires membership in the target organization and takes an `orgId`: > > ```http theme={null} > POST {api}/api/v1/widgets/session/self > Authorization: Bearer > Content-Type: application/json > > { > "orgId": "org-abc-123", > "returnUrl": "http://localhost:54321/callback" > } > ``` > > Additional failure codes: `403 BCK.WIDGET_SESSION.0018` (the caller has no active organization memberships — if you're a buyer/agent enrolling a card, use the open `POST /api/v1/embed/session` flow above instead) and `403 BCK.WIDGET_SESSION.0019` (the `orgId` is not one of the caller's memberships — list them via `/organizations/my-memberships`). **3. Open the browser** Construct the URL and open it with the OS browser-opener (`xdg-open` / `open` / `start`): ``` {embed}/cards/setup ?sessionToken= &returnUrl= &state= &provider=stripe ``` `{embed}` is the standalone embed app — `https://embed.nevermined.app` (live) or `https://embed.nevermined.dev` (staging). The card surfaces moved off the webapp `/embed/*` routes to this dedicated app. Three routes are available: | Route | Callback returns | | - | - | | `{embed}/cards/setup` | `paymentMethodId` + `delegationId` (one-shot, both steps) | | `{embed}/cards/enroll` | `paymentMethodId` only | | `{embed}/cards/delegate?paymentMethodId=` | `delegationId` only | The `state` value is echoed back in the redirect so you can bind the callback to this specific request (CSRF). 16 bytes (32 hex characters) of cryptographic randomness is the recommended minimum. **4. Receive the callback** The browser redirects to `?paymentMethodId=…&delegationId=…&state=` on success. Your server must: 1. Verify the `state` query parameter matches the one you issued. Compare in **constant time** (`crypto.timingSafeEqual` in Node, `hmac.compare_digest` in Python). Reject mismatches with a 400. 2. Extract the ID(s) from the query string. 3. Respond `200 OK` with a friendly "you can close this tab" HTML page. 4. Close the server. Recommended overall timeout: **5 minutes**. Match the `nevermined login` flow — users may switch contexts between the terminal and the browser. ### Allowed `returnUrl` hosts The server validates `returnUrl` against the session's allow-list: * `localhost`, `127.0.0.1`, `[::1]` (any port, any path) — accepted for **both** session kinds. * Other `https://` origins — accepted only for **widget-key** sessions whose key has the origin in its `allowedOrigins` list. * **Self-mint** sessions — both the open `POST /api/v1/embed/session` and the org-scoped `POST /api/v1/widgets/session/self` documented above — reject any non-localhost host. Use the widget-key flow (see option 3) if you need remote redirects. ### Security checklist * Bind only to `127.0.0.1`, not `0.0.0.0`. * Use a per-flow cryptographically random `state`. Compare in constant time. * Treat the session token like a bearer credential — don't log it, don't persist it beyond the flow. It carries `apiKeyHash` and expires in 2 hours. * The embed page strips `sessionToken` from the URL immediately after consumption, so the back button doesn't replay it. The full integrator reference, including TypeScript pseudocode, lives in [`cli-card-setup.md`](https://github.com/nevermined-io/payments/blob/main/markdown/cli-card-setup.md) in the Payments SDK repo. ## 3. Embedded widgets (iframe) Your end-users never leave your domain. You mint a widget session on your server with the organization's widget-key and pass it straight to the browser SDK — no token-exchange round-trip — and the user completes the card-enrollment + delegation flow inside your own page. > [!WARNING] > > The iframe widget flow requires an **active Nevermined organization** — this is the one option that does. The widget-key is the credential that scopes every iframe session to your org's users — see [Platform Partners](/docs/integrations/organizations) for the upgrade path. The full guide — including how to generate a widget key, mint widget sessions server-side, mount the iframe on your page, and react to `nvm:success` / `nvm:error` events — lives in [Embed Nevermined Widgets](/docs/integrations/organization-widgets). Choose this path when: * Your users are in a browser already (a website, a SaaS dashboard) and you want to keep them on your domain. * You need brand consistency — the iframe inherits the parent page's framing and your organization's branding theme. * You want a postMessage event stream rather than a one-shot redirect. Choose the white-label redirect (option 2) instead when your tool runs outside a browser (CLI, agent, desktop) and you need a localhost callback. ## Comparison | | Directly in App | White-label redirect | Embedded widget | | - | - | - | - | | **Where the user finishes** | nevermined.app | A chromeless page in their browser | Your own page (iframe) | | **Integration effort** | None | One HTTP server + one URL open | A widget key + iframe mount | | **Requires an organization** | No | No (open embed session) — or org-scoped via the widget session | Yes | | **Best for** | Power users, internal teams | CLIs, terminal-based agents, desktop apps | Websites, SaaS dashboards | | **Authentication** | The user's own Privy login | The user's own NVM API key (Bearer) | Your server-minted widget session | | **Result delivery** | UI state | `paymentMethodId` + `delegationId` at a localhost callback | `nvm:success` postMessage to the parent page | | **Cross-origin redirect** | n/a | Localhost only (self-mint), or widget-key `allowedOrigins` | Same as widget-key `allowedOrigins` | ## See Also * [Card Enrollment](/docs/products/payments/card-enrollment) — per-provider enrollment internals (Visa / Stripe / Braintree) * [Mandates](/docs/products/payments/mandates) — what a delegation does once it exists * [Embed Nevermined Widgets](/docs/integrations/organization-widgets) — full widget-key + iframe guide * [x402 Card Delegation Spec](/docs/specs/x402-card-delegation) — protocol-level reference * [Platform Partners](/docs/integrations/organizations) — how to become an organization # MCP Point of Sales Source: https://nevermined.ai/docs/solutions/mcp-point-of-sales Monetize Model Context Protocol tools across web and IDEs with Nevermined’s MCP integration. Set up a point of sale for MCP tools. With Nevermined’s MCP integration, builders can automatically expose tools and allow users to pay for access—whether in web apps or non-web environments like Cursor and VS Code. ## How It Works * **Tool Discovery**: Your MCP tools are registered as agent capabilities. * **Payment Plans**: Users purchase subscriptions or credits to invoke tools. * **Access Tokens**: Nevermined issues bearer tokens for authorized tool calls. * **Multi-Channel**: Works in browsers, CLIs, and IDEs supporting MCP. ## Benefits * **Immediate monetization**: Start charging for MCP tool usage. * **Broad distribution**: Reach users in web and IDE environments. * **Flexible pricing**: Subscriptions and metered credits. * **Unified access**: One access model across channels. ## Implementation Steps 1. **Create a Payment Plan** in the Nevermined App. 2. **Register your MCP Tools as an Agent** with endpoints representing tool invocations. 3. **Integrate Nevermined MCP**: Configure MCP clients to include Nevermined-issued bearer tokens. 4. **Publish** your MCP-enabled agent; share with users. ## Learn More * Integration Guide: [MCP Integration](/docs/integrations/mcp) # Activity & Events Source: https://nevermined.ai/docs/solutions/organizations/activity-and-events Track everything in your organization: an activity feed, a live WebSocket stream, and outbound webhooks for member, plan, customer, and subscription events. Organizations emit a structured stream of **events** for everything that happens inside them — members joining, plans being purchased, customers arriving, subscriptions changing. Nevermined exposes that stream three ways so you can consume it however you need: browse it in the dashboard, stream it live, or push it to your own backend. ## The activity feed The **Events** tab is a paginated, filterable history of your organization's activity. Each entry shows what happened, who triggered it, what it affected, and when. It's the audit log and the "what did the team do this week" view in one. > [!NOTE] > > The activity feed is available to every member of a **Premium** or **Enterprise** organization. Events are grouped into a few families: | Family | Example events | | - | - | | **Membership** | `member.invited`, `member.joined`, `member.role_changed`, `member.deactivated`, `member.reactivated`, `member.removed`, `invitation.revoked`, `invitation.expired` | | **Resources** | `agent.created`, `plan.created`, `plan.updated`, `plan.purchased` | | **Customers** | `customer.added`, `customer.blocked`, `customer.unblocked` | | **Subscriptions** | `subscription.upgraded`, `subscription.downgraded`, `subscription.canceled`, `subscription.lapsed` | | **Webhook delivery** | `webhook.delivered`, `webhook.failed` | | **API keys & credits** | `apikey.created`, `apikey.revoked`, `credits.redeemed` | | **Card-delegation lifecycle** | `delegation.created`, `delegation.expired`, `delegation.exhausted`, `delegation.revoked` | You can filter the feed by event type, by the member who triggered an event, and by date range. Each event also carries a structured `subject` describing the resource it's about (an invitation includes the role and email, a subscription includes the tier, and so on). ## Realtime stream For dashboards and integrations that need events the instant they happen, organizations expose a **realtime WebSocket stream**. Open a connection and every new activity event is pushed to you live, with a replay cursor so you can catch up on anything you missed while disconnected. > [!NOTE] > > The realtime stream is an **Enterprise** feature. Manage your connection from the **Realtime** tab, which holds the per-member connection secrets and a copy-paste connection guide. From the Realtime tab you can **create**, **rotate**, and **revoke** per-member WebSocket secrets, and reference the full list of streamable event types. The stream replays recent history from a cursor you provide, then hands off to a live feed — ideal for powering an always-on internal monitor of your organization. ## Webhooks When you'd rather have events **pushed to your own backend** than hold a socket open, organizations support outbound **webhooks**. You register an HTTPS endpoint, choose which event types to receive (or all of them), and Nevermined delivers each matching event as a signed POST. Deliveries are signed with an HMAC secret so your server can verify they're genuine, and delivery attempts are recorded so you can audit and retry. > [!NOTE] > > Webhooks are a **Premium+** capability. The in-dashboard webhooks UI is rolling out behind a feature flag; if you don't see a **Webhooks** tab yet, the realtime stream and activity feed cover the same events in the meantime. ## Consume events from code The activity feed is also part of the Payments SDK. List and filter events, page through history, and build your own monitoring on top — in TypeScript or Python: > [card] [Read the activity feed from the SDK](/docs/integrate/patterns/organizations#read-the-organization-activity-feed) > > `payments.organizations.getOrganizationActivity(...)` with the same event-type and date filters as the dashboard. ## Related > [card] [Analytics](/docs/solutions/organizations/analytics) > > Aggregate these events into revenue and usage dashboards. > [card] [Workspaces & Members](/docs/solutions/organizations/workspaces-and-members) > > The membership events come from here. # Agentic Integration Source: https://nevermined.ai/docs/solutions/organizations/agentic-integration Every organization gets three auto-generated, agent-discoverable files — llms.txt, agentic-instructions.md, and ai-catalog.json — so AI agents and discovery registries can find and pay for your agents. Here's what they are and how to use them. When you publish agents and plans on Nevermined, you don't just get a checkout page — you get a machine-readable **integration surface** that any AI agent can read to discover what you offer and pay for it autonomously. Nevermined generates and keeps this surface up to date for you as three files: > [card] [llms.txt](#llms-txt) > > A concise index of your plans, agents, and reference links. The agent's map of your organization. > [card] [agentic-instructions.md](#agentic-instructions-md) > > A step-by-step guide telling an AI agent how to discover and pay for your agents via x402 or MPP. > [card] [ai-catalog.json](#ai-catalog-json) > > A structured Agentic Resource Discovery (ARD) catalog with your agents' x402 payment terms, crawlable by registries. Nothing to build, host, or keep in sync: publish an agent or a plan and these files reflect it automatically. ## Why this matters An AI agent that has never heard of you can go from **"I found this organization"** to **"I've paid for its agent and I'm calling it"** without a human in the loop. That's the difference between being listed and being *usable* by the agent economy: > [card] Discoverable > > Agents and crawlers read a stable, documented format instead of scraping a marketing page. > [card] Self-serve for agents > > The instructions carry the exact endpoints, environment, and payment steps — an agent can act on them directly. > [card] Payment terms included > > Each agent's price, plan, and settlement scheme travel with the catalog, so a buyer agent can pre-build its x402 payment. > [card] Zero maintenance > > Generated on demand from your live plans and agents. No drift, no stale docs. ## Where to find them Open the Nevermined App and go to **Organization → Agentic Integration**. Each file is listed with a copy button and a direct link — hand any of these URLs to an AI agent to get started. They're also served directly from the API. Every file lives at a **permanent URL** built from your organization ID, which never changes: | File | URL | Content type | | - | - | - | | `llms.txt` | `{API}/api/v1/organizations/{orgId}/llms.txt` | `text/plain` | | `agentic-instructions.md` | `{API}/api/v1/organizations/{orgId}/agentic-instructions.md` | `text/markdown` | | `ai-catalog.json` | `{API}/api/v1/organizations/{orgId}/ai-catalog.json` | `application/json` | `{API}` is the environment's API host — `https://api.sandbox.nevermined.app` for sandbox, `https://api.live.nevermined.app` for live. ```bash theme={null} # No auth needed — this is a public discovery surface curl https://api.sandbox.nevermined.app/api/v1/organizations/org-abc123/agentic-instructions.md ``` > [!NOTE] > > These files are public and served for **active Premium and Enterprise organizations** — any other organization returns `404`. Only your **published** plans and agents appear; deactivating a plan or agent removes it from all three files. ## llms.txt A short, agent-discoverable index that follows the [llms.txt convention](https://llmstxt.org). It's the fast "table of contents" for your organization: the plans you sell, the agents you publish, and links into the Nevermined docs an agent needs to integrate. ```text llms.txt theme={null} # Acme AI > Agent-discoverable index of Payment Plans and AI Agents/Services published by Acme AI on Nevermined. ## Payment Plans - [Acme AI Payment Plan: Pro API access](https://api.live.nevermined.app/api/v1/protocol/plans/) ## Agents - [Acme AI agent: Legal document analyzer](https://api.live.nevermined.app/api/v1/protocol/agents/) ## Nevermined Reference - [x402 payments reference (TypeScript)](https://nevermined.ai/docs/api-reference/typescript/x402) - [This environment's API reference (OpenAPI JSON)](https://api.live.nevermined.app/api/v1/rest/docs-json) - [Get your Nevermined API Keys](https://nevermined.ai/docs/api-reference/typescript/initializing-the-library#get-your-nvm-api-key) - [x402 card-delegation](https://nevermined.ai/docs/specs/x402-card-delegation) - [x402 stablecoins](https://nevermined.ai/docs/integrate/patterns/stablecoin-payments) - [Nevermined Payments Skill](https://nevermined.ai/docs/development-guide/build-using-nvm-skill) - [Nevermined API Reference](https://nevermined.ai/docs/api-reference/introduction) - [Nevermined Concise Context for AI Agents](https://nevermined.ai/docs/llms.txt) - [Nevermined Full Context for AI Agents](https://nevermined.ai/docs/llms-full.txt) ``` **Use it when** you want to give an agent (or an LLM crawler) a lightweight starting point. It's small, cache-friendly, and points onward to everything else. ## agentic-instructions.md The operational guide. Where `llms.txt` is a map, this is the *how-to*: a plain-Markdown document — consumed raw by agents like Claude Code — that tells an autonomous agent exactly how to discover and pay for your agents through Nevermined's **x402 and MPP** flows. Both settle against the same Payment Plans; the agent picks the flow from the service's `402` response. It opens by stating the environment ("you are talking to the sandbox / live environment"), then walks the ordered path — **get a Nevermined API key → set up a payment method and a spending delegation → pay via x402 or MPP** — with the exact endpoints and request bodies inline, so an agent can act on it end to end. The agent picks x402 vs. MPP from the service's `402` response; the same delegation backs both. The key-minting and authentication foundations it relies on are the ones described in [`auth.md`](https://nevermined.app/auth.md). It then lists your **registry of agent-payable APIs** (your plans and agents) and links out to the Nevermined ecosystem docs. > [!TIP] > > This is the single URL to share with a coding agent or harness. Point Claude Code (or any x402-aware agent) at `…/agentic-instructions.md` and it has everything it needs — environment, endpoints, the login → delegation → x402 path, and your catalog — to buy and call your agents on its own. ## ai-catalog.json Your organization's [Agentic Resource Discovery](https://agenticresourcediscovery.org/spec/) (ARD) catalog: one entry per published agent, each carrying an embedded A2A agent card **and** its x402 payment terms. This is the format built for machines — a crawler or registry ingests it directly, and a buyer agent gets everything it needs to pre-build a payment without first triggering a `402`. The payment terms live under the `x-nevermined-payment` key in each entry's `metadata` — plan, price, credits, settlement network, and the ready-to-use x402 `accepts` block: ```json ai-catalog.json theme={null} { "specVersion": "1.0", "host": { "displayName": "Acme AI", "identifier": "did:web:api.live.nevermined.app", "documentationUrl": "https://api.live.nevermined.app/api/v1/organizations/org-abc123/agentic-instructions.md" }, "entries": [ { "identifier": "urn:air:api.live.nevermined.app:agent:", "displayName": "Legal document analyzer", "type": "application/a2a-agent-card+json", "description": "Extracts clauses and obligations from contracts.", "representativeQueries": ["Use Legal document analyzer", "agent for legal"], "metadata": { "x-nevermined-payment": { "paymentProtocol": "x402", "x402Version": 2, "isTrialAvailable": false, "plans": [ { "planId": "", "name": "Pro API access", "priceModel": "fixed", "isCrypto": false, "price": { "amount": "5000000", "asset": "USD", "network": "stripe" }, "credits": { "amount": "1000", "expirySecs": "0", "minPerRequest": "1", "maxPerRequest": "1" }, "accepts": [ { "scheme": "nvm:card-delegation", "network": "stripe", "planId": "", "extra": { "agentId": "" } } ], "planUrl": "https://api.live.nevermined.app/api/v1/protocol/plans/" } ] } } } ] } ``` Crypto plans advertise an on-chain settlement network instead (for example `"network": "eip155:8453"` with `"scheme": "nvm:erc4337"`), so an agent knows exactly which chain to sign for. **Use it when** you're integrating with an ARD-aware registry or building a buyer agent that shops across catalogs programmatically. ## How an agent uses them together The three files layer from "quick index" to "ready-to-transact": **1. An agent is handed one of your URLs** Usually `agentic-instructions.md` (for a coding agent or harness) or `ai-catalog.json` (for a registry or a programmatic buyer). **2. It learns the environment and your catalog** Which network it's on, which API to call, and which of your plans and agents accept payment. **3. It obtains a credential and pays with x402 or MPP** A one-time key + delegation, then it settles against the plan over whichever protocol the service speaks — no human per purchase. **4. It calls your agent** With credits in hand, it invokes your agent and you get paid. See [Buy & Call a Paid Agent](/docs/getting-started/ai-agent-purchase) for the end-to-end flow. ## Related > [card] [Programmatic & Agentic Access](/docs/solutions/organizations/programmatic-access) > > Drive your whole organization from code, and the endpoints behind these files. > [card] [Buy & Call a Paid Agent](/docs/getting-started/ai-agent-purchase) > > The buyer's side — an agent purchasing and calling a paid agent end to end. > [card] [x402 card-delegation](/docs/specs/x402-card-delegation) > > How an agent pays with a delegated card, no human per transaction. > [card] [x402 stablecoin payments](/docs/integrate/patterns/stablecoin-payments) > > Paying for agents with USDC and other stablecoins. > [card] [Paying an MPP service](/docs/development-guide/nevermined-x402#paying-an-mpp-protected-service) > > The MPP buyer flow — the plan-model sibling of x402. # Analytics Source: https://nevermined.ai/docs/solutions/organizations/analytics Revenue, MRR, usage, conversion, and top customers — organization dashboards built from your real on-platform activity, with a date-range filter. The **Analytics** tab turns your organization's on-platform activity into the numbers that matter for a payments business: how much you're earning, what's recurring, what's being used, and how well visitors convert into buyers. Every metric is computed from real Nevermined transactions — there's nothing to instrument. > [!NOTE] > > Analytics dashboards are a **Premium** and **Enterprise** feature, available to every member of a paid organization. ## What you can measure > [card] Revenue > > Total revenue and a per-agent breakdown, so you can see which agents earn the most over any date range. > [card] Monthly Recurring Revenue > > Your MRR alongside the count of active subscriptions — the health metric for subscription plans. > [card] Usage > > Credit consumption per plan and the number of unique users on each plan. > [card] Top customers > > Your highest-spending customers, ranked, with a link straight into the [Customers](/docs/solutions/organizations/customers) CRM. > [card] Conversion > > Checkout sessions, completed purchases, and the conversion rate between them. > [card] Credits by member > > Credit-burn attributed per member, optionally scoped to a single plan — useful for internal cost tracking. ## Working with the dashboards Pick a **date range** (the dashboards default to the last 30 days) and every metric recalculates for that window. Monetary values are shown in USD, and rates are shown as percentages. From the top-customers panel you can jump directly to a customer's detail page to dig into their purchase history. > [!TIP] > > Want these numbers in your own BI tooling or a scheduled report? The organization activity feed is available programmatically from the [Payments SDK](/docs/integrate/patterns/organizations), so you can build your own monitoring and roll-ups on top of the same events. ## Related > [card] [Customers](/docs/solutions/organizations/customers) > > Drill from a revenue number into the customers behind it. > [card] [Plans & Billing](/docs/solutions/organizations/plans-and-billing) > > Make sure Analytics is unlocked on your tier. # Customers Source: https://nevermined.ai/docs/solutions/organizations/customers An Enterprise CRM for your organization: see who buys from your agents, what they spend, and their full purchase history — with search and CSV export. The **Customers** tab is your organization's built-in CRM. It answers a question every business needs: *who is actually paying us, and for what?* As people purchase your plans and use your agents, Nevermined builds and maintains the customer list for you — no manual data entry, no separate billing system to reconcile. > [!NOTE] > > Customer management is an **Enterprise** feature, available to organization **Admins**. Premium organizations see the rest of the dashboard; the Customers tab unlocks when you upgrade to Enterprise. ## Who is a customer A **customer** is any user who has transacted with your organization — bought one of your plans or consumed credits against your agents. Each customer is added automatically the first time they purchase, and their record is kept up to date as they keep buying. Customers are distinct from [members](/docs/solutions/organizations/workspaces-and-members): members build *inside* your organization, customers buy *from* it. ## The customer list The Customers tab shows every customer in a paginated, searchable table: | Column | Meaning | | - | - | | **Customer** | The buyer's username or email, with their user ID. | | **First seen** | When they first purchased from your organization. | | **Last active** | Their most recent purchase. | | **Total spent** | Lifetime spend with your organization, in USD. | Above the table, an **aggregations** panel summarizes the whole customer base — total customers, total purchases, and total spend over time. You can: * **Search** by user ID to jump straight to one customer. * **Export CSV** to download the full list (enriched with name, email, status, first/last seen, and total spent) for use in your own tools. ## Customer detail Click any customer to open their detail view, which focuses on a rolling **90-day** window: > [card] Spend & activity > > Headline stats — total spent, number of purchases, and recent activity — at the top of the page. > [card] Purchase timeline > > A chart of this customer's purchases over the last 90 days, so you can see buying patterns at a glance. Below the summary, a paginated **purchase history** lists each individual transaction — what they bought and when — newest first. ## Related > [card] [White-label Onboarding](/docs/solutions/organizations/white-label-onboarding) > > Provision customers yourself, under your brand — how new customers land in this list without ever seeing Nevermined. > [card] [Analytics](/docs/solutions/organizations/analytics) > > Roll customer activity up into revenue, MRR, and conversion dashboards. > [card] [Activity & Events](/docs/solutions/organizations/activity-and-events) > > Get notified the moment a new customer is added. # Groups & Budgets Source: https://nevermined.ai/docs/solutions/organizations/groups-and-budgets Organize members into groups, cap their spend with budgets, and give each group a shared payment method — all from the Budgets tab or the Organizations API. As your organization grows, you'll want teams to operate independently without handing everyone unlimited spend. **Groups** let you bundle members together; **budgets** put a ceiling on what a group can spend; and **shared payment methods** let a whole group charge to one org-funded source. You manage all three from the **Budgets** tab of the [organization dashboard](https://nevermined.app/organization), or programmatically with your organization's admin API key. > [!NOTE] > > Groups, budgets, and shared payment methods are **Premium and Enterprise** features. Personal and lapsed organizations can't create them. ## Groups A group is a named collection of organization members — for example a *Support* team, a *Research* squad, or a per-customer workspace. An Admin creates a group and adds or removes members at any time. > [card] Create a group > > Give it a name and add the members who should share its budget and payment methods. > [card] Manage membership > > Add or remove members as teams change. Removing someone from a group doesn't remove them from your organization. ## Budgets A **budget** sets how much a group may spend over a period and tracks its consumption in real time. When a group reaches its budget, further spend is blocked until the budget resets or an Admin raises it — so a single team can never run away with the whole organization's balance. * **Set a limit** per group from the **Budgets** tab. * **Track usage** against the limit as members spend. * **Adjust or remove** a budget whenever priorities change. > [!TIP] > > Budgets pair naturally with [Organization Wallets](/docs/solutions/organizations/wallets): fund a group from a shared treasury wallet, then cap how fast it draws down with a budget. ## Shared payment methods Instead of every member enrolling their own card, associate an organization **payment method** with a group. Members of that group then transact against the shared card, and you keep billing centralized. Associate or remove a card from a group at any time. ## Where to find it Everything above lives under the **Budgets** tab of the organization dashboard, alongside [Organization Wallets](/docs/solutions/organizations/wallets). Select your organization with the workspace switcher, then open **Budgets**. ## Do it programmatically Every group, budget, and shared-payment-method action is available on the Organizations REST API using your **organization's admin** [Nevermined API key](/docs/solutions/organizations/workspaces-and-members) — so an agent or a back-office script can provision teams and enforce spend limits without the dashboard. > [!NOTE] > > The full Organizations API reference is coming soon. Until then, see [SDK & Workspaces](/docs/integrate/patterns/organizations) for authenticating against a specific workspace. ## Related > [card] [Organization Wallets](/docs/solutions/organizations/wallets) > > The custodial treasury that funds your groups. > [card] [Plans & Billing](/docs/solutions/organizations/plans-and-billing) > > The tier that unlocks groups, budgets, and wallets. # Organizations Source: https://nevermined.ai/docs/solutions/organizations/overview Turn your Nevermined account into a team workspace: invite members, manage tiered billing, track customers, view analytics, and embed checkout widgets. An **Organization** turns your personal Nevermined account into a first-class, multi-tenant workspace. Instead of one builder shipping agents alone, you get a shared space with its own members, agents, plans, billing, customers, and analytics — everything a team needs to run a payments business on Nevermined. You keep building agents and plans exactly as before. Organizations add the team and business layer on top: who can publish, how you're billed, who's buying from you, and how you embed Nevermined flows into your own product. ## See it in action Watch a walkthrough of the Organizations dashboard — workspaces, members, billing, customers, analytics, and embeddable widgets: [Nevermined Organizations — product demo](https://www.youtube.com/embed/NKmNcaothLo) A tour of the Nevermined Organizations dashboard. ## What you get > [card] A shared team workspace > > Invite teammates as Admins or Members. Agents, plans, and API keys are owned by the organization, not a single person. > [card] Tiered billing > > Subscribe to a Premium or Enterprise tier per environment. Higher tiers raise your caps and unlock features. > [card] Know your customers > > A customer list that auto-populates as people buy from your agents, with spend, purchase history, and CSV export. > [card] Revenue analytics > > Revenue, MRR, usage, conversion, and top customers — dashboards built from your real on-platform activity. > [card] Event streams > > An activity feed, a realtime WebSocket stream, and outbound webhooks to wire org events into your own systems. > [card] Embeddable widgets > > Drop Nevermined checkout, card enrollment, and delegation flows into your own site as signed iframes. ## Tiers at a glance Every Nevermined account starts as a **Personal** account. When you're ready for a team and the business tooling, you upgrade that workspace to a paid organization tier — **Premium** or **Enterprise** — from the [Billing page](https://nevermined.app/organization). Each tier raises your caps and unlocks more of the platform. | Capability | Personal | Premium | Enterprise | | - | - | - | - | | Agents | Up to 20 | Up to 100 | Unlimited | | Plans | Up to 10 | Up to 50 | Unlimited | | Team members | — | Up to 5 | Unlimited | | Member invitations | — | ✓ | ✓ | | Analytics dashboards | — | ✓ | ✓ | | Activity feed | — | ✓ | ✓ | | Webhooks | — | ✓ | ✓ | | Embeddable widgets | — | ✓ | ✓ | | AI instructions + `llms.txt` | — | ✓ | ✓ | | Groups, budgets & shared payment methods | — | ✓ | ✓ | | Organization wallets | — | ✓ | ✓ | | Customer management (CRM) | — | — | ✓ | | Realtime activity stream | — | — | ✓ | *Webhooks are available on Premium and Enterprise through the API today; the in-dashboard **Webhooks** tab is rolling out — see [Activity & Events](/docs/solutions/organizations/activity-and-events#webhooks).* > [!NOTE] > > Subscriptions are scoped to a single environment. Your **sandbox** and **live** workspaces are billed and upgraded independently, so you can trial a tier on sandbox before paying for it on live. ## Where to find it Organizations live in the [Nevermined App](https://nevermined.app). Use the **workspace switcher** in the bottom-left of the sidebar to move between your Personal account and any organization you belong to. When an organization is selected, the sidebar exposes the organization dashboard at [`nevermined.app/organization`](https://nevermined.app/organization), with one tab per feature: Details, Plans, Agents, Members, Budgets, Integration, Customers, Analytics, Events, Widgets, Realtime, and Billing. ## Explore the features > [card] [Workspaces & Members](/docs/solutions/organizations/workspaces-and-members) > > Create an organization, switch workspaces, and invite teammates as Admins or Members. > [card] [Plans & Billing](/docs/solutions/organizations/plans-and-billing) > > Compare Premium and Enterprise, upgrade or downgrade, and understand caps and entitlements. > [card] [Groups & Budgets](/docs/solutions/organizations/groups-and-budgets) > > Bundle members into teams, cap their spend with budgets, and share payment methods. > [card] [Organization Wallets](/docs/solutions/organizations/wallets) > > A custodial USDC/EURC treasury that funds your groups. > [card] [Customers](/docs/solutions/organizations/customers) > > The Enterprise CRM: who's buying from your agents, what they spend, and their purchase history. > [card] [White-label Onboarding](/docs/solutions/organizations/white-label-onboarding) > > Provision your own customers programmatically — under your brand, no seat, with a scoped key to pay for your agents on their behalf. > [card] [Analytics](/docs/solutions/organizations/analytics) > > Revenue, MRR, usage, conversion, and per-member attribution dashboards. > [card] [Activity & Events](/docs/solutions/organizations/activity-and-events) > > The activity feed, the realtime WebSocket stream, and outbound webhooks. > [card] [Embed Widgets](/docs/integrations/organization-widgets) > > Render Nevermined checkout, card, and delegation flows on your own domain. > [card] [Platform Partners](/docs/integrations/organizations) > > Run a marketplace: branded checkout and commissions on every builder's sale. > [card] [Programmatic & Agentic Access](/docs/solutions/organizations/programmatic-access) > > Drive the whole organization from code, and let agents discover and pay for your agents. > [card] [SDK & Workspaces](/docs/integrate/patterns/organizations) > > List memberships, target a workspace when publishing, and read the activity feed from code. # Plans & Billing Source: https://nevermined.ai/docs/solutions/organizations/plans-and-billing Compare the Starter, Premium, and Enterprise organization tiers, upgrade or downgrade anytime, and understand the caps and features each tier unlocks. Organizations come in three paid tiers — **Starter**, **Premium**, and **Enterprise**. Each tier sets your resource caps (how many agents, plans, and members you can have) and unlocks platform features. You manage all of this from the **Billing** tab of the organization dashboard. ## Compare the tiers > [card] Starter > > The entry tier — get your own service into the Catalog. > > * Up to **20 agents** > * Up to **10 plans** > * **1 member** > * **[Publish 1 agent to the Catalog](/docs/products/catalog/publish-ai-service)** > * **1 organization wallet** > * Embeddable widgets > * Activity feed > [card] Premium > > For teams shipping their first Nevermined-powered product. > > * Up to **100 agents** > * Up to **50 plans** > * Up to **5 team members** > * Member invitations > * **[Publish up to 3 agents to the Catalog](/docs/products/catalog/publish-ai-service)** > * Groups, budgets & shared payment methods > * Organization wallets > * Analytics dashboards > * Embeddable widgets > * Activity feed > * Webhooks > * AI instructions, `llms.txt` & ARD catalog > [card] Enterprise > > For organizations operating at scale across many products and teams. > > * **Everything in Premium**, with **[up to 10 Catalog listings](/docs/products/catalog/publish-ai-service)** > * **Customer management** (CRM) > * **Realtime activity stream** (WebSocket) > * **Unlimited** agents > * **Unlimited** plans > * **Unlimited** team members > [!NOTE] > > **[Publish to the Catalog](/docs/products/catalog/publish-ai-service)** is available on **every** paid tier — Starter is the cheapest way to unlock it. **Customer management** and the **Realtime activity stream** are the two Enterprise-exclusive features — they're the main reasons to move from Premium to Enterprise. ## Pricing All three tiers are **recurring monthly subscriptions billed in USD** through Stripe. You can switch tiers or cancel anytime from the Billing page; the live price for each tier is shown on the upgrade screen. > [!WARNING] > > A subscription applies to **one environment only**. Upgrading your **sandbox** workspace does not upgrade **live**, and vice versa — sandbox uses Stripe test-mode pricing while live uses real charges. Trial a tier on sandbox, then subscribe separately on live when you're ready. ## Upgrade, downgrade, or cancel From the **Billing** tab, an Admin can move between tiers at any time: | Change | What happens | | - | - | | **Personal → Starter / Premium / Enterprise** | Create the organization through the in-app Stripe checkout. | | **Between paid tiers** (Starter ↔ Premium ↔ Enterprise) | In place on the same subscription, no re-checkout. **Upgrades** bill the prorated difference now — confirm the card charge in the dialog and the higher tier is granted once it's paid. **Downgrades** apply right away (the credit lands on your next invoice); anything published beyond the lower tier's caps — agents, plans, and Catalog listings — is unlisted automatically, newest first. | | **Cancel** | Your access continues until the end of the current billing period, then the organization lapses. | The Billing page also shows your **invoices** (date, amount, period, and status) so you have a record of every charge. ## Caps and entitlements The Billing page surfaces a live **caps table** showing what you've used versus what your tier allows: | Resource | Personal | Starter | Premium | Enterprise | | - | - | - | - | - | | Agents | 20 | 20 | 100 | Unlimited | | Plans | 10 | 10 | 50 | Unlimited | | Team members | — | 1 | 5 | Unlimited | | Catalog listings | — | 1 | 3 | 10 | **Catalog listings are capped separately from agents.** Enterprise has unlimited agents but still lists at most 10 in the Catalog; publishing over your tier's listing cap is refused until you remove a listing or upgrade. Caps are enforced when you create resources. If you hit a cap, registering a new agent or plan is blocked until you remove something or upgrade. Below the caps, a **features list** shows which capabilities your current tier includes, with the locked ones clearly marked. ## The Lapsed state If a subscription is canceled or a payment ultimately fails, the organization becomes **Lapsed**. A lapsed organization keeps its data, but the paid surface is locked: * Creating new agents and plans is disabled (existing ones remain). * Paid-tier features (catalog publishing, analytics, widgets, customers, activity, integration surfaces) are switched off. When you **cancel**, your active Catalog listings are taken down as well. Resubscribing restores your organization and its members, but it does not relist them — resubmit each service and it goes through validation again. Reactivate at any time by resubscribing from the Billing page — your agents, plans, members, and customers are all still there waiting. ## Related > [card] [Workspaces & Members](/docs/solutions/organizations/workspaces-and-members) > > Seats and roles within your tier. > [card] [Customers](/docs/solutions/organizations/customers) > > The Enterprise-only customer CRM. # Programmatic & Agentic Access Source: https://nevermined.ai/docs/solutions/organizations/programmatic-access Drive your whole organization from code with an admin API key, and let autonomous agents discover and pay for your agents through public discovery endpoints. Everything you can do in the Organizations dashboard, you can do from code. The org-management surface is a REST API, so an autonomous agent or a back-office script can run **most** of your organization with no human in the loop. (A few flows still need a one-time browser step — card enrollment, for example.) ## Authenticate as the organization Call the API with a [Nevermined API key](/docs/solutions/organizations/workspaces-and-members) that belongs to a member with the **Admin** role in the organization you want to act on. If the key is already scoped to a specific organization, that scope applies by default; to act on a different workspace, send the `X-Current-Org-Id` header — it **overrides** the key's own scope. > [!WARNING] > > An admin key can invite members, move treasury funds, and withdraw from organization wallets. Treat it like a production secret: keep it server-side and never hand it to an autonomous agent or a client you don't fully control. > [tab] cURL > > ```bash theme={null} > curl https://api.sandbox.nevermined.app/api/v1/organizations/my-memberships \ > -H "Authorization: Bearer $NVM_API_KEY" \ > -H "X-Current-Org-Id: org-9d81acea-7d38-460e-b7c0-c3b92abcbb07" > ``` > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, > environment: 'sandbox', > }) > > const memberships = await payments.organizations.getMyMemberships() > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments > > payments = Payments( > api_key=os.environ.get('NVM_API_KEY'), > environment='sandbox', > ) > > memberships = payments.organizations.get_my_memberships() > ``` See the [SDK & Workspaces](/docs/integrate/patterns/organizations) pattern for more on listing memberships and targeting a specific workspace when you publish agents or plans. ## What you can automate Every organization feature is API-driven, subject to the same tier gates as the dashboard: > [card] [Members & invitations](/docs/solutions/organizations/workspaces-and-members) > > Invite, change roles, deactivate, and remove members. > [card] [Groups & budgets](/docs/solutions/organizations/groups-and-budgets) > > Create teams, cap their spend, and attach shared payment methods. > [card] [Organization wallets](/docs/solutions/organizations/wallets) > > Create treasury wallets, check balances, fund groups, and withdraw. > [card] [Customers](/docs/solutions/organizations/customers) > > Read your CRM and provision customers (Enterprise). > [card] [Analytics](/docs/solutions/organizations/analytics) > > Pull revenue, MRR, usage, and conversion metrics. > [card] [Events & webhooks](/docs/solutions/organizations/activity-and-events) > > Read the activity feed and manage outbound webhooks. > [!NOTE] > > The [White-label Onboarding](/docs/solutions/organizations/white-label-onboarding) flow is purpose-built for automation: one call provisions a **new** customer account under your brand and hands back a scoped key to pay for your agents on their behalf. (Onboarding an email that already has an account instead triggers a consent step before the accounts are linked.) ## Let agents discover your organization Nevermined also exposes three public, unauthenticated per-organization files — `llms.txt`, `agentic-instructions.md`, and `ai-catalog.json` — so autonomous agents and discovery registries can find and pay for what you offer. What each file contains, how agents consume them, the Premium/Enterprise gate, and worked examples all live in [Agentic Integration](/docs/solutions/organizations/agentic-integration). ## Full API reference Every operation is documented per-endpoint in the **Organizations** group of the **API** reference, auto-generated from the server's OpenAPI spec. For SDK-based access, see the [SDK & Workspaces](/docs/integrate/patterns/organizations) pattern. ## Related > [card] [SDK & Workspaces](/docs/integrate/patterns/organizations) > > List memberships, target a workspace, and read the activity feed from code. > [card] [White-label Onboarding](/docs/solutions/organizations/white-label-onboarding) > > Provision customers programmatically under your brand. # Organization Wallets Source: https://nevermined.ai/docs/solutions/organizations/wallets Custodial stablecoin treasury wallets for your organization — hold USDC and EURC, fund groups, and withdraw, from the Budgets tab or the Organizations API. An **organization wallet** is a custodial stablecoin treasury that belongs to the whole organization rather than to one member. Use it to hold **USDC** and **EURC**, fund the teams that spend on your behalf, and move funds out when you need to. Wallets are managed from the **Budgets** tab of the [organization dashboard](https://nevermined.app/organization) or through the Organizations API. > [!NOTE] > > Organization wallets are a **Premium and Enterprise** feature. They are custodial — Nevermined manages the signing key on the organization's behalf, so there's no seed phrase for your team to safeguard. ## Create and fund a wallet An Admin creates a named wallet for the organization. Each wallet has an on-chain address you can send **USDC** or **EURC** to in order to fund it. You can rename a wallet at any time, and an organization can hold more than one depending on its tier. ## Check balances Every wallet shows its live **USDC** and **EURC** balances, so you always know how much treasury is available before you fund a group or authorize spend. ## Fund a group Share a wallet with a [group](/docs/solutions/organizations/groups-and-budgets) to make it that group's funding source. Combined with a **budget**, this lets a team spend from the shared treasury up to a ceiling you control — and you can un-share a wallet from a group whenever you need to cut it off. **1. Create a wallet** Add an organization wallet from the Budgets tab. **2. Fund it** Send USDC or EURC to the wallet's address. **3. Share with a group** Attach the wallet to a group so its members can spend from it. **4. Cap it with a budget** Set a [budget](/docs/solutions/organizations/groups-and-budgets#budgets) so the group draws down only as fast as you allow. ## Withdraw When you need funds outside the platform, **withdraw** moves stablecoins from an organization wallet to an external address. The withdrawal is submitted on-chain from the custodial wallet. > [!WARNING] > > Withdrawals move real funds on-chain and can't be reversed. Double-check the destination address and amount before confirming. ## Do it programmatically Wallet creation, balances, funding groups, and withdrawals are all available on the Organizations REST API with your **organization's admin** [Nevermined API key](/docs/solutions/organizations/workspaces-and-members) — so an autonomous agent can top up a team or sweep a treasury without a human in the dashboard. > [!NOTE] > > The full Organizations API reference is coming soon. Until then, see [SDK & Workspaces](/docs/integrate/patterns/organizations) for authenticating against a specific workspace. ## Related > [card] [Groups & Budgets](/docs/solutions/organizations/groups-and-budgets) > > The teams and spend limits a wallet funds. > [card] [Plans & Billing](/docs/solutions/organizations/plans-and-billing) > > The tier that unlocks organization wallets. # White-label Customer Onboarding Source: https://nevermined.ai/docs/solutions/organizations/white-label-onboarding Onboard your own customers into Nevermined under your brand: provision their accounts programmatically, with no member seat, auto-recorded in your CRM, and a scoped key you can use to pay for your agents on their behalf. Some businesses want their customers *on* Nevermined. Others want Nevermined to disappear entirely — customers stay on your site, under your brand, and never see a third party. **White-label onboarding** is for the second group. From your own backend you provision a Nevermined account for a customer, get back a usable, scoped credential, and transact for them — all without the customer ever creating a Nevermined login. > [!NOTE] > > Onboarding customers is an **Admin** operation — you call it with your organization's admin API key. The customers you onboard appear in your [Customers](/docs/solutions/organizations/customers) CRM (an Enterprise feature). ## Members vs. customers Two different people transact with your organization, and they're provisioned differently: > [card] [Members](/docs/solutions/organizations/workspaces-and-members) > > People who build *inside* your organization — teammates who publish agents and plans. A member **consumes a seat** and has a role. > [card] [Customers](/docs/solutions/organizations/customers) > > End users who buy *from* your organization. A customer takes **no seat**, is recorded in your CRM, and is who this guide onboards. Both are provisioned through the same endpoint (`POST /organizations/account`) — the outcome is a parameter, not a separate integration. The member flow is unchanged; onboarding a **customer** is the additive path described here. ## How it works You hand the SDK an email. What comes back depends on whether that email already has a Nevermined account, and whether it's yours: | The email is… | What happens | You get back | | - | - | - | | **New** | An account is created, recorded in your Customers CRM, and issued a scoped key | The usable `nvmApiKey` (+ `userId`, `userWallet`) | | **Already your customer** | The scoped key is re-issued (renewal) | The usable `nvmApiKey` | | **An existing account you don't own** | No key is issued. A consent email is sent to the account's owner | `consentRequired: true` only — the account's identity is never disclosed | That last case keeps onboarding safe: you can't silently attach someone else's Nevermined account to your organization, and you can't use the call to probe which emails have accounts. Once the owner approves the emailed challenge, call again with the same email to complete onboarding and receive the key. ## The credential you get back The key returned for a customer is deliberately **narrow** — it's meant for consumption, not building: > [card] Can > > **Purchase plans** and **redeem credits** — everything needed to pay for and use your agents on the customer's behalf. > [card] Cannot > > **Register agents** or **mint credits** — the builder-side capabilities stay with your organization's members. It's also **short-lived** and **revocable**, so a leaked customer credential has a small blast radius. The exact expiry is returned as `expiresAt` (ISO-8601) — track it and re-onboard to refresh before it lapses. Store it server-side and never expose it to the browser. > [!NOTE] > > **Using the raw REST API instead of the SDK?** `POST /organizations/account` returns **two** similar-looking credential fields — present `walletResult.hash` as the `Authorization: Bearer` token; that is the credential (the dashboard copies exactly this). The sibling `walletResult.nvmApiKey` is the encrypted server-side/SDK blob — **do not send it as a header**; it is not a valid Bearer. The SDK handles this for you: `onboardCustomer`'s `nvmApiKey` result field already carries the Bearer, so pass it straight to `Payments.getInstance`. ## Onboard a customer Initialize the SDK with your **organization admin** key, then call `onboardCustomer`. Handle the two shapes it can return: > [tab] TypeScript > > ```typescript theme={null} > import { Payments } from '@nevermined-io/payments' > > const payments = Payments.getInstance({ > nvmApiKey: process.env.NVM_API_KEY!, // your organization admin key ("sandbox:..." or "live:...") > environment: 'sandbox', > }) > > const result = await payments.organizations.onboardCustomer('customer@example.com') > > if (result.consentRequired) { > // The email already has a Nevermined account your org doesn't own. > // A consent email was sent to the owner — retry once they approve. > console.log('Consent pending — ask the customer to check their email.') > } else { > // New account or your returning customer: a usable, scoped key is issued. > console.log('Onboarded customer') > > // Act for the customer with their scoped key. > const customer = Payments.getInstance({ > nvmApiKey: result.nvmApiKey, > environment: 'sandbox', > }) > // `customer` can now purchase plans and redeem credits. > } > ``` > [tab] Python > > ```python theme={null} > import os > from payments_py import Payments, PaymentOptions > > payments = Payments.get_instance( > PaymentOptions( > nvm_api_key=os.environ["NVM_ORG_ADMIN_API_KEY"], # your organization admin key > environment="sandbox", > ) > ) > > result = payments.organizations.onboard_customer("customer@example.com") > > if result.consent_required: > # Existing account your org doesn't own — a consent email was sent. > # Retry once the owner approves. > print("Consent pending — ask the customer to check their email.") > else: > # New account or your returning customer: a usable, scoped key is issued. > print("Onboarded customer", result.user_id) > > # Act for the customer with their scoped key. > customer = Payments.get_instance( > PaymentOptions(nvm_api_key=result.nvm_api_key, environment="sandbox") > ) > # `customer` can now purchase plans and redeem credits. > ``` From there, the `customer` client behaves like any buyer: it can [order a plan](/docs/getting-started/ai-agent-purchase) and [pay your agents over x402](/docs/getting-started/ai-agent-purchase) — all attributed to your organization, all invisible to the end user. ## Two ways to onboard > [card] Programmatic (this guide) > > Provision from your backend with the SDK. Best when you own the customer relationship end-to-end and want zero Nevermined UI. > [card] [Embedded widgets](/docs/integrations/organization-widgets) > > Drop Nevermined checkout, card enrollment, and delegation flows into your own site as signed iframes. Best when the customer completes payment themselves, inside your product. ## Related > [card] [Customers](/docs/solutions/organizations/customers) > > Every onboarded customer lands here — spend, purchase history, and CSV export. > [card] [Organization widgets](/docs/integrations/organization-widgets) > > The embedded, UI-driven counterpart to programmatic onboarding. > [card] [Purchase & pay an agent](/docs/getting-started/ai-agent-purchase) > > What the customer credential does next: order a plan and pay over x402. > [card] [Activity & Events](/docs/solutions/organizations/activity-and-events) > > Get notified the moment a customer is onboarded or makes a purchase. # Workspaces & Members Source: https://nevermined.ai/docs/solutions/organizations/workspaces-and-members Create an organization, switch between workspaces, and invite your team as Admins or Members. Agents, plans, and API keys are owned by the organization. An organization is a **workspace**: a shared container for agents, plans, API keys, billing, and customers. You can belong to several organizations and switch between them — plus your own Personal account — without logging out. Everything you publish lands in whichever workspace is active. ## Workspaces Every account has a **Personal** workspace by default. Organizations are additional workspaces you create or get invited into. The **workspace switcher** in the bottom-left of the sidebar lists your Personal account and every organization you're an active member of; selecting one makes it the active context for the whole app. When an organization is active: * New agents, plans, and API keys are owned by that organization, not by you personally. * The sidebar shows the organization dashboard (Details, Members, Billing, and the rest). * Caps and features follow the organization's tier, not your Personal limits. > [!NOTE] > > Workspaces are environment-specific. The organization you see on **sandbox** and the one on **live** are billed and managed separately — switch environments from the header dropdown. ## Create an organization **1. Open the workspace switcher** In the [Nevermined App](https://nevermined.app), click the workspace switcher in the bottom-left of the sidebar and choose **Create organization**. **2. Pick a tier** Organizations are paid workspaces. Choose **Premium** or **Enterprise** on the upgrade screen — see [Plans & Billing](/docs/solutions/organizations/plans-and-billing) for what each tier includes. **3. Complete checkout** Pay with the embedded Stripe form. Your organization is created and becomes your active workspace as soon as the subscription is confirmed. **4. Invite your team** Head to the **Members** tab and invite teammates (see below). They register agents and create plans into the shared workspace automatically. ## Members and roles Members are the people who share an organization. Every member has one of two roles: > [card] Admin > > Full control: invite and manage members, configure billing, set branding, manage widgets and webhooks, plus everything a Member can do. > [card] Member > > Builds in the shared workspace: register agents, create plans, and view the organization's pages. Cannot manage members or billing. How many members you can have depends on your tier — **5** on Premium and **unlimited** on Enterprise. Personal accounts can't have members; that's what upgrading to an organization unlocks. ### Invite a member From the **Members** tab, an Admin clicks **Send invitation** and provides: * **Name** and **Email** of the invitee. * **Role** — Admin or Member. The invitee receives a magic-link email. When they accept, they sign in (or create an account) with that email and become an active member. Pending invitations appear in the Members tab with a status of **Pending**, **Accepted**, **Revoked**, or **Expired**, and you can **resend** or **revoke** any that are still pending. > [!NOTE] > > The email on the accepting account must match the email the invitation was sent to — invitations can't be transferred to a different address. ### Manage members Admins manage existing members from the actions menu on each row: | Action | Effect | | - | - | | **Change role** | Promote a Member to Admin, or demote an Admin to Member. | | **Deactivate** | Suspend a member's access while keeping them in the list. They can be reactivated later. | | **Reactivate** | Restore a previously deactivated member. | | **Remove** | Permanently remove the member from the organization. | > [!WARNING] > > An organization must always keep at least one active Admin. You can't deactivate, demote, or remove the last remaining Admin — promote someone else first. ## Which workspace owns what When you act through the API or SDKs, Nevermined resolves the active workspace for each request in priority order — the first match wins: **1. Explicit organization in the route** A request to an org-scoped path (for example `/organizations/{orgId}/...`) targets that organization directly. **2. Workspace pin (header)** The SDK's workspace selection, sent as the `X-Current-Org-Id` header. The backend verifies you're an active member before honoring it. **3. API key scope** If your Nevermined API key was minted for a specific organization, that scope applies. **4. Most-recent membership** A fallback to your most recently active membership, preserving behavior for single-org callers. **5. Personal account** With no active membership, what you publish is owned by your Personal account. To pin a workspace from your own code — or drive your own workspace picker — see the [SDK & Workspaces guide](/docs/integrate/patterns/organizations). ## Related > [card] [Plans & Billing](/docs/solutions/organizations/plans-and-billing) > > Choose a tier and understand member seat limits. > [card] [SDK & Workspaces](/docs/integrate/patterns/organizations) > > List your memberships and target a workspace programmatically. # Technical Specifications Source: https://nevermined.ai/docs/specs/introduction Formal specifications for Nevermined protocol, extensions, and integration standards This section contains the **technical specifications** that define how Nevermined protocol and extensions work. These documents are intended for developers building integrations, protocol implementers, and anyone who needs to understand the precise behavior of Nevermined systems. ## Purpose Specifications in this section: * **Define normative behavior** using precise, unambiguous language * **Follow RFC 2119 conventions** for requirement levels (MUST, SHOULD, MAY) * **Include data structures** with exact field definitions and types * **Document protocol flows** with sequence diagrams and state transitions * **Specify error handling** and edge cases ## Audience These specifications are written for: * **Protocol implementers** building x402 facilitators or clients * **SDK developers** creating libraries that interact with Nevermined * **Integration engineers** connecting existing systems to Nevermined * **Security auditors** reviewing protocol designs ## Relationship to Other Documentation | Documentation Type | Purpose | | - | - | | **Getting Started** | Quickstart guides and tutorials | | **Use Cases** | Business scenarios and solution patterns | | **Integration Guides** | Step-by-step implementation instructions | | **API Reference** | SDK methods and REST endpoints | | **Specifications** | Formal protocol definitions (this section) | Specifications are the **source of truth** for protocol behavior. Other documentation may simplify or summarize, but specifications define what implementations MUST do. ## Conventions ### Requirement Levels This documentation uses RFC 2119 terminology: * **MUST** / **REQUIRED** / **SHALL** — absolute requirement * **MUST NOT** / **SHALL NOT** — absolute prohibition * **SHOULD** / **RECOMMENDED** — there may be valid reasons to ignore, but implications must be understood * **SHOULD NOT** / **NOT RECOMMENDED** — there may be valid reasons to do this, but implications must be understood * **MAY** / **OPTIONAL** — truly optional behavior ### Data Types * JSON structures use TypeScript-style type annotations * Hexadecimal values are prefixed with `0x` * Base64 encoding uses standard alphabet with `=` padding * Timestamps use ISO 8601 format unless otherwise specified ## Available Specifications > [card] [x402 Smart Accounts Extension](/docs/specs/x402-smart-accounts) > > Extends x402 with ERC-4337 smart accounts, session keys, and programmable smart contract settlement > [card] [x402 Card Delegation Extension](/docs/specs/x402-card-delegation) > > Extends x402 with credit/debit card delegation via Stripe for fiat-based payment settlement ## Contributing Specifications evolve based on implementation experience and community feedback. If you identify ambiguities, errors, or improvements, please open an issue in the [Nevermined GitHub repository](https://github.com/nevermined-io). # x402 Delegation Extension Source: https://nevermined.ai/docs/specs/x402-card-delegation Specification for extending x402 with delegated payment permissions for crypto (ERC-4337) and fiat (Stripe, Braintree) settlement ## Abstract This specification defines a **delegation extension** to the [x402 protocol](https://x402.org/) that enables payment settlement through on-chain credit burns with delegated spending permissions. The delegation model is shared between crypto and fiat payment providers: * **Crypto delegations** (`provider: 'erc4337'`): Use ERC-4337 smart accounts and session keys for on-chain settlement, with crypto-funded ordering when the subscriber's balance is insufficient. * **Fiat delegations** (`provider: 'stripe' | 'braintree' | 'visa'`): Use the configured Payment Service Provider (Stripe PaymentIntents, Braintree sales, or — for Visa Agentic Tokens — Stripe Connect against the seller's connected account) backed by pre-authorized card delegations for automatic card-funded credit top-ups when the subscriber's balance is insufficient. All providers use the same `DelegationConfig` interface with `spendingLimitCents` and `durationSecs` to control delegation scope. The PSP is selected per plan via the seller's `fiatPaymentProvider` metadata. Visa adds a per-delegation device-binding step (`consumerPrompt` + `assuranceData`) imposed by the Visa Trusted Agent Protocol. The fiat scheme identifier is: `nvm:card-delegation` The extension is designed to be **fully compatible** with existing x402 clients and servers, requiring only the addition of the delegation extension payload. ``` Version: 0.1 Status: Draft Last Updated: February 2026 ``` ## 1. Introduction ### 1.1 Background The x402 protocol standardizes HTTP-native payments where: 1. A client requests a protected resource 2. The server responds with HTTP 402 and payment requirements 3. The client builds and signs a payment authorization 4. The client retries the request with the payment payload 5. A facilitator verifies and settles the payment Standard x402 implementations use EIP-3009 signatures to authorize ERC-20 token transfers, and the smart accounts extension uses ERC-4337 UserOperations for programmable on-chain settlement. Both approaches require clients to hold cryptocurrency and interact with blockchain infrastructure. ### 1.2 Motivation Many real-world payment scenarios involve users and organizations that prefer or require traditional payment methods: * **Enterprise adoption** --- organizations with existing credit card infrastructure should not need crypto wallets to consume AI services * **Regulatory compliance** --- some jurisdictions require fiat-denominated billing and traditional payment rails * **User experience** --- end users are familiar with credit card payments and may not want to manage blockchain wallets * **Budgetary controls** --- organizations need spending limits, approval workflows, and reconciliation against traditional accounting systems * **Instant onboarding** --- new users can start consuming services immediately with an existing payment card, without acquiring tokens This extension enables these use cases by funding on-chain credit purchases through a Payment Service Provider (PSP) — currently Stripe or Braintree — authorized through pre-established delegations managed by the facilitator. Settlement itself uses the same on-chain credit burn mechanism as the smart accounts extension. The delegation model (`DelegationConfig`) is shared across all providers, giving the SDK and middleware a single interface for creating and managing payment permissions regardless of which PSP settles the charge. ### 1.3 Design Goals This extension: * **MUST** be compatible with the existing x402 HTTP handshake * **MUST** use the standard x402 payload structure with an extension field * **MUST** support spending limits and transaction caps per delegation * **SHOULD** leverage the PSP's off-session payment capabilities for seamless settlement * **SHOULD** support multi-party settlement so funds reach merchant-owned accounts (Stripe Connect, Braintree OAuth Connect) * **MUST** ensure PCI compliance by never exposing raw card data to the facilitator or server * **MUST** allow facilitators to verify and settle payments on behalf of clients ## 2. Terminology The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119). ### 2.1 Roles | Role | Description | | - | - | | **Client** | The entity requesting access to a protected resource. Authenticates via JWT tokens issued by the facilitator. | | **Server** | The entity providing the protected resource (API, agent, service). Coordinates with the facilitator. | | **Facilitator** | A third-party service that verifies delegations, manages spending limits, and executes PSP charges (Stripe PaymentIntents, Braintree sales) on behalf of clients. | | **Payment Provider** | The payment processor (Stripe, Braintree, or Visa Trusted Agent Protocol) that handles card authorization, capture, and fund transfer. The active provider for a given plan is selected via the plan's `fiatPaymentProvider` metadata. For Visa, VGS issues the Agentic Token and Stripe Connect settles the charge. | ### 2.2 Definitions | Term | Definition | | - | - | | **Delegation** | A pre-authorized permission granting the facilitator the ability to execute payment operations on behalf of a client, within defined spending limits and time constraints. Delegations use the unified `DelegationConfig` interface for crypto (`erc4337`) and fiat (`stripe`, `braintree`, `visa`) providers. | | **Visa Agentic Token** | A long-lived CMP-issued identifier (`vat_…`) that replaces a real PAN. Bound to Nevermined as the token requestor. Used as the `providerPaymentMethodId` for `provider: 'visa'` delegations. | | **Device Binding** | A per-delegation WebAuthn/passkey ceremony embedded by Visa VTS that produces a single-use `assuranceData` blob bound to the delegation's spending limit, duration, and merchant context. Required by the Visa Trusted Agent Protocol. Browser-only. | | **Consumer Prompt** | Human-readable approval text shown during Visa device binding. Forwarded verbatim to VGS `POST /intents`. Limited to 500 characters. | | **SetupIntent** | A Stripe object used to collect and confirm a customer's payment method for future off-session charges, without immediately charging the card. | | **PaymentIntent** | A Stripe object representing the intent to collect a payment. Used during settlement to charge the delegated card. | | **Payment Method Token** | A permanent Braintree handle that identifies a card vaulted before enrollment moved to VGS; no new card gets one. Used at settlement time as the equivalent of Stripe's `pm_...` ID. | | **Off-session payment** | A PSP-side payment executed without the cardholder being actively present, using a previously saved payment method. | | **Connected Account** | A merchant-owned PSP account (Stripe Connected Account or Braintree OAuth-connected merchant) that receives funds from settlements. | | **Spending Limit** | The maximum amount (in cents) that can be charged against a delegation over its lifetime. | | **VGS (Very Good Security)** | A PCI-compliant proxy service used to tokenize and vault sensitive card data before it reaches the facilitator. Used for card enrollment on both the Stripe and Braintree paths. | ## 3. Extension Structure ### 3.1 Scheme Identifier The scheme identifier is: `nvm:card-delegation` ### 3.2 Payload Schema #### PaymentRequired Response (402) When a server requires payment via card delegation, it returns: ```json theme={null} { "x402Version": 2, "error": "Payment required to access resource", "resource": { "url": "/api/v1/agents/80918427023170428029540261117198154464497879145267720259488529685089104529015/tasks", "description": "AI agent task execution", "mimeType": "application/json" }, "accepts": [{ "scheme": "nvm:card-delegation", "network": "stripe", // or "braintree" or "visa" "planId": "plan_abc123", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015", "httpVerb": "POST" } }], "extensions": {} } ``` #### PaymentPayload (Client Response) The client responds with a PaymentPayload containing a JWT token that encodes the delegation authorization: ```json theme={null} { "x402Version": 2, "resource": { "url": "/api/v1/agents/80918427023170428029540261117198154464497879145267720259488529685089104529015/tasks", "description": "AI agent task execution", "mimeType": "application/json" }, "accepted": { "scheme": "nvm:card-delegation", "network": "stripe", // or "braintree" or "visa" "planId": "plan_abc123", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015", "httpVerb": "POST" } }, "payload": { "token": "eyJhbGciOiJSUzI1NiIs...", "authorization": { "from": "0xD4f58B60330bC59cB0A07eE6A1A66ad64244eC8c", "sessionKeys": [{ "id": "redeem", "data": "0xabc123..." }] } }, "extensions": {} } ``` ### 3.3 Field Definitions #### PaymentRequired Root Fields | Field | Type | Required | Description | | - | - | - | - | | `x402Version` | `number` | Yes | Protocol version. MUST be `2`. | | `error` | `string` | Yes | Human-readable error message. | | `resource` | `object` | Yes | Protected resource information. | | `accepts` | `array` | Yes | Array of accepted payment schemes. | | `extensions` | `object` | Yes | Empty object `{}` for x402 spec alignment. | #### Resource Fields | Field | Type | Required | Description | | - | - | - | - | | `url` | `string` | Yes | The protected resource URL. | | `description` | `string` | No | Human-readable description. | | `mimeType` | `string` | No | Expected response MIME type (e.g., `"application/json"`). | #### Scheme Fields (in `accepts[]` / `accepted`) | Field | Type | Required | Description | | - | - | - | - | | `scheme` | `string` | Yes | Payment scheme. MUST be `"nvm:card-delegation"`. | | `network` | `string` | Yes | Payment network identifier. MUST be `"stripe"`, `"braintree"`, or `"visa"`, matching the plan's `fiatPaymentProvider` metadata (or `"visa"` when the delegation being consumed was issued via the Visa Trusted Agent Protocol). The SDK auto-resolves this from plan metadata and the delegation record; clients may also supply it explicitly. | | `planId` | `string` | No | Plan identifier associated with this delegation. | | `extra` | `object` | Yes | Additional scheme-specific fields. | #### Extra Fields | Field | Type | Required | Description | | - | - | - | - | | `version` | `string` | Yes | Scheme version (e.g., `"1"`). | | `agentId` | `string` | No | Agent identifier (if resource has multiple agents). | | `httpVerb` | `string` | No | HTTP method for the endpoint. | #### PaymentPayload Fields | Field | Type | Required | Description | | - | - | - | - | | `x402Version` | `number` | Yes | Protocol version. MUST be `2`. | | `resource` | `object` | No | Echoed from PaymentRequired. | | `accepted` | `object` | Yes | Selected scheme from `accepts[]`. | | `payload` | `object` | Yes | Scheme-specific authorization data. | | `extensions` | `object` | Yes | Empty object `{}` for x402 spec alignment. | #### Payload Fields | Field | Type | Required | Description | | - | - | - | - | | `token` | `string` | Yes | JWT token encoding the card delegation authorization. See JWT Claims below. | | `authorization` | `object` | No | On-chain authorization for credit burns. Contains subscriber address and session keys. | | `authorization.from` | `string` | Yes (if authorization present) | Subscriber's blockchain address (smart account). | | `authorization.sessionKeys` | `array` | Yes (if authorization present) | Array of session key references for on-chain operations. | | `authorization.sessionKeys[].id` | `string` | Yes | Session key identifier. Must be `"redeem"` for burn session keys. | | `authorization.sessionKeys[].data` | `string` | Yes | Keccak-256 hash of the serialized session key. | #### JWT Claims The `token` field contains a signed JWT with the following claims: | Claim | Type | Required | Description | | - | - | - | - | | `iss` | `string` | Yes | Token issuer. MUST be the facilitator URL (e.g., `"https://api.nevermined.app"`). | | `sub` | `string` | Yes | Subject identifier. The userId of the client who created the delegation. | | `aud` | `string` | Yes | Audience. MUST be `"nvm:card-delegation"`. | | `jti` | `string` | Yes | JWT ID. The delegationId (UUID) that uniquely identifies this delegation. | | `iat` | `number` | Yes | Issued-at timestamp (Unix epoch seconds). | | `exp` | `number` | Yes | Expiration timestamp (Unix epoch seconds). | | `nvm.delegationId` | `string` | Yes | Unique delegation identifier (UUID). MUST match the `jti` claim. | | `nvm.provider` | `string` | Yes | Payment provider identifier. MUST be `"stripe"`, `"braintree"`, `"visa"`, or `"erc4337"`. | | `nvm.providerCustomerId` | `string` | Yes | PSP-side customer identifier. For Stripe, the Customer ID (e.g., `"cus_PaBcDeFgHiJk"`). For Braintree, the customer ID derived from the buyer's userId. For Visa, the CMP cardholder identifier. | | `nvm.providerPaymentMethodId` | `string` | Yes | PSP-side payment method handle for the enrolled card. For Stripe, the PaymentMethod ID (e.g., `"pm_1AbCdEfGhIjKlM"`). For Braintree, the `paymentMethodToken` of a card vaulted before enrollment moved to VGS. For Visa, the Agentic Token (e.g., `"vat_01HXYZABCDEF"`). | | `nvm.vgsIntentId` | `string` | No | Visa-only: identifier of the VGS `POST /intents` mandate provisioned at delegation create time. Required for settlement to call `enroll-cryptogram` against the right intent. | | `nvm.spendingLimitCents` | `number` | Yes | Maximum amount in cents that can be charged over the delegation lifetime. | | `nvm.currency` | `string` | Yes | ISO 4217 currency code (e.g., `"usd"`, `"eur"`). | | `nvm.planId` | `string` | No | Plan identifier associated with this delegation. | | `nvm.maxTransactions` | `number` | No | Maximum number of individual transactions allowed under this delegation. | > [!NOTE] > > The `nvm` claims are namespaced under a single `nvm` object within the JWT payload to avoid collisions with standard JWT claims. The `jti` and `nvm.delegationId` MUST contain the same value for consistency. ### 3.4 Visa Extensions For `provider: 'visa'` delegations, the Visa Trusted Agent Protocol imposes two additional inputs on the create-delegation request (NOT carried in the resulting JWT): | Field | Type | Required | Description | | - | - | - | - | | `consumerPrompt` | `string` | Yes | Human-readable approval text shown during device binding (≤ 500 characters). Forwarded verbatim to VGS `POST /intents` and rendered in the cardholder's VTS-embedded approval iframe. | | `assuranceData` | `unknown` (typically an array) | Yes | Opaque payload produced by the VGS Agentic Auth browser SDK after the WebAuthn/passkey ceremony completes. Treated as opaque end-to-end and forwarded as-is to VGS. Size capped at 64 KiB at the DTO layer. | | `planId` | `string` | Yes | Visa delegations MUST bind to a single plan seller (`BCK.VISA.0015`). | The facilitator MUST reject `provider: 'visa'` requests that are missing either `consumerPrompt` or `assuranceData` with `BCK.VISA.0014` (HTTP 400). The facilitator MUST also reject Visa delegations whose plan seller has not completed Stripe Connect onboarding with `BCK.VISA.0016`, because Visa settlements route through Stripe Connect. > [!WARNING] > > `assuranceData` is **cryptographically single-use** and bound to the spending limit, duration, and merchant context shown to the cardholder. Replaying or recombining it across delegations produces an upstream Visa rejection (surfaced as `BCK.VISA.0003`). The Nevermined SDK therefore cannot create Visa delegations programmatically — both inputs require the in-browser ceremony, which has no headless equivalent. ## 4. Protocol Flow ### 4.1 Overview The protocol flow extends standard x402 with a card enrollment phase and replaces on-chain settlement with an external Payment Service Provider (PSP). Stripe, Braintree, and Visa (Trusted Agent Protocol) are all supported; the active PSP is selected per plan via the seller's `fiatPaymentProvider` metadata, and the design allows for additional providers to be added in the future. Visa adds a per-delegation device-binding step ahead of Phase 1, embedded in the cardholder's browser via Visa VTS. ```mermaid theme={null} --- title: Nevermined + x402 - Card Delegation Flow --- sequenceDiagram autonumber %% ACTORS actor client as Client participant facilitator as Facilitator (Nevermined API) participant vgs as VGS Proxy participant psp as PSP (Stripe, Braintree, ..) participant server as Server (AI Agent) %% PHASE 0: CARD ENROLLMENT rect rgb(240, 248, 255) note over client,psp: Phase 0: Card Enrollment client->>facilitator: POST /payments/card/setup facilitator->>psp: Create SetupIntent psp-->>facilitator: SetupIntent (client_secret) facilitator-->>client: SetupIntent client_secret note over vgs: PI captured by VGS Collect directly (PCI Compliant) client->>vgs: Submit card details (using VGS Collect) vgs->>psp: Confirm SetupIntent with tokenized card psp-->>vgs: SetupIntent confirmed (PaymentMethod) vgs-->>client: Confirmation client->>facilitator: POST /payments/card/enroll (SetupIntent ID) facilitator->>psp: Retrieve PaymentMethod psp-->>facilitator: PaymentMethod details facilitator->>facilitator: Store customer + payment method mapping facilitator-->>client: Enrollment confirmed end %% PHASE 1: DELEGATION CREATION (create-first) rect rgb(255, 248, 240) note over client,facilitator: Phase 1: Delegation Creation (create-first) client->>facilitator: POST /delegation/create
provider, currency, spendingLimitCents, durationSecs facilitator->>facilitator: Validate customer + payment method
Create delegation record (Active) facilitator-->>client: delegationId client->>facilitator: POST /x402/permissions
scheme: nvm:card-delegation
delegationConfig: { delegationId } facilitator->>facilitator: Validate delegation + sign JWT token facilitator-->>client: Base64-encoded PaymentPayload (x402 access token) end %% PHASE 2: VERIFICATION rect rgb(240, 255, 240) note over client,server: Phase 2: Verification client->>server: GET /api server->>client: HTTP 402 + PAYMENT-REQUIRED header client->>server: Request + PAYMENT-SIGNATURE header (base64-encoded x402 token) activate server server->>facilitator: /verify (paymentRequired + paymentPayload) facilitator->>facilitator: Verify JWT signature facilitator->>facilitator: Check delegation status (Active) facilitator->>facilitator: Check expiry (exp > now) facilitator->>facilitator: Check spending limit (spent + amount <= limit) facilitator->>facilitator: Check transaction count (if maxTransactions set) alt verification failed facilitator-->>server: ERROR: Verification failed server-->>client: HTTP 402 + PAYMENT-REQUIRED header else verification passed facilitator-->>server: OK: Verification passed end end %% PHASE 3: SETTLEMENT rect rgb(255, 240, 255) note over server,psp: Phase 3: Settlement (Credit-Based) server->>server: Execute work (AI task, etc.) server->>facilitator: /settle (paymentRequired + paymentPayload + maxAmount) activate facilitator facilitator->>facilitator: Resolve subscriber address facilitator->>facilitator: Check on-chain credit balance alt Insufficient credits facilitator->>psp: Create PaymentIntent (plan price) alt PSP failure psp-->>facilitator: Payment failed facilitator-->>server: Settlement failed server-->>client: HTTP 402 + PAYMENT-REQUIRED header else PSP success psp-->>facilitator: PaymentIntent succeeded facilitator->>facilitator: Mint credits on-chain end end facilitator->>facilitator: Burn credits on-chain (session key) facilitator-->>server: Settlement OK (txHash, creditsRedeemed) deactivate facilitator server-->>client: Response + PAYMENT-RESPONSE header deactivate server end ``` ### 4.2 Step-by-Step Flow The following steps detail the complete payment and execution flow. Steps are grouped into four phases: **Card Enrollment**, **Delegation Creation**, **Verification**, and **Settlement**. *** #### Phase 0: Card Enrollment (Steps 1-10) Card enrollment is a one-time process that securely saves a client's payment method for future use. **Step 1.** Client requests a SetupIntent from the facilitator. ```http theme={null} POST /payments/card/setup HTTP/1.1 Host: facilitator.example.com Authorization: Bearer ``` **Step 2.** Facilitator creates a SetupIntent and returns the `client_secret` to the client. **Step 3.** Client submits card details through a VGS (Very Good Security) proxy. The VGS proxy tokenizes the card data before it reaches any Nevermined infrastructure, ensuring PCI compliance. **Step 4.** VGS forwards the tokenized card data to the PSP to confirm the SetupIntent. **Step 5.** PSP confirms the SetupIntent and attaches the PaymentMethod. **Step 6.** Client notifies the facilitator that enrollment is complete. ```http theme={null} POST /payments/card/enroll HTTP/1.1 Host: facilitator.example.com Authorization: Bearer Content-Type: application/json { "setupIntentId": "seti_1AbCdEfGhIjKlM" } ``` **Step 7.** Facilitator retrieves the confirmed PaymentMethod from the PSP and stores the customer-to-payment-method mapping. **Step 8.** Facilitator confirms enrollment to the client. > [!NOTE] > > Card enrollment only needs to happen once per payment method. A single enrolled card can back multiple delegations with different spending limits and expiry times. *** #### Phase 1: Delegation Creation (Steps 9-12) **Step 9.** Client creates a delegation using the `createDelegation` API, specifying the `provider` (required: `'stripe'`, `'braintree'`, `'visa'`, or `'erc4337'`), spending limits, and optional constraints. The `DelegationConfig` interface is shared across all providers. For Visa, the request MUST additionally include `consumerPrompt`, `assuranceData`, and `planId` (see Section 3.4); both extras are produced by the in-browser Visa VTS device-binding ceremony immediately before this request. The supported flow is **create-first**: create the delegation with `createDelegation`, then request the access token by passing only its `delegationId` (shown below). Inline create-on-the-fly (passing creation fields in `delegationConfig` to `getX402AccessToken` instead of a `delegationId`) is **deprecated** and emits a runtime deprecation warning; it remains reachable for backward compatibility but should not be used in new integrations. `provider` and `currency` are required on `createDelegation` (no silent default); a delegation is plan-agnostic unless `planId` is supplied (Visa always requires `planId`). **Using the `createDelegation` API directly:** ```http theme={null} POST /api/v1/delegation/create HTTP/1.1 Host: facilitator.example.com Authorization: Bearer Content-Type: application/json { "provider": "stripe", "spendingLimitCents": 10000, "durationSecs": 2592000, "providerPaymentMethodId": "pm_1AbCdEfGhIjKlM", "currency": "usd", "maxTransactions": 100 } ``` For Braintree-priced plans, a card vaulted before enrollment moved to VGS uses the same payload with `provider: "braintree"` and its `paymentMethodToken` as `providerPaymentMethodId`. The seller's per-currency Braintree merchant account is resolved by the facilitator, not supplied by the client: ```json theme={null} { "provider": "braintree", "spendingLimitCents": 10000, "durationSecs": 2592000, "providerPaymentMethodId": "abc123token", "currency": "usd", "maxTransactions": 100 } ``` For Visa Trusted Agent Protocol plans, the same payload uses `provider: "visa"`, the Visa Agentic Token (`vat_…`) as `providerPaymentMethodId`, a mandatory `planId`, and the two device-binding extras produced by the browser ceremony: ```json theme={null} { "provider": "visa", "spendingLimitCents": 5000, "durationSecs": 86400, "providerPaymentMethodId": "vat_01HXYZABCDEF", "currency": "usd", "maxTransactions": 5, "planId": "80918427023170428029540261117198154464497879145267720259488529685089104529015", "consumerPrompt": "Allow up to USD 50.00 over 5 transactions at example.com", "assuranceData": [ { "methodResults": { "id": "…" }, "verificationType": "DEVICE" } ] } ``` **Requesting the token by `delegationId` (the supported create-first form):** ```http theme={null} POST /x402/permissions HTTP/1.1 Host: facilitator.example.com Authorization: Bearer Content-Type: application/json { "resource": { "url": "/api/v1/agents/80918427023170428029540261117198154464497879145267720259488529685089104529015/tasks", "description": "AI agent task execution", "mimeType": "application/json" }, "accepted": { "scheme": "nvm:card-delegation", "network": "stripe", // or "braintree" or "visa" "planId": "plan_abc123", "extra": { "version": "1" } }, "delegationConfig": { "delegationId": "deleg-8f14e45f-ce34-4797-b88e-968374b0d4b6" } } ``` For `provider: 'visa'`, only the `delegationId` form is reachable from non-browser callers — the inline `delegationConfig` shortcut would need the browser-only device-binding inputs. **Step 10.** Facilitator validates the client's enrolled payment method and creates a delegation record with status `Active`. For `provider: 'visa'`, the facilitator additionally calls VGS `POST /intents` with the forwarded `consumerPrompt` + `assuranceData` to provision the upstream Visa mandate, persisting the returned intent id on the delegation as `vgsIntentId`. If VGS rejects the intent, the delegation is not created and the caller receives `BCK.VISA.0003`. **Step 11.** Facilitator signs a JWT token containing the delegation claims (see Section 3.3) and wraps it in a standard x402 PaymentPayload structure. The `resource` and `accepted` fields echo back the values from the client's request: ```json theme={null} { "x402Version": 2, "resource": { "url": "/api/v1/agents/80918427023170428029540261117198154464497879145267720259488529685089104529015/tasks", "description": "AI agent task execution", "mimeType": "application/json" }, "accepted": { "scheme": "nvm:card-delegation", "network": "stripe", // or "braintree" or "visa" "planId": "plan_abc123", "extra": { "version": "1" } }, "payload": { "token": "" }, "extensions": {} } ``` **Step 12.** Facilitator base64-encodes the PaymentPayload and returns it to the client. This token is what the client will include in the `PAYMENT-SIGNATURE` header when accessing protected resources. ```json theme={null} { "accessToken": "eyJ4NDAyVmVyc2lvbiI6Mi...", "permissionHash": "0x1a2b3c..." } ``` *** #### Phase 2: Verification (Steps 13-22) **Step 13.** Client initiates an HTTP request to a Server (AI Agent). ```http theme={null} GET /api/resource HTTP/1.1 Host: agent.example.com ``` **Step 14.** Server validates whether the request contains a valid payment in the `PAYMENT-SIGNATURE` header. **Step 15.** If payment is absent, Server responds with `HTTP 402 Payment Required` status and the `PaymentRequired` object in the `PAYMENT-REQUIRED` header (base64-encoded). ```http theme={null} HTTP/1.1 402 Payment Required PAYMENT-REQUIRED: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkLi4u ``` **Step 16.** The Client selects the `nvm:card-delegation` scheme from `accepts[]` and uses the base64-encoded PaymentPayload (received in Step 12) as the x402 access token. **Step 17.** Client sends an HTTP request to the server including the base64-encoded PaymentPayload in the `PAYMENT-SIGNATURE` HTTP header. ```http theme={null} GET /api/resource HTTP/1.1 Host: agent.example.com PAYMENT-SIGNATURE: ``` **Step 18.** Server validates the incoming data and forwards the payment data to the facilitator for verification. ```http theme={null} POST /verify HTTP/1.1 Host: facilitator.example.com Content-Type: application/json { "paymentRequired": { ... }, "x402AccessToken": "", "maxAmount": "500" } ``` **Step 19.** Facilitator base64-decodes the PaymentPayload, extracts the JWT from the `payload.token` field, and performs the following verification checks: 1. **JWT signature verification** --- validates the JWT was signed by the facilitator's private key 2. **Delegation status check** --- confirms the delegation record exists and has status `Active` 3. **Expiry check** --- confirms `exp` claim is in the future 4. **Credit balance check** --- if `planId` is present, checks the subscriber's on-chain credit balance 5. **Session key validation** --- if `authorization` is present, validates the burn session key exists and is active **Step 20.** IF any verification check fails, the facilitator returns an error to the server. **Step 21.** IF all verification checks pass, the facilitator confirms verification to the server. **Step 22.** The Server, after obtaining the verification result from the Facilitator (and BEFORE executing any task), checks the verification result: * If the verification was INVALID, the Server returns to the client a `HTTP 402 PAYMENT-FAILED` response * If the verification was correct, the Server continues with the request execution > [!NOTE] > > The verification phase ensures that the delegation CAN be settled before the server performs any work. This protects the server from executing expensive operations without guaranteed payment. *** #### Phase 3: Settlement (Steps 23-32) **Step 23.** The Server executes the task to fulfill the client request (AI Task or any necessary work). **Step 24.** The Server calls the `/settle` endpoint of the Facilitator to settle the request. ```http theme={null} POST /settle HTTP/1.1 Host: facilitator.example.com Content-Type: application/json { "paymentRequired": { ... }, "x402AccessToken": "", "maxAmount": "500" } ``` The `maxAmount` specifies the number of **credits** to burn for this request (not cents). **Step 25.** Facilitator resolves the subscriber's blockchain address and loads the plan from the on-chain registry. **Step 26.** Facilitator checks the subscriber's on-chain credit balance for the plan. **Step 27.** IF balance is insufficient for the requested `maxAmount`: * Calculate plan price in cents from `plan.price.amounts` * Atomically increment the delegation's spend counter (card charge ceiling) * Create an off-session PSP PaymentIntent to charge the card for the plan price * On PSP failure: roll back spend counter, return settlement failure * On PSP success: mint credits to the subscriber's blockchain address * Wait for the credit balance to update on-chain **Step 28.** Facilitator burns the requested credits on-chain using the burn session key from the token's `authorization.sessionKeys`. **Step 29.** IF the credit burn fails, the facilitator returns a settlement failure. **Step 30.** Facilitator returns the settlement receipt to the server. **Step 31.** Server returns to the client the response with the payment confirmation in the `PAYMENT-RESPONSE` header (base64-encoded). ```http theme={null} HTTP/1.1 200 OK Content-Type: application/json PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJwYXltZW50SW50ZW50SWQiOi4uLg== { "result": "...", "payment": { "creditsRedeemed": 2, "remainingBalance": 98, "orderTx": "pi_1AbCdEfGhIjKlM" } } ``` **Decoded PAYMENT-RESPONSE** (a `credits` plan): ```json theme={null} { "success": true, "transaction": "0x1234567890abcdef...", "network": "stripe", "billingModel": "credits", "creditsRedeemed": "2", "remainingBalance": "98", "orderTx": "pi_1AbCdEfGhIjKlM" } ``` The `PAYMENT-RESPONSE` header contains x402-standard settlement fields. The `network` echoes the value used at verification (`stripe` or `braintree`). For Braintree, `orderTx` is the Braintree merchant transaction ID. Additional Nevermined-specific info (like `creditsRedeemed` and `remainingBalance`) can be included in the response body. The same successful settle on a **pay-as-you-go** plan reports `"0"` for both credit fields, because such a plan holds no credit balance — the charge is referenced by `orderTx`: ```json theme={null} { "success": true, "transaction": "pi_3U6tgrBYvSRKcV421ehH4bnX", "network": "stripe", "billingModel": "pay-as-you-go", "creditsRedeemed": "0", "remainingBalance": "0", "orderTx": "pi_3U6tgrBYvSRKcV421ehH4bnX" } ``` See [Was the buyer charged?](#66-was-the-buyer-charged) for the check that applies to each. > [!WARNING] > > Steps 27-28 represent a failure scenario where the server has already performed work but settlement failed. Implementations SHOULD have mechanisms to handle this edge case, such as retry logic or dispute resolution. ### 4.3 HTTP Header Summary Per [x402 HTTP Transport v2](https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md), payment data is transmitted via HTTP headers: | Header | Direction | Content | | - | - | - | | `PAYMENT-REQUIRED` | Server -> Client (402) | Base64-encoded `PaymentRequired` object | | `PAYMENT-SIGNATURE` | Client -> Server | Base64-encoded `PaymentPayload` object (consistent for both `nvm:card-delegation` and `nvm:erc4337` schemes) | | `PAYMENT-RESPONSE` | Server -> Client (200) | Base64-encoded settlement receipt | ## 5. Verification Requirements ### 5.1 JWT Verification The facilitator MUST verify the following aspects of the JWT token: | Check | Requirement | | - | - | | Signature | JWT MUST be signed by the facilitator's private key and verifiable with the corresponding public key | | Algorithm | JWT MUST use RS256 or ES256 signing algorithm | | Issuer | `iss` claim MUST match the facilitator's configured issuer URL | | Audience | `aud` claim MUST equal `"nvm:card-delegation"` | | Expiry | `exp` claim MUST be in the future | | Issued At | `iat` claim MUST be in the past | | JWT ID | `jti` claim MUST match an existing delegation record | ### 5.2 Delegation Status Verification The facilitator MUST verify: | Check | Requirement | | - | - | | Existence | A delegation record matching the `jti` / `nvm.delegationId` MUST exist | | Status | Delegation status MUST be `Active` | | Customer Match | `nvm.providerCustomerId` MUST match the delegation record | | Payment Method | `nvm.providerPaymentMethodId` MUST match a valid, active payment method | ### 5.3 Balance and Permission Checks The facilitator MUST verify: | Check | Requirement | | - | - | | Credit Balance | If a `planId` is present, the subscriber's on-chain credit balance SHOULD be checked (informational — settle auto-orders if needed) | | Session Key | If `authorization` is present, the burn session key hash MUST match an active `PermissionEntity` | | Delegation Active | The delegation MUST have status `Active` | > [!NOTE] > > Unlike the previous cents-based budget check, verification always returns valid for active delegations. The settle step handles insufficient credits by auto-ordering via card charge. The delegation's spending limit serves as a ceiling on total card charges, not a per-request budget. ## 6. Settlement Requirements ### 6.1 Execution Order When executing settlement, the facilitator MUST: 1. Decode the x402 token and verify the delegation JWT 2. Resolve the subscriber's blockchain address from their userId 3. Load the plan from the on-chain asset registry 4. Check the subscriber's on-chain credit balance 5. If balance is insufficient for `maxAmount`: a. Calculate plan price: `sum(plan.price.amounts)` (in cents) b. Atomically increment delegation spend counter c. Create off-session PSP PaymentIntent for the plan price d. On PSP failure: roll back spend counter, return error e. Mint credits to subscriber using the node account f. Wait for balance update on-chain 6. Burn credits on-chain using the burn session key 7. Return settlement receipt with `creditsRedeemed` and `remainingBalance` ### 6.2 Atomicity > [!WARNING] > > The spend counter MUST be incremented atomically BEFORE the PSP PaymentIntent is created. If the PSP charge fails, the spend counter MUST be rolled back. This prevents race conditions where concurrent requests could exceed spending limits. ### 6.3 Delegation Lifecycle Delegations transition through the following states: | Status | Description | | - | - | | `Active` | Delegation is valid and can be used for payments | | `Exhausted` | Spending limit or transaction count has been reached | | `Expired` | The `exp` timestamp has passed | | `Revoked` | The client or facilitator has explicitly revoked the delegation | The facilitator MUST update the delegation status to `Exhausted` when: * `spentCents >= nvm.spendingLimitCents` * Transaction count reaches `nvm.maxTransactions` (if set) ### 6.4 PSP Connect Routing The facilitator MUST route funds to the seller's account on the PSP that backs the plan. The destination MUST be resolved by the facilitator from the plan being paid for — for Stripe and Visa, the plan-owning organization, else the plan owner's connected account; for Braintree, the plan owner's connected gateway — and MUST NOT be accepted from the client. A request or delegation that names a settlement account has no effect on routing: * **Stripe**: route via Stripe Connect using the `transfer_data.destination` parameter on the PaymentIntent. The facilitator MAY apply platform fees via `application_fee_amount`. * **Braintree**: settlement is one sale for the whole price (`tokenizeNetworkToken`, then `chargeCreditCard`, over Braintree's GraphQL API), on the seller's OAuth-connected gateway, against the child `merchantAccountId` whose currency matches the plan. * **Visa**: the facilitator calls VGS `enroll-cryptogram` against the delegation's `vgsIntentId` to mint a single-use Visa cryptogram, then submits the cryptogram to Stripe Connect (`transfer_data.destination` set to the seller's Stripe Connect account) as the PaymentMethod. The facilitator MAY apply platform fees via `application_fee_amount`. Each settlement consumes one cryptogram — they are not reusable, even within the same delegation's spending limit. In all cases the facilitator selects a `merchantAccountId` whose currency matches `nvm.currency`. For Braintree this is enforced both at plan creation (sellers must have a child merchant account in the chosen currency) and at settlement time; a mismatch fails the charge with `BCK.BRAINTREE.0007`. For Stripe and Visa, the seller's Stripe Connect account is resolved from the plan's owning organization, else the plan owner's profile — if Connect onboarding is incomplete, Visa delegation creation fails with `BCK.VISA.0016` before settlement is ever attempted, and a Stripe or Visa settlement fails with `BCK.STRIPE.0022` / `BCK.STRIPE.0024` rather than paying the platform. ### 6.5 Receipt Format The facilitator MUST return a receipt. The `PAYMENT-RESPONSE` header contains x402-standard fields: | Field | Type | Description | | - | - | - | | `success` | `boolean` | Whether settlement succeeded. | | `network` | `string` | Payment network. MUST be `"stripe"`, `"braintree"`, or `"visa"` (matching the `accepted.network` from verification). | Additional settlement details MAY be included in the response body: | Field | Type | Description | | - | - | - | | `billingModel` | `string` | How the request was priced: `credits` or `pay-as-you-go`. Read this before the two credit fields. | | `creditsRedeemed` | `string` | Number of credits burned on-chain. Always `"0"` on `pay-as-you-go`, including on a successful charge. | | `remainingBalance` | `string` | Subscriber's remaining credit balance. Always `"0"` on `pay-as-you-go`. | | `orderTx` | `string` | PSP transaction ID. On `credits` plans, present only when auto top-up charged the card; on fiat `pay-as-you-go`, it references the per-request charge. | | `transaction` | `string` | Blockchain transaction hash of the credit burn. On crypto `pay-as-you-go` it is the charge reference instead. | ### 6.6 Was the buyer charged? `success` alone tells you the settle worked. What a consumer MUST check **in addition** depends on `billingModel`: | `billingModel` | Success criterion | Credit fields | | - | - | - | | `credits` | `success === true` and `creditsRedeemed > 0` | `creditsRedeemed` is the amount burned, `remainingBalance` what is left | | `pay-as-you-go` | `success === true` **and** a non-empty `orderTx` (fiat rails) / `transaction` (crypto rails) | always the string `"0"` — no balance exists on this plan shape | > [!NOTE] > > **No `billingModel` in the response?** The deployment predates the discriminator. Apply the > **credits** rule — a missing discriminator MUST NOT be read as pay-as-you-go. > [!WARNING] > > Do not gate on `creditsRedeemed` without reading `billingModel` first. A pay-as-you-go plan holds no credit balance, so `creditsRedeemed > 0` can never hold there and a real charge reads as a decline. On a card rail that invites a retry of a payment that already succeeded, and repeated attempts feed issuer fraud scoring. > > Note the type as well: both fields are **strings**, so `"0"` is truthy while `Number("0") > 0` is false — two plausible-looking checks disagree. ## 7. Error Handling ### 7.1 Error Codes Errors come from two distinct response paths. **Scheme-level codes** are returned in the facilitator's `verify` / `settle` JSON body and can apply to any provider. **Nevermined API codes** appear in the `code` field of a structured `NVMException` response from `POST /api/v1/delegation/create` or `POST /api/v1/delegation/enroll-visa` — never on the x402 verify/settle path. #### Scheme-level (`verify` / `settle`) | Code | Name | Description | | - | - | - | | `INVALID_PAYLOAD` | Invalid Payload | The payment payload structure is invalid or missing required fields | | `INVALID_TOKEN` | Invalid Token | The JWT token signature verification failed | | `EXPIRED_TOKEN` | Expired Token | The JWT token `exp` claim is in the past | | `DELEGATION_NOT_FOUND` | Delegation Not Found | No delegation record found for the given `jti` / `delegationId` | | `DELEGATION_INACTIVE` | Delegation Inactive | Delegation status is not `Active` (may be `Exhausted`, `Expired`, or `Revoked`) | | `BUDGET_EXCEEDED` | Budget Exceeded | **Deprecated.** The requested amount would exceed the delegation spending limit | | `INSUFFICIENT_BALANCE` | Insufficient Balance | Credit balance too low and card charge failed | | `MINT_FAILED` | Mint Failed | Credit minting failed after successful card charge | | `BURN_FAILED` | Burn Failed | On-chain credit burn failed | | `TRANSACTION_LIMIT_REACHED` | Transaction Limit Reached | The maximum number of transactions has been reached | | `PAYMENT_FAILED` | Payment Failed | PSP PaymentIntent creation or confirmation failed | | `CARD_DECLINED` | Card Declined | The card was declined by the issuing bank | | `CURRENCY_MISMATCH` | Currency Mismatch | The request currency does not match the delegation currency | | `MERCHANT_ACCOUNT_INVALID` | Merchant Account Invalid | The specified PSP Connected Account is invalid or inactive | > [!NOTE] > > **`delegationId` path parameter format.** The `GET /delegation/{delegationId}` (and its `/transactions` and `DELETE`) endpoints validate `{delegationId}` as a **v4 UUID**. A syntactically-valid but non-v4 value — e.g. the all-zero UUID `00000000-0000-0000-0000-000000000000` used to probe — returns `400` (`BCK.DELEGATION.0009`, a request-format error), **not** `401`/`404`. A genuinely unknown but well-formed v4 UUID is what returns the REST not-found (`404`, `BCK.DELEGATION.0002`) — distinct from the verify/settle scheme code `DELEGATION_NOT_FOUND` above. #### Nevermined API — Visa-specific Returned by `POST /api/v1/delegation/create` (with `provider: 'visa'`) and `POST /api/v1/delegation/enroll-visa`. See [API error codes](/docs/development-guide/api-errors/codes) for the full catalogue. | Code | Name | Description | | - | - | - | | `BCK.VISA.0003` | Visa Mandate Provisioning Failed | VGS rejected `POST /intents` (typically a stale or replayed `assuranceData`) | | `BCK.VISA.0014` | Visa Device Binding Required | `provider: 'visa'` request missing `consumerPrompt` and/or `assuranceData` | | `BCK.VISA.0015` | Visa Plan Binding Required | `provider: 'visa'` request missing `planId` | | `BCK.VISA.0016` | Visa Seller Not Onboarded | The plan seller has not completed Stripe Connect onboarding | | `BCK.VISA.0018` | Visa Card Already Enrolled | The PAN being enrolled is already a Visa Agentic Token under another account | ### 7.2 Error Response Format ```json theme={null} { "error": { "code": "BUDGET_EXCEEDED", "message": "Requested amount exceeds remaining delegation budget", "details": { "delegationId": "deleg-8f14e45f-ce34-4797-b88e-968374b0d4b6", "spendingLimitCents": 10000, "spentCents": 9800, "requestedAmountCents": 500 } } } ``` ## 8. Security Considerations ### 8.1 JWT Security * JWT tokens MUST be signed using asymmetric cryptography (RS256 or ES256) * The facilitator's signing private key MUST be stored in a secure key management system * JWT tokens SHOULD have limited validity periods (RECOMMENDED: 30 days maximum) * Replay protection is inherent through the atomic spend counter and transaction tracking ### 8.2 Spending Limits * Every delegation MUST have a finite spending limit (`nvm.spendingLimitCents`) * Spend counters MUST be incremented atomically to prevent race conditions * The facilitator MUST reject requests that would exceed the spending limit, even by a single cent ### 8.3 Atomic Operations * The spend counter increment and PSP PaymentIntent creation MUST be treated as a logical unit * If the PSP charge fails after the counter is incremented, the counter MUST be rolled back * Concurrent settlement requests for the same delegation MUST be serialized or use optimistic concurrency control ### 8.4 PCI Compliance * Raw card numbers (PAN), CVV, and expiry dates MUST NEVER be transmitted to or stored by the facilitator * Card enrollment MUST use a PCI-compliant proxy (VGS) that tokenizes card data before it reaches Nevermined infrastructure * Only PSP-issued tokens (Customer IDs, PaymentMethod IDs) are stored by the facilitator * The facilitator MUST maintain PCI DSS compliance for the handling of any cardholder data references ### 8.5 Delegation Revocation * Clients MUST be able to revoke delegations at any time * Revoked delegations MUST immediately fail verification * In-flight settlements at the time of revocation MAY complete if the PSP PaymentIntent has already been confirmed ### 8.6 Session Key Security * Burn session keys MUST be scoped to specific plan IDs and subscriber addresses * Session keys MUST have expiration times aligned with the delegation expiry * Session keys MUST be stored securely in the facilitator's database * The facilitator MUST validate that the session key referenced in the token matches an active permission record * Session key policies MUST limit the maximum burn amount per operation ## 9. Implementation Notes ### 9.1 Stripe Integration For Stripe-backed plans, this extension uses: | Feature | Purpose | | - | - | | SetupIntents | Securely save payment methods for future use | | PaymentIntents | Charge saved payment methods off-session | | Stripe Connect | Route payments to merchant connected accounts | | Off-session payments | Execute charges without cardholder presence | Implementations MUST use Stripe API version `2023-10-16` or later. ### 9.2 Braintree Integration For Braintree-backed plans, this extension uses: | Feature | Purpose | | - | - | | VGS-enrolled network token | The card is enrolled once through VGS Collect. Braintree receives its network token at charge time; the card is not vaulted on Braintree | | `tokenizeNetworkToken` + `chargeCreditCard` (GraphQL) | Charge the network token, with a fresh cryptogram, on the seller's gateway at settlement time | | OAuth Connect (Braintree Auth) | Onboard merchants and discover their per-currency child merchant accounts | | Per-currency merchant accounts | Route each charge to a `merchantAccountId` whose `currencyIsoCode` matches the plan currency | Sellers MUST have at least one child merchant account in the plan's currency on their Braintree account; the facilitator discovers the available currencies at OAuth time via `merchantAccount.all()` and persists the resulting `currency → merchantAccountId` map on the seller's profile. Plan creation in a currency the seller does not support is rejected up-front. ### 9.3 Visa Trusted Agent Protocol Integration For Visa-backed plans, this extension uses: | Feature | Purpose | | - | - | | VGS Credential Management Platform (CMP) | Mint Visa Agentic Tokens (`vat_…`) from PANs captured in VGS Collect iframes. Tokens are keyed on PAN globally and bound to Nevermined as the token requestor. | | VGS Agentic API | `POST /cards/{cardId}/agentic-tokens` enrolls a CMP card as an Agentic Token. `POST /intents` provisions a per-delegation mandate from `consumerPrompt` + `assuranceData`. `enroll-cryptogram` mints a single-use cryptogram at settlement time. | | Visa VTS device binding | Per-delegation WebAuthn/passkey ceremony (with email OTP fallback) embedded by VTS in an iframe. Produces single-use `assuranceData` bound to the spending limit, duration, and merchant context. | | Stripe Connect | Visa cryptograms settle as PaymentMethods on Stripe Connect against the seller's connected account. Required for every Visa plan seller. | Card enrolment and delegation creation for Visa are both **browser-only** because the FIDO/passkey ceremony has no headless equivalent. The SDK can list and consume an existing Visa delegation (by `delegationId`) but cannot create one. ### 9.4 PCI-Compliant Card Capture Card enrollment flows MUST tokenize card data in the browser before any data reaches Nevermined infrastructure: * **Stripe path**: card details are collected in a VGS (Very Good Security) Collect iframe and tokenized by VGS, which returns a card ID and provisions a network token. The facilitator only ever sees the card ID and the network token, never the PAN. * **Braintree path**: the same VGS Collect capture as the Stripe path, so one enrolled card can pay on either PSP. At settlement the facilitator sends Braintree the card's network token and a single-use cryptogram; raw card data never reaches Nevermined infrastructure. * **Visa path**: card details are collected in a VGS Collect iframe whose `form.createCard()` posts the tokenized card directly to CMP via VGS-internal routing. The browser receives a CMP `cardId`; the facilitator then enrolls that card as an Agentic Token. No PAN reaches Nevermined infrastructure on the enrolment path. All three paths satisfy the requirement that raw card numbers, CVVs, and expiry dates never transit the facilitator. ### 9.5 Connect / OAuth for Merchant Routing When merchants (server operators) have a connected PSP account, the facilitator routes settlement funds to that account: * **Stripe**: merchants complete Stripe Connect onboarding. Direct charges use `transfer_data.destination`; the facilitator MAY deduct a platform fee using `application_fee_amount`. The destination account is resolved by the facilitator from the plan-owning organization, else the plan owner's profile, at settlement time; it is not carried in the JWT. * **Braintree**: merchants complete OAuth Connect (Braintree Auth) authorization, granting the platform scoped access to their gateway. The facilitator builds a merchant-scoped `BraintreeGateway` per request and charges the whole price in one sale on the merchant's connected account, using a child `merchantAccountId` whose currency matches the plan. ### 9.6 Idempotency Implementations SHOULD pass an idempotency key when creating Stripe PaymentIntents (`idempotency_key`) or Braintree transactions (transaction-level idempotency) to prevent duplicate charges in case of network failures or retries. The idempotency key SHOULD be derived from the delegation ID and a request-specific nonce. ## 10. References * [x402 Protocol](https://x402.org/) * [Stripe PaymentIntents API](https://docs.stripe.com/api/payment_intents) * [Stripe SetupIntents API](https://docs.stripe.com/api/setup_intents) * [Stripe Connect](https://docs.stripe.com/connect) * [Stripe Off-session Payments](https://docs.stripe.com/payments/save-and-reuse) * [Braintree Vault](https://developer.paypal.com/braintree/docs/guides/payment-methods) * [Braintree OAuth Connect (Braintree Auth)](https://developer.paypal.com/braintree/docs/guides/extend/oauth/overview) * [VGS (Very Good Security)](https://www.verygoodsecurity.com/) * [VGS Credential Management Platform](https://www.verygoodsecurity.com/products/credential-management-platform) * [Visa Trusted Agent Protocol](https://developer.visa.com/capabilities/trusted-agent-protocol/docs) * [WebAuthn / FIDO2](https://www.w3.org/TR/webauthn-2/) * [RFC 7519: JSON Web Token (JWT)](https://www.rfc-editor.org/rfc/rfc7519) * [RFC 2119: Key words for use in RFCs](https://www.rfc-editor.org/rfc/rfc2119) # x402 Smart Accounts Extension Source: https://nevermined.ai/docs/specs/x402-smart-accounts Specification for extending x402 with ERC-4337 smart accounts, session keys, and programmable smart contract settlement ## Abstract This specification defines a **smart-account extension** to the [x402 protocol](https://x402.org/) that enables programmable payment settlement using ERC-4337 smart accounts and session keys. While standard x402 settles payments via EIP-3009 ERC-20 token transfers, this extension allows settlement through arbitrary smart contract interactions—enabling subscription plans, credit-based metering, time-based access, and other programmable payment models. The extension is designed to be **fully compatible** with existing x402 clients and servers, requiring only the addition of the `nvm:erc4337` extension payload. ``` Version: 0.3 Status: Draft Last Updated: January 2026 ``` ## 1. Introduction ### 1.1 Background The x402 protocol standardizes HTTP-native payments where: 1. A client requests a protected resource 2. The server responds with HTTP 402 and payment requirements 3. The client builds and signs a payment authorization 4. The client retries the request with the payment payload 5. A facilitator verifies and settles the payment Standard x402 implementations use EIP-3009 signatures to authorize ERC-20 token transfers. This works well for simple pay-per-request scenarios but cannot express more complex payment relationships. ### 1.2 Motivation Many real-world payment scenarios require more than direct token transfers: * **Subscription plans** — pay once, access many times * **Credit packages** — purchase credits in bulk, consume over time * **Time-based access** — pay for access windows (hourly, daily, monthly) * **Tiered pricing** — different rates based on usage volume * **Spending limits** — caps on how much can be spent per period This extension enables these use cases by replacing the EIP-3009 transfer authorization with ERC-4337 UserOperations that can execute arbitrary smart contract calls. Also, end-user scenarios where clients are not experienced with blockchain wallets can benefit of using smart accounts. Smart Accounts bring a superior user experience by enabling social logins, meta-transactions, and session keys that delegate limited permissions to facilitators. This extension allows clients to leverage smart accounts for payment settlement in x402 flows. Finally, Smart Contracts enable more complex business logic, especially for payments. By using smart accounts and session keys, this extension allows for programmable payment models that can adapt to various commercial requirements. ### 1.3 Design Goals This extension: * **MUST** be compatible with the existing x402 HTTP handshake * **MUST** use the standard x402 payload structure with an extension field * **SHOULD** be generic enough to support any smart contract interaction * **SHOULD** leverage established standards (ERC-4337, EIP-712) * **MUST** allow facilitators to verify and execute operations on behalf of clients ## 2. Terminology The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119). ### 2.1 Roles | Role | Description | | - | - | | **Client** | The entity requesting access to a protected resource. Signs payment authorizations locally. | | **Server** | The entity providing the protected resource (API, agent, service). Coordinates with the facilitator. | | **Facilitator** | A third-party service that verifies payment authorizations and executes settlement on-chain. | | **Smart Account** | An ERC-4337 compliant smart contract wallet controlled by the client. | ### 2.2 Definitions | Term | Definition | | - | - | | **UserOperation** | An ERC-4337 structure representing an intent to execute a transaction from a smart account. | | **Session Key** | A delegated signing key with scoped permissions, allowing a third party to execute specific actions on behalf of the smart account owner. | | **Order** | A UserOperation that purchases access (e.g., buying a subscription or credit package). | | **Redeem** / **Burn** | A UserOperation that consumes access (e.g., deducting credits for a request). | ## 3. Extension Structure ### 3.1 Scheme Identifier The scheme identifier is: `nvm:erc4337` ### 3.2 Payload Schema #### PaymentRequired Response (402) When a server requires payment, it returns: ```json theme={null} { "x402Version": 2, "error": "Payment required to access resource", "resource": { "url": "/api/v1/agents/80918427023170428029540261117198154464497879145267720259488529685089104529015/tasks", "description": "AI agent task execution", "mimeType": "application/json" }, "accepts": [{ "scheme": "nvm:erc4337", "network": "eip155:84532", "planId": "44742763076047497640080230236781474129970992727896593861997347135613135571071", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015", "httpVerb": "POST" } }], "extensions": {} } ``` #### PaymentPayload (Client Response) The client responds with a PaymentPayload containing the selected scheme and authorization: ```json theme={null} { "x402Version": 2, "resource": { "url": "/api/v1/agents/80918427023170428029540261117198154464497879145267720259488529685089104529015/tasks", "description": "AI agent task execution", "mimeType": "application/json" }, "accepted": { "scheme": "nvm:erc4337", "network": "eip155:84532", "planId": "44742763076047497640080230236781474129970992727896593861997347135613135571071", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015", "httpVerb": "POST" } }, "payload": { "signature": "0x01845ADb2C711129d4f3966735eD98a9F09fC4cE57d4e89a9255457dd052fe0b95b6357b1c74783f490f542c25a2ffa3833432c3e4603b710e01f1f110be3f3a578b0698c81beaf6ccaa63fdc9a32842ed29eeaa531b", "authorization": { "from": "0xD4f58B60330bC59cB0A07eE6A1A66ad64244eC8c", "sessionKeysProvider": "zerodev", "sessionKeys": [ { "id": "order", "data": "0x20a13d82dd9ee289fc5e5a90f4011c8dc03f8f5d5223aafd6b5cd67e3b1ab425" }, { "id": "redeem", "data": "0x68e8e34d659149087451cafc89a7320114072e49fd89657ccba14cad82c0a533" } ] } }, "extensions": {} } ``` ### 3.3 Field Definitions #### PaymentRequired Root Fields | Field | Type | Required | Description | | - | - | - | - | | `x402Version` | `number` | Yes | Protocol version. MUST be `2`. | | `error` | `string` | Yes | Human-readable error message. | | `resource` | `object` | Yes | Protected resource information. | | `accepts` | `array` | Yes | Array of accepted payment schemes. | | `extensions` | `object` | Yes | Empty object `{}` for x402 spec alignment. | #### Resource Fields | Field | Type | Required | Description | | - | - | - | - | | `url` | `string` | Yes | The protected resource URL. | | `description` | `string` | No | Human-readable description. | | `mimeType` | `string` | No | Expected response MIME type (e.g., `"application/json"`). | #### Scheme Fields (in `accepts[]` / `accepted`) | Field | Type | Required | Description | | - | - | - | - | | `scheme` | `string` | Yes | Payment scheme. MUST be `"nvm:erc4337"`. | | `network` | `string` | Yes | Blockchain network identifier using CAIP-2 (e.g., `"eip155:84532"`). | | `planId` | `string` | Yes | 256-bit plan identifier. | | `extra` | `object` | Yes | Additional scheme-specific fields. | #### Extra Fields | Field | Type | Required | Description | | - | - | - | - | | `version` | `string` | Yes | Scheme version (e.g., `"1"`). | | `agentId` | `string` | No | 256-bit agent identifier (if plan has multiple agents). | | `httpVerb` | `string` | No | HTTP method for the endpoint. | #### PaymentPayload Fields | Field | Type | Required | Description | | - | - | - | - | | `x402Version` | `number` | Yes | Protocol version. MUST be `2`. | | `resource` | `object` | No | Echoed from PaymentRequired. | | `accepted` | `object` | Yes | Selected scheme from `accepts[]`. | | `payload` | `object` | Yes | Scheme-specific authorization data. | | `extensions` | `object` | Yes | Empty object `{}` for x402 spec alignment. | #### Payload Fields (Authorization) | Field | Type | Required | Description | | - | - | - | - | | `signature` | `string` | Yes | EIP-712 signature of the payment payload, signed by the client. | | `authorization` | `object` | Yes | Session key authorization data. | #### Authorization Fields | Field | Type | Required | Description | | - | - | - | - | | `from` | `string` | Yes | Client's smart account address (ERC-4337 compliant). | | `sessionKeysProvider` | `string` | Yes | Session key provider identifier (e.g., `"zerodev"`, `"biconomy"`). | | `sessionKeys` | `array` | Yes | Array of session key objects. MUST contain at least one session key. | #### Session Key Object Each session key object MUST contain an `id` field and either `data` OR `hash`: | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | Operation identifier. Common values: `"order"`, `"redeem"`. | | `data` | `string` | Conditional | Base64-encoded session key data. Required if `hash` is not provided. | | `hash` | `string` | Conditional | Keccak256 hash of the base64-encoded session key. Required if `data` is not provided. | > [!NOTE] > > When `data` is provided, the facilitator can reconstruct and verify the session key directly. When only `hash` is provided, the facilitator MUST have a mechanism to retrieve the session key from off-chain storage using the hash. ### 3.4 Session Key Operations The extension defines standard operation identifiers: | Operation ID | Purpose | Description | | - | - | - | | `order` | Purchase | Executes a purchase operation (subscribe, buy credits, etc.). Used for auto top-up. | | `redeem` | Consume | Consumes access (deduct credits, mark subscription usage). Required for settlement. | Implementations MAY define additional operation identifiers for custom use cases. ## 4. Protocol Flow ### 4.1 Overview The protocol flow maintains compatibility with standard x402 while extending the verification and settlement phases: ```mermaid theme={null} --- title: Nevermined + x402 - Payment & Execution Flow --- sequenceDiagram autonumber %% ACTORS actor client as Client participant server as Server (AI Agent) participant facilitator as Facilitator (Nevermined API) participant blockchain as Blockchain %% 1) CLIENT SELECTS PAYMENT METHOD & SENDS PAYMENT PAYLOAD client->>server: GET /api server->>server: Checks the request includes PAYMENT-SIGNATURE header server->>client: HTTP 402 + PAYMENT-REQUIRED header note over client: Select payment method client->>client: Local signing of the Payment Payload
UserOperations order + burn client->>server: Request + PAYMENT-SIGNATURE header %%2) VERIFICATION activate server server->>facilitator: /verify (paymentRequired + paymentPayload + maxAmount) facilitator->>facilitator: check UserOperations include "burn" permissions alt no "burn" permissions facilitator-->>server: ERROR: Payment verification failed
(no "burn" permissions) end note over facilitator: "burn" permissions present facilitator->>blockchain: get Client balance blockchain-->>facilitator: Client balance activate facilitator alt not enough balance alt "order" permission NOT present facilitator-->>server: ERROR: Payment verification failed
(invalid UserOperation) end facilitator->>blockchain: Verify "order" UserOperation can be executed blockchain-->>facilitator: UserOperation verification result alt "order" UserOperation can be executed facilitator-->>server: OK: correct verification else "order" UserOperation can NOT be executed facilitator-->>server: ERROR: Invalid UserOperation. Can NOT order end else enough balance facilitator->>blockchain: Verify "burn" UserOperation can be executed blockchain-->>facilitator: UserOperation verification result alt "burn" UserOperation can be executed facilitator-->>server: OK: correct verification else "burn" UserOperation can NOT be executed facilitator-->>server: ERROR: Invalid UserOperation. Can NOT burn end end deactivate facilitator note over server: Check verification result alt verification was invalid server-->>client: HTTP 402 + PAYMENT-REQUIRED header end %%3) SETTLEMENT server->server: Server does the work to fulfill the client request server->>facilitator: /settle (paymentRequired + paymentPayload + maxAmount) activate facilitator facilitator->>blockchain: get Client balance blockchain-->>facilitator: Client balance alt not enough balance facilitator->>blockchain: Execute "order" UserOperation blockchain-->>facilitator: "order" tx end facilitator->>blockchain: execute "burn" UserOperation blockchain-->>facilitator: execution result alt "burn" OR "order" UserOperation failed facilitator-->>server: Settlement failed
(invalid UserOperation) server-->>client: HTTP 402 + PAYMENT-REQUIRED header else "burn" UserOperation executed facilitator-->>server: Settlement OK
(txHash, creditsBurned) end deactivate facilitator server-->>client: Response + PAYMENT-RESPONSE header deactivate server ``` ### 4.2 Step-by-Step Flow The following steps detail the complete payment and execution flow. Steps are grouped into three phases: **Initial Request**, **Verification**, and **Settlement**. *** #### Phase 1: Initial Request (Steps 1-5) **Step 1.** Client initiates an HTTP request to a Server (AI Agent). ```http theme={null} GET /api/resource HTTP/1.1 Host: agent.example.com ``` **Step 2.** Server validates whether the request contains a valid payment in the `PAYMENT-SIGNATURE` header. **Step 3.** If payment is absent, Server responds with `HTTP 402 Payment Required` status and the `PaymentRequired` object in the `PAYMENT-REQUIRED` header (base64-encoded). ```http theme={null} HTTP/1.1 402 Payment Required PAYMENT-REQUIRED: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkLi4u ``` **Decoded PAYMENT-REQUIRED:** ```json theme={null} { "x402Version": 2, "error": "Payment required to access resource", "resource": { "url": "/api/resource", "description": "Protected resource", "mimeType": "application/json" }, "accepts": [{ "scheme": "nvm:erc4337", "network": "eip155:84532", "planId": "44742763076047497640080230236781474129970992727896593861997347135613135571071", "extra": { "version": "1", "agentId": "80918427023170428029540261117198154464497879145267720259488529685089104529015" } }], "extensions": {} } ``` **Step 4.** The Client: * Selects one of the `accepts` schemes returned by the server response * Creates a PaymentPayload with the selected scheme in `accepted` * Creates and signs locally a `UserOperation` representing the Payment Intent (using ERC-4337 and EIP-712) **Step 5.** Client sends an HTTP request to the server including the x402 Payment Payload and the signed `UserOperation`s in the `PAYMENT-SIGNATURE` HTTP header. ```http theme={null} GET /api/resource HTTP/1.1 Host: agent.example.com PAYMENT-SIGNATURE: ``` *** #### Phase 2: Verification (Steps 6-20) **Step 6.** Server validates the incoming data and forwards the payment data to the facilitator to verify the Client request. ```http theme={null} POST /verify HTTP/1.1 Host: facilitator.example.com Content-Type: application/json { "paymentRequired": { ... }, "paymentPayload": "", "maxAmount": "5" } ``` The facilitator extracts `planId`, `subscriberAddress` (from `payload.authorization.from`), and `agentId` from the token. **Step 7.** Facilitator checks the request and confirms if it includes "redeem" permissions. **Step 8.** IF the request DOES NOT include "redeem" permissions: * Facilitator rejects the request and returns an error to the server * Server returns to the client a `HTTP 402` response with `PAYMENT-REQUIRED` header **Step 9.** IF the request INCLUDES "redeem" permissions, the Facilitator queries the blockchain to check the Client balance. **Step 10.** Blockchain returns the Client balance to the Facilitator. **Step 11.** Facilitator checks if the "order" UserOperation is included. IF the "order" is NOT included AND the client has insufficient balance: * Facilitator rejects the request and returns an error to the server * Server returns to the client a `HTTP 402 PAYMENT-FAILED` response **Step 12.** IF the "order" UserOperation is included, the Facilitator verifies if the "order" UserOperation can be executed. **Step 13.** Blockchain returns the order verification result to the Facilitator. **Step 14.** IF the "order" UserOperation verification is correct, the Facilitator confirms to the server that the verification is correct. **Step 15.** IF the "order" UserOperation verification is INVALID, the Facilitator returns an error to the server. **Step 16.** IF the Client has enough balance, the Facilitator verifies if the "redeem" UserOperation can be executed. **Step 17.** The Blockchain returns the redeem verification result to the Facilitator. **Step 18.** IF the "redeem" UserOperation verification is correct, the Facilitator confirms to the server that the verification is correct. **Step 19.** IF the "redeem" UserOperation verification is INVALID, the Facilitator returns an error to the server. **Step 20.** The Server, after obtaining the verification result from the Facilitator (and BEFORE executing any task), checks the verification result: * If the verification was INVALID, the Server returns to the client a `HTTP 402 PAYMENT-FAILED` response * If the verification was correct, the Server continues with the request execution > [!NOTE] > > The verification phase ensures that the payment CAN be settled before the server performs any work. This protects the server from executing expensive operations without guaranteed payment. *** #### Phase 3: Settlement (Steps 21-32) **Step 21.** The Server executes the task to fulfill the client request (AI Task or any necessary work). **Step 22.** The Server calls the `/settle` endpoint of the Facilitator to settle the request. ```http theme={null} POST /settle HTTP/1.1 Host: facilitator.example.com Content-Type: application/json { "paymentRequired": { ... }, "paymentPayload": "", "maxAmount": "5" } ``` The `maxAmount` specifies the actual credits to redeem (can be less than or equal to the verified amount). **Step 23.** Facilitator queries the blockchain to check the Client balance. **Step 24.** Blockchain returns the Client balance to the Facilitator. **Step 25.** IF the Client does NOT have enough balance, the Facilitator executes the "order" UserOperation on behalf of the Client. **Step 26.** Blockchain returns the "order" transaction to the Facilitator. **Step 27.** Facilitator executes the "redeem" UserOperation on behalf of the Client. **Step 28.** Blockchain returns the execution result to the Facilitator. **Step 29.** IF the "redeem" OR "order" UserOperations execution FAILED, the Facilitator rejects the request and returns an error to the server. **Step 30.** The Server returns to the client a `HTTP 402 PAYMENT-FAILED` response. **Step 31.** IF the "redeem" UserOperation executed successfully, the Facilitator confirms to the server that the request is verified (including the payment tx / order tx). **Step 32.** Server returns to the client the response with the transaction payment confirmation in the `PAYMENT-RESPONSE` header (base64-encoded). ```http theme={null} HTTP/1.1 200 OK Content-Type: application/json PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0cmFuc2FjdGlvbkhhc2giOi4uLg== { "result": "...", "payment": { "creditsBurned": "5", "remainingBalance": "95" } } ``` **Decoded PAYMENT-RESPONSE:** ```json theme={null} { "success": true, "transactionHash": "0x...", "network": "eip155:84532" } ``` The `PAYMENT-RESPONSE` header contains x402-standard settlement fields. Additional Nevermined-specific info (like `creditsBurned`) can be included in the response body. > [!WARNING] > > Steps 29-30 represent a failure scenario where the server has already performed work but settlement failed. Implementations SHOULD have mechanisms to handle this edge case, such as retry logic or dispute resolution. ### 4.3 HTTP Header Summary Per [x402 HTTP Transport v2](https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md), all payment data is transmitted via HTTP headers using base64 encoding: | Header | Direction | Content | | - | - | - | | `PAYMENT-REQUIRED` | Server → Client (402) | Base64-encoded `PaymentRequired` object | | `PAYMENT-SIGNATURE` | Client → Server | Base64-encoded `PaymentPayload` object | | `PAYMENT-RESPONSE` | Server → Client (200) | Base64-encoded settlement receipt | > [!NOTE] > > All three headers use **base64 encoding**. The response body contains the actual resource data plus optional Nevermined-specific payment info. ## 5. Verification Requirements ### 5.1 Payload Validation The facilitator MUST verify: | Check | Requirement | | - | - | | Version | `x402Version` MUST equal `2` | | Scheme | `scheme` MUST equal `"nvm:erc4337"` | | Network | `network` MUST be a supported network using CAIP-2 format | | Subscriber | `payload.authorization.from` MUST be a valid ERC-4337 smart account address | | Signature | `payload.signature` MUST be a valid EIP-712 signature | | Session Keys | At least one session key MUST be present in `payload.authorization.sessionKeys` | ### 5.2 Session Key Validation For each session key, the facilitator MUST verify: | Check | Requirement | | - | - | | Structure | Session key MUST contain valid `id` and either `data` or `hash` | | Validity | Session key MUST not be expired | | Permissions | Session key MUST grant the required permissions | | Scope | Session key MUST be scoped to the correct smart contracts | ### 5.3 Balance and Permission Checks The facilitator MUST verify: | Check | Requirement | | - | - | | Redeem Permission | A `redeem` session key MUST be present | | Balance | Client MUST have sufficient balance OR valid `order` permission | | UserOperation | All UserOperations MUST pass on-chain simulation | ## 6. Settlement Requirements ### 6.1 Execution Order When executing settlement, the facilitator MUST: 1. Check client balance 2. If balance insufficient, execute `order` UserOperation first 3. Wait for `order` transaction confirmation 4. Execute `redeem` UserOperation 5. Return transaction receipts ### 6.2 Atomicity > [!WARNING] > > The facilitator SHOULD ensure that partial settlement does not leave the system in an inconsistent state. If the `order` succeeds but `redeem` fails, the facilitator MUST handle the error appropriately. ### 6.3 Receipt Format The facilitator MUST return a receipt. The `PAYMENT-RESPONSE` header contains x402-standard fields: | Field | Type | Description | | - | - | - | | `success` | `boolean` | Whether settlement succeeded. | | `transactionHash` | `string` | Transaction hash of the redeem operation. | | `network` | `string` | Network where transactions were executed (CAIP-2 format). | Additional settlement details MAY be included in the response body: | Field | Type | Description | | - | - | - | | `billingModel` | `string` | How the request was priced: `credits` or `pay-as-you-go`. Read this before the two credit fields. | | `creditsRedeemed` | `string` | Number of credits redeemed. Always `"0"` on `pay-as-you-go`, including on a settle that charged the buyer. | | `remainingBalance` | `string` | Subscriber's remaining balance. Always `"0"` on `pay-as-you-go`. | | `orderTx` | — | **Not set on this spec.** The ERC-4337 settle handler never populates it on either billing model; it is the fiat card rails' field. On a pay-as-you-go settle here the proof of charge is a non-empty `transaction`. | ### 6.4 Was the buyer charged? `success` alone tells you the settle worked. What a consumer MUST check **in addition** depends on `billingModel`: | `billingModel` | Success criterion | Credit fields | | - | - | - | | `credits` | `success === true` and `creditsRedeemed > 0` | `creditsRedeemed` is the amount burned, `remainingBalance` what is left | | `pay-as-you-go` | `success === true` **and** a non-empty `transaction` (the on-chain order) | always the string `"0"` — no balance exists on this plan shape | > [!NOTE] > > **No `billingModel` in the response?** The deployment predates the discriminator. Apply the > **credits** rule — a missing discriminator MUST NOT be read as pay-as-you-go. > [!WARNING] > > Do not gate on `creditsRedeemed` without reading `billingModel` first. A pay-as-you-go plan holds no credit balance, so `creditsRedeemed > 0` can never hold there and a real payment reads as a decline. > > Note the type as well: both fields are **strings**, so `"0"` is truthy while `Number("0") > 0` is false — two plausible-looking checks disagree. ## 7. Error Handling ### 7.1 Error Codes | Code | Name | Description | | - | - | - | | `INVALID_PAYLOAD` | Invalid Payload | The payment payload structure is invalid | | `INVALID_SIGNATURE` | Invalid Signature | The EIP-712 signature verification failed | | `INSUFFICIENT_BALANCE` | Insufficient Balance | Client lacks balance and valid `order` permission | | `INVALID_USER_OPERATION` | Invalid UserOperation | UserOperation failed on-chain simulation | | `EXPIRED_SESSION_KEY` | Expired Session Key | Session key has expired | | `SETTLEMENT_FAILED` | Settlement Failed | On-chain settlement transaction failed | | `UNSUPPORTED_NETWORK` | Unsupported Network | The specified network is not supported | ### 7.2 Error Response Format ```json theme={null} { "error": { "code": "INSUFFICIENT_BALANCE", "message": "Client balance is 0, no order permission provided", "details": { "clientAddress": "0x...", "requiredBalance": "1000000", "currentBalance": "0" } } } ``` ## 8. Security Considerations ### 8.1 Signature Security * The EIP-712 signature MUST be verified against the client's smart account address * Replay protection SHOULD be implemented using nonces or timestamps * The facilitator MUST NOT execute UserOperations with invalid signatures ### 8.2 Session Key Security * Session keys SHOULD have limited validity periods * Session keys SHOULD be scoped to specific contracts and methods * Session keys SHOULD include spending limits where applicable * Session keys MUST be revocable by the smart account owner ### 8.3 Facilitator Trust Model Clients delegate execution authority to the facilitator. This trust model assumes: * The facilitator will only execute operations after successful verification * The facilitator will only execute operations after the server completes its work * The facilitator acts as an honest intermediary ### 8.4 Network Considerations * All network identifiers MUST be validated against a known allowlist * Cross-network attacks MUST be prevented by including the network in signed data ## 9. Implementation Notes ### 9.1 ERC-4337 Compatibility This extension is designed to work with any ERC-4337 compliant smart account implementation. The `provider` field in the authorization object indicates which session key format is used. ### 9.2 Session Key Providers Common session key providers and their formats: | Provider | Description | | - | - | | `zerodev` | ZeroDev Kernel session keys | | `biconomy` | Biconomy smart account session keys | | `safe` | Safe session modules | Implementations SHOULD document which providers they support. ### 9.3 Gas and Fees The facilitator acts as the paymaster for UserOperation execution. Settlement economics (gas fees, facilitator fees) are outside the scope of this specification. ## 10. References * [x402 Protocol](https://x402.org/) * [ERC-4337: Account Abstraction](https://eips.ethereum.org/EIPS/eip-4337) * [EIP-712: Typed Structured Data Hashing and Signing](https://eips.ethereum.org/EIPS/eip-712) * [EIP-3009: Transfer With Authorization](https://eips.ethereum.org/EIPS/eip-3009) * [RFC 2119: Key words for use in RFCs](https://www.rfc-editor.org/rfc/rfc2119)