# @moltflow/mcp-server

> MCP server for MoltFlow WhatsApp Automation API -- use with Claude Desktop, Claude.ai, and Claude Code.

Connect your AI assistant to the MoltFlow WhatsApp Automation API for session management, messaging, lead tracking, bulk outreach, campaign analytics, and more. The server exposes 25 MCP tools across 7 domains.

## Quick Start

### Claude Desktop

**Option A: Via npx (no install needed)**

Add to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "moltflow": {
      "command": "npx",
      "args": ["-y", "@moltflow/mcp-server"],
      "env": {
        "MOLTFLOW_API_KEY": "your-api-key-here"
      }
    }
  }
}
```

**Config file location:**
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
- Linux: `~/.config/Claude/claude_desktop_config.json`

**Option B: Global install**

```bash
npm install -g @moltflow/mcp-server
```

Then use `"command": "moltflow-mcp-server"` instead of the npx approach:

```json
{
  "mcpServers": {
    "moltflow": {
      "command": "moltflow-mcp-server",
      "env": {
        "MOLTFLOW_API_KEY": "mf_your_api_key_here"
      }
    }
  }
}
```

Restart Claude Desktop after saving. You should see a hammer icon in the chat input indicating MCP tools are loaded.

### Claude Code (via Plugin)

Use the MoltFlow plugin directory for guided skills and MCP tools:

```bash
claude --plugin-dir ./moltflow-plugin
```

The plugin provides 5 guided skills (`/moltflow:send-message`, `/moltflow:list-sessions`, `/moltflow:check-leads`, `/moltflow:bulk-send`, `/moltflow:help`) plus all 25 MCP tools.

Set `MOLTFLOW_API_KEY` in your environment before launching.

### Claude.ai Web (Remote MCP Gateway)

Configure in Claude.ai under Settings > Integrations > MCP Servers:

- **URL:** `https://apiv2.waiflow.app/mcp`
- **Auth header:** `X-API-Key`
- **Value:** Your MoltFlow API key

No local installation required -- MoltFlow hosts the remote MCP gateway.

### Self-Hosted HTTP Gateway

Run the MCP server in HTTP mode for custom deployments:

```bash
TRANSPORT=http MOLTFLOW_API_KEY=mf_xxxxx PORT=3000 npx @moltflow/mcp-server
```

## Prerequisites

