How to integrate Freshdesk MCP with Vercel AI SDK v6

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Freshdesk logo
Vercel AI SDK logo
divider

Introduction

This guide walks you through connecting Freshdesk to Vercel AI SDK v6 using the Composio tool router. By the end, you'll have a working Freshdesk agent that can create a new ticket for a customer issue, list all open tickets assigned to me, update ticket status to resolved for ticket 12345 through natural language commands.

This guide will help you understand how to give your Vercel AI SDK agent real control over a Freshdesk account through Composio's Freshdesk MCP server.

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

Also integrate Freshdesk with

TL;DR

Here's what you'll learn:
  • How to set up and configure a Vercel AI SDK agent with Freshdesk integration
  • Using Composio's Tool Router to dynamically load and access Freshdesk 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 Freshdesk MCP server, and what's possible with it?

The Freshdesk MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Freshdesk account. It provides structured and secure access to your support desk, so your agent can create tickets, fetch or update customer issues, reply to conversations, and automate ticket management on your behalf.

  • Automated ticket creation and triage: Instantly generate new support tickets for incoming customer queries, ensuring nothing gets lost in the shuffle.
  • Ticket lookup and status updates: Ask your agent to find, view, or update any ticket, including changing status, priority, or details based on evolving customer needs.
  • Streamlined customer replies: Have your agent draft or send replies directly to customers, keeping conversations moving and improving response times.
  • Effortless ticket list retrieval: Quickly pull lists of all tickets—filtered by status, priority, or other criteria—to get a real-time overview of the support pipeline.
  • Ticket deletion and cleanup: Direct your agent to close or remove outdated or resolved tickets, keeping your Freshdesk workspace tidy and efficient.

Supported Tools & Triggers

