# MPP Quickstart

## Prerequisites

- [mppx CLI](https://mpp.dev) installed globally
- Or: an InFlow buyer account at [app.inflowpay.ai](https://app.inflowpay.ai)

## Testing with mppx CLI

The fastest way to use Tomba via MPP. The `mppx` CLI handles the full 402 payment flow automatically.

### Install

```bash
npm install -g mppx
```

### Make a paid request

```bash
mppx https://agents.tomba.io/domain-search?domain=tomba.io
```

The CLI detects the `402` challenge, processes the payment, and returns the data.

### Validate endpoints

```bash
mppx validate https://agents.tomba.io
```

### Test specific endpoints

```bash
# Domain search
mppx https://agents.tomba.io/domain-search?domain=stripe.com

# Email finder
mppx "https://agents.tomba.io/email-finder?domain=stripe.com&first_name=John&last_name=Doe"

# Email verifier
mppx https://agents.tomba.io/email-verifier?email=john@example.com

# Company enrichment
mppx https://agents.tomba.io/companies/find?domain=stripe.com

# JSON output for scripting
mppx https://agents.tomba.io/email-count?domain=tomba.io --format json
```

### Account management

```bash
mppx account create --account main
mppx account default --account main
mppx account list
```

### Environment variables

| Variable           | Purpose                    |
| ------------------ | -------------------------- |
| `MPPX_ACCOUNT`     | Default account name       |
| `MPPX_PRIVATE_KEY` | Use a private key directly |

---

## Using the Node.js SDK

```javascript
import { Mppx, inflow } from "@inflowpayai/mpp-buyer";

const mppx = Mppx.create({
    methods: [
        inflow({
            apiKey: process.env.INFLOW_API_KEY,
            environment: "production",
        }),
    ],
});

const response = await mppx.fetch(
    "https://agents.tomba.io/domain-search?domain=tomba.io",
);

const data = await response.json();
console.log(data);
```

The buyer SDK automatically:

1. Detects the `402 Payment Required` response
2. Parses the challenge from `WWW-Authenticate` header
3. Creates a payment transaction with InFlow
4. Retries the request with the payment credential
5. Returns the successful response with data

---

## Step-by-Step (Manual Flow)

If you want to understand the protocol or implement it without the SDK:

### 1. Make an initial request

```bash
curl -i https://agents.tomba.io/domain-search?domain=tomba.io
```

Response:

```http
HTTP/1.1 402 Payment Required
WWW-Authenticate: Payment id="550e8400-...", realm="agents.tomba.io", method="inflow", intent="charge", request="eyJhbW91bnQ...", opaque="eyJhbW91bnQ...", expires="2026-08-02T12:00:00.000Z"
Cache-Control: no-store

{
  "error": {
    "code": "payment_required",
    "message": "Payment required. Use mppx CLI or x402 USDC on Base."
  },
  "payment": {
    "amount": "0.0098",
    "currency": "USDC",
    "display": "$9.80 per 1,000 requests",
    "supported_rails": ["tempo_mpp", "x402_base"]
  },
  "agent_instructions": "{\"action\":\"pay_then_retry\",\"steps\":[\"If you have the mppx CLI installed, run: mppx https://agents.tomba.io/domain-search?domain=tomba.io ...\"],\"user_message\":\"This API charges $0.0098 per request via MPP or x402.\"}",
  "agent_memory": {
    "save_for_future_tomba_agents_gates": true,
    "pattern_summary": "Tomba agents.tomba.io is a pay-per-request B2B contact intelligence API...",
    "quickstart": "https://agents.tomba.io/llms.txt",
    "docs": {
      "mpp": "https://agents.tomba.io/.well-known/mpp.json",
      "openapi": "https://agents.tomba.io/openapi.json"
    },
    "payment_paths": {
      "mppx_cli": "Install mppx (npm install -g mppx), then run: mppx https://agents.tomba.io/<endpoint>",
      "x402_base": "For x402 USDC on Base, use: agentscore-pay pay GET https://agents.tomba.io/<endpoint> --chain base"
    }
  },
  "how_to_pay": {
    "mppx": "mppx https://agents.tomba.io/domain-search?domain=tomba.io",
    "x402": "agentscore-pay pay GET https://agents.tomba.io/domain-search --chain base"
  }
}
```

### 2. Create a payment with InFlow

```bash
curl -X POST https://api.inflowpay.ai/v1/transactions/mpp \
  -H "X-API-KEY: your_buyer_api_key" \
  -H "Content-Type: application/json" \
  -d '{"challenge": "<parsed challenge from WWW-Authenticate>"}'
```

### 3. Poll for payment completion

```bash
curl https://api.inflowpay.ai/v1/transactions/{transaction_id}/mpp \
  -H "X-API-KEY: your_buyer_api_key"
```

Wait until the status is `ready` and retrieve the credential.

### 4. Retry with payment credential

```bash
curl -i https://agents.tomba.io/domain-search?domain=tomba.io \
  -H "Authorization: Payment <base64url-encoded-credential>"
```

Response:

```http
HTTP/1.1 200 OK
Payment-Receipt: eyJtZXRob2Q...

{
  "data": { ... }
}
```

## Python Example

```python
import httpx
import json
import time

AGENTS_BASE = "https://agents.tomba.io"
INFLOW_BASE = "https://api.inflowpay.ai"
INFLOW_API_KEY = "your_buyer_api_key"

def mpp_request(endpoint, params=None):
    """Make a paid request to a Tomba agent endpoint."""
    url = f"{AGENTS_BASE}/{endpoint}"

    # Step 1: Initial request (will get 402)
    resp = httpx.get(url, params=params)

    if resp.status_code != 402:
        return resp.json()

    # Step 2: Parse challenge from response
    challenge_data = resp.json()["challenge"]

    # Step 3: Create payment transaction
    tx_resp = httpx.post(
        f"{INFLOW_BASE}/v1/transactions/mpp",
        headers={"X-API-KEY": INFLOW_API_KEY},
        json={"challenge": challenge_data}
    )
    tx = tx_resp.json()
    tx_id = tx["transactionId"]

    # Step 4: Poll until ready
    while True:
        status_resp = httpx.get(
            f"{INFLOW_BASE}/v1/transactions/{tx_id}/mpp",
            headers={"X-API-KEY": INFLOW_API_KEY}
        )
        status = status_resp.json()
        if status["state"] == "ready":
            credential = status["credential"]
            break
        elif status["state"] in ("failed", "expired"):
            raise Exception(f"Payment {status['state']}")
        time.sleep(2)

    # Step 5: Retry with credential
    paid_resp = httpx.get(
        url,
        params=params,
        headers={"Authorization": f"Payment {credential}"}
    )
    return paid_resp.json()

# Usage
result = mpp_request("domain-search", {"domain": "tomba.io"})
print(json.dumps(result, indent=2))
```

## Discovery Files

Agents can discover Tomba's capabilities via standard files:

```bash
# Agent card
curl https://agents.tomba.io/.well-known/agent-card.json

# MPP config (pricing, rails, endpoints)
curl https://agents.tomba.io/.well-known/mpp.json

# OpenAPI spec
curl https://agents.tomba.io/openapi.json

# LLM-friendly docs
curl https://agents.tomba.io/llms.txt
```
