IT
Formazione per agenti · x402

playbook-x402-seller

Guida pratica: diventare venditore x402 su Cloudflare Workers. Una guida sintetica dal paywall di Forge Agent Hub (x402 v2, schema exact, USDC su Base): forma del 402, cablaggio @x402/core, regolamento solo dopo il successo, facilitator, file di discovery e la lezione D1 contro KV. ?demo=1 restituisce l’indice e un estratto, senza pagamento.

3 USDC / chiamata · {atomic} atomico · 3000000 atomic

Endpoint

GET|POST https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller

Parametri

NomeObbligatorioTipoDescrizione
Nessuno

Esempio di richiesta (non pagata — attendi 402)

curl -sS -D - "https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller?"

Esempio di challenge 402

Lo stesso oggetto è inviato anche come intestazione PAYMENT-REQUIRED in base64. Gli importi sono unità USDC atomiche (6 decimali).

{
  "x402Version": 2,
  "error": "Payment required",
  "resource": {
    "url": "https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller",
    "description": "Playbook: become an x402 seller on Cloudflare Workers. A concise, practical guide from Forge Agent Hub's own Worker paywall (x402 v2, exact scheme, USDC on Base): 402 shape, @x402/core wiring, settle-only-on-success, facilitators, discovery files, and the D1-versus-KV lesson. ?demo=1 returns the table of contents and an excerpt, unpaid.",
    "mimeType": "application/json"
  },
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "amount": "3000000",
      "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "payTo": "0x7B8bf45ac6AcbA6D4CFB626b57D3f5fF3C9C89F7",
      "maxTimeoutSeconds": 120,
      "extra": {
        "name": "USD Coin",
        "version": "2"
      }
    }
  ]
}

Riprova con pagamento

curl -sS "https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller?" \
  -H "PAYMENT-SIGNATURE: $PAYMENT"

Esempio di risposta

{
  "title": "Become an x402 seller on Cloudflare Workers",
  "toc": [
    "1. What an unpaid caller must see",
    "2. The Worker paywall (x402 v2, exact, USDC on Base)",
    "3. Settle only after a successful handler",
    "4. Facilitator choice, without putting secrets in the repo",
    "5. Discovery files agents actually fetch",
    "6. Cloudflare account, D1, and a failed KV attempt",
    "7. Verify before you list the endpoint"
  ],
  "body": "Full playbook after payment."
}

Demo / campione gratuito

Questo tool è sul worker della wave 1. ?demo=1 restituisce un campione o un estratto etichettato con HTTP 200 e senza pagamento. Il body non sono dati live. Anche le prime 3 chiamate reali riuscite per IP e giorno UTC sono gratuite.

curl -sS "https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller?demo=1"

Risposta demo etichettata

{
  "demo": true,
  "demo_label": "DEMO / SAMPLE — not live data. This is a labelled example response and was not charged.",
  "charged": false,
  "tool": "/api/playbook-x402-seller",
  "docs": "https://agent-hub.dentreprise.workers.dev/tools/playbook-x402-seller/",
  "how_to_get_live_data": "Call the same URL without demo=1. The first 3 successful real calls per IP per UTC day are free; after that attach an x402 v2 PAYMENT-SIGNATURE (USDC on Base).",
  "sample": {
    "title": "Become an x402 seller on Cloudflare Workers",
    "toc": [
      "1. What an unpaid caller must see",
      "2. The Worker paywall (x402 v2, exact, USDC on Base)",
      "3. Settle only after a successful handler",
      "4. Facilitator choice, without putting secrets in the repo",
      "5. Discovery files agents actually fetch",
      "6. Cloudflare account, D1, and a failed KV attempt",
      "7. Verify before you list the endpoint"
    ],
    "excerpt": "An unpaid GET or POST on a paid path must return HTTP 402 with an x402 v2 body (and usually a PAYMENT-REQUIRED header). The body needs x402Version: 2, a resource object, and accepts[] entries whose scheme is exact, network is the CAIP-2 id eip155:8453 (Base), amount is atomic USDC (6 decimals — 0.001 USDC is \"1000\"), and payTo is your receiving address. A free 200, or a forged payment header, must never unlock the resource. The rest of this playbook shows how we wired that on a Cloudflare Worker with @x402/core and @x402/evm, when we settle, how we publish discovery files, and the account/storage mistakes we actually hit.",
    "demo": true,
    "demo_label": "DEMO / excerpt — not the full playbook."
  }
}

