How to integrate Whatsapp MCP with LangChain

Connect LangChain 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 LangChain 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 LangChain 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:
  • Get and set up your OpenAI and Composio API keys
  • Connect your Whatsapp project to Composio
  • Create a Tool Router MCP session for Whatsapp
  • Initialize an MCP client and retrieve Whatsapp tools
  • Build a LangChain agent that can interact with Whatsapp
  • Set up an interactive chat interface for testing

What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides tools and abstractions for building agents that can reason, use tools, and maintain conversation context.

Key features include:

  • Agent Framework: Build agents that can use tools and make decisions
  • MCP Integration: Connect to external services through Model Context Protocol adapters
  • Memory Management: Maintain conversation history across interactions
  • Multi-Provider Support: Works with OpenAI, Anthropic, and other LLM providers

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 step10 STEPS
1

Prerequisites

Before starting this tutorial, make sure you have:
  • Python 3.10 or higher installed on your system
  • A Composio account with an API key
  • An OpenAI API key
  • Basic familiarity with Python and async programming
2

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.
3

Install dependencies

npm install @composio/langchain @langchain/core @langchain/openai @langchain/mcp-adapters dotenv

Install the required packages for LangChain with MCP support.

What's happening:

  • @composio/langchain provides Composio integration for LangChain
  • @langchain/mcp-adapters enables MCP client connections
  • @langchain/core is the core agent framework
  • dotenv/config loads environment variables
4

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_composio_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's API
  • COMPOSIO_USER_ID identifies the user for session management
  • OPENAI_API_KEY enables access to OpenAI's language models
5

Import dependencies

import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

dotenv.config();
What's happening:
  • We're importing LangChain's MCP adapter and Composio SDK
  • The dotenv/config import loads environment variables from your .env file
  • This setup prepares the foundation for connecting LangChain with Whatsapp functionality through MCP
6

Initialize Composio client

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.COMPOSIO_USER_ID;

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });
What's happening:
  • We're loading the COMPOSIO_API_KEY from environment variables and validating it exists
  • Creating a Composio instance that will manage our connection to Whatsapp tools
  • Validating that COMPOSIO_USER_ID is also set before proceeding
7

Create a Tool Router session

const session = await composio.create(
    userId as string,
    {
        toolkits: ['whatsapp']
    }
);

const url = session.mcp.url;
What's happening:
  • We're creating a Tool Router session that gives your agent access to Whatsapp tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned session.mcp.url is the MCP server URL that your agent will use
  • This approach allows the agent to dynamically load and use Whatsapp tools as needed
8

Configure the agent with the MCP URL

const client = new MultiServerMCPClient({
    "whatsapp-agent": {
        transport: "http",
        url: url,
        headers: {
            "x-api-key": process.env.COMPOSIO_API_KEY
        }
    }
});

const tools = await client.getTools();

const agent = createAgent({ model: "gpt-5", tools });
What's happening:
  • We're creating a MultiServerMCPClient that connects to our Whatsapp MCP server via HTTP
  • The client is configured with a name and the URL from our Tool Router session
  • getTools() retrieves all available Whatsapp tools that the agent can use
  • We're creating a LangChain agent using the GPT-5 model
9

Set up interactive chat interface

let conversationHistory: any[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log("Ask any Whatsapp related question or task to the agent.\n");

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

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;
    }

    conversationHistory.push({ role: "user", content: trimmedInput });
    console.log("\nAgent is thinking...\n");

    const response = await agent.invoke({ messages: conversationHistory });
    conversationHistory = response.messages;

    const finalResponse = response.messages[response.messages.length - 1]?.content;
    console.log(`Agent: ${finalResponse}\n`);
        
        rl.prompt();
    });

    rl.on('close', () => {
        console.log('\n👋 Session ended.');
        process.exit(0);
    });
What's happening:
  • We initialize an empty conversationHistory list to maintain context across interactions
  • A readline interface is used to continuously accept user input from the command line
  • When a user types a message, it's added to the conversation history and sent to the agent
  • The agent processes the request using the invoke() method with the full conversation history
  • Users can type 'exit', 'quit', or 'bye' to end the chat session gracefully
10

Run the application

main().catch((err) => {
    console.error('Fatal error:', err);
    process.exit(1);
});
What's happening:
  • We call the main() function to start the application

Complete Code

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

import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";  
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.COMPOSIO_USER_ID;

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });

    const session = await composio.create(
        userId as string,
        {
            toolkits: ['whatsapp']
        }
    );

    const url = session.mcp.url;
    
    const client = new MultiServerMCPClient({
        "whatsapp-agent": {
            transport: "http",
            url: url,
            headers: {
                "x-api-key": process.env.COMPOSIO_API_KEY
            }
        }
    });
    
    const tools = await client.getTools();
  
    const agent = createAgent({ model: "gpt-5", tools });
    
    let conversationHistory: any[] = [];
    
    console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
    console.log("Ask any Whatsapp related question or task to the agent.\n");
    
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        prompt: 'You: '
    });

    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;
        }
        
        conversationHistory.push({ role: "user", content: trimmedInput });
        console.log("\nAgent is thinking...\n");
        
        const response = await agent.invoke({ messages: conversationHistory });
        conversationHistory = response.messages;
        
        const finalResponse = response.messages[response.messages.length - 1]?.content;
        console.log(`Agent: ${finalResponse}\n`);
        
        rl.prompt();
    });

    rl.on('close', () => {
        console.log('\nSession ended.');
        process.exit(0);
    });
}

main().catch((err) => {
    console.error('Fatal error:', err);
    process.exit(1);
});

Conclusion

You've successfully built a LangChain agent that can interact with Whatsapp through Composio's Tool Router.

Key features of this implementation:

  • Dynamic tool loading through Composio's Tool Router
  • Conversation history maintenance for context-aware responses
  • Async Python provides clean, efficient execution of agent workflows
You can extend this further by adding error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-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. LangChain 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