# How to integrate Instantly MCP with LlamaIndex

```json
{
  "title": "How to integrate Instantly MCP with LlamaIndex",
  "toolkit": "Instantly",
  "toolkit_slug": "instantly",
  "framework": "LlamaIndex",
  "framework_slug": "llama-index",
  "url": "https://composio.dev/toolkits/instantly/framework/llama-index",
  "markdown_url": "https://composio.dev/toolkits/instantly/framework/llama-index.md",
  "updated_at": "2026-05-06T08:16:41.601Z"
}
```

## Introduction

This guide walks you through connecting Instantly to LlamaIndex using the Composio tool router. By the end, you'll have a working Instantly agent that can create a new cold email campaign, add a new lead to your campaign, check unread emails in your inbox through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Instantly account through Composio's Instantly MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Instantly with

- [OpenAI Agents SDK](https://composio.dev/toolkits/instantly/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/instantly/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/instantly/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/instantly/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/instantly/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/instantly/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/instantly/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/instantly/framework/cli)
- [Google ADK](https://composio.dev/toolkits/instantly/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/instantly/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/instantly/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/instantly/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/instantly/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 Instantly
- Connect LlamaIndex to the Instantly MCP server
- Build a Instantly-powered agent using LlamaIndex
- Interact with Instantly 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 Instantly MCP server, and what's possible with it?

The Instantly MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Instantly account. It provides structured and secure access to your campaigns, leads, and outreach tools, so your agent can perform actions like launching new campaigns, managing leads, tracking inbox statistics, and handling API credentials on your behalf.
- Automated campaign creation and management: Ask your agent to launch new cold email campaigns or update existing ones, streamlining your outreach workflow without manual setup.
- Lead and lead list management: Let your agent add new leads, organize them into lists, or enrich them with AI-driven insights to maximize your campaign effectiveness.
- Email verification and deliverability tracking: Direct your agent to check the verification status of email addresses or run inbox placement tests to monitor and improve deliverability across providers.
- Inbox activity monitoring: Fetch unread email counts or campaign engagement metrics, helping you stay on top of your outreach performance in real time.
- API key and webhook automation: Have your agent create or delete API keys for secure integrations, or set up webhooks to receive instant notifications about important Instantly events.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `INSTANTLY_CHECK_EMAIL_VERIFICATION_STATUS` | Check Email Verification Status | Tool to check status of an email verification job. Use after submitting a verification request to retrieve the current status of a specific email address. |
| `INSTANTLY_COUNT_UNREAD_EMAILS` | Count Unread Emails | Tool to retrieve the count of unread emails. Use when you need to know how many unread messages are in your inbox before sending new emails. |
| `INSTANTLY_CREATE_AI_ENRICHMENT` | Create AI Enrichment | Tool to create an AI enrichment job for a campaign or lead list. Use when you need to enrich a resource with AI-driven insights. |
| `INSTANTLY_CREATE_API_KEY` | Create API Key | Tool to create a new API key. Use when you need to generate credentials for programmatic access to the Instantly API. |
| `INSTANTLY_CREATE_CAMPAIGN` | Create Campaign | Tool to create a new campaign. Use when you have campaign details ready and want to launch. |
| `INSTANTLY_CREATE_INBOX_PLACEMENT_TEST` | Create Inbox Placement Test | Tool to create an inbox placement test. Use when you need to measure deliverability across providers with your prepared email and recipient list. |
| `INSTANTLY_CREATE_LEAD` | Create Lead | Tool to create a new lead. Use when you need to add an individual lead to a campaign. |
| `INSTANTLY_CREATE_LEAD_LIST` | Create Lead List | Tool to create a new lead list. Use when you need to organize leads into a dedicated list before importing them into campaigns. |
| `INSTANTLY_CREATE_WEBHOOK` | Create Webhook | Tool to create a new webhook endpoint. Use when you need to receive Instantly event notifications via HTTP callbacks. |
| `INSTANTLY_DELETE_API_KEY` | Delete API Key | Tool to delete an API key. Use when you need to remove a specific API key by its ID after confirming its existence. |
| `INSTANTLY_DELETE_CAMPAIGN` | Delete Campaign | Tool to delete a campaign. Use when you need to remove a specific campaign by ID. |
| `INSTANTLY_DELETE_LEAD` | Delete Lead | Tool to delete a lead by its ID. Use when you need to remove a specific lead after confirming its existence. |
| `INSTANTLY_DELETE_LEAD_LIST` | Delete Lead List | Tool to delete a lead list by ID. Use when you need to remove a specific lead list after confirming its existence. |
| `INSTANTLY_DELETE_WEBHOOK` | Delete Webhook | Tool to delete a webhook. Use when you need to remove a specific webhook by its UUID. |
| `INSTANTLY_DISABLE_ACCOUNT_WARMUP` | Disable Account Warmup | Tool to disable the warm-up process for email accounts. Use when you need to stop warmup for specific or all accounts before sending critical campaigns. |
| `INSTANTLY_ENABLE_ACCOUNT_WARMUP` | Enable Account Warmup | Tool to enable the warm-up process for email accounts. Use when you want to start warming up one or more accounts to improve deliverability. |
| `INSTANTLY_GET_CAMPAIGN` | Get Campaign | Tool to retrieve campaign details. Use when you need full campaign configuration for a given campaign ID. |
| `INSTANTLY_GET_CAMPAIGN_ANALYTICS` | Get Campaign Analytics | Tool to retrieve analytics for campaigns. Use when you need performance metrics for one or multiple campaigns. |
| `INSTANTLY_GET_DAILY_CAMPAIGN_ANALYTICS` | Get Daily Campaign Analytics | Tool to retrieve daily analytics for a campaign. Use when you need per-day performance metrics for campaigns. |
| `INSTANTLY_GET_EMAIL_SERVICE_PROVIDER_OPTIONS` | Get Email Service Provider Options | Tool to retrieve email service provider options for inbox placement tests. Use when you need valid recipients_labels options. |
| `INSTANTLY_GET_INBOX_PLACEMENT_TEST` | Get Inbox Placement Test | Tool to retrieve inbox placement test results. Use when you need details for a specific inbox placement test by ID. |
| `INSTANTLY_GET_LEAD` | Get Lead | Tool to retrieve details of a specific lead by its ID. Use when you have the lead UUID and need full lead metadata. |
| `INSTANTLY_GET_LEAD_LIST` | Get Lead List | Tool to retrieve details of a specific lead list by its ID. Use when you have the lead list UUID and need list metadata. |
| `INSTANTLY_GET_VERIFICATION_STATS_FOR_LEAD_LIST` | Get Lead List Verification Stats | Tool to retrieve verification statistics for a lead list. Use when you need summary counts by verification status for a specific lead list. |
| `INSTANTLY_GET_WEBHOOK` | Get Webhook | Tool to retrieve details of a specific webhook subscription. Use when you have the webhook ID and need full webhook configuration. |
| `INSTANTLY_GET_WEBHOOK_EVENT` | Get Webhook Event | Tool to retrieve details of a specific webhook event. Use when you need to inspect a particular webhook event by its ID. |
| `INSTANTLY_LIST_ACCOUNTS` | List Email Accounts | Tool to list all email accounts for the authenticated user. Use after obtaining auth credentials to retrieve available accounts. |
| `INSTANTLY_LIST_API_KEYS` | List API Keys | Tool to list all API keys. Use when you need to retrieve your API keys with optional pagination after authentication. |
| `INSTANTLY_LIST_CAMPAIGNS` | List Campaigns | Tool to list all campaigns. Use when you need to fetch your campaigns list with optional filters and pagination. |
| `INSTANTLY_LIST_CUSTOM_TAGS` | List Custom Tags | Tool to list custom tags. Use when you need to retrieve custom tags with optional pagination and filtering. |
| `INSTANTLY_LIST_DFY_EMAIL_ACCOUNT_ORDERS` | List DFY Email Account Orders | Tool to list DFY email account orders. Use when you need to fetch your DFY email account orders with pagination. |
| `INSTANTLY_LIST_EMAILS` | List Emails | Tool to list emails. Use when you need to retrieve emails with optional filters and pagination. |
| `INSTANTLY_LIST_INBOX_PLACEMENT_BLACKLIST_AND_SPAM_ASSASSIN_REPORTS` | List Inbox Placement Blacklist & SpamAssassin Reports | Tool to list inbox placement blacklist & SpamAssassin reports. Use when you need to retrieve spam and blacklist analytics after running an inbox placement test. |
| `INSTANTLY_LIST_INBOX_PLACEMENT_TESTS` | List Inbox Placement Tests | Tool to list inbox placement tests. Use when you need a paginated overview of tests with optional filtering and sort order. |
| `INSTANTLY_LIST_LEAD_LISTS` | List Lead Lists | Tool to list all lead lists. Use when you need to fetch the lead lists with optional filters and pagination. |
| `INSTANTLY_LIST_LEADS` | List Leads | Tool to list leads. Use when you need to retrieve leads with optional filters like search, status filters, and pagination. |
| `INSTANTLY_LIST_THREADS` | List Email Threads | Tool to list email threads. Use when fetching threads with optional pagination and unread-only filtering. Note: Instantly's public API does not expose a dedicated GET /emails/threads endpoint. Threads can be derived by grouping emails (GET /emails) by their `thread_id`. This action implements that logic by querying /emails and aggregating into threads. |
| `INSTANTLY_LIST_WEBHOOK_EVENTS` | List Webhook Events | Tool to list webhook events. Use when you need to view received webhook events with optional pagination and filters. |
| `INSTANTLY_LIST_WEBHOOKS` | List Webhooks | Tool to list configured webhooks. Use when you need to retrieve your webhook configurations with optional filters and pagination. |
| `INSTANTLY_MARK_THREAD_AS_READ` | Mark Thread As Read | Tool to mark all emails in a specific thread as read. Use when you want to update the read status of an email thread after processing. |
| `INSTANTLY_MERGE_LEADS` | Merge Leads | Tool to merge multiple leads into a single lead. Use after confirming both source and destination lead IDs exist. |
| `INSTANTLY_SEARCH_CAMPAIGNS_BY_LEAD_EMAIL` | Search Campaigns by Lead Email | Tool to search campaigns by a lead's email address. Use when you need to find campaigns containing a specific lead by their email. |
| `INSTANTLY_UPDATE_CAMPAIGN` | Update Campaign | Tool to update details of a campaign. Use when you need to modify campaign settings after verifying its ID. |
| `INSTANTLY_UPDATE_LEAD` | Update Lead | Tool to update a lead's details. Use when you need to modify fields of an existing lead after identifying its ID. |
| `INSTANTLY_UPDATE_LEAD_INTEREST_STATUS` | Update Lead Interest Status | Tool to update a lead's interest status. Use when you need to set or reset a lead’s interest status for follow-up actions. |
| `INSTANTLY_UPDATE_LEAD_LIST` | Update Lead List | Tool to update details of a specific lead list by its ID. Use after verifying the list ID exists. |
| `INSTANTLY_VERIFY_EMAIL` | Verify Email | Tool to initiate email verification. Use when you need to verify an email's deliverability before sending emails. |

## Supported Triggers

None listed.

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

The Instantly MCP server is an implementation of the Model Context Protocol that connects your AI agent to Instantly. It provides structured and secure access so your agent can perform Instantly 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 Instantly account and project
- Basic familiarity with async Python/Typescript

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

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 Instantly 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, instantly)
- 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 Instantly 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=["instantly"],
    )

    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 Instantly actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Instantly 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: ["instantly"],
    },
  );

  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 Instantly 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 Instantly
