# How to integrate Kommo MCP with LlamaIndex

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

## Introduction

This guide walks you through connecting Kommo to LlamaIndex using the Composio tool router. By the end, you'll have a working Kommo agent that can add a new lead with contact info, list all companies created this week, create a follow-up task for a lead through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Kommo account through Composio's Kommo MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Kommo with

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

The Kommo MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Kommo CRM account. It provides structured and secure access to your customer data, so your agent can perform actions like creating leads, managing contacts, tracking companies, organizing pipelines, and automating tasks on your behalf.
- Lead and pipeline management: Automatically create new leads, list existing leads, and organize them within your sales pipelines, helping you stay on top of every sales opportunity.
- Contact and company handling: Effortlessly add or list contacts and companies, making it simple for your agent to keep your CRM up to date and accessible.
- Task automation and tracking: Let your agent create tasks for follow-ups, reminders, or next steps, so nothing falls through the cracks in your customer relationships.
- Pipeline stage and custom field access: Retrieve and list pipeline stages and custom fields, enabling your agent to analyze and optimize your sales processes with tailored data.
- Business process automation: Leverage structured tools to automate repetitive actions like updating records or filtering data, saving you time and reducing manual effort.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `KOMMO_ADD_AI_SOURCE_FILE` | Add AI Source File | Tool to add a knowledge source file to Kommo AI. Use when you need to upload a file (like documentation, policies, or knowledge base articles) to be used by the Kommo AI agent or suggested reply feature. |
| `KOMMO_CREATE_COMPANY` | Create Kommo Companies | Action to add one or more companies into the Kommo account. |
| `KOMMO_CREATE_CONTACT` | Create Kommo Contact | Action to create one or more contacts in Kommo CRM. |
| `KOMMO_CREATE_LEAD` | Create Kommo Lead | Action to create a lead in Kommo CRM. |
| `KOMMO_CREATE_TASK` | Create Kommo Task | Action to create a task in Kommo CRM. |
| `KOMMO_DELETE_FILES` | Delete Kommo Files | Tool to delete files (move to trash) in Kommo. Use when you need to remove files from the Kommo account. |
| `KOMMO_GET_ACCOUNT` | Get Kommo Account | Tool to get account information including user data, custom fields, task types, user groups, amojo rights, and integration status. Use when you need to retrieve account-level details from Kommo CRM. |
| `KOMMO_GET_COMPANY` | Get Kommo Company | Tool to get a company by its ID from Kommo CRM. Use when you need to retrieve detailed information about a specific company including its name, responsible user, and optionally embedded data like contacts, leads, or catalog elements. |
| `KOMMO_GET_CONTACT` | Get Kommo Contact | Tool to get a specific contact by its ID from Kommo CRM. Use when you need to retrieve detailed information about a particular contact. |
| `KOMMO_GET_CUSTOM_FIELD` | Get Kommo Custom Field | Tool to retrieve a custom field by its ID from Kommo CRM. Use when you need detailed information about a specific custom field including its type, settings, and enum values. |
| `KOMMO_GET_EVENT` | Get Kommo Event | Tool to get a specific event by its ID from Kommo CRM. Use when you need to retrieve detailed information about a particular event, including before/after state changes for entities. |
| `KOMMO_GET_FIELD_GROUP` | Get Kommo Field Group | Tool to retrieve a custom field group by its ID from Kommo CRM. Use when you need to get details about a specific field group including its fields and metadata. |
| `KOMMO_GET_FILE_LINKS` | Get File Links | Tool to get entities associated with a file in Kommo. Use when you need to find which leads, contacts, companies, or catalog elements are linked to a specific file. |
| `KOMMO_GET_INCOMING_LEADS_SUMMARY` | Get Incoming Leads Summary | Tool to retrieve summary statistics for incoming (unsorted) leads in Kommo CRM. Use when you need aggregate metrics like total count, acceptance/decline rates, average processing time, and breakdown by lead source category. |
| `KOMMO_GET_LEAD` | Get Kommo Lead | Tool to get a lead by its ID from Kommo CRM. Use when you need to retrieve detailed information about a specific lead including its status, price, responsible user, and optionally embedded data like contacts, catalog elements, or loss reasons. |
| `KOMMO_GET_LOSS_REASON` | Get Kommo Loss Reason | Tool to retrieve a specific loss reason by its ID from Kommo CRM. Use when you need detailed information about a particular loss reason, such as its name, sort order, and timestamps. |
| `KOMMO_GET_PIPELINE` | Get Kommo Pipeline | Tool to get a pipeline by its ID from Kommo CRM. Use when you need to retrieve details about a specific pipeline including its stages. |
| `KOMMO_GET_PIPELINE_STATUS` | Get Kommo Pipeline Status | Tool to get a specific pipeline stage by its ID from Kommo CRM. Use when you need to retrieve detailed information about a particular stage within a pipeline. |
| `KOMMO_GET_TASK` | Get Kommo Task | Tool to retrieve a task by its ID from Kommo CRM. Use when you need to fetch details of a specific task. |
| `KOMMO_GET_USER` | Get Kommo User | Tool to retrieve user data by its ID from Kommo CRM. Use when you need to fetch details about a specific user including their name, email, role, group, and access rights. |
| `KOMMO_GET_WIDGET` | Get Kommo Widget Info | Tool to get detailed information about a widget by its code. Use when you need to retrieve widget metadata, settings, version, or check if a widget is active in the account. |
| `KOMMO_IMPORT_PRODUCTS_TO_AI` | Import Products to AI | Tool to launch import of products from CRM to AI knowledge base. Use when you need to initiate the process of importing product data into the AI system for enhanced product recommendations and knowledge. |
| `KOMMO_LIST_CATALOGS` | List Kommo Catalogs | Tool to retrieve a list of catalogs (lists) from Kommo CRM. Use when you need to fetch available catalogs in the account. |
| `KOMMO_LIST_COMPANIES` | List Kommo Companies | Action to list Kommo companies with various filter options. |
| `KOMMO_LIST_CONTACTS` | List Kommo Contacts | Action to list contacts in Kommo CRM. |
| `KOMMO_LIST_CONVERSATIONS` | List Kommo Conversations | Tool to get a list of conversations from Kommo CRM. Use when you need to retrieve conversations with pagination support. |
| `KOMMO_LIST_CUSTOM_FIELDS` | List Kommo Custom Fields | Action to list custom fields in Kommo CRM. |
| `KOMMO_LIST_ENTITY_FILES` | List Entity Files | Tool to retrieve a list of files attached to an entity in Kommo CRM. Use when you need to see all files (documents, images, PDFs, etc.) that have been uploaded to a specific lead, contact, or company. |
| `KOMMO_LIST_ENTITY_LINKS` | List Kommo Entity Links | Tool to get a list of entities linked to a specific entity in Kommo. Use when you need to retrieve contacts, companies, or leads linked to another entity. |
| `KOMMO_LIST_ENTITY_NOTES` | List Kommo Entity Notes | Tool to get a list of all notes for an entity type (leads, contacts, or companies) in Kommo CRM. Use when you need to retrieve notes across all entities of a specific type, not just for a single entity. |
| `KOMMO_LIST_ENTITY_TAGS` | List Kommo Entity Tags | Tool to get a list of tags for an entity type (leads, contacts, or companies). Use when you need to retrieve available tags for a specific entity type in Kommo CRM. |
| `KOMMO_LIST_EVENTS` | List Kommo Events | Tool to get a list of events from Kommo CRM with filtering options. Use when you need to retrieve events history, track changes to entities (leads, contacts, companies), or monitor specific event types like status changes, field updates, or assignment changes. |
| `KOMMO_LIST_EVENT_TYPES` | List Kommo Event Types | Tool to get a list of all available event types in Kommo CRM. Use when you need to see what event types can be used for filtering events or configuring webhooks. |
| `KOMMO_LIST_FIELD_GROUPS` | List Kommo Field Groups | Tool to get a list of custom field groups for an entity type in Kommo CRM. Use when you need to retrieve field group information to organize custom fields. |
| `KOMMO_LIST_FILES` | List Kommo Files | Tool to retrieve a list of files from Kommo Drive. Use when you need to search, filter, or browse files stored in the Kommo CRM system. Supports filtering by name, extension, size, date, creator, and other criteria. |
| `KOMMO_LIST_INCOMING_LEADS` | List Incoming Leads | Tool to get a list of incoming leads (unsorted) from Kommo with filtering and pagination. Use when you need to retrieve unprocessed leads that haven't been sorted into pipelines yet. Supports filtering by category (sip, mail, forms, chats), UID, and pipeline ID. |
| `KOMMO_LIST_LEADS` | List Kommo Leads | Action to list leads in Kommo CRM. |
| `KOMMO_LIST_LEADS_PIPELINES` | List Kommo Lead Pipelines | Action to list lead pipelines in Kommo CRM. |
| `KOMMO_LIST_LOSS_REASONS` | List Kommo Loss Reasons | Action to list loss reasons for leads in Kommo CRM. Use when you need to retrieve all available loss reasons that can be assigned to lost leads. |
| `KOMMO_LIST_NOTES_BY_ENTITY` | List Kommo Notes By Entity | Tool to get notes for a specific entity by its ID in Kommo CRM. Use when you need to retrieve all notes associated with a lead, contact, or company. |
| `KOMMO_LIST_PIPELINE_STAGES` | List Kommo Pipeline Stages | Action to list stages of a pipeline in Kommo CRM. |
| `KOMMO_LIST_ROLES` | List Kommo User Roles | Tool to get a list of user roles in Kommo CRM. Use when you need to retrieve available user roles and their permissions. |
| `KOMMO_LIST_SOURCES` | List Kommo Lead Sources | Tool to get a list of lead sources in Kommo CRM. Use when you need to retrieve all available lead sources that can be assigned to leads. |
| `KOMMO_LIST_TASKS` | List Kommo Tasks | Action to list tasks in Kommo CRM. |
| `KOMMO_LIST_TEMPLATES` | List Kommo Templates | Tool to get a list of message templates in Kommo CRM. Use when you need to retrieve chat response templates that can be utilized in cards and bots. |
| `KOMMO_LIST_USERS` | List Kommo Users | Tool to get a list of users from Kommo CRM with pagination support. Use when you need to retrieve all users in the account or paginate through the users list. |
| `KOMMO_LIST_WEBHOOKS` | List Kommo Webhooks | Tool to get a list of registered webhooks for the Kommo account. Use when you need to view all webhook configurations and their settings. |
| `KOMMO_LIST_WEBSITE_BUTTONS` | List Kommo Website Buttons | Tool to get a list of website chat button (CRM Plugin) objects from Kommo. Use when you need to retrieve all configured website chat buttons in the account. Supports pagination for large result sets. |
| `KOMMO_LIST_WIDGETS` | List Kommo Widgets | Tool to get a list of installed widgets in Kommo. Use when you need to see which widgets are installed and their current status in the account. |
| `KOMMO_UPDATE_COMPANY` | Update Kommo Company | Action to update a single company in Kommo CRM. |
| `KOMMO_UPDATE_CONTACT` | Update Kommo Contact | Action to update contact information in Kommo CRM by contact ID. |
| `KOMMO_UPDATE_LEAD` | Update Kommo Lead | Action to update an existing lead in Kommo CRM. Allows modifying lead properties including name, price, pipeline stage, responsible user, tags, and custom fields. Requires the lead ID to be specified. |
| `KOMMO_UPDATE_TASK` | Update Kommo Task | Action to update a task in Kommo CRM. |

