Skip to main content

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.

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:

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:

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

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

Metadata

Release files for ai-economy-sdk 0.3.1

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.3.1
File Size Uploaded Provenance Actions
ai_economy_sdk-0.3.1.tar.gz 44.5 kB Without provenance Details for ai_economy_sdk-0.3.1.tar.gz

Built distribution (wheel)

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

Total release size: 66.8 kB

Release files / ai_economy_sdk-0.3.1.tar.gz

Download URL ai_economy_sdk-0.3.1.tar.gz
Size 44.5 kB
Tags Source
SHA-256 checksum
How to use checksums
d8d265727dd867f9dcc5b394748a9ae63096000b0349984bddd93df28dd5a13e
BLAKE2b-256 checksum
How to use checksums
ad164c5e4947480a5c22e3058cd49422db421a4a62615ddd4ad56314d545194f
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.3.1-py3-none-any.whl

Download URL ai_economy_sdk-0.3.1-py3-none-any.whl
Size 22.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8d673f6d20a2d4a3e68d8667e4f5462dd62bb5a49179326c952c212cbe42562e
BLAKE2b-256 checksum
How to use checksums
6a5fb6444381005bcb88201c51ba58d3f8ef28e2fe7c8b89ec6fdddd5c6f7cb2
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.3.1

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