# How to integrate Bigmailer MCP with Vercel AI SDK v6

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

## Introduction

This guide walks you through connecting Bigmailer to Vercel AI SDK v6 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 Vercel AI SDK 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)
- [Mastra AI](https://composio.dev/toolkits/bigmailer/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/bigmailer/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/bigmailer/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- How to set up and configure a Vercel AI SDK agent with Bigmailer integration
- Using Composio's Tool Router to dynamically load and access Bigmailer tools
- Creating an MCP client connection using HTTP transport
- Building an interactive CLI chat interface with conversation history management
- Handling tool calls and results within the Vercel AI SDK framework

## What is Vercel AI SDK?

The Vercel AI SDK is a TypeScript library for building AI-powered applications. It provides tools for creating agents that can use external services and maintain conversation state.
Key features include:
- streamText: Core function for streaming responses with real-time tool support
- MCP Client: Built-in support for Model Context Protocol via @ai-sdk/mcp
- Step Counting: Control multi-step tool execution with stopWhen: stepCountIs()
- OpenAI Provider: Native integration with OpenAI models

## 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:
- Node.js and npm installed
- A Composio account with API key
- An OpenAI API key

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

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) 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](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Navigate to your API settings and generate a new API key.
- Store this key securely as you'll need it for authentication.

### 2. Install required dependencies

First, install the necessary packages for your project.
What you're installing:
- @ai-sdk/openai: Vercel AI SDK's OpenAI provider
- @ai-sdk/mcp: MCP client for Vercel AI SDK
- @composio/core: Composio SDK for tool integration
- ai: Core Vercel AI SDK
- dotenv: Environment variable management
```bash
npm install @ai-sdk/openai @ai-sdk/mcp @composio/core ai dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's needed:
- OPENAI_API_KEY: Your OpenAI API key for GPT model access
- COMPOSIO_API_KEY: Your Composio API key for tool access
- COMPOSIO_USER_ID: A unique identifier for the user session
```bash
OPENAI_API_KEY=your_openai_api_key_here
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
```

### 4. Import required modules and validate environment

What's happening:
- We're importing all necessary libraries including Vercel AI SDK's OpenAI provider and Composio
- The dotenv/config import automatically loads environment variables
- The MCP client import enables connection to Composio's tool server
```typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

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

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

const composio = new Composio({
  apiKey: composioAPIKey,
});
```

### 5. Create Tool Router session and initialize MCP client

What's happening:
- We're creating a Tool Router session that gives your agent access to Bigmailer tools
- The create method takes the user ID and specifies which toolkits should be available
- The returned mcp object contains the URL and authentication headers needed to connect to the MCP server
- This session provides access to all Bigmailer-related tools through the MCP protocol
```typescript
async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["bigmailer"],
  });

  const mcpUrl = session.mcp.url;
```

### 6. Connect to MCP server and retrieve tools

What's happening:
- We're creating an MCP client that connects to our Composio Tool Router session via HTTP
- The mcp.url provides the endpoint, and mcp.headers contains authentication credentials
- The type: "http" is important - Composio requires HTTP transport
- tools() retrieves all available Bigmailer tools that the agent can use
```typescript
const mcpClient = await createMCPClient({
  transport: {
    type: "http",
    url: mcpUrl,
    headers: session.mcp.headers, // Authentication headers for the Composio MCP server
  },
});

const tools = await mcpClient.tools();
```

### 7. Initialize conversation and CLI interface

What's happening:
- We initialize an empty messages array to maintain conversation history
- A readline interface is created to accept user input from the command line
- Instructions are displayed to guide the user on how to interact with the agent
```typescript
let messages: ModelMessage[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log(
  "Ask any questions related to bigmailer, like summarize my last 5 emails, send an email, etc... :)))\n",
);

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

rl.prompt();
```

### 8. Handle user input and stream responses with real-time tool feedback

What's happening:
- We use streamText instead of generateText to stream responses in real-time
- toolChoice: "auto" allows the model to decide when to use Bigmailer tools
- stopWhen: stepCountIs(10) allows up to 10 steps for complex multi-tool operations
- onStepFinish callback displays which tools are being used in real-time
- We iterate through the text stream to create a typewriter effect as the agent responds
- The complete response is added to conversation history to maintain context
- Errors are caught and displayed with helpful retry suggestions
```typescript
rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

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

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

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

  try {
    const stream = streamText({
      model: openai("gpt-5"),
      messages,
      tools,
      toolChoice: "auto",
      stopWhen: stepCountIs(10),
      onStepFinish: (step) => {
        for (const toolCall of step.toolCalls) {
          console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

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

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

## Complete Code

```typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

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

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

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

async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["bigmailer"],
  });

  const mcpUrl = session.mcp.url;

  const mcpClient = await createMCPClient({
    transport: {
      type: "http",
      url: mcpUrl,
      headers: session.mcp.headers, // Authentication headers for the Composio MCP server
    },
  });

  const tools = await mcpClient.tools();

  let messages: ModelMessage[] = [];

  console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
  console.log(
    "Ask any questions related to bigmailer, like summarize my last 5 emails, send an email, etc... :)))\n",
  );

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

  rl.prompt();

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

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

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

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

    try {
      const stream = streamText({
        model: openai("gpt-5"),
        messages,
        tools,
        toolChoice: "auto",
        stopWhen: stepCountIs(10),
        onStepFinish: (step) => {
          for (const toolCall of step.toolCalls) {
            console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

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

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

## Conclusion

You've successfully built a Bigmailer agent using the Vercel AI SDK with streaming capabilities! This implementation provides a powerful foundation for building AI applications with natural language interfaces and real-time feedback.
Key features of this implementation:
- Real-time streaming responses for a better user experience with typewriter effect
- Live tool execution feedback showing which tools are being used as the agent works
- Dynamic tool loading through Composio's Tool Router with secure authentication
- Multi-step tool execution with configurable step limits (up to 10 steps)
- Comprehensive error handling for robust agent execution
- Conversation history maintenance for context-aware responses
You can extend this further by adding custom error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

## 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)
- [Mastra AI](https://composio.dev/toolkits/bigmailer/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/bigmailer/framework/llama-index)
- [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 Vercel AI SDK v6?

Yes, you can. Vercel AI SDK v6 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)
