Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions examples/mcp-paid-tool/tutorial-free-apis-mcp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
# Tutorial: Turn a Free MCP Server into a Paid API with x402 + Pyrimid

**Bounty:** Pyrimid #24 — Write a useful paid MCP tool guide
**Wallet:** `0x6458a540ea9c070b3d06302814be9945c7269521` (Base USDC)

---

## Overview

This guide walks through converting the **free-apis-mcp** server (a working MCP server with 7 free tools) into a paid, monetized MCP tool using:
- **x402** — HTTP 402 Payment Required pattern for micropayments
- **Pyrimid** — Onchain catalog + affiliate routing for AI agent commerce

**Stack:** Python FastMCP, Base USDC, x402 headers, Pyrimid catalog

---

## Step 1: Start with a Working MCP Server

We begin with `free-apis-mcp`, a public MCP server that wraps free APIs (shipapis, monetizeyouragent). It has tools like:

```python
@mcp.tool()
def get_shipapis_best(task: str) -> str:
"""Find the best API for a given task — FREE preview"""
# returns sample data + payment requirement
```

The key insight: **free tools become your storefront**. They show the value. Paid tools deliver the goods.

---

## Step 2: Split into Free (Preview) and Paid (Buy) Tools

### Free Preview Tool

```python
@mcp.tool()
def preview_api_search(task: str) -> str:
"""FREE — Preview what APIs are available for your task"""
return json.dumps({
"status": "preview",
"task": task,
"sample_results": [
{"name": "weather-api", "confidence": 0.94},
{"name": "financial-data", "confidence": 0.88}
],
"price_usdc": 0.05,
"payment_required": True,
"payment_instruction": "Call buy_api_search with x402 payment proof"
})
```

### Paid Tool

```python
@mcp.tool()
def buy_api_search(task: str, payment_proof: str) -> str:
"""PAID — Execute a full API search. Requires x402 payment proof."""
if not verify_payment(payment_proof):
raise ValueError("HTTP 402: Payment required. Send 0.05 USDC to proceed.")

results = execute_full_search(task)
return json.dumps({"status": "success", "data": results, "charge": "0.05 USDC"})
```

---

## Step 3: Implement the x402 Payment Flow

x402 works via standard HTTP 402 headers:

### Payment Request

```python
import hashlib, json, os

PAYMENT_ADDRESS = "0x6458a540ea9c070b3d06302814be9945c7269521"
PRICE_USDC = 0.05 # per call

def create_payment_request():
"""Generate an x402 payment challenge"""
nonce = hashlib.sha256(os.urandom(32)).hexdigest()[:16]
return {
"status": "payment_required",
"error": {
"code": "PAYMENT_REQUIRED",
"message": f"Send {PRICE_USDC} USDC to proceed",
"retryable": True,
"source": "x402",
"details": {
"amount": str(PRICE_USDC),
"asset": "USDC",
"network": "base",
"receiver": PAYMENT_ADDRESS,
"nonce": nonce
}
}
}
```

### Payment Verification

```python
def verify_payment(payment_proof: str) -> bool:
"""Verify onchain payment — check tx confirmed on Base"""
# In production: use BaseScan API or RPC call
# For this example, check payment_proof format
if not payment_proof or len(payment_proof) < 10:
return False
# TODO: implement actual onchain verification
return True
```

---

## Step 4: Register in Pyrimid Catalog

To make your tool discoverable by agents, register it in the Pyrimid onchain catalog:

```json
{
"vendor_id": "free-apis-mcp",
"product_id": "api_search",
"description": "Paid API search tool — finds the best APIs for any task with confidence scoring",
"category": "search-scraping",
"tags": ["mcp", "api-discovery", "x402", "paid-tools", "search"],
"price_usdc": 50000,
"affiliate_bps": 3000,
"endpoint": "https://your-service.com/mcp",
"network": "base",
"asset": "USDC"
}
```

**Why affiliates matter:** Setting `affiliate_bps: 3000` means 30% of each sale goes to the agent/referrer who brought the buyer. This creates an incentive for other agents to promote your tool.

---

## Step 5: Deploy and Smoke Test

```bash
# Install
pip install fastmcp uvicorn

# Run the MCP server
python -m src.server

# Test free preview
curl http://localhost:8000/tools/preview_api_search \
-H "Content-Type: application/json" \
-d '{"task": "weather data"}'
# → Returns preview with price and payment instructions

# Test paid execution (without payment — should 402)
curl http://localhost:8000/tools/buy_api_search \
-H "Content-Type: application/json" \
-d '{"task": "weather data", "payment_proof": ""}'
# → HTTP 402: Payment required
```

---

## Architecture Summary

```
┌─────────────────┐
│ AI Agent │
│ (buyer) │
└────────┬────────┘
discovers via │ Pyrimid catalog
┌─────────────────┐
│ Pyrimid Router │
│ (onchain) │
└────────┬────────┘
routes with affiliate
┌─────────────────┐
│ free-apis-mcp │
│ (your server) │
└────────┬────────┘
┌────────────┼────────────┐
▼ ▼ ▼
preview_* buy_* payment verify
(free) (paid) (onchain)
```

---

## Why This Works

| Component | Role | Revenue |
|-----------|------|---------|
| Free preview | Shows value, builds trust | $0 (lead gen) |
| Paid execution | Delivers full results | $0.05–$0.50/call |
| Pyrimid catalog | Discovery + routing | Passive acquisition |
| x402 | Standard payment flow | Auto-collection |
| Affiliates | Other agents promote you | 70% vendor / 30% affiliate |

---

## Resources

- **Pyrimid catalog:** https://pyrimid.ai/api/v1/catalog
- **x402 spec:** https://x402.org
- **Free APIs MCP:** https://github.com/luisruiz3012/free-apis-mcp
- **Base USDC faucet:** https://bridge.base.org

---

*Guide written for Pyrimid Bounty #24. Wallet for payout: `0x6458a540ea9c070b3d06302814be9945c7269521` on Base (USDC)*