# ampersend docs > Developer documentation for ampersend — the agent payments platform built on x402, A2A, and MCP. This file contains all documentation content in a single document following the llmstxt.org standard. ## Introduction Welcome to the ampersend documentation! ## Quick start If you're an AI agent, start with [getting-started.md](https://ampersend.ai/getting-started.md). It explains what ampersend is from an agent's perspective and walks you through installing the skill and CLI so you can start paying for things. ## What is ampersend? ampersend is a management platform for agent payments and operations, created by [Edge & Node](https://www.edgeandnode.com/). It uses [Coinbase's x402](https://www.coinbase.com/developer-platform/products/x402) payment protocol, [Google's A2A](https://github.com/google-agentic-commerce/a2a-x402) (Agent-to-Agent) framework and [MCP](https://modelcontextprotocol.io/) (Model Context Protocol). As autonomous agents increasingly interact across AI and blockchain ecosystems, there's no standard way to oversee these activities. Payments and processes are often scattered and hard to manage at scale. ampersend addresses this by providing a single management layer for agent transactions. It allows teams to create and monitor agent wallets, track payments, automate funding and approvals, and ensure compliance within one system. --- ## What ampersend enables The platform is designed to help the industry adopt and expand open standards. In collaboration with Coinbase, Google, and the Ethereum Foundation's dAI team, Edge & Node has contributed to key standards such as x402 for payments and ERC-8004 for agent discovery and reputation. ampersend integrates these innovations into a single, operating system and enables: - **Creation** of agent wallets that integrate with A2A and MCP - **Automation** of authorizations, top-ups, and spend limits - **Visibility** through real-time dashboards of agent payment flows - **Control** for enterprise compliance, reporting, and accounting For more details about why ampersend exists, the problems it solves, and how it works, see the [why ampersend](/why-ampersend) overview. You can also find answers to common questions in the [ampersend FAQ](https://ampersend.ai/faq). --- ### Payment scheme support ampersend currently supports the `exact` payment scheme. The [x402 Deferred Scheme](/core-concepts/x402-deferred-scheme) was contributed by Edge & Node to enable trust-minimized micro-payments, but deferred settlement is not yet merged into x402 and is not yet supported by ampersend. --- ## ampersend SDK and ampersend Platform ampersend consists of two complementary components that work together: the [SDK Overview](/sdk/sdk-overview) and the [Platform Overview](/platform/platform-overview). ### ampersend SDK (developer tool) **Role:** Add payment capabilities to agent code. - **What it is**: A software development kit (SDK) for integrating x402 payments into agents - **Purpose**: Enables developers to add payment capabilities to their agent code - **Used by**: Developers building agents - **Provides**: - Payment middleware (`X402Client`, `X402McpClient`) - Wallet integration (`AccountWallet`, `SmartAccountWallet`) - Treasurer for payment authorization - Automatic payment handling in code ### ampersend Platform (management software) **Role:** Manage and monitor agent payments. - **What it is**: A management platform for agent payments and operations - **Purpose**: Provides visibility, control, and management of agent payments - **Used by**: Developers, operators, finance teams, enterprises - **Provides**: - Dashboard for payment visibility - Budget controls and spend limits - Analytics and reporting - Enterprise compliance features - Wallet management and automation ### How they work together - **ampersend SDK**: Developer use the SDK to build agents with payment capabilities - **ampersend Platform**: The dashboard you use to manage those payments #### Typical flow: 1. Developers use the **SDK** to build agents with payment capabilities. 2. The **Platform** provides the management layer to monitor, control, and manage those payments at scale. To get started, see [ampersend sdk quick start](/quick-starts/sdk-quickstart) and [ampersend platform quick start](/quick-starts/platform-quickstart). --- ## Why ampersend Agents are scaling fast. Payments between them are not. x402 make crypto payments possible, but payment primitives alone do not address operational needs at scale. As agent systems grow, visibility, control, and compliance become increasingly difficult. ampersend provides the management layer for agent payments and operations. It gives teams the tooling required to run agent payments in production: - End-to-end visibility into agent payment flows - Provides budgeting, observability, and swarm-level controls - Enables enterprises to adopt agent-to-agent payments with compliance and oversight --- ## The Problem ### Why do agents need funds? Agents need funds to pay for services such as: - Data access - Specialized task execution - Potentially general purchases (for example, booking travel for a user) ### What actions require funds? Examples of funded actions include: - Calling APIs via MCP - Asking another agent to perform a task - Blockchain interactions such as DeFi trading --- ## Core Pillars ampersend is built around three core pillars: 1. **Fast** - HTTP-native stablecoin settlement via x402 - Lightning-fast microtransactions 2. **Observable** - Real-time dashboards of agent-to-agent flows 3. **Controllable** - Budgeting and spend caps at agent level --- ## How It Works ampersend consists of two components: the ampersend SDK and the ampersend Platform. ### ampersend SDK: Enable agents to make and receive payments The ampersend SDK adds payment capabilities to your agent code. 1. **Create your agent** using Google ADK. The agent can run locally or on a server. 2. **Add payment capabilities** using the ampersend SDK: - **For sellers:** Add payment requirements to your agent using SDK components - Examples: `make_x402_before_agent_callback` (Python), `withX402Payment` (TypeScript) - **For buyers:** Integrate SDK client components to automatically handle payments when calling paid agents - Examples: `X402RemoteA2aAgent` (Python), `X402McpClient` (TypeScript) 3. **Deploy or connect** your agent: - Deploy your agent as a paid service, or connect it to paid services - The SDK handles payment flows automatically ### ampersend Platform: Manage agent payments and controls The ampersend Platform provides visibility and operational control. 1. **Create an agent wallet/account in ampersend.** Connects your agent to the platform. 2. **Use the dashboard to:** - Track spend and earnings across all agents - Configure auto top-ups, spending limits, and service allowlists - Automate flows between user accounts and agent accounts - Collect funds automatically for service providers - View analytics on agent behavior and payment flows ## User control **MVP controls:** Daily, monthly, and per-transaction limits. --- ## SDK Quick Start # Get Started ## Choose a path - **Python (A2A):** Buyer (client), standalone testing, and seller (server) - **TypeScript (MCP):** Client, proxy, and FastMCP server --- # Python (A2A) ## What this SDK is for Python SDK for integrating [x402](https://github.com/coinbase/x402) payment capabilities into A2A (Agent-to-Agent) protocol applications. Supports both buyer (client) and seller (server) roles. ### Step 1: Install prerequisites and dependencies ```bash # Install Python 3.13 uv python install 3.13 # Install dependencies uv sync --frozen --group dev ``` ### Step 2: started (sandbox, testnet) Create your first x402-enabled agent using ampersend's sandbox environment (free testnet). #### 1. Create an agent account (sandbox) 1. Visit https://app.sandbox.ampersend.ai 2. Create an agent account 3. Get your Smart Account address and session key 4. Fund with testnet USDC: https://faucet.circle.com/ (select Base Sepolia) #### 2. Create your buyer (client) agent ```python from ampersend_sdk.a2a.client import X402RemoteA2aAgent from ampersend_sdk.ampersend import AmpersendTreasurer, ApiClient, ApiClientOptions from ampersend_sdk.x402.wallets.smart_account import SmartAccountWallet from ampersend_sdk.smart_account import SmartAccountConfig # Configure smart account wallet wallet = SmartAccountWallet( config=SmartAccountConfig( session_key="0x...", # From sandbox dashboard smart_account_address="0x...", # From sandbox dashboard ) ) # Create Ampersend treasurer (with spend limits & monitoring) treasurer = AmpersendTreasurer( api_client=ApiClient( options=ApiClientOptions( base_url="https://api.sandbox.ampersend.ai", session_key_private_key="0x..." ) ), wallet=wallet ) # Create agent pointing to sandbox service (testnet, rate-limited) agent = X402RemoteA2aAgent( treasurer=treasurer, name="my_agent", agent_card="https://subgraph-a2a.x402.sandbox.thegraph.com/.well-known/agent-card.json" ) # Use the agent (payments handled automatically with spend limits) result = await agent.run("Query Uniswap V3 pools on Base Sepolia") ``` ### Optional: Standalone mode (for testing only & _not recommended_) This is a standalone example that runs without the ampersend platform. It is intended for local testing and experimentation only. For production use, configuring agents through the ampersend platform is recommended. See the platform [quick start](/quick-starts/sdk-quickstart) for the supported and secure setup. Use Standalone Mode for Testing Only: ```python from ampersend_sdk.a2a.client import X402RemoteA2aAgent from ampersend_sdk.x402.treasurers.naive import NaiveTreasurer from ampersend_sdk.x402.wallets.account import AccountWallet wallet = AccountWallet(private_key="0x...") treasurer = NaiveTreasurer(wallet=wallet) # Auto-approves, no limits agent = X402RemoteA2aAgent( treasurer=treasurer, name="test_agent", agent_card="https://subgraph-a2a.x402.sandbox.thegraph.com/.well-known/agent-card.json" ) ``` :::caution Standalone mode has no spend limits or monitoring. Recommended for testing only. ::: --- ### Optional: Server (Seller) example Use this when you want to require payment for your agent's tools. ```python from google.adk.agents import Agent from ampersend_sdk.a2a.server import to_a2a, make_x402_before_agent_callback # Create your ADK agent with payment requirements agent = Agent( name="MyAgent", before_agent_callback=make_x402_before_agent_callback( price="$0.001", network="base-sepolia", pay_to_address="0x...", ), ) @agent.tool() async def my_tool(query: str) -> str: return "result" # Convert to A2A app (x402 support configured via before_agent_callback) a2a_app = to_a2a(agent, host="localhost", port=8001) # Serve with uvicorn # uvicorn module:a2a_app --host 0.0.0.0 --port 8001 ``` --- ## Python core concepts (quick reference) ### `X402Treasurer` - **`ampersendTreasurer`** (recommended): Enforces spend limits and provides monitoring via ampersend API - **`NaiveTreasurer`**: Auto-approves all payments (useful for testing and demos only) ### Wallets - **`AccountWallet`**: EOA (Externally Owned Accounts) - **SmartAccountWallet**: ERC-4337 smart accounts with ERC-1271 signatures (includes ERC-7579 OwnableValidator from Rhinestone). ### Payment Flow 1. Client sends request → Server responds with `PAYMENT_REQUIRED` (402) 2. Treasurer authorizes payment → Payment injected into request 3. Request retried with payment → Server verifies and processes ### Python development commands ```bash # Test uv run -- pytest # Lint & format uv run -- ruff check python uv run -- ruff format python # Type check (strict mode) uv run -- mypy python ``` --- ## TypeScript (MCP) What this SDK is for TypeScript SDK for integrating [x402](https://github.com/coinbase/x402) payment capabilities into MCP (Model Context Protocol) applications. Supports client, proxy, and server implementations with EOA and Smart Account wallets. ### Step 1: Install dependencies and build ```bash pnpm install # Build all pnpm build ``` ### Step 2: Quick start options Choose one: - MCP Client - MCP proxy - FastMCP server #### Option A: MCP Client ```typescript import { X402McpClient } from "@ampersend_ai/ampersend-sdk/mcp/client"; import { AccountWallet, NaiveTreasurer, } from "@ampersend_ai/ampersend-sdk/x402"; const wallet = new AccountWallet("0x..."); const treasurer = new NaiveTreasurer(wallet); const client = new X402McpClient({ serverUrl: "http://localhost:8000/mcp", treasurer, }); await client.connect(); const result = await client.callTool("my_tool", { arg: "value" }); await client.close(); ``` #### Option B: MCP Proxy ```bash # Configure environment export BUYER_PRIVATE_KEY=0x... # Start proxy pnpm --filter ampersend-sdk proxy:dev # Connect to: http://localhost:3000/mcp?target=http://original-server:8000/mcp ``` #### Option C: FastMCP Server ```typescript import { withX402Payment } from "@ampersend_ai/ampersend-sdk/mcp/server/fastmcp"; import { FastMCP } from "fastmcp"; const mcp = new FastMCP("my-server"); mcp.addTool({ name: "paid_tool", description: "A tool that requires payment", schema: z.object({ query: z.string() }), execute: withX402Payment({ onExecute: async ({ args }) => { return { scheme: "erc20", amount: "1000000" }; }, onPayment: async ({ payment, requirements }) => { return { success: true }; }, })(async (args, context) => { return "result"; }), }); ``` --- ## Typescript core concepts (quick reference) ### X402Treasurer Handles payment authorization decisions and status tracking. The `NaiveTreasurer` implementation auto-approves all payments (useful for testing and demos). ### Wallets - **`AccountWallet`** - For EOA (Externally Owned Accounts) - **`SmartAccountWallet`** - For ERC-4337 smart accounts with ERC-1271 signatures ### Payment Flow 1. Client makes request → Server returns 402 with payment requirements 2. Treasurer authorizes payment → Payment injected into request metadata 3. Request retried with payment → Server verifies and processes ### Environment variables (TypeScript) ```bash # EOA Mode BUYER_PRIVATE_KEY=0x... # Smart Account Mode BUYER_SMART_ACCOUNT_ADDRESS=0x... BUYER_SMART_ACCOUNT_KEY_PRIVATE_KEY=0x... BUYER_SMART_ACCOUNT_VALIDATOR_ADDRESS=0x... ``` ### Package exports (TypeScript) ```typescript import { ... } from "@ampersend_ai/ampersend-sdk" // Main import { ... } from "@ampersend_ai/ampersend-sdk/x402" // Core x402 import { ... } from "@ampersend_ai/ampersend-sdk/mcp/client" // Client import { ... } from "@ampersend_ai/ampersend-sdk/mcp/proxy" // Proxy import { ... } from "@ampersend_ai/ampersend-sdk/smart-account" // Smart accounts import { ... } from "@ampersend_ai/ampersend-sdk/mcp/server/fastmcp" // FastMCP ``` ### TypeScript development commands ```bash # Build pnpm --filter build # Test pnpm --filter ampersend-sdk test # Lint & format pnpm --filter ampersend-sdk lint pnpm --filter ampersend-sdk format:fix ``` ## Learn More - [x402 Specification](https://github.com/coinbase/x402) - [SDK Package Documentation](https://github.com/edgeandnode/ampersend-sdk) --- ## Platform Quick Start # Get Started ## 1. Open the Platform Go to: - https://app.ampersend.ai ## 2. Automatic smart account creation When you first open the platform, a **[Coinbase Embedded Wallet](https://www.coinbase.com/en-ar/developer-platform/products/embeddedwallets) smart account** is automatically created for you. This is your main funding account for all agents. ### Initial screen ![ampersend Home](/img/ampersend-initial-screen.png) ## 3. Add funds (USDC) You must fund your main account before creating functional agents. - On the homepage, under **Add Funds**, click: - **Receive → Deposit USDC** - Funds transferred to your main account are used for: - Agent auto-top-ups - Agent direct transfers - Covering service usage costs ## 4. Next: monetize an API with hosted endpoints Agents can do more than spend — they can earn. Turn any HTTP API into a paid x402 endpoint and let the ampersend proxy collect payment on every call. - From the dashboard: open your agent and go to **Endpoints → Add endpoint**. - From the CLI: use the `ampersend endpoint` command group. See [Endpoint Commands](/sdk/endpoint-commands), or run [OpenAPI to Endpoints](/quick-starts/openapi-to-endpoints) to bulk-create from an OpenAPI spec. Learn more in [Hosted Endpoints](/platform/hosted-endpoints). --- ## OpenAPI to Endpoints This walkthrough turns an existing OpenAPI 3.0 or 3.1 spec into a set of paid ampersend hosted endpoints. Every path + method pair becomes one endpoint; the proxy forwards paid calls to your upstream and returns the response verbatim. ## Prerequisites - An agent account and active local config. Follow the [SDK quick start](/quick-starts/sdk-quickstart) and run `ampersend setup` if you haven't already. - `ampersend` v0.0.20 or later (`ampersend --version`). - A JSON OpenAPI 3.0 or 3.1 file for the API you want to monetize. Swagger 2.x specs must be upgraded to OpenAPI 3 first (any `swagger2openapi`-style tool works). ## 1. Inspect the spec `endpoint import` reads from a local JSON file — YAML is not parsed. If your source is YAML, convert it once before importing, for example with any `yaml` → `json` tool. Every operation becomes an endpoint using these defaults, unless overridden by vendor extensions (see below): - **Base URL** — `servers[0].url`. Override with `--base-url`. - **Name** — `summary` → `operationId` → `METHOD /path`, in that order. - **Description** — `description` → `summary`. - **Allowed method** — the operation's method. - **Price** — `x-ampersend-price` if present, otherwise the `--default-price` you pass on the CLI. If you omit `--default-price`, it silently defaults to `0.01` USD — always pass an explicit value for production imports. ## 2. Dry-run the import Start with `--dry-run` to verify the spec parses and the endpoint list looks right. No endpoints are created. ```bash ampersend endpoint import ./openapi.json \ --default-price 0.001 \ --dry-run ``` The command returns the parsed endpoint list: ```json { "ok": true, "data": { "dryRun": true, "count": 12, "endpoints": [ { "name": "Get weather", "price_usd": 0.001, "proxy_url": "https://api.example.com/v1/weather", "allowed_methods": ["GET"] } ] } } ``` Scan the output for: - Endpoints you do **not** want to expose for payment (internal or free routes). - Paths that need a different price. - Missing / wrong `proxy_url` (fix by passing `--base-url`). ## 3. Fine-tune with vendor extensions To customize per-operation settings without CLI flags, add extensions directly in the spec: | Extension | Type | Effect | | ------------------------- | ------- | ------------------------------ | | `x-ampersend-price` | number | Per-call price in USD | | `x-ampersend-name` | string | Endpoint display name override | | `x-ampersend-description` | string | Description override | | `x-ampersend-rate-limit` | integer | Rate limit per minute | Example: ```json { "paths": { "/weather": { "get": { "summary": "Get weather", "x-ampersend-price": 0.002, "x-ampersend-rate-limit": 60 } } } } ``` Re-run the dry-run until the output matches what you want to publish. ## 4. Create the endpoints Drop the `--dry-run` flag to actually create them: ```bash ampersend endpoint import ./openapi.json \ --default-price 0.001 \ --timeout 10000 ``` The response includes the number created and the list of new endpoint records: ```json { "ok": true, "data": { "dryRun": false, "count": 12, "created": 12, "endpoints": [ /* ... */ ] } } ``` ## 5. Verify List and test: ```bash ampersend endpoint list ampersend endpoint test ``` `endpoint test` sends a synthetic request through the proxy so you can confirm the upstream is reachable with the current `proxy_url` and headers. ## 6. Add upstream credentials (optional) If your upstream needs an API key, attach it as a proxy header. The value is stored encrypted and included on every proxied request: ```bash ampersend endpoint headers add-proxy \ --name "Authorization" \ --value "Bearer " ``` Use `remove-proxy` to clear it, or `rotate-secret` to roll the per-endpoint signing secret upstreams use to verify ampersend-originated traffic. ## Troubleshooting | Symptom | Fix | | --------------------------------------------- | -------------------------------------------------------------------- | | `Could not resolve a base URL` | Pass `--base-url https://...` | | `Resolved base URL must be http(s)` | The spec's base URL is invalid; override with `--base-url` | | `Invalid price for METHOD /path: must be > 0` | Add `x-ampersend-price` to the operation or raise `--default-price` | | Endpoint created but calls fail with 5xx | `endpoint test `; check `proxy_url` and any upstream auth header | ## Related - [Hosted Endpoints](/platform/hosted-endpoints) — concepts and settings - [Endpoint Commands](/sdk/endpoint-commands) — full CLI reference --- ## x402 (Coinbase) # x402 [x402](https://github.com/coinbase/x402) is an open payment protocol developed by Coinbase that enables instant, HTTP-based transactions for both human users and autonomous agents. It allows payments without requiring traditional user accounts, session management, or complex authentication systems. --- ## What x402 enables x402 enables the following payment and monetization patterns: - **Per-request API monetization:** API services can charge for each individual request without requiring subscription models or upfront commitments - **Autonomous agent payments:** AI agents can independently pay for API access and services as they operate, without human intervention - **Content monetization:** Digital content creators can implement paywalls and access controls that charge users automatically - **Microservice monetization:** Small services and tools can be monetized through microtransactions, making it economically viable to charge for granular functionality - **API aggregation services:** Proxy and gateway services can aggregate multiple APIs and charge for access, creating new business models for API intermediaries ## Payment scheme support in ampersend ampersend currently supports the `exact` payment scheme. The [x402 Deferred Scheme](/core-concepts/x402-deferred-scheme) was contributed by Edge & Node to enable trust-minimized micropayments, but deferred settlement is not yet merged into x402 and is not yet supported by ampersend. --- ## x402 DPS (Edge & Node) # x402 Deferred Payment Scheme The **deferred payment scheme** is a payment scheme for x402 that was [contributed by Edge & Node](https://github.com/coinbase/x402/pull/426) to support trust-minimized micro-payments. Unlike the `exact` scheme, which requires payments to be executed immediately and fully on-chain, the `deferred` scheme allows clients to issue signed vouchers (IOUs) off-chain, which can later be aggregated and redeemed by the seller. :::note This scheme was proposed and implemented by Edge & Node in [PR #426](https://github.com/coinbase/x402/pull/426) to the x402 protocol repository. The PR introduces the deferred scheme specification to enable micro-payments that are smaller than the minimum feasible on-chain transaction cost. ::: ## Overview The deferred scheme is designed to enable payments smaller than the minimum feasible on-chain transaction cost. By allowing off-chain voucher issuance with on-chain settlement, it makes micro-payments economically viable for both buyers and sellers. ## Key benefits The deferred scheme enables: - **Micro-payments**: Support payments smaller than the minimum feasible on-chain transaction cost - **Voucher aggregation**: Multiple payments can accumulate on the same voucher ID before settlement - **Gas efficiency**: Sellers can batch collections when it's economically viable to pay gas fees - **Trust-minimized**: Uses escrow contracts to protect both parties without requiring immediate on-chain execution --- ## How it works The deferred payment flow consists of four main steps: ### 1. Deposit Buyer deposits funds into an escrow contract for a specific seller. This can be done via: - Direct on-chain transfer - Signed authorization (EIP-3009) that allows the escrow contract to pull funds ### 2. Voucher issuance For each payment, the buyer sends a signed voucher off-chain to the seller. Each voucher: - Is cryptographically signed by the buyer - Contains payment details (amount, recipient, etc.) - Can be aggregated with other vouchers sharing the same voucher ID ### 3. Voucher aggregation Multiple payments can accumulate on the same voucher ID: - Each new payment increases the total owed (`valueAggregate`) on the same voucher - A nonce mechanism ensures sequential aggregation - All vouchers are validated before aggregation to prevent double-spending ### 4. Collection The seller collects accumulated vouchers on-chain when: - The total amount is worth the gas cost - A specific threshold is reached - A predetermined time interval has passed The collection process settles all aggregated vouchers in a single on-chain transaction, maximizing gas efficiency. ## Comparison with exact scheme | Feature | Exact Scheme | Deferred Scheme | | ---------------- | --------------------------- | --------------------------------------- | | **Execution** | Immediate on-chain | Off-chain vouchers, on-chain settlement | | **Payment Size** | Suitable for larger amounts | Optimized for micro-payments | | **Gas Cost** | Paid per transaction | Batched and optimized | | **Latency** | Instant settlement | Delayed until collection | | **Use Case** | Real-time payments | High-volume micro-payments | --- ## Use cases The deferred scheme is particularly valuable for: - **Agent-to-Agent Payments**: Where transaction volumes are high but individual amounts are small - **API Call Payments**: Pay-per-use services where each call costs less than gas fees - **Content Monetization**: Micro-payments for content consumption --- ## Technical details ### Voucher structure Each voucher contains: - `voucherId`: Unique identifier for the voucher - `nonce`: Sequential number for aggregation - `valueAggregate`: Total accumulated value - `signature`: Cryptographic signature from the buyer ### Escrow contract The escrow contract provides: - Per-buyer/seller/asset escrow accounts - Thawing period for withdrawals (buyer protection) - Automatic collection mechanisms - Authorization-based funding (EIP-3009) ### Security considerations - **Nonce validation**: Ensures sequential voucher aggregation - **Signature verification**: Prevents unauthorized voucher creation - **Escrow protection**: Funds are locked until collection - **Thawing mechanism**: Protects buyers from sudden seller withdrawals ## Learn more - [x402 Protocol Documentation](https://github.com/coinbase/x402) - [Deferred Scheme PR](https://github.com/coinbase/x402/pull/426) --- ## ampersend & ERC-8004 ## Overview ERC-8004 defines a standard for decentralized AI agent identity, reputation, and validation on Ethereum. Ampersend builds on that standard to provide an operational management layer for the emerging agent economy. **ERC-8004 answers:** Who is this agent? and what do on-chain signals say about them? **Ampersend answers:** How do I manage, discover, and operate agents in practice? Together, they connect identity, trust infrastructure, and economic activity into a unified system. --- ## 1. What ERC-8004 Defines ERC-8004 is an open Ethereum standard for decentralized AI agent discovery and trust. It defines three on-chain registries deployed as singletons per chain: **Identity Registry** - A shared registry built on ERC-721 where agents can publish: - Canonical on-chain identity (each agent is an NFT) - Metadata (name, description, and image) - Service endpoints (MCP and A2A) - Declared capabilities - Trust and verification models - Active or inactive visibility **Reputation Registry**— A standard interface for posting and querying feedback signals on-chain. Enables filtering by reviewer address and tags, with optional off-chain data for extended context. **Validation Registry** — Hooks for requesting and recording independent verification (stake-secured re-execution, zkML proofs, TEE attestations). ### Why ERC-8004 Exists - Agents are proliferating across ecosystems - There was no neutral, portable way to identify and discover them - Trust requires more than self-reported metadata - ERC-8004 provides a common substrate for identity, reputation, and interoperability --- ## 2. What Problem Ampersend Solves ERC-8004 standardizes what agent identity looks like. It does not define how identity is used in practice. Missing pieces before Ampersend: - No UX for publishing agents to the registry - No human-readable discovery surface - No dashboards for managing agent operations - No integration layer connecting identity to payment workflows and real-time activity Ampersend fills this gap by acting as the operational layer on top of ERC-8004. --- ## 3. How Ampersend Integrates with ERC-8004 Ampersend integrates with ERC-8004 in three complementary ways. ### Publishing Agents can be created and managed directly from Ampersend. Entries are written to the ERC-8004 Identity Registry. ### Discovery Agents published to ERC-8004 can be discovered across applications that support the standard. Ampersend provides a searchable discovery interface backed by the registry. ### Enrichment Agents combine ERC-8004 identity with x402-native payments, linking identity to verified economic activity. --- ## 4. Agent Identity Write Path ### What Ampersend Adds Ampersend provides a UI for publishing and managing ERC-8004 agent entries, including: - Agent name and description - Image URL - Service endpoints (MCP and A2A) - Visibility (active or inactive) Under the hood, Ampersend constructs the registration file, stores it (e.g., on IPFS), and calls the Identity Registry contract to register or update the agent. ### Why This Matters - Developers do not need to manually interact with smart contracts - Agent identity becomes portable across ecosystems - Ampersend acts as a standards-compliant authoring tool, not a silo Ampersend does not replace ERC-8004, it makes it operational. --- ## 5. Discovery and Indexing (ERC-8004 Read + Indexing) ### What Ampersend Adds Ampersend introduces a Discovery Page backed by the ERC-8004 registry. Users can: - Browse agents published to ERC-8004 - Search by name or description - Filter by: - Supported protocols such as MCP, A2A, or x402 - Trust models - Active/inactive status ### Why This Matters - ERC-8004 becomes usable by humans, not just protocols. - Discovery is no longer fragmented. - The registry becomes a practical agent directory. Ampersend provides a real discovery surface built on top of the standard. --- ## 6. Platform Enrichment: From Identity to Behavior This is the key differentiator. ERC-8004's Reputation Registry captures on-chain feedback signals — structured data that any address can submit about an agent. Ampersend builds on this foundation by adding operational context and real-time visibility. ### What Ampersend Adds Ampersend enriches ERC-8004 identity and reputation data with live operational signals: - Payment activity (via x402) - Buyer and seller relationships - Transaction volume and frequency - Top counterparties - Allowlist interactions - Agent-level activity feeds This data surfaces across: - Agent detail pages - Buyer and seller dashboards - Allowlist selection flows - Platform analytics ### Why This Matters **ERC-8004 answers:**: What's recorded on-chain about this agent? **Ampersend answers:** What is this agent doing right now, and how do I manage it? Together, they enable: - Practical trust evaluation combining on-chain history and live behavior - Safer agent-to-agent commerce - Operational visibility developers need to run agents in production --- ## 7. How This Connects to x402 The system separates responsibilities: - ERC-8004 handles identity, reputation, and validation (on-chain primitives) - x402 handles payments and settlement (HTTP-native stablecoin transactions) - Ampersend bridges identity, economics, and operations ### The Integration - Agents discovered via ERC-8004 can transact via x402 - Payment proofs can be recorded in ERC-8004 reputation feedback - Ampersend surfaces payment behavior in dashboards and activity feeds This creates a closed operational loop: **Discover → Verify → Transact → Observe** Identity, economics, and operations converge in one system. --- ## SDK Overview ampersend SDK is the payment layer for the agent economy. It enables pay-per-request monetization for AI agents using the open [x402](https://github.com/coinbase/x402) payment protocol. ## What the SDK enables With ampersend SDK, you can: - Turn an agent into a paid service - Call paid agents with automatic, on-chain payments - Browse the [Agent Marketplace](/platform/marketplace) of curated x402 services programmatically via `MarketplaceClient` - Enable agents to discover, call, and pay each other without custom payment logic - Accept USDC or other ERC-20 tokens on supported networks You focus on agent logic. The SDK handles the payment lifecycle automatically. ## What the SDK supports - **Agent Protocols**: A2A (Python), MCP (TypeScript) - **Agent Frameworks**: Google ADK & LangGraph (both coming soon) - **Runtime Languages**: Python, TypeScript - **Payments & Wallet Infrastructure**: Programmatic payments backed by blockchain wallets, including externally owned accounts and smart contract wallets ## When to use the ampersend SDK Use the SDK when you need to: - Make an agent x402 compliant by adding payment capabilities to agent code - Deploy agents as paid services that charge per request - Call paid agents with automatic payment handling - Use paid MCP servers as tools for agents - Implement x402 payment flows in code (authorization, signing, verification) - Support A2A (Python) or MCP (TypeScript) agents with payments :::tip The SDK is the code you integrate into your agent application. For managing and monitoring those payments at scale, use the [platform](/platform/platform-overview). ::: ## Agent-driven endpoint management Beyond making paid calls, the SDK ships an `ampersend endpoint` CLI that lets an agent create, update, and test its own paid [hosted endpoints](/platform/hosted-endpoints) — including bulk import from OpenAPI. See [Endpoint Commands](/sdk/endpoint-commands) for the full reference and [OpenAPI to Endpoints](/quick-starts/openapi-to-endpoints) for a walkthrough. --- ## SDK Architecture & Primitives ## x402 payment flow The x402 payment flow follows a request → challenge → authorize → retry loop: 1. Client calls a paid agent. 2. Server responds with `402 Payment Required`. 3. Client SDK asks the Treasurer whether to authorize. 4. If approved, the wallet produces a signed payment. 5. SDK retries the request with payment metadata. 6. Server verifies, executes the request, and returns a response. This loop is handled automatically by the SDK. --- ## Roles ### Seller (paid agent server) The seller: - Sets the price - Requires payment - Verifies payment on each request ### Buyer (calling agent / client) The buyer: - Calls paid services - Uses the SDK to handle payment detection and retries --- ## Key components ### 1. `X402Treasurer` Controls whether payments are approved or rejected. The treasurer is responsible for payment authorization decisions and can enforce spending policies, budgets, and user confirmations. #### `AmpersendTreasurer` (recommended) Recommended treasurer for production use. Required when using agents created on the ampersend Platform. - Connects your agent to the ampersend API - Enforces spending limits and budgets configured in the ampersend Platform - Reports spending and payment activity for monitoring and analytics - Provides centralized control and compliance features - Supports both EOA and Smart Account wallets #### `NaiveTreasurer` (testing only) Automatically approves all payments without any limits or monitoring. - Only for testing or when creating standalone agents not connected to the ampersend Platform - No spending limits or budget enforcement - No payment reporting or monitoring - Useful for demos and local development ### 2. `X402Wallet` Generates cryptographically signed payment payloads. Wallet types: - `AccountWallet` — EOA / private key - `SmartAccountWallet` — ERC-4337 + ERC-1271 signatures. Currently supports accounts with ERC-7579 and Rhinestone's OwnableValidator. **Note:** When using the ampersend Platform, agents always use a `SmartAccountWallet`. This provides enhanced security, programmability, and integration with the Platform’s management features. ### 3. Client components #### Python (A2A) - `X402Client` — A2A client with payment middleware - `X402RemoteA2aAgent` — Wrapper to call paid remote agents - `X402RemoteA2aAgentToolset` — Toolset that enables agents to use paid remote agents as tools #### TypeScript (MCP) - `X402McpClient` — MCP client that auto-handles x402 retries and signatures ### 4. Server components #### Python (A2A) - `to_a2a()` — turns an ADK agent into a paid A2A service - `make_x402_before_agent_callback()` — adds payment requirements #### TypeScript (MCP) - `withX402Payment()` — FastMCP middleware to require and verify payment --- ## Endpoint Commands The `ampersend endpoint` command group lets an agent manage its own hosted endpoints from the CLI. All commands authenticate as the agent using the active local config — no API key required. Requires `ampersend` v0.0.20 or later. Run `ampersend --version` to check, and follow the [SDK quick start](/quick-starts/sdk-quickstart) to install and run `ampersend setup`. All commands return the standard JSON envelope: ```json { "ok": true, "data": { /* ... */ } } ``` ```json { "ok": false, "error": { "code": "...", "message": "..." } } ``` ## Commands at a glance | Command | Purpose | | --------------------------------------- | ------------------------------------------ | | `endpoint list` | List the agent's hosted endpoints | | `endpoint get ` | Show a single endpoint | | `endpoint create` | Create a new hosted endpoint | | `endpoint update ` | Update one or more fields | | `endpoint delete ` | Delete an endpoint | | `endpoint enable ` / `disable ` | Toggle activation without deleting | | `endpoint test ` | Send a synthetic request through the proxy | | `endpoint headers ...` | Add or remove proxy / required headers | | `endpoint rotate-secret ` | Rotate the per-endpoint signing secret | | `endpoint import ` | Bulk create from OpenAPI 3.0 / 3.1 spec | ## endpoint list ```bash ampersend endpoint list ``` Returns an array of hosted endpoints owned by the authenticated agent. ## endpoint get ```bash ampersend endpoint get ``` ## endpoint create ```bash ampersend endpoint create \ --name \ --price-usd \ --proxy-url \ [options] ``` | Option | Description | | ---------------------------------- | -------------------------------------------------------------------------------- | | `--name ` | Display name (required) | | `--price-usd ` | Per-call price in USD (required, positive number) | | `--proxy-url ` | Upstream URL the proxy forwards to (required, http/https) | | `--description ` | Optional description | | `--methods ` | Allowed HTTP methods, comma-separated (default: `GET`) | | `--rate-limit ` | Global rate limit per minute | | `--timeout ` | Proxy timeout in milliseconds (5000–60000, default 30000) | | `--proxy-header ": "` | Header ampersend forwards to the upstream. Repeat for multiple. | | `--required-header ` | Header name the buyer must include on the incoming request. Repeat for multiple. | To create an endpoint in the disabled state, create it and then call `ampersend endpoint disable `. ## endpoint update ```bash ampersend endpoint update \ [--name ] [--price-usd ] [--proxy-url ] \ [--description ] [--methods ] \ [--rate-limit ] [--timeout ] \ [--enabled ] ``` Only the fields you pass are changed. `--enabled true` / `--enabled false` toggle activation; `enable` / `disable` are shorthand for the same operation. ## endpoint delete ```bash ampersend endpoint delete ``` ## endpoint enable / endpoint disable ```bash ampersend endpoint enable ampersend endpoint disable ``` A disabled endpoint is refused by the proxy without accepting payment. Re-enable with `endpoint enable`. ## endpoint test ```bash ampersend endpoint test ``` Sends a synthetic request through the proxy to verify the upstream is reachable and responds with the expected shape. Useful right after `create` or `update`. ## endpoint headers Two header lists are maintained per endpoint: - **Proxy headers** — added by ampersend to every upstream request (e.g., an upstream API key). Stored encrypted. - **Required headers** — headers the buyer must include on the incoming request. ```bash # Proxy headers (ampersend → upstream) ampersend endpoint headers add-proxy --name
--value ampersend endpoint headers remove-proxy # Required headers (caller → ampersend) ampersend endpoint headers add-required --name
ampersend endpoint headers remove-required ``` `remove-proxy` and `remove-required` take the header name as a positional argument. `add-proxy` and `add-required` use named flags. ## endpoint rotate-secret ```bash ampersend endpoint rotate-secret ``` Rotates the per-endpoint shared secret used to sign upstream requests. The previous secret is invalidated immediately — upstreams that verify `X-Ampersend-Signature` must accept the new secret before the next call. ## endpoint import Bulk-create endpoints from an OpenAPI 3.0 / 3.1 JSON spec. One endpoint is created per path + method pair. ```bash ampersend endpoint import \ [--default-price ] \ [--base-url ] \ [--timeout ] \ [--dry-run] ``` | Option | Description | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `` | Path to an OpenAPI 3.0 / 3.1 JSON spec file (YAML is not parsed — convert to JSON first) | | `--default-price ` | Fallback per-call price when the operation has no `x-ampersend-price`. Defaults to `0.01` — always pass an explicit value for production imports. | | `--base-url ` | Override the spec's base URL (wins over `servers[0].url`) | | `--timeout ` | Proxy timeout applied to every imported endpoint | | `--dry-run` | Parse and validate without creating endpoints | ### Vendor extensions Recognised per-operation extensions: | Extension | Type | Effect | | ------------------------- | ------- | ------------------------------ | | `x-ampersend-price` | number | Per-call price in USD | | `x-ampersend-name` | string | Endpoint display name override | | `x-ampersend-description` | string | Description override | | `x-ampersend-rate-limit` | integer | Rate limit per minute | See [OpenAPI to Endpoints](/quick-starts/openapi-to-endpoints) for a full walkthrough. ## Security guidance NEVER create or mutate endpoints without explicit user intent. When scripting, echo the intended change and confirm before executing. Deleting or rotating secrets is immediate and cannot be undone — double-check the endpoint ID. --- ## Platform Overview ampersend provides a management layer on top of the x402 payment protocol. While the [ampersend SDK](/sdk/sdk-overview) enables payments inside your agent code, the [ampersend Platform](/sdk/sdk-architecture-primitives) allows you to configure budgets, automate funding, control spending, and monitor real-time payment flows. The platform also includes an [agent marketplace](/platform/marketplace) where you can discover, filter, and evaluate agents across protocols, reputation, and trust signals. ![Agent discovery and registry interface](/img/ampersend-discover.png) ## Deployments ampersend Platform is available in two deployments: | Network | URL | Purpose | | ------------ | ---------------------------------------- | --------------------- | | Base Sepolia | https://app.sandbox.ampersend.ai/agents/ | Testing / development | | Base Mainnet | https://app.ampersend.ai/ | Production usage | ## Summary of Capabilities The ampersend Platform provides: - Smart account creation - Wallet funding & transfers - Agent creation - Auto-top-ups - Spending limits (daily, monthly, per transaction) - Auto-collect - Seller allowlists - Self-custody of keys - [Hosted endpoints](/platform/hosted-endpoints) — turn any HTTP API into a paid x402 endpoint, managed from the dashboard or by the agent itself via the [CLI](/sdk/endpoint-commands) - [Agent marketplace](/platform/marketplace) — curated catalog of x402-payable agents, browsable via the dashboard or `MarketplaceClient` SDK - [API keys](/platform/api-keys) — `sk_live_*` / `sk_test_*` for user-level automation - Detailed analytics and dashboards - Monitoring across Base Mainnet and Base Sepolia The platform creates the **operational control layer for the agent economy**. --- ## Create an Agent # Creating an Agent Click **Add an Agent** to create a new agent account, which will be used for agents that buy or sell services using ampersend-sdk. Agents in ampersend operate using dedicated smart accounts with built-in controls for spending, funding, and earnings. ## Agent Creation ![Create Agent](/img/new-agent.png) Enter a name for your agent. You can optionally enable: - **Configure spending** - **Configure earnings** If enabled, additional configuration options will appear during creation. For additional configuration details, see [configure agent](/platform/configure-agent). Click **Create** to initialize the agent. Each newly created agent receives: - A **Smart Account wallet** - A **Private Key** - A **Unique agent address** --- ## Configure an Agent # Configuration Agent configuration defines how an agent manages funds, enforces spending limits, and controls interactions with other agents. These settings set clear operational boundaries so agents can act autonomously without exceeding intended limits. Use this page to configure funding automation, spending controls, access restrictions, and agent keys. When creating an agent, these settings can be configured directly in the creation flow. --- ## Configure auto top-up ## ![Configure Spending](/img/configure-spending.png) Auto top-up automatically replenishes the agent’s wallet from your main account. Funds are topped up to the daily spending limit. The daily limit also serves as the target balance for auto-top-up behavior. Auto top-up ensures the agent has sufficient funds to operate without manual intervention, while still respecting defined spending constraints. --- ## Configure spending limits Spending limits define how much an agent can spend over time and per payment. All spending limits are enforced by the AmpersendTreasurer in the SDK. Three levels of spending control are available: | Limit Type | Description | | ------------------------- | ---------------------------------------------------------------------------- | | **Daily Limit** | Maximum total spend per day. Also used as the target amount for auto top-up. | | **Monthly Limit** | Maximum total spend per calendar month. | | **Per-transaction Limit** | Maximum amount allowed for a single payment. | These limits help prevent runaway spend or abuse when agents act autonomously. --- ## Configure auto-collect ![Configure Earnings](/img/configure-earnings.png) Auto-Collect is an automated mechanism that sweeps unused funds from an agent account back into a designated destination account. Its primary purpose is to reduce idle balances and centralize funds without manual action. ### How Auto-Collect Works When enabled, Auto-Collect continuously monitors the agent’s wallet balance. Once the predefined conditions are met, excess funds are transferred from the agent account. #### Configuration Fields The following fields control Auto-Collect behavior: - **Trigger threshold**: The balance level at which Auto-Collect activates and initiates a sweep - **Reserve amount**: The minimum balance that must remain in the agent account at all times. If auto top-up is enabled, this value must be greater than the daily spending limit - **Collection address**: An optional custom destination address. If set, collected funds are sent to this address instead of the main account --- ## Configure the seller allowlist The seller allowlist restricts which seller agents a buyer can interact with. - When configured, transactions are limited to sellers included in the allowlist - Leave the allowlist empty to allow interactions with all sellers --- ## Manage agent keys Agent keys are session keys used by the agent in your SDK integration. Use this section to add or rotate agent session keys. --- # Summary - **Create** -- initializes wallet + identity - **Configure spending** -- controls how funds are used - **Configure earnings** -- controls how funds are retained or returned These controls define the operational boundaries for autonomous agents. ![Full Configuration Options](/img/new-agent-setup.png) --- ## Manage Agent # Agent Management Once an agent is active, the dashboard displays its spend, earnings, top counterparties, and transaction history. ## Agent dashboard ![Ampersend Dashboard](/img/ampersend-dashboard.png) The dashboard shows: - **Spending volume** - **Net position** - **Earnings** (for sellers) - **Transaction-level events** - **Top spending by seller** - **Full activity feed** This provides visibility across x402-based transactions. --- ## Agent details ![Agent Details](/img/ampersend-agent.png) Selecting an agent opens a detailed view with configuration, endpoints, and reputation data. This view includes: - **Agent identity and address** - **Owner and registration details** - **Endpoints** (MCP, A2A, Web) - **Reputation and reviews** - **Description and metadata** - **Seller allowlist** This is the primary interface for inspecting and managing an individual agent. --- ## Activity monitoring and analytics The Platform provides real-time insight into: - Payment events - Seller and buyer rankings - Payment failures and retries - Net spending over time - Microtransaction patterns This transparency supports audit-ready monitoring and helps make agent-to-agent payments observable and controllable. --- ## Integrate SDK # SDK Integration ## Open setup instructions After creating or subscribing to an agent, open **Setup Instructions**. ## Copy values into your SDK configuration The setup screen provides the values you need to configure the ampersend SDK: - **Agent Address** - **Agent Key (private key)** - **API URL** - **Chain ID** Use these values in your SDK integration (Python A2A or TypeScript MCP). --- ## Hosted Endpoints A **hosted endpoint** turns any HTTP API into a paid x402 endpoint. The ampersend proxy collects payment, forwards the request to your upstream service, and returns the response to the caller. You keep your existing API. Agents earn revenue per call without changing the upstream at all. --- ## What a hosted endpoint does For every incoming call: 1. The proxy checks the `X-PAYMENT` header against the endpoint price. 2. If payment is valid, the proxy forwards the request to the configured `proxy_url`, stripping the payment header and adding any configured proxy headers. 3. The upstream response is returned verbatim to the caller. 4. The facilitator settles payment on chain. The proxy enforces pricing, rate limits, allowed methods, and required headers before forwarding traffic upstream. --- ## How pricing works Every endpoint has a per-call price in USD, settled in USDC on the configured network. | Setting | Description | | ----------------------- | ----------------------------------------------------------------------- | | `price_usd` | Amount charged per call, in USD | | `network` | `base` (mainnet) or `base-sepolia` (testnet) | | `allowed_methods` | Restrict to specific HTTP methods; omit to accept any | | `rate_limit_per_minute` | Optional per-endpoint rate limit across all callers (10–10000) | | `proxy_timeout_ms` | Timeout applied when the proxy calls your upstream | | `instructions` | Optional markdown rendered into the public `skill.md` for this endpoint | The facilitator converts `price_usd` to the token amount at call time. Payments settle into the endpoint owner's agent account. --- ## Headers Two independent header lists can be configured: - **Proxy headers** — added by ampersend to every upstream request (for example, an API key for the upstream). Stored encrypted at rest. - **Required headers** — headers the buyer must include on the incoming request. Useful for passing per-call context to the upstream. Endpoint signing secrets can be rotated with `rotate-secret` at any time. Upstreams can verify the `X-Ampersend-Signature` header to confirm that requests passed through the ampersend proxy. --- ## Agent-managed vs user-managed endpoints Hosted endpoints can be created and maintained by two audiences: | Audience | Authentication | Typical use | | --------- | ------------------------------- | ------------------------------------------------- | | **User** | Dashboard session | Operators listing an API they own | | **Agent** | Agent session token (SDK / CLI) | Agents autonomously listing services they provide | Both flows share the same schema and proxy behavior. - An endpoint owned by an agent can only be mutated by that agent's session. - An endpoint owned by a user can only be mutated through the dashboard. - Cross-agent and cross-user writes are rejected with `403`. --- ## Creating endpoints - **From the dashboard** — open your agent, go to **Endpoints**, click **Add endpoint**. - **From the CLI / SDK** — see [Endpoint Commands](/sdk/endpoint-commands) for the full command reference, or [OpenAPI to Endpoints](/quick-starts/openapi-to-endpoints) for bulk import. --- ## Related - [API Keys](/platform/api-keys) — authenticate automation against the Platform API - [Endpoint Commands](/sdk/endpoint-commands) — CLI reference - [OpenAPI to Endpoints](/quick-starts/openapi-to-endpoints) — bulk import walkthrough --- ## Agent Marketplace The **agent marketplace** is a curated catalog of x402-payable agents and the endpoints they expose. Buyers, including AI apps, autonomous agents, and dashboards, use the marketplace to discover services they can pay for per-call without contracts or accounts. --- ## Listings sources Marketplace listing come from three sources: | Source | What it is | | ----------- | ------------------------------------------------------------------------------------------ | | `catalog` | Hand-curated third-party x402 services (sales data, security scanners, content APIs, etc.) | | `bazaar` | Community-submitted listings (subject to review) | | `ampersend` | First-party Ampersend agents and hosted endpoints | --- ## Agent metadata Each marketplace entry includes: - **Identity** — name, description, category, tags, logo, public website, documentation URL - **Endpoints** — list of x402-payable URLs with method, network, pricing, and protocol version - **Skills** — optional `skill.md` integrations for agent frameworks - **Ampersend link** — the `ampersend_agent_address` field is set when the curated agent is also registered on Ampersend (i.e., you can also pay them via the ampersend wallet directly) --- ## Network filtering By default, the marketplace API filters endpoints to the network the deployment can settle on. The filter is driven by the API's `CHAIN_ID` environment variable (`8453` → `base`, `84532` → `base-sepolia`). - Sandbox and staging deployments only return Base Sepolia endpoints. - Production deployments only return Base mainnet endpoints. This prevents agents from discovering services they cannot pay for. You can override with `?network=base` or `?network=base-sepolia` if you need to browse cross-network (admin / catalog tooling). --- ## REST API The marketplace is **unauthenticated**. No API key or session token required. --- ### List agents ```http GET /api/v1/agents/marketplace ``` Query parameters (all optional): | Param | Type | Description | | ---------- | ------------------------------------ | ------------------------------------------------------------ | | `source` | `catalog` \| `bazaar` \| `ampersend` | Filter by listing source | | `category` | string | Exact-match category (e.g. `Crypto`, `Search`, `Compliance`) | | `search` | string | Substring match across name, description, category, and tags | | `network` | `base` \| `base-sepolia` | Override the default network filter | Returns an array of `CuratedAgentDTO`. --- ### Get one agent ```http GET /api/v1/agents/marketplace/{id} ``` Returns a single `CuratedAgentDTO` with its endpoints and skills, or `404` if not found. --- ## SDK usage ```typescript import { MarketplaceClient } from "@ampersend_ai/ampersend-sdk/ampersend"; // `apiUrl` defaults to https://api.ampersend.ai — pass a custom one for sandbox/staging. const marketplace = new MarketplaceClient(); // Browse the catalog const agents = await marketplace.listAgents({ category: "Crypto" }); for (const agent of agents) { console.log(agent.name, "—", agent.endpoints.length, "endpoints"); } // Drill into one agent const detail = await marketplace.getAgent(agents[0].id); for (const endpoint of detail.endpoints) { console.log(endpoint.url, endpoint.methods, endpoint.pricing_config); } ``` The marketplace client is read-only and unauthenticated, so you don't need an `ApiClient` or session key to use it. --- ## How to call a listed endpoint The marketplace returns the endpoint's `url` and pricing metadata. Invoking and endpoint follows the standard x402 flow: 1. Your agent has an Ampersend wallet (see [Create Agent](/platform/create-agent)). 2. Your HTTP client sends the request to the endpoint's `url`. 3. The endpoint returns `402 Payment Required` with the price and `payTo` address. 4. The Ampersend SDK's x402 middleware signs the payment from the agent's wallet, retries with `X-PAYMENT`, and returns the response. Spend caps and seller allowlists configured on the agent enforce limits — see [Configure Agent](/platform/configure-agent). --- ## Schema reference The full `CuratedAgentDTO` shape returned by the API: ```typescript { id: string name: string description: string | null source: "catalog" | "bazaar" | "ampersend" enabled: boolean category: string tags: string[] url: string | null logo_url: string | null docs_url: string | null ampersend_agent_address: string | null // FK to agent.address if also registered on Ampersend endpoints: CuratedAgentEndpointDTO[] skills: CuratedAgentSkillDTO[] created_at: number // epoch millis updated_at: number // epoch millis } ``` `CuratedAgentEndpointDTO`: ```typescript { id: string curated_agent_id: string url: string methods: ("GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS")[] x402_enabled: boolean x402_protocol_version: 1 | 2 network: string | null // "base" | "base-sepolia" | "solana" | ... description: string | null enabled: boolean pricing_config: { // x402 pricing payload amount: bigint // amount charged per request amountAtomicUnit: bigint // atomic unit of the asset; USDC has 6 decimals → $0.001 = 1000n currency: string // "USDC" networkCaip2ID: string // "eip155:8453" etc. assetAddress: string // ERC-20 contract for the payment asset payTo: string | null // recipient wallet x402Schema: "exact" | "deferred" | null } created_at: number updated_at: number } ``` `CuratedAgentSkillDTO`: ```typescript { id: string; curated_agent_id: string; name: string; instructions: unknown; // server-defined; varies by skill docs_url: string | null; skillmd_url: string | null; // direct link to a skill.md file created_at: number; updated_at: number; } ``` --- ## API Keys API keys let scripts, CI jobs, and provisioning tools call the ampersend Platform API on behalf of your user account. API keys are used for user-level automation workflows such as: - Provisioning agents - Managing agent keys - Exporting transaction data - Managing allowlists and top-up settings ## Key prefixes | Prefix | Environment | Notes | | ---------- | ------------ | -------------------------------------------- | | `sk_live_` | Base Mainnet | Issued from https://app.ampersend.ai | | `sk_test_` | Base Sepolia | Issued from https://app.sandbox.ampersend.ai | The prefix determines which deployment the key can access: a test key cannot call production and a production key cannot call sandbox. --- ## Creating a key 1. Open the dashboard (production or sandbox). 2. Go to **API Keys** in the user menu. 3. Click **Create API key**, give it a name, and copy the secret. :::caution The secret is only shown once. Store it in a secret manager or `.env` file immediately; the dashboard only keeps a hashed copy. ::: --- ## What you can do with an API key API keys authenticate user-session routes. Common automation tasks: - Create an agent account: `POST /agents` - Add an agent key: `POST /agents/{address}/keys` - Manage agents, allowlists, and top-up settings - Export transaction history and payment events For agent-scoped actions (such as managing the agent's own hosted endpoints), use the agent's session token instead. See [Endpoint Commands](/sdk/endpoint-commands). --- ## Using a key Pass the key as a bearer token: ```bash curl https://api.ampersend.ai/v1/agents \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" ``` In scripts, read the key from an environment variable: ```bash export AMPERSEND_API_KEY=sk_test_... ``` --- ## Rotation and revocation - **Rotate** — create a new key, update consumers, then revoke the old key. - **Revoke** — click **Revoke** next to the key in the dashboard. Revocation is immediate; any call with the revoked key returns `401`. Rotate keys regularly and any time a key may have leaked (for example, committed to git, shared in chat). Because only the hash is stored, revocation is the recovery path, and the original secret cannot be recovered. --- ## Security guidance - Never commit API keys to version control. Use `.env` files (gitignored) or a secret manager. - Use `sk_test_*` keys for CI and local development; reserve `sk_live_*` for production automation. - Scope automation to the minimum set of agents and operations required. --- ## Related - [Hosted Endpoints](/platform/hosted-endpoints) — the resource most automation targets - [Endpoint Commands](/sdk/endpoint-commands) — agent-scoped CLI that does not use API keys --- ## OpenClaw [Beta] # OpenClaw > **Beta** — The ampersend SDK (`v0.0.16`) and x402 protocol are under active development. APIs and workspace conventions may change between releases. Give an OpenClaw agent an ampersend wallet and spending controls so it can autonomously pay for x402-enabled APIs. By default, OpenClaw agents can call APIs but cannot pay for them. This integration gives your agent: - A **smart account wallet** provisioned through ampersend - **Transparent x402 payment handling** via the ampersend ClawHub skill - **Spending controls** — including per-transaction, daily, and monthly limits configured in the ampersend dashboard Once configured, the agent can pay for APIs automatically while remaining constrained by your spending limits. --- ## Prerequisites - Access to the **[ampersend platform](https://www.ampersend.ai/)** - An **OpenClaw agent runtime** - Ability to install **ClawHub skills** --- ## Setup ### 1. Create an ampersend agent Go to [ampersend](https://app.ampersend.ai) Create a new agent. Each agent is provisioned with: - **Smart Account wallet** - **Private key** - **Unique agent address** This wallet is used by the OpenClaw agent to authorize payments. > Save the private key. You will need it when configuring the skill. --- ## 2. Configure spending controls Before connecting the agent to OpenClaw, configure spending limits in the ampersend dashboard. These limits are enforced by the SDK and prevent uncontrolled spending. | Control | Description | | ------------------------- | ---------------------------------------------------------- | | **Per-transaction limit** | Maximum amount allowed for a single payment | | **Daily limit** | Maximum total spend per day | | **Monthly limit** | Maximum total spend per calendar month | | **Auto top-up** | Automatically replenishes the wallet up to the daily limit | | **Seller allowlist** | Restricts which APIs the agent can pay | See [Configure an Agent](/platform/configure-agent) for full configuration details. --- ## 3. Install the ampersend ClawHub skill Install the skill using ClawHub. ```bash npm i -g clawhub clawhub install ampersend ``` The skill enables automatic payment handling inside the OpenClaw runtime. --- ## 4. Configure the skill with your agent wallet Set the environment variables for the agent wallet. ``` AMPERSEND_API_URL=https://api.ampersend.ai AMPERSEND_AGENT_ADDRESS=0x... AMPERSEND_PRIVATE_KEY=0x... ``` Restart the OpenClaw agent runtime so the skill loads. --- ## How It Works The integration relies on two components. ### ampersend wallet When you create an agent on the ampersend platform, a **smart account wallet** is provisioned with a unique address and private key. This wallet is used by your OpenClaw agent to authorize API payments. ### Ampersend ClawHub skill The Ampersend skill is installed through **ClawHub**, OpenClaw's skill registry. The skill runs inside the agent runtime and handles x402 payments automatically. When the agent calls a paid API, the skill intercepts the response, signs the payment with the agent wallet, and retries the request with the payment attached. The agent receives the response as a normal API result. ### Payment Flow ``` Agent calls API └─ API returns 402 Payment Required └─ Ampersend skill signs + attaches payment └─ Request retried → API responds ``` --- ## Runtime Behavior After setup, the agent interacts with paid APIs the same way it interacts with any other API. When a request requires payment: 1. API returns `402 Payment Required` with amount, token (USDC), and recipient address 2. The ampersend skill checks the request against configured spending limits 3. If within limits, the skill signs the payment authorization using the agent wallet 4. The request is retried with the signed payment header 5. The API verifies the payment and executes the request 6. The agent receives the response If a payment would exceed a configured spending limit, the transaction is blocked before submission. --- ## Supported Services | Status | Capability | | ------ | ---------------------------- | | ✅ | x402-enabled APIs | | ✅ | HTTP endpoints | | ✅ | USDC payments on Base | | ❌ | API key-based services | | ❌ | Subscription or fiat billing | --- ## Skill Page The Ampersend skill is published on ClawHub at: [https://clawhub.ai/matiasedgeandnode/ampersend](https://clawhub.ai/matiasedgeandnode/ampersend) --- ## CrewAI Use ampersend Wallets and Guardrails with CrewAI Agents. This guide shows how to configure a CrewAI agent with an ampersend wallet so it can pay for services using USDC on Base. > In this example, the agent calls a paid joke API via an x402-enabled endpoint. The ampersend client handles payment settlement and automatically retries the request. --- ## How it works The CrewAI agent uses a tool that wraps an HTTP request with ampersend’s payment client. 1. The tool sends a request to an x402-enabled endpoint. 2. The server responds with a 402 Payment Required response and a price in USDC. 3. The ampersend client intercepts the response. 4. The client signs the payment using the agent’s session key. 5. Payment settles on Base. 6. The client automatically retries the original request. This flow does not require: - API keys - OAuth - Billing dashboards The agent uses its wallet to complete the payment handshake through x402. --- ## Prerequisites Before you begin, make sure you have: - [Claude Code install](https://claude.ai/download/claude-code) - The UV package manager will be installed - An ampersend agent with a funded smart wallet from the ampersend dashboard ## Setup ### 1. Clone the repository ```bash git clone https://github.com/marcusrein/ampersend-crewai cd ampersend-crewai uv sync ``` --- ### 2. Configure credentials Copy the example environment file: ```bash cp .env.example .env ``` Add the following values to `.env`: - ampersend smart account address - session key private key You can find both values in the ampersend dashboard. --- ### 3. Run the agent ```bash uv run python crew.py ``` The agent calls the paid joke API. If the payment succeeds and the request completes, the API returns a joke. --- ### 4. Extend the integration You can replace the joke API with any x402-enabled service. Examples include: - ZK proof generation - Compute services - Data feeds The payment flow remains the same: - x402 handles the payment protocol - settlement occurs in USDC on Base - ampersend manages payment guardrails and execution --- ## Hermes The `@ampersend/hermes` package adds support for x402 payments within Hermes Agent workflows. It includes built-in tools for MCP-based payment proxying, agent identity management via the ampersend dashboard, and client-side controls to validate transactions before submitting requests. Developed as a typed wrapper around `@ampersend_ai/ampersend-sdk`, this offers sensible defaults for common Hermes workflows. Features include automated agent setup through an approval process, Hermes configuration patching for MCP payment proxying, and pre-flight spend validation. While it is optimized for use with Hermes, the package is also flexible enough to integrate with other agent frameworks. --- ## Overview By default, the package uses: - Base mainnet - Production [ampersend API](https://api.ampersend.ai) No flags required for production use. ## Setup (Recommended Flow) Use the two-step bootstrap flow for Hermes, CI environments, and non-TTY shells. ### 1. Clone and install ```bash git clone https://github.com/edgeandnode/ampersend-hermes.git cd ampersend-hermes pnpm install ``` --- ### 2. Start Bootstrap ```bash pnpm bootstrap start --name my-hermes-agent ``` The command generates a key and requests approval. --- ### 3. Approve the agent Open the `user_approve_url` in the ampersend dashboard and approve the request. --- ### 4. Finish bootstrap ```bash pnpm bootstrap finish ``` This polls for approval and activates the agent. > Run these commands from the repository root directory that contains `package.json`. --- ## One-Command Setup Run the full setup flow in a single command: ```bash pnpm setup --name my-hermes-agent ``` This command: 1. Requests approval 2. Waits for approval 3. Patches the Hermes config 4. Starts the MCP proxy After setup completes: 1. Switch back to Hermes 2. Run: ```bash /reload-mcp ``` --- ## Manual Installation ### 1. Configure environment variables ```bash cd ampersend-hermes cp .env.example .env ``` Fill in: - `AMPERSEND_AGENT_KEY` - `AMPERSEND_AGENT_ACCOUNT` --- ### 2. Install dependencies and build ```bash pnpm install && pnpm build ``` --- ## Configuration All environment variables are validated at startup using Zod. Required variables: - `AMPERSEND_AGENT_KEY` - `AMPERSEND_AGENT_ACCOUNT` All other values default to Base mainnet and the production ampersend API. | Variable | Required | Default | Description | | -------------------------- | -------- | -------------------------- | ---------------------------------------------- | | `AMPERSEND_AGENT_KEY` | Yes | — | 0x-prefixed session key private key (66 chars) | | `AMPERSEND_AGENT_ACCOUNT` | Yes | — | 0x-prefixed smart account address (42 chars) | | `AMPERSEND_API_URL` | No | `https://api.ampersend.ai` | ampersend API base URL | | `AMPERSEND_NETWORK` | No | `base` | Network: `base` or `base-sepolia` | | `AMPERSEND_CHAIN_ID` | No | `8453` | Chain ID derived from the network | | `AMPERSEND_MCP_PROXY_PORT` | No | `3000` | MCP proxy listen port | | `AMPERSEND_ENV_FILE` | No | — | Absolute path to `.env` | | `HERMES_CONFIG_DIR` | No | `~/.hermes` | Hermes config directory | ## Override config in tests ```bash import { loadConfig } from "@ampersend/hermes"; const cfg = loadConfig({ AMPERSEND_AGENT_KEY: "0x...", }); ``` --- ## Patch Hermes Config Register ampersend under `mcp_servers.ampersend`. ## Default stdio transport Recommended configuration: ```bash import { patchHermesConfig } from "@ampersend/hermes"; await patchHermesConfig("~/.hermes"); ``` This writes an stdio server entry that runs the ampersend MCP proxy via `npx` with agent credentials set in the environment. The proxy handles: - SIWE authentication - x402 payments ## HTTP transport Connect to an existing proxy: ```bash await patchHermesConfig("~/.hermes", { transport: "http", proxyPort: 3000, }); ``` ## Reload the MCP configuration. Apply changes in Hermes: ```bash /reload-mcp ``` --- ## Setup Options ```bash pnpm setup --name my-agent --proxy-port 4000 ``` Use a custom proxy port. ```bash pnpm setup --name my-agent --no-proxy ``` Patch configuration only. ```bash pnpm setup --name my-agent --daily-limit 10000000 ``` Set a daily limit of 10 USDC. ```bash pnpm setup --name my-agent --network base-sepolia ``` Use Base Sepolia for development. ```bash pnpm setup -h ``` Show all setup options. --- ## Fetch Paid x402 URLs Do not use `getApiClient()` for arbitrary HTTPS URLs. Use one of the following instead: | Method | Use case | | ----------------------- | ----------------------------- | | `ampersend fetch ` | CLI usage and quick tests | | `getPaidFetch()` | TypeScript paid fetch support | ## Use getPaidFetch ```bash import { getPaidFetch } from "@ampersend/hermes"; async function main() { const fetchPaid = getPaidFetch(); const res = await fetchPaid( "https://example.com/x402-endpoint" ); console.log(await res.text()); } void main(); ``` ## Inspect pricing without paying ```bash ampersend fetch --inspect https://example.com/x402-endpoint ``` --- ## Authorize Payments Use the ampersend API to authorize payments with spend limits. ## Direct authorization ```bash import { authorizePayment, } from "@ampersend/hermes"; const result = await authorizePayment({ requirements: [ { scheme: "exact", network: "base", maxAmountRequired: "1000000", resource: "https://api.example.com/resource", description: "Example resource", mimeType: "application/json", payTo: "0x0000000000000000000000000000000000000001", maxTimeoutSeconds: 60, asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", }, ], context: { method: "tools/call", serverUrl: "https://api.example.com", }, }); ``` ## Create a configured treasurer ```bash import { getTreasurer } from "@ampersend/hermes"; const treasurer = getTreasurer(); ``` --- ## Client-Side Guardrails Validate payments before sending API requests. ## Create a spending policy ```bash import { validatePayment, buildSpendPolicy, } from "@ampersend/hermes"; const policy = buildSpendPolicy({ perTxLimit: "1000000", dailyLimit: "10000000", networks: ["base"], }); ``` ## Validate a payment **Valid payment**: ```bash validatePayment( { amount: "500000", network: "base", resource: "/api/data", }, policy, ); ``` **Invalid payment**: ```bash validatePayment( { amount: "2000000", network: "base", resource: "/api/data", }, policy, ); ``` Throws: `SpendLimitViolationError (PER_TX_LIMIT_EXCEEDED)` --- ## Agent Management Create and manage agents through the ampersend approval flow. ## Request approval ```bash import { requestAgentApproval, waitForApproval, getAgentStatus, } from "@ampersend/hermes"; const pending = await requestAgentApproval( "0xAgentKeyAddress", { name: "my-agent", dailyLimit: "10000000", }, ); console.log( "Approve at:", pending.userApproveUrl, ); ``` ## Wait for approval ```bash . const result = await waitForApproval( pending. token, { timeoutMs: 600_000, }, ); ``` ## Check agent status `const status = await getAgentStatus();` --- ## Development Commands ```bash pnpm dev ``` Run in watch mode. ```bash pnpm test ``` Run tests. ```bash pnpm test: watch ``` Run tests in watch mode. ```bash pnpm build ``` Compile to dist/. ```bash pnpm bootstrap start --name agent ``` Request approval. ```bash pnpm bootstrap finish ``` Poll and activate the agent. ```bash pnpm setup --name agent ``` Run the full setup flow. ```bash pnpm proxy ``` Start the MCP proxy only. --- ## Architecture ```bash src/ config.ts client.ts dotenv-path.ts errors.ts bootstrap.ts bootstrap-cli.ts setup.ts mcp/ index.ts hermes-config.ts proxy-cli.ts payment/ index.ts guardrails.ts history.ts agents/ index.ts index.ts ``` --- ## Module Overview | Path | Purpose | | ----------------------- | --------------------------------------------------- | | `config.ts` | Zod-validated config and `needsBootstrap()` | | `client.ts` | API clients, paid fetch support, treasurer creation | | `dotenv-path.ts` | `.env` resolution logic | | `errors.ts` | Typed error classes | | `bootstrap.ts` | Two-phase bootstrap flow | | `bootstrap-cli.ts` | CLI for bootstrap commands | | `setup.ts` | Unified setup CLI | | `mcp/hermes-config.ts` | Hermes config patching | | `mcp/proxy-cli.ts` | MCP proxy runner | | `payment/guardrails.ts` | Spend limit validation | | `agents/index.ts` | Agent approval flow | | `index.ts` | Public exports | --- ## Additional Technical Information For full source code, configuration files, and the latest updates, visit the official [repository](https://github.com/edgeandnode/ampersend-hermes). --- --- ## OpenShell / NemoClaw # Open Shell / NemoClaw Sandbox Use ampersend inside NemoClaw sandboxes to enable autonomous agent payments using smart account wallets and the x402 protocol. This guide covers: - Setting up a sandbox environment - Configuring ampersend - Connecting to a running sandbox - Making x402-enabled payments - Troubleshooting common issues --- ## Prerequisites Before starting, make sure you have: - Docker Desktop running locally (with at least 5 GB of free disk space) - An [NVIDIA API key](https://build.nvidia.com/settings/api-keys) - `openshell >= 0.0.20` - [Node.js](https://nodejs.org) and [npm](https://www.npmjs.com) installed Install OpenShell: ```bash uv tool install -U openshell ``` > Older OpenShell versions can cause sandbox crashes. --- ## Setup ### 1. Configure Clone the repository and install dependencies: ```bash git clone https://github.com/edgeandnode/ampersend-nemoclaw.git cd ampersend-nemoclaw npm install cp .env.example .env # then edit .env ``` Configure required environment variables inside `.env`: | Variable | Required | Description | | ------------------- | -------- | --------------------------------- | | `NVIDIA_API_KEY` | Yes | NVIDIA API key for NemoClaw | | `AMPERSEND_API_URL` | Optional | Override ampersend API URL | | `AMPERSEND_NETWORK` | Optional | Network: `base` or `base-sepolia` | --- ### 2. Start the Gateway On your Mac: ```bash openshell gateway start --plaintext ``` --- ### 3. Run Setup ```bash npm run setup:docker ``` This single command: - Installs OpenShell, Node.js, and NemoClaw in a temporary Docker container - Registers the gateway and creates a sandbox (`my-assistant`) - Applies the ampersend OpenShell policy - Installs the ampersend CLI (`@ampersend_ai/ampersend-sdk`) - Uploads and installs the ampersend OpenClaw plugin - Installs any skills listed in `config/skills-to-install.txt` --- ### 4. Connect to the Sandbox **Option 1: Connect with npm** ```bash npm run connect ``` **Option 2: Connect with Docker** ```bash docker ps docker exec -it bash ``` --- ### 5. Set Up ampersend Inside the sandbox: ```bash # Two-step setup: generates a key, you approve in a browser ampersend setup start --name "my-assistant" # Returns: {"ok": true, "data": {"token": "...", "user_approve_url": "https://...", "agentKeyAddress": "0x..."}} # Show the user_approve_url to the human so they can approve in their browser. # Poll for approval and activate ampersend setup finish # Returns: {"ok": true, "data": {"agentKeyAddress": "0x...", "agentAccount": "0x...", "status": "ready"}} # Verify ampersend config status ``` Or via the OpenClaw plugin: ```bash openclaw ampersend setup --name "my-assistant" openclaw ampersend status ``` --- ### 6. Make Payments **GET request with automatic x402 payment** ```bash ampersend fetch ``` **POST with headers and body** ```bash ampersend fetch -X POST \ -H "Content-Type: application/json" \ -d '{"key":"value"}' \ ``` **Check payment requirements without paying** ```bash ampersend fetch --inspect ``` All commands return JSON. Successful `fetch` responses include: - `data.status` - `data.body` - `data.payment` (when a payment was made) --- ### 7. Add x402 Payment Endpoints to the Network Policy The OpenShell sandbox blocks all outbound traffic by default. The included policy (`config/ampersend-openshell-policy.yaml`) already allows `api.ampersend.ai` (for setup/auth), Base RPC (for on-chain signing), and `httpay.xyz` (as a sample x402 server). If your agent needs to pay a different x402-enabled server, you must add it to the policy. Open `config/ampersend-openshell-policy.yaml` and add an entry under `network_policies`. For example, to allow `api.example.com`: ```yaml my_x402_server: name: my-x402-server endpoints: - host: api.example.com port: 443 protocol: rest tls: terminate enforcement: enforce access: read-write binaries: - path: /usr/bin/node - path: /usr/bin/npx - path: /sandbox/.local/bin/** ``` Or add the host to the existing `x402_endpoints` block: ```yaml x402_endpoints: name: x402-payment-endpoints endpoints: - host: httpay.xyz port: 443 protocol: rest tls: terminate enforcement: enforce access: read-write - host: api.example.com # ← add your host here port: 443 protocol: rest tls: terminate enforcement: enforce access: read-write binaries: - path: /usr/bin/node - path: /usr/bin/npx - path: /sandbox/.local/bin/** ``` Then hot-reload the policy on the live sandbox (no restart needed): ```bash openshell policy set my-assistant --policy config/ampersend-openshell-policy.yaml ``` > **Note:** The `filesystem_policy.read_only` list must include all paths from the base image (e.g. `/app`, `/var/log` for OpenClaw). If you see an error like `"path '/app' cannot be removed on a live sandbox"`, add the missing path to the `read_only` list and retry. --- ## Common Commands | Command | Description | | ------------------------------ | ------------------------------------------------------------------------------------------------- | | `npm run setup:docker` | One-shot: install, gateway, create sandbox, apply ampersend policy, install CLI + plugin + skills | | `npm run connect` | Connect to the sandbox | | `npm run plugin:upload` | Upload the ampersend plugin bundle to the sandbox | | `npm run nemoclaw:interactive` | Start an interactive Docker shell for manual NemoClaw steps | | `npm test` | Run tests (policy, blueprint, plugin) | | `npm run test:ampersend` | Test ampersend CLI config and API reachability | --- ## Troubleshooting **Sandbox stuck in `Provisioning` or `CrashLoopBackOff` with gRPC "Unimplemented"** This is an openshell version mismatch. The CLI must be `>= 0.0.20`. Check with `openshell --version`. Upgrade: ```bash uv tool install -U openshell ``` Then destroy and restart: ```bash openshell gateway destroy && openshell gateway start --plaintext ``` --- **Docker disk full / sandbox image keeps getting garbage-collected** If Kubernetes disk usage exceeds 85%, it garbage-collects the 1.4 GB OpenClaw image in a loop. Free space: ```bash docker system prune -a --volumes -f ``` The setup script checks for this and warns you. --- **`Gateway failed to start`** Exit the container. In Docker Desktop → Settings → Docker Engine, add the following to the JSON and restart: ```json "default-cgroupns-mode": "host" ``` --- **`Connection refused` when running `openshell sandbox list` inside the container** You skipped gateway registration. Run: ```bash openshell gateway add https://host.docker.internal:8080 --local ``` --- **`invalid peer certificate: BadSignature`** Start a plaintext gateway: ```bash openshell gateway start --plaintext ``` --- **`ampersend command not found` inside sandbox** If you used `npm run setup:docker`, reconnect — the CLI auto-installs on login. Otherwise install manually: ```bash npm install -g @ampersend_ai/ampersend-sdk@0.0.16 --prefix /sandbox/.local --ignore-scripts chmod +x /sandbox/.local/bin/ampersend export PATH="/sandbox/.local/bin:$PATH" ``` --- **`npm install -g` EACCES / permission denied inside sandbox** The sandbox runs as non-root user `sandbox`. Use `--prefix /sandbox/.local` instead of a global install. Add `--ignore-scripts` to skip native builds (the network policy blocks `nodejs.org`). --- **Stale Python venv (bad interpreter error in `test-blueprint.sh`)** If the repo was moved or renamed, delete the old venv and re-run: ```bash rm -rf .venv npm test ``` --- ## Additional Technical Information For full source code, configuration files, and the latest updates, visit the official **[repository](https://github.com/edgeandnode/ampersend-nemoclaw)** --- ## BlockRun AgentOps # BlockRun: AgentOps Ampersend and BlockRun provide infrastructure for secure, observable, and programmable AI agent payments using x402, A2A communication, and onchain authorization flows. This guide shows how to: - Run buyer and seller AI agents locally - Process AI-to-AI payments through x402 - Connect agents to BlockRun using X402Transport - Configure smart accounts and session keys - Test autonomous payment workflows on Base Sepolia The example architecture uses: - ADK Agents - LiteLLM - x402 payment flows - BlockRun inference APIs - Base Sepolia testnet infrastructure --- ## Architecture ```text Buyer ↓ A2A (x402: buyer pays seller) ↓ Seller (ADK Agent + LiteLLM) ↓ X402Transport ↓ BlockRun API ``` ## Components ### Seller An ADK Agent with a LiteLLM model backend. Responsibilities: - Receives A2A requests - Charges buyers through x402 - Forwards requests to BlockRun through `X402Transport` - Handles payment signing transparently ### Buyer A simple `X402RemoteA2aAgent`. Responsibilities: - Proxies requests to the seller via A2A - Handles x402 payments automatically --- ## Setup ### 1. Install dependencies ```bash uv sync ``` ### 2. Start the seller Run in Terminal 1: ```bash uv run python examples/a2a_communication.py --seller ``` ### 3. Run the Buyer #### One-shot Run in Terminal 2: ```bash uv run python examples/a2a_communication.py --buyer --prompt "What is 2+2?" ``` #### Interactively via ADK Run in Terminal 2: ```bash uv run -- adk run src/blockrun_agent/buyer_a2a ``` --- ## Environment Variables | Variable | Purpose | | ------------------------------ | ------------------------------------------------------------------- | | `SELLER_SMART_ACCOUNT_ADDRESS` | Seller wallet address. Receives buyer payments and pays BlockRun. | | `SELLER_SESSION_KEY` | Seller session key used for signing. | | `BUYER_SMART_ACCOUNT_ADDRESS` | Buyer wallet address used to pay the seller. | | `BUYER_SESSION_KEY` | Buyer session key used for signing. | | `AMPERSEND_API_URL` | Ampersend API endpoint. Default: `https://api.staging.ampersend.ai` | --- ## Seller Setup ### Programmatic setup ```python from blockrun_agent import SellerAgent, SellerConfig config = SellerConfig( smart_account_address="0x...", session_key_private_key="0x...", network="base-sepolia", model="openai/gpt-oss-20b", ) seller = SellerAgent(config=config) await seller.serve() # Starts on http://0.0.0.0:8001 ``` ### Run with Uvicorn ```bash uvicorn blockrun_agent.seller:a2a_app --port 8001 ``` --- ## Development ### Install development tools ```bash uv sync --group dev ``` ### Lint ```bash uv run ruff check src/ examples/ ``` ### Format ```bash uv run ruff format src/ examples/ ``` ### Type check ```bash uv run mypy src/ ``` --- ### Testnet BlockRun provides a Base Sepolia testnet environment for development. Use testnet USDC from public faucets. | Setting | Mainnet | Testnet | | ------- | ---------------------------- | ------------------------------------------- | | API URL | `https://blockrun.ai/api/v1` | `https://testnet.blockrun.ai/api/v1` | | Network | `base` (Chain 8453) | `base-sepolia` (Chain 84532) | | Models | 26 production models | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ### Faucets - [Alchemy ETH Faucet](https://www.alchemy.com/faucets/base-sepolia) - [Circle USDC Faucet](https://faucet.circle.com/) --- ## On-Chain Proof Verified Base Sepolia transaction showing the x402 payment flow. | Field | Value | | ----------- | --------------------------- | | Transaction | `0xf77aca47...ecddd3` | | Network | Base Sepolia (Chain 84532) | | Value | `0.001 USDC` | | Method | `transferWithAuthorization` | --- ## Additional Technical Information For full source code, configuration files, and the latest updates, visit the official [repository](https://github.com/edgeandnode/ampersend-blockrun-agentops-demo). ---