Skip to content
AgentSearch

x402 TypeScript Tutorial: Let Your AI Agent Pay Per Call for Web Search (Node.js)

If you build agents in TypeScript, you've probably hit the same wall every time you add a web tool: sign up, verify an email, copy an API key into .env, pick a plan. Then do it again for the next tool.

x402 removes that step. The server answers an unpaid request with HTTP 402 Payment Required and a machine-readable price. Your client signs a small USDC payment, retries, and gets the answer. There's no account, no key and no monthly plan, so an agent can pay for exactly the calls it makes.

This guide builds that in Node.js with TypeScript, step by step:

  1. Read a live 402 price for free, with plain fetch.
  2. Pay per call with @x402/fetch.
  3. Wrap search and page reads as agent tools with a hard budget.
  4. Run them in a tool-calling loop with the OpenAI Node SDK.

The API is AgentSearch's direct x402 API at api.agentsearchhq.com, on Base mainnet. The same code works for any x402 v2 seller.

What it costs

Live prices from GET https://api.agentsearchhq.com/x402/v1/pricing:

Endpoint What it does Price per call
POST /x402/v1/search Live web search, ranked results as JSON $0.003
POST /x402/v1/extract Any public URL to clean markdown $0.002
POST /x402/v1/search_and_read Search plus the top pages as markdown, one call $0.005
POST /x402/v1/render JavaScript-heavy pages in headless Chromium see Render

Payments are USDC on Base, x402 v2 exact scheme, settled through the Coinbase CDP facilitator. Failed and empty calls are never settled: payment is verified first and only settled after a usable answer. A typical "search once, read two pages" question costs $0.003 + $0.002 + $0.002 = $0.007.

Step 0: A small, dedicated wallet

Create a new wallet just for the agent and put a few dollars of USDC on Base in it. You don't need ETH for gas; the facilitator pays it. Keep the private key in an environment variable:

export WALLET_PRIVATE_KEY=0x...   # dedicated agent wallet, never your main one

Then set up a project:

mkdir x402-agent && cd x402-agent
npm init -y && npm pkg set type=module
npm i @x402/fetch @x402/evm viem openai
npm i -D typescript tsx @types/node

Node 20 or newer gives you a global fetch, which is all the payment wrapper needs. Run any file below with npx tsx file.ts.

Step 1: Look at the 402 without paying

An unpaid request is free. It returns 402 with the terms in the PAYMENT-REQUIRED header as base64 JSON:

// peek-402.ts
const res = await fetch("https://api.agentsearchhq.com/x402/v1/search", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ query: "x402 payment protocol", max_results: 5 }),
});

console.log(res.status); // 402, nothing charged
const header = res.headers.get("payment-required");
if (!header) throw new Error("no PAYMENT-REQUIRED header");

const terms = JSON.parse(Buffer.from(header, "base64").toString("utf8"));
const offer = terms.accepts[0];
console.log(offer.scheme, offer.network, offer.amount, offer.payTo);
// exact eip155:8453 3000 0xC49B157887e51c21CB655f39CF65D6a4c2a4C337

amount is in USDC atomic units (6 decimals), so 3000 is $0.003. This is also how an agent can discover a price at runtime: ask, read the 402, decide.

Before you pay anything, check that payTo matches the address published at /.well-known/x402 and on the security page.

Step 2: Pay per call with @x402/fetch

@x402/fetch wraps the normal fetch. When a response is 402, it signs the payment with your wallet and retries the request:

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

const account = privateKeyToAccount(process.env.WALLET_PRIVATE_KEY as `0x${string}`);

const payFetch = wrapFetchWithPaymentFromConfig(fetch, {
  schemes: [{ network: "eip155:8453", client: new ExactEvmScheme(account) }],
});

const res = await payFetch("https://api.agentsearchhq.com/x402/v1/search", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ query: "x402 payment protocol", max_results: 5 }),
});

const data = await res.json();
for (const hit of data.results) console.log(hit.score, hit.url);

A search response looks like this (trimmed):

{
  "query": "x402 payment protocol",
  "result_count": 5,
  "results": [
    {"title": "x402 - payments protocol for the internet",
     "url": "https://www.x402.org/",
     "content": "x402 is an open payment standard built on HTTP 402 ...",
     "score": 0.91, "domain": "x402.org", "published_date": null}
  ]
}

The receipt for each paid call comes back in the PAYMENT-RESPONSE header if you want to log it. Search, news and search-and-read also accept optional filters: freshness (day, week, month, year), country, language, and include_domains / exclude_domains.

