> ## Documentation Index
> Fetch the complete documentation index at: https://docs.keenable.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Every page is listed in https://docs.keenable.ai/llms.txt. To pick a product for a job, read https://docs.keenable.ai/choose.md
> Setup steps for agents, covering the SDKs, the MCP server and the CLI: https://docs.keenable.ai/skill.md
> Keenable search and fetch work without an API key. To add them to code, use the official SDK for the project's language: https://docs.keenable.ai/sdks.md
> Without a key, call POST https://api.keenable.ai/v1/search/public or GET https://api.keenable.ai/v1/fetch/public with an X-Keenable-Title header that names your app.
> With a key, send it in the X-API-Key header and read it from the KEENABLE_API_KEY environment variable. Never ask a user to paste a key into chat. Every access method: https://docs.keenable.ai/auth.md
> To get an API key without the console, use device login: https://docs.keenable.ai/authentication.md#device-login
> MCP server: https://api.keenable.ai/mcp (no key, or X-API-Key; keyless Codex uses https://api.keenable.ai/mcp-public), or https://api.keenable.ai/mcp-oauth for OAuth sign-in. These docs are an MCP server at https://docs.keenable.ai/mcp and the OpenAPI spec is at https://docs.keenable.ai/api-reference/openapi.json
> Keenable searches and fetches public web pages. If a question needs no web information, skip the call.
> On 402 with an API key (code insufficient_credits), stop and ask a human to add credits; don't retry. On 429, wait the number of seconds in Retry-After, then retry. Before you ship, follow https://docs.keenable.ai/production.md
> Every error, with its cause and fix, is in https://docs.keenable.ai/errors.md and moving from another search API is covered in https://docs.keenable.ai/migrate.md
> Before you compare Keenable with another search API, read https://docs.keenable.ai/guides/evaluate-search-apis.md

# Let an agent pay per search with x402

> Give an agent web search and fetch with no account or API key: it pays each call in USDC on Base over x402, and your client refuses offers above a cap.

Let an agent with a wallet search and fetch without an account, an API key or a prepaid balance. Each request answers `402` with an offer. Your x402 client signs a USDC payment on Base and sends the request again. This recipe adds a price cap, so the client refuses any offer above \$0.01 instead of signing whatever amount it's asked for.

## Recipe prompt

Paste this into your coding agent to have it build the recipe in your project:

```text Recipe prompt theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
Read https://docs.keenable.ai/recipes/agent-pays-with-x402.md and add a paid search and fetch helper to this TypeScript project with @x402/fetch, @x402/evm and viem. Read WALLET_PRIVATE_KEY from the environment and never log it. Keep the paymentRequirementsSelector that refuses any offer that isn't USDC on eip155:8453 or that costs more than 10000 base units. Don't run it against a funded wallet: show me the code and the curl command that prints the unpaid offer.
```

## What you build

| Piece | What it does |
| - | - |
| A wallet | Holds a small USDC balance on Base. No ETH for gas is needed. |
| An x402 client | `wrapFetchWithPaymentFromConfig` from `@x402/fetch`. It reads the `402` offer, signs the payment and retries with the `PAYMENT-SIGNATURE` header. |
| A price cap | A `paymentRequirementsSelector` that accepts only USDC on Base (`eip155:8453`) at 10,000 base units or less, which is \$0.01. |
| A receipt | The `PAYMENT-RESPONSE` header of each paid response. `decodePaymentResponseHeader` reads the transaction hash from it. |

| Endpoint | Method | Price per request that succeeds |
| - | - | - |
| `/v1/x402/search` | `GET`, `POST` | \$0.01 |
| `/v1/x402/fetch` | `GET` | \$0.01 |
| `/v1/x402/select` | `POST` | \$0.10 |

A SELECT query costs 100,000 base units, so the cap in this recipe refuses it. Raise `MAX_AMOUNT` if your agent should run SELECT queries.

## When it runs

On every call. A paid call is two requests: the first returns `402` with the offer, and the retry carries the payment. Keenable runs the request, settles the payment on-chain and returns the result only after settlement succeeds.

## Code

The TypeScript tab pays for one search and one fetch of the top result, and prints the transaction hash of each payment. The curl tab asks without paying and prints the offer:

