# paid_mcp_session

> Open an MCP session that pays for tool calls with x402 on Algorand.

```python
from ai_economy_sdk import paid_mcp_session
```

```python
@contextlib.asynccontextmanager
async def paid_mcp_session(
    sse_url: str,
    private_key: str,
    network: str,
    algod_url: str | None = None,
    algod_token: str | None = None,
    identity: bool = True,
    timeout: float = 30.0,
    spend_controls: SpendControlsArg = None,
    transport: ClientTransport | None = None,
) -> AsyncGenerator[ClientSession, None]
```

Open an MCP session that pays for tool calls with x402 on Algorand.

Connects to a remote Model Context Protocol server over Streamable HTTP or the
legacy SSE transport, initializing a ClientSession configured with an x402-aware
HTTP client. Outgoing requests automatically carry identity headers (if enabled)
and auto-sign 402 payment challenges for exact Algorand scheme payments.

**Notes**

On receiving HTTP 402 with `PAYMENT-REQUIRED`, the client verifies requirements,
constructs an Algorand transaction or 2-txn atomic group (where the server sponsors
transaction fees as fee payer), signs it, and resubmits under `PAYMENT-SIGNATURE`.
Funds are only deducted from the buyer's account if the tool execution succeeds.

## Parameters

- `sse_url` (`str`, required):
URL of the server's MCP endpoint: `"http://localhost:8000/mcp"` for Streamable
HTTP or `"http://localhost:8000/sse"` for SSE. (The parameter keeps its 0.4
name for compatibility; it accepts either kind of URL.)

- `private_key` (`str`, required):
Base64-encoded 32-byte Algorand private key used by the buyer to sign payments
and identity proofs.

- `network` (`str`, required):
Target Algorand network name (`"mainnet"`, `"testnet"`, `"localnet"`),
canonical CAIP-2 identifier (`"algorand:<32-char-prefix>"`), or legacy long ID.

- `algod_url` (`str | None`, default `None`):
Custom URL for the algod node. If None, defaults to the standard endpoint
for the given network (AlgoNode for public networks, localhost for localnet).

- `algod_token` (`str | None`, default `None`):
Custom authentication token header for the algod node. Default is None.

- `identity` (`bool`, default `True`):
Whether to attach cryptographic identity headers (`x-sender-*`) proving
account ownership on every request to enable vendor discounts and passes.

- `timeout` (`float`, default `30.0`):
HTTP request timeout in seconds for normal requests. Stream reads allow up
to 300 seconds.

- `spend_controls` (`SpendControlsArg`, default `None`):
Client-side spending limits enforced by x402Client before payment authorization:
- None (default): official x402 defaults apply — only default assets (native ALGO
and USDC) are allowed, capped at 1,000,000 base atomic units (1 ALGO / 1 USDC) per payment.
- False: disables all spend controls (any asset, unlimited amount).
- dict: custom spend controls following the x402 SpendControls schema, e.g.:
`{"max_amount_per_payment": False}` removes the amount cap while keeping default assets,
`{"allowed_assets": True}` allows any asset while keeping default payment cap, or
`{"allowed_assets": [{"network": network, "asset": "12345", "max_amount_per_payment": "5000000"}]}`
whitelists a specific ASA.

- `transport` (`ClientTransport | None`, default `None`):
MCP transport to use. When omitted, Streamable HTTP is used if the URL path ends
in `/mcp` and SSE otherwise, which keeps 0.4 behaviour for SSE URLs.

## Yields

- `yields` (`mcp.ClientSession`):
Active, initialized MCP client session capable of invoking tools via
`session.call_tool(tool_name, arguments)`.

## Raises

- `ConfigurationError`: If `transport` is not `"streamable-http"` or `"sse"`.
- `SpendLimitExceededError`: If a tool call needs a payment that `spend_controls` forbid (amount above the cap, or an asset that is not allowed). Nothing is signed and no funds move. The x402 error is its `__cause__`. Other errors propagate unchanged.

## Examples

```python
# Needs running paid MCP server:
import asyncio
from ai_economy_sdk import paid_mcp_session

async def run():
    async with paid_mcp_session(
        "http://localhost:8000/mcp",
        private_key=buyer_pk,
        network="localnet",
    ) as session:
        result = await session.call_tool("echo", {"text": "hello"})
        print(result)

asyncio.run(run())
```

## See also

- `PaymentGate`: Server-side payment middleware.
- `AIEconomySDK`: High-level server framework.

Source: [ai_economy_sdk/client.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/client.py#L100)

Source: https://x402-avm.github.io/reference/python/ai-economy-sdk/paid-mcp-session
