Skip to main content
Skip to article

#Build a WhatsApp AI Agent with MCP: Claude, ChatGPT and Custom Models

AI Agents Are Only as Powerful as Their Tools

An AI that can write a great follow-up email but cannot send it is a brainstorming partner, not an agent. The difference between a chatbot and an agent is execution -- the ability to reach into the real world and do things on your behalf.

MCP (Model Context Protocol) bridges that gap. It gives AI models a standardized way to call external tools, and MoltFlow provides 32 of those tools that cover every aspect of WhatsApp automation. The result: you describe what you want in plain English, and your AI agent handles the WhatsApp API calls, data filtering, campaign orchestration, and analytics queries on its own.

This guide walks through the full setup -- connecting MoltFlow's MCP server to Claude Desktop, Claude Code, or any MCP-compatible client -- and then shows four practical workflows you can run today.

What Is MCP (30-Second Version)

Model Context Protocol is an open standard created by Anthropic that lets AI clients connect to external tool servers. Think of it like USB for AI -- a universal interface that any AI model can use to interact with any service.

The flow is straightforward:

text
You (natural language prompt)
    |
AI Client (Claude Desktop, Claude Code, ChatGPT, custom agent)
    |  MCP protocol
MoltFlow MCP Server (32 tools)
    |  REST API
MoltFlow Backend
    |  WAHA protocol
WhatsApp

The AI client discovers available tools from the MCP server, the model decides which tools to call based on your prompt, and the results flow back into the conversation. You never write API calls -- you just ask for what you want.

MoltFlow's MCP Server: 32 Tools Across 8 Categories

MoltFlow exposes a production-ready MCP server with 32 tools covering every automation surface:

Sessions (5 tools) -- moltflow_list_sessions, moltflow_get_session, moltflow_create_session, moltflow_start_session, moltflow_get_qr_code

Messaging (3 tools) -- moltflow_send_message, moltflow_list_chats, moltflow_get_chat_messages

Groups (7 tools) -- moltflow_list_monitored_groups, moltflow_list_available_groups, moltflow_add_monitored_group, moltflow_get_group_messages, moltflow_list_custom_groups, moltflow_create_custom_group, moltflow_add_custom_group_members

Leads (2 tools) -- moltflow_list_leads, moltflow_update_lead_status

Outreach (4 tools) -- moltflow_create_bulk_send, moltflow_list_bulk_sends, moltflow_get_bulk_send_status, moltflow_create_schedule

Usage (2 tools) -- moltflow_get_current_usage, moltflow_get_plan_limits

Analytics (3 tools) -- moltflow_get_campaign_analytics, moltflow_get_contact_engagement, moltflow_get_contact_history

Channels (6 tools) -- Tools for WhatsApp Channel management including creating, broadcasting, scheduling posts, and discovery.

Every tool includes structured input validation, error handling, and response formatting. The AI model receives clean data it can reason about and present to you.

Setting Up with Claude Desktop

Claude Desktop has built-in MCP support. MoltFlow provides a hosted endpoint with OAuth 2.1 -- no local server to run.

Step 1: Add the MCP Server

Open your Claude Desktop configuration file. On macOS, that is ~/Library/Application Support/Claude/claude_desktop_config.json. On Windows, edit %APPDATA%\Claude\claude_desktop_config.json.

Add the MoltFlow server:

json
{
  "mcpServers": {
    "moltflow": {
      "url": "https://apiv2.waiflow.app/mcp"
    }
  }
}

That is the entire configuration. OAuth handles authentication -- no API key needed in the config file.

Step 2: Restart and Authenticate

Save the file and restart Claude Desktop. On first use, Claude will open your browser for a quick sign-in to your MoltFlow account. Approve the connection, and the 32 MoltFlow tools appear in the tools menu (the hammer icon).

Step 3: Verify the Connection

Type a simple prompt to confirm everything works:

"List all my WhatsApp sessions and show their connection status."

Claude will call moltflow_list_sessions and return a formatted summary. If you see your sessions, the MCP connection is live.

Setting Up with Claude Code

