# Quickstart

> In about five minutes, run a paid MCP tool on a local Algorand network and pay for it from Python and from JavaScript.

In five minutes you will have an MCP server whose `echo` tool costs 5,000 microALGO per call, a Python client that pays for it, and a JavaScript client that pays an HTTP endpoint. Everything runs on LocalNet, a private Algorand network on your machine, so no real money is involved.

## Prerequisites

- Python 3.10 or newer
- Node.js 20 or newer (for the JavaScript step)
- [AlgoKit](https://github.com/algorandfoundation/algokit-cli) and Docker, to run LocalNet

### Start LocalNet

```bash
algokit localnet start
```

algod listens on `http://localhost:4001` and the indexer on `http://localhost:8980`. The examples fund new accounts from LocalNet's built-in dispenser, so you need no keys.

### Get the examples

```bash
git clone https://github.com/x402-avm/examples.git
cd examples
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
npm install
```

This installs `ai-economy-sdk` 0.5.1, `x402-algorand` 0.3.0 and `x402-avm-js` 0.4.1 with their dependencies.

### Run the paid MCP server

```python
"""FastMCP server payment-gated with ai-economy-sdk on Algorand LocalNet.

Runs a FastMCP server with a single paid 'echo' tool priced at 5,000 microALGO.
Funds a server account from LocalNet dispenser and serves Streamable HTTP (/mcp) on port 9201.

How to run:
    python localnet/quickstart_server.py

What it prints:
    pay_to: <44-character Algorand address>
"""
import sys
from pathlib import Path

# Add current directory to path so _localnet can be imported
sys.path.insert(0, str(Path(__file__).resolve().parent))

import uvicorn
from fastmcp import FastMCP
from ai_economy_sdk import DefaultAvmSigner, PaymentGate
from _localnet import ALGOD, new_funded_account

SERVER_PORT = 9201
TOOL_PRICE_MICROALGO = 5000


def main() -> None:
    server_sk, server_addr = new_funded_account(algos=10)
    print(f"pay_to: {server_addr}", flush=True)

    mcp = FastMCP("QuickstartServer")

    @mcp.tool()
    def echo(text: str) -> str:
        """Echo back input text."""
        return f"echo: {text}"

    gate = PaymentGate(
        signer=DefaultAvmSigner(server_sk, algod_client=ALGOD),
        network="localnet",
        pay_to=server_addr,
        asset_id=0,
        prices={"echo": TOOL_PRICE_MICROALGO},
    )

    app = gate.wrap(mcp, transport="streamable-http")
    uvicorn.run(app, host="127.0.0.1", port=SERVER_PORT, log_level="warning")


if __name__ == "__main__":
    main()
```

Source: [examples/localnet/quickstart_server.py](https://github.com/x402-avm/examples/blob/main/localnet/quickstart_server.py)

```bash
python localnet/quickstart_server.py
```

```text
pay_to: GL4IOGTXMILQYI2UOSYORNW4LHB4SULTDRYCA4AMFQUGKTEYN3ZUDQG6XE
```

That address receives the payments; it is new on every run. The server answers MCP calls at `http://127.0.0.1:9201/mcp`.

### Pay for a call from Python

In a second terminal:

```python
"""Paid MCP client session using ai-economy-sdk on Algorand LocalNet.

Funds a fresh buyer account via the LocalNet dispenser, establishes a paid MCP
session to http://127.0.0.1:9201/mcp, calls the 'echo' tool, and verifies the on-chain
charge.

How to run:
    1. Start quickstart_server.py in the background
    2. python localnet/quickstart_client.py

What it prints:
    Result: echo: hello world
    Balance drop: 5000 microALGO
"""
import asyncio
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

from ai_economy_sdk import AIEconomyError, paid_mcp_session
from _localnet import ALGOD, new_funded_account

SERVER_URL = "http://127.0.0.1:9201/mcp"


async def main() -> None:
    buyer_sk, buyer_addr = new_funded_account(algos=5)
    before_balance = ALGOD.account_info(buyer_addr)["amount"]

    try:
        async with paid_mcp_session(SERVER_URL, buyer_sk, "localnet") as session:
            result = await session.call_tool("echo", {"text": "hello world"})
            print(f"Result: {result.content[0].text}")
    except AIEconomyError as err:  # spend controls refused the price (SpendLimitExceededError, 0.5.1+), settlement failed, bad config ...
        raise SystemExit(f"Paid call failed: {err}")

    after_balance = ALGOD.account_info(buyer_addr)["amount"]
    drop = before_balance - after_balance
    print(f"Balance drop: {drop} microALGO")


if __name__ == "__main__":
    asyncio.run(main())
```

Source: [examples/localnet/quickstart_client.py](https://github.com/x402-avm/examples/blob/main/localnet/quickstart_client.py)

```bash
python localnet/quickstart_client.py
```

```text
Result: echo: hello world
Balance drop: 5000 microALGO
```

The buyer paid exactly the price. The server paid the 2,000 microALGO network fee.

### Pay from JavaScript

`x402-avm-js` pays any x402 endpoint on Algorand. Start a small FastAPI paywall (`GET /paid` on port 9221, 5,000 microALGO), then run the client:

```bash
python localnet/server_for_js.py
```

```bash
node localnet/js_pay.mjs
```

```javascript
/**
 * Pay an x402 paywall from JavaScript on LocalNet (start server_for_js.py first, port 9221).
 *
 *   node localnet/js_pay.mjs
 *
 * Fetch -> 402 -> decodePaymentRequired -> payForRequirement (with explicit spend controls)
 * -> retry with PAYMENT-SIGNATURE -> check the exact 5000 microALGO balance drop.
 */
import { SpendLimitExceededError, X402AvmError, decodePaymentRequired, payForRequirement } from 'x402-avm-js';
import { algod, newFundedAccount, signerFor } from './_localnet.mjs';

const URL = 'http://127.0.0.1:9221/paid';
const balance = async (addr) => (await algod.accountInformation(addr).do()).amount;

const buyer = await newFundedAccount();
const before = await balance(buyer.address);

const res402 = await fetch(URL);
if (res402.status !== 402) throw new Error(`Expected 402, got ${res402.status}`);
const challenge = decodePaymentRequired(res402.headers.get('payment-required'));
const [req] = challenge.accepts;
console.log(`Server asks ${req.amount} units of asset ${req.asset} -> ${req.payTo}`);

// Spend controls are checked before anything is signed. The default cap is 1,000,000 base units;
// here we tighten it and pin the asset, network and recipient.
const controls = {
  maxAmount: 10_000n,
  allowedAssets: ['0'],
  allowedNetworks: [req.network],
  allowedPayTo: [req.payTo],
};

try {
  const signature = await payForRequirement(challenge, buyer.address, algod, signerFor(buyer.sk), controls);
  const paid = await fetch(URL, { headers: { 'payment-signature': signature } });
  console.log(`Paid response: ${paid.status}`, await paid.json());
} catch (err) {
  if (err instanceof SpendLimitExceededError) throw new Error(`Refused to overpay: ${err.message}`);
  if (err instanceof X402AvmError) throw new Error(`x402 error ${err.code}: ${err.message}`);
  throw err;
}

const drop = before - (await balance(buyer.address));
console.log(`Balance drop: ${drop} microALGO`);
if (drop !== 5000n) throw new Error(`Expected a drop of 5000 microALGO, got ${drop}`);

// A 50,000 microALGO demand would exceed the 10,000 cap and is refused without signing.
const greedy = { ...challenge, accepts: [{ ...req, amount: '50000' }] };
await payForRequirement(greedy, buyer.address, algod, signerFor(buyer.sk), controls).then(
  () => { throw new Error('Spend cap did not trigger'); },
  (err) => console.log(`Over-cap request rejected: ${err.constructor.name}`),
);
```

Source: [examples/localnet/js_pay.mjs](https://github.com/x402-avm/examples/blob/main/localnet/js_pay.mjs)

```text
Server asks 5000 units of asset 0 -> UR633JM3BS4KZMBELB7COIFAN65JOL5JLSDMHKT34FX4NXHJATFOFTQRWA
Paid response: 200 {
  status: 'ok',
  data: 'Access granted to premium resource',
  txid: 'B3UQGJQZVSHVNNTS6TZ7H4ONG6DRJVTBBRI2V6CDTM45MLFBYLZA',
  payer: 'PVGZFLS3MLQRRH2QJMRQUMH75ZOQQYNSPKFKXFN2URPIJ4MSTFBAZI6WB4'
}
Balance drop: 5000 microALGO
Over-cap request rejected: SpendLimitExceededError
```

The last line is a spend limit at work: the script caps payments at 10,000 microALGO, so a 50,000 microALGO demand is refused before the wallet signs anything.

To run every LocalNet example in order, with the servers they need started and stopped for you:

```bash
bash scripts/run_all_localnet.sh
```

## What just happened

Your client called `echo`, the server answered `402 Payment Required` with a price, the client signed a payment for exactly that price and retried, and the server ran the tool and then settled the payment on chain. [How it works](https://x402-avm.github.io/how-it-works) walks through each step.

## Next

- [Sell your own MCP tools](https://x402-avm.github.io/build/sell-mcp-tools.md)
Price tools by input, serve them, and test with a paying client.
- [Paywall an HTTP API](https://x402-avm.github.io/build/paywall-http-api.md)
Charge per request on FastAPI or Flask.
- [Let your agent pay](https://x402-avm.github.io/build/ai-agents.md)
A budget wallet, spend limits and price checks.
- [Move to TestNet](https://x402-avm.github.io/production/networks.md#testnet)
Real transactions with free TestNet ALGO.

Source: https://x402-avm.github.io/quickstart
