How to integrate Zoho books MCP with LlamaIndex

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Zoho books logo
LlamaIndex logo
divider

Introduction

This guide walks you through connecting Zoho books to LlamaIndex using the Composio tool router. By the end, you'll have a working Zoho books agent that can list unpaid invoices for this month, create a new expense entry today, send payment reminder to a client through natural language commands.

This guide will help you understand how to give your LlamaIndex agent real control over a Zoho books account through Composio's Zoho books MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

Also integrate Zoho books with

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 Zoho books
  • Connect LlamaIndex to the Zoho books MCP server
  • Build a Zoho books-powered agent using LlamaIndex
  • Interact with Zoho books 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 Zoho books MCP server, and what's possible with it?

The Zoho Books MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Zoho Books account. It provides structured and secure access to your accounting data, so your agent can perform actions like managing invoices, tracking expenses, creating customers, reconciling transactions, and generating financial reports on your behalf.

  • Automated invoice management: Ask your agent to create, send, update, or retrieve invoices, helping you streamline your billing process and get paid faster.
  • Expense and transaction tracking: Let your agent record new expenses, categorize transactions, or pull detailed expense reports to keep your books up to date without manual entry.
  • Customer and vendor management: Have your agent add new customers or vendors, update their details, and fetch account histories to support your business relationships.
  • Bank reconciliation and payment handling: Enable your agent to match bank transactions, record payments, and reconcile accounts, giving you an accurate financial overview at any time.
  • Financial reporting and insights: Generate real-time financial statements, analyze cash flow, or pull profit and loss reports—so you always know where your business stands.

Supported Tools & Triggers

