# How to integrate Bigmailer MCP with LlamaIndex

```json
{
  "title": "How to integrate Bigmailer MCP with LlamaIndex",
  "toolkit": "Bigmailer",
  "toolkit_slug": "bigmailer",
  "framework": "LlamaIndex",
  "framework_slug": "llama-index",
  "url": "https://composio.dev/toolkits/bigmailer/framework/llama-index",
  "markdown_url": "https://composio.dev/toolkits/bigmailer/framework/llama-index.md",
  "updated_at": "2026-05-12T10:03:02.591Z"
}
```

## Introduction

This guide walks you through connecting Bigmailer to LlamaIndex using the Composio tool router. By the end, you'll have a working Bigmailer agent that can create a new welcome campaign for brand x, list all brands i manage in bigmailer, get your bigmailer account user details through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Bigmailer account through Composio's Bigmailer MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Bigmailer with

- [OpenAI Agents SDK](https://composio.dev/toolkits/bigmailer/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/bigmailer/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/bigmailer/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/bigmailer/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/bigmailer/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/bigmailer/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/bigmailer/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/bigmailer/framework/cli)
- [Google ADK](https://composio.dev/toolkits/bigmailer/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/bigmailer/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/bigmailer/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/bigmailer/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/bigmailer/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- Set your OpenAI and Composio API keys
- Install LlamaIndex and Composio packages
- Create a Composio Tool Router session for Bigmailer
- Connect LlamaIndex to the Bigmailer MCP server
- Build a Bigmailer-powered agent using LlamaIndex
- Interact with Bigmailer through natural language

## What is LlamaIndex?

LlamaIndex is a data framework for building LLM applications. It provides tools for connecting LLMs to external data sources and services through agents and tools.
Key features include:
- ReAct Agent: Reasoning and acting pattern for tool-using agents
- MCP Tools: Native support for Model Context Protocol
- Context Management: Maintain conversation context across interactions
- Async Support: Built for async/await patterns

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

The Bigmailer MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Bigmailer account. It provides structured and secure access to your email marketing platform, so your agent can perform actions like creating transactional campaigns, retrieving your brands, and managing user account details on your behalf.
- Automated transactional campaign creation: Have your agent quickly set up new transactional email campaigns for any of your brands, with full control over content, sender details, and subject lines.
- Brand management and discovery: Let your agent list and organize all brands associated with your Bigmailer account, providing a clear overview for multi-brand operations.
- User account information retrieval: Easily check your authenticated user details to verify API connectivity and view essential account information in real time.
- Multi-brand marketing workflow automation: Empower your agent to streamline campaign launches and brand management across multiple business entities from one place.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `BIGMAILER_CREATE_BRAND` | Create Brand | Tool to create a new brand in BigMailer. Brands are used to organize email campaigns and define default sending settings. Requires at minimum a brand name, from_name, and from_email. Returns the unique UUID of the created brand. |
| `BIGMAILER_CREATE_BRAND_PROPERTY` | Create Brand Property | Tool to create a brand property in BigMailer. Use when you need to define a custom property for a brand that can be referenced in email templates via merge tags. The merge_tag_name allows the property to be used as *\|TAG_NAME\|* in templates. |
| `BIGMAILER_CREATE_BULK_CAMPAIGN` | Create Bulk Campaign | Tool to create a bulk email campaign in BigMailer. Use when you need to send marketing emails to multiple recipients. The campaign can be sent immediately or scheduled for later. Throttling options allow you to control send rate. At minimum, you must provide a brand_id and campaign name. Use BIGMAILER_LIST_ALL_BRANDS to get valid brand IDs. |
| `BIGMAILER_CREATE_CONTACT` | Create Contact | Tool to create a new contact in BigMailer within a specified brand. Use when you need to add contacts to your mailing lists with optional custom fields and subscription settings. The contact's email address is required, and you can optionally add custom field values, assign to lists, and manage subscription status. |
| `BIGMAILER_CREATE_CONTACT_BATCH` | Create Contact Batch | Tool to create a batch of contacts in BigMailer for a specific brand. Use when you need to upload multiple contacts (1-1000) at once. Supports custom fields, list assignments, and unsubscribe operations. The batch is queued for asynchronous processing and returns a batch ID for tracking. |
| `BIGMAILER_CREATE_FIELD` | Create Field | Tool to create a custom field in a BigMailer brand. Custom fields allow you to store additional contact information (text, date, or integer values). Use when you need to add a new field to track contact data like company name, birthday, or loyalty points. |
| `BIGMAILER_CREATE_LIST` | Create List | Creates a new contact list within a specified brand in BigMailer. Use this to organize and segment contacts. The list must be associated with an existing brand. Use BIGMAILER_LIST_ALL_BRANDS to retrieve valid brand IDs before creating a list. |
| `BIGMAILER_CREATE_SEGMENT` | Create Segment | Tool to create a segment in BigMailer for a specific brand. Segments allow filtering contacts based on conditions like campaign activity (opened, clicked) or custom field values. Use when you need to organize contacts into targeted groups for campaigns. |
| `BIGMAILER_CREATE_SUPPRESSION_LIST` | Create Suppression List | Tool to upload a suppression list for a brand in BigMailer. Use when you need to add email addresses that should be excluded from campaigns. The file must be a CSV with email addresses in the first column of each row. |
| `BIGMAILER_CREATE_TEMPLATE` | Create Template | Tool to create a new email or page template in BigMailer. Templates can be used with bulk campaigns to define the HTML structure. Use when you need to create reusable email designs or landing pages. The template can be shared across all brands in the account if desired. |
| `BIGMAILER_CREATE_TRANSACTIONAL_CAMPAIGN` | Create Transactional Campaign | Creates a new transactional campaign within a specified brand in BigMailer. Transactional campaigns are used for sending automated emails like welcome emails, password resets, order confirmations, etc. The campaign must be associated with an existing brand (use BIGMAILER_LIST_ALL_BRANDS to get valid brand IDs). Returns the unique ID of the created campaign on success. |
| `BIGMAILER_CREATE_USER` | Create User | Tool to create a new user in BigMailer. Use when you need to add team members with specific roles and permissions. Returns the unique UUID of the created user. |
| `BIGMAILER_DELETE_BRAND_PROPERTY` | Delete Brand Property | Tool to delete a brand property from a brand in BigMailer. Use when you need to remove a custom property that was previously associated with a brand. |
| `BIGMAILER_DELETE_CONTACT` | Delete Contact | Tool to delete a contact from a brand in BigMailer. Use when you need to remove a contact permanently from a brand's contact list. |
| `BIGMAILER_DELETE_FIELD` | Delete Custom Field | Deletes a custom field from a specified brand in BigMailer. Custom fields are used to store additional contact information. This action permanently removes the field and cannot be undone. Use this when you need to clean up unused fields or remove fields that are no longer needed. |
| `BIGMAILER_DELETE_LIST` | Delete List | Tool to delete a list from BigMailer. Use when you need to permanently remove a list from a brand. Returns the ID of the deleted list upon success. |
| `BIGMAILER_DELETE_SEGMENT` | Delete Segment | Tool to delete a segment from a brand in BigMailer. Use when you need to remove a segment that is no longer needed. Returns the ID of the deleted segment on success. |
| `BIGMAILER_DELETE_TEMPLATE` | Delete Template | Tool to delete a template from BigMailer. Use when you need to permanently remove a template from a brand. Returns the ID of the deleted template upon success. |
| `BIGMAILER_DELETE_USER` | Delete User | Tool to delete a user from BigMailer. Use when you need to permanently remove a user from the system. Returns the ID of the deleted user upon success. |
| `BIGMAILER_GET_BRAND` | Get Brand | Tool to retrieve detailed information about a specific brand by its ID. Use when you need to get brand configuration, email settings, bounce thresholds, or other brand properties. |
| `BIGMAILER_GET_BRAND_PROPERTY` | Get Brand Property | Tool to retrieve a specific brand property by its ID for a given brand. Use when you need to fetch details about a brand property, such as its name, merge tag name, value, or HTML status. |
| `BIGMAILER_GET_BULK_CAMPAIGN` | Get Bulk Campaign | Tool to retrieve detailed information about a specific bulk campaign in BigMailer. Use when you need to get campaign details including status, content, recipient lists, and performance metrics like opens, clicks, bounces, and unsubscribes. |
| `BIGMAILER_GET_CONTACT` | Get Contact | Tool to retrieve detailed information about a specific contact from BigMailer. Use when you need to fetch contact details including email, custom field values, list memberships, and engagement metrics. |
| `BIGMAILER_GET_CONTACT_BATCH` | Get Contact Batch Status | Tool to retrieve the status and results of a contact batch upload in BigMailer. Use when you need to check the processing status of a batch contact import or review the results of individual contacts in the batch. |
| `BIGMAILER_GET_FIELD` | Get Custom Field | Tool to retrieve a custom field from a BigMailer brand. Use when you need to get details about a specific custom field including its ID, name, type, merge tag name, and sample value. |
| `BIGMAILER_GET_LIST` | Get List | Tool to retrieve details of a specific list within a brand. Use when you need to get information about a list such as its name, creation time, and whether it's the special system list containing all contacts. |
| `BIGMAILER_GET_SEGMENT` | Get Segment | Tool to retrieve a specific segment from BigMailer by brand ID and segment ID. Use when you need to get details about a segment including its conditions and operator. |
| `BIGMAILER_GET_SUPPRESSION_LIST` | Get Suppression List | Tool to retrieve details of a specific suppression list for a brand in BigMailer. Use when you need to get information about a suppression list including its file name, size, and creation timestamp. |
| `BIGMAILER_GET_TEMPLATE` | Get Template | Tool to retrieve detailed information about a specific template by its ID. Use when you need to get template content, HTML body, type, creation time, or sharing settings. |
| `BIGMAILER_GET_TRANSACTIONAL_CAMPAIGN` | Get Transactional Campaign | Tool to retrieve detailed information about a specific transactional campaign in BigMailer. Use when you need to get campaign details including status, content, tracking settings, and performance metrics like opens, clicks, bounces, and unsubscribes. |
| `BIGMAILER_GET_USER` | Get User | Tool to retrieve detailed information about a specific user by their ID. Use when you need to get user details including email, role, activation status, and brand permissions. |
| `BIGMAILER_GET_USER_INFO` | Get User Information | This tool retrieves information about the authenticated user in BigMailer using the GET /me endpoint. It requires only authentication and no additional parameters, making it ideal for verifying API connectivity and retrieving essential user details. |
| `BIGMAILER_LIST_ALL_BRANDS` | List All Brands | This tool retrieves a list of all brands associated with the authenticated BigMailer account. It allows users to view and manage their brands. The operation is executed via a simple GET request to the /brands endpoint and requires proper authentication using the X-API-Key header. The response is a JSON array containing information such as Brand ID, Brand name, and other related details. |
| `BIGMAILER_LIST_BRAND_PROPERTIES` | List Brand Properties | Tool to retrieve a list of brand properties for a specific brand in BigMailer. Use when you need to view custom properties associated with a brand, such as merge tags and their values used in email campaigns. |
| `BIGMAILER_LIST_BULK_CAMPAIGNS` | List Bulk Campaigns | Tool to list bulk campaigns for a specified brand in BigMailer. Use when you need to retrieve all bulk email campaigns associated with a brand, including their status, statistics, and configuration. Supports pagination using cursor-based navigation for large result sets. |
| `BIGMAILER_LIST_CONNECTIONS` | List Connections | Tool to list all connections in your BigMailer account. Use when you need to retrieve connections for email delivery (e.g., AWS SES). Supports pagination for accounts with many connections. |
| `BIGMAILER_LIST_CONTACTS` | List Contacts | Tool to list contacts for a brand in BigMailer. Use when you need to retrieve contacts from a specific brand, optionally filtered by list membership. Supports pagination for large contact lists. |
| `BIGMAILER_LIST_FIELDS` | List Fields | Tool to list custom fields for a brand in BigMailer. Use when you need to retrieve all custom fields defined for a specific brand, including field names, types, and merge tags. |
| `BIGMAILER_LIST_LISTS` | List Contact Lists | Tool to retrieve all contact lists for a specified brand in BigMailer. Use when you need to view or manage contact lists within a brand, or when you need to get a list ID for other operations. Supports pagination for brands with many lists. |
| `BIGMAILER_LIST_MESSAGE_TYPES` | List Message Types | Tool to list message types for a specific brand in BigMailer. Use when you need to retrieve available message type categories that can be used for organizing and categorizing email campaigns. Supports filtering by type (user-created, account-level, or all) and pagination for large result sets. |
| `BIGMAILER_LIST_SEGMENTS` | List Segments | Tool to list segments for a brand in BigMailer. Use when you need to retrieve and view all segments associated with a specific brand. Segments are used to organize and filter contacts based on conditions like campaign activity or field values. |
| `BIGMAILER_LIST_SENDERS` | List Senders | Tool to list all senders configured for a specific brand in BigMailer. Use when you need to retrieve sender identities (domains or email addresses) associated with a brand, including their verification status and DNS configuration details. |
| `BIGMAILER_LIST_SUPPRESSION_LISTS` | List Suppression Lists | Tool to list suppression lists for a specific brand. Suppression lists contain contacts that should be excluded from campaigns. Use this to view and manage suppression lists associated with a brand. Supports pagination via cursor and limit parameters. |
| `BIGMAILER_LIST_TEMPLATES` | List Templates | Tool to list templates for a brand in BigMailer. Use when you need to retrieve all templates associated with a specific brand. Templates can be email or SMS templates used for campaigns and transactional messages. |
| `BIGMAILER_LIST_TRANSACTIONAL_CAMPAIGNS` | List Transactional Campaigns | Tool to list transactional campaigns for a specified brand in BigMailer. Use when you need to retrieve all transactional email campaigns associated with a brand, including their status, statistics, and configuration. Supports pagination using cursor-based navigation for large result sets. |
| `BIGMAILER_LIST_USERS` | List Users | Tool to list all users in your BigMailer account. Use when you need to retrieve user information, check account access, or manage user permissions. Supports pagination for accounts with many users. |
| `BIGMAILER_UPDATE_BRAND` | Update Brand | Tool to update a brand in BigMailer. Use when you need to modify brand settings such as name, email defaults, contact limits, bounce settings, or branding elements. Only the fields provided in the request will be updated; unspecified fields retain their current values. |
| `BIGMAILER_UPDATE_BRAND_PROPERTY` | Update Brand Property | Tool to update a brand property in BigMailer. Use when you need to modify properties of an existing brand, such as the property name, merge tag name, string value, or HTML flag. At least one of the optional fields must be provided. |
| `BIGMAILER_UPDATE_BULK_CAMPAIGN` | Update Bulk Campaign | Tool to update an existing bulk campaign in BigMailer. Use when modifying campaign properties like name, subject, content, recipients, scheduling, or tracking settings. Only the name field is required; all other fields are optional and will only update if provided. |
| `BIGMAILER_UPDATE_CONTACT` | Update Contact | Tool to update an existing contact in BigMailer. Use when you need to modify contact details, manage list subscriptions, or update field values. Supports multiple operation modes (add, replace, remove) for field_values, list_ids, and unsubscribe_ids. |
| `BIGMAILER_UPDATE_FIELD` | Update Field | Tool to update a custom field in BigMailer. Use when you need to modify the name, merge tag name, or sample value of an existing field within a brand. At least one of merge_tag_name, name, or sample_value must be provided. |
| `BIGMAILER_UPDATE_LIST` | Update List | Tool to update a list in BigMailer. Use when you need to rename an existing list within a brand. This action requires both the brand ID and list ID to identify the list to update. |
| `BIGMAILER_UPDATE_SEGMENT` | Update Segment | Tool to update an existing segment in BigMailer. Use when modifying segment properties such as name, operator logic, or conditions. At least one field (name, operator, or conditions) should be provided to update the segment. |
| `BIGMAILER_UPDATE_TEMPLATE` | Update Template | Tool to update an existing email or page template in BigMailer. Use when you need to modify template properties such as name, HTML content, type, or sharing settings. Only the fields provided in the request will be updated; unspecified fields retain their current values. |
| `BIGMAILER_UPDATE_TRANSACTIONAL_CAMPAIGN` | Update Transactional Campaign | Tool to update a transactional campaign in BigMailer. Use when you need to modify campaign settings such as name, subject, content, tracking options, or activation status. Only the fields provided in the request will be updated; unspecified fields retain their current values. |
| `BIGMAILER_UPDATE_USER` | Update User | Tool to update a user in BigMailer. Use when you need to modify user settings such as email, role, or allowed brands. Only the fields provided will be updated. |
| `BIGMAILER_UPSERT_CONTACT` | Upsert Contact | Tool to create or update a contact in a BigMailer brand. Use when you need to add a new contact or update an existing contact's information. If a contact with the given email already exists, it will be updated; otherwise, a new contact will be created. Optionally validates email deliverability before adding (requires validation credits). |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The Bigmailer MCP server is an implementation of the Model Context Protocol that connects your AI agent to Bigmailer. It provides structured and secure access so your agent can perform Bigmailer operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before you begin, make sure you have:
- Python 3.8/Node 16 or higher installed
- A Composio account with the API key
- An OpenAI API key
- A Bigmailer account and project
- Basic familiarity with async Python/Typescript

### 1. Getting API Keys for OpenAI, Composio, and Bigmailer

No description provided.

### 2. Installing dependencies

No description provided.
```python
pip install composio-llamaindex llama-index llama-index-llms-openai llama-index-tools-mcp python-dotenv
```

```typescript
npm install @composio/llamaindex @llamaindex/openai @llamaindex/tools @llamaindex/workflow dotenv
```

### 3. Set environment variables

Create a .env file in your project root:
These credentials will be used to:
- Authenticate with OpenAI's GPT-5 model
- Connect to Composio's Tool Router
- Identify your Composio user session for Bigmailer access
```bash
OPENAI_API_KEY=your-openai-api-key
COMPOSIO_API_KEY=your-composio-api-key
COMPOSIO_USER_ID=your-user-id
```

### 4. Import modules

No description provided.
```python
import asyncio
import os
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()
```

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();
```

### 5. Load environment variables and initialize Composio

No description provided.
```python
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set in the environment")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set in the environment")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set in the environment")
```

```typescript
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!COMPOSIO_API_KEY) throw new Error("COMPOSIO_API_KEY is not set");
if (!COMPOSIO_USER_ID) throw new Error("COMPOSIO_USER_ID is not set");
```

### 6. Create a Tool Router session and build the agent function

What's happening here:
- We create a Composio client using your API key and configure it with the LlamaIndex provider
- We then create a tool router MCP session for your user, specifying the toolkits we want to use (in this case, bigmailer)
- The session returns an MCP HTTP endpoint URL that acts as a gateway to all your configured tools
- LlamaIndex will connect to this endpoint to dynamically discover and use the available Bigmailer tools.
- The MCP tools are mapped to LlamaIndex-compatible tools and plug them into the Agent.
```python
async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["bigmailer"],
    )

    mcp_url = session.mcp.url
    print(f"Composio MCP URL: {mcp_url}")

    mcp_client = BasicMCPClient(mcp_url, headers={"x-api-key": COMPOSIO_API_KEY})
    mcp_tool_spec = McpToolSpec(client=mcp_client)
    tools = await mcp_tool_spec.to_tool_list_async()

    llm = OpenAI(model="gpt-5")

    description = "An agent that uses Composio Tool Router MCP tools to perform Bigmailer actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Bigmailer actions.
    """
    return ReActAgent(tools=tools, llm=llm, description=description, system_prompt=system_prompt, verbose=True)
```

```typescript
async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["bigmailer"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
        description : "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Bigmailer actions." ,
    llm,
    tools,
  });

  return agent;
}
```

### 7. Create an interactive chat loop

No description provided.
```python
async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")
```

```typescript
async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}
```

### 8. Define the main entry point

What's happening here:
- We're orchestrating the entire application flow
- The agent gets built with proper error handling
- Then we kick off the interactive chat loop so you can start talking to Bigmailer
```python
async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")
```

```typescript
async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err) {
    console.error("Failed to start agent:", err);
    process.exit(1);
  }
}

main();
```

### 9. Run the agent

When prompted, authenticate and authorise your agent with Bigmailer, then start asking questions.
```bash
python llamaindex_agent.py
```

```typescript
npx ts-node llamaindex-agent.ts
```

## Complete Code

```python
import asyncio
import os
import signal
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set")

async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["bigmailer"],
    )

    mcp_url = session.mcp.url
    print(f"Composio MCP URL: {mcp_url}")

    mcp_client = BasicMCPClient(mcp_url, headers={"x-api-key": COMPOSIO_API_KEY})
    mcp_tool_spec = McpToolSpec(client=mcp_client)
    tools = await mcp_tool_spec.to_tool_list_async()

    llm = OpenAI(model="gpt-5")
    description = "An agent that uses Composio Tool Router MCP tools to perform Bigmailer actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Bigmailer actions.
    """
    return ReActAgent(
        tools=tools,
        llm=llm,
        description=description,
        system_prompt=system_prompt,
        verbose=True,
    );