```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 Instantly, 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=["instantly"],
    )

    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 Instantly actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Instantly 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: ["instantly"],
    },
  );

  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 Instantly 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 Instantly to LlamaIndex through Composio's Tool Router MCP layer.
Key takeaways:
- Tool Router dynamically exposes Instantly 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 Instantly MCP Agent with another framework

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

## Related Toolkits

- [Metaads](https://composio.dev/toolkits/metaads) - Metaads is Meta's official Ads API that lets you manage, analyze, and optimize your Facebook and Instagram ad campaigns. Streamline ad operations and gain deeper insights with robust automation.
- [Adrapid](https://composio.dev/toolkits/adrapid) - Adrapid is a platform for rapid creation of digital marketing visuals using templates. It streamlines design workflows for banners, images, and HTML5 content with automation.
- [Adyntel](https://composio.dev/toolkits/adyntel) - Adyntel is an API that retrieves LinkedIn ads for any company using a domain or LinkedIn Page ID. Easily access competitive ad intelligence to power your marketing workflows.
- [Beaconstac](https://composio.dev/toolkits/beaconstac) - Beaconstac is a platform for creating and managing QR codes and proximity beacons. It helps businesses engage customers and track marketing performance with powerful analytics.
- [Campaign cleaner](https://composio.dev/toolkits/campaign_cleaner) - Campaign cleaner is an email campaign optimization tool that boosts compatibility and deliverability across email clients. It helps marketers get better results by cleaning, enhancing, and ensuring high performance for every campaign.
- [Deadline funnel](https://composio.dev/toolkits/deadline_funnel) - Deadline Funnel lets you create personalized deadlines and timers for your marketing campaigns. It helps marketers boost conversions by adding authentic urgency to offers.
- [Google Ads](https://composio.dev/toolkits/googleads) - Google Ads is Google's online advertising platform for creating, managing, and optimizing digital campaigns. It helps businesses reach targeted customers and maximize return on ad spend.
- [Proofly](https://composio.dev/toolkits/proofly) - Proofly is a social proof platform that displays real-time notifications of customer activity on your site. It helps you increase website conversions by building trust and urgency for visitors.
- [Segmetrics](https://composio.dev/toolkits/segmetrics) - Segmetrics is a marketing analytics platform that reveals detailed insights into your customer journeys. It helps businesses optimize marketing strategies with accurate, actionable reporting.
- [Semrush](https://composio.dev/toolkits/semrush) - Semrush is a leading SEO tool suite for keyword research, competitor analysis, and campaign tracking. It empowers marketers to improve search rankings and optimize online visibility.
- [Sendloop](https://composio.dev/toolkits/sendloop) - Sendloop is an all-in-one email marketing platform built for SaaS, e-commerce, and small businesses. It makes it easy to send campaigns, manage lists, and track results—all in one place.
- [Sidetracker](https://composio.dev/toolkits/sidetracker) - Sidetracker is a marketing analytics platform that tracks expenses, sales funnels, and customer journeys. It helps optimize marketing spend and visualize campaign performance from start to finish.
- [Stannp](https://composio.dev/toolkits/stannp) - Stannp is an API-driven direct mail platform for sending postcards and letters programmatically. It lets you automate physical mail delivery—no manual printing or mailing required.
- [Tapfiliate](https://composio.dev/toolkits/tapfiliate) - Tapfiliate is an affiliate and referral tracking platform for businesses. It helps companies efficiently manage, track, and grow their affiliate programs.
- [Tpscheck](https://composio.dev/toolkits/tpscheck) - Tpscheck is a real-time service for verifying UK phone numbers against TPS and CTPS registers. It helps prevent unwanted marketing calls and ensures compliance with UK telemarketing laws.
- [Gmail](https://composio.dev/toolkits/gmail) - Gmail is Google's email service with powerful spam protection, search, and G Suite integration. It keeps your inbox organized and makes communication fast and reliable.
- [Google Calendar](https://composio.dev/toolkits/googlecalendar) - Google Calendar is a time management service for scheduling meetings, events, and reminders. It streamlines personal and team organization with integrated notifications and sharing options.
- [Google Drive](https://composio.dev/toolkits/googledrive) - Google Drive is a cloud storage platform for uploading, sharing, and collaborating on files. It's perfect for keeping your documents accessible and organized across devices.
- [Outlook](https://composio.dev/toolkits/outlook) - Outlook is Microsoft's email and calendaring platform for unified communications and scheduling. It helps users stay organized with powerful email, contacts, and calendar management.
- [Twitter](https://composio.dev/toolkits/twitter) - Twitter is a social media platform for sharing real-time updates, conversations, and news. Stay connected, informed, and engaged with communities worldwide.

## Frequently Asked Questions

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

With a standalone Instantly MCP server, the agents and LLMs can only access a fixed set of Instantly tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Instantly 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 Instantly tools.

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

Yes, absolutely. You can configure which Instantly 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 Instantly data and credentials are handled as safely as possible.

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