# How to integrate Persona MCP with Vercel AI SDK v6

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

## Introduction

This guide walks you through connecting Persona to Vercel AI SDK v6 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 Vercel AI 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

- [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)
- [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:
- How to set up and configure a Vercel AI SDK agent with Persona integration
- Using Composio's Tool Router to dynamically load and access Persona tools
- Creating an MCP client connection using HTTP transport
- Building an interactive CLI chat interface with conversation history management
- Handling tool calls and results within the Vercel AI SDK framework

## What is Vercel AI SDK?

The Vercel AI SDK is a TypeScript library for building AI-powered applications. It provides tools for creating agents that can use external services and maintain conversation state.
Key features include:
- streamText: Core function for streaming responses with real-time tool support
- MCP Client: Built-in support for Model Context Protocol via @ai-sdk/mcp
- Step Counting: Control multi-step tool execution with stopWhen: stepCountIs()
- OpenAI Provider: Native integration with OpenAI models

## 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:
- Node.js and npm installed
- A Composio account with API key
- An OpenAI API key

### 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).
- Navigate to your API settings and generate a new API key.
- Store this key securely as you'll need it for authentication.

### 2. Install required dependencies

First, install the necessary packages for your project.
What you're installing:
- @ai-sdk/openai: Vercel AI SDK's OpenAI provider
- @ai-sdk/mcp: MCP client for Vercel AI SDK
- @composio/core: Composio SDK for tool integration
- ai: Core Vercel AI SDK
- dotenv: Environment variable management
```bash
npm install @ai-sdk/openai @ai-sdk/mcp @composio/core ai dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's needed:
- OPENAI_API_KEY: Your OpenAI API key for GPT model access
- COMPOSIO_API_KEY: Your Composio API key for tool access
- COMPOSIO_USER_ID: A unique identifier for the user session
```bash
OPENAI_API_KEY=your_openai_api_key_here
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
```

### 4. Import required modules and validate environment

What's happening:
- We're importing all necessary libraries including Vercel AI SDK's OpenAI provider and Composio
- The dotenv/config import automatically loads environment variables
- The MCP client import enables connection to Composio's tool server
```typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});
```

### 5. Create Tool Router session and initialize MCP client

What's happening:
- We're creating a Tool Router session that gives your agent access to Persona tools
- The create method takes the user ID and specifies which toolkits should be available
- The returned mcp object contains the URL and authentication headers needed to connect to the MCP server
- This session provides access to all Persona-related tools through the MCP protocol
```typescript
async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["persona"],
  });

  const mcpUrl = session.mcp.url;
```

### 6. Connect to MCP server and retrieve tools

What's happening:
- We're creating an MCP client that connects to our Composio Tool Router session via HTTP
- The mcp.url provides the endpoint, and mcp.headers contains authentication credentials
- The type: "http" is important - Composio requires HTTP transport
- tools() retrieves all available Persona tools that the agent can use
```typescript
const mcpClient = await createMCPClient({
  transport: {
    type: "http",
    url: mcpUrl,
    headers: session.mcp.headers, // Authentication headers for the Composio MCP server
  },
});

const tools = await mcpClient.tools();
```

### 7. Initialize conversation and CLI interface

What's happening:
- We initialize an empty messages array to maintain conversation history
- A readline interface is created to accept user input from the command line
- Instructions are displayed to guide the user on how to interact with the agent
```typescript
let messages: ModelMessage[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log(
  "Ask any questions related to persona, like summarize my last 5 emails, send an email, etc... :)))\n",
);

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();
```

### 8. Handle user input and stream responses with real-time tool feedback

What's happening:
- We use streamText instead of generateText to stream responses in real-time
- toolChoice: "auto" allows the model to decide when to use Persona tools
- stopWhen: stepCountIs(10) allows up to 10 steps for complex multi-tool operations
- onStepFinish callback displays which tools are being used in real-time
- We iterate through the text stream to create a typewriter effect as the agent responds
- The complete response is added to conversation history to maintain context
- Errors are caught and displayed with helpful retry suggestions
```typescript
rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

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

  messages.push({ role: "user", content: trimmedInput });
  console.log("\nAgent is thinking...\n");

  try {
    const stream = streamText({
      model: openai("gpt-5"),
      messages,
      tools,
      toolChoice: "auto",
      stopWhen: stepCountIs(10),
      onStepFinish: (step) => {
        for (const toolCall of step.toolCalls) {
          console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

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

## Complete Code

```typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});

async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["persona"],
  });

  const mcpUrl = session.mcp.url;

  const mcpClient = await createMCPClient({
    transport: {
      type: "http",
      url: mcpUrl,
      headers: session.mcp.headers, // Authentication headers for the Composio MCP server
    },
  });

  const tools = await mcpClient.tools();

  let messages: ModelMessage[] = [];

  console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
  console.log(
    "Ask any questions related to persona, like summarize my last 5 emails, send an email, etc... :)))\n",
  );

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (userInput: string) => {
    const trimmedInput = userInput.trim();

    if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
      console.log("\nGoodbye!");
      rl.close();
      process.exit(0);
    }

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

    messages.push({ role: "user", content: trimmedInput });
    console.log("\nAgent is thinking...\n");

    try {
      const stream = streamText({
        model: openai("gpt-5"),
        messages,
        tools,
        toolChoice: "auto",
        stopWhen: stepCountIs(10),
        onStepFinish: (step) => {
          for (const toolCall of step.toolCalls) {
            console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

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

## Conclusion

You've successfully built a Persona agent using the Vercel AI SDK with streaming capabilities! This implementation provides a powerful foundation for building AI applications with natural language interfaces and real-time feedback.
Key features of this implementation:
- Real-time streaming responses for a better user experience with typewriter effect
- Live tool execution feedback showing which tools are being used as the agent works
- Dynamic tool loading through Composio's Tool Router with secure authentication
- Multi-step tool execution with configurable step limits (up to 10 steps)
- Comprehensive error handling for robust agent execution
- Conversation history maintenance for context-aware responses
You can extend this further by adding custom error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

## How to build 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)
- [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 Vercel AI SDK v6?

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