Skip to main content
Glama
yulianheroes-lgtm

WhatsApp Claude MCP

WhatsApp Claude MCP

一个功能强大的 WhatsApp 机器人,通过 Model Context Protocol (MCP) 与 Claude AI 集成。向你的 WhatsApp 机器人发送消息,即可获得由 Claude 驱动的智能回复,并能访问外部 API 和工具。

🌟 主要功能

  • Claude AI 集成:使用 Claude 3.5 Sonnet 进行智能对话

  • MCP 工具:可扩展的工具系统,让 Claude 与外部 API 交互

  • 笑话生成器:内置工具,可从外部 API 获取随机笑话

  • 对话记忆:为每个用户维护多轮上下文的往返

  • WhatsApp Webhook:用于与 WhatsApp 服务集成的简单 REST API

  • 轻松部署:基于 express 服务器,方便部署到云端

Related MCP server: WAHA WhatsApp MCP Server

📋 环境准备

  • Node.js 18+

  • npm 或 yarn

  • Anthropic API 密钥(可在 console.anthropic.com 获取)

  • WhatsApp Cloud API 访问权限(用于生产接入)

🚀 快速开始

1. 克隆并安装

git clone https://github.com/yulianheroes-lgtm/whatsapp-claude-mcp.git
cd whatsapp-claude-mcp
npm install

2. 设置环境变量

cp .env.example .env

编辑 .env 并添加你的 Anthropic API 密钥:

ANTHROPIC_API_KEY=your_anthropic_api_key_here
PORT=3000

3. 启动服务

npm start

你应该会看到:

✅ WhatsApp Claude MCP Server running on http://localhost:3000
🤖 Ready to process WhatsApp messages!

📡 API 使用方法

健康检查

curl http://localhost:3000/health

发送消息给 Claude

curl -X POST http://localhost:3000/webhook/whatsapp \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "1234567890",
    "message": "Tell me a joke"
  }'

响应:

{
  "success": true,
  "userId": "1234567890",
  "message": "😂 Here's a programming joke for you!\n\nWhy do programmers prefer dark mode?\n\nBecause light attracts bugs! 🐛"
}

清除会话记录

curl -X POST http://localhost:3000/webhook/clear-history \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "1234567890"
  }'

🛠️ 可用工具

笑话生成器

Claude 会在合适的时候自动使用该工具:

  • 触发条件:时长用户请求讲笑话

  • 类型:random、programming、general

  • API:Official Joke API

交互示例:

User: Tell me a funny programming joke
Bot: [Uses joke_generator tool] 😂 Here's a programming joke...

📁 项目结构

whatsapp-claude-mcp/
├── src/
│   ├── index.js              # Main Express server
│   ├── whatsapp-handler.js   # Message handling & Claude integration
│   ├── mcp-server.js         # MCP tool definitions & execution
│   └── tools/
│       └── joke-generator.js # Joke generator tool implementation
├── .env.example              # Environment variables template
├── .gitignore               # Git ignore rules
├── package.json             # Dependencies
└── README.md                # This file

🔌 与 WhatsApp 集成

方案一:WhatsApp Cloud API

生产环境请与 WhatsApp Cloud API 集成:

  1. 在 Meta 商务平台上配置 webhook

  2. 将 webhook URL 设为:https://your-domain.com/webhook/whatsapp

  3. 当 WhatsApp 收到消息时,将其转发到此端点

方案二:本地测试

可使用 curl、Postman 或测试脚本发送消息:

// test.js
const userId = '1234567890';
const message = 'Tell me a joke';

const response = await fetch('http://localhost:3000/webhook/whatsapp', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ userId, message })
});

const result = await response.json();
console.log(result.message);

🧠 工作原理

  1. 收到消息 → WhatsApp webhook 接收消息

  2. Claude 处理 → 消息与可用工具一并发送给 Claude

  3. 工具选择 → Claude 判断是否需要工具

  4. 工具执行 → MCP server 执行工具(例如获取笑话)

  5. 生成回复 → Claude 利用工具结果生成回复

  6. 消息回应 → 通过 WhatsApp 发回回复

