ugarapi-mcp-server 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,185 @@
1
+ # SIMPLE OpenNode Integration - Manual Edit
2
+
3
+ Since main.py is too long, here's the SIMPLE way to add OpenNode:
4
+
5
+ ## Step 1: Add OpenNode Config (Line 33)
6
+
7
+ REPLACE THIS:
8
+ ```python
9
+ BTCPAY_SERVER_URL = os.getenv("BTCPAY_SERVER_URL", "https://demo.btcpayserver.org")
10
+ BTCPAY_STORE_ID = os.getenv("BTCPAY_STORE_ID", "test_store")
11
+ BTCPAY_API_KEY = os.getenv("BTCPAY_API_KEY", "test_key")
12
+ ```
13
+
14
+ WITH THIS:
15
+ ```python
16
+ OPENNODE_API_KEY = os.getenv("OPENNODE_API_KEY", "")
17
+ OPENNODE_API_URL = "https://api.opennode.com/v1"
18
+ ```
19
+
20
+ ## Step 2: Add OpenNode Helper Functions (After line 150, before create_payment function)
21
+
22
+ ADD THESE TWO FUNCTIONS:
23
+ ```python
24
+ async def create_opennode_invoice(service: str, amount_sats: int, idempotency_key: str = None):
25
+ """Create Lightning invoice via OpenNode."""
26
+ async with httpx.AsyncClient() as client:
27
+ headers = {"Authorization": OPENNODE_API_KEY, "Content-Type": "application/json"}
28
+ payload = {
29
+ "amount": amount_sats,
30
+ "currency": "sat",
31
+ "description": f"UgarAPI - {service}",
32
+ "callback_url": "https://ugarapi.com/api/v1/payment/webhook",
33
+ "auto_settle": False
34
+ }
35
+ if idempotency_key:
36
+ payload["order_id"] = idempotency_key
37
+
38
+ response = await client.post(f"{OPENNODE_API_URL}/charges", headers=headers, json=payload)
39
+
40
+ if response.status_code != 201:
41
+ raise Exception(f"OpenNode invoice failed: {response.text}")
42
+
43
+ data = response.json()["data"]
44
+ return {
45
+ "invoice_id": data["id"],
46
+ "payment_request": data["lightning_invoice"]["payreq"],
47
+ "amount_sats": amount_sats,
48
+ "expires_at": data["lightning_invoice"]["expires_at"],
49
+ "checkout_url": data["hosted_checkout_url"]
50
+ }
51
+
52
+ async def check_opennode_payment(invoice_id: str):
53
+ """Check if OpenNode invoice is paid."""
54
+ async with httpx.AsyncClient() as client:
55
+ headers = {"Authorization": OPENNODE_API_KEY}
56
+ response = await client.get(f"{OPENNODE_API_URL}/charge/{invoice_id}", headers=headers)
57
+ if response.status_code != 200:
58
+ return None
59
+ data = response.json()["data"]
60
+ return {"paid": data["status"] == "paid", "status": data["status"]}
61
+ ```
62
+
63
+ ## Step 3: Update create_payment Function
64
+
65
+ FIND the @app.post("/api/v1/payment/create") function and REPLACE the try block with:
66
+
67
+ ```python
68
+ try:
69
+ # Use OpenNode instead of simulated payments
70
+ invoice = await create_opennode_invoice(
71
+ service=request.service.value,
72
+ amount_sats=request.amount_sats,
73
+ idempotency_key=request.idempotency_key
74
+ )
75
+
76
+ payment_data = {
77
+ "invoice_id": invoice["invoice_id"],
78
+ "payment_request": invoice["payment_request"],
79
+ "amount_sats": invoice["amount_sats"],
80
+ "expires_at": invoice["expires_at"],
81
+ "paid": False,
82
+ "used": False,
83
+ "created_at": datetime.utcnow().isoformat(),
84
+ "service": request.service.value,
85
+ "idempotency_key": request.idempotency_key,
86
+ "checkout_url": invoice["checkout_url"] # NEW: manual payment URL
87
+ }
88
+
89
+ payments_db[invoice["invoice_id"]] = payment_data
90
+
91
+ result = PaymentResponse(
92
+ invoice_id=invoice["invoice_id"],
93
+ payment_request=invoice["payment_request"],
94
+ amount_sats=invoice["amount_sats"],
95
+ expires_at=invoice["expires_at"],
96
+ idempotency_key=request.idempotency_key
97
+ )
98
+
99
+ if request.idempotency_key:
100
+ store_idempotency(f"payment_{request.idempotency_key}", result.model_dump())
101
+
102
+ log_audit("payment_created", {
103
+ "invoice_id": invoice["invoice_id"],
104
+ "amount_sats": request.amount_sats,
105
+ "service": request.service.value
106
+ }, req)
107
+
108
+ return result
109
+ ```
110
+
111
+ ## Step 4: Update payment_webhook Function
112
+
113
+ FIND @app.post("/api/v1/payment/webhook") and REPLACE the function body:
114
+
115
+ ```python
116
+ async def payment_webhook(data: Dict, req: Request):
117
+ """Webhook for OpenNode payment confirmations."""
118
+ invoice_id = data.get("id") # OpenNode uses "id"
119
+ status = data.get("status")
120
+
121
+ if invoice_id and invoice_id in payments_db:
122
+ if status == "paid":
123
+ payments_db[invoice_id]["paid"] = True
124
+ payments_db[invoice_id]["paid_at"] = datetime.utcnow().isoformat()
125
+ log_audit("payment_confirmed", {"invoice_id": invoice_id}, req)
126
+
127
+ return {"status": "ok"}
128
+ ```
129
+
130
+ ## Step 5: Update verify_payment Function
131
+
132
+ REPLACE the verify_payment function:
133
+
134
+ ```python
135
+ async def verify_payment(invoice_id: str, required_amount_sats: int) -> bool:
136
+ if invoice_id not in payments_db:
137
+ return False
138
+ payment = payments_db[invoice_id]
139
+
140
+ # Check if already marked paid
141
+ if payment.get("paid", False):
142
+ if time.time() > payment.get("expires_at", 0):
143
+ return False
144
+ if payment.get("used", False):
145
+ return False
146
+ return True
147
+
148
+ # Check with OpenNode directly
149
+ try:
150
+ status = await check_opennode_payment(invoice_id)
151
+ if status and status["paid"]:
152
+ payments_db[invoice_id]["paid"] = True
153
+ return True
154
+ except:
155
+ pass
156
+
157
+ return False
158
+ ```
159
+
160
+ ## Step 6: Update Version Number
161
+
162
+ Change line 22:
163
+ ```python
164
+ version="1.2.0" # Was 1.1.0
165
+ ```
166
+
167
+ And update @app.get("/") to show:
168
+ ```python
169
+ "version": "1.2.0",
170
+ "new_in_v1.2": ["Real Bitcoin Lightning payments via OpenNode"]
171
+ ```
172
+
173
+ ---
174
+
175
+ ## DONE!
176
+
177
+ After making these changes:
178
+ 1. Commit to GitHub
179
+ 2. Railway auto-deploys
180
+ 3. Add OPENNODE_API_KEY to Railway variables
181
+ 4. Test creating an invoice!
182
+
183
+ **OR - if this is too complex, I can just create a completely new main.py file for you to copy/paste!**
184
+
185
+ Let me know which you prefer!
package/README.md ADDED
@@ -0,0 +1,165 @@
1
+ # UgarAPI MCP Server
2
+
3
+ Model Context Protocol (MCP) server for UgarAPI - enables AI agents to discover and use UgarAPI services with Bitcoin Lightning payments.
4
+
5
+ ## What This Does
6
+
7
+ Exposes UgarAPI's services as MCP tools that AI systems (Claude, ChatGPT, etc.) can discover and use automatically:
8
+
9
+ - **extract_web_data** - Extract structured data from websites using CSS selectors
10
+ - **timestamp_document** - Create blockchain timestamp proofs for documents
11
+ - **aggregate_api_call** - Route requests through external APIs with failover
12
+
13
+ All payments are handled automatically via Bitcoin Lightning micropayments.
14
+
15
+ ## Installation
16
+
17
+ ### For End Users (Claude Desktop, etc.)
18
+
19
+ 1. Install via npm:
20
+ ```bash
21
+ npm install -g ugarapi-mcp-server
22
+ ```
23
+
24
+ 2. Add to your MCP settings file:
25
+
26
+ **Claude Desktop (macOS):** `~/Library/Application Support/Claude/claude_desktop_config.json`
27
+
28
+ **Claude Desktop (Windows):** `%APPDATA%\Claude\claude_desktop_config.json`
29
+
30
+ ```json
31
+ {
32
+ "mcpServers": {
33
+ "ugarapi": {
34
+ "command": "ugarapi-mcp",
35
+ "env": {
36
+ "UGARAPI_BASE_URL": "https://ugarapi.com"
37
+ }
38
+ }
39
+ }
40
+ }
41
+ ```
42
+
43
+ 3. Restart Claude Desktop
44
+
45
+ 4. Claude can now use UgarAPI services automatically!
46
+
47
+ ### For Developers
48
+
49
+ ```bash
50
+ git clone https://github.com/yourusername/ugarapi-mcp-server
51
+ cd ugarapi-mcp-server
52
+ npm install
53
+ node ugarapi-mcp-server.js
54
+ ```
55
+
56
+ ## Usage Examples
57
+
58
+ Once installed, AI agents can use your services naturally:
59
+
60
+ ### Example 1: Web Scraping
61
+ ```
62
+ User: "Extract the title and price from https://example.com/product"
63
+
64
+ Claude: [calls extract_web_data tool]
65
+ - Creates Lightning invoice (1000 sats)
66
+ - Pays automatically
67
+ - Returns extracted data
68
+ ```
69
+
70
+ ### Example 2: Document Timestamping
71
+ ```
72
+ User: "Timestamp this document hash: abc123..."
73
+
74
+ Claude: [calls timestamp_document tool]
75
+ - Creates Lightning invoice (5000 sats)
76
+ - Pays automatically
77
+ - Returns blockchain proof
78
+ ```
79
+
80
+ ### Example 3: API Aggregation
81
+ ```
82
+ User: "What's the weather in Tokyo?"
83
+
84
+ Claude: [calls aggregate_api_call tool]
85
+ - Creates Lightning invoice (200 sats)
86
+ - Pays automatically
87
+ - Returns weather data
88
+ ```
89
+
90
+ ## How Payments Work
91
+
92
+ 1. **First Call:** MCP server creates a Lightning invoice for the service
93
+ 2. **Payment:** Invoice is paid automatically (in production, you'd configure a Lightning wallet)
94
+ 3. **Service Call:** Once paid, the service executes
95
+ 4. **Idempotency:** Same requests won't be charged twice (cached for 24 hours)
96
+
97
+ ## Configuration
98
+
99
+ Environment variables:
100
+
101
+ - `UGARAPI_BASE_URL` - UgarAPI API endpoint (default: https://ugarapi.com)
102
+
103
+ ## Payment Setup (Production)
104
+
105
+ For production use with real payments, you need:
106
+
107
+ 1. **Lightning Wallet** - Set up a wallet that can pay invoices programmatically
108
+ 2. **Auto-Payment Logic** - Configure the MCP server to pay invoices automatically
109
+ 3. **Spending Limits** - Set maximum spend per hour/day to prevent runaway costs
110
+
111
+ See `docs/payment-setup.md` for detailed instructions.
112
+
113
+ ## Features
114
+
115
+ ✅ **Idempotency** - Safe retries, no double charges
116
+ ✅ **Rate Limiting** - Respects UgarAPI rate limits
117
+ ✅ **Error Handling** - Clear error messages for agents
118
+ ✅ **Receipts** - Full transaction history
119
+ ✅ **Audit Trail** - All calls are logged
120
+
121
+ ## Development
122
+
123
+ Run in development mode:
124
+ ```bash
125
+ npm start
126
+ ```
127
+
128
+ Test with MCP Inspector:
129
+ ```bash
130
+ npx @modelcontextprotocol/inspector node ugarapi-mcp-server.js
131
+ ```
132
+
133
+ ## Publishing to MCP Registry
134
+
135
+ Once tested:
136
+
137
+ 1. Publish to npm:
138
+ ```bash
139
+ npm publish
140
+ ```
141
+
142
+ 2. Submit to MCP registry:
143
+ ```bash
144
+ # Follow instructions at https://github.com/modelcontextprotocol/servers
145
+ ```
146
+
147
+ 3. AI systems can now discover UgarAPI automatically!
148
+
149
+ ## Roadmap
150
+
151
+ - [ ] Automatic Lightning payment integration
152
+ - [ ] Spending limit controls
153
+ - [ ] Multi-agent usage tracking
154
+ - [ ] Advanced caching strategies
155
+ - [ ] Support for more UgarAPI services as they launch
156
+
157
+ ## Support
158
+
159
+ - **UgarAPI Docs:** https://ugarapi.com/docs
160
+ - **Issues:** https://github.com/yourusername/ugarapi-mcp-server/issues
161
+ - **Email:** support@ugarapi.com
162
+
163
+ ## License
164
+
165
+ MIT License - see LICENSE file for details
@@ -0,0 +1,200 @@
1
+ # Autonomous AI Service Business - Complete Blueprint
2
+
3
+ ## Executive Summary
4
+ Launch an automated business providing 3 essential services to AI agents, paid via Bitcoin Lightning micropayments. Total startup cost: ~$500.
5
+
6
+ ---
7
+
8
+ ## The 3 Services
9
+
10
+ ### Service 1: Web Data Extraction API
11
+ **What it does:** AI agents need to extract structured data from websites that don't have APIs
12
+ **Pricing:** 0.0001 BTC (~$10) per 1000 extractions
13
+ **Why AI agents need it:** Most AI agents can't reliably parse complex websites themselves
14
+ **Technical complexity:** Low
15
+ **Revenue potential:** High (constant demand)
16
+
17
+ ### Service 2: Document Verification & Timestamping
18
+ **What it does:** Cryptographically timestamp and verify documents on Bitcoin blockchain
19
+ **Pricing:** 0.00005 BTC (~$5) per document
20
+ **Why AI agents need it:** Autonomous contracts need proof of document existence at specific times
21
+ **Technical complexity:** Medium
22
+ **Revenue potential:** Medium (growing with AI agent adoption)
23
+
24
+ ### Service 3: Cross-Platform API Aggregator
25
+ **What it does:** Single API endpoint that routes requests to multiple services (weather, maps, data APIs) with automatic failover
26
+ **Pricing:** 0.00002 BTC (~$2) per 100 calls + cost pass-through
27
+ **Why AI agents need it:** Reduces integration complexity, handles rate limits and failures
28
+ **Technical complexity:** Medium
29
+ **Revenue potential:** High (recurring usage)
30
+
31
+ ---
32
+
33
+ ## Technical Architecture
34
+
35
+ ### Stack
36
+ - **Backend:** Python + FastAPI
37
+ - **Payment:** Lightning Network (BTCPay Server)
38
+ - **Database:** PostgreSQL (free tier)
39
+ - **Hosting:** Railway.app or Render.com (~$5-15/month)
40
+ - **Domain:** Namecheap (~$12/year)
41
+
42
+ ### Payment Flow
43
+ 1. AI agent requests service via API
44
+ 2. System generates Lightning invoice
45
+ 3. Agent pays invoice (settlement in <1 second)
46
+ 4. System verifies payment
47
+ 5. Service executes and returns result
48
+ 6. Transaction logged
49
+
50
+ ---
51
+
52
+ ## Marketing to AI Agents
53
+
54
+ ### Discovery Channels
55
+ 1. **AI Agent Directories:**
56
+ - List on AIAgentMarketplace.com
57
+ - Register with LangChain integrations
58
+ - AutoGPT plugin directory
59
+
60
+ 2. **Machine-Readable Service Description:**
61
+ - OpenAPI/Swagger spec at yourservice.com/api/spec
62
+ - JSON-LD structured data for AI discovery
63
+ - robots.txt optimized for AI agent crawlers
64
+
65
+ 3. **Direct Integration:**
66
+ - Create MCP (Model Context Protocol) server
67
+ - Publish to MCP registry
68
+ - AI systems can auto-discover your services
69
+
70
+ 4. **API Reputation:**
71
+ - Uptime monitoring (99.9%+ SLA)
72
+ - Published performance metrics
73
+ - Public API status page
74
+
75
+ ### Marketing Content (Machine-Readable)
76
+ ```json
77
+ {
78
+ "service_name": "AgentHub Services",
79
+ "accepts_payment": ["bitcoin_lightning"],
80
+ "services": [
81
+ {
82
+ "id": "web_extraction",
83
+ "description": "Extract structured data from any URL",
84
+ "price_btc": 0.00001,
85
+ "response_time_ms": 500,
86
+ "success_rate": 0.999
87
+ }
88
+ ],
89
+ "api_endpoint": "https://yourdomain.com/api/v1"
90
+ }
91
+ ```
92
+
93
+ ---
94
+
95
+ ## Budget Breakdown ($500)
96
+
97
+ | Item | Cost | Notes |
98
+ |------|------|-------|
99
+ | Domain (1 year) | $12 | .com domain |
100
+ | Hosting (3 months) | $45 | Railway/Render starter |
101
+ | BTCPay Server (hosted) | $0 | Use LunaNode ($3.50/mo starts month 4) |
102
+ | Initial BTC for testing | $50 | Lightning channel liquidity |
103
+ | API credits (external) | $100 | For aggregator service |
104
+ | SSL Certificate | $0 | Free via Let's Encrypt |
105
+ | Development tools | $0 | All open source |
106
+ | **Marketing budget** | $293 | Listings, initial ads |
107
+ | **Total** | $500 | |
108
+
109
+ ---
110
+
111
+ ## Implementation Roadmap
112
+
113
+ ### Week 1: Foundation
114
+ - [ ] Register domain
115
+ - [ ] Set up hosting account
116
+ - [ ] Deploy BTCPay Server
117
+ - [ ] Create Lightning wallet
118
+
119
+ ### Week 2: Service 1 (Web Extraction)
120
+ - [ ] Build extraction API
121
+ - [ ] Integrate payment verification
122
+ - [ ] Test with sample AI agent requests
123
+ - [ ] Deploy to production
124
+
125
+ ### Week 3: Service 2 & 3
126
+ - [ ] Build timestamping service
127
+ - [ ] Build API aggregator
128
+ - [ ] Integration testing
129
+ - [ ] Load testing
130
+
131
+ ### Week 4: Marketing Launch
132
+ - [ ] Create OpenAPI spec
133
+ - [ ] List on AI agent directories
134
+ - [ ] Set up monitoring
135
+ - [ ] Launch MCP server
136
+
137
+ ---
138
+
139
+ ## Revenue Projections (Conservative)
140
+
141
+ ### Month 1
142
+ - 10 AI agents × 100 requests/day × $0.002 = $20/day = **$600/month**
143
+
144
+ ### Month 3
145
+ - 50 AI agents × 200 requests/day × $0.002 = $200/day = **$6,000/month**
146
+
147
+ ### Month 6
148
+ - 200 AI agents × 300 requests/day × $0.002 = $1,200/day = **$36,000/month**
149
+
150
+ *Assumes 50% margin after API costs and hosting*
151
+
152
+ ---
153
+
154
+ ## Competitive Advantages
155
+
156
+ 1. **Bitcoin-native:** No credit cards, no chargebacks, instant settlement
157
+ 2. **AI-optimized:** Service descriptions designed for AI discovery
158
+ 3. **Micropayments:** Pay per use, no subscriptions (AI agents prefer this)
159
+ 4. **Reliability:** Automated failover and redundancy
160
+ 5. **Speed:** Lightning Network = sub-second payment confirmation
161
+
162
+ ---
163
+
164
+ ## Risk Mitigation
165
+
166
+ **Risk:** Low initial traffic
167
+ **Mitigation:** Offer 100 free API calls per agent, focus on quality
168
+
169
+ **Risk:** Bitcoin price volatility
170
+ **Mitigation:** Convert to stablecoins immediately via auto-exchange
171
+
172
+ **Risk:** Service downtime
173
+ **Mitigation:** Multi-region deployment, health checks, auto-restart
174
+
175
+ **Risk:** Fraudulent usage
176
+ **Mitigation:** Prepayment required, rate limiting, IP reputation
177
+
178
+ ---
179
+
180
+ ## Success Metrics
181
+
182
+ - **Week 1:** System operational, first test transaction
183
+ - **Month 1:** 5+ paying AI agents
184
+ - **Month 2:** Break even on hosting costs
185
+ - **Month 3:** $1,000+ monthly revenue
186
+ - **Month 6:** Fully automated, passive income stream
187
+
188
+ ---
189
+
190
+ ## Next Steps
191
+
192
+ 1. Review the technical implementation code
193
+ 2. Choose domain name
194
+ 3. Set up accounts (hosting, BTCPay)
195
+ 4. Deploy code (I'll guide you step-by-step)
196
+ 5. Test with simulated AI agent
197
+ 6. Launch marketing
198
+ 7. Monitor and scale
199
+
200
+ This business can run 24/7 with minimal maintenance once deployed. The key is building services AI agents genuinely need and making discovery frictionless.
@@ -0,0 +1,14 @@
1
+ {
2
+ "mcpServers": {
3
+ "ugarapi": {
4
+ "command": "npx",
5
+ "args": [
6
+ "-y",
7
+ "ugarapi-mcp-server"
8
+ ],
9
+ "env": {
10
+ "UGARAPI_BASE_URL": "https://ugarapi.com"
11
+ }
12
+ }
13
+ }
14
+ }