async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")

async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")
```

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";
import { LlamaindexProvider } from "@composio/llamaindex";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();

const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) {
    throw new Error("OPENAI_API_KEY is not set in the environment");
  }
if (!COMPOSIO_API_KEY) {
    throw new Error("COMPOSIO_API_KEY is not set in the environment");
  }
if (!COMPOSIO_USER_ID) {
    throw new Error("COMPOSIO_USER_ID is not set in the environment");
  }

async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["bigmailer"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
    description:
      "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Bigmailer actions." ,
    llm,
    tools,
  });

  return agent;
}

async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}

async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err: any) {
    console.error("Failed to start agent:", err?.message ?? err);
    process.exit(1);
  }
}

main();
```

## Conclusion

You've successfully connected Bigmailer to LlamaIndex through Composio's Tool Router MCP layer.
Key takeaways:
- Tool Router dynamically exposes Bigmailer tools through an MCP endpoint
- LlamaIndex's ReActAgent handles reasoning and orchestration; Composio handles integrations
- The agent becomes more capable without increasing prompt size
- Async Python provides clean, efficient execution of agent workflows
You can easily extend this to other toolkits like Gmail, Notion, Stripe, GitHub, and more by adding them to the toolkits parameter.

## How to build Bigmailer MCP Agent with another framework

