API Documentation

Complete guide to using MessageAgentKit API and MCP Server

Overview

MessageAgentKit provides a REST API and MCP (Model Context Protocol) server for integrating WhatsApp messaging capabilities into your applications. The API allows you to send text messages, template messages, schedule messages for approval, and retrieve message history.

Base URL: https://your-domain.com

Authentication

All API requests require authentication using a Bearer token in the Authorization header.

REST API Authentication

Authorization: Bearer YOUR_API_TOKEN

MCP Server Authentication

When calling MCP tools, include your API token as the api_token parameter in the tool arguments.

{
  "tool": "send_text_message",
  "arguments": {
    "api_token": "YOUR_API_TOKEN",
    "to": "5511999999999",
    "text": "Hello!"
  }
}
⚠️ Security Best Practice: Never expose your API token in client-side code. Always use environment variables or secure server-side storage.

API Endpoints

POST/api/messages/text

Send a simple text message to a WhatsApp number.

Request Body

{
  "to": "5511999999999",
  "text": "Hello from MessageAgentKit!"
}

Parameters

ParameterTypeRequiredDescription
tostringYesWhatsApp number in E.164 format (country code + number, no + or spaces)
textstringYesMessage content (max 4096 characters)

Response

{
  "messaging_product": "whatsapp",
  "contacts": [...],
  "messages": [
    {
      "id": "wamid.xxx"
    }
  ]
}
POST/api/messages/template

Send a WhatsApp template message (must be pre-approved by WhatsApp).

Request Body

{
  "to": "5511999999999",
  "template_name": "hello_world",
  "language": "en_US",
  "components": []
}

Parameters

ParameterTypeRequiredDescription
tostringYesWhatsApp number in E.164 format
template_namestringYesName of your approved WhatsApp template
languagestringYesLanguage code (e.g., en_US, pt_BR, es_ES)
componentsarrayNoTemplate components for dynamic parameters
POST/api/messages/schedule/text

Schedule a text message for later approval. The message will appear in the dashboard for review before being sent.

Request Body

{
  "to": "5511999999999",
  "text": "Scheduled message",
  "scheduled_for": "2025-01-20T10:00:00Z"
}

Parameters

ParameterTypeRequiredDescription
tostringYesWhatsApp number in E.164 format
textstringYesMessage content
scheduled_forstringYesISO 8601 date string for when to send the message
POST/api/messages/schedule/template

Schedule a template message for later approval.

Request Body

{
  "to": "5511999999999",
  "template_name": "hello_world",
  "language": "en_US",
  "components": [],
  "scheduled_for": "2025-01-20T10:00:00Z"
}
GET/api/messages/list

Retrieve the last 1000 messages sent through the API.

Response

{
  "messages": [
    {
      "sent_at": "2025-01-15 10:30:00",
      "message_type": "text",
      "recipient": "5511999999999",
      "message_content": "Hello!",
      "status": "sent",
      "whatsapp_message_id": "wamid.xxx"
    }
  ]
}
GET/api/messages/scheduled

List scheduled messages with optional filters.

Query Parameters

ParameterTypeDescription
statusstringFilter by status: pending, approved, sent, failed, cancelled
searchstringSearch in recipient or message content
start_datestringFilter by scheduled date (ISO 8601)
end_datestringFilter by scheduled date (ISO 8601)
POST/api/messages/scheduled/approve

Approve and send multiple scheduled messages.

Request Body

{
  "message_ids": ["uuid1", "uuid2", "uuid3"]
}

API Analytics Endpoint

Get comprehensive analytics data for building charts and dashboards. Perfect for Lovable integration.

GET/api/analytics/usage

Returns analytics data including daily message counts, hourly heatmap, totals, and success rate. Lovable can automatically build message analytics charts using this endpoint.

Query Parameters

ParameterTypeRequiredDescription
rangestringNoTime range: 7d, 30d, 90d (default: 7d)

Request Example

GET https://your-domain.com/api/analytics/usage?range=7d
Authorization: Bearer YOUR_API_TOKEN

Response

{
  "totalMessages": 34,
  "daily": [
    {
      "date": "2025-01-15",
      "count": 10,
      "sent": 9,
      "failed": 1
    },
    {
      "date": "2025-01-16",
      "count": 24,
      "sent": 24,
      "failed": 0
    }
  ],
  "hourlyHeatmap": [
    {
      "hour": 9,
      "dayOfWeek": 1,
      "count": 5
    },
    {
      "hour": 14,
      "dayOfWeek": 1,
      "count": 8
    }
  ],
  "successRate": 0.97
}

Response Fields

