How to integrate Whatsapp MCP with Mastra AI

Connect Mastra AI to Whatsapp MCP. Send contact card to new lead, get business profile details for support, and more using natural language, with authentication handled for you.

Whatsapp logoWhatsapp
Oauth2Api Key

WhatsApp is a business messaging platform for secure, automated customer communication. It streamlines chat workflows and customer outreach using the WhatsApp Business API.

127 Tools1 Triggers

Introduction

This guide walks you through connecting Whatsapp to Mastra AI using the Composio tool router. By the end, you'll have a working Whatsapp agent that can send messages and media, manage message templates, build WhatsApp Flows, update your business profile, and create QR codes through natural language commands.

This guide will help you understand how to give your Mastra AI agent real control over a Whatsapp account through Composio's Whatsapp MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

Also integrate Whatsapp with

TL;DR

Here's what you'll learn:
  • Set up your environment so Mastra, OpenAI, and Composio work together
  • Create a Tool Router session in Composio that exposes Whatsapp tools
  • Connect Mastra's MCP client to the Composio generated MCP URL
  • Fetch Whatsapp tool definitions and attach them as a toolset
  • Build a Mastra agent that can reason, call tools, and return structured results
  • Run an interactive CLI where you can chat with your Whatsapp agent

What is Mastra AI?

Mastra AI is a TypeScript framework for building AI agents with tool support. It provides a clean API for creating agents that can use external services through MCP.

Key features include:

  • MCP Client: Built-in support for Model Context Protocol servers
  • Toolsets: Organize tools into logical groups
  • Step Callbacks: Monitor and debug agent execution
  • OpenAI Integration: Works with OpenAI models via @ai-sdk/openai

What is the Whatsapp MCP server, and what's possible with it?

The WhatsApp MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your WhatsApp account. It provides structured and secure access to your WhatsApp Business account settings, profiles, templates, flows, and phone configuration, so your agent can manage business details, register phone numbers, maintain templates, update flows, and review account settings on your behalf.

  • Business profile management: Have your agent update your business description, contact information, and other WhatsApp Business profile settings.
  • Phone number administration: Direct your agent to register or deregister a WhatsApp Business phone number and set its two-step verification PIN.
  • Message template management: Let the agent browse the template library and create or update templates for your WhatsApp Business account.
  • Flow and commerce configuration: Instruct your agent to review Flow assets, update Flow configurations, and check commerce settings for your business phone number.
  • Account oversight and access: Have your agent review owned or shared business accounts, inspect compliance and encryption details, manage assigned user access, and subscribe your application to account notifications.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Step by step09 STEPS
1

Prerequisites

Before starting, make sure you have:
  • Node.js 18 or higher
  • A Composio account with an active API key
  • An OpenAI API key
  • Basic familiarity with TypeScript
2

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key.
  • You need credits or a connected billing setup to use the models.
  • Store the key somewhere safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Go to Settings and copy your API key.
  • This key lets your Mastra agent talk to Composio and reach Whatsapp through MCP.
3

Install dependencies

bash
npm install @composio/core @mastra/core @mastra/mcp @ai-sdk/openai dotenv

Install the required packages.

What's happening:

  • @composio/core is the Composio SDK for creating MCP sessions
  • @mastra/core provides the Agent class
  • @mastra/mcp is Mastra's MCP client
  • @ai-sdk/openai is the model wrapper for OpenAI
  • dotenv loads environment variables from .env
4

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your requests to Composio
  • COMPOSIO_USER_ID tells Composio which user this session belongs to
  • OPENAI_API_KEY lets the Mastra agent call OpenAI models
5

Import libraries and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey as string,
});
What's happening:
  • dotenv/config auto loads your .env so process.env.* is available
  • openai gives you a Mastra compatible model wrapper
  • Agent is the Mastra agent that will call tools and produce answers
  • MCPClient connects Mastra to your Composio MCP server
  • Composio is used to create a Tool Router session
6

