mcp-x-query
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
mcp-x-query
A Model Context Protocol (MCP) server that gives AI assistants real-time access to Twitter/X data through the Grok API.
Connect this server to Claude Desktop (or any MCP-compatible host) and ask questions like:
"What did @sama tweet this week?"
"Show me the full thread starting from this tweet."
"What's trending in tech right now?"
"Find tweets about the latest GPT release."
Table of Contents
Related MCP server: x-mcp-server
Features
Tool | Description |
| Retrieve a single tweet by ID or URL — images/videos auto-analyzed by Grok Vision |
| Get replies to a tweet, sorted by engagement, with optional date range |
| Recent tweets from a user, with optional date range and media enrichment |
| Full profile: bio, followers, pinned tweet, etc. |
| Full-text search with Twitter operators, date range, and media enrichment |
| Full conversation thread reconstructed from any tweet |
| Current trending topics, optionally filtered by category and country |
| Sentiment analysis on a corpus of tweets (by query or account, with language filter) |
| Full analysis of a thread: sentiment, key arguments, summary |
| Extract and summarize all external links shared by an account |
| Tweets from other accounts mentioning a user, with optional date range |
| Tweets from a Twitter/X list by ID or URL, with optional date range, pagination cursor, and media enrichment |
Prerequisites
Node.js 20 or later (
.nvmrcprovided)An xAI API key (starts with
xai-)
Installation
git clone https://github.com/IvyNotFound/mcp-x-query.git
cd mcp-x-query
npm install
npm run buildConfiguration
Copy the environment template and add your API key:
cp .env.example .env
# Edit .env and set XAI_API_KEY=xai-...The server reads XAI_API_KEY from the environment at startup and exits immediately if it is missing.
Available Tools
get_tweet
Retrieves a single tweet with full metadata (media, quoted tweet, engagement metrics).
When the tweet contains images, videos, or GIFs, each media item is automatically analyzed by Grok Vision (grok-2-vision-1212) and enriched with a media_summary field describing the visual content.
Parameter | Type | Required | Description |
| string | Yes | Tweet ID or full x.com / twitter.com URL |
get_tweet_replies
Returns the most-engaged replies to a tweet, optionally filtered by date.
Parameter | Type | Required | Description |
| string | Yes | Tweet ID or URL |
| number | No | 1–100, default 10 |
| string | No | YYYY-MM-DD |
| string | No | YYYY-MM-DD |
get_user_tweets
Fetches a user's recent tweets and retweets (newest first). Pass enrich_media: true to have each media item analyzed by Grok Vision (increases latency).
Parameter | Type | Required | Description |
| string | Yes | Handle with or without |
| number | No | 1–100, default 10 |
| string | No | YYYY-MM-DD |
| string | No | YYYY-MM-DD |
| boolean | No |
|
get_user_profile
Returns full profile information including bio, counters, and pinned tweet.
Parameter | Type | Required | Description |
| string | Yes | Handle with or without |
search_tweets
Full-text search supporting Twitter search operators (from:, to:, -is:retweet, lang:, #hashtag, etc.). Pass enrich_media: true for Grok Vision analysis of each media item.
Parameter | Type | Required | Description |
| string | Yes | Search query |
| number | No | 1–100, default 10 |
| string | No | YYYY-MM-DD |
| string | No | YYYY-MM-DD |
| boolean | No |
|
get_thread
Reconstructs a full conversation thread from any tweet in the chain (root, mid-thread, or leaf).
Parameter | Type | Required | Description |
| string | Yes | Any tweet in the thread |
| number | No | 1–50, default 20 |
| boolean | No |
|
get_trending
Returns currently trending topics on Twitter/X. Results are cached for 5 minutes to avoid redundant API calls.
Parameter | Type | Required | Description |
| string | No | e.g. |
| string | No | e.g. |
analyze_sentiment
Performs sentiment analysis on a corpus of tweets retrieved via a search query or from a specific account. Returns a breakdown (positive/negative/neutral percentages), top themes, and notable tweets.
Parameter | Type | Required | Description |
| string | Yes | Search query (Twitter operators supported) |
| string | No | Restrict analysis to tweets from this account (with or without |
| number | No | 1–100, default 30 |
| string | No | YYYY-MM-DD |
| string | No | YYYY-MM-DD |
| string | No | BCP-47 language code filter (e.g. |
analyze_thread
Reconstructs a full thread then produces a structured analysis: overall sentiment, key arguments made by each participant, a summary, and notable quotes.
Parameter | Type | Required | Description |
| string | Yes | Any tweet in the thread |
| number | No | 1–50, default 20 |
extract_links
Extracts all external URLs shared by a Twitter account (or matching a search query) and returns each link with its title, domain, and a brief summary of the shared content.
Parameter | Type | Required | Description |
| string | Yes | Handle with or without |
| number | No | 1–100, default 50 |
| string | No | YYYY-MM-DD |
| string | No | YYYY-MM-DD |
get_user_mentions
Returns tweets from other accounts that mention a given user. Useful for monitoring brand mentions, replies from the community, or tracking conversations around a specific handle.
Parameter | Type | Required | Description |
| string | Yes | Handle to find mentions for (with or without |
| number | No | 1–100, default 10 |
| string | No | YYYY-MM-DD |
| string | No | YYYY-MM-DD |
get_list_tweets
Fetches recent tweets from a Twitter/X list. Accepts a numeric list ID or a full list URL (https://x.com/i/lists/<ID>). Supports pagination via cursor: the next_cursor field in the response is the ID of the oldest tweet on the page — pass it as cursor in the next call to fetch older tweets. Pass enrich_media: true to have each media item analyzed by Grok Vision (increases latency).
Parameter | Type | Required | Description |
| string | Yes | Numeric list ID (e.g. |
| number | No | 1–100, default 10 |
| string | No | YYYY-MM-DD |
| string | No | YYYY-MM-DD |
| string | No | Pagination cursor: |
| boolean | No |
|
Claude Desktop Setup
Add the server to your Claude Desktop configuration file:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"mcp-x-query": {
"command": "node",
"args": ["/absolute/path/to/mcp-x-query/dist/index.js"],
"env": {
"XAI_API_KEY": "xai-your-api-key-here"
}
}
}
}Restart Claude Desktop after saving the file.
Development
# Watch mode — recompiles on every file save
npm run dev
# Single build
npm run build
# Interactive MCP inspector (useful for manual tool testing)
npm run inspectorThe TypeScript source lives in src/. Compiled output goes to dist/ (gitignored).
Project Structure
src/
├── index.ts # MCP server entry point — tool registration & startup (12 tools)
├── lib/
│ ├── grok-client.ts # Grok API wrapper (OpenAI SDK + x_search tool, maxRetries: 3)
│ ├── errors.ts # Typed error hierarchy: GrokError, GrokAuthError, GrokRateLimitError
│ ├── utils.ts # Input helpers: URL→ID extraction, @ stripping, escapeForPrompt
│ └── cache.ts # TtlCache<K,V>: in-memory TTL cache (used by get_trending, get_user_profile)
├── schemas/
│ ├── tweet.ts # TweetSchema, ThreadSchema, TweetArraySchema, MediaSchema
│ ├── user.ts # UserProfileSchema
│ ├── trending.ts # TrendingTopicsSchema
│ ├── sentiment.ts # SentimentAnalysisSchema, SentimentBreakdownSchema, NotableTweetSchema
│ ├── thread-analysis.ts# ThreadAnalysisSchema
│ └── link-extract.ts # LinkExtractSchema, ExtractedLinkSchema
└── tools/ # One file per MCP tool
├── get-tweet.ts
├── get-tweet-replies.ts
├── get-user-profile.ts
├── get-user-tweets.ts
├── get-thread.ts
├── get-trending.ts
├── search-tweets.ts
├── analyze-sentiment.ts
├── analyze-thread.ts
├── extract-links.ts
├── get-user-mentions.ts
└── get-list-tweets.tsTesting
# Unit tests only — no API key required, runs in < 5 s
npm test
# Unit tests with coverage report (thresholds: lines 60%, functions 60%, branches 50%)
npm run test:coverage
# Integration tests — makes real Grok API calls (requires XAI_API_KEY in .env.test)
cp .env.test.example .env.test
# Edit .env.test and set XAI_API_KEY=xai-..., then:
npm run test:integration
# All tests (unit + integration)
npm run test:allTest types:
File | Type | Tests | Requires API key |
| Unit | 25 | No |
| Unit | 7 | No |
| Unit — MCP schema snapshots | 12 | No |
| Unit (mocked Grok client) | 89 | No |
| Integration — real Grok API calls | 8 | Yes |
Architecture
MCP Host (e.g. Claude Desktop)
│ stdio (JSON-RPC)
▼
src/index.ts ←── registers 12 tools, wraps errors via run()
│
▼
GrokClient.query() GrokClient.analyzeMedia()
(maxRetries: 3) (get_tweet only)
│ HTTPS │ HTTPS
▼ ▼
api.x.ai/v1 ── x_search ──▶ Twitter/X real-time data
api.x.ai/v1 ── chat/completions (grok-2-vision-1212) ──▶ media_summaryKey design decisions:
Schema-driven responses: Every tool uses a Zod schema to define the exact JSON shape.
GrokClientconverts it to JSON Schema (with$refStrategy: "none"to avoid$refnodes Grok rejects) and validates the parsed response viaschema.parse().Lean vs. verbose thread mode: Threads default to a minimal schema to stay within token limits. Pass
verbose: truewhen you need full metadata (capped at 10 tweets).Input normalisation:
extractTweetIdhandles both raw IDs and full URLs.sanitizeUsernamestrips leading@. All tools accept user-friendly input.Typed error hierarchy:
src/lib/errors.tsdefinesGrokError,GrokAuthError(401), andGrokRateLimitError(429). Therun()helper discriminates these for better log messages and always returns a valid MCP response shape.Media enrichment:
get_tweetperforms a second API call viaGrokClient.analyzeMedia()after fetching. For videos the thumbnail frame is used; for images/GIFs the direct URL. The call is fire-and-forget safe — failures are logged and silently skipped so the tweet is always returned.Single-call analysis tools:
analyze_sentiment,analyze_thread, andextract_linkseach use a singleclient.query()call —x_searchfetches and Grok analyses in the same inference step.
Security
Several hardening measures are built into the server to protect against common attack vectors:
Measure | Where | What it does |
API key validation |
| Rejects keys that don't match |
Prompt injection mitigation |
| Replaces |
Username sanitisation |
| Strips |
Tweet ID validation |
| Throws if the extracted ID is not purely numeric ( |
Input length cap | Zod schemas |
|
Date format validation | Zod schemas | All |
API timeouts |
|
|
Media domain whitelist |
|
|
TTL cache |
| Trending topics (5 min) and user profiles (10 min) are cached to reduce API surface area |
Contributing
See CONTRIBUTING.md.
License
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Live X/Twitter data: profiles, tweets, search, followers, lists and trends. 29 read-only tools.
Publish and schedule tweets and threads on X (Twitter) from your AI assistant.
Read public X (Twitter) data and verify follows, reposts, replies and quotes. 14 read-only tools.
X (formerly Twitter) posts, profiles, and search for AI agents. Free key, self-minted, no signup.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceSearch X (formerly Twitter) in real-time from your AI assistant using xAI's Grok API, with no X API account required.1,701 npmMIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with X (Twitter) API v2 for posting tweets, searching, liking, retweeting, and more through natural language.MIT
- AlicenseAqualityDmaintenanceEnables real-time search of X.com (Twitter) posts, users, threads, and trends via xAI's Grok API, directly from Claude.54MIT
- AlicenseNot gradedqualityDmaintenanceReal-time X/Twitter social intelligence for AI agents and developers, powered by Grok's live search capabilities.3MIT