Skip to content
jgaleaPublic

About

Self-hosted WhatsApp gateway. REST API + MCP server for messaging, media, groups, and webhooks.

Topics

Resources

Contributing

Stars

4 stars

Watchers

0 watching

Forks

Repository files navigation

Pigeon

Pigeon 🐦

License: MIT TypeScript Docker Self-hosted Stars Built by AgentVania

A self-hosted WhatsApp automation system. Send and receive WhatsApp messages over a simple REST interface, on a server you control — or plug it into AI tools through the built-in MCP server. Built on Baileys, runs in Docker, stores everything in SQLite.

Features

Send anything Text, images, documents, video, voice notes, locations, contacts, and polls.
Message actions React, edit, delete, and forward.
Conversations Presence and typing indicators, read receipts, status posting, and channels.
Groups & profile Create and manage groups (participants, invite links, settings); set your name, status, and picture; block and unblock.
Receive & react Incoming messages persisted to SQLite, with per-session webhooks (retry, backoff, optional HMAC signing) and a Server-Sent Events stream.
Multi-session Run several numbers from one instance. QR or phone-code pairing over HTTP.
MCP server Built-in MCP server so AI agents (Claude Code, Claude Desktop, and friends) can read chats and send messages as native tools.
Built to run Auto-reconnect, per-session send queue with light rate limiting, one Docker container with two mounted volumes.

Requirements

  • A running Docker engine with docker compose. On macOS that's Docker Desktop, OrbStack, or colima; on Linux, Docker Engine. The daemon must actually be running before you start.
  • A phone with WhatsApp, to pair the number once via QR.
  • Node 22+ only if you want to run it outside Docker (local development).

Quick start

cp .env.example .env          # set WA_API_KEY to any secret string
docker compose up -d --build
curl -s localhost:4000/api/health     # {"status":"ok"}

The container listens inside on port 3000 and is published to 127.0.0.1:4000 by the compose file.

Pair a number:

  1. POST /api/sessions/default/start
  2. Open the QR: GET /api/default/auth/qr (PNG), scan it from the phone under Linked Devices
  3. Poll GET /api/sessions/default until status is WORKING

Send a document:

curl -X POST localhost:4000/api/sendFile \
  -H "x-api-key: $WA_API_KEY" -H 'content-type: application/json' \
  -d '{"session":"default","chatId":"[email protected]",
       "file":{"data":"<base64>","mimetype":"application/pdf","filename":"report.pdf"},
       "caption":"here you go"}'

Local development

npm install
npm run build && npm start    # or: npm run dev
npm test                      # vitest

API

Every route except /api/health requires X-Api-Key: <WA_API_KEY>. There are two route groups: a clean, versioned /v1 API (recommended for new work) and a set of flatter /api endpoints with the session in the request body, convenient for simple clients.

/v1

