# How to integrate Sendbird MCP with LlamaIndex

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

## Introduction

This guide walks you through connecting Sendbird to LlamaIndex using the Composio tool router. By the end, you'll have a working Sendbird agent that can add users to a group chat channel, ban a disruptive user from group chat, get unread message count for a user through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Sendbird account through Composio's Sendbird MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Sendbird with

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

The Sendbird MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Sendbird account. It provides structured and secure access to your in-app chat, voice, and video features, so your agent can perform actions like creating group channels, managing users, moderating conversations, and tracking unread message counts on your behalf.
- Group channel management: Let your agent create new group channels, add or ban members, and delete channels as needed to keep conversations organized and secure.
- User account administration: Automatically register new users or remove users from your Sendbird application, simplifying user lifecycle management.
- Message moderation and cleanup: Empower your agent to delete specific messages—helping enforce community guidelines and remove unwanted content instantly.
- Unread count and status tracking: Retrieve up-to-date counts of unread messages, mentions, and channel invitations for any user to surface important conversations.
- Channel preference insights: Access and update user count preferences in group channels, tailoring notification and message delivery based on user needs.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `SENDBIRD_ADD_MEMBERS_GROUP_CHANNEL` | Add Members To Group Channel | Tool to add members to a group channel. Use when you need to invite one or more users into an existing group channel. |
| `SENDBIRD_BAN_USER_FROM_GROUP_CHANNEL` | Ban User from Group Channel | Tool to ban a user from a group channel. Use when moderating group channels to restrict member access. Execute after confirming channel_url and user_id. |
| `SENDBIRD_CREATE_CHANNEL` | Create Group Channel | Tool to create a new group channel. Use when you need to start a conversation with specific users. Execute after specifying users and optional settings. |
| `SENDBIRD_CREATE_USER` | Create Sendbird User | Creates a new user in Sendbird. Use this to register user accounts before they can join channels or send messages. The user_id must be unique across the application. |
| `SENDBIRD_DELETE_CHANNEL` | Delete Group Channel | Permanently deletes a Sendbird group channel. Use this tool when you need to remove a group channel and all its associated data (messages, members, etc.). WARNING: This action is irreversible. Requires the channel_url identifier of the channel to delete. |
| `SENDBIRD_DELETE_MESSAGE` | Delete Message | Permanently deletes a specific message from a Sendbird group channel. This action cannot be undone. Use this when you need to remove a message that was sent by mistake or contains inappropriate content. Requires both channel_url and message_id, which can be obtained from channel/message listing endpoints. |
| `SENDBIRD_DELETE_USER` | Delete Sendbird User | Tool to delete a Sendbird user. Use when you need to remove a user from your Sendbird application, optionally permanently. |
| `SENDBIRD_GET_COUNT_PREFERENCE_OF_CHANNEL` | Get Count Preference Of Channel | Tool to retrieve a user's count preference for a specific group channel. Use after confirming the user and channel exist to determine whether to display all, unread-only, or mention-only counts. |
| `SENDBIRD_GET_NUMBER_OF_CHANNELS_BY_JOIN_STATUS` | Get User Group Channel Count by Join Status | Retrieves the number of group channels for a user, categorized by join status (joined, invited, etc.). Use this tool to get channel count statistics for a specific user, optionally filtered by channel properties like visibility (public/private), distinctness, or super mode. Returns counts of joined channels, invited channels (with friend/non-friend breakdown), and total count. |
| `SENDBIRD_GET_NUMBER_OF_UNREAD_ITEMS` | Sendbird Get Unread Item Count | Tool to retrieve a user's unread item counts including unread messages, mentions, and pending invitations across group channels. Use this to display unread counts in the UI for a specific user. |
| `SENDBIRD_ISSUE_SESSION_TOKEN` | Issue Session Token | Issues a session token for authenticating a Sendbird user. Use this tool when you need to: - Generate a new session token for SDK authentication - Refresh an expiring or expired session token - Provide secure access for a user to connect to Sendbird chat The session token has a default expiration of 7 days if expires_at is not specified. |
| `SENDBIRD_LEAVE_GROUP_CHANNELS` | Leave Group Channels | Tool to leave group channels for a user. Use when you need to make a user exit one or more joined group channels. |
| `SENDBIRD_LIST_BANNED_MEMBERS` | List Banned Members | Tool to list banned members in a group channel. Use when you need to see which users are banned from a specific group channel. |
| `SENDBIRD_LIST_GROUP_CHANNEL_MESSAGES` | Sendbird List Group Channel Messages | Tool to list (paginate) messages in a group channel when you only know the channel_url. Requires either message_ts (Unix ms timestamp) or message_id as an anchor. Use with SENDBIRD_VIEW_GROUP_CHANNEL (show_read_receipt=true) to fetch unread messages: get last-read timestamp, then call this with message_ts=, prev_limit=0, next_limit=, include=false. |
| `SENDBIRD_LIST_GROUP_CHANNELS` | List Group Channels | Tool to list group channels. Use when you need to fetch paginated group channels with optional filters. |
| `SENDBIRD_LIST_MEMBERS_GROUP_CHANNEL` | List Group Channel Members | Tool to list members of a group channel. Use when you need to paginate through members of a specified group channel. |
| `SENDBIRD_LIST_OPERATORS_CUSTOM_CHANNEL_TYPE` | List Operators by Custom Channel Type | Tool to list operators of a channel by custom channel type. Use when you need to fetch operators for a specific custom channel type with pagination. |
| `SENDBIRD_LIST_OPERATORS_GROUP_CHANNEL` | List Group Channel Operators | Tool to list operators of a group channel. Use after specifying the channel_url when needing to paginate through operators. |
| `SENDBIRD_LIST_OPERATORS_OPEN_CHANNEL` | List Open Channel Operators | Tool to list operators of an open channel. Use when you have the open channel URL and need to fetch its operators. Supports pagination via token and limit. |
| `SENDBIRD_LIST_USERS` | List Sendbird Users | Retrieves a paginated list of users from your Sendbird application. Use this tool to: - Browse all users in your application - Search for users by nickname or user IDs - Filter users by metadata, custom type, or activity status - Paginate through large user lists using the 'next' token Returns user details including profile info, connection status, and metadata. Results are paginated; use the 'next' token from the response to fetch additional pages. |
| `SENDBIRD_MARK_ALL_USER_MESSAGES_AS_READ` | Mark All User Messages As Read | Tool to mark all of a user's messages as read in group channels. Use when resetting unread message counts after a user has viewed all messages. |
| `SENDBIRD_MUTE_USER` | Mute User | Tool to mute a user in a group channel. Use when you need to prevent a user from sending messages for a specified duration. |
| `SENDBIRD_REGISTER_OPERATORS_CUSTOM_CHANNEL_TYPE` | Register Operators by Custom Channel Type | Registers one or more users as operators for all channels with a specified custom channel type. Use this tool when you need to grant operator privileges to users across all channels that share the same custom_type. Operators have elevated permissions including: - Muting and banning users from channels - Deleting messages in channels - Freezing/unfreezing channels - Managing channel settings Prerequisites: - The user IDs must belong to existing Sendbird users - The custom_type should match channels you want to manage Note: This affects all channels with the specified custom_type, not just a single channel. |
| `SENDBIRD_REGISTER_OPERATORS_GROUP_CHANNEL` | Register Group Channel Operators | Tool to register one or more users as operators in a Sendbird group channel. Use when elevating permissions of existing channel members. |
| `SENDBIRD_REGISTER_OPERATORS_OPEN_CHANNEL` | Register Operators to Open Channel | Tool to register operators to an open channel. Use after creating or updating an open channel when you need to assign operator roles. |
| `SENDBIRD_REVOKE_ALL_SESSION_TOKENS` | Revoke All Session Tokens | Tool to revoke all session tokens for a user. Use when you need to invalidate all active sessions for security. |
| `SENDBIRD_SEND_MESSAGE` | Send Message | Tool to send a message to a group channel. Use when you need to post a text, file, or admin message to an existing group channel. |
| `SENDBIRD_UNBAN_USER` | Unban User from Group Channel | Tool to unban a user from a group channel. Use when reinstating a previously banned user. Execute after confirming the user is currently banned. |
| `SENDBIRD_UNMUTE_USER` | Unmute User | Tool to unmute a user in a group channel. Use when you want to restore a muted user's ability to send messages after confirming they are muted. |
| `SENDBIRD_UNREGISTER_OPERATORS_CUSTOM_CHANNEL_TYPE` | Unregister Operators Custom Channel Type | Tool to unregister operators from channels by custom channel type. Use when you need to remove operator roles from users across channels of a specific custom type. |
| `SENDBIRD_UPDATE_COUNT_PREFERENCE_OF_CHANNEL` | Update Count Preference Of Channel | Tool to update a user's unread count preference for a specific group channel. Use when you want to include or suppress a channel in the user's unread counts. |
| `SENDBIRD_UPDATE_GROUP_CHANNEL` | Update Group Channel | Tool to update group channel information. Use when you need to modify channel attributes such as name, cover image, privacy settings, or operator list after channel creation. |
| `SENDBIRD_UPDATE_MESSAGE` | Sendbird Update Message | Tool to update an existing group channel message in Sendbird. Use after you need to modify content or metadata of a sent message. |
| `SENDBIRD_UPDATE_USER` | Update Sendbird User | Tool to update a user's information. Use when modifying nickname, profile image URL, activation status, or metadata. |
| `SENDBIRD_VIEW_GROUP_CHANNEL` | Sendbird View Group Channel | Tool to view information about a specific group channel. Use when you need channel details after confirming the channel_url. |
| `SENDBIRD_VIEW_MESSAGE` | Sendbird View Message | Tool to view a specific message in a group channel. Use after confirming channel_url and message_id. |
| `SENDBIRD_VIEW_USER` | View User | Tool to retrieve information about a specific Sendbird user. Use when you need to fetch detailed user data by their user ID. |

