Twitter MCP Server
The Twitter MCP Server is a comprehensive API integration platform that allows interaction with Twitter's API for various operations:
Tweet Operations: Post tweets (with or without media), reply to tweets, delete tweets, retrieve tweets by ID or in batches
User Operations: Get user information, follow/unfollow users, retrieve user timelines, followers, and following lists (some features currently have availability issues)
Engagement: Like/unlike tweets, retweet/undo retweets, and get lists of retweets and liked tweets
Search & Analytics: Search for tweets and get hashtag analytics (some features currently have availability issues)
List Management: Create lists, add/remove users from lists, and retrieve list members and user-owned lists
Uses environment variables from .env files to store Twitter API credentials securely
Uses npm for dependency management and running build/development scripts
Uses TypeScript for implementation of parameter validation and error handling
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Twitter MCP Server post a tweet saying 'Just launched our new product! Check it out at example.com'"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
X (Twitter) MCP Server
A comprehensive Model Context Protocol server implementation for X (Twitter) API integration with professional workflow automation, enhanced error handling, and real-time documentation.
๐ Features
53 Total Tools - 33 Twitter API + 20 enhanced SocialData.tools research capabilities
Advanced Analytics - Thread analysis, network mapping, sentiment analysis, viral tracking
Bypasses API Restrictions - Enhanced research tools work without Pro tier requirements
Professional Error Handling - Clear upgrade guidance and graceful API key handling
5 Workflow Prompts - Pre-built automation templates
6 Dynamic Resources - Real-time API documentation and status
Full MCP Compliance - Tools, prompts, and resources support
Related MCP server: MCP Twitter
๐ Quick Start
Prerequisites
Node.js 18+
npm or yarn
X (Twitter) API credentials (Basic tier minimum - $200/month)
Local Installation
Clone and Install
git clone <repository-url> cd twitter-server npm installEnvironment Setup
cp .env.example .env # Edit .env with your credentialsRequired Environment Variables:
# Twitter API credentials (Required) X_API_KEY=your_api_key_here X_API_SECRET=your_api_secret_here X_ACCESS_TOKEN=your_access_token_here X_ACCESS_TOKEN_SECRET=your_access_token_secret_here # SocialData.tools API key (Optional - enables enhanced research tools) SOCIALDATA_API_KEY=your_socialdata_api_key_here SOCIALDATA_BASE_URL=https://api.socialdata.tools # Optional, uses default if not setBuild and Run
npm run build npm startTest the Server
# Test with JSON-RPC calls source .env && echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | node dist/index.js # Test specific tool source .env && echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "getUserInfo", "arguments": {"username": "elonmusk"}}}' | node dist/index.js
๐ X (Twitter) API Setup
Required Credentials
Add these to your .env file:
X_API_KEY=your_api_key_here
X_API_SECRET=your_api_secret_here
X_ACCESS_TOKEN=your_access_token_here
X_ACCESS_TOKEN_SECRET=your_access_token_secret_hereAPI Access Levels
Tier | Cost | Working Tools | Limited Tools |
Basic | $200/month | 18/22 tools | searchTweets, getHashtagAnalytics |
Pro | $5,000/month | All 22 tools | None |
๐ ๏ธ Available Tools (53 Total)
๐ฆ Twitter API Tools (33 tools)
โ Tweet Operations (All Working)
postTweet- Post new tweetsgetTweetById- Retrieve specific tweetsreplyToTweet- Reply to tweetsdeleteTweet- Delete your tweets
โ Engagement (All Working)
likeTweet/unlikeTweet- Like/unlike tweetsretweet/undoRetweet- Retweet/undo retweetsgetRetweets- Get retweet users
โ User Management (Most Working)
getUserInfo- Get user profiles โgetUserTimeline- Get user tweets โfollowUser/unfollowUser- Follow/unfollow users โgetFollowers- Get followers โ ๏ธ (403 - requires special permissions)getFollowing- Get following โ ๏ธ (403 - requires special permissions)
โ List Management (All Working)
createList- Create X (Twitter) listsgetUserLists- Get user's listsaddUserToList/removeUserFromList- Manage list membersgetListMembers- Get list members
โ ๏ธ Search & Analytics (Limited)
searchTweets- Search tweets (requires Pro tier - $5,000/month)getHashtagAnalytics- Hashtag analytics (requires Pro tier)getLikedTweets- Get liked tweets (API access issue)
๐ SocialData.tools Enhanced Research (20 tools)
Note: These tools gracefully handle missing API keys with helpful setup instructions
๐ Advanced Search (6 tools)
advancedTweetSearch- Complex queries with operators, bypasses API tier restrictionshistoricalTweetSearch- Access historical tweets beyond standard API limitstrendingTopicsSearch- Real-time trend analysis and popular content discoverybulkUserProfiles- Multi-user profile analysis in single requestsuserGrowthAnalytics- User growth pattern analysis over timeuserInfluenceMetrics- Engagement scoring and influence calculations
๐งต Thread & Conversation Analysis (3 tools)
getFullThread- Reconstruct complete Twitter threads with engagement metricsgetConversationTree- Map conversation structure including replies and quotesgetThreadMetrics- Thread performance analysis and engagement distribution
๐ Network Analysis (3 tools)
findMutualConnections- Discover mutual connections via interactionsanalyzeFollowerDemographics- Follower patterns and demographic analysismapInfluenceNetwork- Influence mapping and connection strength analysis
๐ Advanced Analytics (3 tools)
getHashtagTrends- Hashtag performance tracking over time with trend analysisanalyzeSentiment- Sentiment analysis with keyword frequency trackingtrackVirality- Viral spread patterns and engagement velocity analysis
๐ฑ Direct Messages & Moderation (5 tools)
Various DM and user moderation tools
๐ API Keys Setup
Twitter API (Required)
Get these from Twitter Developer Portal:
X_API_KEY=your_api_key_here
X_API_SECRET=your_api_secret_here
X_ACCESS_TOKEN=your_access_token_here
X_ACCESS_TOKEN_SECRET=your_access_token_secret_hereSocialData.tools API (Optional)
Enables 20 enhanced research tools that bypass Twitter API limitations:
Sign up at SocialData.tools
Get your API key from the dashboard
Add to .env file:
SOCIALDATA_API_KEY=your_socialdata_api_key_here
Without SocialData API key: Enhanced research tools will show helpful setup instructions instead of errors.
๐งช Testing SocialData.tools Integration
Test Enhanced Research Tools
# Test advanced tweet search (bypasses Twitter API Pro tier requirement)
source .env && echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "advancedTweetSearch", "arguments": {"query": "AI OR machine learning", "maxResults": 5}}}' | node dist/index.js
# Test sentiment analysis
source .env && echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "analyzeSentiment", "arguments": {"query": "ChatGPT", "sampleSize": 20}}}' | node dist/index.js
# Test user influence metrics
source .env && echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "userInfluenceMetrics", "arguments": {"username": "openai"}}}' | node dist/index.js
# Test thread analysis
source .env && echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "getFullThread", "arguments": {"tweetId": "1234567890123456789"}}}' | node dist/index.jsTest Without API Key
# These will show helpful setup instructions instead of errors
SOCIALDATA_API_KEY="" echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "advancedTweetSearch", "arguments": {"query": "test"}}}' | node dist/index.js๐ When to Use Which Tools
Twitter API vs SocialData.tools Comparison
Use Case | Twitter API Tool | SocialData.tools Alternative | Advantage |
Basic Search |
|
| Bypasses API restrictions |
User Analysis |
|
| Enhanced analytics |
Historical Data | Limited by API tier |
| Access older tweets |
Sentiment Analysis | Not available |
| Built-in sentiment scoring |
Thread Analysis | Manual reconstruction |
| Automated thread mapping |
Network Mapping | Not available |
| Connection analysis |
Hashtag Trends |
|
| No tier restrictions |
Recommended Workflow
Start with Twitter API tools for posting, engagement, and basic operations
Use SocialData.tools for research, analytics, and advanced insights
Combine both for comprehensive Twitter automation and analysis
๐ฏ MCP Workflow Prompts
Our server includes 5 professional workflow templates:
1. Tweet Composition (compose-tweet)
Interactive guidance for creating engaging tweets with hashtags, mentions, and media.
2. Analytics Reporting (analytics-report)
Comprehensive X (Twitter) analytics workflow for business insights.
3. Content Strategy (content-strategy)
Strategic content planning and audience engagement workflows.
4. Community Management (community-management)
Customer service and community engagement best practices.
5. Hashtag Research (hashtag-research)
Industry-specific hashtag research and trend analysis.
๐ Dynamic Resources
Real-time information accessible via MCP:
API Rate Limits - Live usage monitoring
Access Level Status - Current tier capabilities
Tool Status Report - Working vs limited tools
Quick Start Guide - Getting started documentation
Workflow Templates - Pre-built automation examples
User Profile Data - Dynamic user information (live API calls)
๐งช Testing
Manual Testing
# Test working tools
source .env && echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "postTweet", "arguments": {"text": "Hello from MCP!"}}}' | node dist/index.js
# Test user info
source .env && echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "getUserInfo", "arguments": {"username": "elonmusk"}}}' | node dist/index.js
# Test limited tools (will show upgrade guidance)
source .env && echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "searchTweets", "arguments": {"query": "MCP"}}}' | node dist/index.jsTest Results Summary
18 Tools Working on Basic tier
4 Tools Limited by API tier/permissions
Professional error messages with upgrade guidance
All core functionality operational
๐ง Integration Examples
MCP Client (Cursor/Claude)
{
"mcpServers": {
"x-twitter": {
"command": "node",
"args": ["/path/to/twitter-server/dist/index.js"],
"env": {
"X_API_KEY": "your_api_key",
"X_API_SECRET": "your_api_secret",
"X_ACCESS_TOKEN": "your_access_token",
"X_ACCESS_TOKEN_SECRET": "your_access_token_secret"
}
}
}
}Direct JSON-RPC
# Always source environment first
source .env
# List all tools
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | node dist/index.js
# Call specific tool
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "toolName", "arguments": {"param": "value"}}}' | node dist/index.js๐ API Documentation
Tweet Operations
postTweet
{
"text": "Your tweet content (up to 280 characters)"
}getTweetById
{
"tweetId": "1234567890123456789",
"tweetFields": ["created_at", "public_metrics", "author_id"]
}replyToTweet
{
"tweetId": "1234567890123456789",
"text": "Your reply content"
}User Operations
getUserInfo
{
"username": "elonmusk",
"fields": ["description", "public_metrics", "profile_image_url"]
}followUser
{
"username": "target_username"
}Engagement
likeTweet
{
"tweetId": "1234567890123456789"
}retweet
{
"tweetId": "1234567890123456789"
}๐จ Error Handling
Professional Error Messages
Our enhanced error handling provides:
Clear API tier explanations for limited tools
Upgrade pricing information ($5,000/month Pro tier)
Direct upgrade links to Twitter Developer Portal
Alternative solution suggestions
Example error response:
{
"error": "This endpoint requires X (Twitter) API Pro tier access ($5,000/month). Visit https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve to upgrade your access level."
}๐ Project Structure
twitter-server/
โโโ src/
โ โโโ handlers/ # API endpoint handlers
โ โโโ prompts.ts # MCP workflow prompts
โ โโโ resources.ts # Dynamic MCP resources
โ โโโ index.ts # Main MCP server
โโโ dist/ # Compiled JavaScript
โโโ scripts/ # Documentation & PRD
โโโ package.json๐ Development
Build & Run
npm run build # Compile TypeScript
npm start # Start production server
npm run dev # Development mode with watchAdding New Tools
Add handler function in appropriate
src/handlers/fileRegister tool in
src/index.tsAdd documentation to this README
Test with JSON-RPC calls
Contributing
Follow existing code patterns
Add proper error handling with professional messages
Test with both working and failing scenarios
Update documentation
๐ Known Limitations
API Tier Restrictions
searchTweets: Requires Pro tier ($5,000/month)
getHashtagAnalytics: Requires Pro tier
getFollowers/getFollowing: Requires special permissions (403 errors)
getLikedTweets: Parameter validation issues
Recommendations
Current Setup: Excellent for basic X (Twitter) automation
For Advanced Analytics: Consider Pro tier upgrade
For Followers/Following: Request elevated permissions
๐ Troubleshooting
Common Issues
Error: "fetch is not defined"
# Ensure Node.js 18+
node --version403 Permission Errors
Check API credentials are correct
Verify account has required permissions
Some endpoints need special approval
400 Bad Request Errors
Review parameter formats
Check our enhanced error messages for guidance
Verify API tier supports the endpoint
Getting Help
Check error messages - Our enhanced error handling provides clear guidance
Review API documentation - X (Twitter) Developer Portal
Test with working tools first - Verify basic setup
Check environment variables - Ensure all credentials are set
๐ Current Status
53 Total Tools: 33 Twitter API + 20 SocialData.tools enhanced research
Advanced Analytics: Thread analysis, network mapping, sentiment analysis, viral tracking
Graceful API Key Handling: Enhanced tools show helpful setup instructions when API key missing
Bypasses API Restrictions: Research tools work without Twitter Pro tier requirements
Professional Error Handling: Clear upgrade guidance and user-friendly messages
Full MCP Compliance: Tools, prompts, resources
Production Ready: Enhanced reliability, comprehensive analytics, and excellent UX
Built with โค๏ธ using the Model Context Protocol and SocialData.tools integration
Available Tools
53 toolsaddUserToListC
Add a user to a Twitter list
Inputs: listId (required), username (required).
advancedTweetSearchA
Advanced tweet search with operators and filters, bypassing API tier restrictions
Inputs: query (required), maxResults, startTime, endTime, +2 more.
analyzeFollowerDemographicsC
Analyze follower demographics and engagement patterns
Inputs: username (required), sampleSize, analyzeDemographics.
analyzeSentimentC
Perform sentiment analysis on tweets matching a query
Inputs: query (required), sampleSize, includeKeywords.
blockUserA
Block a user account to prevent them from following you or viewing your tweets
Inputs: userId, username.
bulkUserProfilesC
Get multiple user profiles in a single request for comparative analysis
Inputs: usernames, userIds, includeMetrics.
createListC
Create a new Twitter list
Inputs: name (required), description, private.
createMediaMessageB
Send a direct message with media attachments
Inputs: recipientId (required), text (required), mediaId (required), mediaType, +1 more.
deleteTweetC
Delete a tweet by its ID
Inputs: tweetId (required).
findMutualConnectionsC
Find mutual connections and interactions between two users
Inputs: user1 (required), user2 (required), maxResults.
followUserC
Follow a user by their username
Inputs: username (required).
getAuthenticatedUserA
Get the authenticated user's own profile information without needing to specify username or ID
Inputs: userFields.
getBlockedUsersB
Retrieve a paginated list of users you have blocked
Inputs: maxResults, paginationToken, userFields.
getConversationC
Get full conversation history for a specific conversation
Inputs: conversationId (required), maxResults, paginationToken, dmEventFields.
getConversationTreeB
Map complete conversation structure including replies and quotes
Inputs: tweetId (required), maxDepth, includeQuotes.
getDirectMessageEventsC
Get specific direct message events with detailed information
Inputs: maxResults, paginationToken, dmEventFields, expansions, +1 more.
getDirectMessagesC
Retrieve direct message conversations
Inputs: maxResults, paginationToken, dmEventFields.
getFollowersC
Get followers of a user
Inputs: username (required), maxResults, userFields.
getFollowingC
Get a list of users that a user is following
Inputs: username (required), maxResults, userFields.
getFullThreadC
Reconstruct complete Twitter thread with all tweets and replies
Inputs: tweetId (required), includeMetrics.
getHashtagAnalyticsC
Get analytics for a specific hashtag
Inputs: hashtag (required), startTime, endTime.
getHashtagTrendsC
Analyze hashtag trends and performance over time
Inputs: hashtag (required), timeframe, period.
getLikedTweetsC
Get a list of tweets liked by a user
Inputs: userId (required), maxResults, tweetFields.
getListMembersC
Get members of a Twitter list
Inputs: listId (required), maxResults, userFields.
getMutedUsersB
Retrieve a paginated list of users you have muted
Inputs: maxResults, paginationToken, userFields.
getRetweetsC
Get a list of retweets of a tweet
Inputs: tweetId (required), maxResults, userFields.
getThreadMetricsC
Analyze thread performance and engagement distribution
Inputs: tweetId (required), analyzeEngagement, timeframe.
getTweetByIdC
Get a tweet by its ID
Inputs: tweetId (required), tweetFields.
getTweetsByIdsC
Get multiple tweets by their IDs
Inputs: tweetIds (required), tweetFields.
getUserInfoC
Get information about a Twitter user
Inputs: username (required).
getUserListsC
Get lists owned by a user
Inputs: username (required), maxResults, listFields.
getUserTimelineC
Get tweets from a specific user's timeline
Inputs: username (required), maxResults, tweetFields.
historicalTweetSearchB
Search historical tweets beyond standard API limitations
Inputs: query (required), dateRange (required), maxResults.
likeTweetC
Like a tweet by its ID
Inputs: tweetId (required).
mapInfluenceNetworkC
Map user influence network and connection patterns
Inputs: centerUser (required), depth, connectionTypes.
markAsReadB
Mark direct messages as read (Note: May require special API access)
Inputs: messageId (required), conversationId.
muteUserB
Mute a user account to stop seeing their tweets in your timeline
Inputs: userId, username.
postTweetC
Post a tweet to Twitter
Inputs: text (required).
postTweetWithMediaC
Post a tweet with media attachment to Twitter
Inputs: text (required), mediaPath (required), mediaType (required), altText.
removeUserFromListC
Remove a user from a Twitter list
Inputs: listId (required), username (required).
replyToTweetC
Reply to a tweet
Inputs: tweetId (required), text (required).
retweetC
Retweet a tweet by its ID
Inputs: tweetId (required).
searchTweetsC
Search for tweets using a query string
Inputs: query (required), maxResults, tweetFields.
sendDirectMessageC
Send a direct message to a specified user
Inputs: recipientId (required), text (required), mediaId, attachments.
trackViralityC
Track viral spread patterns and engagement velocity
Inputs: tweetId (required), trackingPeriod, analyzeSpread.
trendingTopicsSearchC
Get trending topics and popular content for analysis
Inputs: location, timeframe, count.
unblockUserC
Unblock a previously blocked user account
Inputs: userId, username.
undoRetweetB
Undo a retweet by its ID
Inputs: tweetId (required).
unfollowUserC
Unfollow a user by their username
Inputs: username (required).
unlikeTweetC
Unlike a previously liked tweet
Inputs: tweetId (required).
unmuteUserC
Unmute a previously muted user account
Inputs: userId, username.
userGrowthAnalyticsC
Analyze user growth patterns and engagement trends over time
Inputs: username (required), timeframe, period.
userInfluenceMetricsC
Calculate user influence scores and engagement metrics
Inputs: username (required), analyzeEngagement, analyzeReach.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
TDQS
Scored across 53 tools
Most tools have distinct purposes, but there is significant overlap in some areas, such as multiple tweet search tools (advancedTweetSearch, historicalTweetSearch, searchTweets) and several analytics tools (e.g., analyzeFollowerDemographics, userGrowthAnalytics, userInfluenceMetrics) that could cause confusion. Descriptions help differentiate them, but the sheer number of similar tools increases ambiguity.
Tool names generally follow a consistent verb_noun pattern (e.g., postTweet, getUserInfo, likeTweet), with only minor deviations like 'addUserToList' (which could be 'addUserToList' is consistent in structure but uses 'add' instead of a more standard verb like 'create'). Overall, the naming is predictable and readable across the set.
With 53 tools, this server is overly comprehensive for a Twitter API wrapper, making it heavy and potentially overwhelming. The scope includes many niche analytics and advanced features that might be better grouped or omitted, as typical MCP servers for social media have 10-30 tools. This count feels excessive and could hinder usability.
The tool set provides complete coverage for Twitter operations, including CRUD for tweets, users, lists, and direct messages, along with advanced features like analytics, search, and engagement tracking. There are no obvious gaps; agents can perform all core and extended workflows without dead ends.
Maintenance
Related MCP Connectors
Publish and schedule tweets and threads on X (Twitter) from your AI assistant.
Hosted MCP server from TwitterAPI.io that gives AI agents read-only access to Twitter/X data. 12 tools: tweet search with X operators, user profiles, a user's latest tweets, followers and followings, replies, quotes, retweeters, mentions and trends. Connect at https://mcp.twitterapi.io/mcp with a TwitterAPI.io API key or account sign-in; usage is paid per result returned.
Twitter (X) data for agents: profiles, tweets, search, followers, lists. $0.0006 per call.
X/Twitter reads, search, monitors and posting. Pay-per-call in USDC โ no signup, no API keys.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceProvides AI agents with comprehensive Twitter functionality through the Model Context Protocol standard, enabling reading tweets, posting content, managing interactions, and accessing timeline data with robust error handling.14 npm21MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables AI models and applications to interact directly with Twitter/X, providing capabilities to create posts, reply to tweets, retrieve user data, and manage account actions.18 npm11MIT
- AlicenseBqualityDmaintenanceA Model Context Protocol server that enables AI agents to interact with Twitter without direct API access, supporting tweet operations, user interactions, and Grok AI integration.141,939 npm32MIT
- FlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables AI assistants to interact with Twitter functionality using cookie-based authentication, allowing for timeline access, tweet management, user information retrieval, and search capabilities.16-