Method Path Body / notes
GET / POST /v1/sessions list / create {name}
GET / DELETE /v1/sessions/:name status (with qr) / logout
POST /v1/sessions/:name/start|stop|restart lifecycle
POST /v1/sessions/:name/messages {chatId, type, text?, caption?, media?, location?, contact?, poll?}
POST /v1/sessions/:name/react {chatId, msgId, emoji, fromMe?}
POST /v1/sessions/:name/edit {chatId, msgId, text}
POST /v1/sessions/:name/delete {chatId, msgId, fromMe?}
POST /v1/sessions/:name/forward {toChatId, fromChatId, msgId}
POST /v1/sessions/:name/presence {type, chatId?}
POST /v1/sessions/:name/scheduled schedule a text {chatId, text, sendAt}; sendAt is ISO-8601 with an offset or Z, or epoch ms, and must be in the future
GET /v1/sessions/:name/scheduled?status=&limit= scheduled messages, soonest first; status is pending, sending, sent, failed or cancelled
DELETE /v1/sessions/:name/scheduled/:id cancel; 409 unless still pending
GET /v1/sessions/:name/chats recent chats
GET /v1/sessions/:name/chats/:chatId/messages?limit=&includeSystem= history; system events (joins, leaves, deletions) have type system and a short body, pass includeSystem=false to drop them
GET /v1/sessions/:name/chats/:chatId/messages/:msgId one stored message, 404 if it isn't in history
GET /v1/sessions/:name/contacts/check?phone= is on WhatsApp
GET /v1/sessions/:name/contacts/:chatId/picture profile picture url
POST /v1/sessions/:name/contacts/:chatId/block {blocked}
PUT /v1/sessions/:name/profile/name|status {name} / {status}
POST/GET /v1/sessions/:name/groups create {subject, participants} / list
GET /v1/sessions/:name/groups/:groupId metadata
GET /v1/sessions/:name/communities communities you belong to
GET /v1/sessions/:name/communities/:communityId/groups a community's linked groups, joined or not, with membership and description
POST /v1/sessions/:name/groups/:groupId/participants {participants, action}
PUT /v1/sessions/:name/groups/:groupId/subject|description update
GET/POST /v1/sessions/:name/groups/:groupId/invite get / invite/revoke
POST /v1/sessions/:name/groups/accept {code}
POST /v1/sessions/:name/status {text?, media?, statusJidList?}
POST/GET/DELETE /v1/sessions/:name/channels create / metadata / follow / delete
POST /v1/sessions/:name/auth/pairing-code {phone} (alternative to QR)
PUT /v1/sessions/:name/webhooks {urls:[...]}
GET /v1/events Server-Sent Events stream

Scheduled messages

The gateway keeps scheduled texts in its SQLite database and sends them itself, so they go out with no client connected. It checks every 20 seconds and sends through the same path and anti-spam guard as POST .../messages. A message whose session isn't WORKING is retried for 30 minutes after its time, then marked failed; anything further overdue (after a long outage, say) is marked failed with a "missed" error rather than sent late. A message that was mid-send when the gateway stopped is marked failed too, since delivery is unknown.

/api

Flatter endpoints with the session in the body: sendText, sendImage, sendFile, sendVoice, sendVideo, sendLocation, sendContact, sendPoll, sendSeen, reaction, startTyping/stopTyping, session lifecycle, :session/auth/qr, :session/chats/:chatId/messages, :session/groups, contacts/check-exists.

Media takes {data} (base64) or {url} (Pigeon fetches it server-side). Chat ids are <number>@s.whatsapp.net for people and <id>@g.us for groups.

Server-side URL fetching (off by default)

Pigeon does not fetch caller-supplied URLs unless you opt in. With PIGEON_ALLOW_URL_MEDIA unset, a media {url} (messages, group pictures, status media) is refused with a message telling the caller to download the file first and send it as {data} or, over MCP, by path. With PIGEON_ALLOW_WEBHOOKS unset, PUT /v1/sessions/:name/webhooks with a non-empty list answers 400 (clearing the list still works). Enabling either accepts residual SSRF risk: the gateway will open outbound connections to addresses chosen by whoever holds the API key.

When enabled, a URL must be public http or https without credentials. The host is resolved (5 s limit, at most 16 addresses) and refused if any address is loopback, private (RFC 1918), CGNAT, link-local, ULA, multicast, the Docker host, or an IPv6 form that embeds one of those (mapped, NAT64, 6to4, Teredo); the connection is then made to the address that was checked, not to a fresh DNS answer, with the socket dropped after 10 s idle and 30 s in total. Media redirects are checked hop by hop (3 at most), bodies are streamed under a 64 MB cap and the connection is torn down when a body goes over it. Webhook deliveries go through the same pinned connection on every attempt, do not follow redirects, time out after 10 s and discard the response body.

MCP server

Pigeon ships an MCP (Model Context Protocol) server so AI tools like Claude Code can use WhatsApp directly. It runs over stdio and talks to a running Pigeon instance via the REST API.

Tools: session_status, list_chats, read_messages, read_contact, send_message, send_media, delete_message, mark_read, check_contact, list_groups, group_info, list_communities, list_community_groups, create_group, add_participants, schedule_message, list_scheduled, cancel_scheduled.

