Twitter/X MCP Server

Twitter/X MCP Server

Connects AI assistants to Twitter/X using cookie-based authentication to read timelines, search tweets, and perform actions like posting and liking. It leverages Twitter's internal GraphQL API to provide full functionality without requiring a developer account.

Category
访问服务器

README

Twitter/X MCP Server

A Model Context Protocol (MCP) server that connects AI assistants to Twitter/X using cookie-based authentication. Provides 12 tools for reading timelines, searching tweets, posting, liking, retweeting, and more — all through Twitter's internal GraphQL API.

Built with TypeScript, @modelcontextprotocol/sdk, and Zod for runtime validation.


Table of Contents


Features

  • Full Twitter access — Read timelines, search, view profiles, post tweets, like, retweet, reply
  • Cookie-based auth — No Twitter Developer account or OAuth app required
  • Anti-bot bypass — Write operations use Puppeteer with stealth plugin to bypass Twitter's automation detection
  • Dual-engine — Fast HTTP for reads, headless browser for writes
  • Clean responses — Deeply nested Twitter GraphQL responses are parsed into simple, readable JSON
  • Type-safe — Written in strict TypeScript with Zod schema validation on all tool inputs
  • Auto ct0 refresh — CSRF tokens are refreshed transparently when Twitter rotates them
  • MCP standard — Works with any MCP-compatible client (Claude Desktop, Claude Code, etc.)

Prerequisites

  • Node.js >= 18.0.0
  • npm >= 8.0.0
  • A Twitter/X account with an active session in your browser

Installation

# Clone the repository
git clone https://github.com/aditya-ai-architect/twitter-mcp.git
cd twitter-mcp

# Install dependencies
npm install

# Build
npm run build

Getting Your Twitter Cookies

The server authenticates using two cookies from your logged-in Twitter session. Here's how to extract them:

  1. Open x.com in your browser and log in
  2. Open Developer Tools (F12 or Ctrl+Shift+I)
  3. Go to the Application tab (Chrome/Edge) or Storage tab (Firefox)
  4. In the left sidebar, expand Cookies and click on https://x.com
  5. Find and copy these two cookie values:
Cookie Description
auth_token Your session authentication token
ct0 CSRF protection token

Important: Both cookies must come from the same active session. If you log out or the session expires, you'll need to extract fresh cookies.


Configuration

Claude Desktop

Add the server to your Claude Desktop config file:

Windows: %APPDATA%\Claude\claude_desktop_config.json macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "twitter": {
      "command": "node",
      "args": ["/absolute/path/to/twitter-mcp/build/index.js"],
      "env": {
        "TWITTER_AUTH_TOKEN": "your_auth_token_here",
        "TWITTER_CT0": "your_ct0_here"
      }
    }
  }
}

Claude Code (CLI)

Add to your Claude Code MCP settings (.claude/settings.json or via claude mcp add):

claude mcp add twitter -- node /absolute/path/to/twitter-mcp/build/index.js

Then set the environment variables before launching, or use a .env file in the project directory.

Environment Variables

Variable Required Description
TWITTER_AUTH_TOKEN Yes The auth_token cookie from your Twitter session
TWITTER_CT0 Yes The ct0 CSRF cookie from your Twitter session

You can also create a .env file in the project root:

TWITTER_AUTH_TOKEN=your_auth_token_here
TWITTER_CT0=your_ct0_here

Tools Reference

Read Operations

get_home_timeline

Fetch tweets from the authenticated user's home timeline.

Parameter Type Default Description
count number 20 Number of tweets to fetch (1-100)

get_user_profile

Get a Twitter user's profile information by their username.

Parameter Type Description
username string Twitter username without the @ symbol

get_user_tweets

Get recent tweets posted by a specific user.

Parameter Type Default Description
username string Twitter username without @
count number 20 Number of tweets to fetch (1-100)

get_tweet

Get a single tweet by its ID.

Parameter Type Description
tweet_id string The tweet ID

search_tweets

Search for tweets matching a query. Supports Twitter search operators (from:, to:, has:, filter:, etc.).

Parameter Type Default Description
query string Search query string
count number 20 Number of results (1-100)

Search operator examples:

  • from:elonmusk — tweets from a specific user
  • to:openai — tweets directed at a user
  • "exact phrase" — exact phrase match
  • has:media — tweets containing media
  • filter:links — tweets containing links
  • lang:en — filter by language
  • since:2024-01-01 until:2024-12-31 — date range

get_trends

Get current trending topics on Twitter. Takes no parameters.


Write Operations

post_tweet

Post a new tweet. Can also reply to an existing tweet.

Parameter Type Description
text string Tweet text (1-280 characters)
reply_to_tweet_id string? Optional tweet ID to reply to

like_tweet

Like a tweet by its ID.

Parameter Type Description
tweet_id string The tweet ID to like

unlike_tweet

Remove a like from a tweet.

Parameter Type Description
tweet_id string The tweet ID to unlike

retweet

Retweet a tweet by its ID.

Parameter Type Description
tweet_id string The tweet ID to retweet

unretweet

Remove a retweet.

Parameter Type Description
tweet_id string The tweet ID to unretweet

reply_to_tweet

Reply to a specific tweet.

Parameter Type Description
tweet_id string The tweet ID to reply to
text string Reply text (1-280 characters)

