How to integrate Whatsapp MCP with OpenAI Agents SDK

Connect OpenAI Agents SDK 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 the OpenAI Agents SDK 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 OpenAI Agents SDK 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
  • Install the necessary dependencies
  • Initialize Composio and create a Tool Router session for Whatsapp
  • Configure an AI agent that can use Whatsapp as a tool
  • Run a live chat session where you can ask the agent to perform Whatsapp operations

What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.

Key features include:

  • Hosted MCP Tools: Connect to external services through hosted MCP endpoints
  • SQLite Sessions: Persist conversation history across interactions
  • Simple API: Clean interface with Agent, Runner, and tool configuration
  • Streaming Support: Real-time response streaming for interactive applications

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:
  • Composio API Key and OpenAI API Key
  • Primary know-how of OpenAI Agents SDK
  • A live Whatsapp project
  • Some knowledge of Python or Typescript
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
3

Install dependencies

npm install @composio/openai-agents @openai/agents dotenv

Install the Composio SDK and the OpenAI Agents SDK.

4

Set up environment variables

bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com

Create a .env file and add your OpenAI and Composio API keys.

5

Import dependencies

import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
What's happening:
  • You're importing all necessary libraries.
  • The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Whatsapp.
6

Set up the Composio instance

dotenv.config();

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

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
What's happening:
  • dotenv.config() loads your .env file so COMPOSIO_API_KEY and USER_ID are available as environment variables.
  • Creating a Composio instance using the API Key and OpenAIAgentsProvider class.
7

Create a Tool Router session

// Create Tool Router session for Whatsapp
const session = await composio.create(userId as string, {
  toolkits: ['whatsapp'],
});
const mcpUrl = session.mcp.url;

What is happening:

  • You give the Tool Router the user id and the toolkits you want available. Here, it is only whatsapp.
  • The router checks the user's Whatsapp connection and prepares the MCP endpoint.
  • The returned session.mcp.url is the MCP URL that your agent will use to access Whatsapp.
  • This approach keeps things lightweight and lets the agent request Whatsapp tools only when needed during the conversation.
8

Configure the agent

// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Whatsapp. Help users perform Whatsapp operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
What's happening:
  • We're creating an Agent instance with a name, model (gpt-5), and clear instructions about its purpose.
  • The agent's instructions tell it that it can access Whatsapp and help with queries, inserts, updates, authentication, and fetching database information.
  • The tools array includes a hostedMcpTool that connects to the MCP server URL we created earlier.
  • The headers object includes the Composio API key for secure authentication with the MCP server.
  • requireApproval: 'never' means the agent can execute Whatsapp operations without asking for permission each time, making interactions smoother.
9

Start chat loop and handle conversation

// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

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

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

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

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
What's happening:
  • The program prints a session URL that you visit to authorize Whatsapp.
  • After authorization, the chat begins.
  • Each message you type is processed by the agent using run().
  • The responses are printed to the console.
  • Typing exit, quit, or q cleanly ends the chat.

Complete Code

Here's the complete code to get you started with Whatsapp and OpenAI Agents SDK:

import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

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

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['whatsapp'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Whatsapp. Help users perform Whatsapp operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

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

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

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

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\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

This was a starter code for integrating Whatsapp MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Whatsapp.

Key features:

  • Hosted MCP tool integration through Composio's Tool Router
  • SQLite session persistence for conversation history
  • Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.
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. OpenAI Agents SDK 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