## Supported Triggers

None listed.

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

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

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

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 Kommo 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, kommo)
- 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 Kommo 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=["kommo"],
    )

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

  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 Kommo 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 Kommo
```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 Kommo, 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=["kommo"],
    )

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

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

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

## Related Toolkits

- [Hubspot](https://composio.dev/toolkits/hubspot) - HubSpot is an all-in-one marketing, sales, and customer service platform. It lets teams nurture leads, automate outreach, and track every customer interaction in one place.
- [Pipedrive](https://composio.dev/toolkits/pipedrive) - Pipedrive is a sales management platform offering pipeline visualization, lead tracking, and workflow automation. It helps sales teams keep deals moving forward efficiently and never miss a follow-up.
- [Salesforce](https://composio.dev/toolkits/salesforce) - Salesforce is a leading CRM platform that helps businesses manage sales, service, and marketing. It centralizes customer data, enabling teams to drive growth and build strong relationships.
- [Apollo](https://composio.dev/toolkits/apollo) - Apollo is a CRM and lead generation platform that helps businesses discover contacts and manage sales pipelines. Use it to streamline customer outreach and track your deals from one place.
- [Attio](https://composio.dev/toolkits/attio) - Attio is a customizable CRM and workspace for managing your team's relationships and workflows. It helps teams organize contacts, automate tasks, and collaborate more efficiently.
- [Acculynx](https://composio.dev/toolkits/acculynx) - AccuLynx is a cloud-based roofing business management software for contractors. It streamlines project tracking, lead management, and document sharing.
- [Addressfinder](https://composio.dev/toolkits/addressfinder) - Addressfinder is a data quality platform for verifying addresses, emails, and phone numbers. It helps you ensure accurate customer and contact data every time.
- [Affinity](https://composio.dev/toolkits/affinity) - Affinity is a relationship intelligence CRM that helps private capital investors find, manage, and close more deals. It streamlines deal flow and surfaces key connections to help you win opportunities.
- [Agencyzoom](https://composio.dev/toolkits/agencyzoom) - AgencyZoom is a sales and performance platform built for P&C insurance agencies. It helps agents boost sales, retain clients, and analyze producer results in one place.
- [Bettercontact](https://composio.dev/toolkits/bettercontact) - Bettercontact is a smart contact enrichment tool for finding emails and phone numbers. It helps boost lead generation with automated, waterfall search across multiple sources.
- [Blackbaud](https://composio.dev/toolkits/blackbaud) - Blackbaud provides cloud-based software for nonprofits, schools, and healthcare institutions. It streamlines fundraising, donor management, and mission-driven operations.
- [Brilliant directories](https://composio.dev/toolkits/brilliant_directories) - Brilliant Directories is an all-in-one platform for building and managing online membership communities and business directories. It streamlines listings, member management, and engagement tools into a single, easy interface.
- [Capsule crm](https://composio.dev/toolkits/capsule_crm) - Capsule CRM is a user-friendly CRM platform for managing contacts and sales pipelines. It helps businesses organize relationships and streamline their sales process efficiently.
- [Centralstationcrm](https://composio.dev/toolkits/centralstationcrm) - CentralStationCRM is an easy-to-use CRM software focused on collaboration and long-term customer relationships. It helps teams manage contacts, deals, and communications all in one place.
- [Clientary](https://composio.dev/toolkits/clientary) - Clientary is a platform for managing clients, invoices, projects, proposals, and more. It streamlines client work and saves you serious admin time.
- [Close](https://composio.dev/toolkits/close) - Close is a CRM platform built for sales teams, combining calling, email automation, and predictive dialers. It streamlines sales workflows and boosts productivity with all-in-one communication tools.
- [Dropcontact](https://composio.dev/toolkits/dropcontact) - Dropcontact is a B2B email finder and data enrichment service for professionals. It delivers verified email addresses and enriches contact info with up-to-date data.
- [Dynamics365](https://composio.dev/toolkits/dynamics365) - Dynamics 365 is Microsoft's platform combining CRM, ERP, and productivity apps. It streamlines sales, marketing, service, and operations in one place.
- [Espocrm](https://composio.dev/toolkits/espocrm) - EspoCRM is an open-source web application for managing customer relationships. It helps businesses organize contacts, track leads, and streamline their sales process.
- [Fireberry](https://composio.dev/toolkits/fireberry) - Fireberry is a CRM platform that streamlines customer and sales management. It helps businesses organize contacts, automate sales, and integrate with other business tools.

## Frequently Asked Questions

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

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

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

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

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