# How to integrate Twitter MCP with CrewAI

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

## Introduction

This guide walks you through connecting Twitter to CrewAI 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 CrewAI 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)

## TL;DR

Here's what you'll learn:
- Get a Composio API key and configure your Twitter connection
- Set up CrewAI with an MCP enabled agent
- Create a Tool Router session or standalone MCP server for Twitter
- Build a conversational loop where your agent can execute Twitter operations

## What is CrewAI?

CrewAI is a powerful framework for building multi-agent AI systems. It provides primitives for defining agents with specific roles, creating tasks, and orchestrating workflows through crews.
Key features include:
- Agent Roles: Define specialized agents with specific goals and backstories
- Task Management: Create tasks with clear descriptions and expected outputs
- Crew Orchestration: Combine agents and tasks into collaborative workflows
- MCP Integration: Connect to external tools through Model Context Protocol

## 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 agent to Twitter. It provides structured and secure access so your agent can perform Twitter operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Python 3.9 or higher
- A Composio account and API key
- A Twitter connection authorized in Composio
- An OpenAI API key for the CrewAI LLM
- Basic familiarity with Python

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

**What's happening:**
- composio connects your agent to Twitter via MCP
- crewai provides Agent, Task, Crew, and LLM primitives
- crewai-tools[mcp] includes MCP helpers
- python-dotenv loads environment variables from .env
```bash
pip install composio crewai crewai-tools[mcp] python-dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates with Composio
- USER_ID scopes the session to your account
- OPENAI_API_KEY lets CrewAI use your chosen OpenAI model
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here
```

### 4. Import dependencies

**What's happening:**
- CrewAI classes define agents and tasks, and run the workflow
- MCPServerHTTP connects the agent to an MCP endpoint
- Composio will give you a short lived Twitter MCP URL
```python
import os
from composio import Composio
from crewai import Agent, Task, Crew
from crewai_tools import MCPServerAdapter
import dotenv

dotenv.load_dotenv()

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

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

### 5. Create a Composio Tool Router session for Twitter

**What's happening:**
- You create a Twitter only session through Composio
- Composio returns an MCP HTTP URL that exposes Twitter tools
```python
composio_client = Composio(api_key=COMPOSIO_API_KEY)
session = composio_client.create(user_id=COMPOSIO_USER_ID, toolkits=["twitter"])

url = session.mcp.url
```

### 6. Initialize the MCP Server

**What's Happening:**
- Server Configuration: The code sets up connection parameters including the MCP server URL, streamable HTTP transport, and Composio API key authentication.
- MCP Adapter Bridge: MCPServerAdapter acts as a context manager that converts Composio MCP tools into a CrewAI-compatible format.
- Agent Setup: Creates a CrewAI Agent with a defined role (Search Assistant), goal (help with internet searches), and access to the MCP tools.
- Configuration Options: The agent includes settings like verbose=False for clean output and max_iter=10 to prevent infinite loops.
- Dynamic Tool Usage: Once created, the agent automatically accesses all Composio Search tools and decides when to use them based on user queries.
```python
server_params = {
    "url": url,
    "transport": "streamable-http",
    "headers": {"x-api-key": COMPOSIO_API_KEY},
}

with MCPServerAdapter(server_params) as tools:
    agent = Agent(
        role="Search Assistant",
        goal="Help users search the internet effectively",
        backstory="You are a helpful assistant with access to search tools.",
        tools=tools,
        verbose=False,
        max_iter=10,
    )
```

### 7. Create a CLI Chatloop and define the Crew

**What's Happening:**
- Interactive CLI Setup: The code creates an infinite loop that continuously prompts for user input and maintains the entire conversation history in a string variable.
- Input Validation: Empty inputs are ignored to prevent processing blank messages and keep the conversation clean.
- Context Building: Each user message is appended to the conversation context, which preserves the full dialogue history for better agent responses.
- Dynamic Task Creation: For every user input, a new Task is created that includes both the full conversation history and the current request as context.
- Crew Execution: A Crew is instantiated with the agent and task, then kicked off to process the request and generate a response.
- Response Management: The agent's response is converted to a string, added to the conversation context, and displayed to the user, maintaining conversational continuity.
```python
print("Chat started! Type 'exit' or 'quit' to end.\n")

conversation_context = ""

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

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

    if not user_input:
        continue

    conversation_context += f"\nUser: {user_input}\n"
    print("\nAgent is thinking...\n")

    task = Task(
        description=(
            f"Conversation history:\n{conversation_context}\n\n"
            f"Current request: {user_input}"
        ),
        expected_output="A helpful response addressing the user's request",
        agent=agent,
    )

    crew = Crew(agents=[agent], tasks=[task], verbose=False)
    result = crew.kickoff()
    response = str(result)

    conversation_context += f"Agent: {response}\n"
    print(f"Agent: {response}\n")
```

## Complete Code

```python
from crewai import Agent, Task, Crew, LLM
from crewai_tools import MCPServerAdapter
from composio import Composio
from dotenv import load_dotenv
import os

load_dotenv()

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

if not GOOGLE_API_KEY:
    raise ValueError("GOOGLE_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.")

# Initialize Composio and create a session
composio = Composio(api_key=COMPOSIO_API_KEY)
session = composio.create(
    user_id=COMPOSIO_USER_ID,
    toolkits=["twitter"],
)
url = session.mcp.url

# Configure LLM
llm = LLM(
    model="gpt-5",
    api_key=os.getenv("OPENAI_API_KEY"),
)

server_params = {
    "url": url,
    "transport": "streamable-http",
    "headers": {"x-api-key": COMPOSIO_API_KEY},
}

with MCPServerAdapter(server_params) as tools:
    agent = Agent(
        role="Search Assistant",
        goal="Help users with internet searches",
        backstory="You are an expert assistant with access to Composio Search tools.",
        tools=tools,
        llm=llm,
        verbose=False,
        max_iter=10,
    )

    print("Chat started! Type 'exit' or 'quit' to end.\n")

    conversation_context = ""

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

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

        if not user_input:
            continue

        conversation_context += f"\nUser: {user_input}\n"
        print("\nAgent is thinking...\n")

        task = Task(
            description=(
                f"Conversation history:\n{conversation_context}\n\n"
                f"Current request: {user_input}"
            ),
            expected_output="A helpful response addressing the user's request",
            agent=agent,
        )

        crew = Crew(agents=[agent], tasks=[task], verbose=False)
        result = crew.kickoff()
        response = str(result)

        conversation_context += f"Agent: {response}\n"
        print(f"Agent: {response}\n")
```

## Conclusion

You now have a CrewAI agent connected to Twitter through Composio's Tool Router. The agent can perform Twitter operations through natural language commands.
Next steps:
- Add role-specific instructions to customize agent behavior
- Plug in more toolkits for multi-app workflows
- Chain tasks for complex multi-step operations

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

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

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