# How to integrate Twitter MCP with Autogen

```json
{
  "title": "How to integrate Twitter MCP with Autogen",
  "toolkit": "Twitter",
  "toolkit_slug": "twitter",
  "framework": "AutoGen",
  "framework_slug": "autogen",
  "url": "https://composio.dev/toolkits/twitter/framework/autogen",
  "markdown_url": "https://composio.dev/toolkits/twitter/framework/autogen.md",
  "updated_at": "2026-05-06T08:32:31.045Z"
}
```

## 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 your conference list, retrieve your most recent bookmarked tweets 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.

## Also integrate Twitter with

- [ChatGPT](https://composio.dev/toolkits/twitter/framework/chatgpt)
- [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)
- [Claude Code](https://composio.dev/toolkits/twitter/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/twitter/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/twitter/framework/codex)
- [Cursor](https://composio.dev/toolkits/twitter/framework/cursor)
- [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)
- [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)
- [LlamaIndex](https://composio.dev/toolkits/twitter/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/twitter/framework/crew-ai)

## 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

| 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_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_A_NEW_DM_CONVERSATION` | Create group DM conversation | Creates a new group direct message (dm) conversation on twitter with specified participant ids and an initial message, which can include text and media attachments. |
| `TWITTER_CREATE_COMPLIANCE_JOB_REQUEST` | 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_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. |
| `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_FETCH_LIST_MEMBERS_BY_ID` | Fetch list members by id | Fetches members of a specific twitter list, identified by its unique id. |
| `TWITTER_FETCH_SPACE_TICKET_BUYERS_LIST` | Fetch space ticket buyers list | Retrieves a list of users who purchased tickets for a specific, valid, and ticketed twitter space. |
| `TWITTER_FOLLOW_A_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_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_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_FULL_ARCHIVE_SEARCH_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_GET_A_USER_S_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_A_USER_S_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_A_USER_S_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_BLOCKED_USERS` | Get users blocked by user ID | Retrieves user objects for accounts blocked by the specified user id; this is a read-only view of a user's block list. |
| `TWITTER_GET_DM_EVENTS_BY_ID` | 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_DM_EVENTS_FOR_A_DM_CONVERSATION` | 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_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_MUTED_USERS` | Get muted users | Returns user objects muted by the x user identified by the `id` path parameter. |
| `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_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_USER_S_FOLLOWED_LISTS` | Get user's followed lists | Returns metadata (not tweets) for lists a specific twitter user follows, optionally including expanded owner details. |
| `TWITTER_HIDE_REPLIES` | Set reply visibility | Hides or unhides an existing reply tweet. |
| `TWITTER_LIST_LOOKUP_BY_LIST_ID` | 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_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_BY_USER_ID` | 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_A_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_POSTS_LABEL_STREAM` | Get tweets label stream | Establishes a persistent stream of real-time events for when tweet labels are applied or removed, offering insights into content categorization. |
| `TWITTER_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_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`) |
| `TWITTER_RECENT_SEARCH_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_REMOVE_A_BOOKMARKED_POST` | 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_REMOVE_A_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_RETRIEVE_COMPLIANCE_JOB_BY_ID` | 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_RETRIEVE_COMPLIANCE_JOBS` | Retrieve compliance jobs | Returns a list of recent compliance jobs, filtered by type (tweets or users) and optionally by status. |
| `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_FROM_A_SPACE` | Retrieve posts from a space | Retrieves tweets from a specified twitter space id; the space must be accessible and results are batched (not streamed). |
| `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_RETRIEVE_POSTS_THAT_REPOST_A_POST` | 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_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_RETURNS_THE_OPEN_API_SPECIFICATION_DOCUMENT` | 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_RETWEET_POST` | Retweet post | Retweets 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. |
| `TWITTER_SEARCH_FOR_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_DM_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_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_SPACE_LOOKUP_BY_SPACE_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_SPACE_LOOKUP_BY_THEIR_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_SPACE_LOOKUP_UP_SPACE_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_UNFOLLOW_A_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 `source user id` to unfollow an existing twitter user (`target user id`), which removes the follow relationship. |
| `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_BY_USER_ID` | Unmute a user by user ID | Unmutes 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. |
| `TWITTER_UNPIN_A_LIST` | Unpin a list | Unpins a list (specified by list id) from a user's profile (specified by id), provided the list is currently pinned by that user. |
| `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_USER_HOME_TIMELINE_BY_USER_ID` | Get user reverse chronological timeline | Retrieves 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. |
| `TWITTER_USER_LIKE_POST` | Like a tweet | Allows 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. |
| `TWITTER_USER_LOOKUP_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_USER_LOOKUP_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_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 agents and assistants directly to Twitter. Instead of manually wiring Twitter APIs, OAuth, and scopes yourself, you get a structured, tool-based interface that an LLM can call safely.
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

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

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

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Navigate to your API settings and generate a new API key.
- Store this key securely as you'll need it for authentication.

### 2. Install dependencies

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
```bash
pip install composio python-dotenv
pip install autogen-agentchat autogen-ext-openai autogen-ext-tools
```

### 3. Set up environment variables

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
```bash
COMPOSIO_API_KEY=your-composio-api-key
OPENAI_API_KEY=your-openai-api-key
USER_ID=your-user-identifier@example.com
```

### 4. Import dependencies and create Tool Router session

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
```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
```

### 5. Configure MCP parameters for Autogen

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
```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")}
)
```

### 6. Create the model client and agent

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
```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
    )
```

### 7. Run the interactive chat loop

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
```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")
```

## Complete Code

```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

- [ChatGPT](https://composio.dev/toolkits/twitter/framework/chatgpt)
- [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)
- [Claude Code](https://composio.dev/toolkits/twitter/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/twitter/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/twitter/framework/codex)
- [Cursor](https://composio.dev/toolkits/twitter/framework/cursor)
- [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)
- [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)
- [LlamaIndex](https://composio.dev/toolkits/twitter/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/twitter/framework/crew-ai)

## 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.
- [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.
- [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.
- [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.
- [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.
- [Slack](https://composio.dev/toolkits/slack) - Slack is a channel-based messaging platform for teams and organizations. It helps people collaborate in real time, share files, and connect all their tools in one place.
- [Airtable](https://composio.dev/toolkits/airtable) - Airtable combines the flexibility of spreadsheets with the power of a database for easy project and data management. Teams use Airtable to organize, track, and collaborate with custom views and automations.
- [Google Docs](https://composio.dev/toolkits/googledocs) - Google Docs is a cloud-based word processor that enables document creation and real-time collaboration. Its seamless sharing and version history make team editing and content management a breeze.
- [Google Super](https://composio.dev/toolkits/googlesuper) - Google Super is an all-in-one suite combining Gmail, Drive, Calendar, Sheets, Analytics, and more. It gives you a unified platform to manage your digital life, boosting productivity and organization.
- [Hubspot](https://composio.dev/toolkits/hubspot) - HubSpot is an all-in-one marketing, sales, and customer service platform. It lets teams nurture leads, automate outreach, and track every customer interaction in one place.
- [Codeinterpreter](https://composio.dev/toolkits/codeinterpreter) - Codeinterpreter is a Python-based coding environment with built-in data analysis and visualization. It lets you instantly run scripts, plot results, and prototype solutions inside supported platforms.
- [Gong](https://composio.dev/toolkits/gong) - Gong is a platform for video meetings, call recording, and team collaboration. It helps teams capture conversations, analyze calls, and turn insights into action.

## 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 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.

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