Skip to main content

x402 payment protocol integration for CrewAI - enable AI agents to pay for APIs with USDC

Project description

crewai-x402

PyPI version License: MIT

Enable CrewAI agents to pay for APIs with USDC using the x402 protocol.

crewai-x402 integrates the x402 payment protocol with CrewAI, allowing your AI agent crews to autonomously access paid APIs without managing API keys or subscriptions.

What is x402?

x402 is the HTTP-native payment protocol that finally implements the 402 Payment Required status code. Instead of API keys and monthly subscriptions, software pays software—per request, in USDC, with cryptographic proof.

How it works:

  1. Agent requests a resource
  2. Server returns 402 Payment Required with price info
  3. Agent signs a USDC payment authorization (EIP-3009)
  4. Agent retries with payment proof
  5. Server settles on-chain, returns data

All in a single HTTP round-trip.

Installation

pip install crewai-x402

Quick Start

import os
from crewai import Agent, Crew, Task
from crewai_x402 import X402Wallet, X402Tool

# 1. Create a wallet with a USDC budget
wallet = X402Wallet(
    private_key=os.environ["WALLET_PRIVATE_KEY"],
    network="eip155:8453",  # Base mainnet (CAIP-2 format)
    budget_usd=10.00
)

# 2. Create the payment tool
payment_tool = X402Tool(wallet=wallet)

# 3. Add to your agent
researcher = Agent(
    role="Research Analyst",
    goal="Find accurate data using any available source",
    backstory="You have access to both free and paid APIs.",
    tools=[payment_tool],
)

# 4. Agent can now pay for premium data
task = Task(
    description="Get the premium analysis from https://sandbox.agentrails.io/api/x402/protected/analysis",
    agent=researcher,
)

crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()

Try It with the Sandbox

The AgentRails Sandbox is a free test environment with x402-protected endpoints you can hit right away. No signup required to see the 402 flow in action.

1. Check available endpoints and pricing

curl https://sandbox.agentrails.io/api/x402/pricing
{
  "endpoints": [
    { "resource": "/api/x402/protected/analysis", "amountUsdc": 0.01 },
    { "resource": "/api/x402/protected/data", "amountUsdc": 0.001 }
  ],
  "supportedNetworks": [
    "eip155:5042002", "eip155:84532", "eip155:11155111",
    "eip155:8453", "eip155:1"
  ],
  "payTo": "0x6255d8dd3f84ec460fc8b07db58ab06384a2f487"
}

2. See a 402 response

curl -i https://sandbox.agentrails.io/api/x402/protected/analysis
# → 402 Payment Required
# → PAYMENT-REQUIRED: <base64-encoded payment requirements>

3. Point your crew at the sandbox

wallet = X402Wallet(
    private_key=os.environ["WALLET_PRIVATE_KEY"],
    network="eip155:84532",  # Base Sepolia testnet (CAIP-2 format)
    budget_usd=1.00
)

payment_tool = X402Tool(wallet=wallet)

researcher = Agent(
    role="Research Analyst",
    goal="Gather data from premium APIs",
    tools=[payment_tool],
)

task = Task(
    description="Get the analysis from https://sandbox.agentrails.io/api/x402/protected/analysis",
    agent=researcher,
)

crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()

Sandbox Endpoints

Endpoint Cost Description
GET /api/x402/protected/analysis $0.01 USDC AI analysis (premium)
GET /api/x402/protected/data $0.001 USDC Data endpoint (micropayment)
GET /api/x402/pricing Free Pricing for all protected endpoints
GET /api/x402/stats Free Payment statistics

Full API reference: sandbox.agentrails.io/swagger

Features

Automatic Payment Handling

The X402Tool automatically detects 402 responses and handles payment negotiation:

tool = X402Tool(
    wallet=wallet,
    auto_pay=True,  # Automatically pay when within budget
    timeout=30.0,   # Request timeout in seconds
)

Budget Control

Set spending limits at the wallet level:

wallet = X402Wallet(
    private_key=key,
    network="eip155:8453",
    budget_usd=5.00  # Crew can't spend more than $5
)

# Check remaining budget
print(f"Remaining: ${wallet.remaining_usd}")

# Check if can afford a specific amount
if wallet.can_afford(0.01):
    print("Can afford $0.01 request")

Per-Request Price Limits

Limit how much an agent can pay for a single request:

