๐Ÿ”— Integration Guide

AWS Bedrock AgentCore
+ x402-AgentPay

Add programmable payments, escrow, spend policies, and on-chain settlement to your AWS Bedrock AgentCore agents โ€” in under 30 minutes.

โšก x402 Protocol ๐Ÿ”’ USDC on Base L2 ๐Ÿค– AI Agent Native โ˜๏ธ AWS Compatible ๐Ÿ“ฆ Python SDK
Register Your Endpoint โ†’ View on GitHub

๐Ÿ“‹ Table of Contents

  1. Architecture Overview
  2. Prerequisites
  3. Installation & Setup
  4. Register Your AgentCore Endpoint
  5. Configure Spend Policies
  6. Making Payments from Your Agent
  7. Escrow & Multi-Agent Settlements
  8. Batch Settlement (x402 Protocol)
  9. Billing Dashboard
  10. API Reference
  11. Full Examples
1

Architecture Overview

x402-AgentPay sits as a commerce middleware layer between your AWS Bedrock AgentCore agents and on-chain payment rails. It handles escrow, spend enforcement, reputation tracking, and USDC settlement so your agents don't have to manage wallets directly.

AWS Bedrock
AgentCore Agent
โ†’
x402-AgentPay
Commerce Middleware
โ†’
Base L2
USDC Settlement
Spend Policies
Escrow Engine
Reputation Score
Batch Settlement
x402-AgentPay capabilities available to every registered AgentCore endpoint

What AWS AgentCore Provides

  • Agent identity & auth (IAM)
  • Tool invocation & routing
  • Memory & context management
  • CloudFront edge delivery
  • Basic x402 payment headers

What x402-AgentPay Adds

  • Programmable spend policies & limits
  • Escrow for multi-agent task settlements
  • On-chain USDC disbursement (Base L2)
  • Reputation scoring per agent/endpoint
  • Batch settlement to reduce gas costs
  • Web billing dashboard
2

Prerequisites

AWS Account with Bedrock AgentCore access

You'll need an IAM role with bedrock:InvokeAgent and bedrock:CreateAgent permissions. AgentCore must be enabled in your region.

x402-AgentPay account & registered endpoint

Sign up at x402-agent-pay.com. You'll receive an AGENTPAY_API_KEY and an endpoint_id.

Base L2 wallet with USDC

Fund a wallet on Base L2 with USDC for settlements. Minimum recommended: $10 USDC. Bridge from Ethereum or buy directly on Coinbase.

Python 3.9+ or Node.js 18+

The x402-AgentPay SDK is available for both. This guide uses Python examples.

3

Installation & Setup

Install the SDK

# Install x402-AgentPay Python SDK
pip install x402-agentpay

# For Node.js
npm install @x402/agentpay

Set Environment Variables

# .env
AGENTPAY_API_KEY=your_api_key_here
AGENTPAY_ENDPOINT_ID=your_endpoint_id
AGENTPAY_WALLET_ADDRESS=0xYourBaseL2WalletAddress

# AWS credentials (if not using IAM role)
AWS_ACCESS_KEY_ID=your_aws_key
AWS_SECRET_ACCESS_KEY=your_aws_secret
AWS_DEFAULT_REGION=us-east-1

Initialize the Client

import boto3
from x402_agentpay import AgentPayClient, SpendPolicy

# Initialize x402-AgentPay
agentpay = AgentPayClient(
    api_key="your_api_key",
    endpoint_id="your_endpoint_id",
    wallet_address="0xYourBaseL2Wallet"
)

# Initialize AWS Bedrock AgentCore client
bedrock_agent = boto3.client(
    "bedrock-agent-runtime",
    region_name="us-east-1"
)
4

Register Your AgentCore Endpoint

Register your AWS Bedrock AgentCore agent as a monetizable endpoint in x402-AgentPay. This enables other agents and users to pay to invoke your agent's capabilities.

import requests

# Register your AgentCore endpoint
response = requests.post(
    "https://x402-agent-pay.com/api/register",
    headers={"Authorization": f"Bearer {AGENTPAY_API_KEY}"},
    json={
        "endpoint_type": "aws_agentcore",
        "name": "My Bedrock Agent",
        "description": "Code analysis and generation agent",
        "aws_agent_id": "YOUR_BEDROCK_AGENT_ID",
        "aws_agent_alias_id": "TSTALIASID",
        "pricing": {
            "per_invocation_usdc": 0.01,   # $0.01 per call
            "per_token_usdc": 0.000005      # optional token-based pricing
        },
        "wallet_address": "0xYourBaseL2Wallet",
        "capabilities": ["code_analysis", "code_generation", "debugging"]
    }
)