Create a Tool Router session for Whatsapp

typescript
async function main() {
  const session = await composio.create(
    composioUserID as string,
    {
      toolkits: ["whatsapp"],
    },
  );

  const composioMCPUrl = session.mcp.url;
  console.log("Whatsapp MCP URL:", composioMCPUrl);
What's happening:
  • create spins up a short-lived MCP HTTP endpoint for this user
  • The toolkits array contains "whatsapp" for Whatsapp access
  • session.mcp.url is the MCP URL that Mastra's MCPClient will connect to
7

Configure Mastra MCP client and fetch tools

typescript
const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      nasdaq: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

console.log("Fetching MCP tools from Composio...");
const composioTools = await mcpClient.getTools();
console.log("Number of tools:", Object.keys(composioTools).length);
What's happening:
  • MCPClient takes an id for this client and a list of MCP servers
  • The headers property includes the x-api-key for authentication
  • getTools fetches the tool definitions exposed by the Whatsapp toolkit
8

Create the Mastra agent

typescript
const agent = new Agent({
    name: "whatsapp-mastra-agent",
    instructions: "You are an AI agent with Whatsapp tools via Composio.",
    model: "openai/gpt-5",
  });
What's happening:
  • Agent is the core Mastra agent
  • name is just an identifier for logging and debugging
  • instructions guide the agent to use tools instead of only answering in natural language
  • model uses openai("gpt-5") to configure the underlying LLM
9

Set up interactive chat interface

typescript
let messages: AiMessageType[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end.\n");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();

rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

  if (!trimmedInput) {
    rl.prompt();
    return;
  }

  messages.push({
    id: crypto.randomUUID(),
    role: "user",
    content: trimmedInput,
  });

  console.log("\nAgent is thinking...\n");

  try {
    const response = await agent.generate(messages, {
      toolsets: {
        whatsapp: composioTools,
      },
      maxSteps: 8,
    });

    const { text } = response;

    if (text && text.trim().length > 0) {
      console.log(`Agent: ${text}\n`);
        messages.push({
          id: crypto.randomUUID(),
          role: "assistant",
          content: text,
        });
      }
    } catch (error) {
      console.error("\nError:", error);
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    console.log("\nSession ended.");
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • messages keeps the full conversation history in Mastra's expected format
  • agent.generate runs the agent with conversation history and Whatsapp toolsets
  • maxSteps limits how many tool calls the agent can take in a single run
  • onStepFinish is a hook that prints intermediate steps for debugging

Complete Code

Here's the complete code to get you started with Whatsapp and Mastra AI:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({ apiKey: composioAPIKey as string });

async function main() {
  const session = await composio.create(composioUserID as string, {
    toolkits: ["whatsapp"],
  });

  const composioMCPUrl = session.mcp.url;

  const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      whatsapp: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "whatsapp-mastra-agent",
    instructions: "You are an AI agent with Whatsapp tools via Composio.",
    model: "openai/gpt-5",
  });

  let messages: AiMessageType[] = [];

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (input: string) => {
    const trimmed = input.trim();
    if (["exit", "quit"].includes(trimmed.toLowerCase())) {
      rl.close();
      return;
    }

    messages.push({ id: crypto.randomUUID(), role: "user", content: trimmed });

    const { text } = await agent.generate(messages, {
      toolsets: { whatsapp: composioTools },
      maxSteps: 8,
    });

    if (text) {
      console.log(`Agent: ${text}\n`);
      messages.push({ id: crypto.randomUUID(), role: "assistant", content: text });
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main();

Conclusion

You've built a Mastra AI agent that can interact with Whatsapp through Composio's Tool Router. You can extend this further by:
  • Adding other toolkits like Gmail, Slack, or GitHub
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows
TOOLS & TRIGGERS

Supported Tools and Triggers

Every Whatsapp action and event your agent gets out of the box.

Accept business solution

Accept an invitation for the authenticated partner app to join a Multi-Partner Solution.

Accept solution deactivation

Accept a pending Multi-Partner Solution deactivation request.

Add business phone number

Add a preverified phone number to a partner-owned pool clients can purchase from.

Approve group join requests

Approve pending WhatsApp group join requests by their join request IDs.

Assign user

Assign a Facebook user or system user to a WhatsApp Business Account with specified tasks.

Block WhatsApp Users

Block one or more WhatsApp users to prevent them from sending messages to your business phone number.

Configure WhatsApp Conversational Automation

Configure conversational automation for a WhatsApp Business phone number, including welcome-message enablement, custom commands, and ice breaker prompts.

Create business account

Create a WhatsApp Business Account under a business portfolio.

Create business solution

Create a Multi-Partner Solution between an owner app and a partner app.

Create WhatsApp Flow

Create a WhatsApp Flow for the WhatsApp Business Account bound to the connection.

Create group

Submit creation of a WhatsApp group for a business phone number.

Create group invite link

Reset a WhatsApp group's invite link and return its replacement.

Create WhatsApp Max Price Agreement

Create a max price agreement for WhatsApp marketing messages pricing.

Create message template

Create a new message template for the WhatsApp Business Account.

Create obo mobility intent

Create an On-Behalf-Of mobility intent for an eligible WhatsApp Business Account.

Create phone number

Create a phone number registration within a WhatsApp Business Account.

Create QR Code

Create a new QR code with a prefilled message for a WhatsApp Business phone number.

Create schedule

Create a campaign schedule for the connection's WhatsApp Business Account.

Create upload session for WhatsApp

Create a resumable upload session for large file uploads to WhatsApp.

Delete flow

Delete a WhatsApp Flow that is in DRAFT status.

Delete group

Delete a WhatsApp group and remove all participants, including the business.

Delete group invite link

Delete an existing WhatsApp group invite link using the Groups invite link API.

Delete WhatsApp Media

Delete a WhatsApp media file previously uploaded via the Media API.

Delete message template

Delete a WhatsApp Business Account message template by name, permanently removing all language variants unless a template ID is supplied to target one variant.

Delete preverified number

Permanently delete a pre-verified phone number from the pre-verified list.

Delete QR Code

Delete a specific QR code from a WhatsApp Business phone number.

Deprecate flow

Irreversibly retire a published WhatsApp Flow by marking it DEPRECATED.

Deregister WhatsApp Business Phone Number

Deregister a WhatsApp Business phone number from the Cloud API.

Download media

Download a WhatsApp media asset using its short-lived media URL.

Edit message template

Edit an existing WhatsApp message template by ID.

Get account number

Retrieve a WhatsApp Account Number node's status and configuration.

Get WhatsApp Business Account Activities

Retrieve a paginated activity history for the WhatsApp Business Account bound to the connection, including administrative actions such as phone number verifications and user additions.

Get assigned business accounts

Retrieve one page of WhatsApp Business Accounts assigned to a specific Meta user.

Get assigned users

List users assigned to a WhatsApp Business Account in a business context.

Get WhatsApp Business Account Details

Retrieve configuration and status details for the WhatsApp Business Account bound to the connection, including account review status, business verification status, timezone, and ownership details.

Get business bot

Retrieve a WhatsApp Business Bot's prompts, commands and welcome-message setting.

Get WhatsApp Business Compliance Info

Retrieve comprehensive business compliance information for a WhatsApp Business phone number.

Get Business Encryption

Retrieve the WhatsApp Business public key and its signature verification status.

Get business portfolio

Retrieve a Meta business portfolio's ID, name and timezone identifier.

Get business profile

Get the business profile information for a WhatsApp Business phone number.

Get business profile node

Retrieve a WhatsApp Business Profile node by its profile ID.

Get call permissions

Check permission to call one WhatsApp user from a business phone number.

Get client WhatsApp Business Accounts

Retrieve WhatsApp Business Accounts shared with or managed by a business portfolio.

Get WhatsApp Commerce Settings

Get commerce settings for a WhatsApp Business phone number.

Get connected client businesses

Retrieve one page of client businesses connected to a Meta application.

Get extended credits

Retrieve one page of a Meta Business Portfolio's extended credit lines.

Get flow

Get one WhatsApp Flow's metadata, validation errors, preview, or health.

Get Flow Assets

List assets associated with a WhatsApp Flow.

Get group

Retrieve metadata about one WhatsApp group by its group ID.

Get Join Requests

Retrieve pending join requests for a WhatsApp group to help manage group membership.

Get max price agreements

Check the max price beta agreement status for a Meta business portfolio.

Get media info

Get metadata and download URL for uploaded WhatsApp media.

Get WhatsApp Message History

Retrieve message history for a WhatsApp Business phone number.

Get message history events

Retrieve one page of delivery status events for a Message History ID.

Get message templates

Get all message templates for the WhatsApp Business Account.

Get migration intent

Retrieve a WhatsApp Business Account migration intent's status and linked accounts.

Get official business account status

Retrieve Official Business Account (OBA) application status for a business phone number.

Get owned WhatsApp Business Accounts

Retrieve WhatsApp Business Accounts owned by a business portfolio.

Get phone number

Retrieve detailed information about a specific WhatsApp Business phone number.

Get phone numbers

Retrieve a page of phone numbers registered to the connection's WhatsApp Business Account.

Get preverified number

Retrieve a pre-verified phone number's verification status, owner, and expiry.

Get preverified number partners

List partner businesses with access to a pre-verified WhatsApp phone number.

Get qr code

Retrieve one message QR code by phone number ID and QR code identifier.

Get reach estimate

Estimate WhatsApp marketing message reach and costs at different max prices.

Get WhatsApp Schedules

Retrieve campaign schedules for the WhatsApp Business Account configured on the connection.

Get WhatsApp Cloud API Settings

Get Cloud API settings for a WhatsApp Business phone number.

Get solution access token

Retrieve an onboarded client's business integration system user access token.

Get Subscribed Apps

Get all applications currently subscribed to webhooks for a WhatsApp Business Account.

Get message template library

Browse the pre-built message template library for WhatsApp Business Account.

Get template status

Get the status and details of a specific message template.

Get upload offset

Get the byte offset of an interrupted resumable upload.

List blocked users

Retrieve one page of blocked users for a WhatsApp Business phone number.

List business accounts

List WhatsApp Business Accounts owned by a business portfolio.

List business solutions

List one page of Multi-Partner Solutions owned by or partnered with a Meta app.

List WhatsApp Flows

List all WhatsApp Flows associated with the WhatsApp Business Account.

List WhatsApp Groups

List all WhatsApp groups associated with a business phone number.

List on behalf requests

List one page of in-progress on-behalf requests for a WhatsApp Business Account.

List preverified numbers

List pre-verified phone numbers available to a business portfolio.

List qr codes

Get a list of all QR codes for a WhatsApp Business phone number.

List WhatsApp Solutions

Retrieve a paginated list of Multi-Partner Solutions for the WhatsApp Business Account configured on the connection, including status and owner application information when returned.

Manage call

Initiate, pre-accept, accept, reject or terminate a WhatsApp WebRTC call.

Migrate flows

Copy up to 100 Flows between WABAs owned by the same Meta business.

Onboard marketing partners

Send a partner-initiated MM Lite onboarding request to an end business.

Publish WhatsApp Flow

Publish a WhatsApp Flow to make it available for use.

Register WhatsApp Business Phone Number

Register a WhatsApp Business phone number for use with WhatsApp Cloud API.

Reject business solution

Reject a pending partnership or deactivation request for a Multi-Partner Solution.

Reject group join requests

Reject pending requests to join a WhatsApp group, individually or in bulk.

Reject solution deactivation

Reject a pending Multi-Partner Solution deactivation request.

Remove Assigned User from WhatsApp Business Account

Remove an assigned user's access from the WhatsApp Business Account bound to the connection.

Remove group participants

Request removal of one to eight WhatsApp group participants.

Request preverified number code

Request a verification code for a business-owned pre-verified phone number.

Request solution deactivation

Ask the partner to deactivate an owned WhatsApp Multi-Partner Solution.

Request verification code

Request an SMS or voice verification code for a WhatsApp Business phone number.

Send contacts

Send contacts WhatsApp number.

Send encrypted message

Send a caller-encrypted WhatsApp message and return the encrypted response.

Send interactive buttons

Send an interactive button message with up to 3 reply buttons to a WhatsApp user.

Send interactive list

Send an interactive list message to a WhatsApp number.

Send location

Send a location message with coordinates, name, and address to a WhatsApp user.

Send marketing message

Send an approved marketing template through the Marketing Messages API.

Send media

Send a media message to a WhatsApp number using a media URL.

Send media by

Send media using a media ID from previously uploaded media.

Send message

Send a text message to a WhatsApp user.

Send template message

Send a template message to a WhatsApp number.

Set business encryption

Set the RSA public key used to encrypt WhatsApp message payloads and data channel requests.

Set obo mobility intent

Set OBO mobility intent for a Multi-Partner Solution associated with a client WABA.

Set solution migration intent

Set migration intent for a Multi-Partner Solution associated with a WABA.

Set WhatsApp Two-Step Verification PIN

Set or reset the two-step verification PIN for a WhatsApp Business phone number.

Share preverified numbers

Share a number from a business's pre-verified phone number pool with a partner.

Subscribe to WABA Webhooks

Subscribe your application to webhook notifications for the WhatsApp Business Account configured on the connection, using the configured app webhook settings.

Unblock WhatsApp Users

Unblock WhatsApp users so they can contact the business phone number again.

Unsubscribe from WABA Webhooks

Unsubscribe your application from webhook events for the connection-bound WhatsApp Business Account, for example when cleaning up an integration.

Update WhatsApp Flow Metadata

Update metadata for a WhatsApp Flow including its name, categories, and endpoint URI.

Update business account settings

Update a WhatsApp Business Account's name or timezone identifier.

Update business compliance info

Create or update regulatory compliance information for a WhatsApp Business phone number.

Update WhatsApp Business Profile

Update WhatsApp Business Profile information including business details, contact information, and profile settings.

Update business profile node

Update a WhatsApp Business Profile directly by its profile node ID.

Update WhatsApp commerce settings

Set or update commerce settings for a WhatsApp Business phone number.

Update Flow JSON

Update the Flow JSON configuration for an existing WhatsApp Flow by uploading a file or inline JSON.

Update group

Update an existing WhatsApp group's subject, description, or photo.

Update official business account status

Submit OBA application information or update application data for a phone number.

Update WhatsApp Cloud API Settings

Update Cloud API settings for a WhatsApp Business phone number.

Upload file chunk

Upload raw file bytes to a resumable upload session and return its file handle.

Upload media

Upload media files (images, videos, audio, documents, stickers) to WhatsApp servers.

Upsert message template

Create or update a message template for the WhatsApp Business Account.

Verify Phone Number OTP Code

Verify the OTP code for a pre-verified phone number.

Verify preverified number code

Verify an OTP for a pre-verified phone number to complete verification.

Who Am I

Return the identity (name) of the connected WhatsApp (Meta) account.

FAQ

Frequently asked questions

With a standalone Whatsapp MCP server, the agents and LLMs can only access a fixed set of Whatsapp tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Whatsapp and many other apps based on the task at hand, all through a single MCP endpoint.

Yes, you can. Mastra AI fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Whatsapp tools.

Yes, absolutely. You can configure which Whatsapp scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Whatsapp data and credentials are handled as safely as possible.

Start with Whatsapp.It takes 30 seconds.

Managed auth, hosted MCP servers, and every Whatsapp tool your agent needs.Free to start.

Start building