Metadata-Version: 2.5
Name: ai-economy-sdk
Version: 0.5.1
Summary: Payment-gated MCP server SDK for Algorand
Project-URL: Homepage, https://github.com/x402-avm/ai-economy-sdk
Project-URL: Documentation, https://x402-avm.github.io
Project-URL: Repository, https://github.com/x402-avm/ai-economy-sdk
Project-URL: Issues, https://github.com/x402-avm/ai-economy-sdk/issues
Project-URL: Changelog, https://github.com/x402-avm/ai-economy-sdk/blob/main/CHANGELOG.md
Author: x402-avm contributors
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,algorand,avm,mcp,micropayments,model-context-protocol,payments,x402
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: exceptiongroup>=1.0; python_version < '3.11'
Requires-Dist: fastapi
Requires-Dist: fastmcp<4,>=3.4
Requires-Dist: httpx>=0.27
Requires-Dist: mcp<2,>=1.29
Requires-Dist: py-algorand-sdk>=2.6
Requires-Dist: starlette
Requires-Dist: uvicorn>=0.30
Requires-Dist: x402-algorand>=0.2.1
Requires-Dist: x402<3,>=2.28
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.8; extra == 'dev'
Requires-Dist: twine>=5.0; extra == 'dev'
Description-Content-Type: text/markdown

# ai-economy-sdk

[![CI](https://github.com/x402-avm/ai-economy-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/x402-avm/ai-economy-sdk/actions/workflows/ci.yml)
[![PyPI version](https://img.shields.io/pypi/v/ai-economy-sdk.svg)](https://pypi.org/project/ai-economy-sdk/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

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

This project is part of the [x402-avm](https://github.com/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](https://github.com/x402-foundation/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

```bash
pip install ai-economy-sdk
```

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

## Quickstart

### 1. Server: Monetize FastMCP Tools

```python
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

```python
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:

```python
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 `ToolError`s, 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](https://x402-avm.github.io): Architecture guides, tutorials, and API references.
- [x402-avm/examples](https://github.com/x402-avm/examples): Runnable examples for LocalNet, TestNet, and MainNet.
- [x402-algorand](https://github.com/x402-avm/x402-algorand): Algorand exact payment scheme plugin for official `x402`.
- [x402-avm-js](https://github.com/x402-avm/x402-avm-js): TypeScript client for web browsers and Node.js.

## Development

Clone the repository and install development dependencies:

```bash
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:

```bash
# 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:

```bash
ruff check .
ruff format --check .
```

## License

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