SpendPreflightdocs
Guides / developer guide

Cap your agent's Brave x402 search spend with Spend Policy

Review each search quote, reserve a bounded budget and keep human approval before your existing wallet signs.

Operator-maintained documentation
Live features and staging previews are distinguished. Index coverage is not yet available.

What Brave announced

Brave announced x402 Search API payments on November 12, 2026. Its current documentation lists web search, LLM Context, news, image, video and local endpoints at 5,000 native-USDC base units ($0.005) per request on Base. No Brave API account or key is required for this payment path. The request-specific 402 is authoritative; a published price is not a permanent guarantee.

Set two budgets before paying

This example caps each Brave search at $0.005 and reserves at most $0.05 per UTC day: nominally ten searches at the documented price. That is the search budget only. Spend Policy is a free SDK helper; its strict remote check uses our separate paid preflight service at $0.02 per check, so ten successful checks plus ten searches can cost $0.25 before any other fees. If that overhead does not suit your task, keep an explicit hard cap in the existing wallet and use the free local preview for review; do not describe a preview as the strict remote-checked path.

Review the actual recipient and exact offer

Obtain a fresh x402 v2 challenge for the intended HTTPS Brave URL using your already-authorized client. Human-review the actual payTo, exact scheme, Base network eip155:8453, native USDC asset and atomic amount. Brave does not publish payTo in its OpenAPI document. Fill the allowlist from the reviewed current challenge, never a guessed address or this guide. A changed payee, asset, chain, amount or URL needs a new review. Missing or unsupported evidence holds.

Install once at the payment boundary

Use spendpreflight@0.4.0 with an existing hookable x402 client. Keep its wallet caps, signer and credentials outside this helper. The sample attaches before payment creation, requires an explicit human approval for every search, and aborts on hold/block or terms changed during review. The separate screeningFetch must be a host-provided fee transport with its own human approval and budget. It must not recursively use the guarded Brave client. With no screening transport the SDK holds without a network request. A remote check sends the selected payment terms and resource URL to SpendPreflight; review the search query in that URL before sharing it.

brave-spend-policy.mjs
// No wallet, signer, target fetch or payment is created here.
import {createSpendPolicy} from 'spendpreflight'; // pin spendpreflight@0.4.0
import {randomUUID} from 'node:crypto';

const origin = 'https://search.agent.s.brave.app';
const paths = new Set(['/res/v1/web/search','/res/v1/llm/context','/res/v1/news/search',
  '/res/v1/videos/search','/res/v1/images/search','/res/v1/local/place_search',
  '/res/v1/local/pois','/res/v1/local/descriptions']);
const asset = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';

export function braveSpendPolicy(reviewedPayee) {
  if (!/^0x[\da-f]{40}$/i.test(reviewedPayee) || /^0x0{40}$/i.test(reviewedPayee))
    throw Error('Supply the actual payTo reviewed by the human; never invent it.');
  return {version:1,dailyCapUsd:0.05,maxPerCallUsd:0.005,holdAboveUsd:0.005,
    merchantAllowlist:[reviewedPayee],merchantBlocklist:[],networkAllowlist:['eip155:8453'],
    assetAllowlist:[{network:'eip155:8453',asset}]};
}

/** Install once on an existing, authorized x402 v2 client, before signing.
 * screeningFetch is the HOST'S separate bounded, human-approved $0.02 preflight
 * fee transport; never use this same guarded search client recursively.
 * Omit it to demonstrate offline hold. Keep wallet caps and a durable ledger.
 */
export function installBraveSpendPolicy(client, reviewedPayee,
  {screeningFetch,approveSearch,now=Date.now}={}) {
  if (typeof client?.onBeforePaymentCreation !== 'function') throw Error('Hookable existing x402 client required');
  const controller = createSpendPolicy(braveSpendPolicy(reviewedPayee),
    {now,...(screeningFetch ? {remote:{fetch:screeningFetch}} : {})});
  client.onBeforePaymentCreation(async ctx => {
    try {
      const before = JSON.stringify({challenge:ctx.paymentRequired,selected:ctx.selectedRequirements});
      const resource = new URL(ctx.paymentRequired?.resource?.url);
      if (resource.origin !== origin || !paths.has(resource.pathname) || resource.username || resource.password || resource.hash)
        return {abort:true,reason:'Brave resource outside reviewed origin/path'};
      const verdict = await controller.check(ctx.paymentRequired,ctx.selectedRequirements);
      if (verdict.decision !== 'allow') return {abort:true,reason:'Spend Policy '+verdict.decision};
      if (typeof approveSearch !== 'function') return {abort:true,reason:'Fresh human search approval required; reservation retained'};
      const createdAt = now();
      const review = Object.freeze({requestId:randomUUID(),resource:resource.href,
        requirement:Object.freeze(structuredClone(ctx.selectedRequirements)),
        searchAmountUsd:verdict.amountUsd,separateScreeningFeeUsd:0.02,
        expiresAt:createdAt+120000});
      const allowed = await approveSearch(review);
      if (allowed !== true || now() < createdAt || now() > review.expiresAt)
        return {abort:true,reason:'Human approval missing or expired; reservation retained'};
      if (before !== JSON.stringify({challenge:ctx.paymentRequired,selected:ctx.selectedRequirements}))
        return {abort:true,reason:'Payment changed during review; reservation retained'};
      // The existing client signs only after this hook. This helper never signs.
    } catch {
      return {abort:true,reason:'Policy or approval unavailable; no automatic retry'};
    }
  });
  return controller;
}
Download tested source

Budgets have practical limits

Create one controller and reuse it; creating one per call resets the in-process budget. Reservations are not settlement accounting and remain consumed when the user declines or a signed request has an unknown outcome. Persist a durable operation/settlement journal and enforce a wallet-wide cap across workers and restarts. A human approval is not permission to bypass hold/block, and installing the package does not automatically intercept an MCP payment tool or a model proxy.

Keep retries under the original operation

A new wallet request may create a new purchase. If a paid response is lost, inspect that same operation and existing wallet evidence before deciding whether another authorization is appropriate. Do not automatically refresh a quote, re-sign, retry payment or switch a payment rail. Keep the final signed resource and selected amount/payee/network/asset identical to what the hook and human reviewed.

Evidence for this guide

The example is exercised offline against the real SDK0.4.0 with mock screening responses and human decisions. Tests cover the daily cap, changed terms, approval expiry, unavailable screening and unsupported offers. No Brave search, wallet, signature, payment or account setup was executed for this guide. This is a tested application composition pattern, not a live Brave wallet integration or endorsement.