# How to integrate Twitter MCP with Pydantic AI

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

## Introduction

This guide walks you through connecting Twitter to Pydantic AI 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 Pydantic AI 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:
- How to set up your Composio API key and User ID
- How to create a Composio Tool Router session for Twitter
- How to attach an MCP Server to a Pydantic AI agent
- How to stream responses and maintain chat history
- How to build a simple REPL-style chat interface to test your Twitter workflows

## What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.
Key features include:
- Type Safety: Built on Pydantic for automatic data validation
- MCP Support: Native support for Model Context Protocol servers
- Streaming: Built-in support for streaming responses
- Async First: Designed for async/await patterns

## 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 with an active API key
- Basic familiarity with Python and async programming

### 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 the required libraries.
What's happening:
- composio connects your agent to external SaaS tools like Twitter
- pydantic-ai lets you create structured AI agents with tool support
- python-dotenv loads your environment variables securely from a .env file
```bash
pip install composio pydantic-ai python-dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates your agent to Composio's API
- USER_ID associates your session with your account for secure tool access
- OPENAI_API_KEY to access OpenAI LLMs
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key
```

### 4. Import dependencies

What's happening:
- We load environment variables and import required modules
- Composio manages connections to Twitter
- MCPServerStreamableHTTP connects to the Twitter MCP server endpoint
- Agent from Pydantic AI lets you define and run the AI assistant
```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
```

### 5. Create a Tool Router Session

What's happening:
- We're creating a Tool Router session that gives your agent access to Twitter tools
- The create method takes the user ID and specifies which toolkits should be available
- The returned session.mcp.url is the MCP server URL that your agent will use
```python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Twitter
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["twitter"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
```

### 6. Initialize the Pydantic AI Agent

What's happening:
- The MCP client connects to the Twitter endpoint
- The agent uses GPT-5 to interpret user commands and perform Twitter operations
- The instructions field defines the agent's role and behavior
```python
# Attach the MCP server to a Pydantic AI Agent
twitter_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[twitter_mcp],
    instructions=(
        "You are a Twitter assistant. Use Twitter tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
```

### 7. Build the chat interface

What's happening:
- The agent reads input from the terminal and streams its response
- Twitter API calls happen automatically under the hood
- The model keeps conversation history to maintain context across turns
```python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Twitter.\n")

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", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
```

### 8. Run the application

What's happening:
- The asyncio loop launches the agent and keeps it running until you exit
```python
if __name__ == "__main__":
    asyncio.run(main())
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Twitter
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["twitter"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    twitter_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[twitter_mcp],
        instructions=(
            "You are a Twitter assistant. Use Twitter tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Twitter.\n")

    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", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

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

## Conclusion

You've built a Pydantic AI agent that can interact with Twitter through Composio's Tool Router. With this setup, your agent can perform real Twitter actions through natural language.
You can extend this further by:
- Adding other toolkits like Gmail, HubSpot, or Salesforce
- Building a web-based chat interface around this agent
- Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Twitter for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.

## 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 Pydantic AI?

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