Step 3: Agent tools with a hard budget

Agents call tools in loops. Don't leave spending to the prompt; put it in code. This module exposes webSearch and readPage, counts what was actually spent, and refuses any call that would cross the budget. Because failed and empty calls aren't settled, it only counts a call when it returns 200.

// web-tools.ts
import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm";
import { privateKeyToAccount } from "viem/accounts";

const API = "https://api.agentsearchhq.com/x402/v1";
const PRICE_USD = { search: 0.003, extract: 0.002 } as const;
type Endpoint = keyof typeof PRICE_USD;

export class BudgetExceeded extends Error {}

export class WebTools {
  spent = 0;
  private payFetch: typeof fetch;

  constructor(private budgetUsd = 0.1) {
    const account = privateKeyToAccount(process.env.WALLET_PRIVATE_KEY as `0x${string}`);
    this.payFetch = wrapFetchWithPaymentFromConfig(fetch, {
      schemes: [{ network: "eip155:8453", client: new ExactEvmScheme(account) }],
    }) as typeof fetch;
  }

  private async call(endpoint: Endpoint, body: object): Promise<any> {
    const price = PRICE_USD[endpoint];
    if (this.spent + price > this.budgetUsd) {
      throw new BudgetExceeded(`${endpoint} would exceed $${this.budgetUsd.toFixed(2)}`);
    }
    const res = await this.payFetch(`${API}/${endpoint}`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(body),
    });
    if (res.status !== 200) {
      // 400, 502 and empty answers are not settled, so nothing to count
      return { error: `HTTP ${res.status}`, detail: (await res.text()).slice(0, 300) };
    }
    this.spent += price;
    return res.json();
  }

  async webSearch(query: string, maxResults = 5) {
    const data = await this.call("search", { query, max_results: maxResults });
    if (data.error) return data;
    return {
      results: (data.results ?? []).map((h: any) => ({
        title: h.title,
        url: h.url,
        snippet: String(h.content ?? "").slice(0, 300),
      })),
    };
  }

  async readPage(url: string, maxChars = 8000) {
    const data = await this.call("extract", { url, max_chars: maxChars });
    if (data.error) return data;
    const md: string = data.markdown ?? "";
    return { url: data.url ?? url, title: data.title, markdown: md, empty: md.trim() === "" };
  }
}

Two habits worth keeping even if you rewrite the rest:

  1. Trim what goes back to the model. 300-character snippets and 8,000-character pages keep the context window, and your model bill, under control. Extract takes max_chars (up to 50,000) so the trimming happens server side.
  2. Return errors as data. The model sees { error: "HTTP 400" } and can try another URL instead of crashing the run.

Step 4: Wire the tools into an agent loop

Here's a minimal tool-calling loop with the OpenAI Node SDK. Any model or framework with tool calls works the same way: describe the tools, run what the model asks for, feed the results back.

// agent.ts
import OpenAI from "openai";
import { WebTools, BudgetExceeded } from "./web-tools.js";

const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "web_search",
      description: "Search the live web. Returns up to 5 results with title, url, snippet.",
      parameters: {
        type: "object",
        properties: { query: { type: "string" } },
        required: ["query"],
      },
    },
  },
  {
    type: "function",
    function: {
      name: "read_page",
      description: "Read one URL as clean markdown. Use on the 1-2 best search results.",
      parameters: {
        type: "object",
        properties: { url: { type: "string" } },
        required: ["url"],
      },
    },
  },
];

const SYSTEM =
  "Answer with sources. Search once, read at most two pages, then answer and cite the URLs you read.";

async function run(question: string) {
  const llm = new OpenAI();
  const web = new WebTools(0.05); // five cents max per question
  const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
    { role: "system", content: SYSTEM },
    { role: "user", content: question },
  ];

  try {
    for (let round = 0; round < 6; round++) { // hard cap on tool rounds
      const resp = await llm.chat.completions.create({ model: "gpt-4o-mini", messages, tools });
      const msg = resp.choices[0].message;
      messages.push(msg);

      if (!msg.tool_calls?.length) {
        console.log(msg.content);
        break;
      }

      for (const call of msg.tool_calls) {
        if (call.type !== "function") continue;
        const args = JSON.parse(call.function.arguments);
        let result: unknown;
        try {
          result =
            call.function.name === "web_search"
              ? await web.webSearch(args.query)
              : await web.readPage(args.url);
        } catch (e) {
          result = e instanceof BudgetExceeded
            ? { error: e.message, hint: "Answer with what you have." }
            : { error: String(e) };
        }
        messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
      }
    }
  } finally {
    console.log(`spent $${web.spent.toFixed(3)}`);
  }
}

