# How to integrate Persona MCP with OpenAI Agents SDK

```json
{
  "title": "How to integrate Persona MCP with OpenAI Agents SDK",
  "toolkit": "Persona",
  "toolkit_slug": "persona",
  "framework": "OpenAI Agents SDK",
  "framework_slug": "open-ai-agents-sdk",
  "url": "https://composio.dev/toolkits/persona/framework/open-ai-agents-sdk",
  "markdown_url": "https://composio.dev/toolkits/persona/framework/open-ai-agents-sdk.md",
  "updated_at": "2026-03-29T06:45:25.385Z"
}
```

## Introduction

This guide walks you through connecting Persona to the OpenAI Agents SDK 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 OpenAI Agents SDK 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

- [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)
- [LlamaIndex](https://composio.dev/toolkits/persona/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/persona/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- Get and set up your OpenAI and Composio API keys
- Install the necessary dependencies
- Initialize Composio and create a Tool Router session for Persona
- Configure an AI agent that can use Persona as a tool
- Run a live chat session where you can ask the agent to perform Persona operations

## What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.
Key features include:
- Hosted MCP Tools: Connect to external services through hosted MCP endpoints
- SQLite Sessions: Persist conversation history across interactions
- Simple API: Clean interface with Agent, Runner, and tool configuration
- Streaming Support: Real-time response streaming for interactive applications

## 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 starting, make sure you have:
- Composio API Key and OpenAI API Key
- Primary know-how of OpenAI Agents SDK
- A live Persona project
- Some knowledge of Python or Typescript

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

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Go to Settings and copy your API key.

### 2. Install dependencies

Install the Composio SDK and the OpenAI Agents SDK.
```python
pip install composio_openai_agents openai-agents python-dotenv
```

```typescript
npm install @composio/openai-agents @openai/agents dotenv
```

### 3. Set up environment variables

Create a .env file and add your OpenAI and Composio API keys.
```bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com
```

### 4. Import dependencies

What's happening:
- You're importing all necessary libraries.
- The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Persona.
```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
```

### 5. Set up the Composio instance

No description provided.
```python
load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())
```

```typescript
dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
```

### 6. Create a Tool Router session

What is happening:
- You give the Tool Router the user id and the toolkits you want available. Here, it is only persona.
- The router checks the user's Persona connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access Persona.
- This approach keeps things lightweight and lets the agent request Persona tools only when needed during the conversation.
```python
# Create a Persona Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["persona"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for Persona
const session = await composio.create(userId as string, {
  toolkits: ['persona'],
});
const mcpUrl = session.mcp.url;
```

### 7. Configure the agent

No description provided.
```python
# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Persona. "
        "Help users perform Persona operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)
```

```typescript
// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Persona. Help users perform Persona operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
```

### 8. Start chat loop and handle conversation

No description provided.
```python
print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

  if (!text) {
    rl.prompt();
    return;
  }

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession

load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())

# Create Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["persona"]
)
mcp_url = session.mcp.url

# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Persona. "
        "Help users perform Persona operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)

print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['persona'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Persona. Help users perform Persona operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

    if (!text) {
      rl.prompt();
      return;
    }

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
```

## Conclusion

This was a starter code for integrating Persona MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Persona.
Key features:
- Hosted MCP tool integration through Composio's Tool Router
- SQLite session persistence for conversation history
- Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## How to build Persona MCP Agent with another framework

- [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)
- [LlamaIndex](https://composio.dev/toolkits/persona/framework/llama-index)
- [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 OpenAI Agents SDK?

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