# Modexia AgentPay — Complete Documentation for AI Agents > This is the comprehensive, AI-ingestible documentation for Modexia AgentPay — the financial infrastructure layer for autonomous AI agents. This document contains everything an AI assistant needs to generate working Modexia integrations, troubleshoot errors, and understand the platform architecture. --- # 1. PLATFORM OVERVIEW Modexia AgentPay enables AI agents to hold USDC wallets, execute autonomous payments, navigate HTTP 402 paywalls, and operate within configurable spending policies — all without requiring the agent (or the developer) to manage private keys or interact with raw blockchain code. ## What Modexia Solves Traditional payment infrastructure (Stripe, PayPal, Square) is designed for human-initiated transactions with manual approval flows. AI agents need a fundamentally different model: - **Autonomous execution** — agents must pay for resources without human approval at transaction time - **Programmable guardrails** — spending must be bounded by policies that agents cannot bypass - **Machine-to-machine settlement** — USDC stablecoin for instant, borderless settlement - **Protocol-native integration** — HTTP 402 paywall support, MCP tools, LangChain bindings Modexia provides all of this as managed infrastructure so developers can focus on their agent's logic, not payment plumbing. ## How It Works 1. **Developer signs up** at https://modexia.software and receives an API key (`mx_test_...` for testnet, `mx_live_...` for mainnet) 2. **A Circle MPC wallet** is automatically provisioned for the developer's account on the Base network 3. **Developer funds the wallet** using integrated fiat on-ramps (Coinbase, MoonPay) — credit card to USDC in seconds 4. **Agent uses the SDK** to check balance, send payments, fetch paid resources, and transfer cross-chain 5. **All transactions** are recorded on-chain and visible in the Modexia dashboard ## Supported Networks - **Base Mainnet** — primary network for production transactions - **Base Sepolia** — free testnet for development and testing - Cross-chain destinations: Ethereum, Arbitrum, Optimism, Polygon, Solana, Akash Network --- # 2. PYTHON SDK REFERENCE ## Installation ```bash pip install modexiaagentpay ``` ## Initialization ```python from modexia import ModexiaClient # Testnet client = ModexiaClient(api_key="mx_test_your_key_here") # Mainnet client = ModexiaClient(api_key="mx_live_your_key_here") ``` The SDK includes connection pooling via `requests.Session()`, automatic retries with exponential backoff (up to 3 attempts), and typed exception classes. ## Methods ### retrieve_balance() Returns the current USDC balance of the agent's wallet as a string. ```python balance = client.retrieve_balance() print(f"Agent balance: {balance} USDC") # Output: "Agent balance: 42.50 USDC" ``` ### transfer(recipient, amount) Sends USDC from the agent's wallet to any address on the Base network. ```python receipt = client.transfer( recipient="0x742d35Cc6634C0532925a3b844Bc9e7595f2bD15", amount=5.0 ) print(f"Transaction ID: {receipt.txId}") print(f"Status: {receipt.status}") ``` Parameters: - `recipient` (str): Destination wallet address (0x...) - `amount` (float): Amount in USDC (e.g., 5.0 = $5.00) The 1% platform fee is automatically added. So `amount=5.0` will deduct 5.05 USDC from the agent's wallet. ### get_history(limit=5) Returns recent transaction history for the agent. ```python history = client.get_history(limit=10) for tx in history: print(f"{tx.timestamp} | {tx.type} | {tx.amount} USDC | {tx.status}") ``` ### smart_fetch(url, params=None) Fetches a URL and automatically handles HTTP 402 Payment Required responses. This is the core method for autonomous API consumption. ```python # Agent tries to access a paid API response = client.smart_fetch("https://api.example.com/premium-data") # If the API returns 402, smart_fetch automatically: # 1. Detects the 402 response # 2. Parses the payment header (amount, recipient) # 3. Negotiates payment through ModexiaRouterV3 # 4. Attaches cryptographic proof of payment # 5. Retries the request with payment proof # The developer sees only the final successful response print(response.status_code) # 200 print(response.json()) # The actual data ``` If `smart_fetch` returns a response with `status_code == 402`, it means automatic negotiation failed (likely due to insufficient funds or a policy violation). ### cross_chain_transfer(to_chain, to_token, recipient, amount) Transfers USDC from the agent's Base wallet to any supported chain via Circle CCTP and Squid Router. Gas is abstracted — no native tokens needed on the destination chain. ```python # Transfer 10 USDC to an Ethereum address receipt = client.cross_chain_transfer( to_chain="1", # Ethereum chain ID to_token="0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", # USDC on Ethereum recipient="0x742d35Cc6634C0532925a3b844Bc9e7595f2bD15", amount=10.0 ) print(f"Cross-chain TX: {receipt.txId}") # Track on Squidscan or Axelarscan ``` Supported destination chains: - Ethereum (Chain ID: `1`) - Arbitrum (Chain ID: `42161`) - Optimism (Chain ID: `10`) - Polygon (Chain ID: `137`) - Solana (via specialized routing) - Akash Network (Chain ID: `akashnet-2`) Settlement time: 3-10 minutes depending on destination chain finality. ### Payment Channel Methods For high-frequency micropayments (e.g., streaming API consumption): ```python # Open a channel with 50 USDC locked channel = client.open_channel(provider="0xProviderAddress...", amount=50.0) # Consume incrementally as the agent uses the service client.consume_channel(channel_id=channel.id, amount=0.01) client.consume_channel(channel_id=channel.id, amount=0.01) # Settle when done — provider gets consumed amount, agent gets refund client.settle_channel(channel_id=channel.id) ``` --- # 3. ERROR HANDLING ## Exception Hierarchy All Modexia exceptions inherit from `ModexiaError`. ```python from modexia import ModexiaClient, ModexiaAuthError, ModexiaPaymentError, ModexiaNetworkError client = ModexiaClient(api_key="mx_test_...") try: receipt = client.transfer(recipient="0x...", amount=100.0) except ModexiaAuthError as e: # HTTP 401/403 — invalid, expired, or incorrectly scoped API key # Action: Stop execution, check API key in Dashboard print(f"Auth error: {e}") except ModexiaPaymentError as e: # HTTP 400/422 — transaction logic failure # Action: Check balance, check spending policies print(f"Payment error: {e}") except ModexiaNetworkError as e: # HTTP 5xx or timeout — transient connectivity issue # Action: SDK handles up to 3 retries automatically print(f"Network error: {e}") ``` ## API Error Codes ### Financial Failures - `INSUFFICIENT_FUNDS` — wallet doesn't have enough USDC (amount + 1% fee) - `TRANSFER_FAILED` — blockchain transaction reverted. Check `txHash` on Basescan - `DUPLICATE_IDEMPOTENCY_KEY` — transaction with this key already processed in last 24 hours ### Policy Violations - `DAILY_LIMIT_EXCEEDED` — agent hit 24-hour spending cap - `MAX_PER_REQUEST_EXCEEDED` — single payment exceeds configured safety limit - `UNAUTHORIZED_RECIPIENT` — destination address not on allowlist (restricted mode) ## Best Practices for AI Agents 1. Always wrap Modexia calls in try/except blocks 2. Log the `txId` even for failed transactions — useful for debugging 3. Use `wait=True` (default) to ensure transaction finality before proceeding 4. Check `retrieve_balance()` before large transfers --- # 4. MCP SERVER The Modexia MCP Server exposes wallet operations as Model Context Protocol tools, enabling seamless integration with Claude Desktop, Cursor, and any MCP-compatible AI host. ## Installation ```bash uvx modexia-mcp ``` Or install via pip: ```bash pip install modexia-mcp ``` ## Configuration Set your API key as an environment variable: ```bash export MODEXIA_API_KEY="mx_test_your_key_here" ``` For Claude Desktop, add to `claude_desktop_config.json`: ```json { "mcpServers": { "modexia": { "command": "uvx", "args": ["modexia-mcp"], "env": { "MODEXIA_API_KEY": "mx_test_your_key_here" } } } } ``` ## Available MCP Tools The MCP server exposes these tools that AI agents can call: - `check_balance` — Get current wallet USDC balance - `send_payment` — Transfer USDC to a recipient address - `get_transaction_history` — View recent transactions - `smart_fetch` — Fetch a URL with automatic 402 paywall handling - `cross_chain_transfer` — Move USDC to another blockchain No SDK code needed — agents interact via the MCP standard protocol. --- # 5. JAVASCRIPT / TYPESCRIPT SDK ## Installation ```bash npm install @modexia/sdk ``` ## Usage ```typescript import { ModexiaClient } from '@modexia/sdk'; const client = new ModexiaClient({ apiKey: 'mx_test_...' }); // Check balance const balance = await client.retrieveBalance(); console.log(`Balance: ${balance} USDC`); // Send payment const receipt = await client.transfer({ recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f2bD15', amount: 5.0, }); console.log(`TX: ${receipt.txId}`); ``` --- # 6. LANGCHAIN INTEGRATION ```bash pip install langchain-modexia ``` ```python from langchain_modexia import ModexiaToolkit # Create tools for your LangChain agent toolkit = ModexiaToolkit(api_key="mx_test_...") tools = toolkit.get_tools() # Tools include: check_balance, send_payment, smart_fetch, etc. # Pass these to your LangChain agent as standard tools ``` --- # 7. REST API All SDK operations are available via direct HTTP calls. Base URL: `https://api.modexia.software` ### Authentication Include your API key in the `x-modexia-key` header: ```bash curl -H "x-modexia-key: mx_test_your_key_here" \ https://api.modexia.software/v1/balance ``` ### Endpoints - `GET /v1/balance` — Returns current wallet balance - `POST /v1/transfer` — Send USDC to a recipient - Body: `{ "recipient": "0x...", "amount": 5.0 }` - `GET /v1/history?limit=10` — Transaction history - `POST /v1/smart-fetch` — Fetch URL with 402 handling - Body: `{ "url": "https://api.example.com/data" }` - `POST /v1/cross-chain` — Cross-chain USDC transfer - Body: `{ "to_chain": "1", "to_token": "0x...", "recipient": "0x...", "amount": 10.0 }` --- # 8. SPENDING POLICIES (MASTER GUARD) Spending policies are server-side AND on-chain guardrails that control what agents can spend. They are enforced by the Master Guard V3 smart contract — agents cannot bypass them even if their logic is compromised. ## Configuration Options - **Daily limit** — Maximum USDC an agent can spend in 24 hours - **Hourly limit** — Maximum USDC per hour - **Per-request limit** — Maximum single transaction amount - **Provider allowlist** — Restrict payments to approved recipient addresses only Policies are configured in the Modexia Dashboard or via API. --- # 9. ARCHITECTURE ``` ┌─────────────────────────────────────────────────────────┐ │ AI AGENT │ │ (Holds API key, makes autonomous payment decisions) │ └────────────────────┬────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────┐ │ MODEXIA PLATFORM │ │ │ │ [API Gateway] → [Auth] → [Policy Engine] │ │ ↓ │ │ [Payment Engine] → [Web3 Gateway] → [On-Chain] │ │ ↓ │ │ [Transaction Ledger] ← [Blockchain Verification] │ └─────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────┐ │ SERVICE PROVIDER │ │ (Receives USDC payment, provides compute/API access) │ └─────────────────────────────────────────────────────────┘ ``` ### Tech Stack - **Frontend**: Next.js (App Router), Tailwind CSS, Framer Motion - **Backend**: Node.js / Express.js - **Database**: PostgreSQL (pgvector) on Supabase - **Wallets**: Circle MPC (developer-controlled, non-custodial) - **Smart Contracts**: ModexiaRouterV3, MasterGuardV3 on Base - **Auth**: Supabase Auth + API keys (`mx_test_...` / `mx_live_...`) - **Cross-Chain**: Circle CCTP + Squid Router - **Monitoring**: Sentry, Mixpanel --- # 10. SECURITY MODEL ## Non-Custodial Architecture Modexia uses Circle's Multi-Party Computation (MPC) infrastructure. The developer's Entity Secret is the master key — **Modexia never stores it**. It is only present on the developer's server during initialization. ## Key Security Properties 1. **No private key exposure** — MPC distributes key material across multiple parties 2. **On-chain policy enforcement** — Master Guard V3 enforces spending limits at the smart contract level 3. **API key scoping** — `mx_test_` keys work only on testnet, `mx_live_` keys only on mainnet 4. **Automatic retries** — SDK handles transient network failures with exponential backoff 5. **Recovery files** — developers maintain offline recovery files for wallet access ## API Key Best Practices - Never hardcode API keys in frontend code or public repositories - Use environment variables or secret managers (AWS Secrets Manager, Doppler) - Rotate keys immediately if compromised via the Dashboard - Use `mx_test_` keys for development, `mx_live_` for production ## Phishing Protection Modexia staff will NEVER ask for Private Keys, Entity Secrets, or API keys via DM, email, or chat. --- # 11. PRICING - **1% per transaction** — deducted automatically from the agent's wallet balance - **No monthly fees** — pay only for what you use - **No setup costs** — sign up and start building immediately - **No minimum volume** — works for 1 transaction or 1 million - **Free testnet** — unlimited testing on Base Sepolia at no cost --- # 12. ONBOARDING FLOW 1. **Sign up** at https://modexia.software (social auth or email via Supabase) 2. **Get API key** from the Dashboard (automatically generated on sign-up) 3. **Install SDK**: `pip install modexiaagentpay` 4. **Fund wallet**: Use the integrated fiat on-ramps (Coinbase, MoonPay) in the Dashboard 5. **Write agent code**: Initialize `ModexiaClient` and start transacting 6. **Monitor**: Track all transactions in the Dashboard in real-time --- # 13. COMMON INTEGRATION PATTERNS ## Pattern 1: AI Agent That Pays for APIs ```python from modexia import ModexiaClient client = ModexiaClient(api_key="mx_test_...") # Agent autonomously accesses paid APIs data = client.smart_fetch("https://api.weather-premium.com/forecast?city=NYC") print(data.json()) # Agent got the data, payment handled automatically ``` ## Pattern 2: AI Agent With Budget Controls ```python from modexia import ModexiaClient, ModexiaPaymentError client = ModexiaClient(api_key="mx_test_...") try: # This will fail if spending policy is exceeded receipt = client.transfer(recipient="0x...", amount=1000.0) except ModexiaPaymentError as e: if "DAILY_LIMIT_EXCEEDED" in str(e): print("Agent has reached its daily spending limit") elif "INSUFFICIENT_FUNDS" in str(e): print("Agent wallet needs more USDC") ``` ## Pattern 3: Cross-Chain Settlement ```python from modexia import ModexiaClient client = ModexiaClient(api_key="mx_live_...") # Agent earned revenue and sends it to Ethereum mainnet receipt = client.cross_chain_transfer( to_chain="1", to_token="0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", recipient="0xTreasuryAddress...", amount=500.0 ) # Arrives in 3-10 minutes, no ETH gas needed ``` ## Pattern 4: MCP with Claude ``` User: "Check my agent's balance and send $5 to 0x742d..." Claude (via MCP): → Calls check_balance tool → "Balance: 42.50 USDC" → Calls send_payment tool with recipient and amount → "Payment sent! TX ID: 0xabc123..." ``` --- # 14. GLOSSARY - **AgentPay** — Modexia's core payment infrastructure product - **Base** — Coinbase's L2 blockchain built on Ethereum (where Modexia wallets live) - **CCTP** — Circle's Cross-Chain Transfer Protocol for moving USDC between chains - **Entity Secret** — Master cryptographic key for Circle MPC wallets (never stored by Modexia) - **Master Guard** — On-chain smart contract that enforces spending policies - **MCP** — Model Context Protocol, a standard for connecting AI agents to external tools - **ModexiaRouterV3** — Smart contract that handles payment routing and fee distribution - **MPC** — Multi-Party Computation, cryptographic protocol for key management without exposing private keys - **smart_fetch** — SDK method that automatically handles HTTP 402 paywalls - **Spending Policy** — Configurable limits on agent spending (daily, hourly, per-request) - **USDC** — USD Coin, a stablecoin pegged 1:1 to the US dollar - **x402** — HTTP 402 Payment Required protocol for machine-payable web resources --- # 15. LINKS AND RESOURCES - Website: https://modexia.software - Documentation: https://modexia.software/docs - Getting Started: https://modexia.software/docs/getting-started - Python SDK (PyPI): https://pypi.org/project/modexiaagentpay - GitHub: https://github.com/Modexia/ModexiaAgentpay - MCP Server Product Page: https://modexia.software/product/mcp - Python SDK Product Page: https://modexia.software/product/python-sdk - Security: https://modexia.software/product/security - Pricing: https://modexia.software/pricing - X/Twitter: https://x.com/modexiaio - Support: support@modexia.software - Security Reports: security@modexia.software --- © 2026 Modexia Inc. All rights reserved.