How to integrate Twitter MCP with LlamaIndex

Framework Integration Gradient
Twitter Logo
LlamaIndex Logo
divider

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 my conference list, retrieve my most recent bookmarked tweets, start a group dm with collaborators 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.

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 (now X) account. It provides structured and secure access to your social media presence, so your agent can perform actions like posting tweets, managing lists, handling bookmarks, and starting group DMs on your behalf.

  • Automated tweet posting and management: Let your agent compose and publish tweets, including text, media, polls, or quote tweets, directly to your timeline.
  • List creation and member management: Have your agent create new Twitter lists, add or remove users, fetch list members, or delete lists as needed.
  • Bookmark handling and retrieval: Easily get your bookmarked tweets or add posts to your bookmarks for quick access later, all through your agent.
  • Direct and group message automation: Enable your agent to create group DMs, send initial messages, or delete specific direct messages securely and efficiently.
  • Compliance and content moderation: Use your agent to set up compliance jobs, check the status of tweets or user IDs, and help manage your account’s integrity.

Supported Tools & Triggers

Tools
Add a list memberAdds a user to a specified twitter list; the list must be owned by the authenticated user.
Add post to bookmarksAdds a specified, existing, and accessible tweet to a user's bookmarks, with success indicated by the 'bookmarked' field in the response.
Get bookmarks by userRetrieves tweets bookmarked by the authenticated user, where the provided user id must match the authenticated user's id.
Create group DM conversationCreates a new group direct message (dm) conversation on twitter with specified participant ids and an initial message, which can include text and media attachments.
Create compliance jobCreates 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.
Create a listCreates a new, empty list on x (formerly twitter), for which the provided name must be unique for the authenticated user; accounts are added separately.
Create a postCreates a tweet on twitter; `text` is required unless `card uri`, `media media ids`, `poll options`, or `quote tweet id` is provided.
Delete direct messagePermanently 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.
Delete listPermanently 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.
Fetch list members by idFetches members of a specific twitter list, identified by its unique id.
Fetch space ticket buyers listRetrieves a list of users who purchased tickets for a specific, valid, and ticketed twitter space.
Follow a listAllows 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.
Get followers by user idRetrieves a list of users who follow a specified public twitter user id.
Get following by user IDRetrieves users followed by a specific twitter user, allowing pagination and customization of returned user and tweet data fields via expansions.
Follow a userAllows 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.
Search full archive of tweetsSearches the full archive of public tweets from march 2006 onwards; use 'start time' and 'end time' together for a defined time window.
Get full archive search countsReturns 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`.
Get a user's list membershipsRetrieves all twitter lists a specified user is a member of, including public lists and private lists the authenticated user is authorized to view.
Get a user's owned listsCall this action to retrieve lists created (owned) by a specific twitter user, not lists they follow or are subscribed to.
Get a user's pinned listsRetrieves the lists a specific, existing twitter user has pinned to their profile to highlight them.
Get users blocked by user IDRetrieves user objects for accounts blocked by the specified user id; this is a read-only view of a user's block list.
Get DM events by IDFetches 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.
Get DM events for a DM conversationFetches 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.
Get list followersFetches 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.
Get muted usersReturns user objects muted by the x user identified by the `id` path parameter.
Get post retweetersRetrieves users who publicly retweeted a specified public post id, excluding quote tweets and retweets from private accounts.
Get recent direct message eventsReturns recent direct message events for the authenticated user, such as new messages or changes in conversation participants.
Get user's followed listsReturns metadata (not tweets) for lists a specific twitter user follows, optionally including expanded owner details.
Set reply visibilityHides or unhides an existing reply tweet.
Lookup list by IDReturns 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.
List post likersRetrieves users who have liked the post (tweet) identified by the provided id.
List posts timeline by list IDFetches the most recent tweets posted by members of a specified twitter list.
Mute user by IDMutes 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.
Pin a listPins 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.
Delete tweetIrreversibly deletes a specific tweet by its id; the tweet may persist in third-party caches after deletion.
Look up post by idFetches comprehensive details for a single tweet by its unique id, provided the tweet exists and is accessible.
Get tweets by IDsRetrieves detailed information for one or more posts (tweets) identified by their unique ids, allowing selection of specific fields and expansions.
Get tweets label streamEstablishes a persistent stream of real-time events for when tweet labels are applied or removed, offering insights into content categorization.
Fetch tweet usage dataFetches tweet usage statistics for a project (e.
Search recent tweetsSearches 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.
Fetch recent tweet countsRetrieves the count of tweets matching a specified search query within the last 7 days, aggregated by 'minute', 'hour', or 'day'.
Remove a bookmarked postRemoves 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.
Remove a list memberRemoves 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.
Retrieve compliance job by idRetrieves status, download/upload urls, and other details for an existing twitter compliance job specified by its unique id.
Retrieve compliance jobsReturns a list of recent compliance jobs, filtered by type (tweets or users) and optionally by status.
Retrieve DM conversation eventsRetrieves direct message (dm) events for a specific conversation id on twitter, useful for analyzing messages and participant activities.
Retrieve posts from a spaceRetrieves tweets from a specified twitter space id; the space must be accessible and results are batched (not streamed).
Retrieve posts that quote a postRetrieves tweets that quote a specified tweet, requiring a valid tweet id.
Retrieve retweets of a postRetrieves tweets that retweeted a specified public or authenticated-user-accessible tweet id, optionally customizing the response with fields and expansions.
Retrieve liked tweets by user IDRetrieves tweets liked by a specified twitter user, provided their liked tweets are public or accessible.
Fetch OpenAPI specificationFetches the openapi specification (json) for twitter's api v2, used to programmatically understand the api's structure for developing client libraries or tools.
Retweet postRetweets a tweet (`tweet id`) for a given user (`id`), provided the tweet is public (or user follows if protected), not already retweeted by the user, and its author has not blocked the user.
Search for spacesSearches for twitter spaces by a textual query, optionally filtering by state (live, scheduled, all) to discover audio conversations.
Send a new message to a DM conversationSends a message, with optional text and/or media attachments (using pre-uploaded `media id`s), to a specified twitter direct message conversation.
Send a new message to a userSends 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.
Look up space by IDRetrieves details for a twitter space by its id, allowing for customization and expansion of related data, provided the space id is valid and accessible.
Get spaces by creator IDsRetrieves twitter spaces created by a list of specified user ids, with options to customize returned data fields.
Get space information by IDsFetches detailed information for one or more twitter spaces (live, scheduled, or ended) by their unique ids; at least one space id must be provided.
Unfollow a listEnables 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.
Unfollow userAllows the authenticated `source user id` to unfollow an existing twitter user (`target user id`), which removes the follow relationship.
Unlike postAllows 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.
Unmute a user by user IDUnmutes a `target user id` for the `source user id` (authenticated user), allowing the source user to see tweets and notifications from the target user again.
Unpin a listUnpins a list (specified by list id) from a user's profile (specified by id), provided the list is currently pinned by that user.
Unretweet postRemoves a user's retweet of a specified post, if the user had previously retweeted it.
Update list attributesUpdates an existing twitter list's name, description, or privacy status, requiring the list id and at least one mutable property.
Get user reverse chronological timelineRetrieves the home timeline/feed for a specified twitter user, showing tweets from accounts they follow - not their own posts - in reverse chronological order; useful for displaying their personalized feed without algorithmic sorting.
Like a tweetAllows the authenticated user (`id`) to like a specific, accessible tweet (`tweet id`), provided neither user has blocked the other and the authenticated user is not restricted from liking.
Look up user by IDRetrieves detailed public information for a twitter user by their id, optionally expanding related data (e.
Look up users by IDsRetrieves detailed information for specified x (formerly twitter) user ids, optionally customizing returned fields and expanding related entities.
Look up user by usernameFetches 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.
Look up users by usernameRetrieves 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.
Get authenticated userReturns profile information for the currently authenticated x user, customizable via request fields.

What is the Composio tool router, and how does it fit here?

What is Tool Router?

Composio's Tool Router helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Tool Router

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Tool Router works

The Tool Router follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Prerequisites

Before you begin, make sure you have:
  • Python 3.8/Node 16 or higher installed
  • A Composio account with the API key
  • An OpenAI API key
  • A Twitter account and project
  • Basic familiarity with async Python/Typescript

Getting API Keys for OpenAI, Composio, and Twitter

OpenAI API key (OPENAI_API_KEY)
  • Go to the OpenAI dashboard
  • Create an API key if you don't have one
  • Assign it to OPENAI_API_KEY in .env
Composio API key and user ID
  • Log into the Composio dashboard
  • Copy your API key from Settings
    • Use this as COMPOSIO_API_KEY
  • Pick a stable user identifier (email or ID)
    • Use this as COMPOSIO_USER_ID

Installing dependencies

pip install composio-llamaindex llama-index llama-index-llms-openai llama-index-tools-mcp python-dotenv

Create a new Python project and install the necessary dependencies:

  • composio-llamaindex: Composio's LlamaIndex integration
  • llama-index: Core LlamaIndex framework
  • llama-index-llms-openai: OpenAI LLM integration
  • llama-index-tools-mcp: MCP client for LlamaIndex
  • python-dotenv: Environment variable management

Set environment variables

bash
OPENAI_API_KEY=your-openai-api-key
COMPOSIO_API_KEY=your-composio-api-key
COMPOSIO_USER_ID=your-user-id

Create a .env file in your project root:

These credentials will be used to:

  • Authenticate with OpenAI's GPT-5 model
  • Connect to Composio's Tool Router
  • Identify your Composio user session for Twitter access

Import modules

import asyncio
import os
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()

Create a new file called twitter_llamaindex_agent.py and import the required modules:

Key imports:

  • asyncio: For async/await support
  • Composio: Main client for Composio services
  • LlamaIndexProvider: Adapts Composio tools for LlamaIndex
  • ReActAgent: LlamaIndex's reasoning and action agent
  • BasicMCPClient: Connects to MCP endpoints
  • McpToolSpec: Converts MCP tools to LlamaIndex format

Load environment variables and initialize Composio

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set in the environment")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set in the environment")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set in the environment")

What's happening:

This ensures missing credentials cause early, clear errors before the agent attempts to initialise.

Create a Tool Router session and build the agent function

async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["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)

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.

Create an interactive chat loop

async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")

What's happening here:

  • We're creating a direct terminal interface to chat with your Twitter database
  • The LLM's responses are streamed to the CLI for faster interaction.
  • The agent uses context to maintain conversation history
  • You can type 'quit' or 'exit' to stop the chat loop gracefully
  • Agent responses and any errors are displayed in a clear, readable format

Define the main entry point

async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")

What's happening here:

  • We're orchestrating the entire application flow
  • The agent gets built with proper error handling
  • Then we kick off the interactive chat loop so you can start talking to Twitter

Run the agent

npx ts-node llamaindex-agent.ts

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

Complete Code

Here's the complete code to get you started with Twitter and LlamaIndex:

import asyncio
import os
import signal
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set")

async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["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!")

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

FAQ

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.

Used by agents from

Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai

Never worry about agent reliability

We handle tool reliability, observability, and security so you never have to second-guess an agent action.