Metadata-Version: 2.4
Name: ai-economy-sdk
Version: 0.3.1
Summary: Payment-gated MCP server SDK for Algorand
Author-email: AI Economy Team <team@aieconomy.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/aieconomy/ai-economy-sdk
Project-URL: Bug Tracker, https://github.com/aieconomy/ai-economy-sdk/issues
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: x402-algorand>=0.1.4
Requires-Dist: fastmcp<4,>=3.4
Requires-Dist: mcp<2,>=1.29
Requires-Dist: py-algorand-sdk>=2.6
Requires-Dist: httpx>=0.27
Requires-Dist: starlette
Requires-Dist: uvicorn>=0.30
Dynamic: license-file

# AI Economy SDK (v0.3)

`ai-economy-sdk` turns Model Context Protocol (MCP) servers into **payment-gated, on-chain services** powered by Algorand and the `x402` standard. It supports dynamic per-call pricing, cryptographic client identity verification, subscription passes (ASA), automated bulk usage discounts, charge-only-on-success settlement, and persistent cross-proxy replay protection.

```sh
pip install ai-economy-sdk
```

## Networks

Wherever the SDK takes a `network`, you can pass any of these:

| You pass | Means | Default endpoints |
|---|---|---|
| `"mainnet"` | Algorand MainNet | AlgoNode `mainnet-api` / `mainnet-idx` |
| `"testnet"` | Algorand TestNet | AlgoNode `testnet-api` / `testnet-idx` |
| `"localnet"` | AlgoKit LocalNet; the genesis hash is read from its algod | `localhost:4001` / `localhost:8980` |
| `"algorand:<genesis hash>"` | Any network, including a private one, by its CAIP-2 id | LocalNet ports, or the URLs you pass |

`resolve_network(name)` gives the CAIP-2 id, `endpoints_for(name)` gives the default URLs, and
`usdc_asset_id(name)` gives Circle USDC's asset id (31566704 on MainNet, 10458941 on TestNet).
To use your own nodes, set `ALGOD_MAINNET_URL`, `ALGOD_TESTNET_URL`, `INDEXER_MAINNET_URL`,
`INDEXER_TESTNET_URL`, or pass URLs explicitly.

Prices are in the asset's base units. The ALGO fee floor (see below) only applies to ALGO prices,
so a USDC price of `1000` (0.001 USDC) is accepted.

---

## Architecture & Core API (v0.3)

### 1. `PaymentGate` (Core Server Middleware)
Directly wrap any `FastMCP` instance with payment enforcement, fee floor protection, and replay prevention:

```python
from fastmcp import FastMCP
from algosdk import mnemonic
from algosdk.v2client import algod
from ai_economy_sdk import PaymentGate, DefaultAvmSigner, ChainReader

# Load wallet & clients
server_pk = mnemonic.to_private_key("...")
server_addr = "..."
algod_client = algod.AlgodClient("", "https://mainnet-api.algonode.cloud")  # or LocalNet: ("a" * 64, "http://localhost:4001")
signer = DefaultAvmSigner(server_pk, algod_client=algod_client)
chain = ChainReader.for_network("mainnet")

mcp = FastMCP("weather_service")

@mcp.tool()
async def get_weather(location: str) -> str:
    return f"Weather in {location}: sunny"

def pricing(tool: str, args: dict, sender: str | None) -> int:
    return 15000 if args.get("location") == "PremiumCity" else 5000

gate = PaymentGate(
    signer=signer,
    network="mainnet",      # "testnet", "localnet" or "algorand:<genesis hash>"
    pay_to=server_addr,
    asset_id=31566704,      # USDC on MainNet; 0 for ALGO
    prices=pricing,
    default_price=3000,
    chain=chain,
    subscription_asset_id=1010,
    min_fee_per_txn=1000,   # Network fee per transaction (default 1000)
    allow_loss=False,       # Enforce facilitator fee floor (default False)
    replay_db="/path/to/replay.sqlite", # SQLite WAL database for multi-process replay sharing
)

app = gate.wrap(mcp)  # Returns ASGI app ready for uvicorn
```

#### Charge Only on Success
`PaymentGate` verifies the caller's payment signature and parameters prior to execution, but delays on-chain settlement submission until after the tool completes successfully (`ai_economy_sdk/gate.py:80-110`):
- **Tool Failure or Exception**: If the tool execution raises an exception or returns an MCP error (`isError=True`), settlement is aborted, the payment hash reservation is released, and the client is not charged.
- **Settlement Failure**: If on-chain submission fails, `ToolError("payment settlement failed: <reason>")` is raised and tool output is withheld.
- **Settlement Success**: Transaction is committed in the `ReplayStore` and settlement headers are attached to the response.

#### Facilitator Fee Floor
In Algorand `x402` exact payments, the server acts as fee payer for an atomic 2-transaction group (client payment txn + server fee-payer txn), costing `2 x min_fee_per_txn = 2000 microalgos`.
- **Startup Check**: If `allow_loss=False`, `PaymentGate.__init__` raises `ValueError` if any price in `prices` or `default_price` falls in `0 < v <= fee_cost` (`gate.py:146-162`).
- **Runtime Clamping**: In `price_for()`, if after applying discounts the final price is `0 < price <= fee_cost`, it is clamped to `fee_cost + 1` (2,001 microalgos) and logs a warning once per tool.
- **Free Tools**: Tools with price 0 stay 0.
- Real execution example: `paid=6000 fee=2000 net=4000` or `paid=3000 fee=2000 net=1000`.