- [OpenAI Agents SDK](https://composio.dev/toolkits/bigmailer/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/bigmailer/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/bigmailer/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/bigmailer/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/bigmailer/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/bigmailer/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/bigmailer/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/bigmailer/framework/cli)
- [Google ADK](https://composio.dev/toolkits/bigmailer/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/bigmailer/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/bigmailer/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/bigmailer/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/bigmailer/framework/crew-ai)

## Related Toolkits

- [Reddit](https://composio.dev/toolkits/reddit) - Reddit is a social news platform with thriving user-driven communities (subreddits). It's the go-to place for discussion, content sharing, and viral marketing.
- [Facebook](https://composio.dev/toolkits/facebook) - Facebook is a social media and advertising platform for businesses and creators. It helps you connect, share, and manage content across your public Facebook Pages.
- [Linkedin](https://composio.dev/toolkits/linkedin) - LinkedIn is a professional networking platform for connecting, sharing content, and engaging with business opportunities. It's the go-to place for building your professional brand and unlocking new career connections.
- [Active campaign](https://composio.dev/toolkits/active_campaign) - ActiveCampaign is a marketing automation and CRM platform for managing email campaigns, sales pipelines, and customer segmentation. It helps businesses engage customers and drive growth through smart automation and targeted outreach.
- [ActiveTrail](https://composio.dev/toolkits/active_trail) - ActiveTrail is a user-friendly email marketing and automation platform. It helps you reach subscribers and automate campaigns with ease.
- [Ahrefs](https://composio.dev/toolkits/ahrefs) - Ahrefs is an SEO and marketing platform for site audits, keyword research, and competitor insights. It helps you improve search rankings and drive organic traffic.
- [Amcards](https://composio.dev/toolkits/amcards) - AMCards lets you create and mail personalized greeting cards online. Build stronger customer relationships with easy, automated card campaigns.
- [Beamer](https://composio.dev/toolkits/beamer) - Beamer is a news and changelog platform for in-app announcements and feature updates. It helps companies boost user engagement by sharing news where users are most active.
- [Benchmark email](https://composio.dev/toolkits/benchmark_email) - Benchmark Email is a platform for creating, sending, and tracking email campaigns. It's built to help you engage audiences and analyze results—all in one place.
- [Brandfetch](https://composio.dev/toolkits/brandfetch) - Brandfetch is an API that delivers company logos, colors, and visual branding assets. It helps marketers and developers keep brand visuals consistent everywhere.
- [Brevo](https://composio.dev/toolkits/brevo) - Brevo is an all-in-one email and SMS marketing platform for transactional messaging, automation, and CRM. It helps businesses engage customers and streamline communications through powerful campaign tools.
- [Campayn](https://composio.dev/toolkits/campayn) - Campayn is an email marketing platform for creating, sending, and managing campaigns. It helps businesses engage contacts and grow audiences with easy-to-use tools.
- [Cardly](https://composio.dev/toolkits/cardly) - Cardly is a platform for creating and sending personalized direct mail to customers. It helps businesses break through the digital clutter by getting real engagement via physical mailboxes.
- [ClickSend](https://composio.dev/toolkits/clicksend) - ClickSend is a cloud-based SMS and email marketing platform for businesses. It streamlines communication by enabling quick message delivery and contact management.
- [Crustdata](https://composio.dev/toolkits/crustdata) - CrustData is an AI-powered data intelligence platform for real-time company and people data. It helps B2B sales teams, AI SDRs, and investors react to live business signals.
- [Curated](https://composio.dev/toolkits/curated) - Curated is a platform for collecting, curating, and publishing newsletters. It streamlines content aggregation and distribution for creators and teams.
- [Customerio](https://composio.dev/toolkits/customerio) - Customer.io is a customer engagement platform for targeted messaging across email, SMS, and push. Easily automate, segment, and track communications with your audience.
- [Cutt ly](https://composio.dev/toolkits/cutt_ly) - Cutt.ly is a URL shortening service for managing and analyzing links. Streamline your workflows with quick, trackable, and branded short URLs.
- [Demio](https://composio.dev/toolkits/demio) - Demio is webinar software built for marketers, offering both live and automated sessions with interactive features. It helps teams engage audiences and optimize lead generation through detailed analytics.
- [Doppler marketing automation](https://composio.dev/toolkits/doppler_marketing_automation) - Doppler marketing automation is a platform for creating, sending, and tracking email campaigns. It helps you automate marketing workflows and manage subscriber lists for better engagement.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Bigmailer MCP?

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

### Can I use Tool Router MCP with LlamaIndex?

Yes, you can. LlamaIndex 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 Bigmailer tools.

### Can I manage the permissions and scopes for Bigmailer while using Tool Router?

Yes, absolutely. You can configure which Bigmailer 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.

### How safe is my data with Composio Tool Router?

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 Bigmailer data and credentials are handled as safely as possible.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
