# How to integrate Persona MCP with LlamaIndex

```json
{
  "title": "How to integrate Persona MCP with LlamaIndex",
  "toolkit": "Persona",
  "toolkit_slug": "persona",
  "framework": "LlamaIndex",
  "framework_slug": "llama-index",
  "url": "https://composio.dev/toolkits/persona/framework/llama-index",
  "markdown_url": "https://composio.dev/toolkits/persona/framework/llama-index.md",
  "updated_at": "2026-03-29T06:45:25.385Z"
}
```

## Introduction

This guide walks you through connecting Persona to LlamaIndex using the Composio tool router. By the end, you'll have a working Persona agent that can get all pending verification cases, trigger a new kyc verification for user, list users who failed identity checks through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Persona account through Composio's Persona MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Persona with

- [OpenAI Agents SDK](https://composio.dev/toolkits/persona/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/persona/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/persona/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/persona/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/persona/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/persona/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/persona/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/persona/framework/cli)
- [Google ADK](https://composio.dev/toolkits/persona/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/persona/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/persona/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/persona/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/persona/framework/crew-ai)

## 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 Persona
- Connect LlamaIndex to the Persona MCP server
- Build a Persona-powered agent using LlamaIndex
- Interact with Persona 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 Persona MCP server, and what's possible with it?

The Persona MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Persona account. It provides structured and secure access so your agent can perform Persona operations on your behalf.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `PERSONA_ADD_TAG_TO_ACCOUNT` | Add Tag to Account | Tool to add a tag to an Account in Persona. Use when you need to categorize or label an account with a specific tag. Either tag_id or tag_name must be provided in the request meta. |
| `PERSONA_ARCHIVE_A_BROWSER_FINGERPRINT_LIST_ITEM` | Archive Browser Fingerprint List Item | Tool to archive a browser fingerprint list item in Persona. Use when you need to mark a browser fingerprint list item as archived without permanently deleting it. |
| `PERSONA_ARCHIVE_A_COUNTRY_LIST_ITEM` | Archive Country List Item | Tool to archive a Country List Item by ID. Use when you need to mark a country list item as archived. This action is idempotent - archiving an already archived item is safe. |
| `PERSONA_ARCHIVE_A_GEOLOCATION_LIST_ITEM` | Archive a Geolocation List Item | Tool to archive a geolocation list item from Persona. Use when you need to archive a specific geolocation list item by its ID. This operation marks the item as archived without permanently deleting it. |
| `PERSONA_ARCHIVE_GOVERNMENT_ID_NUMBER_LIST_ITEM` | Archive Government ID Number List Item | Tool to archive a Government ID Number List Item. Use when you need to remove a government ID number from the active list. |
| `PERSONA_ARCHIVE_A_NAME_LIST_ITEM` | Archive a Name List Item | Tool to archive a name list item in Persona. Use when you need to archive a specific name list item by its ID. |
| `PERSONA_ARCHIVE_A_WEBHOOK` | Archive a webhook | Tool to archive a Persona webhook by its ID. Use when you need to deactivate a webhook without deleting it. Archived webhooks will no longer receive events but can be referenced for historical purposes. |
| `PERSONA_ARCHIVE_EMAIL_ADDRESS_LIST_ITEM` | Archive Email Address List Item | Tool to archive an Email Address List Item in Persona. Use when you need to archive an email address or domain from a list. The archived item will be marked with an archived timestamp in the response. |
| `PERSONA_ARCHIVE_IP_ADDRESS_LIST_ITEM` | Archive IP Address List Item | Tool to archive an IP address list item in Persona. Use when you need to remove an IP address from active monitoring. |
| `PERSONA_ARCHIVE_PHONE_NUMBER_LIST_ITEM` | Archive Phone Number List Item | Tool to archive a phone number list item in Persona. Use when you need to mark a phone number list item as archived without permanently deleting it. |
| `PERSONA_ARCHIVE_STRING_LIST_ITEM` | Archive String List Item | Tool to archive a String List Item in Persona. Use when you need to mark a string list item as archived without permanently deleting it. The item will be marked with an archived timestamp and its status will be updated accordingly. |
| `PERSONA_CLONE_WEBHOOK` | Clone Webhook | Tool to clone an existing Persona webhook. Use when you need to duplicate a webhook configuration with all its settings. |
| `PERSONA_CONSOLIDATE_ACCOUNTS` | Consolidate Accounts | Tool to consolidate multiple source accounts into a single destination account. Use when merging duplicate accounts or combining account data from multiple sources into one primary account. |
| `PERSONA_CREATE_AN_ACCOUNT` | Create an Account | Tool to create an account in Persona. Use when you need to create a new account with personal information such as name, email, phone, address, and custom fields. |
| `PERSONA_CREATE_IP_ADDRESS_LIST_ITEM` | Create IP Address List Item | Tool to create an IP Address List Item in Persona. Use when you need to add an IP address to a watchlist or allowlist for identity verification purposes. The list ID must be obtained first using a list retrieval action. |
| `PERSONA_CREATE_COUNTRY_LIST_ITEM` | Create Country List Item | Tool to create a country list item in Persona. Use when you need to add a country to a country list for identity verification or compliance purposes. |
| `PERSONA_CREATE_GENERIC_DOCUMENT` | Create Generic Document | Tool to create a generic document in Persona. Use when you need to create a document record of a specific kind/type for an account or inquiry. |
| `PERSONA_CREATE_EMAIL_ADDRESS_LIST_ITEM` | Create Email Address List Item | Tool to create an email address list item in Persona. Use when you need to add an email address to a watchlist or blocklist. |
| `PERSONA_CREATE_GOVERNMENT_ID_NUMBER_LIST_ITEM` | Create Government ID Number List Item | Tool to create a new government ID number list item in Persona. Use when you need to add a government ID number (such as SSN, passport, or driver's license) to a watchlist or monitoring list. |
| `PERSONA_CREATE_NAME_LIST_ITEM` | Create Name List Item | Tool to create a new name list item in Persona. Use when you need to add a person's name to a specific list for verification or monitoring purposes. |
| `PERSONA_CREATE_PHONE_NUMBER_LIST_ITEM` | Create Phone Number List Item | Tool to create a phone number list item in Persona. Use when you need to add a phone number to a specific list for tracking or verification purposes. |
| `PERSONA_CREATE_STRING_LIST_ITEM` | Create String List Item | Tool to create a String List Item in Persona. Use when adding a new string value to an existing list for matching or filtering purposes. |
| `PERSONA_CREATE_WEBHOOK` | Create Webhook | Tool to create a new webhook in Persona. Use when you need to set up real-time notifications for specific events in your Persona account. The webhook will send POST requests to your URL when enabled events occur. |
| `PERSONA_DISABLE_WEBHOOK` | Disable Webhook | Tool to disable a webhook in Persona. Use when you need to stop a webhook from receiving events without deleting it. |
| `PERSONA_ENABLE_WEBHOOK` | Enable Webhook | Tool to enable a webhook in Persona. Use when you need to activate a previously disabled webhook. |
| `PERSONA_EXPIRE_INQUIRY_SESSIONS` | Expire Inquiry Sessions | Tool to expire all inquiry sessions for specified inquiry IDs. Use when you need to expire multiple inquiry sessions at once by providing a list of inquiry IDs. |
| `PERSONA_IMPORT_EMAIL_ADDRESS_LISTS` | Import Email Address Lists | Tool to import email addresses into a list from a CSV file. Use when you need to bulk import email addresses for identity verification or list management. |
| `PERSONA_IMPORT_IP_ADDRESS_LISTS` | Import IP Address Lists | Tool to import IP address lists into Persona. Use when you need to bulk upload IPv4 or IPv6 addresses to an existing list. |
| `PERSONA_IMPORT_NAME_LISTS` | Import Name Lists | Tool to import name lists to Persona. Use when you need to bulk import first and last names to an existing name list for identity verification purposes. |
| `PERSONA_IMPORT_PHONE_NUMBER_LISTS` | Import Phone Number Lists | Tool to import phone number lists into Persona. Use when you need to bulk upload phone numbers in E.164 format to an existing list. |
| `PERSONA_LIST_ALL_ACCOUNTS` | List All Accounts | Tool to list all accounts in Persona. Use when you need to retrieve a paginated list of accounts with optional filtering by reference ID or account type. |
| `PERSONA_LIST_ALL_API_LOGS` | List All API Logs | Tool to list all API logs in Persona. Use when you need to retrieve a paginated history of API requests made to your organization, including request details, response status, and timing information. |
| `PERSONA_LIST_ALL_CASES` | List All Cases | Tool to list all cases in Persona. Use when you need to retrieve a collection of cases with optional filtering and pagination. |
| `PERSONA_LIST_ALL_DEVICES` | List All Devices | Tool to list all devices filtered by inquiry session ID. Use when you need to retrieve devices associated with a specific inquiry session. |
| `PERSONA_LIST_ALL_EVENTS` | List all Events | Tool to list all events from Persona. Use when you need to retrieve events for your organization. Supports pagination and filtering by creation date. Events up to 3 months old can be viewed. |
| `PERSONA_LIST_ALL_IMPORTERS` | List all Importers | Tool to list all importers in Persona. Use when you need to retrieve a list of all import operations, including account importers, email address list importers, and other types. |
| `PERSONA_LIST_ALL_INQUIRIES` | List All Inquiries | Tool to list all inquiries in Persona. Use when you need to retrieve a paginated collection of inquiries with optional filtering by reference ID, account ID, status, or inquiry template ID. |
| `PERSONA_LIST_ALL_INQUIRY_SESSIONS` | List All Inquiry Sessions | Tool to list all inquiry sessions in Persona. Use when you need to retrieve a collection of inquiry sessions with optional filtering. |
| `PERSONA_LIST_ALL_LISTS` | List All Lists | Tool to list all lists in Persona. Use when you need to retrieve a paginated collection of lists with optional filtering and field selection. |
| `PERSONA_LIST_ALL_RATE_LIMITS` | List All Rate Limits | Tool to list all rate limits in Persona. Use when you need to retrieve current rate limit information for your API usage. |
| `PERSONA_LIST_ALL_REPORTS` | List All Reports | Tool to list all reports in Persona. Use when you need to retrieve a collection of reports with optional filtering and pagination. Reports can include various types such as adverse media, watchlist, profile, and verification reports. |
| `PERSONA_LIST_ALL_TRANSACTIONS` | List All Transactions | Tool to list all transactions in Persona. Use when you need to retrieve a paginated collection of transactions with optional filtering. |
| `PERSONA_LIST_ALL_WEBHOOKS` | List All Webhooks | Tool to list all webhooks in Persona. Use when you need to retrieve a paginated list of webhooks configured for the account. |
| `PERSONA_LIST_ALL_WORKFLOW_RUNS` | List all Workflow Runs | Tool to list all workflow runs in Persona. Use when you need to retrieve workflow runs with optional filtering by workflow ID, inquiry ID, account ID, or session token. Supports pagination for large result sets. |
| `PERSONA_REDACT_AN_ACCOUNT` | Redact an Account | Tool to permanently redact an account in Persona. Use when you need to delete sensitive personal information from an account to comply with privacy regulations or user requests. This operation is irreversible. |
| `PERSONA_REMOVE_ACCOUNT_TAG` | Remove Account Tag | Tool to remove a tag from a Persona Account. Use when you need to remove a tag association from an account by providing either the tag ID or tag name. |
| `PERSONA_RETRIEVE_A_COUNTRY_LIST_ITEM` | Retrieve a Country List Item | Tool to retrieve a country list item by ID in Persona. Use when you need to fetch details of a specific country list item. |
| `PERSONA_RETRIEVE_A_GEOLOCATION_LIST_ITEM` | Retrieve a Geolocation List Item | Tool to retrieve a geolocation list item from Persona. Use when you need to fetch details of a specific geolocation list item by its ID. |
| `PERSONA_RETRIEVE_AN_ACCOUNT` | Retrieve an Account | Tool to retrieve an account in Persona. Use when you need to fetch details of a specific account by its ID. |
| `PERSONA_RETRIEVE_A_NAME_LIST_ITEM` | Retrieve a Name List Item | Tool to retrieve a Name List Item in Persona. Use when you need to get details about a specific name list item, including first name, last name, status, match count, and timestamps. |
| `PERSONA_RETRIEVE_AN_EVENT` | Retrieve an Event | Tool to retrieve an event in Persona. Use when you need to fetch details of a specific event that was logged by Persona. |
| `PERSONA_RETRIEVE_AN_IMPORTER` | Retrieve an Importer | Tool to retrieve a specific importer in Persona. Use when you need to get details about a specific import operation by its ID. |
| `PERSONA_RETRIEVE_IP_ADDRESS_LIST_ITEM` | Retrieve IP Address List Item | Tool to retrieve an IP Address List Item in Persona. Use when you need to get details about a specific IP address list item, including its value, status, match count, and timestamps. |
| `PERSONA_RETRIEVE_AN_API_LOG` | Retrieve an API Log | Tool to retrieve an API log in Persona. Use when you need to fetch details of a specific API request/response that was logged by Persona. |
| `PERSONA_RETRIEVE_A_STRING_LIST_ITEM` | Retrieve a String List Item | Tool to retrieve a string list item by ID in Persona. Use when you need to fetch details of a specific string list item. |
| `PERSONA_RETRIEVE_A_WEBHOOK` | Retrieve a Webhook | Tool to retrieve a webhook by its ID. Use when you need to fetch details about a specific webhook configuration. |
| `PERSONA_RETRIEVE_BROWSER_FINGERPRINT_LIST_ITEM` | Retrieve Browser Fingerprint List Item | Tool to retrieve a browser fingerprint list item in Persona. Use when you need to fetch details of a specific browser fingerprint from a list for identity verification or fraud prevention purposes. |
| `PERSONA_RETRIEVE_A_DOCUMENT` | Retrieve a Document | Tool to retrieve a document from Persona. Use when you need to fetch details of a specific document by its ID. |
| `PERSONA_RETRIEVE_GENERIC_DOCUMENT` | Retrieve Generic Document | Tool to retrieve a generic document in Persona. Use when you need to fetch details of a specific document by its ID. |
| `PERSONA_RETRIEVE_EMAIL_ADDRESS_LIST_ITEM` | Retrieve Email Address List Item | Tool to retrieve an Email Address List Item in Persona. Use when you need to get details about a specific email address list item, including its value, status, match count, and timestamps. |
| `PERSONA_RETRIEVE_GOVERNMENT_ID_NUMBER_LIST_ITEM` | Retrieve Government ID Number List Item | Tool to retrieve a Government ID Number List Item in Persona. Use when you need to get details about a specific government ID number list item, including its ID number, ID class, status, match count, and timestamps. |
| `PERSONA_RETRIEVE_PHONE_NUMBER_LIST_ITEM` | Retrieve Phone Number List Item | Tool to retrieve a phone number list item in Persona. Use when you need to fetch details of a specific phone number from a list for identity verification or fraud prevention purposes. |
| `PERSONA_ROTATE_WEBHOOK_SECRET` | Rotate Webhook Secret | Tool to rotate a webhook's secret in Persona. Use when you need to generate a new secret key for webhook signature verification while optionally keeping the old secret active for a grace period. |
| `PERSONA_SEARCH_ACCOUNTS` | Search Accounts | Tool to search accounts in Persona using flexible query criteria. Use when you need to find accounts based on specific attributes, tags, or status. Supports boolean logic (AND/OR/NOT) and comparison operators. |
| `PERSONA_SEARCH_CASES` | Search Cases | Tool to search cases in Persona using advanced query filters with boolean logic. Use when you need to find cases matching specific criteria using operators like eq, gt, gte, lt, lte combined with AND/OR/NOT logic. |
| `PERSONA_SET_TAGS_ON_ACCOUNT` | Set Tags on Account | Tool to set tags on a Persona Account. Use when you need to assign or update tags for an account using either tag IDs or tag names. This operation replaces all existing tags with the provided ones. |
| `PERSONA_UPDATE_AN_ACCOUNT` | Update an Account | Tool to update an account in Persona. Use when you need to modify account information such as name, email, phone, address, reference ID, or custom fields. |
| `PERSONA_UPDATE_A_WEBHOOK` | Update a Webhook | Tool to update a webhook in Persona. Use when you need to modify webhook configuration such as name, description, URL, or enabled events. |
| `PERSONA_UPDATE_GENERIC_DOCUMENT` | Update Generic Document | Tool to update a generic document in Persona. Use when you need to modify fields, files, or kind of an existing document by its ID. |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The Persona MCP server is an implementation of the Model Context Protocol that connects your AI agent to Persona. It provides structured and secure access so your agent can perform Persona operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. 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 Persona account and project
- Basic familiarity with async Python/Typescript

### 1. Getting API Keys for OpenAI, Composio, and Persona

No description provided.

### 2. Installing dependencies

No description provided.
```python
pip install composio-llamaindex llama-index llama-index-llms-openai llama-index-tools-mcp python-dotenv
```

```typescript
npm install @composio/llamaindex @llamaindex/openai @llamaindex/tools @llamaindex/workflow dotenv
```

### 3. Set environment variables

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 Persona access
```bash
OPENAI_API_KEY=your-openai-api-key
COMPOSIO_API_KEY=your-composio-api-key
COMPOSIO_USER_ID=your-user-id
```

### 4. Import modules

No description provided.
```python
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()
```

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();
```

### 5. Load environment variables and initialize Composio

No description provided.
```python
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")
```

```typescript
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!COMPOSIO_API_KEY) throw new Error("COMPOSIO_API_KEY is not set");
if (!COMPOSIO_USER_ID) throw new Error("COMPOSIO_USER_ID is not set");
```

### 6. Create a Tool Router session and build the agent function

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, persona)
- 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 Persona tools.
- The MCP tools are mapped to LlamaIndex-compatible tools and plug them into the Agent.
```python
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=["persona"],
    )

    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 Persona actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Persona actions.
    """
    return ReActAgent(tools=tools, llm=llm, description=description, system_prompt=system_prompt, verbose=True)
```

```typescript
async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["persona"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
        description : "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Persona actions." ,
    llm,
    tools,
  });

  return agent;
}
```

### 7. Create an interactive chat loop

No description provided.
```python
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}")
```

```typescript
async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}
```

### 8. Define the main entry point

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 Persona
```python
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!")
```

```typescript
async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err) {
    console.error("Failed to start agent:", err);
    process.exit(1);
  }
}

main();
```

### 9. Run the agent

When prompted, authenticate and authorise your agent with Persona, then start asking questions.
```bash
python llamaindex_agent.py
```

```typescript
npx ts-node llamaindex-agent.ts
```

## Complete Code

```python
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=["persona"],
    )

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

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";
import { LlamaindexProvider } from "@composio/llamaindex";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();

const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) {
    throw new Error("OPENAI_API_KEY is not set in the environment");
  }
if (!COMPOSIO_API_KEY) {
    throw new Error("COMPOSIO_API_KEY is not set in the environment");
  }
if (!COMPOSIO_USER_ID) {
    throw new Error("COMPOSIO_USER_ID is not set in the environment");
  }

async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["persona"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
    description:
      "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Persona actions." ,
    llm,
    tools,
  });

  return agent;
}

async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}

async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err: any) {
    console.error("Failed to start agent:", err?.message ?? err);
    process.exit(1);
  }
}

main();
```

## Conclusion

You've successfully connected Persona to LlamaIndex through Composio's Tool Router MCP layer.
Key takeaways:
- Tool Router dynamically exposes Persona 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 Persona MCP Agent with another framework

- [OpenAI Agents SDK](https://composio.dev/toolkits/persona/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/persona/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/persona/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/persona/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/persona/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/persona/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/persona/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/persona/framework/cli)
- [Google ADK](https://composio.dev/toolkits/persona/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/persona/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/persona/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/persona/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/persona/framework/crew-ai)

## Related Toolkits

- [Stripe](https://composio.dev/toolkits/stripe) - Stripe is a global online payments platform offering APIs for managing payments, customers, and subscriptions. Trusted by businesses for secure, efficient, and scalable payment processing worldwide.
- [Aeroleads](https://composio.dev/toolkits/aeroleads) - Aeroleads is a B2B lead generation platform for finding business emails and phone numbers. Grow your sales pipeline faster with powerful prospecting tools.
- [Alpha vantage](https://composio.dev/toolkits/alpha_vantage) - Alpha Vantage is a financial data platform offering real-time and historical stock market APIs. Get instant, reliable access to equities, forex, and technical analysis data for smarter trading decisions.
- [Altoviz](https://composio.dev/toolkits/altoviz) - Altoviz is a cloud-based billing and invoicing platform for businesses. It streamlines online payments, expense tracking, and customizable invoice management.
- [Apilio](https://composio.dev/toolkits/apilio) - Apilio is a home automation platform that lets you connect and control smart devices from different brands. It helps you build flexible automations with complex conditions, schedules, and integrations.
- [Autobound](https://composio.dev/toolkits/autobound) - Autobound is an AI-powered sales engagement platform that crafts hyper-personalized outreach and insights. It helps sales teams boost response rates and close more deals through tailored content and recommendations.
- [Basin](https://composio.dev/toolkits/basin) - Basin is a no-code form backend for quickly setting up reliable contact forms. It lets you collect and manage form submissions without writing any server-side code.
- [Benzinga](https://composio.dev/toolkits/benzinga) - Benzinga provides real-time financial news and data APIs for market coverage. It helps you track breaking news and actionable market insights instantly.
- [Better proposals](https://composio.dev/toolkits/better_proposals) - Better Proposals is a web-based tool for crafting and sending professional proposals. It helps teams impress clients and close deals faster with slick, easy-to-use templates.
- [Bidsketch](https://composio.dev/toolkits/bidsketch) - Bidsketch is a proposal software that helps businesses create professional proposals quickly and efficiently. It streamlines the proposal process, saving time while boosting client win rates.
- [Bolna](https://composio.dev/toolkits/bolna) - Bolna is an AI platform for building conversational voice agents. It helps businesses automate support and streamline interactions through natural, voice-powered conversations.
- [Botsonic](https://composio.dev/toolkits/botsonic) - Botsonic is a no-code AI chatbot builder for easily creating and deploying chatbots to your website. It empowers businesses to offer conversational experiences without writing code.
- [Botstar](https://composio.dev/toolkits/botstar) - BotStar is a comprehensive chatbot platform for designing, developing, and training chatbots visually on Messenger and websites. It helps businesses automate conversations and customer interactions without coding.
- [Bouncer](https://composio.dev/toolkits/bouncer) - Bouncer is an email validation platform that verifies the authenticity of email addresses in real-time and batch. It helps boost deliverability and reduce bounce rates for your communications.
- [Brex](https://composio.dev/toolkits/brex) - Brex provides corporate credit cards and spend management tailored for startups and tech businesses. It helps optimize company cash flow, streamline accounting, and accelerate business growth.
- [Callerapi](https://composio.dev/toolkits/callerapi) - CallerAPI is a white-label caller identification platform for branded caller ID and fraud prevention. It helps businesses boost customer trust while stopping spam, fraud, and robocalls.
- [Callingly](https://composio.dev/toolkits/callingly) - Callingly is a lead response management platform that automates immediate call and text follow-ups with new leads. It helps sales teams boost response speed and close more deals by connecting seamlessly with CRMs and lead sources.
- [Callpage](https://composio.dev/toolkits/callpage) - Callpage is a lead capture platform that lets businesses instantly connect with website visitors via callback. It boosts lead generation and increases your sales conversion rates.
- [Chaser](https://composio.dev/toolkits/chaser) - Chaser is accounts receivable automation software that sends invoice reminders and helps businesses get paid faster. It streamlines the collections process to save time and improve cash flow.
- [Clearout](https://composio.dev/toolkits/clearout) - Clearout is an AI-powered service for verifying, finding, and enriching email addresses. It boosts deliverability and helps you discover high-quality leads effortlessly.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Persona MCP?

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

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

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

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
