How to integrate Twitter MCP with LangChain

Framework Integration Gradient
Twitter Logo
LangChain Logo
divider

Introduction

This guide walks you through connecting Twitter to LangChain 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 LangChain 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:
  • Get and set up your OpenAI and Composio API keys
  • Connect your Twitter project to Composio
  • Create a Tool Router MCP session for Twitter
  • Initialize an MCP client and retrieve Twitter tools
  • Build a LangChain agent that can interact with Twitter
  • Set up an interactive chat interface for testing

What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides tools and abstractions for building agents that can reason, use tools, and maintain conversation context.

Key features include:

  • Agent Framework: Build agents that can use tools and make decisions
  • MCP Integration: Connect to external services through Model Context Protocol adapters
  • Memory Management: Maintain conversation history across interactions
  • Multi-Provider Support: Works with OpenAI, Anthropic, and other LLM providers

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 starting this tutorial, make sure you have:
  • Python 3.10 or higher installed on your system
  • A Composio account with an API key
  • An OpenAI API key
  • Basic familiarity with Python and async programming

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard 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.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.

Install dependencies

pip install composio-langchain langchain-mcp-adapters langchain python-dotenv

Install the required packages for LangChain with MCP support.

What's happening:

  • composio-langchain provides Composio integration for LangChain
  • langchain-mcp-adapters enables MCP client connections
  • langchain is the core agent framework
  • python-dotenv loads environment variables

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_composio_user_id_here
OPENAI_API_KEY=your_openai_api_key_here

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your requests to Composio's API
  • COMPOSIO_USER_ID identifies the user for session management
  • OPENAI_API_KEY enables access to OpenAI's language models

Import dependencies

from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent
from dotenv import load_dotenv
from composio import Composio
import asyncio
import os

load_dotenv()
What's happening:
  • We're importing LangChain's MCP adapter and Composio SDK
  • The dotenv import loads environment variables from your .env file
  • This setup prepares the foundation for connecting LangChain with Twitter functionality through MCP

Initialize Composio client

async def main():
    composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))

    if not os.getenv("COMPOSIO_API_KEY"):
        raise ValueError("COMPOSIO_API_KEY is not set")
    if not os.getenv("COMPOSIO_USER_ID"):
        raise ValueError("COMPOSIO_USER_ID is not set")
What's happening:
  • We're loading the COMPOSIO_API_KEY from environment variables and validating it exists
  • Creating a Composio instance that will manage our connection to Twitter tools
  • Validating that COMPOSIO_USER_ID is also set before proceeding

Create a Tool Router session

# Create Tool Router session for Twitter
session = composio.create(
    user_id=os.getenv("COMPOSIO_USER_ID"),
    toolkits=['twitter']
)

url = session.mcp.url
What's happening:
  • We're creating a Tool Router session that gives your agent access to Twitter tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned session.mcp.url is the MCP server URL that your agent will use
  • This approach allows the agent to dynamically load and use Twitter tools as needed

Configure the agent with the MCP URL

client = MultiServerMCPClient({
    "twitter-agent": {
        "transport": "streamable_http",
        "url": session.mcp.url,
        "headers": {
            "x-api-key": os.getenv("COMPOSIO_API_KEY")
        }
    }
})

tools = await client.get_tools()

agent = create_agent("gpt-5", tools)
What's happening:
  • We're creating a MultiServerMCPClient that connects to our Twitter MCP server via HTTP
  • The client is configured with a name and the URL from our Tool Router session
  • get_tools() retrieves all available Twitter tools that the agent can use
  • We're creating a LangChain agent using the GPT-5 model

Set up interactive chat interface

conversation_history = []

print("Chat started! Type 'exit' or 'quit' to end the conversation.\n")
print("Ask any Twitter related question or task to the agent.\n")

while True:
    user_input = input("You: ").strip()

    if user_input.lower() in ['exit', 'quit', 'bye']:
        print("\nGoodbye!")
        break

    if not user_input:
        continue

    conversation_history.append({"role": "user", "content": user_input})
    print("\nAgent is thinking...\n")

    response = await agent.ainvoke({"messages": conversation_history})
    conversation_history = response['messages']
    final_response = response['messages'][-1].content
    print(f"Agent: {final_response}\n")
What's happening:
  • We initialize an empty conversation_history list to maintain context across interactions
  • A while loop continuously accepts user input from the command line
  • When a user types a message, it's added to the conversation history and sent to the agent
  • The agent processes the request using the ainvoke() method with the full conversation history
  • Users can type 'exit', 'quit', or 'bye' to end the chat session gracefully

Run the application

if __name__ == "__main__":
    asyncio.run(main())
What's happening:
  • We call the main() function using asyncio.run() to start the application

Complete Code

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

from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent
from dotenv import load_dotenv
from composio import Composio
import asyncio
import os

load_dotenv()

async def main():
    composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))
    
    if not os.getenv("COMPOSIO_API_KEY"):
        raise ValueError("COMPOSIO_API_KEY is not set")
    if not os.getenv("COMPOSIO_USER_ID"):
        raise ValueError("COMPOSIO_USER_ID is not set")
    
    session = composio.create(
        user_id=os.getenv("COMPOSIO_USER_ID"),
        toolkits=['twitter']
    )

    url = session.mcp.url
    
    client = MultiServerMCPClient({
        "twitter-agent": {
            "transport": "streamable_http",
            "url": url,
            "headers": {
                "x-api-key": os.getenv("COMPOSIO_API_KEY")
            }
        }
    })
    
    tools = await client.get_tools()
  
    agent = create_agent("gpt-5", tools)
    
    conversation_history = []
    
    print("Chat started! Type 'exit' or 'quit' to end the conversation.\n")
    print("Ask any Twitter related question or task to the agent.\n")
    
    while True:
        user_input = input("You: ").strip()
        
        if user_input.lower() in ['exit', 'quit', 'bye']:
            print("\nGoodbye!")
            break
        
        if not user_input:
            continue
        
        conversation_history.append({"role": "user", "content": user_input})
        print("\nAgent is thinking...\n")
        
        response = await agent.ainvoke({"messages": conversation_history})
        conversation_history = response['messages']
        final_response = response['messages'][-1].content
        print(f"Agent: {final_response}\n")

if __name__ == "__main__":
    asyncio.run(main())

Conclusion

You've successfully built a LangChain agent that can interact with Twitter through Composio's Tool Router.

Key features of this implementation:

  • Dynamic tool loading through Composio's Tool Router
  • Conversation history maintenance for context-aware responses
  • Async Python provides clean, efficient execution of agent workflows
You can extend this further by adding error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

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 LangChain?

Yes, you can. LangChain 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.