Response Formats

All tools return clean, parsed JSON instead of raw Twitter GraphQL responses.

Tweet Object

{
  "id": "1234567890",
  "text": "Hello world!",
  "author": {
    "id": "9876543210",
    "username": "johndoe",
    "name": "John Doe",
    "profile_image_url": "https://pbs.twimg.com/...",
    "verified": true
  },
  "created_at": "Mon Jan 27 12:00:00 +0000 2025",
  "likes": 42,
  "retweets": 12,
  "replies": 5,
  "quotes": 3,
  "bookmarks": 7,
  "views": 1500,
  "language": "en",
  "conversation_id": "1234567890",
  "media": [
    {
      "type": "photo",
      "url": "https://pbs.twimg.com/media/...",
      "preview_url": "https://pbs.twimg.com/media/..."
    }
  ]
}

User Profile Object

{
  "id": "9876543210",
  "username": "johndoe",
  "name": "John Doe",
  "description": "Software engineer & builder",
  "profile_image_url": "https://pbs.twimg.com/...",
  "profile_banner_url": "https://pbs.twimg.com/...",
  "followers_count": 1500,
  "following_count": 300,
  "tweet_count": 4200,
  "verified": true,
  "created_at": "Tue Mar 15 00:00:00 +0000 2020",
  "location": "San Francisco, CA",
  "url": "https://example.com"
}

Trend Item Object

{
  "name": "#TrendingTopic",
  "tweet_count": 125000,
  "description": "125K posts",
  "domain": "Technology"
}

Development

# Watch mode — recompiles on file changes
npm run dev

# Build once
npm run build

# Run directly (requires env vars)
npm start

# Test with MCP Inspector
npx @modelcontextprotocol/inspector node build/index.js

Project Structure

twitter-mcp/
├── src/
│   ├── index.ts              # MCP server entry, tool registration
│   ├── twitter-client.ts     # Twitter API client, auth, request/response handling
│   └── types.ts              # TypeScript interfaces (Tweet, UserProfile, TrendItem)
├── build/                    # Compiled JavaScript output
├── package.json
├── tsconfig.json
├── .env.example
└── .gitignore

Architecture

┌─────────────────┐     stdio      ┌─────────────────┐
│   MCP Client    │ ◄────────────► │  twitter-mcp    │
│ (Claude, etc.)  │   JSON-RPC     │  MCP Server     │
└─────────────────┘                └────────┬────────┘
                                            │
                              ┌─────────────┴─────────────┐
                              │                           │
                      ┌───────▼───────┐          ┌────────▼────────┐
                      │  undici HTTP  │          │   Puppeteer +   │
                      │  (Read ops)   │          │   Stealth       │
                      │  Fast, direct │          │   (Write ops)   │
                      └───────┬───────┘          └────────┬────────┘
                              │                           │
                              └─────────────┬─────────────┘
                                            │
                                   ┌────────▼────────┐
                                   │   x.com API     │
                                   │   (GraphQL)     │
                                   └─────────────────┘

How it works:

The server uses a dual-engine approach to handle Twitter's anti-bot detection:

  • Read operations (timeline, search, profiles) use fast direct HTTP requests via undici — no browser needed
  • Write operations (post, like, retweet, reply) use a headless Puppeteer browser with the stealth plugin to bypass Twitter's automation detection (error 226)

The stealth browser launches lazily on the first write call and stays alive for subsequent operations.

Authentication:

  • Cookies (auth_token + ct0) are set on the browser session and HTTP client
  • ct0 is automatically refreshed when Twitter rotates it
  • CSRF mismatches are detected and retried transparently

Troubleshooting

"Missing required environment variables"

Both TWITTER_AUTH_TOKEN and TWITTER_CT0 must be set. Double-check your Claude Desktop config or .env file.

HTTP 401 / 403 errors

Your cookies have expired. Extract fresh cookies from your browser following the instructions above.

HTTP 429 errors

You've hit Twitter's rate limit. Wait a few minutes before trying again. Different endpoints have different rate limits.

Empty responses / no tweets returned

Twitter occasionally changes GraphQL query IDs when deploying updates. The hardcoded query IDs in src/twitter-client.ts may need to be refreshed. You can extract current query IDs from Twitter's web client JavaScript bundles using browser DevTools (Network tab → filter by graphql).

Error 226 "This request looks like it might be automated"

Write operations use a stealth Puppeteer browser to bypass this. If you still see this error, your account may have temporary restrictions — try posting manually once from your browser, then retry.

Browser launch failures

The first write operation launches a Chromium browser. Ensure you have enough memory and that Puppeteer's bundled Chromium was downloaded during npm install. On Linux servers, you may need additional system libraries — see Puppeteer troubleshooting.

Server won't start in Claude Desktop

  • Ensure the path in your config uses absolute paths
  • On Windows, use forward slashes (C:/Users/...) or escaped backslashes (C:\\Users\\...)
  • Check Claude Desktop logs for error messages

Disclaimer

This server uses Twitter's internal, undocumented GraphQL API through cookie-based session authentication. This is not the official Twitter API.

  • Twitter may change endpoints, query IDs, or authentication requirements at any time
  • Automated use of Twitter via cookies may violate Twitter's Terms of Service
  • Use at your own risk and responsibility
  • This project is intended for personal use and educational purposes

License

ISC

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选