Tools
Accept EstimateTool to mark an estimate as accepted.
Activate Bank AccountTool to activate a bank account.
Add Bill AttachmentTool to add an attachment to an existing bill in Zoho Books.
Add Bill CommentTool to add a comment to a bill in Zoho Books.
Add Contact AddressTool to add an additional address to a contact in Zoho Books.
Add Invoice CommentTool to add a comment to an invoice.
Add Project CommentTool to add a comment to a project.
Add Purchase Order CommentTool to add a comment to a purchase order in Zoho Books.
Add Sales Order CommentTool to add a comment to a sales order in Zoho Books.
Add Vendor Credit CommentTool to add a comment to a vendor credit.
Apply Credit Note to InvoiceTool to apply a credit note to one or more invoices in Zoho Books.
Apply Credits to BillTool to apply vendor credits to a bill in Zoho Books.
Apply Credits to InvoiceTool to apply credit notes to an invoice in Zoho Books.
Bulk Export Invoices PDFTool to export multiple invoices to a single PDF.
Bulk Print InvoicesTool to bulk print up to 25 invoices as a single PDF.
Categorize As Customer Payment RefundTool to categorize an uncategorized bank transaction as a customer payment refund.
Categorize Uncategorized TransactionTool to categorize an uncategorized bank transaction.
Clone ProjectTool to clone an existing project.
Convert Purchase Order To BillTool to retrieve bill data from purchase orders for conversion.
Create Bank AccountTool to create a bank or credit card account.
Create Bank TransactionTool to create a manual bank transaction.
Create Chart Of AccountTool to create a new chart of account in Zoho Books.
Create ContactTool to create a new contact in Zoho Books.
Create Contact PersonTool to create a new contact person for an existing contact in Zoho Books.
Create CurrencyTool to create a new currency for an organization.
Create Customer Payment RefundTool to refund an excess customer payment.
Create EmployeeTool to create a new employee in Zoho Books.
Create Exchange RateTool to create a new exchange rate for a currency.
Create ExpenseTool to create a new expense in Zoho Books.
Create Invoice From Sales OrderTool to create an instant invoice from an existing sales order.
Create ItemTool to create a new item (product or service).
Create JournalTool to create a journal entry in Zoho Books.
Create LocationTool to create a new location in Zoho Books.
Create ProjectTool to create a project in Zoho Books.
Create Recurring BillTool to create a recurring bill in Zoho Books.
Create Recurring ExpenseTool to create a new recurring expense in Zoho Books.
Create Recurring InvoiceTool to create a recurring invoice.
Create Reporting TagTool to create a new reporting tag in Zoho Books.
Create Bank Account RuleTool to create a rule for automatic transaction categorization.
Create Sales ReceiptTool to create a sales receipt in Zoho Books.
Create Time EntryTool to create a new time entry for a project task.
Create UserTool to create a new user in Zoho Books.
Create Vendor CreditTool to create a vendor credit in Zoho Books.
Create Vendor PaymentTool to create a vendor payment in Zoho Books.
Deactivate Bank AccountTool to deactivate a bank account.
Delete Bank AccountTool to delete a bank account from your organization.
Delete Bank TransactionTool to delete a specific bank transaction.
Delete BillTool to delete a specific bill.
Delete Bill AttachmentTool to delete an attachment from a specific bill.
Delete Bill CommentTool to delete a comment from a bill.
Delete Bill PaymentTool to delete a specific bill payment.
Delete Bulk Customer PaymentsTool to bulk delete multiple customer payments.
Delete Bulk Vendor PaymentsTool to bulk delete multiple vendor payments.
Delete Chart of AccountTool to delete a specific chart of account.
Delete Chart Of Account TransactionTool to delete a chart of account transaction.
Delete ContactTool to delete a specific contact.
Delete Contact AddressTool to delete an additional address from a contact.
Delete Contact PersonTool to delete a specific contact person.
Delete Credit NoteTool to delete a specific credit note.
Delete Credit Note CommentTool to delete a comment from a credit note.
Delete Credit Note RefundTool to delete a specific credit note refund.
Delete CurrencyTool to delete a specific currency from organization settings.
Delete Customer PaymentTool to delete a customer payment.
Delete Customer Payment RefundTool to delete a specific customer payment refund.
Delete EmployeeTool to delete a specific employee.
Delete EstimateTool to delete a specific estimate.
Delete Exchange RateTool to delete an exchange rate for a currency.
Delete ExpenseTool to delete a specific expense.
Delete Expense ReceiptTool to delete a receipt from an expense.
Delete InvoiceTool to delete a specific invoice.
Delete Invoice AttachmentTool to delete the last attached attachment from an invoice.
Delete Invoice CommentTool to delete a comment from an invoice.
Delete Invoice DocumentTool to delete a document/attachment from a specific invoice.
Delete Invoice PaymentTool to delete a payment applied to an invoice.
Delete ItemTool to delete a specific item.
Delete Journal Comment V4Tool to delete a journal comment using Zoho Books API v4 (Beta).
Delete Journal DocumentTool to delete a document/attachment from a journal entry.
Delete JournalsTool to delete multiple journal entries in one request.
Delete Journal (v4 Beta)Tool to delete a journal using the v4 Beta API.
Delete LocationTool to delete a specific location.
Delete Project Comment (v4 Beta)Tool to delete a project comment using v4 Beta API.
Delete Project TaskTool to delete a project task.
Delete Project V4Tool to delete a specific project using v4 Beta API.
Delete Purchase OrderTool to delete a specific purchase order.
Delete Purchase Order AttachmentTool to delete an attachment from a purchase order.
Delete Purchase Order CommentTool to delete a comment from a purchase order.
Delete Recurring BillTool to delete a recurring bill.
Delete Recurring InvoiceTool to delete a recurring invoice.
Delete Bank Account RuleTool to delete a bank account rule from your account.
Delete Sales Order CommentTool to delete a comment from a sales order.
Delete Sales ReceiptTool to delete a specific sales receipt.
Delete Time EntryTool to delete a specific time entry from a project.
Delete Vendor CreditTool to delete a specific vendor credit.
Delete Vendor Credit RefundTool to delete a vendor credit refund.
Delete Vendor PaymentTool to delete a vendor payment.
Disable Contact Payment ReminderTool to disable payment reminders for a contact.
Disable Invoice Payment ReminderTool to disable payment reminders for an invoice.
Email Contact StatementTool to email a statement to a contact.
Email EstimateTool to send an estimate email.
Email InvoiceTool to send an invoice email.
Enable Contact Payment ReminderTool to enable payment reminders for a contact.
Enable Contact PortalTool to enable portal access for a contact.
Enable Invoice Payment ReminderTool to enable payment reminders for an invoice.
Exclude Bank TransactionTool to exclude an uncategorized bank transaction.
Bulk Export Estimates PDFTool to export multiple estimates to a single PDF.
Bulk Export Sales Orders PDFTool to export multiple sales orders to a single PDF.
Get All Tag OptionsTool to retrieve all options for a reporting tag.
Get Bank AccountTool to fetch details of a specific bank account.
Get Base Currency AdjustmentTool to fetch details of a specific base currency adjustment.
Get BillTool to fetch details of a specific bill.
Get Bill AttachmentTool to fetch an attachment from a specific bill.
Get Chart Of AccountTool to fetch details of a specific chart of account.
Get ContactTool to fetch details of a specific contact.
Get Contact AddressTool to retrieve all addresses associated with a contact.
Get Contact PersonTool to retrieve details of a specific contact person.
Get Contact Statement MailTool to retrieve the pre-populated email content for a contact statement.
Get Credit NoteTool to fetch details of a specific credit note by ID.
Get CurrencyTool to retrieve details of a specific currency.
Get EstimateTool to fetch details of a specific estimate.
Get Estimate EmailTool to retrieve the pre-populated email content for an estimate.
Get ExpenseTool to fetch details of a specific expense.
Get InvoiceTool to fetch details of a specific invoice.
Get Invoice AttachmentTool to fetch the last attached attachment from a specific invoice.
Get Invoice EmailTool to retrieve the pre-populated email content for an invoice.
Get ItemTool to fetch details of a specific item.
Get Journal Credits List (v4 Beta)Tool to retrieve the list of available journal credits for a specific journal using v4 Beta API.
Get Journal Details V4Tool to fetch details of a specific journal entry from Zoho Books API v4 (Beta).
Get Journals List (v4 Beta)Tool to retrieve a paginated list of journals using Zoho Books v4 Beta API.
Get Last Imported StatementTool to get details of previously imported statement for a bank account.
Get Matching Bank TransactionsTool to retrieve potential matching transactions for an uncategorized bank transaction.
Get Opening BalanceTool to retrieve opening balance for an organization.
Get OrganizationTool to fetch details of a specific organization.
Get Payment Reminder Mail ContentTool to retrieve the pre-populated payment reminder email content for an invoice.
Get ProjectTool to fetch details of a specific project.
Get Project UserTool to fetch details of a specific user associated with a project.
Get Purchase OrderTool to fetch details of a specific purchase order.
Get Recurring InvoiceTool to retrieve a single recurring invoice profile's full configuration by ID.
Get Sales OrderTool to fetch details of a specific sales order.
Get Sales Order AttachmentTool to fetch an attachment from a specific sales order.
Get Sales Order Email ContentTool to retrieve the pre-populated email content for a sales order.
Get UserTool to fetch details of a specific user.
Get Vendor Credit RefundTool to fetch details of a specific vendor credit refund.
Import Bank StatementsTool to import bank or credit card statement transactions in bulk.
List Bank AccountsTool to list bank and credit card accounts.
List Bank RulesTool to list all rules created for a bank or credit card account.
List Bank TransactionsTool to list bank transactions with optional filters.
List Base Currency AdjustmentsTool to list base currency adjustments for an organization.
List Bill Comments and HistoryTool to list comments and history entries for a bill.
List Bill PaymentsTool to list payments recorded against a bill.
List BillsTool to retrieve a paginated list of bills.
List Chart Of AccountsTool to list chart of accounts.
List Chart of Account TransactionsTool to list transactions for a specific chart of account.
List Contact CommentsTool to retrieve recent activities and comments for a specific contact.
List Contact PersonsTool to retrieve a paginated list of contact persons from Zoho Books.
List Contact RefundsTool to list refunds for a contact.
List ContactsTool to retrieve a paginated list of contacts with optional filters.
List Credit Note RefundsTool to retrieve a paginated list of credit note refunds with filters.
List Credit NotesTool to retrieve a paginated list of credit notes with optional filters.
List CurrenciesTool to list currencies configured for the organization.
List Customer Payment RefundsTool to list refunds of a customer payment.
List Customer PaymentsTool to list customer payments in Zoho Books.
List EmployeesTool to retrieve a paginated list of employees.
List Estimate Comments & HistoryTool to retrieve comments and history for a specific estimate.
List EstimatesTool to retrieve a paginated list of estimates with optional filters.
List Estimate TemplatesTool to retrieve a list of estimate templates.
List Expense CommentsTool to retrieve history and comments for a specific expense.
List ExpensesTool to retrieve a paginated list of expenses with filters and search.
List Fixed AssetsTool to retrieve a paginated list of fixed assets from Zoho Books.
List Fixed Asset TypesTool to retrieve a paginated list of fixed asset types from Zoho Books.
List Invoice Comments and HistoryTool to list comments and history entries for an invoice.
List Invoice Credits AppliedTool to list credit notes applied to an invoice.
List Invoice PaymentsTool to list payments recorded against an invoice.
List InvoicesTool to retrieve a paginated list of invoices with filters and search.
List Invoice TemplatesTool to retrieve a list of invoice templates.
List Item DetailsTool to bulk fetch details for multiple items from Zoho Books using their IDs.
List ItemsTool to retrieve a paginated list of items from Zoho Books.
List Journal TemplatesTool to list journal templates with pagination.
List LocationsTool to list all locations in the organization.
List OrganizationsTool to list all organizations for the authenticated user.
List ProjectsTool to retrieve a paginated list of projects with optional filters.
List Project UsersTool to retrieve all users assigned to a project.
List Purchase OrdersTool to retrieve a paginated list of purchase orders.
List Recurring Bill HistoryTool to list comments and history entries for a recurring bill.
List Recurring Invoice HistoryTool to retrieve comments and history for a specific recurring invoice.
List Reporting TagsTool to retrieve all reporting tags from Zoho Books.
List Retainer InvoicesTool to retrieve a paginated list of retainer invoices with filters and sorting.
List Sales Order Comments & HistoryTool to list comments and history entries for a sales order.
List Sales OrdersTool to retrieve a paginated list of sales orders.
List Sales ReceiptsTool to retrieve a paginated list of sales receipts with filters.
List TasksTool to retrieve a paginated list of tasks for a specific project.
List TaxesTool to retrieve a paginated list of taxes.
List Tax ExemptionsTool to retrieve a list of tax exemptions from Zoho Books.
List UsersTool to retrieve a paginated list of users.
List Vendor Credit RefundsTool to retrieve a paginated list of vendor credit refunds with filters.
List Vendor Credit RefundsTool to list refunds of a specific vendor credit.
List Vendor CreditsTool to retrieve a paginated list of vendor credits with filters and search.
List Vendor Payment RefundsTool to list refunds of a vendor payment.
List Vendor PaymentsTool to retrieve a paginated list of vendor payments with filters and search.
Mark Bill OpenTool to mark a bill as open.
Mark Bill VoidTool to mark a bill as Void.
Mark Contact as ActiveTool to mark a contact as active.
Mark Contact as InactiveTool to mark a contact as inactive.
Mark Estimate As SentTool to mark an estimate as Sent.
Mark Invoice As SentTool to mark an invoice as Sent.
Mark Item as ActiveTool to mark an item as active.
Mark Item as InactiveTool to mark an item as inactive.
Mark Location ActiveTool to mark a location as active.
Mark Location as InactiveTool to mark a location as inactive.
Mark Location PrimaryTool to mark a location as primary.
Mark Project ActiveTool to mark a project as active.
Mark Reporting Tag as ActiveTool to mark a reporting tag as active.
Mark Reporting Tag as InactiveTool to mark a reporting tag as inactive.
Mark Reporting Tag Default OptionTool to mark an option as default for a reporting tag.
Mark Retainer Invoice SentTool to mark a retainer invoice as Sent.
Mark Sales Order VoidTool to mark a sales order as Void.
Mark Tag Option ActiveTool to mark a reporting tag option as active.
Mark Tag Option as InactiveTool to mark a reporting tag option as inactive.
Mark User as InactiveTool to mark a user as inactive in Zoho Books.
Mark Vendor Credit VoidTool to void a vendor credit.
Open Sales OrderTool to mark a sales order as Open.
Bulk Print EstimatesTool to bulk print up to 25 estimates as a single PDF.
Bulk Print Sales OrdersTool to bulk print up to 25 sales orders as a single PDF.
Send Payment ReminderTool to send a payment reminder for an invoice.
Resume Recurring InvoiceTool to resume a recurring invoice.
Send Bulk Invoice ReminderTool to send payment reminders for multiple invoices at once.
Send Contact EmailTool to send an email to a contact in Zoho Books.
Stop Recurring InvoiceTool to stop a recurring invoice.
Untrack Contact 1099Tool to untrack a contact for 1099 reporting.
Update Bank TransactionTool to update an existing bank transaction in Zoho Books.
Update Vendor BillTool to update a vendor bill.
Update ContactTool to update details of a contact.
Update Contact PersonTool to update an existing contact person in Zoho Books.
Update Credit Note RefundTool to update details of a specific credit note refund.
Update CurrencyTool to update an existing currency in Zoho Books.
Update Custom Fields in ItemTool to update custom field values in an existing item.
Update EstimateTool to update an existing estimate (quote).
Update Estimate Billing AddressTool to update the billing address of an estimate.
Update Estimate Shipping AddressTool to update the shipping address for an estimate.
Update Estimate TemplateTool to update the template associated with an estimate.
Update InvoiceTool to update details of a specific invoice.
Update Invoice Attachment PreferenceTool to update attachment preference for an invoice.
Update Invoice Billing AddressTool to update the billing address of an invoice.
Update Invoice Shipping AddressTool to update the shipping address of a specific invoice.
Update Invoice TemplateTool to update the template associated with an invoice.
Update ItemTool to update details of a specific item.
Update JournalTool to update a journal entry in Zoho Books.
Update LocationTool to update an existing location in Zoho Books.
Update OrganizationTool to update an organization's settings and details.
Update ProjectTool to update a project in Zoho Books.
Update Project UserTool to update a user's details in a project.
Update Purchase Order Billing AddressTool to update the billing address of a purchase order.
Update Purchase Order CommentTool to update a comment on a purchase order.
Update Recurring BillTool to update a recurring bill in Zoho Books.
Update Recurring Invoice TemplateTool to update the template associated with a recurring invoice.
Update Reporting TagTool to update an existing reporting tag in Zoho Books.
Update Reporting Tag OptionsTool to update reporting tag options in Zoho Books.
Update Sales OrderTool to update a specific sales order.
Update Sales Order Attachment PreferenceTool to update attachment preference for a sales order.
Update Sales Order Billing AddressTool to update the billing address of a sales order.
Update Sales Order Shipping AddressTool to update the shipping address of a specific sales order.
Update Sales Order TemplateTool to update the template associated with a sales order.
Update UserTool to update an existing user in Zoho Books.
Update Vendor Payment RefundTool to update a vendor payment refund in Zoho Books.
Void InvoiceTool to mark an invoice as Void.
Write Off InvoiceTool to write off an invoice.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

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 Zoho books account and project
  • Basic familiarity with async Python/Typescript

