How to integrate Twitter MCP with Autogen

Framework Integration Gradient
Twitter Logo
AutoGen Logo
divider

Introduction

This guide walks you through connecting Twitter to AutoGen 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 AutoGen 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
  • Install the required dependencies for Autogen and Composio
  • Initialize Composio and create a Tool Router session for Twitter
  • Wire that MCP URL into Autogen using McpWorkbench and StreamableHttpServerParams
  • Configure an Autogen AssistantAgent that can call Twitter tools
  • Run a live chat loop where you ask the agent to perform Twitter operations

What is AutoGen?

Autogen is a framework for building multi-agent conversational AI systems from Microsoft. It enables you to create agents that can collaborate, use tools, and maintain complex workflows.

Key features include:

  • Multi-Agent Systems: Build collaborative agent workflows
  • MCP Workbench: Native support for Model Context Protocol tools
  • Streaming HTTP: Connect to external services through streamable HTTP
  • AssistantAgent: Pre-built agent class for tool-using assistants

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

You will need:

  • A Composio API key
  • An OpenAI API key (used by Autogen's OpenAIChatCompletionClient)
  • A Twitter account you can connect to Composio
  • Some basic familiarity with Autogen and Python async

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

bash
pip install composio python-dotenv
pip install autogen-agentchat autogen-ext-openai autogen-ext-tools

Install Composio, Autogen extensions, and dotenv.

What's happening:

  • composio connects your agent to Twitter via MCP
  • autogen-agentchat provides the AssistantAgent class
  • autogen-ext-openai provides the OpenAI model client
  • autogen-ext-tools provides MCP workbench support

Set up environment variables

bash
COMPOSIO_API_KEY=your-composio-api-key
OPENAI_API_KEY=your-openai-api-key
USER_ID=your-user-identifier@example.com

Create a .env file in your project folder.

What's happening:

  • COMPOSIO_API_KEY is required to talk to Composio
  • OPENAI_API_KEY is used by Autogen's OpenAI client
  • USER_ID is how Composio identifies which user's Twitter connections to use

Import dependencies and create Tool Router session

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio

from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.tools.mcp import McpWorkbench, StreamableHttpServerParams

load_dotenv()

async def main():
    # Initialize Composio and create a Twitter session
    composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))
    session = composio.create(
        user_id=os.getenv("USER_ID"),
        toolkits=["twitter"]
    )
    url = session.mcp.url
What's happening:
  • load_dotenv() reads your .env file
  • Composio(api_key=...) initializes the SDK
  • create(...) creates a Tool Router session that exposes Twitter tools
  • session.mcp.url is the MCP endpoint that Autogen will connect to

Configure MCP parameters for Autogen

python
# Configure MCP server parameters for Streamable HTTP
server_params = StreamableHttpServerParams(
    url=url,
    timeout=30.0,
    sse_read_timeout=300.0,
    terminate_on_close=True,
    headers={"x-api-key": os.getenv("COMPOSIO_API_KEY")}
)

Autogen expects parameters describing how to talk to the MCP server. That is what StreamableHttpServerParams is for.

What's happening:

  • url points to the Tool Router MCP endpoint from Composio
  • timeout is the HTTP timeout for requests
  • sse_read_timeout controls how long to wait when streaming responses
  • terminate_on_close=True cleans up the MCP server process when the workbench is closed

Create the model client and agent

python
# Create model client
model_client = OpenAIChatCompletionClient(
    model="gpt-5",
    api_key=os.getenv("OPENAI_API_KEY")
)

# Use McpWorkbench as context manager
async with McpWorkbench(server_params) as workbench:
    # Create Twitter assistant agent with MCP tools
    agent = AssistantAgent(
        name="twitter_assistant",
        description="An AI assistant that helps with Twitter operations.",
        model_client=model_client,
        workbench=workbench,
        model_client_stream=True,
        max_tool_iterations=10
    )

What's happening:

  • OpenAIChatCompletionClient wraps the OpenAI model for Autogen
  • McpWorkbench connects the agent to the MCP tools
  • AssistantAgent is configured with the Twitter tools from the workbench

Run the interactive chat loop

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

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

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

    if not user_input:
        continue

    print("\nAgent is thinking...\n")

    # Run the agent with streaming
    try:
        response_text = ""
        async for message in agent.run_stream(task=user_input):
            if hasattr(message, "content") and message.content:
                response_text = message.content

        # Print the final response
        if response_text:
            print(f"Agent: {response_text}\n")
        else:
            print("Agent: I encountered an issue processing your request.\n")

    except Exception as e:
        print(f"Agent: Sorry, I encountered an error: {str(e)}\n")
What's happening:
  • The script prompts you in a loop with You:
  • Autogen passes your input to the model, which decides which Twitter tools to call via MCP
  • agent.run_stream(...) yields streaming messages as the agent thinks and calls tools
  • Typing exit, quit, or bye ends the loop

Complete Code

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

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio

from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.tools.mcp import McpWorkbench, StreamableHttpServerParams

load_dotenv()

async def main():
    # Initialize Composio and create a Twitter session
    composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))
    session = composio.create(
        user_id=os.getenv("USER_ID"),
        toolkits=["twitter"]
    )
    url = session.mcp.url

    # Configure MCP server parameters for Streamable HTTP
    server_params = StreamableHttpServerParams(
        url=url,
        timeout=30.0,
        sse_read_timeout=300.0,
        terminate_on_close=True,
        headers={"x-api-key": os.getenv("COMPOSIO_API_KEY")}
    )

    # Create model client
    model_client = OpenAIChatCompletionClient(
        model="gpt-5",
        api_key=os.getenv("OPENAI_API_KEY")
    )

    # Use McpWorkbench as context manager
    async with McpWorkbench(server_params) as workbench:
        # Create Twitter assistant agent with MCP tools
        agent = AssistantAgent(
            name="twitter_assistant",
            description="An AI assistant that helps with Twitter operations.",
            model_client=model_client,
            workbench=workbench,
            model_client_stream=True,
            max_tool_iterations=10
        )

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

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

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

            if not user_input:
                continue

            print("\nAgent is thinking...\n")

            # Run the agent with streaming
            try:
                response_text = ""
                async for message in agent.run_stream(task=user_input):
                    if hasattr(message, 'content') and message.content:
                        response_text = message.content

                # Print the final response
                if response_text:
                    print(f"Agent: {response_text}\n")
                else:
                    print("Agent: I encountered an issue processing your request.\n")

            except Exception as e:
                print(f"Agent: Sorry, I encountered an error: {str(e)}\n")

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

Conclusion

You now have an Autogen assistant wired into Twitter through Composio's Tool Router and MCP. From here you can:
  • Add more toolkits to the toolkits list, for example notion or hubspot
  • Refine the agent description to point it at specific workflows
  • Wrap this script behind a UI, Slack bot, or internal tool
Once the pattern is clear for Twitter, you can reuse the same structure for other MCP-enabled apps with minimal code changes.

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

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