WhatsApp MCP Server
Servidor MCP de WhatsApp (TypeScript/Baileys)
Este es un servidor de Protocolo de Contexto de Modelo (MCP) para WhatsApp, creado con TypeScript y utilizando la biblioteca @whiskeysockets/baileys .
Le permite conectar su cuenta personal de WhatsApp a un agente de IA (como Anthropic Claude a través de su aplicación de escritorio o Cursor) que le permite:
Busca tus mensajes personales de WhatsApp.
Busca tus contactos (individuos, no grupos).
Enumere sus chats recientes.
Recuperar el historial de mensajes de chats específicos.
Envía mensajes a personas o grupos.
Se conecta directamente a tu cuenta personal de WhatsApp mediante la API multidispositivo de WhatsApp Web. Todos tus mensajes y datos de autenticación se almacenan localmente en una base de datos SQLite ( ./data/ ) y en la caché de autenticación ( ./auth_info/ ). Los datos solo se envían al agente de IA conectado cuando este utiliza explícitamente las herramientas MCP proporcionadas (que controlas a través de la interfaz del agente).
(Opcional: considere agregar una captura de pantalla o un GIF similar al ejemplo de referencia aquí)
Ejemplo
Usuario: Envía un mensaje de WhatsApp a "Meu amor" en WhatsApp diciendo "Te amo"
Asistente: Bien, primero necesito encontrar el contacto. Usando la herramienta: whatsapp.search_contacts
{
"query": "Meu amor"
}Resultado de la herramienta:
[
{
"jid": "5599xxxxxx@s.whatsapp.net",
"name": "Meu Amor"
}
]Asistente: Encontré el contacto. Estoy enviando el mensaje. Usando la herramienta: whatsapp.send_message
{
"recipient": "5599xxxxxx@s.whatsapp.net",
"message": "Te amo"
}Resultado de la herramienta:
Message sent successfully to 5599xxxxxx@s.whatsapp.net (ID: XXXXXXXXXXX).Related MCP server: WAHA MCP
Características principales (herramientas MCP)
El servidor expone las siguientes herramientas al agente de IA conectado:
search_contacts: busca contactos por nombre o parte del número de teléfono (JID).list_messages: recupera el historial de mensajes de un chat específico, con paginación.list_chats: enumera tus chats, ordenables por actividad o nombre, filtrables, paginados, opcionalmente incluye detalles del último mensaje.get_chat: obtiene información detallada sobre un chat específico.get_message_context: recupera los mensajes enviados inmediatamente antes y después de un ID de mensaje específico para el contexto.send_message: envía un mensaje de texto a un JID de destinatario específico (usuario o grupo).
Instalación
Instalación mediante herrería
Para instalar WhatsApp MCP Server para Claude Desktop automáticamente a través de Smithery :
npx -y @smithery/cli install @jlucaso1/whatsapp-mcp-ts --client claudePrerrequisitos
Node.js: Versión 23.10.0 o superior (como se especifica en
package.json). Puede comprobar su versión connode -v. (Tiene compatibilidad inicial con TypeScript y SQLite).npm (o yarn/pnpm): generalmente viene con Node.js.
Cliente de IA: aplicación de escritorio Anthropic Claude, Cursor, Cline o Roo Code (u otro cliente compatible con MCP).
Pasos
Clonar este repositorio:
git clone <your-repo-url> whatsapp-mcp-ts cd whatsapp-mcp-tsInstalar dependencias:
npm install # or yarn install / pnpm installEjecute el servidor por primera vez: use
nodepara ejecutar el script principal directamente.node src/main.tsLa primera vez que lo ejecute, probablemente generará un enlace de código QR usando
quickchart.ioe intentará abrirlo en su navegador predeterminado.Escanee este código QR usando su aplicación móvil WhatsApp (Configuración > Dispositivos vinculados > Vincular un dispositivo).
Las credenciales de autenticación se guardarán localmente en el directorio
auth_info/(git ignora esto).Los mensajes comenzarán a sincronizarse y se almacenarán en
./data/whatsapp.db. Esto podría tardar un tiempo, dependiendo del tamaño de tu historial. Consulta el archivowa-logs.txty la salida de la consola para ver el progreso.Mantén esta ventana de terminal abierta. Después de sincronizar, puedes cerrarla.
Configuración para el cliente de IA
Debes decirle a tu cliente de IA cómo iniciar este servidor MCP.
Prepare el JSON de configuración: Copie la siguiente estructura JSON. Deberá reemplazar
{{PATH_TO_REPO}}con la ruta absoluta al directorio donde clonó este repositorio.{ "mcpServers": { "whatsapp": { "command": "node", "args": [ "{{PATH_TO_REPO}}/src/main.ts" ], "timeout": 15, // Optional: Adjust startup timeout if needed "disabled": false } } }Obtener la ruta absoluta: Dirígete al directorio
whatsapp-mcp-tsen tu terminal y ejecutapwd. Usa esta salida para{{PATH_TO_REPO}}.
Guardar el archivo de configuración:
Para Claude Desktop: guarde el JSON como
claude_desktop_config.jsonen su directorio de configuración:macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json(Ruta probable, verificar si es necesario)Linux:
~/.config/Claude/claude_desktop_config.json(Ruta probable, verificar si es necesario)
Para el cursor: guarde el JSON como
mcp.jsonen su directorio de configuración:~/.cursor/mcp.json
Reiniciar Claude Desktop/Cursor: Cerrar y volver a abrir el cliente AI. Ahora debería detectar el servidor MCP de WhatsApp y permitirle usar sus herramientas.
Uso
Una vez que el servidor esté en funcionamiento (ya sea manualmente mediante node src/main.ts o iniciado por el cliente de IA mediante el archivo de configuración) y conectado a tu cliente de IA, podrás interactuar con tus datos de WhatsApp a través de la interfaz de chat del agente. Pídele que busque contactos, enumere chats recientes, lea mensajes o los envíe.
Descripción general de la arquitectura
Esta aplicación es un único proceso Node.js que:
Utiliza
@whiskeysockets/baileyspara conectarse a la API web de WhatsApp, manejando la autenticación y los eventos en tiempo real.Almacena los chats y mensajes de WhatsApp localmente en una base de datos SQLite (
./data/whatsapp.db) usandonode:sqlite.Ejecuta un servidor MCP usando
@modelcontextprotocol/sdkque escucha solicitudes de un cliente AI a través de entrada/salida estándar (stdio).Proporciona herramientas MCP que consultan la base de datos SQLite local o utilizan el socket Baileys para enviar mensajes.
Utiliza
pinopara registrar la actividad (wa-logs.txtpara eventos de WhatsApp,mcp-logs.txtpara la actividad del servidor MCP).
Almacenamiento de datos y privacidad
Autenticación: Sus credenciales de conexión de WhatsApp se almacenan localmente en el directorio
./auth_info/.Mensajes y chats: su historial de mensajes y los metadatos del chat se almacenan localmente en el archivo SQLite
./data/whatsapp.db.Datos locales: Tanto
auth_info/comodata/se incluyen en.gitignorepara evitar confirmaciones accidentales. Estos directorios se consideran confidenciales.Interacción LLM: Los datos solo se envían al Modelo de Lenguaje Grande (LLM) conectado cuando el agente de IA utiliza activamente una de las herramientas MCP proporcionadas (p. ej.,
list_messagesosend_message). El servidor no envía sus datos de forma proactiva a ningún otro lugar.
Detalles técnicos
Lenguaje: TypeScript
Tiempo de ejecución: Node.js (>= v23.10.0)
API de WhatsApp:
@whiskeysockets/baileysSDK de MCP:
@modelcontextprotocol/sdkBase de datos:
node:sqlite(SQLite incluido)Registro:
pinoValidación de esquema:
zod(para entradas de la herramienta MCP)
Solución de problemas
Problemas con el código QR:
Si el enlace del código QR no se abre automáticamente, verifique la salida de la consola para la URL de
quickchart.ioy ábrala manualmente.Asegúrese de escanear el código QR inmediatamente con la aplicación WhatsApp de su teléfono.
Errores de autenticación/Cierre de sesión:
Si la conexión se cierra con un error
DisconnectReason.loggedOut, deberá volver a autenticarse. Detenga el servidor, elimine el directorio./auth_info/y reinicie el servidor (node src/main.ts) para obtener un nuevo código QR.
Problemas de sincronización de mensajes:
La sincronización inicial puede tardar un poco. Consulta la actividad
wa-logs.txt.Si los mensajes parecen desincronizados o faltan, es posible que necesite un reinicio completo. Detenga el servidor, elimine los directorios
./auth_info/y./data/y, a continuación, reinicie el servidor para volver a autenticar y sincronizar el historial.
Problemas de conexión MCP (Claude/Cursor):
Verifique el
commandyargs(especialmente{{PATH_TO_REPO}}) enclaude_desktop_config.jsonomcp.json. Asegúrese de que la ruta sea absoluta y correcta.Verifique que Node.js esté instalado correctamente y en la RUTA de su sistema.
Verifique los registros del cliente AI para ver si hay errores relacionados con el inicio del servidor MCP.
Consulte los registros de este servidor (
mcp-logs.txt) para ver si hay errores relacionados con MCP.
Errores al enviar mensajes:
Asegúrese de que el JID del destinatario sea correcto (por ejemplo,
number@s.whatsapp.netpara usuarios,groupid@g.uspara grupos).Consulte
wa-logs.txtpara ver errores específicos de Baileys.
Problemas generales: consulte
wa-logs.txtymcp-logs.txtpara obtener mensajes de error detallados.
Para más problemas de integración de MCP, consulte la documentación oficial de MCP .
Créditos
https://github.com/lharries/whatsapp-mcp Haga lo mismo que esta base de código pero use Go y Python.
Licencia
Este proyecto está licenciado bajo la licencia ISC (ver package.json ).
Available Tools
7 toolsget_chatD
| Name | Required | Description | Default |
|---|---|---|---|
| chat_jid | Yes | The JID of the chat to retrieve | |
| include_last_message | No | Include last message details (default true) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_message_contextD
| Name | Required | Description | Default |
|---|---|---|---|
| message_id | Yes | The ID of the target message to get context around | |
| before | No | Number of messages before (default 5) | |
| after | No | Number of messages after (default 5) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
list_chatsD
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | Max chats per page (default 20) | |
| page | No | Page number (0-indexed, default 0) | |
| sort_by | No | Sort order: 'last_active' (default) or 'name' | last_active |
| query | No | Optional filter by chat name or JID | |
| include_last_message | No | Include last message details (default true) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
list_messagesD
| Name | Required | Description | Default |
|---|---|---|---|
| chat_jid | Yes | The JID of the chat (e.g., '123456@s.whatsapp.net' or 'group@g.us') | |
| limit | No | Max messages per page (default 20) | |
| page | No | Page number (0-indexed, default 0) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
search_contactsD
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | Search term for contact name or phone number part of JID |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
search_messagesD
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | The text content to search for within messages | |
| chat_jid | No | Optional: The JID of a specific chat to search within (e.g., '123...net' or 'group@g.us'). If omitted, searches all chats. | |
| limit | No | Max messages per page (default 10) | |
| page | No | Page number (0-indexed, default 0) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
send_messageD
| Name | Required | Description | Default |
|---|---|---|---|
| recipient | Yes | Recipient JID (user or group, e.g., '12345@s.whatsapp.net' or 'group123@g.us') | |
| message | Yes | The text message to send |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
7 tool updates
- First observed
get_chat - First observed
get_message_context - First observed
list_chats - First observed
list_messages - First observed
search_contacts - First observed
search_messages - First observed
send_message
TDQS
Scored across 7 tools
The tools are mostly distinct in purpose, with clear separation between chat operations (get_chat, list_chats), message operations (list_messages, search_messages, send_message), and contact operations (search_contacts). However, get_message_context and get_chat could potentially overlap in functionality if both retrieve chat data, creating minor ambiguity.
All tool names follow a consistent verb_noun pattern with snake_case throughout (e.g., get_chat, list_messages, search_contacts). There are no deviations in naming conventions, making the set predictable and readable.
With 7 tools, this server is well-scoped for a WhatsApp integration, covering core functionalities like retrieving chats, messages, contacts, and sending messages. The count is appropriate, neither too sparse nor bloated, allowing comprehensive interaction without overwhelming complexity.
The toolset covers basic read and send operations for chats, messages, and contacts, but lacks update or delete capabilities (e.g., no update_message or delete_chat). This creates notable gaps in lifecycle coverage, though agents can still perform core messaging workflows.
Maintenance
Related MCP Connectors
WhatsMCP connects Claude and other MCP-compatible AI agents directly to WhatsApp. Send and receive text, images, documents, and voice notes; manage groups (create, add/remove members, promote admins); look up contacts and profiles; follow channels; and read call and message history — all through a standard MCP interface. For voice use cases, WhatsMCP offers SIP-based calling plans (inbound-only, or full inbound/outbound) so AI voice agents can answer and place WhatsApp calls, plus low-latency WebSocket integrations with voice agent providers like ElevenLabs. Multiple WhatsApp accounts can be paired and managed per workspace, with webhook support for real-time inbound message delivery to your own infrastructure.
Ask questions across your WhatsApp inbox from Claude, ChatGPT, Cursor or any MCP client.
Your own WhatsApp as an MCP server: read, search and send from any MCP client.
Let Claude or ChatGPT search, read and send your WhatsApp messages over MCP. OAuth sign-in.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables interaction with WhatsApp through local stdio or remote HTTP/SSE connections. It allows users to send messages, manage groups, and access chat history using natural language.26 npm3MIT
- FlicenseNot gradedqualityNot gradedmaintenanceA self-hosted MCP server that connects AI clients to WhatsApp via the WAHA HTTP API. It enables users to manage sessions, search contacts, and send or receive messages and media directly through natural language interfaces.6 npm-
- AlicenseNot gradedqualityCmaintenanceMCP server that connects AI agents to WhatsApp using the multi-device API, enabling messaging, group management, and more as a regular user.7 npmMIT
- AlicenseNot gradedqualityDmaintenanceAn MCP server that connects Claude and other LLM clients to WhatsApp via the Baileys library. Enables sending and receiving messages, listing chats, downloading media, and more.13 npmMIT