Skip to main content

Querying an Agent

After purchasing a payment plan, subscribers can generate X402 access tokens and use them to query AI agents. This guide explains how to get tokens and make authenticated requests.

Overview

The query flow consists of:
  1. Generate X402 Access Token: Get a payment-authorized token for agent access
  2. Make Authenticated Requests: Include the token in HTTP headers
  3. Receive Responses: Agent validates the token and processes the request

Get X402 Access Token

The X402 access token is a cryptographically signed credential that proves you have purchased access to an agent:

Token Parameters

The getX402AccessToken method accepts several optional parameters:

Card-Delegation Tokens (Fiat)

For plans that accept fiat payments, generate tokens using the nvm:card-delegation scheme. Pass X402TokenOptions with a CardDelegationConfig to specify the payment method and spending limits:

Auto-Detecting the Scheme

If you don’t know whether a plan uses crypto or fiat, use resolveScheme() to auto-detect from plan metadata:

CLI

Basic Example

Token Structure (X402 v2)

The access token is a JSON Web Token (JWT) containing an X402 v2 payment credential:

Make Requests with X402 Token

Using PAYMENT-SIGNATURE Header (X402 v2 Spec)

The X402 v2 specification defines the PAYMENT-SIGNATURE header for payment credentials:
Note: The A2A (Agent-to-Agent) protocol also uses the payment-signature header for authentication. For A2A integration details, see the A2A Integration guide.

Complete Query Example

Handling 402 Payment Required

If the token is invalid or credits are insufficient, agents return HTTP 402 with payment details:

MCP JSON-RPC Requests

For MCP-based agents, use JSON-RPC format:

Token Reuse

X402 access tokens can be reused for multiple requests until they expire or credits are exhausted:

Check Balance Before Querying

To avoid 402 errors, check your balance before making requests:

Best Practices

  1. Token Caching: Generate tokens once and reuse them for multiple requests
  2. Balance Checking: Check balance before generating tokens
  3. Error Handling: Always handle 402 Payment Required responses
  4. HTTPS Only: Never send tokens over unencrypted HTTP
  5. Token Expiration: Regenerate tokens if you receive 402 errors
  6. Header Standard: Prefer PAYMENT-SIGNATURE header (X402 v2 spec)

Source References:
  • src/x402/token.ts (getX402AccessToken method)
  • tests/e2e/test_x402_e2e.test.ts (lines 114-133, token generation)
  • tests/e2e/test_payments_e2e.test.ts (MockAgentServer, lines 72-127)