Agent skill

Build X402 Server

by coinbase in coinbase/cdp-sdk

Write code that charges for an HTTP route with the x402 protocol and receives USDC in a CDP-managed wallet.

MITAuto-check: notesBackend & APIs

Install Build X402 Server

skills CLI
$ npx skills add coinbase/cdp-sdk --skill build-x402-server -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install coinbase/cdp-sdk build-x402-server --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/coinbase/cdp-sdk.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/build-x402-server .claude/skills/build-x402-server && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
build-x402-server
GitHub stars
204
Token cost
~3.7k tokens
SKILL.md length
1,362 words
Files
1
Skills in repo
3
Repo updated
First seen
Licence
MIT

At a glance

Write code that charges for an HTTP route with the x402 protocol and receives USDC in a CDP-managed wallet.

  • Works in 5 steps: Confirm credentials → Install → Price the route → …
  • The user wants to monetize an API
  • SKILL.md covers When not to use this skill, Decisions, Steps and Troubleshooting, plus 2 more sections
  • Calls pip, npm and curl; needs CDP_API_KEY_ID and CDP_API_KEY_SECRET

What it does

Build X402 Server is an agent skill from coinbase/cdp-sdk. Write code that charges for an HTTP route with the x402 protocol and receives USDC in a CDP-managed wallet. Covers TypeScript (Express, Hono, Next.js) and Python (FastAPI, Flask). Use when the user wants to monetize an API, price a route per request, put a paywall in front of an endpoint, accept payments from agents, or add x402 to a server they already run.

Its SKILL.md is about 3.7k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts. Compatibility notes: Requires a CDP API key and wallet secret. Node.js = 22 (TypeScript) or Python = 3.10.

It sits in Backend & APIs, covering Backend development. It works with x402, TypeScript, FastAPI and Hono. The repository describes itself as: Client libraries for managing EVM and Solana wallets while relying on CDP to secure private keys. The licence is MIT.

When your agent uses it

  • The user wants to monetize an API
  • Price a route per request
  • Put a paywall in front of an endpoint
  • Accept payments from agents

Example prompts

  • “/build-x402-server”

Requirements

  • Python 3
  • Node.js
  • A credential in CDP_API_KEY_SECRET
  • A credential in CDP_WALLET_SECRET
  • Compatibility (from SKILL.md): Requires a CDP API key and wallet secret. Node.js >= 22 (TypeScript) or Python >= 3.10.

Workflow steps

5 steps, taken from the step headings in SKILL.md.

  1. Confirm credentials
  2. Install
  3. Price the route
  4. Confirm the route is protected
  5. Take a real payment

What it can do on your machine

Read from SKILL.md and the folder at commit 993de49. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • pip
    • npm
    • curl

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • docs.cdp.coinbase.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • CDP_API_KEY_ID
    • CDP_API_KEY_SECRET
    • CDP_WALLET_SECRET

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Requires a CDP API key and wallet secret. Node.js >= 22 (TypeScript) or Python >= 3.10.

    From compatibility in the SKILL.md frontmatter.

Context cost

Build X402 Server loads about 3.7k tokens when it runs. Until then it costs about 95 tokens; SKILL.md has 1,362 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~95
When it runs · the whole SKILL.md, loaded when a task matches
~3.7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check: notes

The automated check noted patterns worth knowing about, such as sudo or a known installer.

  • NoteMentions a .env fileSKILL.md:257
    process loads its environment, not just `.env` |

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from coinbase/cdp-sdk at commit 993de49, republished under its MIT licence (© coinbase). 1,362 words, ~3,705 tokens.

