How to integrate Zoho books MCP with Vercel AI SDK v6

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Zoho books logo
Vercel AI SDK logo
divider

Introduction

This guide walks you through connecting Zoho books to Vercel AI SDK v6 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 Vercel AI SDK 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:
  • How to set up and configure a Vercel AI SDK agent with Zoho books integration
  • Using Composio's Tool Router to dynamically load and access Zoho books tools
  • Creating an MCP client connection using HTTP transport
  • Building an interactive CLI chat interface with conversation history management
  • Handling tool calls and results within the Vercel AI SDK framework

What is Vercel AI SDK?

The Vercel AI SDK is a TypeScript library for building AI-powered applications. It provides tools for creating agents that can use external services and maintain conversation state.

Key features include:

  • streamText: Core function for streaming responses with real-time tool support
  • MCP Client: Built-in support for Model Context Protocol via @ai-sdk/mcp
  • Step Counting: Control multi-step tool execution with stopWhen: stepCountIs()
  • OpenAI Provider: Native integration with OpenAI models

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:
  • Node.js and npm installed
  • A Composio account with API key
  • An OpenAI API key

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.

Install required dependencies

bash
npm install @ai-sdk/openai @ai-sdk/mcp @composio/core ai dotenv

First, install the necessary packages for your project.

What you're installing:

  • @ai-sdk/openai: Vercel AI SDK's OpenAI provider
  • @ai-sdk/mcp: MCP client for Vercel AI SDK
  • @composio/core: Composio SDK for tool integration
  • ai: Core Vercel AI SDK
  • dotenv: Environment variable management

Set up environment variables

bash
OPENAI_API_KEY=your_openai_api_key_here
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here

Create a .env file in your project root.

What's needed:

  • OPENAI_API_KEY: Your OpenAI API key for GPT model access
  • COMPOSIO_API_KEY: Your Composio API key for tool access
  • COMPOSIO_USER_ID: A unique identifier for the user session

Import required modules and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});
What's happening:
  • We're importing all necessary libraries including Vercel AI SDK's OpenAI provider and Composio
  • The dotenv/config import automatically loads environment variables
  • The MCP client import enables connection to Composio's tool server

Create Tool Router session and initialize MCP client

typescript
async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["zoho_books"],
  });

  const mcpUrl = session.mcp.url;
What's happening:
  • We're creating a Tool Router session that gives your agent access to Zoho books tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned mcp object contains the URL and authentication headers needed to connect to the MCP server
  • This session provides access to all Zoho books-related tools through the MCP protocol

Connect to MCP server and retrieve tools

typescript
const mcpClient = await createMCPClient({
  transport: {
    type: "http",
    url: mcpUrl,
    headers: session.mcp.headers, // Authentication headers for the Composio MCP server
  },
});

const tools = await mcpClient.tools();
What's happening:
  • We're creating an MCP client that connects to our Composio Tool Router session via HTTP
  • The mcp.url provides the endpoint, and mcp.headers contains authentication credentials
  • The type: "http" is important - Composio requires HTTP transport
  • tools() retrieves all available Zoho books tools that the agent can use

Initialize conversation and CLI interface

typescript
let messages: ModelMessage[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log(
  "Ask any questions related to zoho_books, like summarize my last 5 emails, send an email, etc... :)))\n",
);

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();
What's happening:
  • We initialize an empty messages array to maintain conversation history
  • A readline interface is created to accept user input from the command line
  • Instructions are displayed to guide the user on how to interact with the agent

Handle user input and stream responses with real-time tool feedback

typescript
rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

  if (!trimmedInput) {
    rl.prompt();
    return;
  }

  messages.push({ role: "user", content: trimmedInput });
  console.log("\nAgent is thinking...\n");

  try {
    const stream = streamText({
      model: openai("gpt-5"),
      messages,
      tools,
      toolChoice: "auto",
      stopWhen: stepCountIs(10),
      onStepFinish: (step) => {
        for (const toolCall of step.toolCalls) {
          console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • We use streamText instead of generateText to stream responses in real-time
  • toolChoice: "auto" allows the model to decide when to use Zoho books tools
  • stopWhen: stepCountIs(10) allows up to 10 steps for complex multi-tool operations
  • onStepFinish callback displays which tools are being used in real-time
  • We iterate through the text stream to create a typewriter effect as the agent responds
  • The complete response is added to conversation history to maintain context
  • Errors are caught and displayed with helpful retry suggestions

Complete Code

Here's the complete code to get you started with Zoho books and Vercel AI SDK:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});

async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["zoho_books"],
  });

  const mcpUrl = session.mcp.url;

  const mcpClient = await createMCPClient({
    transport: {
      type: "http",
      url: mcpUrl,
      headers: session.mcp.headers, // Authentication headers for the Composio MCP server
    },
  });

  const tools = await mcpClient.tools();

  let messages: ModelMessage[] = [];

  console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
  console.log(
    "Ask any questions related to zoho_books, like summarize my last 5 emails, send an email, etc... :)))\n",
  );

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (userInput: string) => {
    const trimmedInput = userInput.trim();

    if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
      console.log("\nGoodbye!");
      rl.close();
      process.exit(0);
    }

    if (!trimmedInput) {
      rl.prompt();
      return;
    }

    messages.push({ role: "user", content: trimmedInput });
    console.log("\nAgent is thinking...\n");

    try {
      const stream = streamText({
        model: openai("gpt-5"),
        messages,
        tools,
        toolChoice: "auto",
        stopWhen: stepCountIs(10),
        onStepFinish: (step) => {
          for (const toolCall of step.toolCalls) {
            console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});

Conclusion

You've successfully built a Zoho books agent using the Vercel AI SDK with streaming capabilities! This implementation provides a powerful foundation for building AI applications with natural language interfaces and real-time feedback.

Key features of this implementation:

  • Real-time streaming responses for a better user experience with typewriter effect
  • Live tool execution feedback showing which tools are being used as the agent works
  • Dynamic tool loading through Composio's Tool Router with secure authentication
  • Multi-step tool execution with configurable step limits (up to 10 steps)
  • Comprehensive error handling for robust agent execution
  • Conversation history maintenance for context-aware responses

You can extend this further by adding custom error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

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 Vercel AI SDK v6?

Yes, you can. Vercel AI SDK v6 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.