# When calling the tool directly
result = tool._run(
    url="https://sandbox.agentrails.io/api/x402/protected/analysis",
    max_price_usd=0.05  # Won't pay more than $0.05 for this request
)

Payment History

Track all payments made by the wallet:

for payment in wallet.payments:
    print(f"{payment.resource_url}: ${payment.amount_usd}")

# Get summary
summary = wallet.get_payment_summary()
print(f"Total spent: ${summary['spent_usd']}")
print(f"Payments made: {summary['payment_count']}")

Multi-Network Support

Supports multiple EVM networks using CAIP-2 identifiers:

# Base (recommended - low fees)
wallet = X402Wallet(private_key=key, network="eip155:8453")

# Ethereum
wallet = X402Wallet(private_key=key, network="eip155:1")

# Testnets
wallet = X402Wallet(private_key=key, network="eip155:84532")   # Base Sepolia
wallet = X402Wallet(private_key=key, network="eip155:5042002") # Arc testnet

Legacy network names (base-mainnet, base-sepolia, etc.) are still accepted for backwards compatibility.

API Reference

X402Wallet

X402Wallet(
    private_key: str,      # Hex-encoded private key
    network: str,          # CAIP-2 network ID (e.g., "eip155:8453")
    budget_usd: float,     # Maximum USD to spend
)

Properties:

  • address - Wallet address
  • spent_usd - Total USD spent
  • remaining_usd - Remaining budget
  • payments - List of PaymentRecord objects

Methods:

  • can_afford(amount_usd) - Check if budget allows payment
  • sign_payment(to, amount, valid_before) - Sign EIP-3009 authorization
  • get_payment_summary() - Get spending summary dict
  • reset_budget(new_budget) - Reset budget and clear history

X402Tool

X402Tool(
    wallet: X402Wallet,    # Wallet for payments
    auto_pay: bool = True, # Auto-pay when within budget
    timeout: float = 30.0, # HTTP timeout
)

Tool Input Fields:

  • url (required) - URL to request
  • method - HTTP method (default: "GET")
  • body - Request body
  • headers - Additional headers
  • max_price_usd - Per-request price limit

Networks

V2 uses CAIP-2 network identifiers:

Network ID (CAIP-2) Chain ID Environment Legacy Alias
eip155:8453 8453 Production base-mainnet
eip155:84532 84532 Testnet base-sepolia
eip155:1 1 Production ethereum-mainnet
eip155:11155111 11155111 Testnet ethereum-sepolia
eip155:5042002 5042002 Testnet arc-testnet

Security Considerations

  1. Never commit private keys - Use environment variables or secret managers
  2. Set appropriate budgets - Limit what crews can spend
  3. Use testnets first - Test with eip155:84532 (Base Sepolia) before mainnet
  4. Monitor spending - Check wallet.get_payment_summary() regularly

Examples

See the examples/ directory:

  • research_crew.py - Research crew with payment capability

How It Differs From API Keys

API Keys x402
1 key per service 1 wallet for all services
Monthly subscriptions Pay per request
Human signup required Zero onboarding
Credential rotation No credentials to leak
Service-level limits Agent-level budgets

Related Packages

Resources

License

MIT License - see LICENSE for details.

Contributing

Contributions welcome! Please read our contributing guidelines and submit PRs to the GitHub repository.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

crewai_x402-0.2.0.tar.gz (15.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

crewai_x402-0.2.0-py3-none-any.whl (12.4 kB view details)

Uploaded Python 3

File details

Details for the file crewai_x402-0.2.0.tar.gz.

File metadata

  • Download URL: crewai_x402-0.2.0.tar.gz
  • Upload date:
  • Size: 15.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for crewai_x402-0.2.0.tar.gz
Algorithm Hash digest
SHA256 a0fcaa00f5cf9462cd73b1ef765dc55ec245a38a3f0a6c792c8c50d0aa2e5ec4
MD5 1d8c3ccb6be74d73a4228d4c3c11e92c
BLAKE2b-256 1eef1fd25837076cec4c330c781c3d1d9ef666f9c62aa5c3fc64f9c303a84b49

See more details on using hashes here.

File details

Details for the file crewai_x402-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: crewai_x402-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 12.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for crewai_x402-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1139712d7812d302de3418216e206ead3f109131b4d4a4c94f4c1acb6ff74228
MD5 264dac2c888c6df3136ca77915df7c0d
BLAKE2b-256 e32d2c695017362047bb5b5787a9bface12c824df1ee23ef1f3e7ebdb273f8b0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page