Skip to content

Call a paid tool from a script

The examples call sql-guard ($0.004 a call). Every paid tool is called the same way; /api/pricing lists them.

Credits key · Wallet · Errors · Budget · Many calls

With a credits key

Buy a key by card at /credits and send it as Authorization: Bearer a402_YOUR_KEY.

curl
curl https://agent402.tools/api/sql-guard \
  -H "Authorization: Bearer $AGENT402_CREDITS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"sql":"DELETE FROM users"}'
Python
# pip install requests
import os, requests

r = requests.post(
    "https://agent402.tools/api/sql-guard",
    headers={"Authorization": f"Bearer {os.environ['AGENT402_CREDITS_KEY']}"},
    json={"sql":"DELETE FROM users"},
    timeout=120,
)
print(r.status_code, r.json())
print("left on the key:", r.headers.get("X-Credits-Balance"))
Node
// npm install agent402-client
import { Agent402 } from "agent402-client";

const agent = new Agent402({ creditsKey: process.env.AGENT402_CREDITS_KEY });
console.log(await agent.call("sql-guard", {"sql":"DELETE FROM users"}));

Each call takes its price on a final 200, and X-Credits-Balance says what is left. Tools tied to a wallet (memory, usage) and those that buy from an outside seller take a wallet.

With a wallet, over x402

AGENT_KEY is the private key of a wallet that holds a little USDC on Base. Use a new one, never your main wallet: make and fund one. The examples use it to sign on your machine.

The two requests, in curl

curl cannot sign, so this small script does:

sign.mjs
// sign.mjs   (npm install @x402/core @x402/evm viem)
import { x402Client } from "@x402/core/client";
import { decodePaymentRequiredHeader, encodePaymentSignatureHeader } from "@x402/core/http";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

const client = new x402Client();
registerExactEvmScheme(client, { signer: privateKeyToAccount(process.env.AGENT_KEY) });
const offer = decodePaymentRequiredHeader(process.argv[2]);
console.log(encodePaymentSignatureHeader(await client.createPaymentPayload(offer)));
curl
# 1. Ask. The answer is 402, and its PAYMENT-REQUIRED header is the offer.
OFFER=$(curl -s -D - -o /dev/null https://agent402.tools/api/sql-guard \
  -H "Content-Type: application/json" -d '{"sql":"DELETE FROM users"}' \
  | tr -d '\r' | awk 'tolower($1) == "payment-required:" { print $2 }')

# 2. Sign it, and send the same request again with the signature.
curl https://agent402.tools/api/sql-guard \
  -H "PAYMENT-SIGNATURE: $(node sign.mjs "$OFFER")" \
  -H "Content-Type: application/json" -d '{"sql":"DELETE FROM users"}'

Or let a package do both

Python
# pip install agent402-structured-tools "x402[evm,requests]"
import os
from eth_account import Account
from x402 import x402ClientSync
from x402.http.clients.requests import x402_requests
from x402.mechanisms.evm.exact.register import register_exact_evm_client
from agent402_structured_tools import agent402_tool_specs

client = x402ClientSync()
register_exact_evm_client(client, Account.from_key(os.environ["AGENT_KEY"]))
specs = agent402_tool_specs(x402_fetch=x402_requests(client).request,
                            x402_client=client, max_per_call_usd=0.05)
call = next(s["execute"] for s in specs if s["name"] == "agent402_call")
print(call("sql-guard", {"sql":"DELETE FROM users"}))
Node
// npm install agent402-client @x402/core @x402/evm @x402/fetch viem
import { Agent402 } from "agent402-client";
import { x402Client } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { wrapFetchWithPayment } from "@x402/fetch";
import { privateKeyToAccount } from "viem/accounts";

const client = new x402Client();
registerExactEvmScheme(client, { signer: privateKeyToAccount(process.env.AGENT_KEY) });
const agent = new Agent402({ x402Client: client, fetch: wrapFetchWithPayment(fetch, client), maxPerCallUsd: 0.05 });
console.log(await agent.call("sql-guard", {"sql":"DELETE FROM users"}));

Other chains, MPP and the free tools: how to pay.

When a call fails

what happenedanswerwhat it carriesyour money
No balance402reason: "insufficient", with balanceUsd and priceUsdNothing is debited.
Over a limit set on the key402over_call_limit or over_daily_limit, with limitUsdNothing is debited.
Over your own capno requestSpendingLimitError from the SDK, with limit and priceUsdNothing is signed or sent.
Payment refused402reason and retry, which says what helpsPayment check explains each reason.
Wrong input400expected, required and howToCall, a request that worksNot charged on x402 and credits.
The tool failed502, 503 or 504error and errorCodeNot charged on x402 and credits. Some calls are paid before they run; a failed one can be retried free with the same payment, or is refunded.
Node
import { Agent402, SpendingLimitError } from "agent402-client";

const agent = new Agent402({ creditsKey: process.env.AGENT402_CREDITS_KEY, maxPerCallUsd: 0.001 });
try {
  await agent.call("sql-guard", {"sql":"DELETE FROM users"});
} catch (e) {
  if (e instanceof SpendingLimitError) console.log("over your cap:", e.limit, e.priceUsd); // nothing was sent
  else console.log(e.status, e.message, "paid:", e.paid);
}

A budget for one job

Make one client per job. maxTotalUsd stops it at that total, estimate prices a list first, and callWithSpend returns the running total.

Node
import { Agent402 } from "agent402-client";

const job = new Agent402({ creditsKey: process.env.AGENT402_CREDITS_KEY, maxTotalUsd: 2 });
const calls = ["DELETE FROM users", "SELECT 1", "DROP TABLE users"]
  .map((sql) => ({ slug: "sql-guard", params: { sql } }));

const plan = await job.estimate(calls); // nothing is run or paid
console.log("would cost", plan.totalUsd);
for (const { slug, params } of plan.withinTotal ? calls : []) {
  const { result, spend } = await job.callWithSpend(slug, params);
  console.log(result.verdict, "spent so far:", spend.totalUsd);
}

In an MCP app, AGENT402_BUDGET caps a session of agent402-mcp. A credits key can also hold a limit per call and per day, set on its balance page.

Many calls, and long ones

Call a tool once per URL; each call is paid on its own, so one that fails costs the others nothing. site-crawl reads up to 20 pages a call and returns a cursor while pages are left:

Node
import { Agent402 } from "agent402-client";

const job = new Agent402({ creditsKey: process.env.AGENT402_CREDITS_KEY, maxTotalUsd: 0.2 });
const url = "https://example.com";
let cursor, pages = [];
do {
  const r = await job.call("site-crawl", { url, limit: 20, ...(cursor && { cursor }) });
  pages.push(...r.pages);
  cursor = r.cursor; // there while pages are left
} while (cursor);
console.log(pages.length, "pages");

Some tools take a list in one call, priced per item: weather-risk-brief and filings-brief. A skill pack runs several tools for one payment.

A tool that takes minutes runs as a job: send Prefer: respond-async, get a link, and poll it free. The SDK does this for you. More: long calls as jobs and buying at volume.