Skip to main content

AI Economy SDK (v0.4)

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.

pip install ai-economy-sdk

Migrating from 0.3

  • CAIP-2 Network Identifiers: Algorand network IDs now use the standard CAIP-2 short format (32-character URL-safe prefix of the raw genesis hash), e.g. algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k for MainNet and algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe for TestNet.
  • Backwards Compatibility: Legacy long IDs (algorand:<full 44-char base64 hash ending in =>) are still accepted everywhere as input and automatically normalized to the short format.
  • Official x402 Architecture: x402-algorand is now a standalone plugin for the official x402 (>=2.28) package instead of a monorepo fork.

Networks

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

You pass Means CAIP-2 ID Genesis Hash Default Endpoints
"mainnet" Algorand MainNet algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8= AlgoNode mainnet-api / mainnet-idx
"testnet" Algorand TestNet algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI= AlgoNode testnet-api / testnet-idx
"localnet" AlgoKit LocalNet derived from algod read from algod (sp.gh) localhost:4001 / localhost:8980
"algorand:<prefix>" Custom network short CAIP-2 ID lookup via genesis_hash_for LocalNet ports or user URLs

resolve_network(name) gives the short CAIP-2 id, genesis_hash_for(name) returns the full base64 genesis hash, 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.4)

1. PaymentGate (Core Server Middleware)

Directly wrap any FastMCP instance with payment enforcement, fee floor protection, and replay prevention:

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 CAIP-2 id
    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:

  • 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.
  • 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 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:

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:

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:

# 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

# 4. 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.

Metadata

Release files for ai-economy-sdk 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ai-economy-sdk 0.4.0
File Size Uploaded Provenance Actions
ai_economy_sdk-0.4.0.tar.gz 56.6 kB Without provenance Details for ai_economy_sdk-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ai-economy-sdk 0.4.0
File Interpreter ABI Platform Actions
ai_economy_sdk-0.4.0-py3-none-any.whl Python 3 none any Details for ai_economy_sdk-0.4.0-py3-none-any.whl

Total release size: 92.8 kB

Release files / ai_economy_sdk-0.4.0.tar.gz

Download URL ai_economy_sdk-0.4.0.tar.gz
Size 56.6 kB
Tags Source
SHA-256 checksum
How to use checksums
f702acf6f4355412eb7c7d68cf28471e441a711efb6b98142859734341148186
BLAKE2b-256 checksum
How to use checksums
03d00afcb3367f79db92f171d4b1cdfaa66904a503fb55334f065665d9765f38
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.4

Release files / ai_economy_sdk-0.4.0-py3-none-any.whl

Download URL ai_economy_sdk-0.4.0-py3-none-any.whl
Size 36.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
243d83ee25fd01738d34dc0c90c4f0925df46b55c059b3caf0033b39ab5e7df5
BLAKE2b-256 checksum
How to use checksums
cb6874f12f15450d07b3e743c75dc57f5e834af09963bdf86aec837e1c5e4763
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.4

Security for ai-economy-sdk 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page