Tools
Add Note to TicketTool to add a private or public note to an existing ticket in Freshdesk.
Add Ticket User AccessTool to add agent access to a specific ticket in Freshdesk.
Add Watcher to TicketTool to add the authenticated user as a watcher to a Freshdesk ticket.
Bulk Unwatch TicketsTool to remove the authenticated user as a watcher from multiple Freshdesk tickets in bulk.
Bulk Update TicketsTool to update multiple tickets simultaneously in bulk.
Cancel Contact ImportTool to cancel an ongoing contact import operation in Freshdesk.
Create Admin GroupTool to create a new admin group in Freshdesk.
Create Admin GroupTool to create a new admin-level support agent group in Freshdesk.
Create Admin Ticket FieldTool to create a new custom ticket field in Freshdesk.
Create Admin Ticket Field SectionTool to create a new section within a ticket field in Freshdesk.
Create Multiple AgentsTool to create multiple agents in Freshdesk in a single bulk operation.
Create Canned ResponseTool to create a new canned response in Freshdesk.
Bulk Create Canned ResponsesTool to create multiple canned responses in bulk via asynchronous operation.
Create Canned Response FolderTool to create a new canned response folder in Freshdesk.
Create CompanyTool to create a new company in Freshdesk.
Create ContactTool to create a new contact in Freshdesk.
Create Contact FieldTool to create a new custom contact field in Freshdesk.
Create Discussion CategoryTool to create a new discussion category in Freshdesk forums.
Create Discussion Forum TopicTool to create a new topic in a Freshdesk discussion forum.
Create Discussion Topic CommentTool to create a new comment on a discussion forum topic.
Create Email MailboxTool to create a new email mailbox in Freshdesk.
Create ForumTool to create a new forum within a category in Freshdesk discussions.
Create SLA PolicyTool to create a new SLA (Service Level Agreement) policy in Freshdesk.
Create Solution ArticleTool to create a new solution article in a Freshdesk knowledge base folder.
Create Solution CategoryTool to create a new solution category in Freshdesk's knowledge base.
Create TicketCreates a new ticket in Freshdesk.
Create Ticket FormTool to create a new ticket form in Freshdesk.
Create Ticket via Outbound EmailTool to create a ticket by sending an outbound email to external recipients.
Create Ticket Time EntryTool to create a time entry for a specific ticket in Freshdesk.
Create Translated Solution CategoryTool to create a translated version of an existing solution category.
Currently Authenticated AgentTool to retrieve profile information for the currently authenticated agent.
Delete Admin GroupTool to delete an admin group from Freshdesk.
Delete AgentTool to permanently delete an agent from Freshdesk.
Delete Automation RulePermanently deletes an automation rule from Freshdesk by its type and rule ID.
Delete CompanyTool to permanently disband a company from Freshdesk.
Delete Company FieldTool to permanently delete a custom company field from Freshdesk.
Delete ContactTool to soft delete a contact from Freshdesk.
Delete Contact FieldPermanently delete a custom contact field from Freshdesk.
Delete ConversationTool to permanently delete a conversation from a ticket in Freshdesk.
Delete Discussion CategoryPermanently deletes a forum discussion category from Freshdesk.
Delete Discussion CommentTool to permanently delete a comment from a discussion in Freshdesk.
Delete Discussion ForumTool to permanently delete a discussion forum in Freshdesk.
Unmonitor ForumTool to unfollow/unmonitor a discussion forum in Freshdesk.
Unmonitor TopicTool to unfollow/unmonitor a discussion topic in Freshdesk.
Delete Discussion TopicTool to permanently delete a discussion topic in Freshdesk.
Delete Email MailboxTool to permanently delete an email mailbox from Freshdesk.
Delete GroupTool to permanently disband a group from Freshdesk.
Delete Multiple TicketsAsynchronously deletes multiple tickets in bulk.
Delete SectionTool to permanently delete a section from a ticket field in Freshdesk.
Delete SkillTool to permanently delete a skill from Freshdesk.
Delete Solution ArticleTool to permanently delete a solution article and its translated versions in Freshdesk.
Delete Solution CategoryPermanently delete a solution category from Freshdesk's knowledge base.
Delete Solution FolderTool to permanently delete a solution folder and its translated versions in Freshdesk.
Delete TicketTool to permanently delete a ticket from Freshdesk.
Delete Ticket FieldPermanently delete a custom ticket field from Freshdesk.
Delete Ticket FormTool to permanently delete a ticket form from Freshdesk.
Delete Ticket Form FieldTool to permanently delete a specific field from a ticket form in Freshdesk.
Delete Ticket SummaryTool to delete the AI-generated summary of a ticket in Freshdesk.
Delete Ticket User AccessTool to remove all agent access from a specific ticket in Freshdesk.
Delete Time EntryTool to permanently delete a time entry from Freshdesk.
Export ContactsTool to initiate an asynchronous export of contacts from Freshdesk to CSV file.
Get AccountTool to view Freshdesk account information.
Get AgentTool to retrieve detailed information about a specific agent by ID.
Get Agent AvailabilityTool to retrieve availability information for a specific agent.
Search Agents AutocompleteTool to search for agents using autocomplete functionality in Freshdesk.
Get Business HoursRetrieves all business hours configurations from Freshdesk.
Get Canned Response FoldersTool to retrieve all canned response folders from Freshdesk.
Get CompaniesTool to retrieve all companies from a Freshdesk account with pagination support.
Get CompanyTool to retrieve detailed information about a specific company by ID.
Get Company FieldsTool to retrieve all company fields configured in Freshdesk.
Get ContactTool to retrieve detailed information about a specific contact by ID.
Get Contact FieldsTool to retrieve all contact fields configured in Freshdesk.
Get ContactsTool to retrieve all contacts from a Freshdesk account.
Get Discussion CategoryTool to view details of a specific forum category in Freshdesk.
View Discussion TopicTool to retrieve detailed information about a specific discussion topic by ID.
Get Email MailboxTool to retrieve detailed information about a specific email mailbox by ID.
Get Folder ResponsesTool to retrieve all canned responses within a specific folder in Freshdesk.
Get Imported ContactsTool to retrieve details of all contact import operations in Freshdesk.
Get JobTool to view the status of a bulk job operation.
List All Scenario AutomationsTool to list all scenario-based automations in Freshdesk.
Filter TicketsTool to search and filter tickets in Freshdesk using flexible query syntax.
Get TicketsRetrieves a list of tickets from Freshdesk.
Get Ticket Time EntriesTool to retrieve all time entries for a specific ticket in Freshdesk.
Get Ticket User AccessTool to retrieve agent access information for a specific ticket in Freshdesk.
Get Translated Solution CategoryTool to view a translated solution category in Freshdesk.
Hard Delete ContactTool to permanently delete a contact from Freshdesk.
Import ContactTool to import contacts in bulk from a CSV file to Freshdesk.
List Admin GroupsTool to list all admin groups in Freshdesk.
List All Agents in a GroupTool to retrieve all agents associated with a specific group in Freshdesk.
List All Sections for a Ticket FieldTool to retrieve all dynamic sections for a specific ticket field in Freshdesk.
List All SkillsTool to retrieve all skills configured in Freshdesk account.
List All Ticket ConversationsTool to retrieve all conversations of a specific ticket in Freshdesk.
List Automation RulesTool to list all automation rules for a specific automation type in Freshdesk.
List All Forum CategoriesTool to retrieve all forum categories (discussions) from Freshdesk.
List All Topics in a ForumTool to retrieve all discussion topics within a specified forum in Freshdesk.
List Email MailboxesTool to retrieve all email mailbox configurations from Freshdesk account.
List All Email ConfigsRetrieve all email configurations from a Freshdesk account.
List Forums in CategoryTool to retrieve all forums within a specified category in Freshdesk.
List Monitored TopicsTool to retrieve all discussion topics that are monitored/followed by a specific user in Freshdesk.
List Participated TopicsTool to retrieve discussion topics that a user has participated in by creating or commenting.
List All ProductsTool to retrieve all products configured in Freshdesk account.
List All RolesTool to retrieve all roles available in the Freshdesk system with their permissions and details.
List Satisfaction RatingsTool to retrieve all customer satisfaction survey ratings from Freshdesk.
List All SLA PoliciesTool to retrieve all SLA (Service Level Agreement) policies in Freshdesk.
List Solution ArticlesTool to retrieve all solution articles within a specified folder in Freshdesk.
List Solution CategoriesTool to retrieve all solution categories in Freshdesk.
List Solution FoldersTool to retrieve all folders within a specified solution category in Freshdesk.
List Translated Category FoldersTool to retrieve all translated solution folders in a category.
List Solution SubfoldersTool to list all subfolders within a specific solution folder in Freshdesk.
List a Specific Section DetailsTool to retrieve details of a specific section within a ticket field in Freshdesk.
List All SurveysTool to retrieve all surveys from a Freshdesk account.
List All Ticket FieldsTool to list all ticket fields configured in Freshdesk.
List Ticket FormsTool to retrieve all ticket forms from Freshdesk.
List Ticket Satisfaction RatingsTool to list all satisfaction ratings of a ticket.
List Ticket WatchersTool to list all watchers subscribed to a specific Freshdesk ticket.
List Time EntriesTool to retrieve all time entries from Freshdesk with optional filtering by company, agent, execution time range, and billable status.
List Topic Comments (Paginated)Tool to list all comments on a specific discussion topic with pagination support.
List Translated Solution ArticlesTool to view all translated solution articles in a folder for a specific language.
List Translated SubfoldersTool to list all translated subfolders within a parent folder in Freshdesk.
Update Group AgentsTool to add or remove agents in a Freshdesk group.
Remove Watcher from TicketTool to remove the authenticated user as a watcher from a Freshdesk ticket.
Reply to Forward TicketTool to reply to or forward a ticket to external email addresses.
Reply to TicketTool to create a public reply to an existing support ticket in Freshdesk.
Search AgentsTool to search and filter agents in Freshdesk.
Search CompaniesTool to search and filter companies in Freshdesk using query strings with custom fields.
Search Companies AutocompleteTool to search for companies using autocomplete functionality in Freshdesk.
Search ContactsTool to search and filter contacts in Freshdesk using query-based search.
Search Contacts AutocompleteTool to search for contacts using autocomplete functionality in Freshdesk.
Search Solution ArticlesTool to search solution articles in Freshdesk knowledge base by keyword.
Toggle TimerTool to toggle the timer on a time entry to start or stop time tracking.
Update Admin GroupTool to update an existing admin-level support agent group in Freshdesk.
Update Admin Ticket FieldTool to update an existing ticket field configuration in Freshdesk.
Update Admin Ticket Field SectionTool to update a section within a ticket field in Freshdesk.
Update AgentTool to update an existing agent's information in Freshdesk.
Update Agent AvailabilityTool to update agent availability settings in Freshdesk.
Update Automation RuleTool to update an existing automation rule in Freshdesk.
Update Canned ResponseTool to update an existing canned response in Freshdesk.
Update Canned Response FolderUpdates the name of an existing canned response folder in Freshdesk.
Update CompanyTool to update an existing company's information in Freshdesk.
Update ContactTool to update an existing contact's information in Freshdesk.
Update Contact FieldTool to update a contact field's configuration in Freshdesk.
Make AgentTool to convert a contact into an agent in Freshdesk.
Update ConversationTool to update the content of a conversation note in Freshdesk.
Update Discussion CategoryTool to update an existing discussion category in Freshdesk forums.
Update Discussion CommentTool to update an existing comment in a discussion forum.
Update Discussion ForumTool to update an existing discussion forum in Freshdesk.
Update Discussion TopicTool to update an existing discussion topic in Freshdesk.
Update Email SettingsTool to update mailbox settings for email handling in Freshdesk.
Update Automatic BCC EmailsTool to update automatic BCC email addresses for all ticket communications in Freshdesk.
Update SLA PolicyTool to update an existing SLA (Service Level Agreement) policy in Freshdesk.
Update Solution CategoryTool to update an existing solution category in Freshdesk.
Update Solution FolderTool to update an existing solution folder in Freshdesk knowledge base.
Update Solution ArticleTool to update an existing solution article in Freshdesk.
Update TicketTool to update an existing ticket in Freshdesk.
Bulk Add Watcher to TicketsTool to add the authenticated user as a watcher to multiple tickets in a single bulk operation.
Update Ticket FormTool to update an existing ticket form in Freshdesk.
Update Ticket SummaryTool to update the AI-generated summary of a ticket in Freshdesk.
Update Ticket User AccessTool to update agent access to a specific ticket in Freshdesk by adding or removing agents.
Update Time EntryTool to update an existing time entry in Freshdesk.
View a Canned ResponseTool to view details of a specific canned response in Freshdesk.
View Automation RuleTool to view details of a specific automation rule in Freshdesk.
View a Business HourTool to retrieve a specific business hour configuration from Freshdesk.
View a Company FieldTool to retrieve details of a specific company field by ID.
View a Contact FieldTool to retrieve details of a specific contact field by ID.
View Email Mailbox SettingsTool to retrieve mailbox settings for the Freshdesk account.
View Email ConfigTool to view details of a specific email configuration in Freshdesk.
View GroupTool to view details of a specific admin group in Freshdesk.
View Automatic BCC EmailsTool to view automatic BCC email addresses configured in Freshdesk.
View ProductTool to retrieve detailed information about a specific product by ID.
View a RoleTool to view detailed information about a specific role by ID.
View Helpdesk SettingsTool to retrieve helpdesk settings from Freshdesk.
View a SkillTool to retrieve a specific skill from Freshdesk by ID.
View Solution CategoryTool to view a specific solution category by ID in Freshdesk.
View Solution FolderTool to view a specific solution folder by ID in Freshdesk.
View Solution ArticleTool to view a specific solution article by ID in Freshdesk.
View TicketViews an existing ticket in Freshdesk.
View a Ticket FieldTool to retrieve a single ticket field configuration from Freshdesk.
View a Ticket Form's FieldTool to retrieve a specific field from a ticket form in Freshdesk.

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: ["freshdesk"],
  });

  const mcpUrl = session.mcp.url;
What's happening:
  • We're creating a Tool Router session that gives your agent access to Freshdesk 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 Freshdesk-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 Freshdesk 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 freshdesk, 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 Freshdesk 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 Freshdesk 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: ["freshdesk"],
  });

  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 freshdesk, 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 Freshdesk 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 Freshdesk MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Freshdesk MCP?

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

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

Yes, absolutely. You can configure which Freshdesk 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 Freshdesk 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.