Getting API Keys for OpenAI, Composio, and Zoho books

OpenAI API key (OPENAI_API_KEY)
  • Go to the OpenAI dashboard
  • Create an API key if you don't have one
  • Assign it to OPENAI_API_KEY in .env
Composio API key and user ID
  • Log into the Composio dashboard
  • Copy your API key from Settings
    • Use this as COMPOSIO_API_KEY
  • Pick a stable user identifier (email or ID)
    • Use this as COMPOSIO_USER_ID

Installing dependencies

pip install composio-llamaindex llama-index llama-index-llms-openai llama-index-tools-mcp python-dotenv

Create a new Python project and install the necessary dependencies:

  • composio-llamaindex: Composio's LlamaIndex integration
  • llama-index: Core LlamaIndex framework
  • llama-index-llms-openai: OpenAI LLM integration
  • llama-index-tools-mcp: MCP client for LlamaIndex
  • python-dotenv: Environment variable management

Set environment variables

bash
OPENAI_API_KEY=your-openai-api-key
COMPOSIO_API_KEY=your-composio-api-key
COMPOSIO_USER_ID=your-user-id

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 Zoho books access

Import modules

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()

Create a new file called zoho books_llamaindex_agent.py and import the required modules:

Key imports:

  • asyncio: For async/await support
  • Composio: Main client for Composio services
  • LlamaIndexProvider: Adapts Composio tools for LlamaIndex
  • ReActAgent: LlamaIndex's reasoning and action agent
  • BasicMCPClient: Connects to MCP endpoints
  • McpToolSpec: Converts MCP tools to LlamaIndex format

