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
ReplayStoreand 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__raisesValueErrorif any price inpricesordefault_pricefalls in0 < v <= fee_cost(gate.py:146-162). - Runtime Clamping: In
price_for(), if after applying discounts the final price is0 < price <= fee_cost, it is clamped tofee_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=4000orpaid=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_dbis 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-signatureoverx402-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, andverify_identity_txngenerate and verify a never-submitted zero-fee, zero-amount self-payment (X-Identity-Txn: base64(msgpack(signed_txn))). Becausefee=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 withinmax_age_days. Whenissueris 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 tohas_active_subscriptionwhen 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):
test_attack_1_underpay: Rejects client transaction paying less than required price.test_attack_2_wrong_receiver: Rejects transaction sending payment to an address other thanpay_to.test_attack_3_wrong_asset: Rejects transaction using wrong asset ID (e.g. ALGO instead of required ASA).test_attack_4_forged_signature: Rejects transactions with invalid or forged cryptographic signatures.test_attack_5_tampered_after_signing: Rejects transaction payloads modified after client signing.test_attack_6_expired: Rejects transactions with validity rounds outside the current network round window.test_attack_7_wrong_genesis_hash: Rejects transactions targeting a different genesis hash / network.test_attack_8_group_broken: Rejects malformed or incomplete atomic transaction groups.test_attack_9_insufficient_funds: Rejects transactions from accounts with insufficient balance.test_attack_10_replay_across_proxies: Verifies that replaying a payment payload across different proxy ports sharing a SQLiteReplayStoreis rejected with HTTP 402.
Metadata
Release files for ai-economy-sdk 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ai_economy_sdk-0.3.0.tar.gz | 43.8 kB | Without provenance | Details for ai_economy_sdk-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ai_economy_sdk-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for ai_economy_sdk-0.3.0-py3-none-any.whl |
Total release size: 65.2 kB
Release files / ai_economy_sdk-0.3.0.tar.gz
| Download URL | ai_economy_sdk-0.3.0.tar.gz |
|---|---|
| Size | 43.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f5bd89843b0c565f0498812e62f83a66ca3303e316e42aca53aed19ed83b236a
|
|
BLAKE2b-256 checksum How to use checksums |
21e37ef5f51e459e221efbeee2e3691814c06f18c3ffec2e17af6c74aef18bd5
|
| 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.0-py3-none-any.whl
| Download URL | ai_economy_sdk-0.3.0-py3-none-any.whl |
|---|---|
| Size | 21.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
45c976d44c3d621f2cb9be3bd29380655db97fe667fd98556a6dc9a94f5dc9df
|
|
BLAKE2b-256 checksum How to use checksums |
c30d4939281cc786de22c1c08a34c34a6c5aeb553c21385898927215fefbc7a9
|
| 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.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.