ATP Protocol is a payment-gated agent execution API that makes agent-to-agent payments and “pay to unlock results” easy on Solana, with a simple client integration (two endpoints + a Solana payment).
ATP-Protocol is an early-stage Python project in the AI payments / x402 ecosystem, focused on agent-commerce, agent-framework, agent-to-agent, agents. It currently has 4 GitHub stars and 1 forks, and sits alongside related tools like daydreams, x402-deploy, dna-x402.
The premier agent-to-agent payment protocol and foundational framework to empower the agent economy.
ATP (Agent Trade Protocol) is the premier agent-to-agent payment protocol that will be the foundational framework to empower the agent economy. Designed to overcome x402's issues and make agent-to-agent payments dynamic and simple, ATP enables automatic payment processing for agent services on the Solana blockchain. The protocol provides a middleware layer that automatically deducts payments from user wallets based on token usage, ensuring secure and transparent transactions.
ATP Protocol operates through three main components:
sequenceDiagram
participant Client
participant Server
participant Middleware
participant SettlementService
participant Solana
Client->>Server: POST /v1/chat<br/>(with wallet key)
Server->>Server: Process request
Server->>Middleware: Response with usage data
Middleware->>Middleware: Encrypt response
Middleware->>SettlementService: Parse usage & calculate payment
SettlementService->>SettlementService: Calculate payment amount
SettlementService->>Solana: Create & sign transaction
Solana-->>SettlementService: Transaction confirmed
SettlementService-->>Middleware: Payment confirmed (tx signature)
Middleware->>Middleware: Decrypt response
Middleware->>Client: Return decrypted response<br/>(with settlement details)
pip install atp-protocol
Add ATP middleware to your FastAPI server:
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from atp.middleware import ATPSettlementMiddleware
from atp.schemas import PaymentToken
app = FastAPI(title="My ATP-Protected API")
# Add ATP Settlement Middleware
app.add_middleware(
ATPSettlementMiddleware,
allowed_endpoints=["/v1/chat", "/v1/completions"],
input_cost_per_million_usd=10.0, # $10 per million input tokens
output_cost_per_million_usd=30.0, # $30 per million output tokens
recipient_pubkey="YourSolanaWalletPublicKeyHere", # Your wallet
payment_token=PaymentToken.SOL, # SOL or USDC
wallet_private_key_header="x-wallet-private-key",
require_wallet=True,
)
@app.post("/v1/chat")
async def chat(request: dict):
"""Agent endpoint with automatic payment processing."""
message = request.get("message", "")
# Agent logic implementation
response_text = "Agent response here"
# Return response with usage data
# Middleware handles payment processing automatically
return JSONResponse(content={
"response": response_text,
"usage": {
"input_tokens": 100,
"output_tokens": 50,
"total_tokens": 150
}
})
from atp.client import ATPClient
# Initialize client with wallet
client = ATPClient(
wallet_private_key="[1,2,3,...]", # Your wallet private key
settlement_service_url="https://facilitator.swarms.world"
)
# Make request with automatic payment processing
response = await client.post(
url="https://api.example.com/v1/chat",
json={"message": "Hello!"}
)
print(response["response"]) # Agent output
print(response["atp_settlement"]) # Payment details
Below is a comprehensive table of example integrations and usage:
| Category | Example Link | Description |
|---|---|---|
| Framework Integration | Swarms Framework | Enterprise multi-agent orchestration |
| Framework Integration | LangChain | Popular Python LLM framework |
| Framework Integration | AutoGen | Microsoft's multi-agent framework |
| Framework Integration | CrewAI | Multi-agent orchestration |
| Framework Integration | Anthropic | Claude API integration |
| Category | Example Link | Description |
|---|---|---|
| Client Example | Health Check | Check settlement service status |
| Client Example | Parse Usage | Parse usage from various formats |
| Client Example | Calculate Payment | Calculate payment without executing |
| Client Example | Execute Settlement | Direct settlement execution |
| Client Example | Make Request | Request ATP-protected endpoints |
| Server Example | Basic Example | Simple middleware setup |
| Server Example | Full Flow | Complete payment flow |
| Server Example | Settlement Service | Direct service usage |
See examples/README.md for complete documentation.
| Feature | Description |
|---|---|
| Response Encryption | Agent responses are encrypted before payment verification, ensuring users cannot see output until payment is confirmed on-chain. |
| Payment Verification | Responses are only decrypted after successful blockchain transaction confirmation (status="paid" with valid transaction signature). |
| Error Handling | Failed payments result in encrypted responses with error details, preventing unauthorized access to agent output. |
Payments are automatically split between:
recipient_pubkeyThe middleware automatically supports multiple usage formats:
{
"usage": {
"prompt_tokens": 100,
"completion_tokens": 50,
"total_tokens": 150
}
}
{
"usage": {
"input_tokens": 100,
"output_tokens": 50
}
}
{
"usageMetadata": {
"promptTokenCount": 100,
"candidatesTokenCount": 50,
"totalTokenCount": 150
}
}
The settlement service automatically detects and parses these formats, so you can use any format your agent API returns.
# Settlement Service
ATP_SETTLEMENT_URL="https://facilitator.swarms.world" # Default
ATP_SETTLEMENT_TIMEOUT=300.0 # 5 minutes (default)
# Encryption (optional - generates new key if not set)
ATP_ENCRYPTION_KEY="base64-encoded-fernet-key"
app.add_middleware(
ATPSettlementMiddleware,
allowed_endpoints=["/v1/chat"], # Endpoints to protect
input_cost_per_million_usd=10.0, # Pricing
output_cost_per_million_usd=30.0,
recipient_pubkey="YourWalletPublicKey", # Required
payment_token=PaymentToken.SOL, # SOL or USDC
wallet_private_key_header="x-wallet-private-key",
require_wallet=True, # Require wallet for payment
settlement_service_url="https://facilitator.swarms.world",
settlement_timeout=300.0,
fail_on_settlement_error=False, # Graceful error handling
)
The ATPSettlementMiddleware class provides automatic payment processing for FastAPI endpoints.
Key Features:
See Middleware Documentation for complete API reference.
The ATPClient class provides a simple interface for:
See Client Documentation for complete API reference.
The settlement service (facilitator) handles:
See Settlement Service Documentation for complete API reference.
If wallet private key is missing and require_wallet=True:
{
"detail": "Missing wallet private key in header: x-wallet-private-key"
}
Status: 401 Unauthorized
If payment fails and fail_on_settlement_error=False (default):
{
"response": "encrypted_data_here",
"response_encrypted": true,
"atp_settlement": {
"error": "Settlement failed",
"detail": "Insufficient funds",
"status_code": 400
},
"atp_settlement_status": "failed",
"atp_message": "Agent response is encrypted. Payment required to decrypt."
}
The response remains encrypted until payment succeeds.
Wallet Security: Never log or persist wallet private keys. Use them only in-memory for transaction signing.
Error Handling: Use fail_on_settlement_error=False for graceful degradation. Check atp_settlement_status in responses to handle payment failures appropriately.
Timeout Configuration: Increase settlement_timeout if you experience timeout errors. Blockchain confirmation can take time depending on network conditions.
Usage Data: Always include accurate token counts in your responses. Middleware skips settlement if usage data cannot be parsed.
Testing: Use testnet wallets and small amounts for testing. Verify transactions on Solana explorer before production deployment.
Monitoring: Monitor atp_settlement_status in responses to track payment success rates and identify potential issues.
| Resource | Description |
|---|---|
| Full Documentation | Complete API documentation |
| Settlement Service API | Facilitator API reference |
| Middleware Reference | Middleware configuration |
| Client Reference | Client API reference |
| ATP Vision | Protocol vision and roadmap |
Contributions are welcome. Please read our contributing guidelines and submit pull requests for review.
git clone https://github.com/The-Swarm-Corporation/ATP-Protocol.git
cd ATP-Protocol
pip install -e .
pytest tests/
# Format code
black .
# Lint code
ruff check .
This project is licensed under the MIT License. See the LICENSE file for details.
If you use ATP (Agent Trade Protocol) in your research or software, please cite The Swarm Corporation:
@software{atp_protocol,
title = {ATP: Agent Trade Protocol},
author = {{The Swarm Corporation}},
year = {2025},
url = {https://github.com/The-Swarm-Corporation/ATP-Protocol},
note = {Agent-to-agent payment protocol for the agent economy}
}
The Swarm Corporation. ATP: Agent Trade Protocol. https://github.com/The-Swarm-Corporation/ATP-Protocol
Built by The Swarm Corporation to enable agent-to-agent commerce on the blockchain.
For additional information, see the examples directory or the complete documentation.
Open Source AI trading agent that operates autonomously across 1000+ markets - Polymarket, Kalshi, Binance, Hyperliquid, Solana DEXs, 5 EVM chains. Scans for edge, executes instantly, manages risk while you sleep. Agent commerce protocol for machine-to-machine payments. Self-hosted. Built on Claude.
DePIN for Vintage Hardware — Proof-of-Antiquity blockchain where old machines outmine new ones. AI-powered hardware fingerprinting, 15+ CPU architectures, Solana bridge (wRTC). $0 VC.
Drop-in OpenAI Python client with transparent x402 payment support.
Client SDK for the Vybe x402 API. Pay-per-call USDC over HTTP and prepaid-credit WebSocket streaming for Vybe's Solana analytics API. Built for AI agents.
Autonomous AI BD Agent for SolCex Exchange: 24/7 Cross-Chain Token Scoring & Payments 2026
Drop-in OpenAI Typescript client with transparent x402 payment support.