Skip to main content

ATP: Agent Trade Protocol

The premier agent-to-agent payment protocol and foundational framework to empower the agent economy.

Python 3.10+ License: MIT Documentation

Overview

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.

Key Features

  • Security: Response encryption ensures users cannot access output until payment is confirmed on-chain
  • Automation: Zero-configuration payment processing through middleware integration
  • Decentralization: All payments executed on Solana blockchain with full transaction visibility
  • Format Flexibility: Supports multiple usage formats (OpenAI, Anthropic, Google, etc.) automatically
  • Transparency: Automatic payment splitting between treasury and recipient wallets

Architecture

ATP Protocol operates through three main components:

  1. Settlement Service (Facilitator): Centralized service handling all settlement logic, usage parsing, payment calculation, and blockchain transaction execution
  2. Middleware: FastAPI middleware that intercepts API responses, extracts usage data, encrypts responses, executes payments, and decrypts responses only after payment confirmation
  3. Client: User-facing client that simplifies making requests to ATP-protected endpoints and interacting with the settlement service

Request Flow

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)

Quick Start

Installation

pip install atp-protocol

Server Setup (5 minutes)

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
        }
    })

Client Usage

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

Examples

Below is a comprehensive table of example integrations and usage:

Framework Integrations

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

Client & Server Example Scripts

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.

Security Features

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.

Payment Structure

Payments are automatically split between:

  • Treasury: Receives processing fee (default 5%, configured on settlement service)
  • Recipient: Receives remainder (95% by default) - your wallet specified via recipient_pubkey

Supported Payment Tokens

  • SOL (Solana native token)
  • USDC (USD Coin on Solana)

Usage Data Formats

The middleware automatically supports multiple usage formats:

OpenAI Format

{
  "usage": {
    "prompt_tokens": 100,
    "completion_tokens": 50,
    "total_tokens": 150
  }
}

Anthropic Format

{
  "usage": {
    "input_tokens": 100,
    "output_tokens": 50
  }
}

Google/Gemini Format

{
  "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.

Configuration

Environment Variables

# 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"

Middleware Configuration

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
)

API Reference

Middleware

The ATPSettlementMiddleware class provides automatic payment processing for FastAPI endpoints.

Key Features:

  • Automatic usage parsing from multiple formats
  • Response encryption before payment
  • Payment execution via settlement service
  • Response decryption after payment confirmation

See Middleware Documentation for complete API reference.

Client

The ATPClient class provides a simple interface for:

  • Making requests to ATP-protected endpoints
  • Interacting with the settlement service directly
  • Parsing usage data
  • Calculating payments
  • Executing settlements

See Client Documentation for complete API reference.

Settlement Service

The settlement service (facilitator) handles:

  • Usage parsing from various formats
  • Payment calculation
  • Blockchain transaction creation and execution
  • Transaction confirmation

See Settlement Service Documentation for complete API reference.

Development

Requirements

  • Python 3.10+
  • FastAPI (for middleware)
  • Solana wallet (for payments)

Installation from Source

git clone https://github.com/The-Swarm-Corporation/ATP-Protocol.git
cd ATP-Protocol
pip install -e .

Running Tests

pytest tests/

Code Quality

# Format code
black .

# Lint code
ruff check .

Error Handling

Missing Wallet Key

If wallet private key is missing and require_wallet=True:

{
  "detail": "Missing wallet private key in header: x-wallet-private-key"
}

Status: 401 Unauthorized

Payment Failure

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.

Best Practices

  1. Wallet Security: Never log or persist wallet private keys. Use them only in-memory for transaction signing.

  2. Error Handling: Use fail_on_settlement_error=False for graceful degradation. Check atp_settlement_status in responses to handle payment failures appropriately.

  3. Timeout Configuration: Increase settlement_timeout if you experience timeout errors. Blockchain confirmation can take time depending on network conditions.

  4. Usage Data: Always include accurate token counts in your responses. Middleware skips settlement if usage data cannot be parsed.

  5. Testing: Use testnet wallets and small amounts for testing. Verify transactions on Solana explorer before production deployment.

  6. Monitoring: Monitor atp_settlement_status in responses to track payment success rates and identify potential issues.

Resources

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

Contributing

Contributions are welcome. Please read our contributing guidelines and submit pull requests for review.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Acknowledgments

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.

Metadata

Release files for atp-protocol 1.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for atp-protocol 1.4.0
File Size Uploaded
atp_protocol-1.4.0.tar.gz 35.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for atp-protocol 1.4.0
File Interpreter ABI Platform
atp_protocol-1.4.0-py3-none-any.whl Python 3 none any Details

Total release size: 71.2 kB

Release files / atp_protocol-1.4.0.tar.gz

Download URL atp_protocol-1.4.0.tar.gz
Size 35.0 kB
Tags Source
SHA-256 checksum
How to use checksums
3434f7bee8c4ad47c589be25e321b10710960ef62755c476512b102e091c0d62
BLAKE2b-256 checksum
How to use checksums
ebeb1fceb7d214c7d423014d1d8d0919a104f03a691330866988096432e6b308
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.1.3 CPython/3.12.3 Darwin/24.5.0

Release files / atp_protocol-1.4.0-py3-none-any.whl

Download URL atp_protocol-1.4.0-py3-none-any.whl
Size 36.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
769fd09af207bea67ac20a05e22e730ed11fb70718a11aa3b680f3c3bda2f538
BLAKE2b-256 checksum
How to use checksums
0592ba318de185149e2039027d78c98f08f3cb7359605bf3cbb5b569222b9721
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.1.3 CPython/3.12.3 Darwin/24.5.0

Release history Release notifications | RSS feed

This release

1.4.0 This release

2 release files

1.3.0

2 release files

1.2.0

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page