How to integrate Pipedrive MCP with LlamaIndex

Framework Integration Gradient
Pipedrive Logo
LlamaIndex Logo
divider

Introduction

This guide walks you through connecting Pipedrive to LlamaIndex using the Composio tool router. By the end, you'll have a working Pipedrive agent that can add a new deal for acme corp, log a sales call with follow-up, create a lead labeled 'high priority', add a comment to yesterday's note through natural language commands.

This guide will help you understand how to give your LlamaIndex agent real control over a Pipedrive account through Composio's Pipedrive 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 Pipedrive
  • Connect LlamaIndex to the Pipedrive MCP server
  • Build a Pipedrive-powered agent using LlamaIndex
  • Interact with Pipedrive 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 Pipedrive MCP server, and what's possible with it?

The Pipedrive MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Pipedrive account. It provides structured and secure access to your sales pipelines, so your agent can add deals, log sales activities, manage leads, and automate pipeline updates on your behalf.

  • Automated deal creation and management: Let your agent add new deals, update existing ones, and include custom fields to keep your pipeline moving smoothly.
  • Lead tracking and labeling: Automatically add leads linked to people or organizations, and tag them with custom labels for better segmentation and follow-up.
  • Sales activity logging: Effortlessly log calls and add comments to notes so every sales interaction is recorded and actionable.
  • Deal and contact following: Have your agent add followers to deals, organizations, people, or products so your team never misses an important update.
  • Channel and messaging support: Enable your agent to add new messaging channels for integrated communication right within your Pipedrive environment.

Supported Tools & Triggers

