Files
conversation-history/product-incubation/hermes-mcp-whatsapp-implementation.md

197 lines
7.4 KiB
Markdown

# hermes-mcp WhatsApp Implementation
**Date:** 2026-05-01
**Author:** opencode AI (reviewed by Garfield)
**Status:** Phase 1 — outbound send-only prototype; uncommitted, pending cleanup
---
## What was built
WhatsApp Business Cloud API integration added to hermes-mcp, following the same multi-account pattern as the existing email tools. Uses the Meta Graph API (`graph.facebook.com/v18.0`).
---
## Files changed
### New file: `src/clients/whatsapp.ts`
WhatsApp API client. Reads credentials from env vars per account (`WHATSAPP_{ACCOUNT}_*`). Exports:
- `sendMessage` — sends a plain text message via `POST /{phoneId}/messages`
- `sendTemplate` — sends an approved template with optional components
- `listTemplates` — `GET /{businessAccountId}/message_templates`
All calls use `AbortSignal.timeout(10000)` and throw on non-2xx responses.
### New file: `opencode.json`
opencode MCP connection config (project-level). Points to `https://hermes.fetcherpay.com/mcp` with `x-api-key` auth.
> ⚠️ **Credential risk — do not commit with a live API key.** If this file contains a real `x-api-key`, strip it before committing or add `opencode.json` to `.gitignore` and treat it as local-only.
### Modified: `src/tools.ts`
Added MCP tools and their `handleToolCall` cases:
| Tool name | Required params | Notes |
|-----------|----------------|-------|
| `whatsapp_send_message` | `to`, `message` | Only works inside the 24-hour customer-service window. Outside the window, use `send_template`. |
| `whatsapp_send_template` | `to`, `template_name` | Requires a pre-approved Meta template. |
| `whatsapp_list_templates` | _(none)_ | Lists templates for the business account. |
All tools accept an optional `account` param (defaults to `"default"`).
Also exported `WhatsAppToolArgs` type for use in the client module.
> ⚠️ `whatsapp_get_message_status` was drafted but **is non-functional** — the Meta Cloud API does not support polling message status via `GET /{phoneId}/messages/{id}`. Status updates are push-only via webhooks. This tool/endpoint must be removed or disabled until webhook-backed state storage exists.
### Modified: `src/index.ts`
Added REST API endpoints (all behind `requireAuth`):
| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/api/whatsapp/send` | Send a text message |
| `POST` | `/api/whatsapp/template` | Send a template message |
| `GET` | `/api/whatsapp/templates` | List approved templates |
> ⚠️ A `GET /api/whatsapp/message-status` endpoint was drafted but should **not be exposed** until it has a real data source (webhook ingestion + persisted delivery state).
### Modified: `src/manifest.ts`
WhatsApp tools added to the manifest under category `whatsapp` with full input schemas and examples.
### Modified: `.env.example`
Added three new env vars for the default account:
```
WHATSAPP_DEFAULT_PHONE_NUMBER_ID=your-phone-number-id
WHATSAPP_DEFAULT_ACCESS_TOKEN=your-permanent-access-token
WHATSAPP_DEFAULT_BUSINESS_ACCOUNT_ID=your-business-account-id
```
For additional accounts, duplicate with `WHATSAPP_{ACCOUNT}_*` (e.g., `WHATSAPP_BUSINESS_*`).
---
## Credential setup
Get values from [Meta Business Settings → WhatsApp Business Accounts](https://business.facebook.com/settings/whatsapp-business-accounts):
1. **Phone Number ID** — from the app's WhatsApp product config
2. **Access Token** — use a permanent System User token (not a temporary user token)
3. **Business Account ID** — the WABA ID, needed only for `list_templates`
---
## Product constraints
### 24-hour customer-service window
`whatsapp_send_message` (free-form text) only succeeds when the recipient has sent a message to your number within the last 24 hours. Outside that window, Meta rejects free-form messages and **only approved templates** can be sent.
**User implication:** If a conversation is cold, you must use `send_template` with a pre-approved template name.
### No inbound / status reads (yet)
This phase is **outbound-only**. There is no webhook handler, so:
- No incoming message reception
- No delivery or read-receipt tracking
- No `get_message_status` support (the Meta API simply doesn't allow polling for this)
---
## Blockers before commit
- [ ] Remove or disable `whatsapp_get_message_status` tool and REST endpoint
- [ ] Verify `opencode.json` contains no live secrets; `.gitignore` it if needed
- [ ] Add tests:
- [ ] Env var / account resolution
- [ ] Tool dispatch argument validation
- [ ] REST endpoint validation and error paths
- [ ] One live smoke-test plan for Meta API calls
---
## Next steps (post-cleanup)
- [ ] Add `/api/whatsapp/webhook` for inbound messages and delivery events
- [ ] Persist inbound/status events so future read/status tools have a real source of truth
- [ ] Re-introduce `get_message_status` once webhook-backed state exists
- [ ] Add `read_messages` tool to surface recent inbound messages (depends on webhook)
- [ ] Document the 24-hour window / template-only constraint in user-facing docs
- [ ] Store `WHATSAPP_DEFAULT_*` values in Kubernetes Secrets
- [ ] Build and redeploy to `hermes.fetcherpay.com`
## WhatsApp Web Workaround Update
# WhatsApp Web Integration Update
**Date:** 2026-05-01
**Status:** Implementation Complete - Ready for Deployment
**Author:** OpenCode AI
---
## What was added
### New file: `src/clients/whatsapp-web.ts`
Playwright-based WhatsApp Web automation that works without a browser GUI on the server:
1. **QR Code Server** - Extracts QR code from WhatsApp Web and serves it via HTTP
- URL: `http://your-server:3000/whatsapp-web/qr`
- User visits this URL to scan QR with their phone
- Works remotely without GUI access to server
2. **Session Persistence** - Saves cookies to `/tmp/whatsapp-web-session/session.json`
- After first scan, subsequent uses don't need QR scan
- Session persists across server restarts
3. **Headless Operation** - Runs in headless mode on server
- No X server or display needed
- QR served via HTTP instead of showing browser window
### Modified files:
- `src/tools.ts` - Added `whatsapp_web_send_message` tool
- `src/index.ts` - Added `POST /api/whatsapp-web/send` endpoint
- `.env.example` - Added `WHATSAPP_WEB_HEADLESS` and `WHATSAPP_WEB_SESSION_DIR`
---
## How to deploy and test
### 1. Deploy to production (hermes.fetcherpay.com)
```bash
# Build and redeploy
npm run build
kubectl set image deployment/hermes-mcp hermes-mcp=your-registry/hermes-mcp:latest
```
### 2. First time: Scan QR code
Visit: `http://hermes.fetcherpay.com:3000/whatsapp-web/qr`
- Opens page with QR code
- Scan with WhatsApp: Settings → Linked Devices → Link a Device
- Session saves automatically
### 3. Test sending message
```bash
curl -X POST "https://hermes.fetcherpay.com/api/whatsapp-web/send" \n -H "x-api-key: 114521f3f9e6858480d6269446a446ef" \n -H "Content-Type: application/json" \n -d '{"to": "+19548716341", "message": "Test from Hermes"}'
```
---
## Server Requirements
For WhatsApp Web to work on the production server:
- **Playwright dependencies** must be installed in the Docker container
- Chromium browser (installed automatically by Playwright)
- No X server needed (runs headless)
If the server doesn't have Playwright dependencies, the container will need:
```dockerfile
RUN npx playwright install chromium
RUN npx playwright install-deps chromium
```
---
## Warning
WhatsApp Web automation may violate WhatsApp ToS. Use sparingly to avoid account ban.
---
**Files:** `src/clients/whatsapp-web.ts`, modified: `src/tools.ts`, `src/index.ts`, `.env.example`