# How to integrate Twitter MCP with OpenAI Agents SDK

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

## Introduction

This guide walks you through connecting Twitter to the OpenAI Agents SDK 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 OpenAI Agents SDK 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)
- [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 necessary dependencies
- Initialize Composio and create a Tool Router session for Twitter
- Configure an AI agent that can use Twitter as a tool
- Run a live chat session where you can ask the agent to perform Twitter operations

## What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.
Key features include:
- Hosted MCP Tools: Connect to external services through hosted MCP endpoints
- SQLite Sessions: Persist conversation history across interactions
- Simple API: Clean interface with Agent, Runner, and tool configuration
- Streaming Support: Real-time response streaming for interactive applications

## 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:
- Composio API Key and OpenAI API Key
- Primary know-how of OpenAI Agents SDK
- A live Twitter project
- Some knowledge of Python or Typescript

### 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).
- Go to Settings and copy your API key.

### 2. Install dependencies

Install the Composio SDK and the OpenAI Agents SDK.
```python
pip install composio_openai_agents openai-agents python-dotenv
```

```typescript
npm install @composio/openai-agents @openai/agents dotenv
```

### 3. Set up environment variables

Create a .env file and add your OpenAI and Composio API keys.
```bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com
```

### 4. Import dependencies

What's happening:
- You're importing all necessary libraries.
- The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Twitter.
```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
```

### 5. Set up the Composio instance

No description provided.
```python
load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())
```

```typescript
dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
```

### 6. Create a Tool Router session

What is happening:
- You give the Tool Router the user id and the toolkits you want available. Here, it is only twitter.
- The router checks the user's Twitter connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access Twitter.
- This approach keeps things lightweight and lets the agent request Twitter tools only when needed during the conversation.
```python
# Create a Twitter Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["twitter"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for Twitter
const session = await composio.create(userId as string, {
  toolkits: ['twitter'],
});
const mcpUrl = session.mcp.url;
```

### 7. Configure the agent

No description provided.
```python
# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Twitter. "
        "Help users perform Twitter operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)
```

```typescript
// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Twitter. Help users perform Twitter operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
```

### 8. Start chat loop and handle conversation

No description provided.
```python
print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

  if (!text) {
    rl.prompt();
    return;
  }

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession

load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())

# Create Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["twitter"]
)
mcp_url = session.mcp.url

# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Twitter. "
        "Help users perform Twitter operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)

print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['twitter'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Twitter. Help users perform Twitter operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

    if (!text) {
      rl.prompt();
      return;
    }

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
```

## Conclusion

This was a starter code for integrating Twitter MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Twitter.
Key features:
- Hosted MCP tool integration through Composio's Tool Router
- SQLite session persistence for conversation history
- Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## How to build Twitter MCP Agent with another framework

- [ChatGPT](https://composio.dev/toolkits/twitter/framework/chatgpt)
- [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 OpenAI Agents SDK?

Yes, you can. OpenAI Agents SDK 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)