Load environment variables and initialize Composio

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")

What's happening:

This ensures missing credentials cause early, clear errors before the agent attempts to initialise.

Create a Tool Router session and build the agent function

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

    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 Zoho books actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Zoho books actions.
    """
    return ReActAgent(tools=tools, llm=llm, description=description, system_prompt=system_prompt, verbose=True)

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, zoho books)
  • 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 Zoho books tools.
  • The MCP tools are mapped to LlamaIndex-compatible tools and plug them into the Agent.

Create an interactive chat loop

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}")

What's happening here:

  • We're creating a direct terminal interface to chat with your Zoho books database
  • The LLM's responses are streamed to the CLI for faster interaction.
  • The agent uses context to maintain conversation history
  • You can type 'quit' or 'exit' to stop the chat loop gracefully
  • Agent responses and any errors are displayed in a clear, readable format

Define the main entry point

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!")

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 Zoho books

Run the agent

npx ts-node llamaindex-agent.ts

When prompted, authenticate and authorise your agent with Zoho books, then start asking questions.

Complete Code

Here's the complete code to get you started with Zoho books and LlamaIndex:

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

    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 Zoho books actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Zoho books 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!")

Conclusion

You've successfully connected Zoho books to LlamaIndex through Composio's Tool Router MCP layer. Key takeaways:
  • Tool Router dynamically exposes Zoho books 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 Zoho books MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Zoho books MCP?

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

Can I manage the permissions and scopes for Zoho books while using Tool Router?

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

Used by agents from

Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai

Never worry about agent reliability

We handle tool reliability, observability, and security so you never have to second-guess an agent action.