await run("What changed in the x402 v2 spec?");

A typical run is one search and two page reads, $0.007. With a $0.05 budget the worst case per question is five cents, and the six-round cap stops a runaway loop long before that.

When Extract comes back empty

Some pages are single-page apps that ship an empty HTML shell and draw everything with JavaScript. Extract returns little or no markdown for those, and since empty extractions aren't settled, the miss costs nothing.

For those URLs, call POST /x402/v1/render with the same { url } body. It loads the page in headless Chromium and returns markdown with the title and links. Add it as a third tool, or fall back to it inside readPage when empty is true. Current Render pricing is on the Render page, and reading JavaScript pages from an AI agent walks through when you need it.

One call instead of four: Search + Read

If your agent nearly always reads the top results anyway, search_and_read returns the top 1 to 5 results with each page's markdown in a single paid call, $0.005, settled only when at least one page has text:

const res = await payFetch("https://api.agentsearchhq.com/x402/v1/search_and_read", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ query: "x402 v2 spec changes", num_results: 3 }),
});
const { results } = await res.json();
for (const page of results) console.log(page.url, page.chars, page.extract_status);

That's one payment instead of four for a search plus three reads ($0.005 versus $0.009 a la carte). Details on Search + Read.

Prefer not to write payment code?

You don't have to. The AgentSearch packages pay the direct x402 API for you once you set AGENTSEARCH_WALLET_PRIVATE_KEY, and they include a free search tier: up to 25 searches a day per IP, up to 5 results each, no key and no wallet. That's a good way to build and test at $0 before you fund anything. Search stays on the free tier until you opt in to paid search (mode: "paid" in the AI SDK package, AGENTSEARCH_MODE=paid in MCP); a wallet key on its own only pays for the other tools.

  • Vercel AI SDK: npm i @agentsearchhq/ai-sdk ai zod gives you ready-made AI SDK tools (agentSearchFreeTools() for the free set, agentSearchTools() for all six): free web search, free-trial extract and render, and pay-per-call news, screenshots and search-and-read. Guide: add web search to the Vercel AI SDK.
  • LangChain.js: see add web search to a LangChain.js agent.
  • MCP (Claude, Cursor, Cline, VS Code): npx -y @agentsearchhq/agentsearch-mcp, with AGENTSEARCH_WALLET_PRIVATE_KEY in the server's env for paid calls. With nothing set, Extract and Render run on a free trial of 5 and 3 calls a day per IP. Setup: free MCP web scraping.
  • n8n: the n8n-nodes-agentsearch community node. See n8n AI agent: read web pages.

Wallet checklist

  • Use a new wallet that holds only what the agent may spend.
  • Keep the key in an environment variable or a secret manager, never in a repo or a prompt.
  • Cap spend in code (budget per task) and cap tool rounds per run.
  • Check payTo, amount, token and network against the 402 terms and /.well-known/x402.
  • Never sign a Permit, Permit2 or approve request to pay for a call. An x402 exact payment is a single transfer of the listed amount with a short validity window.

FAQ

Do I need an AgentSearch account or API key?

No. The 402 response is the price list, and the signed payment is the authorization.

Which network and token?

USDC on Base mainnet (eip155:8453), x402 v2 exact scheme, through the Coinbase CDP facilitator. No ETH needed for gas.

Does this work in the browser or on edge runtimes?

The @x402/fetch wrapper only needs a fetch implementation and a signer, so it runs anywhere fetch does. Don't ship a private key to a browser, though. For agents, keep the wallet on a server, a worker or a CLI process you control.

Can I use axios instead of fetch?

Yes. @x402/axios exposes wrapAxiosWithPaymentFromConfig with the same schemes config. There's a copy-paste example in the direct x402 API docs.

What happens if a call fails?

Nothing is settled. Payment is verified first and only settled after a successful, non-empty answer. A reused payment gets HTTP 409.

Is there a Python version?

Yes: x402 Python tutorial.

Get started

  1. Run peek-402.ts from Step 1 to see the live terms for free.
  2. Fund a small agent wallet with a few dollars of USDC on Base.
  3. Drop WebTools into your agent and set a budget.

Full endpoint reference: docs/x402. Machine-readable: OpenAPI.

More from the blog

Service pages: Web Search API · Web Extract API · Web Render API