schedule_message takes chatId, text and sendAt, an ISO-8601 time that must carry an explicit offset or Z (naive times and past times are rejected). list_scheduled takes an optional status; cancel_scheduled takes an id and only works on pending messages. In draft-only mode schedule_message returns the draft without scheduling it.

read_contact merges a person's messages across their real number and any privacy-masked @lid chat, since WhatsApp can split one contact across two chats. create_group and add_participants manage group membership. group_info, list_communities and list_community_groups are read-only: they return a group's description and posting rules, and a community's subgroups whether or not you have joined them. read_messages and read_contact skip system events (member joins and leaves, deletions, setting changes) unless includeSystem is true.

Text written by other WhatsApp users (message bodies, captions, chat and group names, descriptions, file names) comes back fenced between [UNTRUSTED_<nonce>] markers with a fresh nonce per response, with zero-width and bidirectional control characters stripped and fence lookalikes inside the content defused. The server instructions tell the model to treat fenced text as data, never as instructions.

Recipients must be one bare phone number or one JID ending in @s.whatsapp.net, @lid or @g.us. Newsletters, status@broadcast and strings holding several numbers are refused.

send_media with a url only works when the gateway runs with PIGEON_ALLOW_URL_MEDIA=1; otherwise download the file first and send it by path. send_media with a local path only reads from ~/Downloads, ~/code/artifacts, the Pigeon media folder and any folders listed in PIGEON_UPLOAD_DIRS (comma-separated). Symlinks are resolved first, dotfiles and dot-directories, the data folder, .env and ~/.ssh are always refused, and files are capped at 48 MB. download_media writes only into ~/Downloads/pigeon (or PIGEON_DOWNLOAD_DIR), names the file after the sender's suggestion with any directory part and leading dots removed, and never overwrites: a clash gets a (n) suffix.

Register it with your MCP client, e.g. in a .mcp.json:

{
  "mcpServers": {
    "pigeon": {
      "command": "node",
      "args": ["/path/to/pigeon/dist/mcp.js"]
    }
  }
}

It reads WA_API_KEY (and optional WA_API_URL, WA_SESSION, PIGEON_UPLOAD_DIRS, PIGEON_DOWNLOAD_DIR) from the environment, falling back to the .env in the project root. Build first with npm run build.

Draft-only mode

Set WA_MCP_READONLY=true to run the MCP server in draft-only mode. send_message and send_media stop hitting WhatsApp: instead of sending, they return the composed draft (sent: false) for you to review. delete_message, create_group, add_participants and mark_read (which sends a read receipt) are held back the same way. The read tools (session_status, list_chats, read_messages, check_contact) keep working, and so does download_media, since it sends nothing and only writes inside the download folder. Use this when you want an assistant to draft replies but never send on its own. There's no per-call override, so it's a hard guarantee for that session.

Anti-spam guard

WhatsApp restricts accounts that message strangers in bursts, especially right after linking a new device. The send guard enforces sane limits on cold sends — first contact with a number that has never messaged you. Warm replies and group messages pass through untouched.

A cold send is blocked when it lands inside the post-link cooldown, too soon after the previous cold send, or over the hourly/daily caps. The send fails with a reason explaining which limit it hit. Warm replies (any number that has messaged you) and group/broadcast/newsletter sends are never gated.

The limits and their defaults:

Setting Default What it does
WA_SEND_GUARD on master switch; off disables all cold-send limits
WA_GUARD_POST_CONNECT_MS 120000 (2 min) after the session links or relinks, cold sends are paused for this long
WA_GUARD_COLD_MIN_GAP_MS 60000 (1 min) minimum gap between two cold sends
WA_GUARD_COLD_PER_HOUR 5 max cold sends per rolling hour
WA_GUARD_COLD_PER_DAY 20 max cold sends per rolling day
WA_GUARD_PARTICIPANTS_PER_HOUR 20 max distinct numbers added to groups per rolling hour, across create_group and participant adds

Two ways to override on a per-send basis:

  • Pass "force": true on a single send to bypass the guard for one deliberate, vetted message (works over the HTTP API and the MCP send tools).
  • Set WA_SEND_GUARD=off to turn the guard off entirely for the session.

