{"id":51089677,"url":"https://github.com/aws-samples/sample-agentcore-cloudfront-x402-payments","last_synced_at":"2026-07-12T05:00:33.619Z","repository":{"id":340702607,"uuid":"1162126118","full_name":"aws-samples/sample-agentcore-cloudfront-x402-payments","owner":"aws-samples","description":"AWS payment demo of x402 using Bedrock AgentCore, Strands SDK, and CloudFront.","archived":false,"fork":false,"pushed_at":"2026-05-09T03:58:18.000Z","size":1779,"stargazers_count":16,"open_issues_count":6,"forks_count":3,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-09T05:41:08.583Z","etag":null,"topics":["agentic-ai","aws","aws-bedrock","aws-cloudfront","aws-lambda","coinbase","crypto","cryptocurrency","x402","x402-payment"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit-0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aws-samples.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-19T22:35:18.000Z","updated_at":"2026-05-09T03:58:22.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/aws-samples/sample-agentcore-cloudfront-x402-payments","commit_stats":null,"previous_names":["aws-samples/sample-agentcore-cloudfront-x402-payments"],"tags_count":0,"template":false,"template_full_name":"amazon-archives/__template_MIT-0","purl":"pkg:github/aws-samples/sample-agentcore-cloudfront-x402-payments","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws-samples%2Fsample-agentcore-cloudfront-x402-payments","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws-samples%2Fsample-agentcore-cloudfront-x402-payments/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws-samples%2Fsample-agentcore-cloudfront-x402-payments/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws-samples%2Fsample-agentcore-cloudfront-x402-payments/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aws-samples","download_url":"https://codeload.github.com/aws-samples/sample-agentcore-cloudfront-x402-payments/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aws-samples%2Fsample-agentcore-cloudfront-x402-payments/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35382323,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-12T02:00:06.386Z","response_time":87,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agentic-ai","aws","aws-bedrock","aws-cloudfront","aws-lambda","coinbase","crypto","cryptocurrency","x402","x402-payment"],"created_at":"2026-06-24T01:00:24.483Z","updated_at":"2026-07-12T05:00:33.610Z","avatar_url":"https://github.com/aws-samples.png","language":"Python","funding_links":[],"categories":["🛠 Developer Tools \u0026 Starters"],"sub_categories":["Agent Frameworks \u0026 Managed Platforms"],"readme":"# x402 Payments using Amazon Bedrock AgentCore\n\nHTTP 402 payment-gated content delivery using AWS Bedrock AgentCore and AgentCore Payments, paying a seller operating on CloudFront, Lambda@Edge, and S3.\n\n\u003e **Update — May 7, 2026:** AWS has launched [Amazon Bedrock AgentCore Payments](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments.html) (Preview) — bringing native, managed payment capabilities to AI agents built on Amazon Bedrock. AgentCore Payments lets agents autonomously discover, authorize, and execute x402 micropayments with built-in wallet management, policy-based spending controls, and a full audit trail — no custom payment infrastructure required. The architectures and reference implementations described in this repo now integrate directly with AgentCore Payments. [Get started with AgentCore Payments.](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments.html)\n\n## Overview\n\nThis project demonstrates a payment-gated content delivery system using the [x402 protocol](https://github.com/coinbase/x402):\n\n- **Payer**: AI agent on Bedrock AgentCore Runtime with AgentCore Payments (ProcessPayment API)\n- **Seller**: CloudFront + Lambda@Edge for x402 payment verification\n- **Web UI**: React demo interface\n\n## Architecture\n\n| Agent requests content and receives a 402 payment challenge | Agent pays and content is delivered |\n|:---:|:---:|\n| ![Agent Challenge](assets/agent-challenge.png) | ![Content Received](assets/content-received.png) |\n\n```mermaid\nflowchart LR\n    Browser[\"🌐 Browser\"]\n\n    subgraph AWS[\"AWS Account\"]\n        direction LR\n\n        subgraph WebUI[\"web-ui-infrastructure\"]\n            direction TB\n            CF_UI[\"Amazon CloudFront\"]\n            S3_UI[\"Amazon S3\\n(React App)\"]\n            APIGW[\"Amazon API Gateway\\n(REST, 29s timeout)\"]\n            Lambda_Proxy[\"AWS Lambda\\n(Python 3.12 Proxy)\"]\n            CF_UI --\u003e S3_UI\n            APIGW --\u003e Lambda_Proxy\n        end\n\n        subgraph Payer[\"payer-infrastructure\"]\n            direction TB\n            subgraph AgentCore[\"Amazon Bedrock AgentCore\"]\n                direction TB\n                Gateway[\"Gateway\\n(MCP Tool Server, IAM SigV4)\"]\n                Runtime[\"Runtime\\n(Session Management)\"]\n                Agent[\"Strands Agent\\n(Python)\"]\n                Gateway --\u003e Runtime\n                Runtime --\u003e Agent\n            end\n            Payments[\"AgentCore Payments\\n(ProcessPayment API)\"]\n            Bedrock[\"Amazon Bedrock\\n(Claude Sonnet)\"]\n            CW[\"Amazon CloudWatch\\n(Dashboards, Alarms)\"]\n            S3_Spec[\"Amazon S3\\n(OpenAPI Spec)\"]\n            Agent --\u003e Payments\n            Agent --\u003e Bedrock\n            Gateway --\u003e S3_Spec\n        end\n\n        subgraph Seller[\"seller-infrastructure\"]\n            direction TB\n            CF_Seller[\"Amazon CloudFront\\n(x402 Payment-Gated)\"]\n            LambdaEdge[\"Lambda@Edge\\n(Payment Verifier,\\nNode.js 20.x, us-east-1)\"]\n            S3_Content[\"Amazon S3\\n(Content Bucket)\"]\n            CF_Seller --\u003e LambdaEdge\n            LambdaEdge --\u003e|\"Valid payment\"| S3_Content\n            LambdaEdge --\u003e|\"No payment\"| FourOhTwo[\"402 Response\\n+ x402 Headers\"]\n        end\n    end\n\n    Facilitator[\"x402 Facilitator\\n(x402.org)\"]\n    Blockchain[\"Base Sepolia\\n(USDC Testnet)\"]\n\n    Browser --\u003e|\"HTTPS\"| CF_UI\n    Browser --\u003e|\"API Calls\"| APIGW\n    Lambda_Proxy --\u003e|\"InvokeAgentRuntime\"| Runtime\n    Agent --\u003e|\"HTTPS +\\nx402 Headers\"| CF_Seller\n    LambdaEdge --\u003e|\"Verify \u0026 Settle\"| Facilitator\n    Facilitator --\u003e|\"On-chain\\nSettlement\"| Blockchain\n    Payments --\u003e|\"Sign \u0026 Pay\"| Blockchain\n    Lambda_Proxy --\u003e|\"eth_call\\n(Balance)\"| Blockchain\n```\n\nThree CDK stacks deploy into a single AWS account:\n- **web-ui-infrastructure** — CloudFront + S3 for the React app, API Gateway + Lambda proxy to AgentCore\n- **payer-infrastructure** — IAM roles (including AgentCore Payments roles), CloudWatch observability for Bedrock AgentCore (Runtime, Gateway, Agent)\n- **seller-infrastructure** — CloudFront + Lambda@Edge for x402 payment-gated content, S3 content bucket\n\nAgentCore Gateway acts as an MCP tool server:\n- Content endpoints exposed as discoverable MCP tools via OpenAPI spec\n- Agent discovers tools at runtime via MCP protocol\n- x402 payment headers pass through to CloudFront\n- Agent handles 402 responses and payment signing\n\n## Payment Flow\n\nThe Web UI guides users through a 3-step payment process:\n\n1. **Step 1: Request Content**\n   - User selects content item\n   - Agent requests content from CloudFront\n   - Lambda@Edge returns `402 Payment Required` with x402 headers\n   - Agent extracts x402_payload and reports payment requirements\n\n2. **Step 2: Confirm Payment**\n   - User confirms payment\n   - Agent calls ProcessPayment via AgentCore Payments (passes x402_payload as-is)\n   - AgentCore signs the transaction server-side\n   - Agent retries request with payment proof header (X-PAYMENT or PAYMENT-SIGNATURE)\n   - Lambda@Edge verifies signature via x402 facilitator\n   - Facilitator settles payment on-chain\n   - Agent confirms successful payment\n\n3. **Step 3: View Content**\n   - User clicks to view purchased content\n   - Agent presents the content data in readable format\n   - Transaction hash available for block explorer verification\n\n## Stack\n\n| Component | Technology |\n|-----------|------------|\n| Agent Framework | [Strands Agents SDK](https://strandsagents.com/) (Python) |\n| Agent Runtime | [Amazon Bedrock AgentCore](https://docs.aws.amazon.com/bedrock-agentcore/) |\n| Tool Discovery | MCP Protocol via Gateway |\n| LLM | Amazon Bedrock (Claude Sonnet) |\n| Payments | [Amazon Bedrock AgentCore Payments](https://docs.aws.amazon.com/bedrock-agentcore/) (ProcessPayment API) |\n| Content Delivery | CloudFront + Lambda@Edge |\n| Payment Protocol | [x402](https://github.com/coinbase/x402) |\n| Network | Base Sepolia (testnet) |\n| Web UI | React + Vite + TypeScript |\n\n## Project Structure\n\n```\nsample-agentcore-cloudfront-x402-payments/\n├── payer-agent/              # AI Agent (Python) - Strands agent with AgentCore Payments\n│   ├── agent/                # Agent implementation \u0026 tools\n│   ├── openapi/              # OpenAPI specs for Gateway targets\n│   ├── scripts/              # Deployment \u0026 test scripts\n│   └── tests/                # Test suite\n│\n├── payer-infrastructure/     # CDK Stack for AgentCore Runtime + Payments IAM\n│   └── lib/\n│       ├── agentcore-stack.ts\n│       └── observability-stack.ts\n│\n├── seller-infrastructure/    # CDK Stack for x402 Payment API ← Agent calls this\n│   ├── lib/\n│   │   ├── cloudfront-stack.ts\n│   │   └── lambda-edge/\n│   │       ├── payment-verifier.ts  # x402 payment verification\n│   │       └── content-config.ts    # Content \u0026 pricing config\n│   └── content/              # S3-backed content files\n│\n├── web-ui/                   # React Frontend (Vite + TypeScript)\n│   └── src/\n│       ├── api/              # Agent \u0026 Gateway clients\n│       ├── components/       # UI components\n│       └── hooks/            # React hooks\n│\n├── web-ui-infrastructure/    # CDK Stack for Web UI hosting ← Browser loads this\n│   └── lib/\n│       ├── web-ui-stack.ts   # CloudFront + S3 + API Gateway\n│       └── lambda/           # API proxy for AgentCore\n│\n├── scripts/                  # Setup \u0026 verification scripts\n└── docs/                     # Documentation\n```\n\n### Two CloudFront Distributions\n\nThis project deploys **two separate CloudFront distributions** for different purposes:\n\n| Stack | CloudFront Purpose | Called By |\n|-------|-------------------|-----------|\n| `seller-infrastructure` | Payment-gated API (returns 402, verifies payments) | AI Agent |\n| `web-ui-infrastructure` | Static React app hosting | Browser |\n\nThe Web UI (browser) → Agent → Seller API for ease of use.\n\n### Deployed URLs\n\nAfter deployment, you'll have URLs for each component:\n\n| Component | URL Pattern | Purpose |\n|-----------|-------------|---------|\n| Web UI | `https://\u003cdistribution-id\u003e.cloudfront.net` | React frontend |\n| Content API | `https://\u003cdistribution-id\u003e.cloudfront.net` | x402-protected endpoints |\n| API Gateway | `https://\u003capi-id\u003e.execute-api.\u003cregion\u003e.amazonaws.com/prod/` | AgentCore proxy |\n\nGet your URLs from CDK deployment outputs or CloudFormation console.\n\n### Wallet Addresses (Base Sepolia Testnet)\n\n| Role | Source | Description |\n|------|--------|-------------|\n| Payer (Agent) | AgentCore Payments | Created via CreatePaymentInstrument API |\n| Seller | Your own wallet | Set `PAYMENT_RECIPIENT_ADDRESS` in `seller-infrastructure/.env` |\n\nThe payer wallet is managed by AgentCore Payments — the agent never sees private keys. Fund it with USDC at https://faucet.circle.com/ (Base Sepolia).\n\n## Agent Tools\n\nBuilt-in tools:\n\n| Tool | Description |\n|------|-------------|\n| `process_payment` | Execute x402 payment via AgentCore Payments ProcessPayment API |\n| `request_content` | Request content (detects 402, returns raw x402_payload) |\n| `request_content_with_payment` | Retry with payment proof header (auto-backoff) |\n\nService discovery tools:\n\n| Tool | Description |\n|------|-------------|\n| `discover_services` | Find available paid services from Gateway |\n| `request_service` | Request any discovered service by name |\n| `list_approved_services` | List pre-approved services for autonomous purchasing |\n| `check_service_approval` | Check if a purchase is pre-approved |\n\nMCP tools (discovered via Gateway at `/mcp/tools`):\n\n| Tool | Price (USDC) | Description |\n|------|--------------|-------------|\n| `get_premium_article` | 0.001 | AI/blockchain article |\n| `get_weather_data` | 0.0005 | Weather conditions |\n| `get_market_analysis` | 0.002 | Crypto market data |\n| `get_research_report` | 0.005 | Blockchain research |\n| `get_dataset` | 0.01 | ML dataset |\n| `get_tutorial` | 0.003 | Smart contract tutorial |\n\n## Prerequisites\n\n- AWS Account with Bedrock AgentCore access\n- [Coinbase Developer Platform](https://portal.cdp.coinbase.com/) API keys (for AgentCore Payments credential provider setup)\n- Node.js 18+, Python 3.10+\n- AWS CDK CLI\n- Docker (for agent deployment to AgentCore)\n\nSee [QUICKSTART.md](QUICKSTART.md) for a streamlined deployment guide.\n\n## Quick Start\n\n### 1. Clone and setup\n\n```bash\ngit clone https://github.com/aws-samples/sample-agentcore-cloudfront-x402-payments\ncd sample-agentcore-cloudfront-x402-payments\n```\n\n### 2. Configure credentials\n\n```bash\n# Payer agent - set AgentCore Payments config\ncp payer-agent/.env.example payer-agent/.env\n# Edit payer-agent/.env → set MANAGER_ARN, PAYMENT_SESSION_ID, etc.\n\n# Seller infrastructure - set your wallet address\ncp seller-infrastructure/.env.example seller-infrastructure/.env\n# Edit seller-infrastructure/.env → set PAYMENT_RECIPIENT_ADDRESS\n```\n\n### 3. Deploy seller infrastructure\n\n```bash\ncd seller-infrastructure\nnpm install\nnpx cdk bootstrap  # First time only\nnpx cdk deploy\n```\n\n### 4. Set up AgentCore Payments\n\nDeploy payer infrastructure (creates IAM roles), then create resources via boto3:\n\n```bash\ncd payer-infrastructure \u0026\u0026 npm install \u0026\u0026 npx cdk bootstrap \u0026\u0026 npx cdk deploy --all\n```\n\nSee [QUICKSTART.md](QUICKSTART.md) for the full boto3 setup script (credential provider → manager → connector → instrument → session).\n\n### 5. Deploy payer infrastructure\n\n```bash\ncd payer-infrastructure\nnpm install\nnpx cdk bootstrap  # First time only\nnpx cdk deploy --all\n```\n\n### 6. Deploy payer agent\n\n```bash\ncd payer-agent\npython -m venv .venv\nsource .venv/bin/activate\npip install -e \".[dev]\"\npython scripts/deploy_to_agentcore.py\n```\n\n### 7. Run Web UI\n\n```bash\n# Configure the web UI\ncp web-ui/.env.example web-ui/.env.local\n# Edit web-ui/.env.local:\n#   VITE_API_ENDPOINT=http://localhost:8080        (local backend API server)\n#   VITE_AWS_REGION=us-west-2                      (your AWS region)\n#   VITE_SELLER_URL=https://dXXXXXXXXXXXXX.cloudfront.net  (from step 3)\n\n# In one terminal, start the backend API server:\ncd sample-agentcore-cloudfront-x402-payments/payer-agent\nsource .venv/bin/activate\npython -m agent.api_server\n\n# In another terminal, start the frontend:\ncd sample-agentcore-cloudfront-x402-payments/web-ui\nnpm install\nnpm run dev\n```\n\n### 8. Test\n\n```bash\ncd sample-agentcore-cloudfront-x402-payments/payer-agent\npytest\n\n# Integration tests\nSELLER_API_URL=$(grep SELLER_API_URL .env | cut -d= -f2) pytest -m integration\n\n# Invoke agent\npython scripts/invoke_gateway.py \"Get me the premium article\"\n```\n\n## Web UI\n\nThe React frontend provides a step-by-step interface for the x402 payment flow:\n\n- **Wallet Display**: Shows agent wallet address and USDC balance on Base Sepolia\n- **Content Grid**: 6 content items with pricing (0.0005 - 0.01 USDC)\n- **3-Step Flow**: Request → Pay → View, each step is a separate agent call\n- **Debug Panel**: Shows HTTP requests/responses for transparency\n- **Agent Response**: Displays agent reasoning at each step\n\nThe step-by-step approach keeps each API call under the 29-second timeout limit while providing clear visibility into the payment process.\n\n### Production Deployment (Optional)\n\nTo host the Web UI on CloudFront + S3 instead of running locally:\n\n```bash\ncd web-ui-infrastructure\nnpm install\nnpx cdk bootstrap  # First time only\nnpx cdk deploy\n```\n\n## Tests\n\n```bash\ncd payer-agent\nsource .venv/bin/activate\n\npytest                                    # All tests\npytest tests/test_402_response.py -v      # 402 handling\npytest tests/test_payment_analysis.py -v  # Payment decisions\npytest tests/test_payment_signing.py -v   # Wallet signing\npytest tests/test_content_delivery.py -v  # Content retrieval\npytest tests/test_error_scenarios.py -v   # Error handling\n```\n\n## Observability\n\n- CloudWatch Dashboards\n- OpenTelemetry tracing\n- Structured JSON logging\n- EMF metrics from Lambda@Edge\n\n## Security\n\n- IAM SigV4 authentication via AgentCore Gateway\n- Wallet keys stored in AgentCore Identity (agent never sees private keys)\n- 4-role IAM model: agent can only call ProcessPayment, not create sessions or instruments\n- Session-level spending limits enforced server-side\n- Cryptographic signature validation via x402 facilitator\n- Session isolation in AgentCore Runtime\n\n\u003e **⚠️ Web UI Security Notice:** The deployed Web UI (CloudFront + API Gateway) does not include authentication. Anyone with the URL can trigger agent invocations that spend from the connected wallet. This is intentional for demo purposes on Base Sepolia testnet. **Do not deploy with a mainnet wallet or real funds without adding authentication** (e.g., Amazon Cognito, API keys, or IAM auth on API Gateway). If you deploy the Web UI publicly, treat the URL as sensitive and restrict access accordingly.\n\n## Known Issues\n\n- **Python 3.14 + httpcore/anyio incompatibility:** Integration tests that make real HTTP calls via `httpx` fail on Python 3.14 (pre-release) with `TypeError: cannot create weak reference to 'NoneType' object` in `httpcore/_async/connection_pool.py`. Unit tests (which mock HTTP) are unaffected. Use Python 3.12 or 3.13 for integration tests until upstream `httpcore`/`anyio` releases fix this.\n\n## References\n\n- [x402 Protocol Specification](https://github.com/coinbase/x402/tree/main/specs)\n- [x402 CloudFront + Lambda@Edge Example](https://github.com/coinbase/x402/tree/main/examples/typescript/servers/cloudfront-lambda-edge) — the seller infrastructure in this project is based on this example\n- [Strands Agents Documentation](https://strandsagents.com/latest/documentation/docs/)\n- [Bedrock AgentCore Documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments.html)\n- [EIP-3009: Transfer With Authorization](https://eips.ethereum.org/EIPS/eip-3009)\n\n## Creating a Seller Wallet\n\nYou need a wallet address on Base Sepolia to receive payments. Options:\n\n1. **CDP Portal** (recommended): Create at [portal.cdp.coinbase.com](https://portal.cdp.coinbase.com/)\n2. **MetaMask**: Add Base Sepolia network and use your address\n3. **Any EVM wallet**: Any wallet that supports Base Sepolia testnet\n\nSet your wallet address in `seller-infrastructure/.env`:\n```bash\nPAYMENT_RECIPIENT_ADDRESS=\u003cYOUR_WALLET_ADDRESS\u003e\n```\n## Security\n\nSee [CONTRIBUTING](CONTRIBUTING.md) for more information.\n\n## License\n\nThis library is licensed under the MIT-0 License. See the LICENSE file.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faws-samples%2Fsample-agentcore-cloudfront-x402-payments","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faws-samples%2Fsample-agentcore-cloudfront-x402-payments","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faws-samples%2Fsample-agentcore-cloudfront-x402-payments/lists"}