🚀 添加更多工具

要新增工具(如天气、翻译):

1. 创建工具文件

// src/tools/weather.js
export const weatherTool = {
  name: 'get_weather',
  description: 'Get current weather for a location',
  inputSchema: {
    type: 'object',
    properties: {
      location: { type: 'string', description: 'City name' }
    }
  }
};

export async function executeWeather(location) {
  // Fetch weather data
  return { /* weather data */ };
}

2. 在 MCP Server 中注册

// src/mcp-server.js
import { weatherTool, executeWeather } from './tools/weather.js';

export class MCPServer {
  constructor() {
    this.tools = [
      jokeGeneratorTool,
      weatherTool  // Add here
    ];
  }

  async processTool(toolName, toolInput) {
    switch (toolName) {
      case 'get_weather':
        return await executeWeather(toolInput.location);
      // ...
    }
  }
}

📚 API 参考

POST /webhook/whatsapp

请求体:

{
  "userId": "string (required)",
  "message": "string (required)"
}

响应:

{
  "success": boolean,
  "userId": "string",
  "message": "string"
}

POST /webhook/clear-history

请求体:

{
  "userId": "string (required)"
}

响应:

{
  "success": boolean,
  "message": "string"
}

🔐 安全注意事项

  • API 密钥:切勿将 .env 文件提交到版本控制中

  • 限速策略:生产环境建议开启限速

  • 输入校验:始终验证 webhook 的请求负载

  • HTTPS:生产环境使用 HTTPS

  • 认证机制:为 WhatsApp 集成增加 webhook 签名验证

📝 环境变量

变量

说明

示例

ANTHROPIC_API_KEY

Claude API 密钥

sk-ant-...

PORT

服务端口

3000

NODE_ENV

运行环境

development

JOKE_API_URL

笑话 API 地址

https://official-joke-api.appspot.com/random_joke

🤝 一起贡献

欢迎 fork、修改并贡献代码!

📄 许可证

MIT License · 详情参阅 LICENSE 文件

🆘 疑难排查

"API key not found"

  • 确认 .env 文件存在,且 ANTHROPIC_API_KEY 已设置

  • 在 console.anthropic.com 检查密钥是否有效

"Tool execution failed"

  • 检查外部 API 是否可访问

  • 确认网络连接正常

  • 查看控制台输出中的日志报错

"No response from Claude"

  • 检查 ANTHROPIC_API_KEY 是否正确

  • 确认 Claude 模型可用

  • 检查 API 限速设置

📞 支持

如遇问题或有疑问:

  1. 查看以上“疑难排查”部分

  2. 阅读 Claude API 相关文档

  3. 在 GitHub 上提交 issue

🎯 未来规划

  • 支持 WhatsApp 消息中的图片/媒体

  • 增加更多工具(天气、新闻、翻译等)

  • 使用数据库存储持久化的聊天记录

  • 增加限流和身份认证

  • 提供管理后台监控面板

  • 多种语言支持

  • 支持为每个用户自定义 Claude 系统提示词


由 yulianheroes-lgtm 用 ❤️ 制作

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.

  • Let Claude or ChatGPT search, read and send your WhatsApp messages over MCP. OAuth sign-in.

  • Ask questions across your WhatsApp inbox from Claude, ChatGPT, Cursor or any MCP client.

  • Your own WhatsApp in Claude and ChatGPT: read chats, draft replies, send messages you approve.

    1

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    Enables sending, reading, and deleting WhatsApp messages through Claude Desktop and other MCP clients with granular per-chat permissions. Built on whatsapp-web.js using a headless browser to automate WhatsApp Web.
    6
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    Enables Claude to interact with WhatsApp through a unified backend API, providing 20 tools for messaging, media, groups, contacts, and chat management.
    22
    40 npm
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    A local MCP server that connects WhatsApp to Claude via QR code, enabling chat listing, message retrieval, and sending with automatic rate limiting for anti-ban protection.
    36 npm
    MIT