# How to integrate Booqable MCP with LlamaIndex

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

## Introduction

This guide walks you through connecting Booqable to LlamaIndex using the Composio tool router. By the end, you'll have a working Booqable agent that can add a new customer named alice brown, list all active orders for this week, create a rental order for customer id 123 through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Booqable account through Composio's Booqable MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Booqable with

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

The Booqable MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Booqable account. It provides structured and secure access to your rental management system, so your agent can perform actions like creating customers, managing orders, retrieving inventory data, and organizing product groups on your behalf.
- Customer management and onboarding: Effortlessly create new customers, fetch details for existing clients, or delete customer records when needed—all through your AI agent.
- Order creation and tracking: Let your agent generate new rental orders, retrieve specific order details, or list and filter all existing orders based on your business needs.
- Inventory and product group organization: Have your agent create new product groups to organize inventory, fetch product group information, or remove groups that are no longer needed.
- Automated cleanup and archiving: Direct your agent to archive customers or orders, helping you keep your database clean and up-to-date without manual intervention.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `BOOQABLE_CREATE_CUSTOMER` | Create Customer | Tool to create a new customer. Use when onboarding a new client and you have verified their details. Example: Create 'Jane Doe' with email jane@doe.com. |
| `BOOQABLE_CREATE_ORDER` | Create Order | Tool to create a new order. Use after collecting valid customer ID and timing details. Example: Create an order for customer '297f2584-...' starting at '2018-01-01T09:00:00Z'. |
| `BOOQABLE_CREATE_PRODUCT_GROUP` | Create Product Group | Tool to create a new product group in Booqable. Use when you have defined the group's name and pricing details and want to organize items under a shared group. |
| `BOOQABLE_DELETE_CUSTOMER` | Delete Customer | Tool to delete (archive) a customer by ID. Use after confirming the customer should be hidden from searches. |
| `BOOQABLE_DELETE_ORDER` | Delete Order | Tool to delete (archive) an order by ID. Use when you need to hide completed or canceled orders from active listings. |
| `BOOQABLE_DELETE_PRODUCT_GROUP` | Delete Product Group | Tool to delete a product group by ID. Use when you need to permanently remove a product group from your catalog after confirming its identifier. |
| `BOOQABLE_GET_CUSTOMER` | Get Customer | Tool to fetch a specific customer by ID. Use after obtaining a customer identifier to retrieve full customer details. |
| `BOOQABLE_GET_CUSTOMERS` | Get Customers | Tool to retrieve a list of customers. Use when you need to paginate through customers. |
| `BOOQABLE_GET_INVENTORY_LEVELS` | Get Inventory Levels | Tool to fetch inventory levels for products. Shows availability of products across locations for a date range. Use when checking product availability or stock levels. |
| `BOOQABLE_GET_NEW_ORDER` | Get New Order | Tool to retrieve a new order template with default values. Use when you need to initialize an order creation form or fetch default order settings before creating an order. |
| `BOOQABLE_GET_ORDER` | Get Order | Tool to retrieve a specific order by ID. Use when you need complete details of a known order, including optional relationships like customer or coupon. Call after confirming the order ID. |
| `BOOQABLE_GET_PRODUCT` | Get Product | Tool to fetch a specific product by ID. Use after obtaining a product identifier to retrieve detailed inventory item data. |
| `BOOQABLE_GET_PRODUCT_GROUP` | Get Product Group | Tool to fetch a specific product group by ID. Use after obtaining the product group identifier to retrieve its full details. |
| `BOOQABLE_LIST_BARCODES` | List Barcodes | Tool to retrieve a list of barcodes. Use when you need to list barcodes with pagination, filtering by owner, type, or dates. |
| `BOOQABLE_LIST_BUNDLE_ITEMS` | List Bundle Items | Tool to retrieve a list of bundle items. Use when you need to see which products are included in bundles, with their quantities and discounts. |
| `BOOQABLE_LIST_CLUSTERS` | List Clusters | Tool to retrieve a list of clusters from Booqable. Use when you need to list clusters with optional filtering, field selection, and pagination support. |
| `BOOQABLE_LIST_COUPONS` | List Coupons | Tool to retrieve a list of coupons. Use when you need to list or search for discount coupons with pagination and filtering. |
| `BOOQABLE_LIST_DEFAULT_PROPERTIES` | List Default Properties | Tool to retrieve a list of default properties from Booqable. Use when you need to view custom property definitions with pagination, filtering, or sorting options. |
| `BOOQABLE_LIST_DOCUMENTS` | List Documents | Tool to retrieve a list of documents. Use when you need to fetch invoices, quotes, contracts, or packing slips with optional filtering and pagination. |
| `BOOQABLE_LIST_EMAIL_TEMPLATES` | List Email Templates | Tool to list email templates from Booqable. Use when you need to retrieve available email templates with optional filtering, pagination, and sorting. |
| `BOOQABLE_LIST_EMPLOYEES` | List Employees | Tool to retrieve a list of employees from Booqable. Use when you need to list employee accounts with pagination and filtering options. |
| `BOOQABLE_LIST_INVENTORY_BREAKDOWNS` | List Inventory Breakdowns | Tool to retrieve a list of inventory breakdowns filtered by status and product/product group. Use when you need to analyze inventory allocation across locations. Note: Both status filter and either product_id or product_group_id filter are required. |
| `BOOQABLE_LIST_ITEMS` | List Items | Tool to retrieve a list of items (products and product groups). Use when you need to browse the catalog with pagination and filtering. |
| `BOOQABLE_LIST_LINES` | List Lines | Tool to retrieve a paginated list of lines from orders. Use when you need to list line items, with support for filtering by order, product, or other attributes. |
| `BOOQABLE_LIST_LOCATIONS` | List Locations | Tool to retrieve a list of locations from Booqable. Use when you need to view available locations with pagination, filtering, or sorting options. |
| `BOOQABLE_LIST_NOTES` | List Notes | Tool to retrieve a list of notes. Use when you need to list notes with optional filtering by owner, date, or content. |
| `BOOQABLE_LIST_ORDERS` | List Orders | Tool to retrieve a paginated list of orders. Use when you need to browse orders with support for filtering by status, customer, dates, and other attributes. |
| `BOOQABLE_LIST_PAYMENT_METHODS` | List Payment Methods | Tool to retrieve a list of payment methods from Booqable. Use when you need to list payment methods with optional filtering by creation date, customer, status, or ID, and support for pagination. |
| `BOOQABLE_LIST_PAYMENTS` | List Payments | Tool to list all payments from Booqable. Use when you need to retrieve payment records with optional filtering by created_at, order_id, payment_method, or payment_status. |
| `BOOQABLE_LIST_PHOTOS` | List Photos | Tool to retrieve a paginated list of photos from Booqable. Use when you need to list photos with support for filtering by owner resource and pagination. |
| `BOOQABLE_LIST_PLANNINGS` | List Plannings | Tool to retrieve planning records that track product and bundle reservations across locations and time periods. Use when you need to check what items are planned or reserved for specific dates, locations, or orders. |
| `BOOQABLE_LIST_PRICE_RULESETS` | List Price Rulesets | Tool to list price rulesets. Use when you need to retrieve price rulesets with optional filtering by archived status, name, or ID, and pagination support. |
| `BOOQABLE_LIST_PRICE_STRUCTURES` | List Price Structures | Tool to list price structures. Use when you need to retrieve price structures with optional filtering by name, ID, or product group, and pagination support. |
| `BOOQABLE_LIST_PRODUCT_GROUPS` | List Product Groups | Tool to list product groups from Booqable API v4. Use when you need to retrieve multiple product groups with filtering, pagination, and field selection options. |
| `BOOQABLE_LIST_PRODUCTS` | List Products | Tool to retrieve a list of products. Use when you need to browse products with pagination and filtering. |
| `BOOQABLE_LIST_PROPERTIES` | List Properties | Tool to retrieve a list of properties. Use when you need to list custom properties associated with customers, products, or other resources in Booqable. |
| `BOOQABLE_LIST_PROVINCES` | List Provinces | Tool to retrieve a list of provinces. Use when you need to list available provinces, optionally filtered by country. |
| `BOOQABLE_LIST_STOCK_ITEM_PLANNINGS` | List Stock Item Plannings | Tool to retrieve a list of stock item plannings. Use when you need to list stock item plannings with filtering and pagination. |
| `BOOQABLE_LIST_STOCK_ITEMS` | List Stock Items | Tool to retrieve a list of stock items. Use when you need to list physical inventory items with tracking identifiers like serial numbers or barcodes. |
| `BOOQABLE_LIST_TAX_RATES` | List Tax Rates | Tool to retrieve a list of tax rates. Use when you need to list or search for tax rates with pagination and filtering. |
| `BOOQABLE_LIST_TAX_VALUES` | List Tax Values | Tool to retrieve a list of tax values. Use when you need to fetch tax rates with optional filtering, pagination, and sorting. |
| `BOOQABLE_LIST_USERS` | List Users | Tool to retrieve a list of users from Booqable. Use when you need to list user accounts with pagination and filtering options. |
| `BOOQABLE_SEARCH_BUNDLES` | Search Bundles | Tool to search bundles with advanced filtering. Use when you need to find bundles by specific criteria (discountable, taxable, show_in_store, etc.) using complex queries with logical operators. |
| `BOOQABLE_SEARCH_CUSTOMERS` | Search Customers | Tool to search customers in the Booqable system. Use when you need to retrieve customer data with optional field selection and relationship inclusion. |
| `BOOQABLE_SEARCH_DOCUMENTS` | Search Documents | Tool to search documents using advanced filtering with logical operators. Use when you need to find documents matching complex criteria with AND/OR conditions. |
| `BOOQABLE_SEARCH_ITEMS` | Search Items | Tool to search items (products and bundles) with advanced filtering. Use when you need to find items by specific criteria (name, product_type, archived status, etc.) using complex queries. |
| `BOOQABLE_SEARCH_ORDERS` | Search Orders | Tool to search orders with advanced filtering using logical operators. Use when you need to find orders by specific criteria (status, dates, customer) with complex queries like date ranges or multiple conditions. |
| `BOOQABLE_SEARCH_PLANNINGS` | Search Plannings | Tool to search plannings with advanced filtering. Use when you need to find planning records by specific criteria using complex queries with logical operators. |
| `BOOQABLE_UPDATE_COMPANIES` | Update Company | Tool to update the current company's information in Booqable. Use when you need to modify company details such as name, contact information, address, or billing settings. |