### 2. `ReplayStore` (Cross-Proxy Replay Protection)
`ReplayStore` (`ai_economy_sdk/replay.py:10-70`) tracks processed transaction hashes:
- Supports in-memory storage (when `replay_db` is omitted) or a persistent SQLite database in WAL mode (`PRAGMA journal_mode=WAL;`).
- Multi-process servers sharing a single domain (e.g. `mcp_server_1..4`) share the SQLite database file (`replay_<domain>.sqlite`), preventing replay attacks across different proxy workers.

### 3. `AIEconomySDK` (High-Level / Compatibility Interface)
Convenience wrapper combining FastMCP, dynamic tool decorators, and PaymentGate:

```python
from ai_economy_sdk import AIEconomySDK, DefaultAvmSigner

sdk = AIEconomySDK(
    server_signer=signer,
    network="testnet",
    asset_id="0",
    pay_to_address=server_addr,
    indexer_url="https://testnet-idx.algonode.cloud",
    subscription_asset_id=1010,
)

@sdk.add_tool(
    name="get_weather",
    description="Get weather for a location",
    pricing_func=lambda args, sender=None: 15000 if args.get("location") == "PremiumCity" else 5000,
)
async def get_weather(location: str) -> str:
    return f"The weather in {location} is 72 degrees and sunny!"

app = sdk.build_app()
```

### 4. `paid_mcp_session` (Client)
Async context manager for consumer clients that automatically handles `402 Payment Required` challenges, composes atomic payment transactions on Algorand, attaches signed identity headers, and executes MCP tool calls:

```python
from ai_economy_sdk import paid_mcp_session

async with paid_mcp_session(
    sse_url="http://127.0.0.1:8001/sse",
    private_key=client_pk,
    network="mainnet",      # algod defaults to AlgoNode; pass algod_url/algod_token for your own node
) as session:
    res = await session.call_tool("get_weather", {"location": "PremiumCity"})
    print("Result:", [c.text for c in res.content])
```

### 5. Identity Proofs (`sign_identity`, `verify_identity`, & Browser `X-Identity-Txn`)
Clients prove account ownership via off-chain signatures without submitting a blockchain transaction:
- **Legacy Headers**: `x-sender-address`, `x-sender-timestamp`, `x-sender-signature` over `x402-identity:{address}:{timestamp}`.
- **Browser Wallet Identity Proof (`X-Identity-Txn`)**: Standard browser wallets cannot sign arbitrary text bytes, but can sign Algorand transactions. `make_identity_txn`, `sign_identity_txn`, and `verify_identity_txn` generate and verify a never-submitted zero-fee, zero-amount self-payment (`X-Identity-Txn: base64(msgpack(signed_txn))`). Because `fee=0`, it can never be confirmed on-chain on its own, ensuring safe zero-cost authentication.

### 6. `ChainReader` & Subscription Issuer Check
Interacts with the Algorand Indexer to check token holdings, verified subscription receipts, and past payment volume:
- `has_active_subscription(address, asset_id, max_age_days=30.0, issuer=None)`: Checks if the user holds the subscription ASA and received it within `max_age_days`. When `issuer` is specified, verifies that the asset transfer sender was the authorized issuer (preventing secondary token circulations from granting subscriptions).
- `PaymentGate(..., subscription_issuer="...")`: Passes the trusted issuer address to `has_active_subscription` when evaluating free subscriber access.
- `past_usage(address, pay_to, asset_id, days=30)`: Sums payments made by the address to the server over the trailing window.

---

## Testing & Adversarial Security Suite

Run unit, integration, and security tests against LocalNet:

```bash
# 1. Run unit tests offline
python -m pytest tests -q

# 2. Run full test suite including live LocalNet e2e settlement and replay tests
LOCALNET=1 python -m pytest tests -q

# 3. Check against the real TestNet and MainNet (read-only: payments are only simulated, nothing is signed with a funded key or sent)
PUBLIC_NETS=1 python -m pytest tests -q -m public

# 3. Run adversarial security test suite (10 on-chain attack vectors)
LOCALNET=1 python -m pytest tests/test_adversarial_localnet.py -v
```

### Adversarial On-Chain Security Tests (`test_adversarial_localnet.py:210-420`):
1. `test_attack_1_underpay`: Rejects client transaction paying less than required price.
2. `test_attack_2_wrong_receiver`: Rejects transaction sending payment to an address other than `pay_to`.
3. `test_attack_3_wrong_asset`: Rejects transaction using wrong asset ID (e.g. ALGO instead of required ASA).
4. `test_attack_4_forged_signature`: Rejects transactions with invalid or forged cryptographic signatures.
5. `test_attack_5_tampered_after_signing`: Rejects transaction payloads modified after client signing.
6. `test_attack_6_expired`: Rejects transactions with validity rounds outside the current network round window.
7. `test_attack_7_wrong_genesis_hash`: Rejects transactions targeting a different genesis hash / network.
8. `test_attack_8_group_broken`: Rejects malformed or incomplete atomic transaction groups.
9. `test_attack_9_insufficient_funds`: Rejects transactions from accounts with insufficient balance.
10. `test_attack_10_replay_across_proxies`: Verifies that replaying a payment payload across different proxy ports sharing a SQLite `ReplayStore` is rejected with HTTP 402.

## License

MIT. See `LICENSE`.
