How to integrate Borneo MCP with Vercel AI SDK

Framework Integration Gradient
Borneo Logo
Vercel AI SDK Logo
divider

Introduction

This guide walks you through connecting Borneo to Vercel AI SDK using the Composio tool router. By the end, you'll have a working Borneo agent that can start a new cloud resource scan for sensitive data, archive a discovered recipient for compliance reasons, create a new dashboard user with admin access, generate a data protection impact assessment for a processing activity through natural language commands.

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

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

TL;DR

Here's what you'll learn:
  • How to set up and configure a Vercel AI SDK agent with Borneo integration
  • Using Composio's Tool Router to dynamically load and access Borneo 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
  • Step Counting: Control multi-step tool execution
  • OpenAI Provider: Native integration with OpenAI models

What is the Borneo MCP server, and what's possible with it?

The Borneo MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Borneo account. It provides structured and secure access to your organization's data security and privacy operations, so your agent can perform actions like scheduling cloud resource scans, managing data breaches, onboarding users, and automating privacy compliance workflows on your behalf.

  • Automated sensitive data discovery and scans: Instruct your agent to create and schedule scans across cloud resources for compliance, security audits, and regular data inspection.
  • Data breach evaluation and remediation: Have your agent delete outdated or irrelevant data breach records to maintain accurate compliance documentation and ensure up-to-date risk management.
  • User and employee onboarding automation: Let your agent create dashboard users with specific roles or onboard new employees, streamlining access management and HR integration tasks.
  • Department and domain management: Direct your agent to add new departments with multilingual support or set up domains for automated system integrations and workflow triggers.
  • Privacy assessment and compliance operations: Empower your agent to initiate or update Data Protection Impact Assessments (DPIAs) for processing activities, supporting structured risk evaluation and regulatory compliance.

Supported Tools & Triggers