```typescript TypeScript theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
// npm install @x402/fetch @x402/evm viem
import { decodePaymentResponseHeader, wrapFetchWithPaymentFromConfig, type SelectPaymentRequirements } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

const MAX_AMOUNT = 10_000n; // USDC base units (6 decimals): $0.01
const USDC_BASE = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"; // USDC contract on Base

// Pay only USDC on Base, and never more than MAX_AMOUNT per request
const capped: SelectPaymentRequirements = (_version, accepts) => {
  const offer = accepts.find(
    (a) => a.network === "eip155:8453" && a.asset.toLowerCase() === USDC_BASE && BigInt(a.amount) <= MAX_AMOUNT,
  );
  if (!offer) throw new Error(`No USDC offer at or under ${MAX_AMOUNT} base units`);
  return offer;
};

const account = privateKeyToAccount(process.env.WALLET_PRIVATE_KEY as `0x${string}`);
const pay = wrapFetchWithPaymentFromConfig(fetch, {
  schemes: [{ network: "eip155:8453", client: new ExactEvmScheme(account) }],
  paymentRequirementsSelector: capped,
});

async function paid(url: string) {
  const res = await pay(url);
  if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
  const receipt = decodePaymentResponseHeader(res.headers.get("PAYMENT-RESPONSE")!);
  return { body: await res.json(), tx: receipt.transaction };
}

async function main() {
  const api = "https://api.keenable.ai/v1/x402";
  const search = await paid(`${api}/search?query=${encodeURIComponent("x402 payment protocol specification")}&max_results=3`);
  console.log(`search: ${search.body.results.length} results, tx ${search.tx}`);

  const top = search.body.results[0];
  if (!top) return console.log("no results, so no fetch");
  const url = top.url;
  const page = await paid(`${api}/fetch?url=${encodeURIComponent(url)}&max_chars=2000`);
  console.log(`fetch: ${page.body.content.length} chars from ${url}, tx ${page.tx}`);
}

main();
```

```bash curl theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
# Ask without paying: the 402 response carries the offer
curl -s -i "https://api.keenable.ai/v1/x402/search?query=x402+payment+protocol+specification&max_results=3" \
  | grep -i '^payment-required:' | cut -d' ' -f2 | tr -d '\r' | base64 --decode | jq '.accepts[0] | {network, amount, asset, maxTimeoutSeconds}'
```

Install the three packages with `npm install @x402/fetch @x402/evm viem`, and set `WALLET_PRIVATE_KEY` to the key of a wallet you funded for this.

## Example output

The curl tab decodes the `PAYMENT-REQUIRED` header of the `402` response and prints the first offer:

```json Example output theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
{
  "network": "eip155:8453",
  "amount": "10000",
  "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  "maxTimeoutSeconds": 300
}
```

`amount` is in USDC base units, 6 decimals, so `10000` is \$0.01. `asset` is the USDC contract on Base. The TypeScript tab prints one line per paid call, with the number of results or the page length, and the transaction hash.

## Production notes

| Situation | What happens | What to do |
| - | - | - |
| Rate limits | 50 paid requests per second per wallet, and 100 requests per second per IP address, with no hourly cap. The per-IP limit counts the offer request and the paid retry. | Keep each batch under both limits. See [Rate limits](https://docs.keenable.ai/rate-limits.md). |
| `429` | The response carries `Retry-After` and the code `paid_rate_limit_per_second`. | Wait that many seconds, then retry with a new payment. |
| `402` after you paid | The payment was rejected, or settlement failed (`Payment settlement failed`). Keenable withholds the result. | Retry with a new payment. Each signed payment is good for one request. |
| An error response | Any status of `400` or above cancels the payment before it settles. | Nothing is charged. Fix the request from the error body. |
| An offer above the cap | The selector throws, so nothing is signed. | Check the offer. Raise the cap only on purpose. |
| `451` | Pay-per-request access isn't offered in the caller's region. Keenable returns it before any offer. | Nothing is signed or charged. See [Errors](https://docs.keenable.ai/pay-per-request.md#errors) for the regions. |

Keep the wallet balance small. If your agent calls Keenable regularly, an API key costs less: \$4 per 1,000 requests from a prepaid balance rather than \$10. See [Pay per request](https://docs.keenable.ai/pay-per-request.md).

## Next steps

* [Pay per request](https://docs.keenable.ai/pay-per-request.md): the payment flow, every error and ZeroClick prepaid credits.
* [Enrich a list with SELECT](https://docs.keenable.ai/recipes/enrich-a-list-with-select.md): a SELECT query you can send over x402.
* [Research loop](https://docs.keenable.ai/recipes/research-loop.md): the searches and fetches an agent pays for.
* [Recipes](https://docs.keenable.ai/recipes.md): every recipe on one page.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.