Skip to main content

ai-economy-sdk

CI PyPI version License: MIT

Payment-gated Model Context Protocol (MCP) server and client SDK for Algorand.

This project is part of the x402-avm GitHub organization. It is not affiliated with GoPlausible's x402-avm packages.

ai-economy-sdk turns Model Context Protocol (MCP) tools into monetized services on Algorand using the official x402 payment standard. On the server side, PaymentGate wraps FastMCP applications to enforce per-call micropayments, dynamic rates, and vendor passes with settle-on-success protection. On the client side, paid_mcp_session connects to payment-gated servers and automatically settles transactions only when tool execution succeeds.

Requirements

  • Python 3.10+
  • x402 >= 2.28, < 3.0
  • x402-algorand >= 0.2.1
  • fastmcp >= 3.4, < 4.0
  • mcp >= 1.29, < 2.0
  • py-algorand-sdk >= 2.6

Installation

pip install ai-economy-sdk

Installing ai-economy-sdk automatically installs x402-algorand and the official x402 package.

Quickstart

1. Server: Monetize FastMCP Tools

from fastmcp import FastMCP
from ai_economy_sdk import PaymentGate, DefaultAvmSigner

mcp = FastMCP("paid-service")


@mcp.tool()
def summarize(text: str) -> str:
    return f"Summary: {text[:50]}..."


gate = PaymentGate(
    signer=DefaultAvmSigner(server_private_key),
    network="localnet",
    pay_to=server_address,
    asset_id=0,  # Native ALGO (or ASA ID such as USDC)
    prices={"summarize": 5_000},  # 5,000 microALGO per call
)

app = gate.wrap(mcp, transport="streamable-http")  # MCP endpoint: POST /mcp
# Run with: uvicorn server:app --port 8000

2. Client: Invoke Paid Tools

import asyncio
from ai_economy_sdk import paid_mcp_session


async def main():
    async with paid_mcp_session(
        "http://127.0.0.1:8000/mcp",
        buyer_private_key,
        "localnet",
    ) as session:
        result = await session.call_tool("summarize", {"text": "Hello Algorand x402"})
        print(result.content[0].text)


asyncio.run(main())

Transports

PaymentGate.wrap() serves either MCP HTTP transport:

transport= Endpoints Notes
"streamable-http" (alias "http") POST /mcp Recommended. Stateless by default; pass stateless_http=False for MCP sessions.
"sse" GET /sse, POST /messages/ Legacy HTTP+SSE transport.

Calling wrap() without transport= still serves SSE, as in 0.4, and emits a FutureWarning: the default will change to "streamable-http" in a future release. paid_mcp_session picks Streamable HTTP for URLs ending in /mcp and SSE otherwise; pass transport= to choose explicitly.

The gate inspects every HTTP POST for a JSON-RPC tools/call, whatever its path. A priced tool call that reaches the FastMCP server any other way (for example over a transport the gate does not wrap) is refused with PaymentRequiredError. To build the HTTP app yourself, install both layers:

from ai_economy_sdk import SettleOnSuccessMiddleware

mcp.add_middleware(SettleOnSuccessMiddleware(gate))
app = mcp.http_app(transport="http", middleware=gate.middleware())

Errors and logging

Every exception the SDK raises deliberately subclasses ai_economy_sdk.AIEconomyError and also the built-in type raised before 0.5.0 (ConfigurationError is a ValueError, SettlementError and PaymentRequiredError are FastMCP ToolErrors, and so on). Payment refusals, settlement failures and failed chain lookups are logged to the ai_economy_sdk logger.

Key Capabilities

  • Settle-on-Success: Payments are verified before tool execution, but committed on-chain only after the tool completes successfully. If a tool raises an error, the payment is never submitted and the buyer is not charged.
  • Identity Verification: Built-in X-Identity-Txn cryptographic proofs (sign_identity_txn) verify client account ownership without on-chain execution or transaction fees. The legacy sign_identity headers are still accepted but the function is deprecated.
  • Spend Limits & Controls: Direct integration with official x402Client spend controls allows setting per-payment caps or whitelisting custom ASAs.
  • Vendor Passes & Subscriptions: Support for period-based access passes and subscription ASA tokens.
  • Replay Protection: Built-in replay prevention using memory or SQLite stores across single-process and multi-worker deployments.

Ecosystem

  • Documentation: Architecture guides, tutorials, and API references.
  • x402-avm/examples: Runnable examples for LocalNet, TestNet, and MainNet.
  • x402-algorand: Algorand exact payment scheme plugin for official x402.
  • x402-avm-js: TypeScript client for web browsers and Node.js.

Development

Clone the repository and install development dependencies:

git clone https://github.com/x402-avm/ai-economy-sdk.git
cd ai-economy-sdk
uv pip install -e ".[dev]"

Run tests across test tiers:

# Tier 1: Offline unit tests (default)
pytest --cov=ai_economy_sdk

# Tier 2: AlgoKit LocalNet integration tests (requires `algokit localnet start`)
LOCALNET=1 pytest

# Tier 3: Public network simulations (TestNet/MainNet, simulate only)
PUBLIC_NETS=1 pytest

Check formatting and linting:

ruff check .
ruff format --check .

License

MIT License. Copyright (c) 2026 x402-avm contributors.

Metadata

Release files for ai-economy-sdk 0.5.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.5.0
File Size Uploaded Provenance Actions
ai_economy_sdk-0.5.0.tar.gz 71.9 kB Without provenance Details for ai_economy_sdk-0.5.0.tar.gz

Built distribution (wheel)

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

Total release size: 116.4 kB

Release files / ai_economy_sdk-0.5.0.tar.gz

Download URL ai_economy_sdk-0.5.0.tar.gz
Size 71.9 kB
Tags Source
SHA-256 checksum
How to use checksums
0d877cbfb81e6bf20a038eabcd9091d9cd018978266b8ae39d4bfde26ab3ba17
BLAKE2b-256 checksum
How to use checksums
f1b2347111fdfb8029154a5c81647444b0ca21616505e94ad4fa7bafd5af000b
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.5.0-py3-none-any.whl

Download URL ai_economy_sdk-0.5.0-py3-none-any.whl
Size 44.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0087717bdfed019740abfd8f2573252ddee72d25aa8d16a34f2108e1b8756bd6
BLAKE2b-256 checksum
How to use checksums
de98213f95945768df87f274fddf5cc1270085b87de40390eb9c28efcc5d55fa
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.5.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