Introduction
Welcome to the PayAgents developer documentation. PayAgents is an all-in-one payment routing API and SDK built to power the machine-to-machine agentic economy.
As software agents evolve to complete complex workflows — querying external data, training LLMs, or executing web actions — they frequently hit paywalls. Traditional subscription models and credit cards fail for automated agent systems because they require interactive manual checks, incur high fraud risks, and charge expensive fees for tiny, high-frequency actions.
Why Machine-Native Payments?
Autonomous AI agents require low-latency, friction-free transactions. PayAgents handles this by routing value instantly using micropayment rails, enabling agents to pay for only what they consume, down to a fraction of a cent.
Key Protocols Supported
- L402 (Bitcoin Lightning network): A protocol that marries Lightning payment invoices with HTTP headers. Ideal for extremely high-frequency micropayments settled in SATs.
- x402 (Base Stablecoins): Standardized stablecoin payments on Coinbase's Layer-2 Base network. Perfect for stable, dollar-denominated agentic utilities with low network gas.
Unified Wallet Framework
Developers using PayAgents do not need to run their own node clusters, manage private keys, lock liquidity in payment channels, or worry about swapping base assets to pay transaction gas. In the background, our core engine auto-swaps and routes funds, exposing a unified USD balance. You deposit and withdraw standard currency, and we route the payments across whatever rails the counterparty demands.
Getting Started
Integrate transactional controls into your workspace in less than five minutes. Our SDK wraps all transaction formatting, signature generation, and verification.
1. Install the SDK
Add the PayAgents package to your project repository:
npm install payagents
2. Obtain an API Key
Log into the PayAgents Dashboard and generate a key inside API Settings. Store it in your environment variables:
PAYAGENTS_API_KEY=pa_live_58c97be34015f...
3. Initialize the Client
Import and instantiate the PayAgents client in your project:
import { PayAgents } from 'payagents';
const client = new PayAgents({
apiKey: process.env.PAYAGENTS_API_KEY
});
Receiving Payments
Monetize your custom APIs and agentic services by gating endpoints behind a paywall. The SDK offers middleware utilities that automatically issue payment challenges and intercept verification hashes.
Cross-Rail Gating
When gating an API, you only configure the target USD fee. PayAgents automatically formats the response headers so that agents requesting via L402 receive Lightning invoices, while agents requesting via x402 receive EVM stablecoin challenges.
Non-Custodial Direct Settlement (Zero Platform Custody)
By default, incoming payments accumulate in your PayAgents USD balance ledger. If you prefer zero platform custody, configure PayAgents to route all payments directly into your personal crypto wallet or Lightning address.
you@getalby.com). When configured, all HTTP 402 challenges instruct paying agents to transfer funds directly to your addresses peer-to-peer.
Gating HTTP API Endpoints
Wrap your Express server route with one line of middleware:
import express from 'express';
import { PayAgents } from 'payagents';
const app = express();
const pa = PayAgents.server({
apiKey: process.env.PAYAGENTS_API_KEY
});
// Gate this endpoint: charge $0.005 per call
app.post('/api/v1/extract',
pa.middleware({ price: '0.005 USD' }),
async (req, res) => {
// Execution enters here ONLY after payment is settled.
const data = await performExtraction(req.body.url);
res.json({ success: true, data });
}
);
app.listen(3000);
How the Gating Protocol Works
- Initial Unpaid Request: An AI agent calls
/api/v1/extractwithout authorization. - Challenge Issued: PayAgents middleware intercepts and responds with
HTTP 402 Payment Required, attaching metadata instructions (Lightning invoice or EVM signature parameters). - Settlement: The caller agent automatically pays the invoice or stablecoin payload via their client.
- Fulfillment Request: The caller retries the API request with the settlement token in the
Authorizationheader. - Verification: Middleware validates the preimage through the network, settles the balance, and passes execution to your route handler.
Enabling Spending
Give your AI agents the capability to pay for external resources autonomously using the pay() API wrapper. The PayAgents engine handles payment rails and checks balance limits locally.
Executing a Payment
Pass destination URL and policy bounds directly to the client:
import { PayAgents } from 'payagents';
const client = new PayAgents({ apiKey: process.env.PAYAGENTS_API_KEY });
try {
// Call client.pay to query a payment-gated endpoint
const response = await client.pay('https://api.scraper.io/gated-route', {
maxAmount: '0.01 USD', // Max authorization threshold
payload: {
target: 'https://news.ycombinator.com'
}
});
console.log('Response content:', response.data);
} catch (err) {
console.error('Payment routing failed or budget exceeded:', err);
}
Spend Protection against Hallucinations
AI agents can occasionally hallucinate or enter recursive calling loops that drain corporate wallets in seconds. It is highly recommended to set strict transaction caps and monthly limits in your PayAgents dashboard to prevent budget overrun.
Dashboard Spend Policies
- Single-Payment Cap: Intercept and abort any transaction exceeding a specific threshold (e.g. max $0.05 per action).
- Daily/Monthly Quotas: Restrict cumulative daily or monthly spend bounds.
- Domain Allowlists: Ensure keys are only allowed to spend balances on verified API URLs.
- Human Approval Gateways: Require manual authentication for transactions above a specified cost.
Model Context Protocol (MCP)
The Model Context Protocol (MCP) is the open standard that connects LLMs (such as Claude Desktop, Cursor, Windsurf, and custom OpenAI/Gemini agents) to external tools and data sources. PayAgents provides a dedicated, official package payagents-mcp that delivers full spending and receiving capabilities.
1. Claude Desktop & Cursor Client Setup (Sending)
Add PayAgents to your claude_desktop_config.json or .cursor/mcp.json in seconds:
{
"mcpServers": {
"payagents": {
"command": "npx",
"args": ["-y", "payagents-mcp"],
"env": {
"PAYAGENTS_API_KEY": "pa_live_your_api_key_here"
}
}
}
}
Your LLM automatically discovers 3 built-in tools:
payagents_pay_url: Probes HTTP 402 paywalls, selects the cheapest rail (Lightning or Base USDC), pays the fee, and returns unlocked data.payagents_get_balance: Checks the remaining USD budget and active enterprise spending policy caps.payagents_get_transaction: Fetches transaction details and cryptographic settlement proofs.
2. Monetizing Custom MCP Tools (Receiving)
Wrap your tool handlers with mcpCharge to collect micro-fees directly into your wallet:
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { mcpCharge } from 'payagents-mcp';
import { z } from 'zod';
const server = new McpServer({ name: 'alpha-server', version: '1.0.0' });
// Charge $0.005 USD per tool call
server.tool('get_alpha_signals',
'Get proprietary real-time signals',
{ symbol: z.string(), payment_proof: z.string().optional() },
mcpCharge({ price: '0.005 USD' }, async ({ symbol }) => {
const signals = await fetchAlpha(symbol);
return {
content: [{ type: 'text', text: JSON.stringify(signals) }]
};
})
);