How to integrate Borneo MCP with LlamaIndex

Framework Integration Gradient
Borneo Logo
LlamaIndex Logo
divider

Introduction

This guide walks you through connecting Borneo to LlamaIndex 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 LlamaIndex 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:
  • Set your OpenAI and Composio API keys
  • Install LlamaIndex and Composio packages
  • Create a Composio Tool Router session for Borneo
  • Connect LlamaIndex to the Borneo MCP server
  • Build a Borneo-powered agent using LlamaIndex
  • Interact with Borneo through natural language

What is LlamaIndex?

LlamaIndex is a data framework for building LLM applications. It provides tools for connecting LLMs to external data sources and services through agents and tools.

Key features include:

  • ReAct Agent: Reasoning and acting pattern for tool-using agents
  • MCP Tools: Native support for Model Context Protocol
  • Context Management: Maintain conversation context across interactions
  • Async Support: Built for async/await patterns

What is the 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:
  • Python 3.8/Node 16 or higher installed
  • A Composio account with the API key
  • An OpenAI API key
  • A Borneo account and project
  • Basic familiarity with async Python/Typescript

Getting API Keys for OpenAI, Composio, and Borneo

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

Installing dependencies

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

Create a new Python project and install the necessary dependencies:

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

Set environment variables

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

Create a .env file in your project root:

These credentials will be used to:

  • Authenticate with OpenAI's GPT-5 model
  • Connect to Composio's Tool Router
  • Identify your Composio user session for Borneo access

Import modules

import asyncio
import os
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()

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

Key imports:

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

Load environment variables and initialize Composio

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set in the environment")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set in the environment")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set in the environment")

What's happening:

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

Create a Tool Router session and build the agent function

async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["borneo"],
    )

    mcp_url = session.mcp.url
    print(f"Composio MCP URL: {mcp_url}")

    mcp_client = BasicMCPClient(mcp_url, headers={"x-api-key": COMPOSIO_API_KEY})
    mcp_tool_spec = McpToolSpec(client=mcp_client)
    tools = await mcp_tool_spec.to_tool_list_async()

    llm = OpenAI(model="gpt-5")

    description = "An agent that uses Composio Tool Router MCP tools to perform Borneo actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Borneo actions.
    """
    return ReActAgent(tools=tools, llm=llm, description=description, system_prompt=system_prompt, verbose=True)

What's happening here:

  • We create a Composio client using your API key and configure it with the LlamaIndex provider
  • We then create a tool router MCP session for your user, specifying the toolkits we want to use (in this case, borneo)
  • The session returns an MCP HTTP endpoint URL that acts as a gateway to all your configured tools
  • LlamaIndex will connect to this endpoint to dynamically discover and use the available Borneo tools.
  • The MCP tools are mapped to LlamaIndex-compatible tools and plug them into the Agent.

Create an interactive chat loop

async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")

What's happening here:

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

Define the main entry point

async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")

What's happening here:

  • We're orchestrating the entire application flow
  • The agent gets built with proper error handling
  • Then we kick off the interactive chat loop so you can start talking to Borneo

Run the agent

npx ts-node llamaindex-agent.ts

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

Complete Code

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

import asyncio
import os
import signal
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set")

async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["borneo"],
    )

    mcp_url = session.mcp.url
    print(f"Composio MCP URL: {mcp_url}")

    mcp_client = BasicMCPClient(mcp_url, headers={"x-api-key": COMPOSIO_API_KEY})
    mcp_tool_spec = McpToolSpec(client=mcp_client)
    tools = await mcp_tool_spec.to_tool_list_async()

    llm = OpenAI(model="gpt-5")
    description = "An agent that uses Composio Tool Router MCP tools to perform Borneo actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Borneo actions.
    """
    return ReActAgent(
        tools=tools,
        llm=llm,
        description=description,
        system_prompt=system_prompt,
        verbose=True,
    );

async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")

async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")

Conclusion

You've successfully connected Borneo to LlamaIndex through Composio's Tool Router MCP layer. Key takeaways:
  • Tool Router dynamically exposes Borneo tools through an MCP endpoint
  • LlamaIndex's ReActAgent handles reasoning and orchestration; Composio handles integrations
  • The agent becomes more capable without increasing prompt size
  • Async Python provides clean, efficient execution of agent workflows
You can easily extend this to other toolkits like Gmail, Notion, Stripe, GitHub, and more by adding them to the toolkits parameter.

How to build 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 LlamaIndex?

Yes, you can. LlamaIndex fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right 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.