Download SKILL.mdSave it as .claude/skills/build-x402-server/SKILL.md (or your agent's skills folder).
name
build-x402-server
description
Write code that charges for an HTTP route with the x402 protocol and receives USDC in a CDP-managed wallet. Covers TypeScript (Express, Hono, Next.js) and Python (FastAPI, Flask). Use when the user wants to monetize an API, price a route per request, put a paywall in front of an endpoint, accept payments from agents, or add x402 to a server they already run.
compatibility
Requires a CDP API key and wallet secret. Node.js >= 22 (TypeScript) or Python >= 3.10.
metadata.author
cdp@coinbase.com
metadata.version
0.1.0

Build an x402 server

Take the user from an unprotected HTTP route to one that answers 402 Payment Required and settles a real payment into a CDP-managed wallet.

Resolve the Decisions table below before writing any code, then read only the language and framework subsections you resolved to in step 3.

When not to use this skill

  • The user sells through Coinbase Business. The Business Checkouts API returns one checkout with a hosted payment URL for people and a payable x402_url for agents, and they run no server at all. Check for this early: for that user it is a genuinely better answer than anything below.
  • The user is charging for an MCP tool rather than an HTTP route. See Charge over MCP.
  • The user is the one paying. Use the build-x402-client skill.
  • The user wants a deployed money-making service with no code. Use the agentic-wallet monetize-service skill. It is the nearest neighbour to this skill and the most likely mis-selection.

Decisions

Resolve every row before writing code. Detect first; only ask when detection is ambiguous.

DecisionHow to detectAsk only ifDefault
Languagepackage.json -> TypeScript. pyproject.toml / requirements.txt -> Python.Both present, or neitherAsk
FrameworkRead deps for express, hono, next, fastapi, flask.No server framework presentAsk; suggest Express or FastAPI
Wiring approachAn existing x402ResourceServer or paymentMiddleware call -> facilitator swap.—Greenfield
Route config sourceAn x402.config.json already in the project -> config file.—Inline in code
Receiver walletThe user supplied a payTo address -> use it.—CDP-provisioned wallet
Networkenvironment: "development" selects testnets.Never assume mainnetdevelopment
SchemeFixed price -> exact. Metered or usage-based -> upto.—exact

Two hard rules, not preferences:

  1. Never move a server to mainnet unless the user asks in the current turn. That puts real payers in front of a route that may not be ready.
  2. If the user supplies a payTo address, echo it back for confirmation before writing it. A typo'd receiver sends every future payment somewhere unrecoverable.

Steps

1. Confirm credentials

Before installing anything, check the environment for CDP_API_KEY_ID, CDP_API_KEY_SECRET, and CDP_WALLET_SECRET. The API key authenticates the server to the CDP Facilitator; the wallet secret provisions the wallet that receives payments, and is only needed when the user has not supplied a payTo of their own. Send them to API key authentication if they have no key. Also confirm the runtime: Node.js 22 or later, or Python 3.10 or later.

2. Install

Pick the line matching the Decisions table. @x402/core, @x402/evm, @x402/svm, and @x402/extensions are optional peer dependencies of the CDP SDK, so they are not installed for you, and all four are needed even for an EVM-only server because @coinbase/cdp-sdk/x402 imports them at module load. Only the framework and its adapter change between the three TypeScript lines.

bash
# TypeScript, Express
npm install express @coinbase/cdp-sdk @x402/core @x402/evm @x402/svm @x402/extensions @x402/express

# ...or Hono:    hono @hono/node-server, and @x402/hono in place of @x402/express
# ...or Next.js: next, and @x402/next in place of @x402/express

# Python
pip install "cdp-sdk" "x402[evm,svm,fastapi]" uvicorn   # FastAPI
pip install "cdp-sdk" "x402[evm,svm,flask]"             # Flask
3. Price the route

Three things are needed from the user before writing anything. Ask for whichever cannot be inferred: which routes to charge for, the price per call, and a one-line description of what each route returns. The description is not decoration — it is what buyers see when the service is listed for discovery, so a vague one costs the user customers later.

State the containment rule plainly: only routes named in the config are protected, everything else stays free. That is the sentence that stops someone paywalling /health.

Read only the subsections matching the language and framework resolved above.

TypeScript

createX402Server provisions the receiver wallet, wires the CDP Facilitator, registers the schemes and extensions, and returns an object any x402 framework adapter accepts. It is async — await it before app.use.

typescript
import { createX402Server } from "@coinbase/cdp-sdk/x402";
import { paymentMiddlewareFromHTTPServer } from "@x402/express";
import express from "express";

const app = express();

const server = await createX402Server({
  environment: "development", // testnets and test funds
  routes: {
    "GET /report": { price: "$0.01", description: "Generate a concise research report" },
  },
});

app.use(paymentMiddlewareFromHTTPServer(server));
app.get("/report", (_req, res) => res.json({ report: "..." }));

app.listen(8402, () => console.log(`Receiving payments at ${server.payToEvmAddress}`));

Two variants on that shape:

  • The user already runs x402. Do not rewrite their server. Replace the facilitator argument with createCdpFacilitatorClient() from @coinbase/cdp-sdk/x402 — same return type, so nothing else in their code moves. This path needs a payTo address, and the factory is synchronous.
  • Routes belong in a file. Pass configPath: "./x402.config.json" instead of routes. Inline routes win per key when both are given, which is how you keep a shared file and still special-case one route in code. Keep credentials in environment variables, not the file.

Hono is the Express code with @x402/hono in place of @x402/express and serve({ fetch: app.fetch, port }) in place of app.listen. The server object is identical.

Next.js is the one genuine exception. App Router route files re-evaluate, so build the server once in its own module and import it from the handler:

typescript
// app/x402.ts — note the /server subpath: the client ExactEvmScheme needs a signer
import { x402ResourceServer } from "@x402/core/server";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { createCdpFacilitatorClient } from "@coinbase/cdp-sdk/x402";

export const server = new x402ResourceServer(createCdpFacilitatorClient()).register(
  "eip155:84532",
  new ExactEvmScheme(),
);

// app/api/report/route.ts
import { withX402 } from "@x402/next";
export const GET = withX402(handler, { accepts: [...], description: "..." }, server);

Gotchas worth stating once:

  • Register the middleware before the protected handlers.
  • Omitting environment means mainnet.
  • Under "development", routes default to both Base Sepolia and Solana Devnet.

Usage-based pricing (upto) only when the user asks for it. The route takes scheme: "upto" and a price that acts as a ceiling; the handler calls setSettlementOverrides(res, { amount }) with the amount actually used before sending the body. amount is a string, and it accepts atomic units ("100000" is $0.10 in 6-decimal USDC), a dollar price ("$0.05"), or a percentage of the authorized ceiling ("50%") — pick whichever the usage calculation produces naturally. upto defaults to the same networks as exact, so under "development" it resolves to Base Sepolia and Solana Devnet. Solana voucher signing delegates to the facilitator.

Show full SKILL.md (511 more words)Show less
Python

There is no createX402Server in Python, so assemble the pieces by hand. It is two halves, and naming them is what keeps the Python version from reading as long and arbitrary:

  1. A CDP wallet to receive payments, resolved from cdp.evm.get_or_create_account(...).address.
  2. The x402 Foundation middleware, pointed at the CDP Facilitator with create_facilitator_config().
python
from cdp.x402 import create_facilitator_config
from fastapi import FastAPI
from x402.http import HTTPFacilitatorClient, PaymentOption
from x402.http.middleware.fastapi import PaymentMiddlewareASGI
from x402.http.types import RouteConfig
from x402.mechanisms.evm.exact import ExactEvmServerScheme
from x402.server import x402ResourceServer

PAY_TO = "0x1234567890123456789012345678901234567890"  # Your EVM address to get paid on Base Sepolia
NETWORK = "eip155:84532"  # Base Sepolia

server = x402ResourceServer(HTTPFacilitatorClient(create_facilitator_config()))
server.register(NETWORK, ExactEvmServerScheme())

routes = {
    "GET /report": RouteConfig(
        accepts=[PaymentOption(scheme="exact", pay_to=PAY_TO, price="$0.01", network=NETWORK)],
        mime_type="application/json",
        description="AI-generated report",
    ),
}

app = FastAPI()
app.add_middleware(PaymentMiddlewareASGI, routes=routes, server=server)

Run it with uvicorn.run(app, port=8402).

The sharpest edge is resolving PAY_TO. CdpClient is an async context manager, but the route config above is module-level and synchronous, which is why the examples resolve the receiver once at import time with asyncio.run(resolve_pay_to()). That works when the module is the entry point. Under an ASGI server that imports it from inside a running event loop, it raises RuntimeError, and the user needs a lifespan hook instead.

Flask is the same code with three substitutions: x402ResourceServerSync and HTTPFacilitatorClientSync in place of the async pair, and payment_middleware(app, routes=routes, server=server) from x402.http.middleware.flask, which is a function that mutates the app rather than a middleware class. Handing Flask the async x402ResourceServer raises a TypeError.

Two more gotchas: PaymentOption is a dataclass whose scheme, pay_to, price, and network have no defaults, so a missing one is a TypeError at construction — which, with a module-level route map, means the server refuses to import rather than failing a request later. And this path is EVM-only, with no Solana option.

4. Confirm the route is protected

Start the server, then from a second terminal:

bash
curl -i http://localhost:8402/report
console
HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkIiwi...

This is the cheap checkpoint before any money moves, and it needs no buyer. Do not skip to step 5.

5. Take a real payment

Either testing path works:

  • Point the agentic-wallet pay-for-service skill at http://localhost:8402/report.
  • Build a buyer with the build-x402-client skill and point it at the same URL.

Success is HTTP 200 on the buyer side. The buyer wallet needs testnet USDC first, which is step 4 of the client skill — link it rather than re-teaching funding here.

Troubleshooting

SymptomCauseFix
Route returns 200 with no paymentRoute key does not match the real method and path, or middleware was registered after the handlerCompare the key to the handler; move app.use above it
402 with no PAYMENT-REQUIRED headerThe middleware was never reachedCheck registration order and the mount path
Verification passes, settlement failsBuyer and server are on different chainsMatch the buyer's network to the one in the 402
Auth error at startupCDP_API_KEY_* not visible to the processCheck how the process loads its environment, not just .env
Payments land somewhere unknownA CDP wallet was provisioned and the printed payTo was never recordedRead it back from server.payToEvmAddress and save it

Runnable examples

TypeScript, under https://github.com/coinbase/cdp-sdk/blob/main/examples/typescript/x402/servers/: express/server.ts (all three approaches), express/x402.config.json and express/x402.config.schema.json, hono/server.ts, next/app/api/report/route.ts, mcp/server.ts.

Python, under https://github.com/coinbase/cdp-sdk/blob/main/examples/python/x402/servers/: fastapi/server.py, flask/server.py, bazaar.py, mcp/server.py.

After the first payment

  • Make the endpoint findable: Get discovered. TypeScript's createX402Server handles it automatically; Python needs manual metadata like bazaar.py above
  • What settled the payment: CDP Facilitator
  • Other networks, schemes, receivers, lifecycle hooks: Production configuration
  • Charging for MCP tools: Charge over MCP
  • Mainnet: drop environment: "development" and confirm with the user first

© coinbase, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in skills/build-x402-server of coinbase/cdp-sdk.

Open the folder on GitHubat commit 993de49

Compare with similar skills

Build X402 Server next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Build X402 Server compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Build X402 Server this skillcoinbase/cdp-sdk204—~3.7kAutomated safety check: NotesMIT
Implementing API Patternsancoleman/ai-design-components5261 repos~3kAutomated safety check: PassMIT
Nevermined PaymentsLeoYeAI/openclaw-master-skills2.2k—~4.5kAutomated safety check: NotesMIT
Fastcrudbenavlabs/fastcrud1.6k—~5kAutomated safety check: PassMIT
Phoenix ServerArize-ai/phoenix12k—~1.6kAutomated safety check: PassCustom licence
FastAPI Project Templateswshobson/agents40k12 repos~901Automated safety check: PassMIT

Similar skills

  • Implementing API Patterns

    ancoleman/ai-design-components

    API design and implementation across REST, GraphQL, gRPC, and tRPC patterns.

    526 GitHub starsUsed in 1 repo~3k tokens
    Backend & APIsAuto-check passed
  • Nevermined Payments

    LeoYeAI/openclaw-master-skills

    Integrates Nevermined payment infrastructure into AI agents, MCP servers, Google A2A agents, and REST APIs.

    2.2k GitHub stars~4.5k tokensUpdated 2 mo ago
    Backend & APIsAuto-check: notes
  • Fastcrud

    benavlabs/fastcrud

    A skill your agent uses when building or modifying CRUD endpoints with FastCRUD (the fastcrud PyPI package) in a FastAPI project — covers FastCRUD, crudrouter, EndpointCreator, FilterConfig…

    1.6k GitHub stars~5k tokensUpdated 13 days ago
    Backend & APIsAuto-check passed
  • Phoenix Server

    Arize-ai/phoenix

    Backend development guide for the Phoenix AI observability platform (Strawberry GraphQL, SQLAlchemy async, FastAPI).

    12k GitHub stars~1.6k tokensUpdated today
    Backend & APIsAuto-check passed
  • Scaffolds FastAPI projects with a layered app layout, dependency injection through Depends, async handlers and database access, middleware and pytest setup.

    40k GitHub starsUsed in 12 repos~901 tokens
    Backend & APIsAuto-check passed
  • Implementation patterns for Upstash Workflow and QStash handlers in the LobeHub codebase: dry runs, fan-out chunking and single-item execution.

    83k GitHub stars~1.7k tokensUpdated today
    Backend & APIsAuto-check passed

More from coinbase/cdp-sdk

  • Build X402 Client

    coinbase/cdp-sdk

    Write code that pays for an HTTP API returning 402 Payment Required, using the x402 protocol and a CDP-managed wallet.

    204 GitHub stars~3k tokensUpdated 2 days ago
    Auto-check passed
  • Bump X402 Dependencies

    coinbase/cdp-sdk

    Bumps every @x402/ package (the optional peer dependencies in the CDP TypeScript SDK, the pinned dev dependencies used to test the SDK against x402, and the dependencies in every TypeScript x402…

    204 GitHub stars~2.1k tokensUpdated 2 days ago
    Auto-check passed

Categories

Questions about Build X402 Server

What does Build X402 Server do?

Write code that charges for an HTTP route with the x402 protocol and receives USDC in a CDP-managed wallet. Build X402 Server is an agent skill from coinbase/cdp-sdk. Write code that charges for an HTTP route with the x402 protocol and receives USDC in a CDP-managed wallet.

When should I use Build X402 Server?

Build X402 Server fits situations like: the user wants to monetize an API; price a route per request; put a paywall in front of an endpoint; accept payments from agents.

How do I install Build X402 Server in Claude Code?

Run `npx skills add coinbase/cdp-sdk --skill build-x402-server -a claude-code`. Or copy the skill folder (skills/build-x402-server in coinbase/cdp-sdk) into .claude/skills/build-x402-server in your project. Claude Code loads it when a task matches its description.

How do I install Build X402 Server in Codex?

Run `npx skills add coinbase/cdp-sdk --skill build-x402-server -a codex`. Or copy the skill folder (skills/build-x402-server in coinbase/cdp-sdk) into .agents/skills/build-x402-server in your project. Codex loads it when a task matches its description.

Can I use Build X402 Server in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add coinbase/cdp-sdk --skill build-x402-server -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/build-x402-server, .gemini/skills/build-x402-server, .github/skills/build-x402-server and .opencode/skills/build-x402-server in your project.

What does Build X402 Server need to run?

Going by SKILL.md and its folder, Build X402 Server needs the command-line tools its instructions call (pip, npm and curl) and credentials named CDP_API_KEY_ID, CDP_API_KEY_SECRET and CDP_WALLET_SECRET. Our summary lists: Python 3; Node.js; A credential in CDP_API_KEY_SECRET; A credential in CDP_WALLET_SECRET. Compatibility (from SKILL.md): Requires a CDP API key and wallet secret. Node.js >= 22 (TypeScript) or Python >= 3.10..

Does Build X402 Server access the network?

SKILL.md names 1 domain. As links in the text: docs.cdp.coinbase.com. This is read from the text; nothing was executed.

Is Build X402 Server safe to install?

Our automated static check of SKILL.md found notes only (mentions a .env file), nothing it rates as a warning. It is not a guarantee. Review the folder before installing.

What licence does Build X402 Server use?

Build X402 Server is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Build X402 Server use?

About 3.7k tokens (SKILL.md is roughly 15k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Build X402 Server?

Skills that share tags, products or a category with Build X402 Server: Implementing API Patterns (ancoleman/ai-design-components, 526 stars), Nevermined Payments (LeoYeAI/openclaw-master-skills, 2.2k stars), Fastcrud (benavlabs/fastcrud, 1.6k stars) and Phoenix Server (Arize-ai/phoenix, 12k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Build X402 Server?

coinbase (a GitHub organization) maintains it in coinbase/cdp-sdk, which has 204 GitHub stars. The repository holds 3 skills in this directory. The repository was last updated on October 6, 2026.

Source: coinbase/cdp-sdk on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.