## Supported Triggers

None listed.

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

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

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

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 Sendbird 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, sendbird)
- 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 Sendbird 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=["sendbird"],
    )

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

  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 Sendbird 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 Sendbird
```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 Sendbird, 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=["sendbird"],
    )

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

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

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

## Related Toolkits

- [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.
- [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.
- [Slack](https://composio.dev/toolkits/slack) - Slack is a channel-based messaging platform for teams and organizations. It helps people collaborate in real time, share files, and connect all their tools in one place.
- [Gong](https://composio.dev/toolkits/gong) - Gong is a platform for video meetings, call recording, and team collaboration. It helps teams capture conversations, analyze calls, and turn insights into action.
- [Microsoft teams](https://composio.dev/toolkits/microsoft_teams) - Microsoft Teams is a collaboration platform that combines chat, meetings, and file sharing within Microsoft 365. It keeps distributed teams connected and productive through seamless virtual communication.
- [Slackbot](https://composio.dev/toolkits/slackbot) - Slackbot is a conversational automation tool for Slack that handles reminders, notifications, and automated responses. It boosts team productivity by streamlining onboarding, answering FAQs, and managing timely alerts—all right inside Slack.
- [2chat](https://composio.dev/toolkits/_2chat) - 2chat is an API platform for WhatsApp and multichannel text messaging. It streamlines chat automation, group management, and real-time messaging for developers.
- [Agent mail](https://composio.dev/toolkits/agent_mail) - Agent mail provides AI agents with dedicated email inboxes for sending, receiving, and managing emails. It empowers agents to communicate autonomously with people, services, and other agents—no human intervention needed.
- [Basecamp](https://composio.dev/toolkits/basecamp) - Basecamp is a project management and team collaboration tool by 37signals. It helps teams organize tasks, share files, and communicate efficiently in one place.
- [Chatwork](https://composio.dev/toolkits/chatwork) - Chatwork is a team communication platform with group chats, file sharing, and task management. It helps businesses boost collaboration and streamline productivity.
- [Clickmeeting](https://composio.dev/toolkits/clickmeeting) - ClickMeeting is a cloud-based platform for running online meetings and webinars. It helps businesses and individuals host, manage, and engage virtual audiences with ease.
- [Confluence](https://composio.dev/toolkits/confluence) - Confluence is Atlassian's team collaboration and knowledge management platform. It helps your team organize, share, and update documents and project content in one secure workspace.
- [Dailybot](https://composio.dev/toolkits/dailybot) - DailyBot streamlines team collaboration with chat-based standups, reminders, and polls. It keeps work flowing smoothly in your favorite messaging platforms.
- [Dialmycalls](https://composio.dev/toolkits/dialmycalls) - Dialmycalls is a mass notification service for sending voice and text messages to contacts. It helps teams and organizations quickly broadcast urgent alerts and updates.
- [Dialpad](https://composio.dev/toolkits/dialpad) - Dialpad is a cloud-based business phone and contact center system for teams. It unifies voice, video, messaging, and meetings across your devices.
- [Discord](https://composio.dev/toolkits/discord) - Discord is a real-time messaging and VoIP platform for communities and teams. It lets users chat, share media, and collaborate across public and private channels.
- [Discordbot](https://composio.dev/toolkits/discordbot) - Discordbot is an automation tool for Discord servers that handles moderation, messaging, and user engagement. It helps communities run smoothly by automating routine and complex tasks.
- [Echtpost](https://composio.dev/toolkits/echtpost) - Echtpost is a secure digital communication platform for encrypted document and message exchange. It ensures confidential data stays private and protected during transmission.
- [Egnyte](https://composio.dev/toolkits/egnyte) - Egnyte is a cloud-based platform for secure file sharing, storage, and governance. It helps teams collaborate efficiently while maintaining data compliance and security.
- [Google Meet](https://composio.dev/toolkits/googlemeet) - Google Meet is a secure video conferencing platform for virtual meetings, chat, and screen sharing. It helps teams connect, collaborate, and communicate seamlessly from anywhere.

## Frequently Asked Questions

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

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

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

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

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