Tools
Triggers
Add a call logAdds a new call log.
Add a channelNew messaging channel added; registration limited to admins.
Add a comment to a noteAdds a new comment to a note.
Add a dealAdd a new deal to pipedrive with any custom fields, which vary by account and are identified by long hash keys.
Add a follower to a dealAdds a follower to a deal.
Add a follower to an organizationAdds a follower to an organization.
Add a follower to a personAdds a follower to a person.
Add a follower to a productAdds a follower to a product.
Add a leadPipedrive api lets you add leads linked to people or organizations and tags them with 'api' source.
Add a lead labelCreates a lead label.
Add an activityNew activity added.
Add a new deal fieldAdds a new deal field.
Add a new filterNew filter creation returns an id.
Add a new goalAdds a new goal.
Add a new organization fieldAdds a new organization field.
Add a new person fieldAdds a new person field.
Add a new pipelineAdds a new pipeline.
Add a new product fieldAdds a new product field.
Add a new stageAdds a new stage, returns the id upon success.
Add a new teamAdds a new team to the company and returns the created object.
Add a new userAdds a new user to the company, returns the id upon success.
Add an installment subscriptionAdds a new installment subscription.
Add an organizationSet up a new pipedrive organization using custom fields with unique key hashes.
Add a noteAdd a note to a deal, person, organization, lead, or project in pipedrive.
Add a participant to a dealAdds a participant to a deal.
Add a personAdd a new contact in pipedrive with optional custom fields unique to each account found using the `personfields` endpoint.
Add a productAdds a new product to the products inventory.
Add a product to a dealAdds a product to a deal, creating a new item called a deal-product.
Add a projectAdds a new project.
Add a recurring subscriptionAdds a new recurring subscription.
Add a roleAdds a new role.
Add a taskAdds a new task.
Add fileUpload and link files to deals, people, organizations, activities, products, or leads in pipedrive.
Add new activity typeAdds a new activity type.
Add or update role settingAdds or updates the visibility setting for a role.
Add person pictureThis service allows adding a photo to a person's profile, replacing any existing one.
Add role assignmentAssigns a user to a role.
Add users to a teamAdds users to an existing team.
Archive a projectArchives a project.
Attach an audio file to the call logAdds an audio recording to the call log.
Cancel a recurring subscriptionCancels a recurring subscription.
Create a new webhookCreates and returns details of a new webhook.
Create an organization relationshipCreates and returns an organization relationship.
Create a remote file and link it to an itemCreates an empty file on google drive linked to an item.
Delete a call logDeletes a call log.
Delete a channelThe endpoint removes a messenger channel along with conversations and messages.
Delete a comment related to a noteDeletes a comment.
Delete a conversationDeletes an existing conversation.
Delete a dealMarks a deal as deleted.
Delete a deal fieldMarks a field as deleted.
Delete a fileMarks a file as deleted.
Delete a filterMarks a filter as deleted.
Delete a follower from a dealDeletes a follower from a deal.
Delete a follower from an organizationDeletes a follower from an organization.
Delete a follower from a personDeletes a follower from a person.
Delete a follower from a productDeletes a follower from a product.
Delete a leadDeletes a specific lead.
Delete a lead labelDeletes a specific lead label.
Delete an activityMarks an activity as deleted.
Delete an activity typeMarks an activity type as deleted.
Delete an attached product from a dealDeletes a product attachment from a deal, using the `product attachment id`.
Delete an organizationMarks an organization as deleted.
Delete an organization fieldMarks a field as deleted.
Delete an organization relationshipDeletes an organization relationship and returns the deleted id.
Delete a noteDeletes a specific note.
Delete a participant from a dealDeletes a participant from a deal.
Delete a personMarks a person as deleted.
Delete a person fieldMarks a field as deleted.
Delete a pipelineMarks a pipeline as deleted.
Delete a productMarks a product as deleted.
Delete a product fieldMarks a product field as deleted.
Delete a projectMarks a project as deleted.
Delete a roleMarks a role as deleted.
Delete a role assignmentRemoves the assigned user from a role and adds to the default role.
Delete a stageMarks a stage as deleted.
Delete a subscriptionMarks an installment or a recurring subscription as deleted.
Delete a taskMarks a task as deleted.
Delete existing goalMarks a goal as deleted.
Delete existing webhookDeletes the specified webhook.
Delete mail threadMarks a mail thread as deleted.
Delete multiple activities in bulkMarks multiple activities as deleted.
Delete multiple activity types in bulkMarks multiple activity types as deleted.
Delete multiple deal fields in bulkMarks multiple deal fields as deleted.
Delete multiple deals in bulkMarks multiple deals as deleted.
Delete multiple filters in bulkMarks multiple filters as deleted.
Delete multiple organization fields in bulkMarks multiple fields as deleted.
Delete multiple organizations in bulkMarks multiple organizations as deleted.
Delete multiple person fields in bulkMarks multiple fields as deleted.
Delete multiple persons in bulkMarks multiple persons as deleted.
Delete multiple product fields in bulkMarks multiple fields as deleted.
Delete multiple stages in bulkMarks multiple stages as deleted.
Delete person pictureDeletes a person’s picture.
Delete users from a teamDeletes users from an existing team.
Download one fileInitializes a file download.
Duplicate dealDuplicates a deal.
Enumerate accessible users for leadLists the users permitted to access a lead.
Find goalsQuery goal data by appending `{searchfield}={searchvalue}` to the url with dot-notation fields and values.
Find subscription by dealReturns details of an installment or a recurring subscription by the deal id.
Find users by nameFinds users by their name.
Get all activities assigned to a particular userReturns all activities assigned to a particular user.
Get all activities betaThis beta cursor-paginated endpoint returns all activities, accessible only to global admins, not regular users who get a 403 error.
Get all activity fieldsReturns all activity fields.
Get all activity typesReturns all activity types.
Get all add ons for a single companyReturns the add-ons for a single company.
Get all call logs assigned to a particular userReturns all call logs assigned to a particular user.
Get all comments for a noteReturns all comments associated with a note.
Get all deal fieldsReturns data about all deal fields.
Get all dealsReturns all deals.
Get all deals betaThis endpoint returns all deals with cursor pagination (in beta).
Get all filesReturns data about all files.
Get all filter helpersThe text provides links to documentation for adding or updating filters, and information on all supported filter helpers in an api.
Get all filtersReturns data about all filters.
Get all lead labelsReturns details of all lead labels.
Get all leadsThe api returns sorted leads by creation time, supporting pagination via `limit` and `start`.
Get all lead sourcesReturns all lead sources.
Get all mail messages of mail threadReturns all the mail messages inside a specified mail thread.
Get all note fieldsReturns data about all note fields.
Get all notesReturns all notes.
Get all organization fieldsReturns data about all organization fields.
Get all organizationsReturns all organizations.
Get all organizations betaThis beta api endpoint lists all organizations with cursor pagination.
Get all payments of a subscriptionReturns all payments of an installment or recurring subscription.
Get all permission setsReturns data about all permission sets.
Get all person fieldsReturns data about all person fields.
Get all personsReturns all persons.
Get all persons betaThis beta endpoint returns all persons, using cursor pagination.
Get all pipelinesReturns data about all pipelines.
Get all product fieldsReturns data about all product fields.
Get all productsReturns data about all products.
Get all project boardsReturns all projects boards that are not deleted.
Get all projectsReturns all projects.
Get all project templatesThe endpoint retrieves all non-deleted project templates with cursor-based pagination.
Get all relationships for organizationGets all of the relationships for a supplied organization id.
Get all rolesReturns all the roles within the company.
Get all stagesReturns data about all stages.
Get all supported currenciesReturns all supported currencies in given account which should be used when saving monetary values with other objects.
Get all tasksReturns all tasks.
Get all teamsReturns data about teams within the company.
Get all teams of a userReturns data about all teams which have the specified user as a member.
Get all user connectionsReturns data about all connections for the authorized user.
Get all usersReturns data about all users within the company.
Get all users in a teamReturns a list of all user ids within a team.
Get all webhooksReturns data about all the webhooks of a company.
Get a single teamReturns data about a specific team.
Get current user dataReturns data about an authorized user within the company with bound company data: company id, company name, and domain.
Get deals conversion rates in pipelineReturns all stage-to-stage conversion and pipeline-to-close rates for the given time period.
Get deals in a pipelineLists deals in a specific pipeline across all its stages.
Get deals in a stageLists deals in a specific stage.
Get deals movements in pipelineReturns statistics for deals movements for the given time period.
Get deals summaryReturns a summary of all the deals.
Get deals timelineReturns opened and won deals in time-based groups according to a specified dealfield, with examples of deals grouped by month over a 3-month period starting january 2012.
Get deals where a product is attached toReturns data about deals that have a product attached to it.
Get details of a boardReturns the details of a specific project board.
Get details of a call logReturns details of a specific call log.
Get details of a dealFetches specific deal details, including exclusive fields like deal age and pipeline stage duration.
Get details of an activityReturns the details of a specific activity.
Get details of an organizationProvides detailed information about an organization, including additional fields not shown when listing all organizations, and maps custom fields as long hashes to the 'key' value in organizationfields.
Get details of a personThe text describes an api endpoint that returns detailed person information, including extra fields and custom fields as hashes.
Get details of a phaseReturns the details of a specific project phase.
Get details of a projectReturns the details of a specific project.
Get details of a subscriptionReturns details of an installment or a recurring subscription.
Get details of a taskReturns the details of a specific task.
Get details of a templateReturns the details of a specific project template.
Get mail threadsReturns mail threads in a specified folder ordered by the most recent message within.
Get one commentReturns the details of a comment.
Get one deal fieldReturns data about a specific deal field.
Get one fileReturns data about a specific file.
Get one filterReturns data about a specific filter.
Get one leadApi returns specific lead details with custom field values in the deals format.
Get one mail messageReturns data about a specific mail message.
Get one mail threadReturns a specific mail thread.
Get one noteReturns details about a specific note.
Get one organization fieldReturns data about a specific organization field.
Get one organization relationshipFinds and returns an organization relationship from its id.
Get one permission setReturns data about a specific permission set.
Get one person fieldReturns data about a specific person field.
Get one pipelineReturns data about a specific pipeline.
Get one productReturns data about a specific product.
Get one product fieldReturns data about a specific product field.
Get one roleReturns the details of a specific role.
Get one stageReturns data about a specific stage.
Get one userReturns data about a specific user within the company.
Get project phasesReturns all active project phases under a specific board.
Get recentsReturns data about all recent changes occurred after the given timestamp.
Get result of a goalGets the progress of a goal for the specified period.
Link a remote file to an itemLinks an existing remote file (`googledrive`) to the item you supply.
Link User Video IntegrationA video calling provider must call this endpoint after a user has installed the video calling app so that the new user's information is sent.
List activities associated with a dealLists activities associated with a deal.
List activities associated with an organizationLists activities associated with an organization.
List activities associated with a personLists activities associated with a person.
List all persons associated with a dealThe endpoint lists every person linked to a deal, including primary contacts and participants, and provides a `data.
List deals associated with an organizationLists deals associated with an organization.
List deals associated with a personLists deals associated with a person.
List files attached to a dealLists files associated with a deal.
List files attached to an organizationLists files associated with an organization.
List files attached to a personLists files associated with a person.
List files attached to a productLists files associated with a product.
List followers of a dealLists the followers of a deal.
List followers of an organizationLists the followers of an organization.
List followers of a personLists the followers of a person.
List followers of a productLists the followers of a product.
List followers of a userLists the followers of a specific user.
List mail messages associated with a dealLists mail messages associated with a deal.
List mail messages associated with an organizationLists mail messages associated with an organization.
List mail messages associated with a personLists mail messages associated with a person.
List participants of a dealLists the participants associated with a deal.
List permission set assignmentsReturns the list of assignments for a permission set.
List permitted usersLists the users permitted to access a deal.
List Person Access UsersList users permitted to access a person.
List persons of an organizationLists persons associated with an organization.
List pipeline visibility for a roleReturns a list of visible or hidden pipeline ids by role.
List Product Permitted UsersLists users permitted to access a product.
List products associated with a personLists products associated with a person.
List products attached to a dealLists products attached to a deal.
List role assignmentsReturns all users assigned to a role.
List role settingsReturns the visibility settings of a specific role.
List settings of an authorized userLists the settings of an authorized user.
List updates about a dealLists updates about a deal.
List updates about an organizationLists updates about an organization.
List updates about a personLists updates about a person.
List updates about participants of a dealThis endpoint provides cursor-paginated updates on deal participants.
List user permissionsLists aggregated permissions over all assigned permission sets for a user.
List user role settingsLists the settings of user's assigned role.
Merge two dealsMerges a deal with another deal.
Merge two organizationsMerges an organization with another organization.
Merge two personsMerges a person with another person.
Organization accessible user listList users permitted to access an organization.
Perform a search from multiple item typesPerforms a search from your choice of item types and fields.
List User Role AssignmentsLists role assignments for a user.
Receives an incoming messageAdds a message to a conversation.
Refreshing the tokensAccess tokens expire after the time specified in `expires in`.
Requesting authorizationAuthorize a user by redirecting them to the pipedrive oauth authorization page and request their permissions to act on their behalf.
Returns project activitiesReturns activities linked to a specific project.
Returns project groupsReturns all active groups under a specific project.
Returns project planReturns information about items in a project plan.
Returns project tasksReturns tasks linked to a specific project.
Search dealsThis api endpoint searches deals by title, notes, and custom fields, filters results by person or organization id, and is a specific use case of /v1/itemsearch with limited oauth scope.
Search Item By FieldPerforms a search from the values of a specific field.
Search leadsEndpoint searches leads by title, notes, custom fields, with options to filter by person and organization ids, and is a more specific use of the /v1/itemsearch with limited oauth scope.
Search organizationsSearches all organizations by name, address, notes and/or custom fields.
Search personsThis endpoint searches for individuals by various identifiers and is a specific use case of /v1/itemsearch with limited oauth scope, allowing results filtering by organization id.
Search productsSearches all products by name, code and/or custom fields.
UnlinkuserfromvideocallintegrationA video calling provider must call this endpoint to remove the link between a user and the installed video calling app.
Update a comment related to a noteUpdates a comment related to a note.
Update activity in project planUpdates an activity phase or group in a project.
Update a dealUpdates the properties of a deal.
Update a deal fieldUpdates a deal field.
Update a leadUpdating lead properties modifies only specified fields; use `null` to unset.
Update a lead labelUpdates one or more properties of a lead label.
Update an activityUpdates an activity.
Update an activity typeUpdates an activity type.
Update an installment subscriptionUpdates an installment subscription.
Update an organizationUpdates the properties of an organization.
Update an organization fieldUpdates an organization field.
Update an organization relationshipUpdates and returns an organization relationship.
Update a noteUpdates a note.
Update a personModifies a person’s details in pipedrive.
Update a person fieldUpdates a person field.
Update a pipelineUpdates the properties of a pipeline.
Update a productUpdates product data.
Update a product fieldUpdates a product field.
Update a projectUpdates a project.
Update a recurring subscriptionUpdates a recurring subscription.
Update a taskUpdates a task.
Update a teamUpdates an existing team and returns the updated object.
Update existing goalUpdates an existing goal.
Update file detailsUpdates the properties of a file.
Update filterUpdates an existing filter.
Update mail thread detailsUpdates the properties of a mail thread.
Update pipeline visibility for a roleUpdates pipeline visibility settings for different roles.
Update role detailsUpdates the parent role and/or the name of a specific role.
Update stage detailsUpdates the properties of a stage.
Update task in project planUpdates a task phase or group in a project.
Update the product attached to a dealUpdates the details of the product that has been attached to a deal.
Update user detailsUpdates the properties of a user.

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

Getting API Keys for OpenAI, Composio, and Pipedrive

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 Pipedrive 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 pipedrive_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=["pipedrive"],
    )

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

Run the agent

npx ts-node llamaindex-agent.ts

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

Complete Code

Here's the complete code to get you started with Pipedrive 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=["pipedrive"],
    )

    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 Pipedrive actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Pipedrive 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 Pipedrive to LlamaIndex through Composio's Tool Router MCP layer. Key takeaways:
  • Tool Router dynamically exposes Pipedrive 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 Pipedrive MCP Agent with another framework

FAQ

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

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

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

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