FieldTypeDescription
totalMessagesnumberTotal number of messages in the specified range
dailyarrayArray of daily message counts with sent/failed breakdown
hourlyHeatmaparrayArray of hourly message counts by day of week (1=Monday, 7=Sunday)
successRatenumberSuccess rate as decimal (0.0 to 1.0)
💡 Lovable Integration: This endpoint is designed for Lovable to automatically build message analytics charts and dashboards. Just use the endpoint and Lovable handles the rest!

MCP Tools

The MCP Server exposes tools that can be called by AI agents (Claude, GPT, etc.) to interact with WhatsApp. All tools require an api_token parameter.

send_text_message

Send a text message immediately.

Parameters

ParameterTypeRequiredDescription
api_tokenstringYesYour API token
tostringYesWhatsApp number in E.164 format
textstringYesMessage content

send_template_message

Send a template message immediately.

Parameters

ParameterTypeRequiredDescription
api_tokenstringYesYour API token
tostringYesWhatsApp number in E.164 format
template_namestringYesName of approved template
languagestringYesLanguage code
componentsarrayNoTemplate components

schedule_text_message

Schedule a text message for later approval.

Parameters

Same as send_text_message plus:

  • scheduled_for (string, required): ISO 8601 date string

schedule_template_message

Schedule a template message for later approval.

Parameters

Same as send_template_message plus:

  • scheduled_for (string, required): ISO 8601 date string

Best Practices

Phone Number Format

Always use E.164 format for phone numbers. This means:

  • Include country code (without +)
  • No spaces, dashes, or special characters
  • Example: 5511999999999 for Brazil (+55 11 99999-9999)

Error Handling

Always implement proper error handling:

try {
  const response = await fetch('https://your-domain.com/api/messages/text', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_TOKEN',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ to: '5511999999999', text: 'Hello' })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || 'Request failed');
  }

  const data = await response.json();
  console.log('Message sent:', data.messages[0].id);
} catch (error) {
  console.error('Error sending message:', error);
  // Handle error appropriately
}

Rate Limiting

WhatsApp Business API has rate limits. Be mindful of:

  • Message sending rate (varies by account tier)
  • Template message approval process
  • 24-hour messaging window for conversations

Message Scheduling

Use scheduled messages for:

  • Campaigns that need approval before sending
  • Bulk messaging with review workflow
  • Compliance and audit requirements

Security

  • Never commit API tokens to version control
  • Use environment variables for sensitive data
  • Rotate API tokens periodically
  • Validate user input before sending messages
  • Implement rate limiting on your side

Error Handling

All endpoints return standard HTTP status codes:

Status CodeDescription
200Success
201Created (for scheduled messages)
400Bad Request (missing or invalid parameters)
401Unauthorized (invalid or missing API token)
404Not Found
500Internal Server Error

Error Response Format

{
  "error": "Error message description"
}

Common Errors

Invalid phone number format

Ensure phone numbers are in E.164 format without + or spaces.

Template not approved

Templates must be approved by WhatsApp before use.

Rate limit exceeded

You've exceeded the messaging rate limit. Wait before retrying.

Code Examples

JavaScript/Node.js

const sendWhatsAppMessage = async (to, text) => {
  const response = await fetch('https://your-domain.com/api/messages/text', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.WHATSAPP_API_TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ to, text })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error);
  }

  return await response.json();
};

// Usage
try {
  const result = await sendWhatsAppMessage('5511999999999', 'Hello!');
  console.log('Message ID:', result.messages[0].id);
} catch (error) {
  console.error('Failed to send message:', error.message);
}

Python

import requests
import os

def send_whatsapp_message(to, text):
    url = 'https://your-domain.com/api/messages/text'
    headers = {
        'Authorization': f'Bearer {os.getenv("WHATSAPP_API_TOKEN")}',
        'Content-Type': 'application/json'
    }
    data = {'to': to, 'text': text}
    
    response = requests.post(url, json=data, headers=headers)
    response.raise_for_status()
    return response.json()

# Usage
try:
    result = send_whatsapp_message('5511999999999', 'Hello!')
    print(f"Message ID: {result['messages'][0]['id']}")
except requests.exceptions.RequestException as e:
    print(f"Failed to send message: {e}")

cURL

curl -X POST https://your-domain.com/api/messages/text \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "5511999999999",
    "text": "Hello from MessageAgentKit!"
  }'

MCP Tool Call Example

{
  "tool": "send_text_message",
  "arguments": {
    "api_token": "YOUR_API_TOKEN",
    "to": "5511999999999",
    "text": "Hello from MCP!"
  }
}