Claude Code (Anthropic's CLI agent) supports MCP servers natively. Register MoltFlow with one command:

bash
claude mcp add moltflow --transport http --url https://apiv2.waiflow.app/mcp

OAuth handles authentication via browser sign-in on first use. All 32 tools are immediately available in every Claude Code session.

Alternatively, you can add a .mcp.json file to your project root for team-wide configuration:

json
{
  "mcpServers": {
    "moltflow": {
      "url": "https://apiv2.waiflow.app/mcp"
    }
  }
}

Now every team member who opens the project in Claude Code gets automatic access to MoltFlow's WhatsApp tools. No individual setup required.

Once connected, you can use MoltFlow tools directly in conversation:

text
> Use MoltFlow to send a WhatsApp message to +14155551234 saying
  "Meeting confirmed for 3pm tomorrow" on my sales-team session.

Claude Code calls moltflow_send_message with:
  session: "sales-team"
  chatId: "[email protected]"
  text: "Meeting confirmed for 3pm tomorrow"

Result: Message sent successfully. ID: msg_3f8a2b...

Practical Examples

These are not hypothetical scenarios. Each one shows the exact tool calls the AI agent makes and the kind of results you get back.

Example 1: Re-Engage Cold Leads

Your prompt:

"Find all leads who haven't responded in 3 days and send each one a follow-up on my main session."

What the agent does:

  1. Calls moltflow_list_leads with a status filter to get all active leads
  2. For each lead, calls moltflow_get_contact_history to check the last response timestamp
  3. Filters to leads where the last inbound message was more than 3 days ago
  4. Calls moltflow_send_message for each cold lead with a personalized follow-up

The tool chain in action:

text
moltflow_list_leads
  -> returns 47 leads

moltflow_get_contact_history (for each lead)
  -> identifies 12 leads with no response in 3+ days

moltflow_send_message (x12)
  -> "Hi [name], just circling back on our conversation from
     last week. Are you still looking for a solution?"

Agent summary: "Sent follow-up messages to 12 leads who haven't
responded since March 12 or earlier. 35 leads had recent activity
and were skipped."

The agent handles the data retrieval, filtering logic, and message sending. You get a summary of what happened and can review the results.

Example 2: Monitor a Group for Pricing Mentions

Your prompt:

"Start monitoring our Sales Prospects group and show me any messages from the last 24 hours that mention pricing, cost, or budget."

What the agent does:

  1. Calls moltflow_list_available_groups to find the group ID for "Sales Prospects"
  2. Calls moltflow_add_monitored_group to enable monitoring with keyword triggers
  3. Calls moltflow_get_group_messages to pull recent messages with AI-powered intent analysis

The tool chain in action:

text
moltflow_list_available_groups
  -> finds "Sales Prospects" group (ID: [email protected])

moltflow_add_monitored_group
  -> session: "main"
  -> groupId: "[email protected]"
  -> keywords: ["pricing", "cost", "budget", "price", "how much"]

moltflow_get_group_messages
  -> returns messages with AI analysis (intent, lead score, confidence)

Agent summary:
  "Found 4 messages mentioning pricing in the last 24 hours:
   - Ahmed K. (score 8.2): 'What's the pricing for the enterprise tier?'
   - Maria L. (score 7.5): 'Is there a cost difference between annual and monthly?'
   - Jake R. (score 6.1): 'Budget is tight this quarter but interested'
   - Priya S. (score 5.8): 'Can you share the price list?'
   Recommended: Follow up with Ahmed and Maria first — highest intent scores."

The AI does not just retrieve data -- it analyzes intent, scores leads, and recommends next actions.

Example 3: Launch a Bulk Campaign to a Custom Group

Your prompt:

"Create a VIP Clients custom group from my contacts list, add these numbers: +14155551111, +14155552222, +14155553333, +14155554444. Then send them all a message about our new premium feature launch."

What the agent does:

  1. Calls moltflow_create_custom_group to create the "VIP Clients" group
  2. Calls moltflow_add_custom_group_members to add the four contacts
  3. Calls moltflow_create_bulk_send to launch the campaign with anti-spam delays

The tool chain in action:

text
moltflow_create_custom_group
  -> name: "VIP Clients"
  -> session: "main"
  -> returns group ID: cg_8f3a2b

moltflow_add_custom_group_members
  -> groupId: "cg_8f3a2b"
  -> members: ["14155551111", "14155552222", "14155553333", "14155554444"]
  -> 4 members added

moltflow_create_bulk_send
  -> customGroupId: "cg_8f3a2b"
  -> message: "Hi! We just launched our new Premium Analytics dashboard
     — real-time delivery tracking, engagement heatmaps, and conversion
     funnels. As a VIP client, you get early access. Reply YES for a
     personal walkthrough."
  -> campaign created, ID: bs_4c7d1e, status: sending

Agent summary: "Created 'VIP Clients' group with 4 contacts and launched
bulk campaign bs_4c7d1e. Messages are being sent with randomized delays
(8-15 seconds between each) to comply with anti-spam safeguards. Use
moltflow_get_bulk_send_status to check progress."

The anti-spam delays, typing simulation, and rate limiting all happen server-side. The agent does not need to manage any of that.

Example 4: Pull This Week's Engagement Analytics

Your prompt:

"Show me the engagement analytics for all campaigns I ran this week. Which campaign had the best read rate?"

What the agent does:

  1. Calls moltflow_list_bulk_sends to get all campaigns from the current week
  2. Calls moltflow_get_campaign_analytics for each campaign to pull delivery metrics
  3. Compares results and identifies the top performer

The tool chain in action:

text
moltflow_list_bulk_sends
  -> returns 3 campaigns from this week

moltflow_get_campaign_analytics (x3)
  -> Campaign "Spring Promo": 89% delivered, 72% read, 18% replied
  -> Campaign "Feature Update": 94% delivered, 81% read, 12% replied
  -> Campaign "VIP Follow-up": 91% delivered, 85% read, 34% replied

Agent summary:
  "This week's campaign performance:

   1. VIP Follow-up — 85% read rate, 34% reply rate (best engagement)
   2. Feature Update — 81% read rate, 12% reply rate (best delivery)
   3. Spring Promo — 72% read rate, 18% reply rate

   VIP Follow-up had the highest read rate at 85% and the highest
   reply rate at 34%. The smaller, targeted group likely drove the
   higher engagement. Consider segmenting your Spring Promo audience
   into smaller groups for better results."

The AI does not just dump numbers -- it compares, ranks, and provides actionable recommendations.

Using with ChatGPT and OpenAI Models

ChatGPT does not natively support MCP, but you can bridge the gap by mapping MoltFlow's MCP tools to OpenAI function calling. The pattern works with any model that supports tool use.

Here is how you would define a MoltFlow tool for OpenAI's API:

python
import openai
import requests

MOLTFLOW_API_URL = "https://apiv2.waiflow.app/api/v2"
MOLTFLOW_API_KEY = "mf_your_api_key_here"

tools = [
    {
        "type": "function",
        "function": {
            "name": "send_whatsapp_message",
            "description": "Send a WhatsApp message to a phone number",
            "parameters": {
                "type": "object",
                "properties": {
                    "session": {
                        "type": "string",
                        "description": "WhatsApp session ID"
                    },
                    "phone": {
                        "type": "string",
                        "description": "Phone number with country code"
                    },
                    "message": {
                        "type": "string",
                        "description": "Message text to send"
                    }
                },
                "required": ["session", "phone", "message"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "list_leads",
            "description": "List captured leads with optional status filter",
            "parameters": {
                "type": "object",
                "properties": {
                    "status": {
                        "type": "string",
                        "enum": ["new", "contacted", "qualified", "converted"],
                        "description": "Filter by lead status"
                    }
                }
            }
        }
    }
]

def handle_tool_call(tool_name, arguments):
    """Route tool calls to MoltFlow's REST API."""
    headers = {"X-API-Key": MOLTFLOW_API_KEY}

    if tool_name == "send_whatsapp_message":
        resp = requests.post(
            f"{MOLTFLOW_API_URL}/messages/send",
            headers=headers,
            json={
                "session": arguments["session"],
                "chatId": f"{arguments['phone']}@c.us",
                "text": arguments["message"]
            }
        )
        return resp.json()

    elif tool_name == "list_leads":
        params = {}
        if "status" in arguments:
            params["status"] = arguments["status"]
        resp = requests.get(
            f"{MOLTFLOW_API_URL}/leads",
            headers=headers,
            params=params
        )
        return resp.json()

# Standard OpenAI tool-calling loop
response = openai.chat.completions.create(
    model="gpt-4o",
    messages=[{
        "role": "user",
        "content": "Send a follow-up to all new leads on my main session"
    }],
    tools=tools
)

This same approach works with any framework that supports function calling -- LangChain, CrewAI, AutoGen, or a custom agent loop. MoltFlow's REST API is the execution layer; the AI model provides the decision-making.

Building Custom Agents with Claude Agent SDK

For production agent systems, the Claude Agent SDK (formerly Claude Code SDK) lets you build autonomous agents that use MoltFlow tools programmatically:

typescript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

const tools = [
  {
    name: "moltflow_list_leads",
    description: "List captured leads from WhatsApp group monitoring",
    input_schema: {
      type: "object" as const,
      properties: {
        status: {
          type: "string",
          enum: ["new", "contacted", "qualified", "converted"],
          description: "Filter by lead status"
        },
        session: {
          type: "string",
          description: "Filter by WhatsApp session"
        }
      }
    }
  },
  {
    name: "moltflow_send_message",
    description: "Send a WhatsApp message",
    input_schema: {
      type: "object" as const,
      properties: {
        session: { type: "string", description: "Session ID" },
        chatId: { type: "string", description: "Chat ID ([email protected])" },
        text: { type: "string", description: "Message text" }
      },
      required: ["session", "chatId", "text"]
    }
  }
];

async function runAgent(task: string) {
  let messages: Anthropic.MessageParam[] = [
    { role: "user", content: task }
  ];

  while (true) {
    const response = await client.messages.create({
      model: "claude-sonnet-4-20250514",
      max_tokens: 4096,
      tools,
      messages
    });

    if (response.stop_reason === "end_turn") {
      // Agent finished — extract final text
      const text = response.content
        .filter(b => b.type === "text")
        .map(b => b.text)
        .join("\n");
      console.log("Agent:", text);
      break;
    }

    // Process tool calls
    for (const block of response.content) {
      if (block.type === "tool_use") {
        const result = await callMoltFlowAPI(block.name, block.input);
        messages.push(
          { role: "assistant", content: response.content },
          {
            role: "user",
            content: [{
              type: "tool_result",
              tool_use_id: block.id,
              content: JSON.stringify(result)
            }]
          }
        );
      }
    }
  }
}

runAgent("Check my new leads and send a welcome message to anyone scored above 7");

This gives you a fully autonomous agent that can chain multiple MoltFlow operations together based on runtime decisions. Deploy it as a cron job, a webhook handler, or a Slack bot -- the agent decides which tools to call and in what order.

Security: Give Agents Only the Permissions They Need

When connecting AI agents to WhatsApp, least-privilege access is critical. MoltFlow's API key scoping system lets you control exactly what each agent can do.

Scope Categories

Every API key requires explicit scopes. No wildcard defaults -- you choose what the key can access:

  • sessions:read / sessions:write -- View or manage WhatsApp sessions
  • messages:read / messages:send -- Read chat history or send messages
  • groups:read / groups:write -- View or manage monitored and custom groups
  • leads:read / leads:write -- View or update lead data
  • outreach:read / outreach:write -- View or launch bulk campaigns
  • analytics:read -- Pull engagement and delivery metrics

Recommended Scope Profiles

Read-Only Analyst -- An agent that answers questions about your data but cannot send messages or modify anything:

text
sessions:read, messages:read, groups:read, leads:read, analytics:read

Messaging Agent -- An agent that can send messages and manage leads but cannot launch bulk campaigns:

text
sessions:read, messages:read, messages:send, leads:read, leads:write

Campaign Manager -- Full outreach capabilities including bulk sends:

text
sessions:read, messages:send, groups:read, groups:write,
leads:read, outreach:read, outreach:write, analytics:read

If an agent tries to call a tool it does not have permission for, MoltFlow returns a 403 response with an X-Required-Scopes header telling you exactly which scope is missing. The agent sees a clear error, not a silent failure.

Key Rotation

Generate separate API keys for each agent or integration. If one is compromised, revoke it without affecting your other systems. Keys are managed in your dashboard under Sessions > API Keys.

The Future Is Agents That Actually Do Things

The shift from AI assistants to AI agents is not about better language models. It is about giving models the ability to execute. MCP provides the standard interface, and MoltFlow provides the WhatsApp execution layer.

Today you can tell Claude "follow up with my cold leads" and it happens. You can ask ChatGPT to "analyze my campaign performance" and get real numbers. You can build an autonomous agent that monitors groups, scores leads, and sends personalized outreach -- all running on your own data, with your own WhatsApp number, under your control.

The tools are here. The protocol is standardized. The only thing left is to connect and start building.

Get started now:

> Try MoltFlow Free — 100 messages/month

$ curl https://molt.waiflow.app/pricing

bash-5.2$ echo "End of post."_