Tools
Access scan iteration by idRetrieves detailed information about a specific scan iteration in the borneo integration platform.
Add discovered recipientsAdds multiple discovered recipients to the system as confirmed recipients.
Archive discovered recipientArchives a specific discovered recipient in the borneo platform.
Delete data breach by idDeletes a specific data breach evaluation record from the borneo system.
Create and schedule cloud resource scanThe createscan endpoint initiates a new scan operation in the borneo integration platform, allowing users to configure and schedule data scans across various cloud resources.
Create dashboard userCreates a new dashboard user in the borneo integration platform with specified roles, organizational access, and authentication settings.
Create department with translationsCreates a new department in the borneo integration platform.
Create domain with polling frequencyCreates a new domain within the borneo integration platform, allowing for automatic polling and management of connected systems or applications.
Create dpia for processing activityCreates a new data protection impact assessment (dpia) for a specific processing activity in the borneo application.
Create employee with json payloadCreates a new employee record in the borneo integration platform.
Create headquarter entryCreates a new headquarters entry in the borneo integration platform.
Create legal document entryCreates or uploads a new legal document in the borneo integration platform with specified metadata.
Create new assetCreates a new asset in the borneo integration platform.
Create new infotype categoryCreates a new infotype category in the borneo integration platform, allowing users to organize and group related sensitive data types.
Create processing activityCreates a new processing activity in the borneo integration platform.
Create processing activity thresholdCreates a new threshold for a specific data processing activity in the context of lopdp (law on personal data protection) compliance.
Create recipient with detailsCreates a new recipient in the borneo integration platform.
Create threshold for processing activityCreates a new threshold for a specific data processing activity in the borneo integration platform.
Delete asset by idThe deleteasset endpoint removes a specific asset from the borneo integration platform.
Delete category by labelDeletes a specific category from the borneo integration platform using its unique label.
Delete dashboard report by idDeletes a specific dashboard report from the borneo integration platform.
Delete department by idDeletes a specific department from the borneo platform using its unique identifier.
Delete domain by idDeletes a specific domain from the borneo integration platform.
Delete dpia by idDeletes a specific data protection impact assessment (dpia) from the borneo system.
Delete employee by idDeletes an employee record from the borneo system using the specified employee id.
Delete headquarters by idDeletes a specific headquarters record from the borneo system.
Delete legal document by idDeletes a specific legal document from the borneo platform using its unique identifier.
Delete lopdp threshold by idThis endpoint deletes a specific lopdp (local public data protection) threshold from the borneo integration platform.
Delete processing activity by idDeletes a specific processing activity from the borneo integration platform.
Delete recipient by idDeletes a specific recipient from the borneo integration platform.
Delete tag from resourceThe deletetags endpoint removes specified tags from resources in the borneo integration platform.
Delete threshold by idDeletes a specific threshold from the borneo integration platform.
Disable dashboard user by usernameDisables a specified user account in the borneo dashboard, preventing further access to the system.
Download dashboard reportThe downloaddashboardreport endpoint allows users to download specific types of dashboard reports from the borneo integration platform.
Download dashboard report editionDownloads a specific dashboard report edition from the borneo integration platform.
Enable dashboard userEnables dashboard access for a specified user in the borneo integration platform.
Evaluate data breach impactThis endpoint allows users to evaluate and document details of a data breach incident.
Export filtered leaf resourcesThe listleafresources endpoint exports a comprehensive list of leaf resources in the borneo integration platform, allowing for extensive filtering, sorting, and detailed information retrieval.
Export insight page using scanidThe exportpageinsight endpoint allows users to export filtered inspection results from a specific scan in the borneo integration platform.
Export inventory resource listExports a filtered and sorted list of inventory resources from the borneo integration platform.
Export processing activities listThis endpoint exports a filtered list of processing activities in specified formats and languages.
Export recipients list with filterThe exportrecipientslist endpoint generates and exports a list of recipients based on specified criteria.
Fetch dashboard report by idRetrieves a specific dashboard report from the borneo integration platform.
Fetch data breach evaluationRetrieves detailed information about a specific evaluated data breach incident.
Filter and list inspection resultsThe insightlistpost endpoint retrieves a list of inspection results from the borneo integration platform.
Filter and sort assets listThe listassets endpoint retrieves a customized list of assets from borneo.
Filter employee listThe filteremployeelist endpoint allows you to retrieve a filtered list of employees based on specified criteria.
Filter recipients listThe filterrecipientslist endpoint allows users to retrieve a filtered list of recipients based on specified criteria.
Get category by labelRetrieves detailed information about a specific category within borneo's data classification system using the category's unique label.
Get cloud account by idRetrieves detailed information about a specific cloud account within the borneo integration platform.
Get dashboard report edition by idRetrieves a specific edition of a dashboard report from the borneo integration platform.
Get department filter listThe filterdepartmentlist endpoint allows users to retrieve a filtered list of departments from the borneo integration platform.
Get domain by idRetrieves detailed information about a specific domain within the borneo integration platform.
Get headquarters by idRetrieves detailed information about a specific headquarters registered in the borneo system.
Get insight by type and idRetrieves a specific insight from the borneo platform based on its type and unique identifier.
Get resource inventory by idRetrieves detailed inventory information for a specific resource identified by its unique resourceid.
Get scan by scanidRetrieves detailed information about a specific data scan performed by borneo's data risk remediation platform.
Get threshold by idRetrieves detailed information about a specific threshold setting in the borneo integration platform.
Get user profile by idRetrieves the user profile information for a specific user in the borneo integration platform.
List dashboard report editionsLists the editions of a specific dashboard report in the borneo integration platform.
List dashboard reports with filtersRetrieves a list of dashboard reports from the borneo integration platform, allowing for filtered, paginated, and sorted results.
List dashboard users with filtersLists and filters dashboard users in the borneo integration platform based on specified criteria.
List data breaches with filtersThe listdatabreaches endpoint retrieves a list of data breaches based on specified filter conditions, allowing for detailed searching and sorting of breach information.
List data breach filtersRetrieves a list of available filter options for data breaches in the borneo platform.
List departments with sort and paginationThe listdepartments endpoint retrieves a list of departments within the borneo integration platform.
List discovered documentRetrieves a list of discovered documents in the borneo integration platform, allowing for flexible querying, filtering, and sorting of results.
List discovered infotypesThe listdiscoveredinfotypes endpoint retrieves discovered info types from borneo, supporting flexible querying, filtering, sorting, and pagination.
List discovered recipientsLists and retrieves discovered recipients in the borneo integration platform.
List domains with pagination and sortingRetrieves a list of domains in the borneo integration platform with support for pagination and custom sorting.
List employees with filtersRetrieves a list of employees based on specified filtering and sorting criteria.
List error details from filtered scan iterationsThe errorlist endpoint retrieves errors related to scan iterations in borneo.
List events with filtersLists and retrieves events based on specified criteria, with options for filtering, sorting, and pagination.
List filtered sorted categoriesThe listcategories endpoint allows users to retrieve a list of categories from the borneo integration platform.
List filter options for recipientsLists the available filters for recipients in the borneo integration platform based on the specified filter type.
List headquarters with sortingThe headquarters list endpoint retrieves a paginated list of headquarters records from borneo.
List insight filtersThe list-filters endpoint retrieves a list of available filters for data insights, specifically focused on file extension filters.
List inventory resources with filtersRetrieves a comprehensive list of resources from borneo's inventory.
List issues with filtersThe listissues endpoint allows users to retrieve a filtered and sorted list of issues from the borneo integration platform.
List leaf resources with filtersThe listleafresources endpoint retrieves and filters leaf resources from borneo's catalog.
List legal documents with paginationRetrieves a paginated and sortable list of legal documents based on specified filter criteria.
List or filter recipientsThe listrecipients endpoint retrieves a paginated and filtered list of recipients from the borneo application.
List processing activitiesListprocessingactivities retrieves a list of processing activities with extensive filtering, sorting, and pagination.
List processing activities filtersThis endpoint retrieves a list of available filters for processing activities in the pops (processing of personal data) dashboard.
List scan execution resultsThe listscanexecutions endpoint retrieves and filters inspection results from scan executions in the borneo integration platform.
List scan iterations with filterThe listscaniterations endpoint allows users to retrieve a paginated list of scan iterations with customizable filtering, sorting, and field selection options.
List scans with filtersThe list scans endpoint retrieves a filtered and sorted list of scans from the borneo integration platform.
List toms with filter and pagination optionsThe listtoms endpoint retrieves a filtered, sorted, and paginated list of toms from the borneo integration platform.
List user profile with filters and sortingThe listuserprofiles endpoint retrieves a paginated and filterable list of user profiles from borneo.
Mark scan false positives by idMarks specified reports as false positives within a given scan in the borneo platform.
Pause scan by idThe pausescan endpoint allows users to temporarily halt an ongoing scan process in the borneo integration platform.
Poll domain by idThis endpoint allows you to initiate a poll operation or submit data for a specific domain within the borneo integration platform.
Post accounts with filter and sort optionsThe listaccounts endpoint retrieves a filtered and sorted list of accounts from the borneo platform.
Post classification statsRetrieves statistical information about resource classifications based on the specified filter criteria.
Post connector with filtering optionsRetrieves a filtered and sorted list of connectors from the borneo integration platform.
Post current dashboard userRetrieves or updates information about the currently authenticated user in the borneo dashboard.
Post dashboard reportCreates or schedules a dashboard report in the borneo integration platform for privacy operations and data discovery.
Post data breach informationCreates a new data breach report in the borneo platform.
Post discovered recipient by idUpdates or processes information for a specific discovered recipient user in the borneo integration platform.
Post filtered access logsThe listaccesslogs endpoint retrieves and filters access logs from the borneo integration platform.
Post log audit records with filter criteriaThe retrieveauditlogs endpoint fetches filtered audit logs from borneo.
Post resource lineage filterRetrieves the lineage information for a specified resource within the borneo integration platform.
Post resource stats with deleted resourcesRetrieves statistics about resources within the borneo integration platform.
Post scan resource statusRetrieves and filters the resource status for a specific scan iteration in the borneo integration platform.
Post support chat queryThe post /support/chat endpoint handles chat support interactions in borneo.
Put tom status and noteUpdates a specific technical operating model (tom) in the borneo integration platform.
Remove dashboard user by usernameRemoves a specified user from the dashboard in the borneo integration platform.
Reset dashboard user passwordInitiates a password reset process for a specified dashboard user in the borneo platform.
Resume scan by idThe resumedatascan endpoint allows users to resume a previously paused or interrupted data scan operation within the borneo integration platform.
Retrieve account details by idRetrieves detailed information for a specific account within the borneo integration platform.
Retrieve asset by idRetrieves detailed information about a specific asset within the borneo integration platform.
Retrieve connector by idRetrieves detailed information about a specific connector in the borneo integration platform.
Retrieve data breach by idRetrieves detailed information about a specific data breach incident using its unique identifier.
Retrieve data resource statisticsRetrieves comprehensive statistical information about data resources across the borneo integration platform.
Retrieve department informationRetrieves detailed information about a specific department within the borneo integration platform.
Retrieve discovered document by idRetrieves detailed information about a specific discovered document within the borneo system.
Retrieve discovered infotype by idRetrieves detailed information about a specific discovered infotype from the borneo platform.
Retrieve discovered recipient by idRetrieves detailed information about a specific discovered recipient using their unique identifier.
Retrieve dpia by idRetrieves a specific data protection impact assessment (dpia) using its unique identifier.
Retrieve employee details by idRetrieves detailed information for a specific employee within the borneo integration platform.
Retrieve error details by idThe geterrordetails endpoint retrieves detailed information about a specific error in the borneo integration platform using its unique identifier.
Retrieve issue by idRetrieves detailed information about a specific issue in the borneo system.
Retrieve legal document by idRetrieves a specific legal document from the borneo system using its unique identifier.
Retrieve lopdp threshold by idRetrieves detailed information about a specific lopdp (logical object data point) threshold configuration within the borneo integration platform.
Retrieve processing activity by idRetrieves detailed information about a specific processing activity within the borneo platform.
Retrieve recipient detailsRetrieves detailed information about a specific recipient identified by their unique recipientid within the borneo integration platform.
Retrieve recipient processing activitiesRetrieves a paginated list of processing activities associated with a specific recipient in the borneo integration platform.
Retrieve resource catalog by idRetrieves detailed information about a specific resource from the borneo catalog using its unique identifier.
Retrieve resource columnsRetrieves column information for resources in the borneo integration platform.
Retrieve tom by idRetrieves detailed information about a specific tom resource using its unique identifier.
Scan legal document byidInitiates a scanning process for a specified legal document within the borneo integration platform.
Stop scan via scanidStops an ongoing scan operation in the borneo integration platform.
Submit chat feedbackThe submitchatfeedback endpoint allows users to provide feedback on a chat support interaction within the borneo integration platform.
Submit detailed scan resultsRetrieves detailed insights for a specific scan iteration of a particular resource in the borneo integration platform.
Trigger dashboard report by report idTriggers the generation or retrieval of a specific dashboard report in the borneo integration platform.
Update asset information by idThe updateasset endpoint allows you to modify the details of an existing asset in the borneo integration platform.
Update category infotypesUpdates the infotypes associated with a specific category in the borneo integration platform.
Update dashboard report frequency and recipientsUpdates the settings of an existing dashboard report in the borneo integration platform.
Update dashboard user detailsUpdates the information of an existing dashboard user in the borneo integration platform.
Update dashboard user rolesUpdates the roles and department associations for a specified user across multiple organizations in the borneo dashboard.
Update data breach entryThe updatedatabreach endpoint allows users to create or update detailed information about a specific data breach incident in the borneo integration platform.
Update department nameThis endpoint updates the information of an existing department within the borneo integration platform.
Update discovered document statusThis endpoint updates the status of a specific discovered document in the borneo integration platform.
Update discovered infotype statusUpdates the status of a specific discovered infotype in the borneo integration platform.
Update domain detailsUpdates the properties of an existing domain within the borneo integration platform.
Update dpia by idUpdates an existing data protection impact assessment (dpia) in the borneo system.
Update employee by idUpdates the information of an existing employee in the borneo integration platform.
Update headquarter details by idUpdates the information for an existing headquarter in the borneo integration platform.
Update lopdp threshold by idUpdates the lopdp (likely operational privacy data protection) threshold settings for a specific threshold identified by the lopdpthresholdid.
Update processing activity detailsThis endpoint updates an existing processing activity in a data privacy management system.
Update recipient details by idUpdates the information of an existing recipient in the borneo integration platform.
Update recipient status via idUpdates the status and automation status of a specific recipient in the borneo integration platform.
Update threshold by idUpdates an existing threshold in the borneo integration platform with new settings and information related to data processing and compliance.
Verify email with id and tokenCompletes the email verification process for a user account in the borneo integration platform.

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

What is Tool Router?

Composio's Tool Router 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 Tool Router

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

How the Tool Router works

The Tool Router 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 { experimental_createMCPClient as 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: ["borneo"],
  });

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

  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 borneo, 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 Borneo 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 Borneo MCP Agent with another framework

FAQ

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

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

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

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

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

Used by agents from

Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
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.