JavaScript — @x402/fetch

Client ufficiale x402 v2. Installa @x402/fetch e @x402/evm. Il vecchio nome di pacchetto x402-fetch è la linea v1 deprecata e non va usato per questi endpoint.

import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm";
import { privateKeyToAccount } from "viem/accounts";

// Official x402 v2 client. The older package name "x402-fetch" is the deprecated v1 line.
const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY);
const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
  schemes: [{ network: "eip155:8453", client: new ExactEvmScheme(account) }],
});

const res = await fetchWithPayment(
  "https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller"
);
console.log(await res.json());

Python — x402

Pacchetto ufficiale PyPI x402. Usa x402HttpxClient (async) o x402_requests (sync) dopo register_exact_evm_client con EthAccountSigner.

import asyncio
import os
from eth_account import Account
from x402 import x402Client
from x402.http.clients import x402HttpxClient
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact.register import register_exact_evm_client

# Official PyPI package: x402
account = Account.from_key(os.environ["EVM_PRIVATE_KEY"])
client = x402Client()
register_exact_evm_client(client, EthAccountSigner(account))

async def main():
    async with x402HttpxClient(client) as http:
        res = await http.get("https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller")
        print(res.json())

asyncio.run(main())

# Sync alternative:
# from x402 import x402ClientSync
# from x402.http.clients import x402_requests
# client = x402ClientSync()
# register_exact_evm_client(client, EthAccountSigner(account))
# with x402_requests(client) as session:
#     print(session.get("https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller").json())

Server MCP — forge-agent-mcp

stdio copre l’intero catalogo (entrambi gli host API). Clona forge-agent-mcp e punta il client MCP a src/server.mjs. Il remote Streamable HTTP ospitato sul gateway originale espone ancora solo i tool di quel gateway.

{
  "mcpServers": {
    "forge-agent-hub": {
      "command": "node",
      "args": ["/path/to/forge-agent-mcp/src/server.mjs"]
    },
    "forge-agent-api": {
      "url": "https://x402-gateway.forge-x402.workers.dev/mcp",
      "transport": "streamable-http"
    }
  }
}

Wrapper di strumento LangChain

Avvolgi gli stessi client x402 come strumento LangChain con DynamicStructuredTool (@langchain/core) o @tool (langchain_core).

import { DynamicStructuredTool } from "@langchain/core/tools";
import { z } from "zod";
import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY);
const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
  schemes: [{ network: "eip155:8453", client: new ExactEvmScheme(account) }],
});

export const playbook_x402_seller = new DynamicStructuredTool({
  name: "playbook_x402_seller",
  description: "Playbook: become an x402 seller on Cloudflare Workers.",
  schema: z.object({}),
  func: async (input) => {
    const res = await fetchWithPayment("https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller" + "?" + new URLSearchParams(input));
    return JSON.stringify(await res.json());
  },
});
import os
from langchain_core.tools import tool
from eth_account import Account
from x402 import x402ClientSync
from x402.http.clients import x402_requests
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact.register import register_exact_evm_client

account = Account.from_key(os.environ["EVM_PRIVATE_KEY"])
client = x402ClientSync()
register_exact_evm_client(client, EthAccountSigner(account))

@tool
def playbook_x402_seller() -> str:
    """Playbook: become an x402 seller on Cloudflare Workers."""
    with x402_requests(client) as session:
        return session.get("https://forge-tools.dentreprise.workers.dev/api/playbook-x402-seller").text

Endpoint correlati