{
  "markdown": "# AgentPay\n\n[![Tests](https://github.com/romudille-bit/agentpay/actions/workflows/test.yml/badge.svg)](https://github.com/romudille-bit/agentpay/actions/workflows/test.yml)\n[![PyPI](https://img.shields.io/pypi/v/agentpay-x402?color=blue)](https://pypi.org/project/agentpay-x402/)\n[![Python](https://img.shields.io/pypi/pyversions/agentpay-x402)](https://pypi.org/project/agentpay-x402/)\n[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)\n[![MCP](https://img.shields.io/npm/v/%40romudille%2Fagentpay-mcp?label=mcp&color=orange)](https://www.npmjs.com/package/@romudille/agentpay-mcp)\n[![Live gateway](https://img.shields.io/badge/gateway-agentpay.tools-black)](https://agentpay.tools)\n\n*Most agent-payment tools are a wallet — they move money. AgentPay is the layer that decides whether to spend it at all.*\n\n**AgentPay is the economic intelligence layer for MCP servers and AI agents.**\n\nAgents spend money. Most don't know how much, or why, until the session ends and the bill arrives.\n\nAgentPay gives agents economic intelligence — the ability to reason about cost while they work, not after.\n\nIt starts with a budget. Every session opens with a hard cap enforced at the payment layer — not in code a model can ignore, but at the point where money moves. The agent knows from the first call exactly what it has to spend.\n\nBefore calling a tool, it knows what that call costs. Mid-task, it can check what's left and route to a cheaper alternative if the math doesn't work. When the session ends, a receipt captures every call, every cost, every decision — not a debug log, but proof of economic accountability.\n\nThe developer sees all of it: spending patterns per agent, anomaly flags when something loops or spikes, policy controls that enforce exactly which tools an agent can use and how much it can spend on each.\n\nThe result is an agent that doesn't just have a budget. It knows how to use one.\n\n**Start free:** 20 tools (17 free), no USDC needed, no wallet setup required.  \n**Live gateway:** `https://agentpay.tools`\n\n---\n\n## Install\n\n```bash\npip install agentpay-x402            # core (Stellar)\npip install \"agentpay-x402[base]\"    # + pay tools that settle on Base\n```\n\n---\n\n## Quickstart — 3 lines, zero setup\n\n17 free tools. No USDC, no wallet, no API keys, no human. `quickstart()` registers\nan agent, mints a wallet, and returns a ready, budget-capped session.\n\n```python\nfrom agentpay import quickstart\n\ns = quickstart()                                   # registers + mints a wallet\nprint(s.call(\"token_price\", {\"symbol\": \"ETH\"})[\"result\"][\"price_usd\"])\nprint(s.spending_summary())                        # receipt: every call, cost, tx\n```\n\nSet a hard budget, or bring your own funded wallet to pay for tools:\n\n```python\ns = quickstart(max_spend=\"0.50\")                   # cap this run at $0.50\ns = quickstart(secret_key=\"S...\", base_key=\"0x...\")  # your wallet (Stellar + Base)\n```\n\nEvery call is session-tracked, and the cap is enforced **before** any payment is signed.\n\n---\n\n## 20 Tools (17 Free + 3 Paid)\n\nEvery call is session-tracked — you get a receipt showing every tool called, every cost, and every timestamp.\n\n| Tool | Parameters | Returns |\n|------|-----------|---------|\n| `url_reader` | `url` | Clean markdown content of any web page |\n| `web_search` | `query` | Top 5 results with full content |\n| `market_snapshot` | — | S&P 500, Treasury yield, BTC, ETH, gas in one call |\n| `token_price` | `symbol` (BTC, ETH, SOL…) | price_usd, change_24h_pct, market_cap_usd |\n| `gas_tracker` | — | slow/standard/fast gwei, base_fee_gwei |\n| `fear_greed_index` | `limit` (days of history, default 1) | value 0–100, value_classification, history[] |\n| `token_market_data` | `token_a`, `token_b` | volume_24h_usd, market_cap_usd, price_usd |\n| `wallet_balance` | `address`, `chain` (ethereum/stellar) | token balances |\n| `whale_activity` | `token`, `min_usd` (default 100k) | large_transfers[] with direction, total_volume_usd |\n| `defi_tvl` | `protocol` (optional, e.g. \"uniswap\") | tvl, change_1d, change_7d, chains[] |\n| `token_security` | `contract_address`, `chain` | risk_level, is_honeypot, buy_tax, sell_tax |\n| `open_interest` | `symbol` (BTC, ETH…) | total_oi_usd, oi_change_1h/24h_pct, long_short_ratio |\n| `orderbook_depth` | `symbol` (e.g. ETHUSDT) | best_bid/ask, spread_pct, slippage at $10k/$50k/$250k |\n| `funding_rates` | `asset` (optional) | funding_rate_pct, annualized_rate_pct, sentiment per exchange |\n| `crypto_news` | `currencies` (e.g. \"ETH,BTC\"), `filter` | headlines[] with title, url, sentiment, score |\n| `yield_scanner` | `token`, `chain` (optional), `min_tvl` | top 10 pools by APY with protocol, tvl_usd, risk_level |\n| `dune_query` | `query_id`, `limit`, `fast_only` | rows[], columns[], row_count from Dune Analytics |\n| `session_create` | `agent_address`, `max_spend`, `label` | session_id, budget config, gateway_url, receipt — **$0.01** |\n| `pre_trade_check` | `symbol`, `size_usd`, `side`, `token_address?` | one-call trade verdict (ok/caution/avoid): slippage at YOUR size, side-aware funding carry, OI crowding, optional security — **$0.01** |\n| `verified_route` | `need`, `budget_usd?`, `chain?` | buyer-side trust oracle: sweeps the x402 marketplace, collapses sybil/factory clusters, ranks real providers by usage × delivery scores → one vetted recommendation + ready_to_pay challenge — **$0.01** |\n\n---\n\n## Session Intelligence\n\nThis is the economic intelligence layer in practice. The Session gives your agent — and you — real visibility into what happened, what it cost, and why.\n\n```python\nfrom agentpay import quickstart, BudgetExceeded\n\n# quickstart() registers + mints a wallet; the returned session is also a\n# context manager, so you can `with` it for a printed receipt on exit.\n# Budget caps are exact: max_spend=0.10 (float) == \"0.10\" (str).\nwith quickstart(max_spend=0.10) as session:\n\n    # Price an entire multi-tool plan BEFORE spending anything (free, no wallet)\n    plan = session.estimate_plan([\"token_price\", \"pre_trade_check\", \"session_create\"])\n    plan[\"total_usdc\"], plan[\"fits_budget\"]   # per-step costs + cheaper alternatives inside\n\n    # Reason about cost before committing (use the *_usd Decimals for comparisons)\n    if session.would_exceed(session.tool_cost_usd(\"dune_query\")):\n        alt = session.suggest_cheaper(\"dune_query\")   # {\"name\": ..., \"price\": ...}\n\n    # Call a tool — budget enforced before any payment is signed\n    r = session.call(\"token_price\", {\"symbol\": \"ETH\"})\n    r.data[\"price_usd\"]    # inner tool output  (r[\"result\"][\"price_usd\"] still works)\n    r.cost                 # payment amount, e.g. \"0\"\n    r.network              # settlement chain, e.g. \"stellar-mainnet\" / \"base\"\n\n    session.remaining_usd()   # Decimal('0.10')\n\n    # For an external x402 tool that offers several chains, pick one:\n    # session.call(\"https://some-x402-tool/endpoint\", {}, chain=\"base\")\n\n    # Full receipt — every call, cost, tx hash, and settlement chain\n    print(session.spending_summary())\n    # {\n    #   \"calls\": 1, \"spent\": \"$0\", \"remaining\": \"$0.1\", \"budget\": \"$0.1\",\n    #   \"breakdown\": [\n    #     {\"tool\": \"token_price\", \"cost\": \"Free\", \"tx_hash\": \"\", \"network\": \"stellar-mainnet\"}\n    #   ]\n    # }\n```\n\n### Policy parameters\n\nControl exactly what your agent is allowed to do:\n\n```python\nfrom agentpay import AgentWallet, Session\n\nwallet = AgentWallet(secret_key=\"S...\", network=\"mainnet\")   # or quickstart()'s minted wallet\nwith Session(wallet,\n             gateway_url=\"https://agentpay.tools\",\n             max_spend=0.10,\n             allowed_tools=[\"token_price\", \"gas_tracker\", \"web_search\"],\n             max_per_tool={\"dune_query\": 0.02},\n             rate_limit=10,                # max 10 calls/min\n             prefer_chain=\"base\") as session:   # Base is the default; pass \"stellar\" to override\n    ...\n```\n\n`BudgetExceeded` fires before any payment goes out if a tool would push you over the cap, isn't on the allowlist, or exceeds its per-tool limit.\n\n---\n\n## Example: Market intelligence agent\n\nFive free tools, one session, full receipt.\n\n```python\nfrom agentpay import quickstart\n\nwith quickstart() as session:\n\n    snapshot = session.call(\"market_snapshot\", {})\n    rates    = session.call(\"funding_rates\",    {\"asset\": \"ETH\"})\n    oi       = session.call(\"open_interest\",    {\"symbol\": \"ETH\"})\n    fg       = session.call(\"fear_greed_index\", {})\n    whales   = session.call(\"whale_activity\",   {\"token\": \"ETH\", \"min_usd\": 500_000})\n\n    m = snapshot[\"result\"]\n    print(f\"S&P:       {m['sp500_price']:,.0f}  ({m['sp500_change_pct']:+.2f}%)\")\n    print(f\"ETH:       ${m['eth_price_usd']:,.0f}\")\n    print(f\"Gas:       {m['gas_standard_gwei']} gwei\")\n\n    avg_rate = sum(e[\"funding_rate_pct\"] for e in rates[\"result\"][\"rates\"]) / len(rates[\"result\"][\"rates\"])\n    print(f\"Funding:   {avg_rate:+.4f}%/8h\")\n    print(f\"OI 24h:    {oi['result']['oi_change_24h_pct']:+.2f}%\")\n    print(f\"Sentiment: {fg['result']['value_classification']}\")\n    print(f\"Whale vol: ${whales['result']['total_volume_usd']:,.0f}\")\n\n    print(session.spending_summary())\n```\n\n---\n\n## Use it in your agent\n\n### Agent Skills (one command, any agent)\n\n```bash\nnpx skills add romudille-bit/agentpay\n```\n\nInstalls the **`agentpay-route`** skill (find, judge, and pay for the best paid x402 tool\nwithin a budget) and **`agentpay-session`** (hard spend cap + verifiable receipts) into\nClaude Code, Codex, Droid, OpenCode, or any [skills-CLI](https://github.com/vercel-labs/skills)-compatible\nruntime. Pair with the MCP below for keyless routing out of the box; add\n`AGENTPAY_BASE_KEY` + `AGENTPAY_MAX_SPEND` for capped, in-place paid calls.\n\n### Claude Code plugin (one command)\n\n```\n/plugin marketplace add romudille-bit/agentpay\n/plugin install agentpay@agentpay\n```\n\nInstalls the **`agentpay-route`** skill — your agent finds, judges, and pays for the best paid\nx402 tool within a budget — plus the 17 free tools. No keys needed to route.\n\n### MCP server (any runtime)\n\nSelf-contained — pure Node, no Python, no repo, no keys to start:\n\n```bash\nnpx -y @romudille/agentpay-mcp\n```\n\n```json\n{\n  \"mcpServers\": {\n    \"agentpay\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@romudille/agentpay-mcp\"]\n    }\n  }\n}\n```\n\nExposes the 17 free tools **plus** `verified_route` (buyer-side trust oracle —\nfree preview keyless, full paid payload in wallet mode), `route` (legacy alias)\nand `estimate_plan` (price a multi-tool plan before spending). Listed on\n[Glama](https://glama.ai/mcp/servers/romudille-bit/agentpay).\n\n**Wallet mode (v2.4.0):** add an EVM key and paid tools settle **in-place** —\ngasless EIP-3009 on Base (no ETH needed; nothing broadcast client-side, a\nrejected call moves no USDC) under a hard session cap:\n\n```json\n{\n  \"mcpServers\": {\n    \"agentpay\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@romudille/agentpay-mcp\"],\n      \"env\": {\n        \"AGENTPAY_BASE_KEY\": \"0x<EVM private key>\",\n        \"AGENTPAY_MAX_SPEND\": \"0.10\"\n      }\n    }\n  }\n}\n```\n\nFund the key's address with USDC on Base mainnet; every paid call counts\nagainst `AGENTPAY_MAX_SPEND` and is refused past the cap — the budget story,\nenforced inside the MCP itself. Use a dedicated small-balance key.\n\n### Buyer-side routing — find & pay for the best tool, within a budget\n\nWhen an agent needs a paid tool, AgentPay discovers the options across the x402 marketplace,\ndrops the fake/empty stubs, ranks by **real usage** (not price), and recommends the cheapest one\nthat actually works — within a budget. The agent pays the provider **directly** (peer-to-peer,\nno custody) and keeps a verifiable receipt.\n\n```bash\nagentpay-route \"funding rates\" --budget 0.01   # ranked candidates + a recommendation\n```\n\n---\n\n## Paid tools: session_create, pre_trade_check, verified_route ($0.01 each)\n\nThree tools cost money today. `session_create` opens a budget-capped session with a\nhard `max_spend` limit — for autonomous agents that need spend enforcement across\nmultiple calls. `pre_trade_check` is the first **outcome bundle**: one call returns\nan ok/caution/avoid trade verdict from live orderbook slippage at your size,\nside-aware funding carry, open-interest crowding, and an optional contract security\nscan — with the per-factor breakdown and raw components embedded. `verified_route`\nis the **buyer-side trust oracle**: \"I need X, budget $Y — which x402 tool is\nreal?\" It sweeps the whole marketplace, collapses sybil/factory clusters, keeps\nonly providers relevant to *your need*, ranks them by real unique-payer usage ×\nthe [Prober's](https://agentpay.tools/probes) paid delivery scores, and returns\none vetted recommendation with a ready-to-pay challenge. All 17 data tools\nremain free.\n\nPrice any plan before spending a cent (free, no wallet): `POST /v1/plan/estimate`,\nor `session.estimate_plan([...])` from the SDK.\n\nWhen metered inference ships, it works through the same Session interface — your agent checks cost, decides if it's worth it, and pays in USDC on Base or Stellar (via the SDK).\n\n```python\n# Future — inference as a Session tool\nremaining = session.remaining()\ninfer_cost = session.tool_cost(\"inference\")   # e.g. \"$0.02\"\n\nif remaining >= infer_cost:\n    result = session.call(\"inference\", {\"prompt\": \"...\", \"model\": \"claude-haiku\"})\nelse:\n    result = session.call(\"url_reader\", {\"url\": summary_url})  # cheaper path\n```\n\nTo fund a wallet for `session_create`: send USDC to a Stellar wallet (`S...` key, issuer `GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN`) or a Base wallet (`0x...`, contract `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`).\n\n### Eating our own dog food\n\nAgentPay's **flagship analyst agent** (`agents/analyst/`) runs daily on these exact\nrails as a real customer: it prices its plan with `estimate_plan`, gathers free\nintel, buys `pre_trade_check` verdicts on the majors under a hard $0.25 cap, and\npublishes a market note with an on-chain-verifiable receipt. The first best\ncustomer is the house.\n\n---\n\n## Architecture\n\nAgentPay is an x402 payment gateway and economic intelligence layer — agents call tools within a hard budget cap, pay USDC on-chain when tools cost money, and accumulate a full session receipt as they work. Free tools skip the payment step entirely; the session tracking and cost awareness are always on.\n\n### Chain support & x402 interop\n\n**Base** settles via the standard x402 `exact` scheme (gasless EIP-3009 through the\nCDP facilitator) — **any standard x402 client can pay AgentPay on Base**, no AgentPay\nSDK required.\n\n**Stellar** settles as a **classic payment + text memo** verified directly on Horizon.\nIt is supported by the AgentPay SDK (`pip install agentpay-x402`) and by manual\npayment per the 402 instructions — but it is **not** the standard `@x402/stellar`\nscheme (which uses Soroban null-account templates, signed auth entries, and\nfacilitator settlement). A standard `@x402/stellar` client cannot pay AgentPay's\nStellar rail today; migrating to the standard Soroban scheme is on the v2 roadmap.\nStandard clients should pay on Base — Circle CCTP bridges USDC 1:1 between the two.\n\n```\nagent (Python SDK)\n    │\n    │  POST /tools/{name}/call\n    │  ← 200 {result: ...}              ← free tools return directly\n    │  ← 402 {payment_id, amount, ...}  ← paid tools (session_create, pre_trade_check, verified_route)\n    │  → USDC on Base (~2s, standard x402) or Stellar (~3–5s, SDK classic+memo)\n    │  → retry with X-Payment header\n    │  ← 200 {result: ...}\n    ▼\ngateway (FastAPI on Railway)\n    │\n    ├── registry/registry.py   — 20-tool catalog (17 free; session_create, pre_trade_check, verified_route — $0.01 each)\n    ├── gateway/routes/plan.py — POST /v1/plan/estimate (free pre-flight plan pricing)\n    ├── gateway/radar.py       — Arbitrum x402 Radar discovery + settlement verify (see RADAR.md)\n    ├── gateway/stellar.py     — Stellar payment verification via Horizon\n    ├── gateway/base.py        — Base payment verification via JSON-RPC\n    └── gateway/services/tools_runtime.py — real API dispatchers\n            ├── Jina Reader       url_reader\n            ├── Jina Search       web_search\n            ├── Yahoo+CoinGecko   market_snapshot\n            ├── CoinGecko         token_price, token_market_data\n            ├── Etherscan V2      gas_tracker, whale_activity, wallet_balance\n            ├── DeFiLlama         defi_tvl, yield_scanner\n            ├── alternative.me    fear_greed_index\n            ├── Reddit            crypto_news\n            ├── Dune Analytics    dune_query\n            ├── GoPlus            token_security\n            └── Binance+Bybit+OKX funding_rates, open_interest, orderbook_depth\n```\n\n---\n\n## Stacks sBTC settlement (M1)\n\nAgentPay settles x402 micropayments in **sBTC on Stacks** — budget-capped, signed\nsign-don't-broadcast, broadcast by the gateway. Milestone 1 of the Stacks Endowment\ngrant is demonstrated live on testnet:\n\n- **Developer guide:** [`docs/stacks-m1.md`](docs/stacks-m1.md) — setup, known limitations, dependencies.\n- **Runnable demo:** [`examples/stacks_m1_demo.py`](examples/stacks_m1_demo.py) — capped session → sBTC payment → receipt → over-cap rejection.\n- **Demo video:** [YouTube (~40s)](https://www.youtube.com/watch?v=rGb07rwyG1I)\n- **On-chain proof:** [`0xa5351bad…`](https://explorer.hiro.so/txid/0xa5351bad31ed6bbcb57c0f9fcbcd997cc203b7011d62666176452edaed2d8c87?chain=testnet) — `sbtc-token::transfer`, payer → gateway, status `success` (PoX-5 testnet, block 82215).\n\n---\n\n## Discovery\n\n| Directory | Status |\n|-----------|--------|\n| [PyPI](https://pypi.org/project/agentpay-x402/) | ✅ agentpay-x402 |\n| [x402scout](https://x402scout.com) | ✅ indexed, health-checked every 15min |\n| [Glama MCP](https://glama.ai/mcp/servers/romudille-bit/agentpay) | ✅ listed |\n| [awesome-x402](https://github.com/xpaysh/awesome-x402) | ✅ listed |\n| [npm](https://www.npmjs.com/package/@romudille/agentpay-mcp) | ✅ @romudille/agentpay-mcp |\n| [skills CLI](https://github.com/vercel-labs/skills) | ✅ `npx skills add romudille-bit/agentpay` |\n| [402index.io](https://402index.io) | ✅ domain verified, 17 tools synced |\n| Coinbase Bazaar | ✅ indexed via REST — `session_create`, `pre_trade_check`, `verified_route` (Base). ⚠️ NOT in the curated set: invisible on the MCP `search_resources` default (AGE-125) |\n| Claude Code plugin | ✅ `/plugin marketplace add romudille-bit/agentpay` |\n| [MCP Registry](https://registry.modelcontextprotocol.io) | ✅ `io.github.romudille-bit/agentpay` v2.4.3 (official) |\n| [402audit](https://402audit.com) | ✅ audited — score 100, verdict \"proprietary\" |\n| [signal402](https://signal402.com) | ✅ auto-indexed from Bazaar (6h refresh) |\n| [x402.fuchss.app](https://x402.fuchss.app/provider/agentpay.tools) | ✅ listed — grade recovering post-AGE-123 |\n| ~~xpay.tools~~ | dropped — redundant with Bazaar (SPA mirror) |\n\n**Agent-readable endpoints:**\n\n| Endpoint | Purpose |\n|----------|---------|\n| `/.well-known/agentpay.json` | AgentPay manifest |\n| `/.well-known/agent.json` | A2A agent card |\n| `/llms.txt` | LLM-readable service description |\n| `/.well-known/l402-services` | 402index.io discovery format |\n",
  "bytes": 19101,
  "sha": "a7cb9f1dfe5f1078e23021d5996735c27bc0f7f266d22a6d4f4669b0c98136e3",
  "repo_slug": "romudille-bit/agentpay",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_romudille_bit_agentpay_e07335eb/readme"
}