-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathapproval_server.py
More file actions
364 lines (304 loc) · 12.9 KB
/
approval_server.py
File metadata and controls
364 lines (304 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#!/usr/bin/env python3
"""
Local MCP approval server that sends WhatsApp messages via Twilio
"""
import os
import json
import uuid
import asyncio
from datetime import datetime, timedelta
from typing import Optional
from dotenv import load_dotenv
from fastmcp import FastMCP
from fastapi import Request
from fastapi.responses import JSONResponse
from sqlmodel import Field, SQLModel, Session, create_engine, select
from twilio.rest import Client
# Load environment variables
load_dotenv()
# Initialize MCP server
mcp = FastMCP("approval-server")
# Database models
class ApprovalRequest(SQLModel, table=True):
id: str = Field(primary_key=True)
request_id: str = Field(unique=True, index=True)
description: str
requester: str
phone_number: str
status: str = Field(default="pending")
created_at: datetime = Field(default_factory=datetime.utcnow)
responded_at: Optional[datetime] = None
response: Optional[str] = None
expires_at: datetime
# Database setup
DATABASE_URL = "sqlite:///approvals.db"
engine = create_engine(DATABASE_URL)
SQLModel.metadata.create_all(engine)
# Server configuration
SERVER_PORT = int(os.environ.get("SERVER_PORT", 8000))
# Twilio configuration
TWILIO_ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN")
TWILIO_WHATSAPP_FROM = os.environ.get("TWILIO_WHATSAPP_FROM", "whatsapp:+14155238886")
TWILIO_CONTENT_SID = os.environ.get("TWILIO_CONTENT_SID")
APPROVAL_PHONE = os.environ.get("APPROVAL_PHONE")
twilio_client = None
if TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN:
twilio_client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
@mcp.tool()
async def permissions__approve(tool_name: str, input: dict, reason: str = "") -> dict:
"""Request approval via WhatsApp before executing a tool."""
# Format the request description in a more readable way
if tool_name == "Bash" and isinstance(input, dict):
command = input.get("command", "")
description = input.get("description", "")
request = f"Execute command: `{command}`\n*Reason:* {description}"
else:
request = f"*Tool:* {tool_name}"
if input:
# Format parameters more nicely
params = []
for key, value in input.items():
if isinstance(value, str) and len(value) > 50:
value = value[:50] + "..."
params.append(f" • {key}: {value}")
if params:
request += "\n" + "\n".join(params)
if reason:
request = f"*Reason:* {reason}\n\n{request}"
print(f"🤖 Claude requesting approval: {request}")
if not twilio_client:
print("❌ Twilio not configured")
return {"error": "Twilio not configured"}
if not APPROVAL_PHONE:
print("❌ APPROVAL_PHONE not configured")
return {"error": "APPROVAL_PHONE not configured in environment variables"}
request_id = str(uuid.uuid4())
short_id = request_id[:8]
expires_at = datetime.utcnow() + timedelta(minutes=5)
# Create approval request
approval = ApprovalRequest(
id=short_id,
request_id=request_id,
description=request,
requester="Claude",
phone_number=APPROVAL_PHONE,
expires_at=expires_at
)
# Store in database
with Session(engine) as session:
session.add(approval)
session.commit()
# Send WhatsApp message
to_number = f"whatsapp:{APPROVAL_PHONE}" if not APPROVAL_PHONE.startswith("whatsapp:") else APPROVAL_PHONE
try:
if TWILIO_CONTENT_SID:
# Use content template (quick-reply buttons)
message = twilio_client.messages.create(
from_=TWILIO_WHATSAPP_FROM,
to=to_number,
content_sid=TWILIO_CONTENT_SID,
content_variables=json.dumps({
"1": request,
"2": short_id
})
)
else:
# Fallback to regular message with cleaner formatting
message_body = f"""🔔 *Approval Request*
{request}
*Request ID:* `{short_id}`
Reply:
• *APPROVE {short_id}*
• *DENY {short_id}*
⏱️ Expires in 5 minutes"""
message = twilio_client.messages.create(
body=message_body.strip(),
from_=TWILIO_WHATSAPP_FROM,
to=to_number
)
print(f"✅ Sent approval request {short_id} to {APPROVAL_PHONE}")
# Wait for approval (poll database)
max_wait_time = 300 # 5 minutes
check_interval = 2 # Check every 2 seconds
start_time = datetime.utcnow()
while (datetime.utcnow() - start_time).total_seconds() < max_wait_time:
with Session(engine) as session:
statement = select(ApprovalRequest).where(ApprovalRequest.id == short_id)
current_approval = session.exec(statement).first()
if current_approval and current_approval.status != "pending":
print(f"📱 Received response: {current_approval.status}")
if current_approval.status == "approved":
return {"approved": True}
else:
return {"denied": True, "message": "Request was denied"}
# Check if expired
if datetime.utcnow() > expires_at:
print(f"⏰ Request {short_id} expired")
return {"error": "Request expired"}
await asyncio.sleep(check_interval)
print(f"⏰ Request {short_id} timed out")
return {"error": "Request timed out"}
except Exception as e:
# Clean up database entry on failure
with Session(engine) as session:
approval_to_delete = session.get(ApprovalRequest, short_id)
if approval_to_delete:
session.delete(approval_to_delete)
session.commit()
return {"error": f"Failed to send WhatsApp message: {str(e)}"}
@mcp.custom_route("/twilio-webhook", methods=["GET"])
async def webhook_test():
"""Test endpoint to verify webhook URL is reachable"""
print("🔥 WEBHOOK GET TEST CALLED!")
return {"status": "webhook endpoint reachable", "message": "Configure Twilio to POST here"}
@mcp.custom_route("/twilio-webhook", methods=["POST"])
async def twilio_webhook(request: Request):
"""Handle incoming WhatsApp messages"""
print("🔥 WEBHOOK CALLED!")
# Parse form data
form_data = await request.form()
# Extract fields
Body = form_data.get("Body")
From = form_data.get("From")
To = form_data.get("To")
ListId = form_data.get("ListId")
ListTitle = form_data.get("ListTitle")
ButtonText = form_data.get("ButtonText")
ButtonPayload = form_data.get("ButtonPayload")
MessageStatus = form_data.get("MessageStatus")
MessageSid = form_data.get("MessageSid")
print(f"📱 MessageStatus: {MessageStatus}")
print(f"📱 From: {From}, To: {To}")
print(f"📱 Body: {Body}")
print(f"🔍 ListId: {ListId}")
print(f"🔍 ButtonPayload: {ButtonPayload}")
print(f"🔍 ButtonText: {ButtonText}")
# Debug: Print all form data
print("📋 All form data:")
for key, value in form_data.items():
print(f" {key}: {value}")
# If this is just a status callback (not an actual message), ignore it
if MessageStatus and not Body:
print("📊 Status callback received, ignoring")
return JSONResponse({"status": "ok", "message": "Status callback received"})
# Ensure we have From field (Body is optional for button responses)
if not From:
print("❌ Missing From field")
return JSONResponse({"status": "error", "message": "Missing From field"})
# Handle button responses (quick-reply)
if ButtonPayload:
parts = ButtonPayload.split("_")
if len(parts) == 2:
action, short_id = parts
if action in ["approve", "deny"]:
response = "approved" if action == "approve" else "denied"
response_text = ButtonText or f"{action}_{short_id}"
else:
return JSONResponse({"status": "ignored", "reason": "Invalid button payload"})
else:
return JSONResponse({"status": "ignored", "reason": "Invalid button payload format"})
# Handle list-picker responses (fallback)
elif ListId:
parts = ListId.split(":")
if len(parts) == 2:
action, short_id = parts
if action in ["approve", "deny"]:
response = "approved" if action == "approve" else "denied"
response_text = f"{action}:{short_id}"
else:
return JSONResponse({"status": "ignored", "reason": "Invalid list selection"})
else:
return JSONResponse({"status": "ignored", "reason": "Invalid list ID format"})
else:
# Handle text responses (fallback)
if not Body:
print("❌ No body content")
return JSONResponse({"status": "ignored", "reason": "No body content"})
body = Body.strip().upper()
# Parse response
if body.startswith("APPROVE "):
short_id = body.replace("APPROVE ", "").strip()
response = "approved"
response_text = body
elif body.startswith("DENY "):
short_id = body.replace("DENY ", "").strip()
response = "denied"
response_text = body
else:
print(f"❌ Invalid format: {body}")
return JSONResponse({"status": "ignored", "reason": "Invalid format"})
# Update database
with Session(engine) as session:
# Extract phone number from From field (remove "whatsapp:" prefix if present)
from_phone = From.replace("whatsapp:", "") if From and From.startswith("whatsapp:") else From
# Check if request exists and is still pending
statement = select(ApprovalRequest).where(
ApprovalRequest.id == short_id,
ApprovalRequest.phone_number == from_phone
)
approval = session.exec(statement).first()
if not approval:
print(f"❌ Request {short_id} not found")
return JSONResponse({"status": "error", "reason": "Request not found"})
if approval.status != "pending":
print(f"❌ Request {short_id} already processed")
return JSONResponse({"status": "error", "reason": "Request already processed"})
if datetime.utcnow() > approval.expires_at:
print(f"❌ Request {short_id} expired")
return JSONResponse({"status": "error", "reason": "Request expired"})
# Update the request
approval.status = response
approval.response = response_text
approval.responded_at = datetime.utcnow()
session.add(approval)
session.commit()
session.refresh(approval)
print(f"✅ Request {short_id} {response}")
request_id = approval.request_id
# Send confirmation message
if twilio_client:
if response == "approved":
confirmation = f"✅ Request {short_id} has been approved."
else:
confirmation = f"❌ Request {short_id} has been denied."
twilio_client.messages.create(
body=confirmation,
from_=To,
to=From
)
return JSONResponse({
"status": "success",
"request_id": request_id,
"response": response
})
if __name__ == "__main__":
print("🚀 Starting approval MCP server...")
print(f"📱 Approval messages will be sent to: {APPROVAL_PHONE or 'NOT CONFIGURED'}")
print(f"🔧 Twilio configured: {twilio_client is not None}")
if not APPROVAL_PHONE:
print("⚠️ WARNING: APPROVAL_PHONE not set in environment variables")
print()
print("🌐 Server endpoints:")
print(f" • MCP: http://localhost:{SERVER_PORT} (FastMCP HTTP server)")
print(" • Webhook: POST /twilio-webhook (for Twilio)")
print(" • Test: GET /twilio-webhook (browser test)")
print()
print("📡 Expose webhook with ngrok:")
print(f" ngrok http {SERVER_PORT}")
print()
print("⚙️ Configure Twilio webhook:")
print(" Method: POST")
print(" URL: https://your-ngrok-url.ngrok.io/twilio-webhook")
print()
print("💡 To test:")
print("1. Configure Claude to connect to this server")
print("2. Ask Claude to request approval for something")
print("3. Respond to the WhatsApp message")
print("\n🛑 Press Ctrl+C to stop")
# FastMCP runs with SSE transport
try:
mcp.run(transport="sse", host="127.0.0.1", port=SERVER_PORT)
except Exception as e:
print(f"❌ Server error: {e}")
sys.exit(1)