Skip to main content
Glama
README.md
# mcp-baileys

**WhatsApp MCP server built on [Baileys](https://github.com/WhiskeySockets/Baileys), with an AI bridge daemon and an optional shared MCP hub.**

`mcp-baileys` lets AI agents (Claude, Gemini / Antigravity, or any [Model Context Protocol](https://modelcontextprotocol.io/) client) read, search and send WhatsApp messages across multiple linked accounts, with local SQLite persistence and a small web dashboard.

> Spanish quick start: see [GUIA_RAPIDA.md](./GUIA_RAPIDA.md).

---

## Features

- **Multi-account WhatsApp** via Baileys (WhatsApp Web multi-device protocol). Link accounts with a QR code or an 8-digit pairing code.
- **MCP server over stdio and SSE** exposing ~60 `whatsapp_*` tools (search, history, media, groups, sending, presence, scheduling, live progress cards, account management).
- **SQLite persistence** (`better-sqlite3`, WAL mode) with **FTS5 full-text search** over the stored history. Optional mirroring to MongoDB / PostgreSQL.
- **Voice notes**: audio transcription (Gemini) and text-to-speech replies as PTT voice notes (Edge TTS / Gemini / ElevenLabs).
- **Web UI** at `/` — account management, QR / pairing, chat history search, test sends, chat import, linked-group configuration.
- **Live voice UI** at `/live` — hands-free PWA voice client talking to the assistant in real time.
- **AI bridge daemon** (`bridge/`) — HTTP daemon (default port `4040`) that forwards WhatsApp conversations to an AI agent session (Antigravity / Gemini CLI) and streams answers back.
- **Shared MCP hub** (`mcp-hub/`, optional) — one process per machine exposing MCP servers over Streamable HTTP, with on-demand stdio backends, tool caching and an optional mesh of peer hubs for failover.
- **Anti-ban safety rails**: per-recipient rate limiting, natural typing presence before sending, no automatic cold 1:1 outreach.

## Architecture

```
 WhatsApp (linked devices)
          │  messages / audio / commands
          ▼
┌──────────────────────────────────────────┐
│ mcp-baileys server (port 3333)           │
│  • Baileys multi-account sockets         │
│  • SQLite (FTS5) history + media store   │
│  • Transcription / TTS                   │
│  • MCP stdio + SSE, REST API, Web UI     │
└───────────────────┬──────────────────────┘
                    │ POST /v1/chat (streaming)
                    ▼
┌──────────────────────────────────────────┐
│ AI bridge (bridge/, port 4040)           │
│  • Session detection / agent CLI shim    │
│  • Prompt injection + response streaming │
└───────────────────┬──────────────────────┘
                    ▼
        Antigravity / Gemini CLI agent
```

## Requirements

- Node.js **22+**
- pnpm (recommended, `corepack enable`) or npm
- Build toolchain for native modules if no prebuilt binary is available (`python3`, `make`, `g++`)
- Optional: a Gemini API key (transcription / TTS), an ElevenLabs API key (TTS)

## Install

```bash
git clone <your-fork-url> mcp-baileys
cd mcp-baileys
pnpm install        # or: npm install
cp .env.example .env
```

The `postinstall` hook runs `scripts/patch-baileys.js`, which applies a few robustness patches to the installed Baileys package (decryption fallbacks, LID group addressing). Make sure install scripts are not disabled.

## Build & run

```bash
npm run build       # compile TypeScript to dist/
npm start           # run the compiled server (dist/index.js)
npm run dev         # watch mode with tsx
npm test            # node:test suite
```

Open `http://localhost:3333`, then scan the QR code from **WhatsApp → Linked devices** (or request a pairing code from the UI).

The AI bridge runs as a separate process:

```bash
npm run bridge:start          # TypeScript bridge (bridge/src)
node bridge/headless-bridge.mjs   # headless bridge daemon
```

### PM2

```bash
npm run build
pm2 start ecosystem.config.cjs   # starts "mcp-baileys" and "ai-bridge"
```

### macOS LaunchAgent

```bash
npm run service:install     # installs com.mcp.baileys, logs in ~/Library/Logs/mcp-baileys
npm run service:uninstall
```

## MCP client configuration

**stdio (from source):**

```json
{
  "mcpServers": {
    "whatsapp": {
      "command": "node",
      "args": ["--import", "tsx", "src/mcp/stdio.ts"],
      "cwd": "/path/to/mcp-baileys"
    }
  }
}
```

**stdio (compiled):** use `"args": ["/path/to/mcp-baileys/dist/mcp/stdio.js"]` after `npm run build`.

**SSE:** point SSE-capable clients at `http://localhost:3333/sse` while the server is running.

## Docker

```bash
docker compose up -d --build
docker compose logs -f
```

Sessions are stored in the `./auth_info` volume and the database / media in `./data`. Values from `.env` are loaded when present. Expose port `3333` only on trusted networks.

## Configuration

All configuration is done through environment variables (see `.env.example`).

### Core

| Variable | Default | Description |
| --- | --- | --- |
| `PORT` | `3333` | HTTP port (Web UI, REST, SSE). |
| `HOST` | `0.0.0.0` | Bind address. Use `127.0.0.1` to keep it local. |
| `LOG_LEVEL` | `info` | Pino log level. |
| `AUTO_RECONNECT` | `true` | Reconnect sockets automatically. |
| `AUTH_DIR` | `./auth_info` | Baileys credentials (one subfolder per extra account). |
| `DATA_DIR` | `./data` | SQLite database and runtime data. |
| `MEDIA_DIR` | `./data/media` | Downloaded media. |
| `USE_PAIRING_CODE` | `false` | Link with a pairing code instead of QR. |
| `PHONE_NUMBER` | — | Number used for pairing (international format, digits only, e.g. `15552345678`). |
| `DEFAULT_ACCOUNT_LABEL` | — | Display name of the default account. |
| `AUTO_READ_ACCOUNTS` | — | Comma list of account ids whose incoming messages are marked as read. |

### AI / assistant

| Variable | Default | Description |
| --- | --- | --- |
| `GEMINI_API_KEY` | — | Gemini key for transcription / TTS / live voice. |
| `ELEVENLABS_API_KEY` | — | Optional ElevenLabs TTS. |
| `TTS_PROVIDER` | `gemini` | TTS engine. |
| `TTS_VOICE` | — | Voice id for the selected provider. |
| `ASSISTANT_NAME` | `Assistant` | Name the assistant answers to in groups. |
| `ASSISTANT_ALIASES` | — | Comma list of extra mention words that also trigger the assistant. |
| `ANTIGRAVITY_BRIDGE_URL` | `http://127.0.0.1:4040` | AI bridge base URL. |
| `ANTIGRAVITY_GROUP_JID` | — | Default group linked to the agent (e.g. `123456789012345678@g.us`). |
| `TRANSCRIPTION_GROUP_JID` | — | Group where transcriptions are posted. |
| `ANTIGRAVITY_CONVERSATION_ID` | — | Default agent conversation id. |
| `AUTO_START_ANTIGRAVITY` | `true` | Start the bridge integration on boot. |
| `ENABLE_AUTO_REACTIONS` | `false` | Automatic acknowledgement reactions on incoming messages. |

### Access control & security

| Variable | Default | Description |
| --- | --- | --- |
| `OWNER_PHONES` | — | Comma list of admin phone numbers allowed to run privileged commands. |
| `ALLOWED_PHONES` | — | Comma list of phone numbers allowed to talk to the assistant. |
| `BRAIN_API_TOKEN` | — | Token required for any non-loopback request (sent in the `Authorization` header or `X-Brain-Token`). |
| `GUARDED_ACCOUNTS` | — | Sessions whose outbound messages go through the outbound guard. |
| `ALERT_GROUP_JID` | — | Group for internal alerts (held groups, unanswered acks). |
| `LID_PN_MAPPINGS` | — | Optional fixed `<lid>:<phone>` pairs. |
| `ANTIGRAVITY_BRIDGE_TOKEN` | — | Shared secret between the server and the AI bridge. |
| `RATE_LIMIT_ENABLED` | `true` | Per-recipient outbound rate limiting. |
| `RATE_LIMIT_MAX_PER_MINUTE` | `10` | Max messages per recipient per window. |
| `RATE_LIMIT_WINDOW_MS` | `60000` | Rate limit window. |

### Shared MCP hub (`mcp-hub/`)

| Variable | Description |
| --- | --- |
| `MCP_HUB_ROLE` | Role / name of this node in the mesh. |
| `MCP_HUB_PEERS_JSON` | JSON array describing peer hubs (name, URL) for failover. |
| `VIDEO_GPU_PUBLIC_BASE` | Public base URL of the optional video GPU node. |
| `GPU_NODE_NAME` | Name of the peer that hosts GPU-only MCP servers. |

Generate tokens with `openssl rand -hex 32`. Never commit `.env`, `auth_info*/` or `data/`.

## Responsible use

This project uses the unofficial WhatsApp Web protocol. Automated use can violate the [WhatsApp Terms of Service](https://www.whatsapp.com/legal/terms-of-service) and lead to account restrictions. Use it for your own accounts and conversations where participants expect it:

- Do not start unsolicited 1:1 conversations with numbers that have no prior history (no cold outreach, no bulk messaging).
- Keep the built-in rate limits enabled and let the server send natural typing presence before messages.
- Avoid automatic reactions or replies to every incoming message, and guard against bot-to-bot loops.
- Use dedicated, consented numbers for automation; keep credentials and session folders private.

This project is not affiliated with or endorsed by WhatsApp or Meta.

## Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md).

## License

[MIT](./LICENSE)