# How to integrate Twitter MCP with LlamaIndex

```json
{
  "title": "How to integrate Twitter MCP with LlamaIndex",
  "toolkit": "Twitter",
  "toolkit_slug": "twitter",
  "framework": "LlamaIndex",
  "framework_slug": "llama-index",
  "url": "https://composio.dev/toolkits/twitter/framework/llama-index",
  "markdown_url": "https://composio.dev/toolkits/twitter/framework/llama-index.md",
  "updated_at": "2026-10-05T11:08:33.788Z"
}
```

## Introduction

This guide walks you through connecting Twitter to LlamaIndex using the Composio tool router. By the end, you'll have a working Twitter agent that can post a tweet with latest blog link, add user to your conference list, retrieve your most recent bookmarked tweets through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Twitter account through Composio's Twitter MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Twitter with

- [Claude Code](https://composio.dev/toolkits/twitter/framework/claude-code)
- [Cursor](https://composio.dev/toolkits/twitter/framework/cursor)
- [ChatGPT](https://composio.dev/toolkits/twitter/framework/chatgpt)
- [Claude Cowork](https://composio.dev/toolkits/twitter/framework/claude-cowork)
- [Antigravity](https://composio.dev/toolkits/twitter/framework/antigravity)
- [OpenAI Agents SDK](https://composio.dev/toolkits/twitter/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/twitter/framework/claude-agents-sdk)
- [Grok Bot](https://composio.dev/toolkits/twitter/framework/grok-bot)
- [Muse](https://composio.dev/toolkits/twitter/framework/muse)
- [Codex](https://composio.dev/toolkits/twitter/framework/codex)
- [Kimi Code](https://composio.dev/toolkits/twitter/framework/kimi)
- [Grok Build](https://composio.dev/toolkits/twitter/framework/grok-build)
- [VS Code](https://composio.dev/toolkits/twitter/framework/vscode)
- [OpenCode](https://composio.dev/toolkits/twitter/framework/opencode)
- [OpenClaw](https://composio.dev/toolkits/twitter/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/twitter/framework/hermes-agent)
- [Atomic Agent](https://composio.dev/toolkits/twitter/framework/atomic-agent)
- [CLI](https://composio.dev/toolkits/twitter/framework/cli)
- [Google ADK](https://composio.dev/toolkits/twitter/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/twitter/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/twitter/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/twitter/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/twitter/framework/crew-ai)
- [Pydantic AI](https://composio.dev/toolkits/twitter/framework/pydantic-ai)
- [AutoGen](https://composio.dev/toolkits/twitter/framework/autogen)

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

The Twitter MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Twitter account. It provides structured and secure access to your posts, profile, users, lists, media, and analytics, so your agent can publish posts, search recent conversations, manage follows and lists, upload images, and review post performance on your behalf.
- Post publishing and cleanup: Have your agent create new posts, publish posts with uploaded images, or delete posts you no longer want.
- Recent post search: Direct your agent to search posts from the last seven days by keyword, topic, or username for timely research and monitoring.
- Audience and profile management: Let the agent look up users, view your authenticated profile, follow or unfollow accounts, and retrieve your blocked users.
- List organization: Instruct your agent to create lists for organizing accounts or delete lists you no longer need.
- Post performance analysis: Have your agent retrieve analytics for selected posts over a defined time range to assess their performance.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `TWITTER_ADD_A_LIST_MEMBER` | Add a list member | Adds a user to a specified Twitter List; the list must be owned by the authenticated user. |
| `TWITTER_ADD_POST_TO_BOOKMARKS` | Add post to bookmarks | Adds a specified, existing, and accessible Tweet to a user's bookmarks, with success indicated by the 'bookmarked' field in the response. |
| `TWITTER_APPEND_MEDIA_UPLOAD` | Append Media Upload | Append data chunk to an ongoing media upload session on X/Twitter. Use this action during chunked media uploads to append each segment of media data in sequence. |
| `TWITTER_BOOKMARKS_BY_USER` | Get bookmarks by user | Retrieves Tweets bookmarked by the authenticated user, where the provided User ID must match the authenticated user's ID. |
| `TWITTER_CREATE_ACTIVITY_SUBSCRIPTION` | Create activity subscription | Tool to create a subscription for an X activity event. Use when you need to monitor specific user activities like profile updates, follows, or spaces events. |
| `TWITTER_CREATE_COMPLIANCE_JOB` | Create compliance job | Creates a new compliance job to check the status of Tweet or user IDs; upload IDs as a plain text file (one ID per line) to the `upload_url` received in the response. |
| `TWITTER_CREATE_A_NEW_DM_CONVERSATION` | Create group DM conversation | Creates a new group Direct Message (DM) conversation on Twitter. REQUIRED PARAMETERS: - conversation_type: Must be 'Group' - participant_ids: List of Twitter user IDs to include in the conversation - message: JSON object with the initial message. Must contain 'text' field. To include media attachments, use message.attachments array with media_id (NOT media_url): {"text": "...", "attachments": [{"media_id": "1234567890"}]} Note: Media must be uploaded first using the upload_media action to obtain a media_id. |
| `TWITTER_CREATE_LIST` | Create a list | Creates a new, empty List on X (formerly Twitter), for which the provided name must be unique for the authenticated user; accounts are added separately. |
| `TWITTER_CREATION_OF_A_POST` | Create a post | Creates a Tweet on Twitter; `text` is required unless `card_uri`, `media_media_ids`, `poll_options`, or `quote_tweet_id` is provided. Example - Creating a tweet with media and location: { "text": "Check out our latest product update! 🚀", "media_media_ids": ["1455952740635586573"], "geo_place_id": "df51dec6f4ee2b2c" } Example - Quote tweet with commentary: { "text": "This is a game-changer for the industry! Here's why... 🧵", "quote_tweet_id": "1453828617121234945" } Example - Reply to a tweet: { "text": "Great point! Here's my take on this...", "reply_in_reply_to_tweet_id": "1453828617121234945" } |
| `TWITTER_DELETE_DM` | Delete direct message | Permanently deletes a specific Twitter Direct Message (DM) event using its `event_id` if the authenticated user sent it; this action is irreversible and does not delete entire conversations. |
| `TWITTER_DELETE_LIST` | Delete list | Permanently deletes a specified Twitter List using its ID, which must be owned by the authenticated user; this action is irreversible and the list must already exist. |
| `TWITTER_FOLLOWERS_BY_USER_ID` | Get followers by user id | Retrieves a list of users who follow a specified public Twitter user ID. |
| `TWITTER_FOLLOWING_BY_USER_ID` | Get following by user ID | Retrieves users followed by a specific Twitter user, allowing pagination and customization of returned user and tweet data fields via expansions. |
| `TWITTER_FOLLOW_LIST` | Follow a list | Allows the authenticated user (`id`) to follow a specific Twitter List (`list_id`) they are permitted to access, subscribing them to the list's timeline; this does not automatically follow individual list members. |
| `TWITTER_FOLLOW_USER` | Follow a user | Allows an authenticated user (path `id`) to follow another user (`target_user_id`), which results in a pending request if the target user's tweets are protected. |
| `TWITTER_FULL_ARCHIVE_SEARCH` | Search full archive of tweets | Searches the full archive of public Tweets from March 2006 onwards; use 'start_time' and 'end_time' together for a defined time window. |
| `TWITTER_GET_BLOCKED_USERS` | Get users blocked by user ID | Retrieves the authenticated user's own block list. IMPORTANT: You can only retrieve YOUR OWN block list - the `id` parameter must be the authenticated user's ID. Use the 'Get authenticated user' action first to obtain your user ID. |
| `TWITTER_GET_COMPLIANCE_JOB` | Retrieve compliance job by id | Retrieves status, download/upload URLs, and other details for an existing Twitter compliance job specified by its unique ID. |
| `TWITTER_GET_COMPLIANCE_JOBS` | Retrieve compliance jobs | Returns a list of recent compliance jobs, filtered by type (tweets or users) and optionally by status. |
| `TWITTER_GET_DM_CONVERSATION_EVENTS` | Get DM events for a DM conversation | Fetches Direct Message (DM) events for a one-on-one conversation with a specified participant ID, ordered chronologically newest to oldest; does not support group DMs. |
| `TWITTER_GET_DM_EVENT` | Get DM events by ID | Fetches a specific Direct Message (DM) event by its unique ID, allowing optional expansion of related data like users or tweets; ensure the `event_id` refers to an existing DM event accessible to the authenticated user. |
| `TWITTER_GET_LIST` | Lookup list by ID | Returns metadata for a specific Twitter List, identified by its ID; does not return list members but can expand the owner's User object via the `expansions` parameter. |
| `TWITTER_GET_LIST_FOLLOWERS` | Get list followers | Fetches a list of users who follow a specific Twitter List, identified by its ID; ensure the authenticated user has access if the list is private. |
| `TWITTER_GET_LIST_MEMBERS` | Fetch list members by id | Fetches members of a specific Twitter List, identified by its unique ID. |
| `TWITTER_GET_MEDIA_UPLOAD_STATUS` | Get Media Upload Status | Get the processing status of uploaded media (videos/GIFs) on X/Twitter. Only call this when the FINALIZE command returned a processing_info field. Poll every 3–5 seconds with a 60–120 second maximum timeout to avoid HTTP 429 errors. Response state cycles through 'pending', 'in_progress', 'succeeded', and 'failed'. Only attach media_id to a tweet when state is 'succeeded'. State 'failed' is terminal — requires a completely new upload via TWITTER_UPLOAD_MEDIA or TWITTER_UPLOAD_LARGE_MEDIA. Video/GIF processing takes 30–120 seconds; posting before 'succeeded' results in non-playable media. |
| `TWITTER_GET_MUTED_USERS` | Get muted users | Returns user objects muted by the X user identified by the `id` path parameter. |
| `TWITTER_GET_OPENAPI_SPEC` | Fetch OpenAPI specification | Fetches the OpenAPI specification (JSON) for Twitter's API v2, used to programmatically understand the API's structure for developing client libraries or tools. |
| `TWITTER_GET_POST_ANALYTICS` | Get Post analytics | Tool to retrieve analytics data for specified Posts within a defined time range. Use when you need engagement metrics, impressions, or other analytics for one or more Posts. Requires OAuth 2.0 with tweet.read and users.read scopes. |
| `TWITTER_GET_POST_RETWEETERS_ACTION` | Get post retweeters | Retrieves users who publicly retweeted a specified public Post ID, excluding Quote Tweets and retweets from private accounts. |
| `TWITTER_GET_POST_RETWEETS` | Retrieve retweets of a post | Retrieves Tweets that Retweeted a specified public or authenticated-user-accessible Tweet ID, optionally customizing the response with fields and expansions. |
| `TWITTER_GET_POST_USAGE` | Fetch tweet usage data | Fetches Tweet usage statistics for a Project (e.g., consumption, caps, daily breakdowns for Project & Client Apps) to monitor API limits; data can be retrieved for 1 to 90 days. |
| `TWITTER_GET_RECENT_DM_EVENTS` | Get recent direct message events | Returns recent Direct Message events for the authenticated user, such as new messages or changes in conversation participants. |
| `TWITTER_GET_SPACE_BY_ID` | Look up space by ID | Retrieves details for a Twitter Space by its ID, allowing for customization and expansion of related data, provided the Space ID is valid and accessible. |
| `TWITTER_GET_SPACE_POSTS` | Retrieve posts from a space | Retrieves Tweets that were shared/posted during a Twitter Space broadcast. IMPORTANT: This endpoint returns Tweets that participants explicitly shared during the Space session, NOT audio transcripts, comments, or reactions. Most Spaces have zero associated Tweets, so empty results (result_count=0) are normal and expected. Twitter Spaces are primarily audio conversations - this endpoint only returns text Tweets that were shared alongside the audio. |
| `TWITTER_GET_SPACES_BY_CREATORS` | Get spaces by creator IDs | Retrieves Twitter Spaces created by a list of specified User IDs, with options to customize returned data fields. |
| `TWITTER_GET_SPACES_BY_IDS` | Get space information by IDs | Fetches detailed information for one or more Twitter Spaces (live, scheduled, or ended) by their unique IDs; at least one Space ID must be provided. |
| `TWITTER_GET_SPACE_TICKET_BUYERS` | Fetch space ticket buyers list | Retrieves a list of users who purchased tickets for a specific, valid, and ticketed Twitter Space. |
| `TWITTER_GET_USER_BY_ID` | Look up user by ID | Retrieves detailed public information for a Twitter user by their ID, optionally expanding related data (e.g., pinned tweets) and specifying particular user or tweet fields to return. |
| `TWITTER_GET_USER_FOLLOWED_LISTS` | Get user's followed lists | Returns metadata (not Tweets) for lists a specific Twitter user follows, optionally including expanded owner details. |
| `TWITTER_GET_USER_LIST_MEMBERSHIPS` | Get a user's list memberships | Retrieves all Twitter Lists a specified user is a member of, including public Lists and private Lists the authenticated user is authorized to view. |
| `TWITTER_GET_USER_OWNED_LISTS` | Get a user's owned lists | Call this action to retrieve Lists created (owned) by a specific Twitter user, not Lists they follow or are subscribed to. |
| `TWITTER_GET_USER_PINNED_LISTS` | Get a user's pinned lists | Retrieves the Lists a specific, existing Twitter user has pinned to their profile to highlight them. |
| `TWITTER_GET_USERS_BY_IDS` | Look up users by IDs | Retrieves detailed information for specified X (formerly Twitter) user IDs, optionally customizing returned fields and expanding related entities. |
| `TWITTER_HIDE_REPLIES` | Set reply visibility | Hides or unhides an existing reply Tweet. This action allows the authenticated user to hide or unhide a reply to a conversation they own (started). You can only hide replies to posts you authored. Note: Requires the tweet.moderate.write OAuth scope. |
| `TWITTER_INITIALIZE_MEDIA_UPLOAD` | Initialize Media Upload | Initialize a media upload session for X/Twitter. Use this to start a chunked media upload process, which returns a media_id for subsequent APPEND and FINALIZE commands. Required for uploading large files or when using the chunked upload workflow. |
| `TWITTER_LIST_POST_LIKERS` | List post likers | Retrieves users who have liked the Post (Tweet) identified by the provided ID. |
| `TWITTER_LIST_POSTS_TIMELINE_BY_LIST_ID` | List posts timeline by list ID | Fetches the most recent Tweets posted by members of a specified Twitter List. |
| `TWITTER_MUTE_USER` | Mute user by ID | Mutes a target user on behalf of an authenticated user, preventing the target's Tweets and Retweets from appearing in the authenticated user's home timeline without notifying the target. |
| `TWITTER_PIN_LIST` | Pin a list | Pins a specified List to the authenticated user's profile, provided the List exists, the user has access rights, and the pin limit (typically 5 Lists) is not exceeded. |
| `TWITTER_POST_DELETE_BY_POST_ID` | Delete tweet | Irreversibly deletes a specific Tweet by its ID; the Tweet may persist in third-party caches after deletion. |
| `TWITTER_POST_LOOKUP_BY_POST_ID` | Look up post by id | Fetches comprehensive details for a single Tweet by its unique ID, provided the Tweet exists and is accessible. |
| `TWITTER_POST_LOOKUP_BY_POST_IDS` | Get tweets by IDs | Retrieves detailed information for one or more Posts (Tweets) identified by their unique IDs, allowing selection of specific fields and expansions. |
| `TWITTER_RECENT_SEARCH` | Search recent tweets | Searches Tweets from the last 7 days matching a query (using X's search syntax), ideal for real-time analysis, trend monitoring, or retrieving posts from specific users (e.g., `from:username`) DEFAULT FIELDS: Tweet objects always return 'id' and 'text' by default. User objects always return 'id', 'name', and 'username' by default when expanded. Do not request these default fields in field parameters. IMPORTANT LIMITATION - Impression Counts: The public_metrics.impression_count field returns 0 for search results from other users. Impression data is a non-public metric only available for tweets owned by the authenticated user. To filter by engagement, use retweet_count, like_count, or quote_count instead. Example - Get original tweets from Elon Musk since Sept 20, 2025: { "query": "from:elonmusk -is:retweet -is:reply", "start_time": "2025-09-20T00:00:00Z", "max_results": 50, "tweet_fields": ["created_at","public_metrics","text"], "expansions": ["author_id","attachments.media_keys","referenced_tweets.id"] } |
| `TWITTER_REMOVE_LIST_MEMBER` | Remove a list member | Removes a user from a Twitter List; the response `is_member` field will be `false` if removal was successful or the user was not a member, and the updated list of members is not returned. |
| `TWITTER_REMOVE_POST_FROM_BOOKMARKS` | Remove a bookmarked post | Removes a Tweet, specified by `tweet_id`, from the authenticated user's bookmarks; the Tweet must have been previously bookmarked by the user for the action to have an effect. |
| `TWITTER_RETRIEVE_DM_CONVERSATION_EVENTS` | Retrieve DM conversation events | Retrieves Direct Message (DM) events for a specific conversation ID on Twitter, useful for analyzing messages and participant activities. |
| `TWITTER_RETRIEVE_POSTS_THAT_QUOTE_A_POST` | Retrieve posts that quote a post | Retrieves Tweets that quote a specified Tweet, requiring a valid Tweet ID. |
| `TWITTER_RETURNS_POST_OBJECTS_LIKED_BY_THE_PROVIDED_USER_ID` | Retrieve liked tweets by user ID | Retrieves Tweets liked by a specified Twitter user, provided their liked tweets are public or accessible. |
| `TWITTER_RETWEET_POST` | Retweet post | Retweets a Tweet for the authenticated user. The user ID is automatically fetched from the authenticated session - you only need to provide the tweet_id to retweet. |
| `TWITTER_SEARCH_FULL_ARCHIVE_COUNTS` | Get full archive search counts | Returns a count of Tweets from the full archive that match a specified query, aggregated by day, hour, or minute; `start_time` must be before `end_time` if both are provided, and `since_id`/`until_id` cannot be used with `start_time`/`end_time`. |
| `TWITTER_SEARCH_RECENT_COUNTS` | Fetch recent tweet counts | Retrieves the count of Tweets matching a specified search query within the last 7 days, aggregated by 'minute', 'hour', or 'day'. |
| `TWITTER_SEARCH_SPACES` | Search for spaces | Searches for Twitter Spaces by a textual query, optionally filtering by state (live, scheduled, all) to discover audio conversations. |
| `TWITTER_SEND_A_NEW_MESSAGE_TO_A_USER` | Send a new message to a user | Sends a new Direct Message with text and/or media (media_id for attachments must be pre-uploaded) to a specified Twitter user; this creates a new DM and does not modify existing messages. |
| `TWITTER_SEND_DM_TO_CONVERSATION` | Send a new message to a DM conversation | Sends a message, with optional text and/or media attachments (using pre-uploaded `media_id`s), to a specified Twitter Direct Message conversation. |
| `TWITTER_STREAM_POST_LABELS` | Get tweets label stream | Stream real-time Tweet label events (apply/remove). Requires Enterprise access and App-Only OAuth 2.0 auth. Returns PublicTweetNotice or PublicTweetUnviewable events. 403 errors indicate missing Enterprise access or wrong auth type. |
| `TWITTER_UNFOLLOW_LIST` | Unfollow a list | Enables a user (via `id`) to unfollow a specific Twitter List (via `list_id`), which removes its tweets from their timeline and stops related notifications; the action reports `following: false` on success, even if the user was not initially following the list. |
| `TWITTER_UNFOLLOW_USER` | Unfollow user | Allows the authenticated user to unfollow an existing Twitter user (`target_user_id`), which removes the follow relationship. The source user ID is automatically determined from the authenticated session. |
| `TWITTER_UNLIKE_POST` | Unlike post | Allows an authenticated user (`id`) to remove their like from a specific post (`tweet_id`); the action is idempotent and completes successfully even if the post was not liked. |
| `TWITTER_UNMUTE_USER` | Unmute a user by user ID | Unmutes a target user for the authenticated user, allowing them to see Tweets and notifications from the target user again. The source_user_id is automatically populated from the authenticated user's credentials. |
| `TWITTER_UNPIN_LIST` | Unpin a list | Unpins a List (specified by list_id) from the authenticated user's profile. The user ID is automatically retrieved if not provided. |
| `TWITTER_UNRETWEET_POST` | Unretweet post | Removes a user's retweet of a specified Post, if the user had previously retweeted it. |
| `TWITTER_UPDATE_LIST` | Update list attributes | Updates an existing Twitter List's name, description, or privacy status, requiring the List ID and at least one mutable property. |
| `TWITTER_UPLOAD_MEDIA` | Upload Media | Upload media (images only) to X/Twitter using the v2 API. Supports tweet_image, dm_image, and subtitles media categories only. One file per call; the returned media_id expires (see expires_after_secs in response), so upload immediately before creating the tweet. For GIFs, videos, or any file larger than ~5 MB, use TWITTER_UPLOAD_LARGE_MEDIA instead. |
| `TWITTER_USER_HOME_TIMELINE_BY_USER_ID` | Get user reverse chronological timeline | Retrieves the home timeline (reverse chronological feed) for the authenticated Twitter user. Returns tweets from accounts the user follows as well as the user's own tweets, in reverse chronological order. Useful for displaying the personalized feed without algorithmic sorting. CRITICAL: The 'id' parameter MUST be the authenticated user's own numeric Twitter user ID - use TWITTER_USER_LOOKUP_ME to get your ID first. This endpoint cannot fetch another user's home timeline, and passing any ID that doesn't match the authenticating user (including phone numbers or other user IDs) will result in an error. DEFAULT FIELDS: Tweet objects always return 'id' and 'text' by default. User objects always return 'id', 'name', and 'username' by default when expanded. Do not request these default fields in field parameters. |
| `TWITTER_USER_LIKE_POST` | Like a tweet | Allows the authenticated user to like a specific, accessible Tweet, provided neither user has blocked the other and the authenticated user is not restricted from liking. The authenticated user's ID is automatically determined from the OAuth token - you only need to provide the tweet_id. |
| `TWITTER_USER_LOOKUP_BY_USERNAME` | Look up user by username | Fetches public profile information for a valid and existing Twitter user by their username, optionally expanding related data like pinned Tweets; results may be limited for protected profiles not followed by the authenticated user. |
| `TWITTER_USER_LOOKUP_BY_USERNAMES` | Look up users by username | Retrieves detailed information for 1 to 100 Twitter users by their usernames (each 1-15 alphanumeric characters/underscores), allowing customizable user/tweet fields and expansion of related data like pinned tweets. |
| `TWITTER_USER_LOOKUP_ME` | Get authenticated user | Returns profile information for the currently authenticated X user, customizable via request fields. |

## Supported Triggers

None listed.

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

The Twitter MCP server is an implementation of the Model Context Protocol that connects your AI agent to Twitter. It provides structured and secure access so your agent can perform Twitter 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 Twitter account and project
- Basic familiarity with async Python/Typescript

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

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 Twitter 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, twitter)
- 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 Twitter 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=["twitter"],
    )

    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 Twitter actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Twitter 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: ["twitter"],
    },
  );

  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 Twitter 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 Twitter
```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 Twitter, 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=["twitter"],
    )

    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 Twitter actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Twitter 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: ["twitter"],
    },
  );

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

- [Claude Code](https://composio.dev/toolkits/twitter/framework/claude-code)
- [Cursor](https://composio.dev/toolkits/twitter/framework/cursor)
- [ChatGPT](https://composio.dev/toolkits/twitter/framework/chatgpt)
- [Claude Cowork](https://composio.dev/toolkits/twitter/framework/claude-cowork)
- [Antigravity](https://composio.dev/toolkits/twitter/framework/antigravity)
- [OpenAI Agents SDK](https://composio.dev/toolkits/twitter/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/twitter/framework/claude-agents-sdk)
- [Grok Bot](https://composio.dev/toolkits/twitter/framework/grok-bot)
- [Muse](https://composio.dev/toolkits/twitter/framework/muse)
- [Codex](https://composio.dev/toolkits/twitter/framework/codex)
- [Kimi Code](https://composio.dev/toolkits/twitter/framework/kimi)
- [Grok Build](https://composio.dev/toolkits/twitter/framework/grok-build)
- [VS Code](https://composio.dev/toolkits/twitter/framework/vscode)
- [OpenCode](https://composio.dev/toolkits/twitter/framework/opencode)
- [OpenClaw](https://composio.dev/toolkits/twitter/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/twitter/framework/hermes-agent)
- [Atomic Agent](https://composio.dev/toolkits/twitter/framework/atomic-agent)
- [CLI](https://composio.dev/toolkits/twitter/framework/cli)
- [Google ADK](https://composio.dev/toolkits/twitter/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/twitter/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/twitter/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/twitter/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/twitter/framework/crew-ai)
- [Pydantic AI](https://composio.dev/toolkits/twitter/framework/pydantic-ai)
- [AutoGen](https://composio.dev/toolkits/twitter/framework/autogen)

## Related Toolkits

- [Instagram](https://composio.dev/toolkits/instagram) - Instagram is a social platform for sharing photos, videos, and stories with your audience. It helps brands and creators engage, grow, and analyze their online presence.
- [Ayrshare](https://composio.dev/toolkits/ayrshare) - Ayrshare is a Social Media API for managing, automating, and analyzing posts across multiple platforms. It helps you streamline social media workflows and centralize analytics.
- [DEV Community](https://composio.dev/toolkits/devto) - DEV Community (dev.to) is a social publishing platform for software developers. Use it to share technical articles, grow a developer audience, and join community discussions.
- [Dotsimple](https://composio.dev/toolkits/dotsimple) - Dotsimple is a social media management platform for planning, creating, and publishing content. It helps teams boost their reach with AI-powered content generation and actionable analytics.
- [Just One API](https://composio.dev/toolkits/just_one_api) - Just One API is a unified platform providing public social, creator, entertainment, and ecommerce data. Use it to query standardized, metered datasets across hundreds of endpoints for research and product insights.
- [Pinterest](https://composio.dev/toolkits/pinterest) - Pinterest is a visual discovery platform for recipes, home ideas, style inspiration, travel plans, and more. It helps people save, organize, and revisit ideas through Pins and Boards.
- [Strava](https://composio.dev/toolkits/strava) - Strava is a social fitness network and app for cyclists and runners. It's perfect for tracking workouts, sharing progress, and joining active communities.
- [TikHub](https://composio.dev/toolkits/tik_hub) - TikHub is a social metadata API that exposes supported TikTok and social metadata routes. It provides consistent, API-key-based access to public metadata without cookies or device signatures.
- [Tiktok](https://composio.dev/toolkits/tiktok) - Tiktok is a short-form video platform for creating, sharing, and discovering viral content. It helps creators and brands reach massive audiences with creative tools and global social features.
- [Twitch](https://composio.dev/toolkits/twitch) - Twitch is a live streaming platform for gamers, creators, and communities. It enables real-time interaction, monetization, and community building.
- [TwitterShots](https://composio.dev/toolkits/twittershots) - TwitterShots is an API service that renders public X posts as clean screenshots and retrieves tweet content. Use it to capture social posts, extract tweet text, and track API usage without building screenshot infrastructure.
- [Upload-Post](https://composio.dev/toolkits/upload_post) - Upload-Post is a social publishing API for posting, scheduling, and managing content across social networks. Use it to run multi-channel content workflows through one clean API instead of separate platform integrations.
- [Gmail](https://composio.dev/toolkits/gmail) - Gmail is Google's email service with powerful spam protection, search, and G Suite integration. It keeps your inbox organized and makes communication fast and reliable.
- [Google Calendar](https://composio.dev/toolkits/googlecalendar) - Google Calendar is a time management service for scheduling meetings, events, and reminders. It streamlines personal and team organization with integrated notifications and sharing options.
- [Google Drive](https://composio.dev/toolkits/googledrive) - Google Drive is a cloud storage platform for uploading, sharing, and collaborating on files. It's perfect for keeping your documents accessible and organized across devices.
- [Outlook](https://composio.dev/toolkits/outlook) - Outlook is Microsoft's email and calendaring platform for unified communications and scheduling. It helps users stay organized with powerful email, contacts, and calendar management.
- [Google Sheets](https://composio.dev/toolkits/googlesheets) - Google Sheets is a cloud-based spreadsheet tool for real-time collaboration and data analysis. It lets teams work together from anywhere, updating information instantly.
- [Supabase](https://composio.dev/toolkits/supabase) - Supabase is an open-source backend platform offering scalable Postgres databases, authentication, storage, and real-time APIs. It lets developers build modern apps without managing infrastructure.
- [Composio](https://composio.dev/toolkits/composio) - Composio is an integration platform that connects AI agents with hundreds of business tools. It streamlines authentication and lets you trigger actions across services—no custom code needed.
- [Notion](https://composio.dev/toolkits/notion) - Notion is a collaborative workspace for notes, docs, wikis, and tasks. It streamlines team knowledge, project tracking, and workflow customization in one place.

## Frequently Asked Questions

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

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

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

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

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