Changing the limits

All five settings are read from the environment (falling back to .env in the project root). Edit .env, then restart so the new values load:

# .env — example: loosen to 10/hour, 40/day, 30s between cold sends
WA_GUARD_COLD_PER_HOUR=10
WA_GUARD_COLD_PER_DAY=40
WA_GUARD_COLD_MIN_GAP_MS=30000
# Docker: recreate the container so it picks up the new .env values
docker compose up -d

# Local (npm): restart the process
npm run build && npm start

To turn the guard off, or shorten the post-link cooldown to 30s:

# .env
WA_SEND_GUARD=off
# or keep it on but shorten the cooldown
WA_GUARD_POST_CONNECT_MS=30000

The docker-compose.yml passes each guard variable through from .env with the defaults above, so anything you don't set keeps its default.

Configuration

Variable Default Purpose
WA_API_KEY (required) shared API key for the X-Api-Key header
WA_PORT 4000 listen port
WA_HOST 127.0.0.1 bind address
WA_DATA_DIR ./data SQLite location (sessions + history)
WA_MEDIA_DIR ./media downloaded media
WA_MEDIA_AUTODOWNLOAD on save inbound media to WA_MEDIA_DIR when the message arrives and serve that copy from the media endpoint; off downloads from WhatsApp on each request
WA_MEDIA_LIFETIME_DAYS 180 media cleanup window
WA_LOG_LEVEL info pino log level
WA_WEBHOOK_SECRET (unset) if set, sign webhooks with an x-pigeon-signature HMAC
PIGEON_ALLOW_URL_MEDIA 0 opt in to fetching media from caller-supplied urls (accepts residual SSRF risk)
PIGEON_ALLOW_WEBHOOKS 0 opt in to webhook delivery (accepts residual SSRF risk)
WA_API_URL http://127.0.0.1:4000 Pigeon base URL (MCP server only)
WA_SESSION default session the MCP server operates on
WA_MCP_READONLY false MCP server only; when true, send tools draft instead of sending
PIGEON_UPLOAD_DIRS (unset) MCP server only; extra comma-separated folders send_media may read local files from
PIGEON_DOWNLOAD_DIR ~/Downloads/pigeon MCP server only; the one folder download_media saves into
WA_SEND_GUARD on anti-spam guard on cold (first-contact) sends; off to disable
WA_GUARD_POST_CONNECT_MS 120000 pause cold sends for this long after the session links
WA_GUARD_COLD_MIN_GAP_MS 60000 minimum gap between two cold sends
WA_GUARD_COLD_PER_HOUR 5 max cold sends per rolling hour
WA_GUARD_COLD_PER_DAY 20 max cold sends per rolling day
WA_GUARD_PARTICIPANTS_PER_HOUR 20 max distinct numbers added to groups (created or joined) per rolling hour

How it works

HTTP (Fastify)
 |- /v1/*    versioned API ----+
 |- /api/*   flat endpoints ---+
                               v   one core
   SessionManager . MessageService . MediaService
   HistoryStore . WebhookDispatcher . SQLite auth state
                               |
                         Baileys socket(s)

Storage

SQLite under WA_DATA_DIR holds session auth state and message history. Media lives under WA_MEDIA_DIR with a lifetime cleanup. Both are mounted volumes, so they survive container rebuilds.

Disclaimer

Pigeon is not affiliated with, endorsed by, or connected to WhatsApp or Meta. It uses Baileys, an unofficial library, to automate a WhatsApp account. This is not officially supported, and accounts using automation can be restricted. Use it at your own risk, on a number you control.

Scope

Pigeon is built for personal automation, prototyping, and development. It has no bulk-send features by design. Message people who have agreed to hear from you, respect local law, and for business or marketing messaging at scale use the official WhatsApp Business Platform.

Credits

Built by Jean Galea.

If you want WhatsApp, or any messaging, done properly for a business on the official APIs, that's what AgentVania does.

License

MIT. See LICENSE.

About

Self-hosted WhatsApp gateway. REST API + MCP server for messaging, media, groups, and webhooks.

Topics

Resources

Contributing

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages