Expose OpenWA to AI agents over MCP
Turn OpenWA into a set of tools an AI agent can call. The Model Context Protocol (MCP) lets clients like Claude and Cursor invoke external capabilities as first-class tools. OpenWA ships an opt-in MCP server that exposes 26 curated read tools by default, and 52 once you opt in to the write tier — listing sessions, sending messages, reading and searching chats, messages, and contacts, basic group management, plus label reads and writes and automation-rule reads — running through the same services and authentication as the REST API.
This guide shows you how to enable the server, connect a client, mint a safe key for it, and lock it down.
- A running OpenWA instance (v0.31.0). See Installation.
- At least one connected session to act on. See Connect your first session.
- An API key. See the Authentication guide.
- An MCP client (for example Claude Code or Cursor).
Why the server is off by default
The MCP server is disabled unless you opt in, and it is purely additive. When MCP_ENABLED is unset, the MCP server is not mounted and the MCP module and MCP SDK are not loaded, and every REST route behaves exactly as before (the protocol-neutral tool registry AgentToolsModule is built either way, and nothing reads it until the server is enabled). Turning it on mounts one extra route on the existing server; it does not start a second process or change any REST behavior.
The agent surface is also intentionally narrow. Rather than reflecting every REST route, OpenWA exposes a hand-picked, read/write-tiered set of tools. This keeps destructive and privileged operations off the agent's path and keeps the agent from drowning in choices.
Enable the server
Set MCP_ENABLED=true and start OpenWA as usual. The server mounts a stateless Streamable-HTTP transport at POST /mcp on the existing port (2785 by default). The transport keeps no sessions and opens no standalone SSE stream, so GET /mcp and DELETE /mcp answer 405 with Allow: POST (since v0.23.6; before, they answered 404, which Streamable HTTP clients reported as an SSE error on connect). A POST that carries requests is still answered as a text/event-stream, so a client must send an Accept header listing both application/json and text/event-stream; without it the transport answers 406.
MCP_ENABLED=true npm run start:prod # or set MCP_ENABLED in your .env / compose file
Note that /mcp sits at the server root, not behind the /api prefix used by REST endpoints. The full local URL is http://localhost:2785/mcp.
Optional tuning
| Variable | Default | Effect |
|---|---|---|
MCP_READONLY | unset (read-only) | Unset, or any value other than false, mounts only the 26 read-tier tools. Set it to false to mount all 52, adding the write tier. |
MCP_RATE_LIMIT_MAX | 60 | Max tool calls per key per window. |
MCP_RATE_LIMIT_WINDOW_MS | 60000 | Sliding window in milliseconds (default 1 minute). |
MCP_IP_RATE_LIMIT_MAX | 120 | Pre-auth cap on JSON-RPC messages per client IP per window. Each message of a batch counts (v0.23.6+). |
MCP_IP_RATE_LIMIT_WINDOW_MS | 60000 | Per-IP window in milliseconds. |
MCP_MAX_RESULT_BYTES | 0 (no cap) | Cap on one tool result, in UTF-8 bytes (v0.31.0+): see How a tool call is authorized. Read once when the server mounts; a malformed value such as 100k fails the boot. |
MCP_READONLY=false # opt in to the write tools; unset means read-only
MCP_RATE_LIMIT_MAX=60 # max tool calls per key per window
MCP_RATE_LIMIT_WINDOW_MS=60000 # sliding window in ms
The per-key limiter is keyed by the authenticated API key id and is independent of the REST throttler. A second limiter runs before authentication, keyed by the resolved client IP (it honours TRUSTED_PROXIES), so a flood of invalid keys is shed with a JSON-RPC 429 rather than reaching a key lookup. Since v0.23.6 it counts JSON-RPC messages rather than HTTP requests: each element of a batch spends one unit, and a batch larger than the remaining budget is refused whole with a 429, running none of its messages while still spending whatever budget the IP had left. Also since v0.23.6, an IPv6 client is keyed on its /64, so clients that reach the gateway from one IPv6 network share a bucket; raise MCP_IP_RATE_LIMIT_MAX if that is your setup. Any missing, blank, non-positive, or non-numeric value falls back to the default.
What the server exposes
The tool surface is an allowlist by construction: a capability is exposed only if a tool descriptor is written for it. There is no automatic reflection of REST routes. Each tool is tiered read or write. Every write tool requires an operator role, and so do eight reads: MessageSearch (v0.27.0+, because it searches stored message text and returns snippets), the three webhook reads and the two automation-rule reads, because they expose delivery URLs and rule bodies, plus GroupGetInviteCode, because an invite code is a transferable join capability rather than plain read data, plus ContactCheckNumber, because it queries WhatsApp about a third party. The remaining reads work with a viewer key. Since v0.31.0 every tool is also advertised with a title, the name a client shows: the tool name split into words (MessageSendText is Message send text).
| Domain | Read tools | Write tools |
|---|---|---|
| Session | list, get, chats, stats, presence | mark read/unread, typing, subscribe presence |
| Message | list, search (operator), history, reactions | send text/image/video/audio/document/location/contact/sticker (each takes an optional quotedMessageId), send template, reply, forward, react |
| Contact | list, get, check-number (operator), resolve-phone, profile-picture | block, unblock |
| Group | list, get, invite-code (operator) | create, add participants, set subject, set description |
| Webhook | list all, list for session, get (all operator) | — |
| Label | list, get, chats for a label, labels on a chat | upsert, delete, add to chat, remove from chat |
| Automation rule | list, get (both operator) | — |
SessionFindAll, SessionGetChats, ContactFindAll, GroupFindAll and WebhooksList answer a bare array with no total, and a call returns at most 1000 rows, also when limit is omitted, so a full page does not show that the list is complete: ask again with offset. Since v0.31.0 their limit description says so.
On Baileys, SessionGetChats lists a chat WhatsApp holds under a privacy id (@lid) that has no saved, verified or push name with name set to an empty string, and with a phone to show instead when the session can map the id; up to v0.30.3 name held the id's own digits. Title such a chat by phone, else by id. Since v0.31.0 every Baileys chat name is also trimmed, and a blank name of any other chat lists the contact's name or the id's digits. whatsapp-web.js lists no phone and lists an unnamed privacy-id chat under its id. The SessionGetChats and MessageSearch descriptions state the Baileys rule.
On Baileys, the contact list tool (ContactFindAll) returns only contacts with a name saved on the phone (v0.23.6+), the same list GET /api/sessions/{sessionId}/contacts returns. A peer known only by its pushname is no longer listed, but the get tool (ContactFindOne) still resolves it with isMyContact: false. whatsapp-web.js still lists unsaved chat partners.
The label tools are split by engine, and labels are a WhatsApp Business feature. The four read tools (LabelFindAll, LabelFindOne, LabelListChats, LabelListForChat) work on whatsapp-web.js only. LabelUpsert and LabelDelete work on Baileys only. LabelAddToChat and LabelRemoveFromChat work on both. A tool called on the wrong engine fails with isError: true and EngineNotSupportedError.
Three more tools are limited to one engine, and since v0.26.0 their descriptions say so: MessageHistory and MessageGetReactions work on whatsapp-web.js only, and GroupCreate on Baileys only. Called on the other engine they fail the same way, and a retry cannot succeed. On Baileys, use MessageList for stored messages.
MessageSendText, MessageSendImage, MessageSendVideo, MessageSendAudio, MessageSendDocument, MessageSendLocation, MessageSendContact, and MessageSendSticker each accept an optional quotedMessageId, which makes the send a reply. MessageSendTemplate has no quote field, matching the REST route; the ninth quotable REST endpoint, send-poll, has no MCP tool at all. MessageReply keeps its own quotedMessageId, which is required there.
The value is engine-specific: whatsapp-web.js takes the serialized message id, Baileys the raw key id of a message it has already stored. No tool was added or removed for this, so the count above is unchanged.
mentions, linkPreview, and idempotencyKey (v0.23.0+ / v0.30.0+)Every send tool whose REST route carries mentions accepts it too: MessageSendText, the four media sends, MessageSendSticker, MessageSendTemplate, and MessageReply. MessageSendText also accepts linkPreview and customLinkPreview (including thumbnailUrl and thumbnailBase64 since v0.27.0), and since v0.30.0 MessageSendTemplate also accepts linkPreview (the linkPreview argument description of both tools says that, when linkPreview is omitted, the session config's linkPreview default applies when one is set (since v0.30.3), and that otherwise Baileys attaches a preview only when linkPreview is true). That default does not apply to a MessageSendText call that sets customLinkPreview. Since v0.30.0 all 11 send tools (MessageSendText, MessageSendImage, MessageSendVideo, MessageSendAudio, MessageSendDocument, MessageSendLocation, MessageSendContact, MessageSendSticker, MessageSendTemplate, MessageReply, and MessageForward) also accept an optional idempotencyKey (1 to 255 visible ASCII characters), and every published tool schema sets additionalProperties: false and refuses unknown arguments (including unknown keys inside customLinkPreview) with Unrecognized key: "x" (up to five names listed, each cut at 64 characters) instead of silently dropping them. Tool call arguments with more than 10,000 array items and object keys in total (nested included) are also refused before schema validation (arguments contain more than the maximum of 10000 elements). No tool was added or removed, so the count above is unchanged.
Tools refuse an empty required chatId or messageId, and MessageReply an empty quotedMessageId, as the REST routes do; the same holds for fromChatId, toChatId, contactId, groupId, webhookId, ruleId, and the number of ContactCheckNumber. Since v0.28.0 GroupGetInfo, GroupParticipantsAdd, and GroupGetInviteCode also refuse a groupId that does not name a group with 400 (BadRequestException) before looking up the engine, and ContactCheckNumber refuses a non-phone @ id or a digitless value with 400. Since v0.30.0 GroupFindAll checks that the session exists first and returns 404 (NotFoundException) for an unknown sessionId (where it previously returned 400 Session is not started), SessionGetPresence returns observedAt as an ISO date-time string (matching REST), and MessageList and MessageSearch refuse a from filter over 255 characters. Since v0.31.0 a tool's sessionId must be 1 to 128 letters, digits and hyphens, as the REST routes require, and any other value is refused by the schema check with -32602 before a lookup (see How a tool call is authorized). MessageSendImage, MessageSendVideo, MessageSendAudio, MessageSendDocument, and MessageSendSticker accept a url only when it is an absolute http:// or https:// URL with a host (or when base64 holds the data instead, see the next note). Before v0.23.6 those arguments accepted an empty string (the label tools already refused an empty chatId), and a well-formed URL with another scheme passed the schema and went out as garbled base64. For an unrestricted key an empty MessageList.chatId applies no filter; a chat-restricted key must provide an allowed chat. Chat IDs (chatId, fromChatId, toChatId) over 255 characters are refused. NUL characters in tool input are refused too. The gateway downloads that url itself, and since v0.23.6 it does so through the session's egress proxy when the session has one (before, from the gateway's own address): a download through that proxy that fails before any response arrives (the proxy is down, refuses the connection or rejects its credentials with 407, it cannot open a tunnel to the media host, or the fetch times out) fails the send with an EngineNotSentError tool error (503 on REST), and SESSION_PROXY_URL_FETCH=false on the gateway restores the direct download. Most other failed downloads now come back as a BadRequestException, or a PayloadTooLargeException above MEDIA_DOWNLOAD_MAX_BYTES, with a message saying why, where they used to be a generic Internal error. That includes an error status from the media host, an error status other than 407 that an http or https session proxy answers itself for an http:// URL it cannot reach or will not forward, and, without a proxy, a timeout or a failed connection. Since v0.31.0 a url that carries a user name or password is refused too, with a BadRequestException saying Media URL must not contain credentials (userinfo), before any connection; it used to fail as an internal error. A redirect, or a host name that does not resolve, is refused as before with a BadRequestException saying Destination address is not allowed, and SSRF_ALLOWED_HOSTS does not lift the refusal of a redirect. No tool was added or removed, so the count above is unchanged.
url may sit beside base64 (v0.26.0+)Every message write tool (MessageSend*, MessageReply, MessageForward and MessageReact) and the session tools SessionSubscribePresence, SessionMarkChatRead, SessionMarkChatUnread and SessionSendChatState refuse a chat id that is not in the form localpart@host, such as a phone number without @c.us, as their REST routes do, instead of passing it to the engine. The media send tools check url together with base64: when base64 holds data, a url left beside it, often an empty string from an agent that fills every optional field, is neither fetched nor an error, as on the REST routes. No tool was added or removed, so the count above is unchanged.
Deliberately excluded (never exposed as tools): session lifecycle (create / delete / start / stop / force-kill), chat delete, bulk send, message delete, group leave / remove / promote / demote / invite-revoke, all API-key management, all plugin management, infrastructure import/export/restart, settings writes, automation-rule writes (autoreply is REST-only), and webhook create/update/delete. These are destructive, privileged, or have no agent use case.
How a tool call is authorized
The MCP server is a thin transport adapter over a protocol-neutral tool registry. Every POST /mcp first passes the pre-auth per-IP throttle and the mount's API key gate (which refuses a missing, unknown, revoked, expired, or allowedIps-scoped key before any MCP method runs). Past that gate, the MCP SDK bounds total argument elements at 10,000 and validates the arguments against the tool's strict Zod schema (additionalProperties: false); arguments it refuses come back as an isError tool result (MCP error -32602: Input validation error: ...) without reaching per-tool authorization (so a key lacking the tool's role or session gets -32602 rather than 403 and writes no audit row). A call whose arguments pass the SDK check then runs through invokeTool in five steps:
- Key extraction: the adapter reads the API key from the
X-API-Keyheader orAuthorization: Bearer …. - Authentication:
invokeToolvalidates the call through the sameAuthServicethe REST guard uses, enforcing key validity, expiry, the per-sessionallowedSessionsscope, the tool's required role (hasPermission), and whether the tool supportsallowedChatsbefore the handler runs. - Validation:
invokeToolre-parses the arguments with the same Zod schema and refuses NUL characters before reaching any service. - Chat arguments: a chat-restricted key must name allowed chats; ordinary send quotes are refused, while
MessageReplybinds its quote to the authorized chat. - Execution: the handler calls the existing service method and shapes its result through the same response DTO the matching REST controller uses, so no field is exposed over MCP that REST hides. Since v0.30.0 a tool result up to 32 KiB (
32768bytes of UTF-8, raised from 4 KiB) is returned inline astext, while a larger payload returnsReceived resource mcp://toolResult/<id>.json with <n> bytesin the text block followed by an embedded base64resourceblock (MCP_MAX_RESULT_BYTESchanges that, see below the list). Tool error messages and server log lines are clipped at 4,096 characters (... [truncated, <n> characters in all]), and HTTP error codes (such asIDEMPOTENCY_KEY_REUSED,IDEMPOTENCY_KEY_IN_PROGRESS, orIDEMPOTENCY_OUTCOME_UNKNOWN) are included ascodein the tool error JSON, withretryAfterSecondsbeside it since v0.31.0 when the REST answer has one: the409ENGINE_PAGE_RELOADINGof a whatsapp-web.js session whose page is reloading, and the429SEND_PACING_LIMITED.
Capping a result (v0.31.0+). For a client that puts a whole tool result in the model's context, set MCP_MAX_RESULT_BYTES to a byte count (for example 100000): every result, an error answer included, is then one text item, and none is offloaded as a resource. A payload within the cap comes back whole, also past 32 KiB; a larger one is cut to at most that many bytes, never inside a character, and followed by …[truncated: <n> bytes in all; narrow the request, with limit and offset where the tool takes them, to see the rest]. An error answer ends with …[truncated: <n> bytes in all]; that covers the -32602 refusal of arguments the schema rejects, which names each invalid value and so grows with the arguments. The note follows the cut, so a cut result runs slightly past the cap. Unset or 0, the default, changes nothing. The value is read once when the server mounts.
Because the transport is stateless, each request mints and tears down its own server instance — any node can answer a request, but a tool call runs on the node that received it, so with several nodes a call for a session another node owns does not reach that node's engine. The per-key and per-IP rate limits are kept in each node's memory. See Scaling.
Connect a client
Point an MCP client at http://localhost:2785/mcp and supply your API key in a header. For a project-scoped client such as Claude Code, drop a .mcp.json at your project root:
{
"mcpServers": {
"openwa": {
"type": "http",
"url": "http://localhost:2785/mcp",
"headers": { "Authorization": "Bearer YOUR_API_KEY" }
}
}
}
.mcp.json out of version controlIt carries a live API key. Add it to .gitignore. Replace YOUR_API_KEY with a real key — mint a dedicated one as shown below.
From the client, list the tools. You should see the 26 read tools, or all 52 if you set MCP_READONLY=false. Then call one — for example SessionFindAll — to confirm authentication and execution end to end.
Mint a dedicated key for the agent
Do not reuse an admin key. Create a least-privilege, session-scoped operator key for the MCP client. Create it once over REST; the plaintext key is returned only in this 201 Created response under apiKey, so copy it immediately.
curl -X POST http://localhost:2785/api/auth/api-keys \
-H "X-API-Key: YOUR_ADMIN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "claude-mcp",
"role": "operator",
"allowedSessions": ["8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a"]
}'
The call returns 201 Created with the one-time plaintext key in apiKey:
{
"id": "a1b2c3d4-0000-0000-0000-000000000000",
"name": "claude-mcp",
"keyPrefix": "owa_k1_01234",
"role": "operator",
"allowedSessions": ["8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a"],
"isActive": true,
"usageCount": 0,
"createdAt": "2026-06-25T09:30:00.000Z",
"apiKey": "owa_k1_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
}
Paste the apiKey value into your .mcp.json — it is returned only in this response. To rotate, create a new key and delete the old one — there is no way to retrieve an existing key's plaintext later. See the full request and response shapes in the API reference and the Authentication guide.
Since v0.25.0 a key with allowedChats can use chat-scoped tools. MessageList requires an explicit allowed chatId; MessageSearch (v0.27.0+) scopes results on the built-in search provider to the key's allowed chats (and is refused when a plugin search provider is active); chat, contact, group and label-chat lists filter before pagination. Forwarding checks both chats. SessionFindOne remains available inside session scope; session discovery and statistics, contact number checks, webhook management, automation rules, group creation, participants, invite codes and the label catalogue (LabelFindAll, LabelFindOne, LabelUpsert and LabelDelete) remain refused. MessageReply can quote within the authorized chat; other send tools cannot quote with a chat-restricted key. Rejections return isError: true with ForbiddenException.
A tool call carries no genuine client IP, so a key with allowedIps is still refused at the /mcp mount with 403. Leave that field empty and constrain access at the proxy. Combine allowedSessions and allowedChats to narrow the key further.
Since v0.30.0 MessageList exposes the full filter and pagination surface of the REST message list: chatId, from (up to 255 characters), direction (incoming or outgoing), type, since and until (epoch milliseconds), orderBy (createdAt or timestamp), messageId, after (for stable cursor pagination), inlineMedia (since v0.31.0 off unless the call passes true: a media message is listed with an { omitted, sizeBytes } marker in place of its payload, and true carries the payloads inline as base64, up to the per-response budget MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES, 8 MiB by default, with the newest payload let through whatever its size, which makes a result very large; GET /api/sessions/{sessionId}/messages still inlines unless asked not to; under MCP_MAX_RESULT_BYTES a payload that does not fit the cap arrives cut and cannot be decoded, so fetch it from GET /api/sessions/{sessionId}/messages/{chatId}/{messageId}/media), limit, and offset. MessageSearch (v0.27.0+) searches stored message text across every session and chat the key is allowed to read (q required, plus optional chatId, from capped at 255 characters in v0.30.0+, type up to 50 characters added in v0.30.0+, direction, dateFrom, dateTo, match, limit, and offset; it takes no sessionId, and the key's allowedSessions scopes the search); when match is omitted it uses contains if SEARCH_CONTAINS_ENABLED=true and word otherwise. Also since v0.30.0, all 11 send tools (MessageSendText, MessageSendImage, MessageSendVideo, MessageSendAudio, MessageSendDocument, MessageSendLocation, MessageSendContact, MessageSendSticker, MessageSendTemplate, MessageReply, and MessageForward) accept an optional idempotencyKey (1 to 255 visible ASCII characters), which shares the 24-hour per-session idempotency store with REST (a key used over REST is refused as IDEMPOTENCY_KEY_REUSED over MCP and vice versa). Per-recipient message receipts (GET /api/sessions/{sessionId}/messages/{chatId}/{messageId}/receipts, v0.28.0+) and phone-to-LID lookup (GET /api/sessions/{sessionId}/contacts/{number}/lid, v0.27.1+) remain REST-only.
Security
The MCP server reuses REST's security model rather than re-implementing it, but the agent context changes how you scope keys.
- Same authorization as REST. Role and per-session
allowedSessionsscoping are enforced identically to REST. A key scoped to one session cannot act on another. A key withallowedIpsis refused at the mount because tools have no client IP. A key withallowedChatsuses the same chat fence as REST, including persisted phone/LID aliases, and only reaches tools explicitly authorized for chat scope. - Untrusted content. Message bodies, search snippets, captions, chat/contact names and group subjects returned by tools are controlled by WhatsApp users. Treat them as data rather than instructions. Prefer a viewer key with session and chat scope; when write tools are enabled, configure the client to confirm each write with a human.
- Least privilege. Give each MCP client a dedicated, non-admin, session-scoped key (
operatorat most). This bounds the blast radius if the key leaks. - Read-only when you can. Read-only is the default: leave
MCP_READONLYunset unless the agent must send, and write tools are never mounted. - Response parity. Tools reuse the REST response DTOs, so fields the REST API strips — webhook secrets and custom headers, session proxy URLs, engine config — are not exposed over MCP either.
- Rate limiting. The per-key limiter bounds how fast a single key can call tools, independently of the REST throttler. Tune it with the env vars above.
/mcp to the public internetAuthentication today is a static API key, which is appropriate for a self-hosted instance reached locally or over a trusted network. Do not expose /mcp publicly without a fronting authentication proxy. OAuth 2.1 support for public, internet-facing deployments is planned but not yet available in v0.31.0.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
Client can't connect to /mcp | Server not enabled | Start OpenWA with MCP_ENABLED=true and confirm it loaded on port 2785. |
| Tool list is empty or shows only reads | MCP_READONLY is not set to false; read-only is the default | Set MCP_READONLY=false and restart to mount the write tier. Leave it unset to stay observe-only. |
401-style auth failure | Missing, expired, or wrong key | Check the Authorization / X-API-Key header; mint a fresh key if expired. |
| Auth rejected for a valid key | Key carries an allowedIps list | Use a key minted without allowedIps for MCP. |
Tool calls fail with API key is restricted to selected chats | The tool is not authorized for chat scope, or the server predates v0.25.0 | Upgrade to v0.25.0 and use chat-scoped tools with allowed chats; do not widen the key for an unrelated tool. |
| A tool refused with a role error | Key role below operator | Every write tool needs operator, and so do MessageSearch, the webhook reads, the automation-rule reads, the group invite-code read and ContactCheckNumber. Re-mint the key with "role": "operator". |
| Tool acts on the wrong / no session | Key not scoped to that session | Set allowedSessions to include the target session id. |
| Calls start failing under load | Per-key rate limit hit | Slow the agent, or raise MCP_RATE_LIMIT_MAX. |
/mcp answers HTTP 429 before any tool runs | Pre-auth per-IP limit hit; since v0.23.6 each message of a JSON-RPC batch counts and IPv6 clients in one /64 share a bucket | Send smaller batches, or raise MCP_IP_RATE_LIMIT_MAX. |
A tool result ends in …[truncated: <n> bytes in all ...] | MCP_MAX_RESULT_BYTES is set (v0.31.0+) and the result is larger than the cap | Narrow the request with limit, offset and the filters, or raise the cap. Unset it, or set 0, to get results over 32 KiB as the base64 resource block again. |
MessageList lists media as { omitted, sizeBytes } | The tool lists media without its payload unless inlineMedia is true (v0.31.0+) | Pass inlineMedia: true for the base64 inline, which makes the result very large, or fetch the file from GET /api/sessions/{sessionId}/messages/{chatId}/{messageId}/media. |
See Troubleshooting for general diagnostics.
Next steps
- Send messages — the workflow most agent tools drive.
- Authentication — roles, scoping, and key rotation in depth.
- Scaling — multi-node limits, including how MCP calls are routed.
- API reference — the REST endpoints each tool mirrors.