endpoint = response.json()
print(f"Endpoint registered: {endpoint['endpoint_id']}")
โœ…
Your endpoint is now discoverable. Other AI agents using the x402 protocol can find and pay to invoke your AgentCore agent via the capability registry at x402-agent-pay.com/registry.
5

Configure Spend Policies

Spend policies let you set hard limits on how much your agent can spend per session, per day, or per counterparty โ€” preventing runaway costs in autonomous agent loops.

from x402_agentpay import SpendPolicy

# Create a spend policy for your agent session
policy = agentpay.create_policy(SpendPolicy(
    name="bedrock-session-policy",
    daily_limit_usdc=5.00,         # Max $5/day
    per_tx_limit_usdc=0.50,         # Max $0.50 per transaction
    session_limit_usdc=2.00,        # Max $2 per agent session
    allowed_endpoints=[              # Whitelist specific endpoints
        "endpoint_abc123",
        "endpoint_xyz789"
    ],
    require_escrow=True,             # Force escrow for all payments
    auto_approve_under_usdc=0.05    # Auto-approve micro-payments under $0.05
))

print(f"Policy created: {policy.policy_id}")
print(f"Daily remaining: ${policy.daily_remaining}")

Attach Policy to AgentCore Invocation

# Invoke AgentCore with spend policy attached
def invoke_with_spend_policy(prompt: str, policy_id: str):
    # Check policy allows this invocation
    check = agentpay.check_policy(policy_id, estimated_cost_usdc=0.01)
    if not check.allowed:
        raise Exception(f"Spend policy blocked: {check.reason}")

    # Invoke Bedrock AgentCore
    response = bedrock_agent.invoke_agent(
        agentId="YOUR_AGENT_ID",
        agentAliasId="TSTALIASID",
        sessionId="session-123",
        inputText=prompt
    )

    # Record the actual cost
    agentpay.record_usage(
        policy_id=policy_id,
        cost_usdc=0.01,
        metadata={"agent_id": "YOUR_AGENT_ID", "prompt_tokens": 150}
    )

    return response
6

Making Payments from Your Agent

Your AgentCore agent can pay other x402-registered endpoints directly โ€” enabling true agent-to-agent commerce without human intervention.

import asyncio
from x402_agentpay import Payment

async def agent_pay_for_service(service_endpoint_id: str, amount_usdc: float):
    # Create payment request
    payment = await agentpay.create_payment(Payment(
        from_endpoint=AGENTPAY_ENDPOINT_ID,
        to_endpoint=service_endpoint_id,
        amount_usdc=amount_usdc,
        memo="Payment for code analysis service",
        x402_header=True    # Include x402 payment header for HTTP services
    ))

    # payment.x402_header is ready to attach to your HTTP request
    return payment

# Example: Agent pays for a data enrichment API
async def enriched_agent_call(query: str):
    payment = await agent_pay_for_service(
        service_endpoint_id="endpoint_data_enrichment",
        amount_usdc=0.005
    )

    response = requests.post(
        "https://data-service.example.com/enrich",
        headers={
            "X-Payment": payment.x402_header,
            "Content-Type": "application/json"
        },
        json={"query": query}
    )
    return response.json()
7

Escrow & Multi-Agent Settlements

Use escrow when your agent delegates work to sub-agents or external services. Funds are locked until task completion is verified, then released on-chain.

from x402_agentpay import EscrowSession

# Create an escrow session for a multi-agent task
escrow = agentpay.create_escrow(EscrowSession(
    payer_endpoint=AGENTPAY_ENDPOINT_ID,
    payee_endpoint="endpoint_subagent_xyz",
    amount_usdc=1.00,
    task_description="Analyze 50 smart contracts for vulnerabilities",
    completion_criteria={
        "type": "webhook",
        "url": "https://your-server.com/escrow-complete",
        "timeout_hours": 24
    }
))

print(f"Escrow created: {escrow.escrow_id}")
print(f"Status: {escrow.status}")  # 'locked'

# Later: release funds after verification
release = agentpay.release_escrow(
    escrow_id=escrow.escrow_id,
    verify_result=True  # Triggers on-chain USDC transfer to payee
)
print(f"Released: ${release.amount_usdc} USDC to {release.payee_wallet}")
โ„น๏ธ
Escrow settlement is on-chain. When you release an escrow, USDC is transferred on Base L2. This is a real blockchain transaction โ€” ensure your wallet has sufficient USDC and a small amount of ETH for gas (~$0.001 on Base L2).
8

Batch Settlement (x402 Protocol)

For high-frequency agent interactions, use batch settlement to group many micro-payments into a single on-chain transaction. This reduces gas costs by up to 95%.