- **Node.js 18+** (for npx or local install)
- **MoltFlow API key** -- create one at [https://molt.waiflow.app/settings/api-keys](https://molt.waiflow.app/settings/api-keys)

## Available Tools

### Sessions (5 tools)

| Tool | Description | Type |
|------|-------------|------|
| `moltflow_list_sessions` | List all WhatsApp sessions with connection status | Read |
| `moltflow_get_session` | Get detailed info for a specific session | Read |
| `moltflow_create_session` | Create a new WhatsApp session (stopped state) | Write |
| `moltflow_start_session` | Start a session and initialize the WAHA engine | Write |
| `moltflow_get_qr_code` | Get QR code for linking a phone number | Read |

### Messages (3 tools)

| Tool | Description | Type |
|------|-------------|------|
| `moltflow_send_message` | Send a text message via WhatsApp | Write |
| `moltflow_list_chats` | List all chats for a session | Read |
| `moltflow_get_chat_messages` | Get message history for a specific chat | Read |

### Groups (6 tools)

| Tool | Description | Type |
|------|-------------|------|
| `moltflow_list_monitored_groups` | List groups being monitored for leads | Read |
| `moltflow_list_available_groups` | List WhatsApp groups available for monitoring | Read |
| `moltflow_add_monitored_group` | Add a group to lead monitoring | Write |
| `moltflow_list_custom_groups` | List custom contact groups for bulk messaging | Read |
| `moltflow_create_custom_group` | Create a new custom contact group | Write |
| `moltflow_add_custom_group_members` | Add contacts to a custom group | Write |

### Leads (2 tools)

| Tool | Description | Type |
|------|-------------|------|
| `moltflow_list_leads` | List leads detected from monitored groups | Read |
| `moltflow_update_lead_status` | Update lead pipeline status | Write |

### Outreach (4 tools)

| Tool | Description | Type |
|------|-------------|------|
| `moltflow_create_bulk_send` | Create a bulk messaging campaign | Write |
| `moltflow_list_bulk_sends` | List bulk send campaigns with status | Read |
| `moltflow_get_bulk_send_status` | Get detailed progress of a bulk send | Read |
| `moltflow_create_schedule` | Create a scheduled message (one-time or recurring) | Write |

### Usage (2 tools)

| Tool | Description | Type |
|------|-------------|------|
| `moltflow_get_current_usage` | Get current billing period usage stats | Read |
| `moltflow_get_plan_limits` | Get plan feature limits and capabilities | Read |

### Analytics (3 tools)

| Tool | Description | Type |
|------|-------------|------|
| `moltflow_get_campaign_analytics` | Get campaign engagement funnel (sent/delivered/read/replied/reacted/ignored) | Read |
| `moltflow_get_contact_engagement` | Get contact engagement leaderboard sorted by score | Read |
| `moltflow_get_contact_history` | Get per-contact engagement history timeline | Read |

> Analytics tools require Pro plan or higher. Free/Starter plans receive a 402 response with an upgrade prompt.

## Configuration

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `MOLTFLOW_API_KEY` | Yes | -- | Your MoltFlow API key |
| `MOLTFLOW_API_URL` | No | `https://apiv2.waiflow.app/api/v2` | Custom API base URL |
| `TRANSPORT` | No | `stdio` | Transport mode: `stdio` or `http` |
| `PORT` | No | `3000` | HTTP server port (http mode only) |
| `HOST` | No | `127.0.0.1` | Bind address (http mode only) |
| `MCP_RATE_LIMIT` | No | `120` | Requests per minute per API key (http mode) |
| `ALLOWED_ORIGINS` | No | -- | Comma-separated additional CORS origins (http mode) |
| `NODE_ENV` | No | -- | Set to `production` to enforce HTTPS (http mode) |

## Response Formats

All tools accept a `response_format` parameter:

- **`markdown`** (default) -- Human-readable formatted output with headers, tables, and lists. Best for conversational use in Claude.
- **`json`** -- Raw JSON response from the MoltFlow API. Best for programmatic processing or when you need exact field values.

Example:

```
"List my sessions in JSON format"
-> Calls moltflow_list_sessions with response_format: "json"
```

## Pagination

List tools support `limit` and `offset` parameters for paginating through results:

- `limit` -- Maximum items to return (1-100, default varies by tool)
- `offset` -- Number of items to skip (default: 0)

When more results are available, the response includes a "Next" indicator with the offset for the next page.

## API Scopes

Each tool requires specific API key scopes. Create a scoped key at [https://molt.waiflow.app/settings/api-keys](https://molt.waiflow.app/settings/api-keys).

| Scope | Tools |
|-------|-------|
| `sessions:read` | list_sessions, get_session, get_qr_code |
| `sessions:manage` | create_session, start_session |
| `messages:read` | list_chats, get_chat_messages, list_bulk_sends, get_bulk_send_status |
| `messages:send` | send_message |
| `messages:write` | create_bulk_send, create_schedule |
| `groups:read` | list_monitored_groups, list_available_groups |
| `groups:manage` | add_monitored_group |
| `custom-groups:read` | list_custom_groups |
| `custom-groups:manage` | create_custom_group, add_custom_group_members |
| `leads:read` | list_leads |
| `leads:write` | update_lead_status |
| `usage:read` | get_current_usage, get_plan_limits |
| `analytics:read` | get_campaign_analytics, get_contact_engagement, get_contact_history |

API keys require explicit scopes — select only the permissions your integration needs. Use the table above to match tools to scopes.

## Error Handling

The server returns structured error messages with actionable guidance:

| HTTP Code | Error | Description |
|-----------|-------|-------------|
| 401 | `UNAUTHORIZED` | Invalid or missing API key. Check `MOLTFLOW_API_KEY` is set correctly. |
| 403 | `FORBIDDEN` | API key lacks required scope, or plan limit exceeded. |
| 404 | `NOT_FOUND` | Resource not found. Verify the ID is correct. |
| 409 | `CONFLICT` | Resource state conflict (e.g., session already running, session not in QR state). |
| 422 | `VALIDATION_ERROR` | Invalid input. Check required fields and value formats. |
| 429 | `RATE_LIMITED` | Too many requests. Wait and retry. Free: 10/min, Starter: 20/min, Pro: 40/min, Business: 60/min. |
| 500 | `SERVER_ERROR` | Internal error. Retry after a few seconds. |

All errors include a human-readable message. In markdown mode, errors render as formatted text with suggestions. In json mode, errors include the raw error object.

## HTTP Gateway Mode

The HTTP gateway enables remote MCP clients (like Claude.ai web) to connect over HTTP.

### Starting the Gateway

```bash
TRANSPORT=http \
MOLTFLOW_API_KEY=mf_xxxxx \
PORT=3000 \
HOST=127.0.0.1 \
npx @moltflow/mcp-server
```

### Endpoints

- `POST /mcp` -- MCP protocol endpoint. Requires `X-API-Key` header.
- `GET /health` -- Health check. Returns server status, version, and transport mode.

### Security

- **CORS whitelist** -- Only `claude.ai`, `www.claude.ai`, and `api.claude.ai` by default. Add custom origins via `ALLOWED_ORIGINS`.
- **Rate limiting** -- 120 requests/minute per API key (configurable via `MCP_RATE_LIMIT`). Returns `429` with `Retry-After` header when exceeded.
- **Localhost binding** -- Binds to `127.0.0.1` by default. Set `HOST=0.0.0.0` to allow network access (use behind a reverse proxy with HTTPS).
- **HTTPS enforcement** -- In `NODE_ENV=production`, rejects plain HTTP requests.
- **Stateless transport** -- Each request creates a fresh transport instance. No session state is shared between requests.

### Production Deployment

For production, run behind a reverse proxy (Nginx, Caddy, Traefik) for HTTPS termination:

```nginx
location /mcp {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header Host $host;
}
```

```bash
NODE_ENV=production \
HOST=127.0.0.1 \
PORT=3000 \
TRANSPORT=http \
MOLTFLOW_API_KEY=mf_xxxxx \
npx @moltflow/mcp-server
```

## Development

```bash
git clone https://github.com/moltflow/moltflow.git
cd moltflow/mcp-server
npm install
npm run build       # TypeScript compilation
npm run typecheck   # Type checking without emit
```

### Project Structure

```
mcp-server/
  src/
    index.ts            # Entry point (stdio/http transport selection)
    gateway.ts          # Express HTTP gateway with security middleware
    types.ts            # API response type definitions
    schemas/            # Zod input validation schemas
    tools/
      index.ts          # Tool registration barrel (25 tools)
      sessions.ts       # Session management tools (5)
      messages.ts       # Messaging tools (3)
      groups.ts         # Group monitoring and custom groups (6)
      leads.ts          # Lead management tools (2)
      outreach.ts       # Bulk send and scheduling tools (4)
      usage.ts          # Usage and plan limit tools (2)
      analytics.ts      # Campaign analytics and engagement tools (3)
    services/
      api-client.ts     # HTTP client for MoltFlow API
      error-handler.ts  # Error formatting and user-friendly messages
      formatter.ts      # Markdown and list output formatting
    middleware/
      cors.ts           # CORS whitelist for Claude.ai
      rate-limit.ts     # In-memory rate limiting
  dist/                 # Compiled JavaScript output
  package.json
  tsconfig.json
```

## Troubleshooting

### "MOLTFLOW_API_KEY environment variable is not set"

The server starts but all tool calls will fail. Set the key:

```bash
# macOS/Linux
export MOLTFLOW_API_KEY=mf_your_key_here

# Windows (PowerShell)
$env:MOLTFLOW_API_KEY = "mf_your_key_here"
```

### Tools not appearing in Claude Desktop

1. Verify `claude_desktop_config.json` is valid JSON (no trailing commas).
2. Confirm the config file is in the correct location for your OS.
3. Restart Claude Desktop completely (not just close the chat).
4. Check Claude Desktop logs for MCP server errors.

### "401 Unauthorized" on every tool call

Your API key is invalid or expired. Generate a new one at [https://molt.waiflow.app/settings/api-keys](https://molt.waiflow.app/settings/api-keys).

### "403 Forbidden -- insufficient scope"

Your API key does not have the required scope for this tool. Create a new key with the required scopes listed in the table above.

### "429 Rate Limited"

You have exceeded the rate limit for your plan. Wait for the `Retry-After` period, or upgrade your plan for a higher limit.

### Session stuck in "starting" state

The WAHA engine may need time to initialize. Wait 10-15 seconds, then call `moltflow_get_session` to check the current status. If it stays in "starting" for more than 30 seconds, try stopping and restarting the session from the MoltFlow dashboard.

### QR code expired

QR codes expire after approximately 60 seconds. Call `moltflow_get_qr_code` again to get a fresh code.

### HTTP gateway not responding

1. Verify `TRANSPORT=http` is set.
2. Check that the port is not in use: `lsof -i :3000` (macOS/Linux) or `netstat -ano | findstr 3000` (Windows).
3. If binding to `0.0.0.0`, ensure your firewall allows the port.

## Links

- **Dashboard:** [https://molt.waiflow.app](https://molt.waiflow.app)
- **API Base URL:** `https://apiv2.waiflow.app/api/v2`
- **API Keys:** [https://molt.waiflow.app/settings/api-keys](https://molt.waiflow.app/settings/api-keys)
- **Claude Code Plugin:** [moltflow-plugin/](../moltflow-plugin/)
- **ClawHub Skill:** [@moltflow/skills on npm](https://www.npmjs.com/package/@moltflow/skills)
- **OpenAI Actions:** [@moltflow/openai-actions on npm](https://www.npmjs.com/package/@moltflow/openai-actions)

## License

MIT
