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:- Generate X402 Access Token: Get a payment-authorized token for agent access
- Make Authenticated Requests: Include the token in HTTP headers
- 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
ThegetX402AccessToken method accepts several optional parameters:
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 thePAYMENT-SIGNATURE header for payment credentials:
Using Authorization Header (Alternative)
Many agents also support the standard Authorization header with Bearer scheme: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
- Token Caching: Generate tokens once and reuse them for multiple requests
- Balance Checking: Check balance before generating tokens
- Error Handling: Always handle 402 Payment Required responses
- HTTPS Only: Never send tokens over unencrypted HTTP
- Token Expiration: Regenerate tokens if you receive 402 errors
- Header Standard: Prefer
PAYMENT-SIGNATUREheader (X402 v2 spec)
Related Documentation
- Payments and Balance - How to purchase plans and check credits
- Validation of Requests - How agents validate tokens (for builders)
- X402 Protocol - Complete X402 specification
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)