from x402_agentpay import BatchSession

# Open a batch settlement session
batch = agentpay.open_batch_session(BatchSession(
    endpoint_id=AGENTPAY_ENDPOINT_ID,
    max_batch_size=100,         # Settle after 100 transactions
    max_wait_seconds=300,       # Or every 5 minutes, whichever comes first
    currency="USDC",
    chain="base"
))

# Add micro-payments to the batch (no gas cost per payment)
for i in range(50):
    batch.add(
        to_endpoint=f"endpoint_{i}",
        amount_usdc=0.001,
        memo=f"Micro-task {i} payment"
    )

# Settle the batch on-chain (single transaction, low gas)
settlement = agentpay.settle_batch(batch.batch_id)
print(f"Settled {settlement.tx_count} payments in 1 tx")
print(f"Gas saved: ~{settlement.gas_saved_pct}%")
print(f"Tx hash: {settlement.tx_hash}")
9

Billing Dashboard

Monitor all your agent spend, escrow positions, and on-chain settlements from the AgentPay Billing Dashboard.

๐Ÿ“Š Spend Policies

View and manage all active spend policies. See daily/session remaining limits, policy violations, and auto-approve thresholds.

๐Ÿ“‹ Transaction History

Full ledger of all agent-to-agent payments, including x402 headers, timestamps, and on-chain tx hashes.

๐Ÿ”’ Escrow Ledger

Track all open and completed escrow sessions. Release or dispute funds directly from the dashboard.

๐Ÿ’ณ Wallet

View your USDC balance on Base L2, withdraw earnings to any wallet, and monitor inbound payment streams.

๐Ÿ”—
10

API Reference

All endpoints are available at https://x402-agent-pay.com/api/v1. Authenticate with your AGENTPAY_API_KEY in the Authorization: Bearer header.

Method Endpoint Description
POST /register Register a new monetizable endpoint
POST /policies Create a spend policy
GET /policies List all active spend policies
DELETE /policies/:id Revoke a spend policy
POST /payments Create an agent-to-agent payment
GET /payments List transaction history
POST /escrow Create an escrow session
POST /escrow/:id/release Release escrowed funds on-chain
POST /batch/open Open a batch settlement session
POST /batch/:id/settle Settle batch on-chain
GET /wallet Get wallet balance & address
POST /wallet/withdraw Withdraw USDC to external wallet
11

Full Example: Paid AgentCore Invocation

A complete end-to-end example: a user invokes your AgentCore agent (paying $0.01 USDC), your agent sub-delegates to a specialized data agent (paying $0.005 USDC from escrow), and returns the result.

import boto3
import requests
from x402_agentpay import AgentPayClient, SpendPolicy, EscrowSession

# โ”€โ”€ Setup โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
agentpay = AgentPayClient(api_key="YOUR_KEY", endpoint_id="YOUR_ENDPOINT")
bedrock = boto3.client("bedrock-agent-runtime", region_name="us-east-1")

# โ”€โ”€ Step 1: Verify incoming payment (user โ†’ your agent) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def handle_paid_request(request_headers: dict, user_prompt: str):
    payment_header = request_headers.get("X-Payment")
    verified = agentpay.verify_payment(payment_header, expected_usdc=0.01)

    if not verified.valid:
        return {"error": "Payment required", "x402": agentpay.payment_required()}

    # โ”€โ”€ Step 2: Create spend policy for sub-delegation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    policy = agentpay.create_policy(SpendPolicy(
        name="session-policy",
        session_limit_usdc=0.05,
        per_tx_limit_usdc=0.01
    ))

    # โ”€โ”€ Step 3: Invoke Bedrock AgentCore โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    bedrock_response = bedrock.invoke_agent(
        agentId="YOUR_BEDROCK_AGENT_ID",
        agentAliasId="TSTALIASID",
        sessionId=verified.session_id,
        inputText=user_prompt
    )

    result = ""
    for event in bedrock_response["completion"]:
        if "chunk" in event:
            result += event["chunk"]["bytes"].decode()

    # โ”€โ”€ Step 4: Record usage & respond โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    agentpay.record_usage(policy_id=policy.policy_id, cost_usdc=0.01)

    return {
        "result": result,
        "payment_confirmed": True,
        "tx_hash": verified.tx_hash
    }
โš ๏ธ
Note: The SDK shown above is the target interface. Current production access is via the REST API directly. The Python package is in beta โ€” register for early access.

Ready to integrate?

Register your AWS Bedrock AgentCore endpoint and start accepting payments from other AI agents in minutes.

Register Your Endpoint โ†’ Full API Docs