networkerman/whatsapp-cloud-api-mcp-server
If you are the rightful owner of whatsapp-cloud-api-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
This is a comprehensive MCP server providing full access to WhatsApp Cloud API capabilities.
WhatsApp Cloud API MCP Server
⚠️ NEW: Claude Usage Guide for WhatsApp Templates – Ensure Meta-compliant messages with strict MCP validation
A clean, simple MCP (Model Context Protocol) server that provides comprehensive access to the WhatsApp Cloud API capabilities, including messaging, templates, business management, and media handling.
Author
Udayan Das Chowdhury
Lead Product Manager driving Omnichannel Product Management at Netcore Cloud
LinkedIn: @udayan-das-chowdhury8329
Features
🚀 Complete WhatsApp Cloud API Coverage
- Text Messaging - Send text messages with URL previews and replies
- Media Messaging - Send images, videos, audio, documents, and stickers
- Interactive Messages - Send buttons and list messages
- Location & Contacts - Send location pins and contact cards
- Message Reactions - React to messages with emojis
- Template Management - Create, manage, and send template messages
- Business Profile - Manage business profile information
- Phone Number Management - Register and verify phone numbers
- Media Upload - Upload and manage media files
- Message Status - Mark messages as read and track delivery
- Advanced Features - WhatsApp Flows, Analytics, Webhooks, Business Account Management
📱 Based on Official API
Built from the official WhatsApp Cloud API Postman collection, ensuring 100% API compatibility and coverage.
🧪 Comprehensive Testing Suite
Includes a rigorous QA testing framework with 50+ test cases covering:
- Stress Testing - Multiple message types, concurrent requests
- Edge Case Testing - Unicode, long messages, invalid inputs
- Performance Benchmarking - Response time monitoring
- Error Handling - Graceful error management
- API Coverage - All endpoints and features tested
🔍 Claude Integration for Template Validation
Prompt Claude with structured inputs to auto-generate templates that pass Meta's strict format checks (e.g., character limits, emoji usage, formatting rules).
🚀 Quick Start
Prerequisites
- Python 3.10 or higher - Required for MCP support
- Meta WhatsApp Business API credentials - Get these from Meta Business
Step-by-Step Installation
-
Clone the repository:
git clone <your-repo-url> cd whatsapp-cloud-api-mcp-server -
Set up environment variables:
# Create virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install dependencies pip install -r requirements.txt -
Configure environment variables:
Option A: Railway Deployment (Recommended)
- Set environment variables in Railway.app dashboard
- Deploy automatically with
main_http.py
Option B: Local Development
- Use the provided
run_server.shwrapper script - All environment variables are configured in the script
-
🧪 Run comprehensive QA tests (optional):
# Run rigorous QA testing python rigorous_qa_test.py # Quick setup verification python test_setup.py
🧠 Claude Usage Guide for WhatsApp Business API MCP
🚀 NEW: Claude Setup & Prompt for WhatsApp Template Validation with MCP
This section outlines how to use Claude AI with the WhatsApp Business API MCP for creating Meta-compliant templates with strict validation. It ensures that every message template you generate adheres to the latest Meta WhatsApp Business API constraints.
🛠 Claude Setup Prompt
Copy and paste this to Claude when working on WhatsApp templates:
You now have access to WhatsApp Business API MCP tools with strict validation built-in. These tools enforce Meta's constraints and will prevent you from creating invalid templates.
Critical Constraints You Must Follow
Character Limits (Strictly Enforced):
- Body text: 550 characters maximum
- Header text: 60 characters
- Footer text: 60 characters
- Button text: 20 characters each
Content Rules:
- Max 10 emojis total (across all parts of the template)
- No consecutive line breaks (\n\n disallowed)
- Formatting syntax: bold, italic,
strike,mono - Button text: Plain text only — no emojis, formatting, or variables
Template Types & Button Limits:
- Marketing/Utility: Max 10 buttons total
- Carousel: Max 2 buttons per card, identical button structure on all cards
- Authentication: Only 1 OTP button, fixed format
How to Use
✅ Provide complete instructions: "Create a carousel template for 3 products with variables for product name and price, plus quick reply and URL buttons."
✅ Include realistic example values: "Variable {{1}} = 'Premium Coffee Beans'" (not "Product Name")
✅ Specify valid button combinations: Example: [QUICK_REPLY + URL] on all carousel cards
📛 Handling Validation Errors
The MCP will return structured error messages when something breaks:
{
"errors": [
{
"field": "body_text",
"issue": "Exceeds character limit",
"current": 623,
"limit": 550,
"fix": "Reduce by 73 characters"
}
]
}
🚫 Don't guess — follow the exact feedback.
🔐 Special Rules: Authentication Templates
- Copy Code: Simple OTP with a copy button
- One-Tap: Android autofill (needs app package + hash)
- Zero-Tap: Android broadcast OTP
All use: {{1}} is your verification code
✅ MCP Enforces:
- Character & emoji limits
- Formatting correctness
- Button validation (combo & count)
- Structural & variable-example consistency
❌ MCP Cannot Check:
- Brand tone or content quality
- Cultural/contextual appropriateness
- Meta approval probability
🧩 Best Practices
- Start with template type (marketing, utility, auth, carousel)
- Keep body ≤ 550 characters
- Use ≤ 10 emojis
- Avoid \n\n
- Use realistic placeholder values
- Respect button structure rules
💡 Example Claude Request
Good: "Create a utility template for order confirmations with variables {{1}} (customer name) and {{2}} (order number). Include a URL button. Stay under 550 characters."
Bad: "Make a confirmation template"
⚙️ About This Project
This MCP (Model Context Protocol) system was created to streamline WhatsApp Cloud API template generation and enforce Meta's compliance constraints programmatically.
🧠 Built by:
Udayan Das Chowdhury, Lead Product Manager @ Netcore Cloud
Specializing in CPaaS (WhatsApp, RCS, SMS) and API-first MarTech infrastructure.
LinkedIn
🔍 SEO Keywords (for better discovery)
Searchable terms for developers & product managers:
- WhatsApp Business API template generator
- WhatsApp Cloud API MCP
- WhatsApp Claude prompt
- WhatsApp template validator
- Meta compliant WhatsApp messages
- WhatsApp MCP server Python
- WhatsApp MCP for Claude AI
- Meta template character limit
- Carousel WhatsApp template rules
- WhatsApp Marketing template creation
- OTP template WhatsApp validation
🎯 Claude Desktop Integration
Claude can now be prompted with strict validation rules for WhatsApp template creation. See Claude Usage Guide above.
-
Create Claude configuration:
{ "mcpServers": { "whatsapp": { "command": "/path/to/whatsapp-cloud-api-mcp-server/run_server.sh", "args": [], "env": { "HOME": "/Users/your-username", "LOGNAME": "your-username", "PATH": "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin", "SHELL": "/bin/zsh", "TERM": "xterm-256color", "USER": "your-username" } } } } -
Restart Claude Desktop and test WhatsApp tools
🧪 Testing with MCP Inspector
# List all available tools
npx @modelcontextprotocol/inspector --cli "/path/to/run_server.sh" --method tools/list
# List all available resources
npx @modelcontextprotocol/inspector --cli "/path/to/run_server.sh" --method resources/list
# Test a specific tool
npx @modelcontextprotocol/inspector --cli "/path/to/run_server.sh" --method tools/call --tool-name get_message_templates
Troubleshooting Connection Issues
If you're getting "Server disconnected" errors when connecting to Claude, run the diagnostic script:
python diagnose.py
This will check your setup and identify common issues like:
- Python version incompatibility - MCP requires Python 3.10+
- Missing environment variables - Required WhatsApp API credentials
- Missing dependencies - Required Python packages
- Configuration errors - Invalid API credentials
🔧 Common ID-Related Issues
Problem: "Tried accessing nonexisting field (message_templates) on node type (Business)"
- Solution: You're using WABA ID instead of Meta Business Account ID for templates
- Fix: Set
META_BUSINESS_ACCOUNT_IDto your Meta Business Account ID (not WABA ID)
Problem: "Tried accessing nonexisting field (phone_numbers) on node type (Business)"
- Solution: You're using Meta Business Account ID instead of WABA ID for phone operations
- Fix: Set
WABA_IDto your WhatsApp Business Account ID (not Meta Business Account ID)
Problem: Some endpoints work but others don't
- Solution: You need BOTH IDs set correctly
- Fix: Ensure both
META_BUSINESS_ACCOUNT_IDandWABA_IDare set to their respective correct values
Quick fixes:
# 1. Check your setup
python diagnose.py
# 2. If Python version is wrong (3.9.x), upgrade:
brew install python@3.12
# 3. If missing .env file:
python setup.py
# 4. If missing dependencies:
pip install mcp httpx python-dotenv
# 5. Run diagnostic again
python diagnose.py
For detailed troubleshooting, see .
Environment Variables
Set up your WhatsApp Business API credentials:
# 🔑 REQUIRED for all operations
META_ACCESS_TOKEN=your_access_token_here
META_PHONE_NUMBER_ID=your_phone_number_id_here
# 🔑 CRITICAL: You need BOTH IDs for full functionality
META_BUSINESS_ACCOUNT_ID=your_meta_business_account_id_here # For templates and business operations
WABA_ID=your_waba_id_here # For phone numbers and WABA operations
# 🆔 NEW: APP ID for advanced features (optional but recommended)
META_APP_ID=your_meta_app_id_here
# 📱 Testing phone number (optional)
TEST_PHONE_NUMBER=your_test_phone_number_here
# Optional - API version (defaults to v22.0)
WHATSAPP_API_VERSION=v22.0
🔍 How to Find Your IDs
-
Meta Business Account ID:
- Go to Meta Business Manager
- Navigate to Business Settings → Business Info
- Copy the "Business ID" (this is your Meta Business Account ID)
-
WABA ID (WhatsApp Business Account ID):
- Go to Meta Business Manager
- Navigate to All Tools → WhatsApp → API Setup
- Copy the "WhatsApp Business Account ID" (this is your WABA ID)
-
Phone Number ID:
- In the same WhatsApp API Setup page
- Under "Phone numbers", copy the "Phone number ID"
-
Access Token:
- In WhatsApp API Setup, under "Access tokens"
- Generate or copy your permanent access token
-
🆔 APP ID (NEW):
- Go to Meta for Developers
- Navigate to My Apps → Your App
- Copy the "App ID" from the app dashboard
- This enables advanced features like Flows and enhanced analytics
⚠️ Important Notes
- Both IDs are different and serve different purposes
- Meta Business Account ID is used for templates and business profile operations
- WABA ID is used for phone number operations and WABA-specific features
- APP ID enables advanced features like WhatsApp Flows and enhanced analytics
- Setting all three ensures maximum compatibility with all WhatsApp Cloud API features
🧪 Testing Your Setup
Quick Health Check
# Test basic functionality
python diagnose.py
Quick Setup Verification
# Run quick setup test (recommended for new users)
python test_setup.py
Comprehensive QA Testing
# Run the rigorous QA test suite
python rigorous_qa_test.py
The QA test suite includes:
- 40+ individual test cases
- Stress testing with multiple message types
- Concurrent request testing
- Performance benchmarking
- Error handling validation
- API coverage verification
Expected Test Results
- Success Rate: 100% (all tests should pass)
- Performance: Average response time < 5 seconds
- Coverage: All major API endpoints tested
Running the Server
Standalone Mode
python main.py
HTTP Server Mode (for deployment)
python main_http.py
Integration with Claude Desktop
Add to your Claude configuration:
{
"mcpServers": {
"whatsapp": {
"command": "/path/to/your/project/venv/bin/python",
"args": ["main.py"],
"cwd": "/path/to/your/project",
"env": {
"META_ACCESS_TOKEN": "your-token-here",
"META_PHONE_NUMBER_ID": "your-phone-id-here",
"META_BUSINESS_ACCOUNT_ID": "your-business-account-id-here",
"WABA_ID": "your-waba-id-here",
"META_APP_ID": "your-app-id-here"
}
}
}
}
Available Tools
📝 Text Messaging
send_whatsapp_message- Basic text message (legacy compatibility)send_text_message- Advanced text message with URL previews and repliessend_reaction- React to messages with emojis
🖼️ Media Messaging
send_image_message- Send images with captionssend_video_message- Send videos with captionssend_audio_message- Send audio filessend_document_message- Send documents with filenamessend_sticker_message- Send sticker messages
🎯 Interactive Messaging
send_button_message- Send messages with interactive buttonssend_list_message- Send messages with selectable lists
📍 Location & Contacts
send_location_message- Send location pins with names and addressessend_contact_message- Send contact cards
📋 Template Management
get_message_templates- List all templates with filteringcreate_message_template- Create new template messagesdelete_message_template- Delete existing templatessend_template_message- Send template messages with parameterssend_template_with_media_header- Send templates with media headers
📁 Media Management
upload_media- Upload media files and get media IDsget_media_info- Get information about uploaded mediadelete_media- Delete uploaded media files
🏢 Business Management
get_business_profile- Get business profile informationupdate_business_profile- Update business profile detailsget_phone_numbers- List all business phone numbersget_phone_number_info- Get detailed phone number informationregister_phone_number- Register phone numbers with 2FAverify_phone_number- Verify phone numbers with codes
🔄 Advanced Features (requires APP ID)
list_flows- List WhatsApp Flowscreate_flow- Create new WhatsApp Flowsget_flow- Get specific flow detailsget_analytics- Get analytics dataget_webhook_subscriptions- Manage webhook subscriptionsget_business_accounts- Manage business accounts
⚙️ Utility Functions
mark_message_as_read- Mark received messages as read
Available Resources
📚 Dynamic Resources
resource://contacts- Sample contact listresource://templates- Live template data from your accountresource://business_profile- Current business profile information
Usage Examples
Send a Text Message
await send_text_message(
phone_number="+1234567890",
message="Hello from WhatsApp Cloud API!",
preview_url=True
)
Send a Template Message
await send_template_message(
phone_number="+1234567890",
template_name="hello_world",
language_code="en_US",
body_parameters=["John", "Welcome!"]
)
Send an Interactive Button Message
await send_button_message(
phone_number="+1234567890",
body_text="Choose an option:",
buttons=[
{"title": "Option 1", "id": "opt1"},
{"title": "Option 2", "id": "opt2"}
],
header_text="Please select"
)
Upload and Send Media
# Upload media
media_result = await upload_media(
file_path="/path/to/image.jpg",
media_type="image"
)
# Send media message
await send_image_message(
phone_number="+1234567890",
image_id=media_result["data"]["id"],
caption="Check out this image!"
)
Create a Template
await create_message_template(
name="welcome_template",
category="UTILITY",
language="en_US",
body_text="Welcome {{1}}! Your order {{2}} is confirmed.",
header_text="Order Confirmation",
footer_text="Thank you for your business"
)
Create a WhatsApp Flow (requires APP ID)
await create_flow(
name="Customer Support Flow",
categories=["SIGN_UP", "UTILITY"]
)
Project Structure
whatsapp-cloud-api-mcp-server/
├── main.py # Server entry point
├── main_http.py # HTTP server for deployment
├── comprehensive_tools.py # All tool definitions
├── comprehensive_tools_extended.py # Advanced features
├── rigorous_qa_test.py # Comprehensive QA testing suite
├── mcp_server/ # Core modules
│ ├── __init__.py # Module initialization
│ ├── base_handler.py # Base WhatsApp handler
│ ├── messaging_handler.py # Messaging operations
│ ├── template_handler.py # Template operations
│ ├── business_handler.py # Business operations
│ ├── media_handler.py # Media operations
│ ├── flow_handler.py # Flow operations
│ ├── analytics_handler.py # Analytics operations
│ ├── webhook_handler.py # Webhook operations
│ ├── business_account_handler.py # Business account operations
│ └── models.py # Data models
├── setup.py # Setup script
├── diagnose.py # Diagnostic script
├── test_setup.py # Quick setup verification
├── requirements.txt # Project dependencies
├── pyproject.toml # Project configuration
└── .env # Environment variables (not versioned)
🧪 Testing Framework
The project includes a comprehensive testing framework (rigorous_qa_test.py) that provides:
Test Coverage
- 50+ individual test cases
- Stress testing with multiple message types
- Concurrent request testing
- Performance benchmarking
- Error handling validation
- API coverage verification
Running Tests
# Install testing dependencies
pip install requests python-dotenv
# Run comprehensive QA tests
python rigorous_qa_test.py
# Test with custom URL
python rigorous_qa_test.py https://your-custom-url.com
Expected Results
- Success Rate: 100% (all tests should pass)
- Performance: Average response time < 5 seconds
- Coverage: All major API endpoints tested
🎯 Current Status & Future Plans
✅ Production Ready
- ✅ Claude Desktop Integration: Fully working with 50+ WhatsApp tools
- ✅ Railway Deployment: Live at
https://whatsapp-cloud-api-mcp-server-production.up.railway.app/ - ✅ MCP Inspector Testing: All tools and resources verified
- ✅ Comprehensive QA Suite: 50+ test cases passing
- ✅ Environment Management: Proper configuration for both local and cloud deployment
🚀 Future Enhancements
- SSE (Server-Sent Events) Support: For real-time message delivery
- Enhanced Error Handling: More granular error responses
- Rate Limiting: Built-in API rate limit management
- Webhook Validation: Enhanced webhook security
- Multi-tenant Support: Support for multiple WhatsApp Business accounts
🔒 Stability Notes
- Current version is production-stable
- All changes are backward compatible
- Environment variables are properly isolated
- Deployment configurations are optimized
Contributing
Contributions are welcome! Feel free to open issues or submit pull requests.
⚠️ Important: Before making changes, please:
- Test thoroughly with the QA suite
- Ensure backward compatibility
- Update documentation accordingly
License
This project is licensed under the MIT License.