## Supported Triggers

None listed.

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

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

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

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 Booqable 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, booqable)
- 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 Booqable 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=["booqable"],
    )

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

  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 Booqable 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 Booqable
```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 Booqable, 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=["booqable"],
    )

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

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

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

## Related Toolkits

- [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.
- [Apaleo](https://composio.dev/toolkits/apaleo) - Apaleo is a cloud-based property management platform for hospitality businesses. It centralizes reservations, billing, and daily operations for smoother hotel management.
- [Appointo](https://composio.dev/toolkits/appointo) - Appointo is an appointment booking platform for Shopify stores. It lets businesses add online scheduling to their websites with zero coding.
- [Bart](https://composio.dev/toolkits/bart) - Bart is the Bay Area Rapid Transit system, providing fast public transportation across the San Francisco Bay Area. It helps commuters and travelers get real-time schedule info, plan routes, and stay updated on service changes.
- [Bookingmood](https://composio.dev/toolkits/bookingmood) - Bookingmood is commission-free booking software for rental businesses. It lets you manage reservations and sync bookings directly on your website.
- [Cal](https://composio.dev/toolkits/cal) - Cal is a meeting scheduling platform that offers shareable booking links and real-time calendar syncing. It streamlines the process of finding mutual availability to make scheduling effortless.
- [Calendarhero](https://composio.dev/toolkits/calendarhero) - Calendarhero is a powerful scheduling platform that streamlines your calendar management across multiple services. It helps you efficiently schedule, reschedule, and organize meetings without the back-and-forth.
- [Calendly](https://composio.dev/toolkits/calendly) - Calendly is an appointment scheduling tool that automates meeting invitations, availability checks, and reminders. It helps individuals and teams avoid endless email back-and-forth when booking meetings.
- [Etermin](https://composio.dev/toolkits/etermin) - eTermin is an online appointment scheduling platform for businesses to manage bookings. It streamlines client appointments, saving time and reducing scheduling conflicts.
- [Evenium](https://composio.dev/toolkits/evenium) - Evenium is an all-in-one platform for managing professional events, from planning to analysis. It helps teams simplify event logistics, boost engagement, and track every detail in one place.
- [Eventee](https://composio.dev/toolkits/eventee) - Eventee is a user-friendly event management platform for mobile and web. It boosts attendee engagement for in-person, virtual, and hybrid events.
- [Eventzilla](https://composio.dev/toolkits/eventzilla) - Eventzilla is an event management platform for creating, promoting, and running events. It streamlines ticketing, registration, and attendee coordination for organizers.
- [Humanitix](https://composio.dev/toolkits/humanitix) - Humanitix is a not-for-profit ticketing platform that donates 100% of profits to charity. It empowers event organizers to make social impact with every ticket sold.
- [Lodgify](https://composio.dev/toolkits/lodgify) - Lodgify is an all-in-one vacation rental software for property managers and owners. It centralizes bookings, guest messaging, and channel synchronization in one dashboard.
- [Planyo Online Booking](https://composio.dev/toolkits/planyo_online_booking) - Planyo Online Booking is a flexible reservation system for managing bookings by day, hour, or event. It streamlines scheduling for any business needing reservations.
- [Scheduleonce](https://composio.dev/toolkits/scheduleonce) - Scheduleonce is a scheduling platform for capturing, qualifying, and engaging with inbound leads. It streamlines appointment booking and follow-ups for faster lead conversion.
- [Supersaas](https://composio.dev/toolkits/supersaas) - Supersaas is a flexible appointment scheduling platform for businesses and individuals. It streamlines bookings, reminders, and calendar management in one place.
- [Sympla](https://composio.dev/toolkits/sympla) - Sympla is a platform for managing in-person and online events, ticket sales, and registrations. It streamlines event setup, attendee tracking, and digital content delivery.
- [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 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.

## Frequently Asked Questions

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

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

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

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

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