Skip to main content
Glama
stat-guy

Enhanced Grok Search MCP Server

by stat-guy

Enhanced Grok Search MCP Server

A robust MCP (Model Context Protocol) server that provides comprehensive web search and analysis capabilities using xAI's Grok API.

Features

🔍 Search Capabilities

  • Web Search: Search general web content using Grok's AI-powered search

  • News Search: Search for recent news and current events with timeline analysis

  • Twitter/X Search: Search social media posts with sentiment analysis

  • Date Range Filtering: Search within specific time periods

📊 Analysis Modes

  • Basic Mode: Traditional search results with titles, snippets, and URLs

  • Comprehensive Mode: Rich analysis including:

    • Detailed timelines of events

    • Direct quotes with full attribution

    • Multiple perspectives and viewpoints

    • Historical context and implications

    • Fact verification status

    • Key findings categorization

🛡️ Reliability Features

  • Retry Logic: Automatic retry with exponential backoff for failed requests

  • Request Timeouts: Configurable timeouts to prevent hanging

  • Graceful Error Handling: Comprehensive error responses with detailed context

  • Health Monitoring: Built-in health checks and performance metrics

  • Caching: Intelligent caching for comprehensive analyses

  • Input Validation: Enhanced sanitization and validation of all inputs

🔧 Technical Features

  • NPX Compatible: Easy installation and usage via NPX

  • MCP Protocol: Full compatibility with MCP clients like Claude Desktop

  • Structured Logging: Comprehensive logging for debugging and monitoring

  • Performance Metrics: Request tracking and success rate monitoring

Related MCP server: Grok MCP Server

Installation

Simple 3-Step Process

git clone https://github.com/stat-guy/grok-search-mcp.git
cd grok-search-mcp
npm install -g .

Verify Installation

Test that the installation worked:

npx grok-search-mcp --help

Success indicator: If you see Grok Search MCP Server running on stdio, your installation is ready!

Alternative: NPX Usage

npx grok-search-mcp

Setup

1. Get Your xAI API Key

  1. Visit the xAI Developer Portal

  2. Create an account or sign in

  3. Generate your API key

  4. Copy the API key for the next step

2. Configure Environment Variable

Set your xAI API key as an environment variable:

export XAI_API_KEY="your-api-key-here"

Or create a .env file in your project:

XAI_API_KEY=your-api-key-here

3. Configure Claude Desktop

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": {
    "grok-search": {
      "command": "npx",
      "args": ["grok-search-mcp"],
      "env": {
        "XAI_API_KEY": "your-api-key-here"
      }
    }
  }
}

Available Tools

General-purpose search tool with configurable search types and analysis modes.

Parameters:

  • query (required): The search query

  • search_type (optional): "web", "news", or "general" (default: "web")

  • analysis_mode (optional): "basic" or "comprehensive" (default: "basic")

  • max_results (optional): Maximum number of results (1-20, default: 10)

  • from_date (optional): Start date in YYYY-MM-DD format

  • to_date (optional): End date in YYYY-MM-DD format

Basic Mode Example:

{
  "query": "latest AI developments",
  "search_type": "news",
  "max_results": 5
}

Comprehensive Mode Example:

{
  "query": "US Iran conflict 2025",
  "search_type": "news",
  "analysis_mode": "comprehensive",
  "max_results": 10,
  "from_date": "2025-06-20",
  "to_date": "2025-06-24"
}

Search general web content with comprehensive analysis support.

Parameters:

  • query (required): The web search query

  • analysis_mode (optional): "basic" or "comprehensive" (default: "basic")

  • max_results (optional): Maximum number of results (1-20, default: 10)

  • from_date (optional): Start date in YYYY-MM-DD format

  • to_date (optional): End date in YYYY-MM-DD format

Search for recent news with comprehensive timeline and context analysis.

Parameters:

  • query (required): The news search query

  • analysis_mode (optional): "basic" or "comprehensive" (default: "basic")

  • max_results (optional): Maximum number of results (1-20, default: 10)

  • from_date (optional): Start date in YYYY-MM-DD format

  • to_date (optional): End date in YYYY-MM-DD format

grok_twitter

Search Twitter/X posts with social media analysis.

Parameters:

  • query (required): The search query for tweets

  • handles (optional): Array of Twitter handles to filter by (without @ symbol)

  • analysis_mode (optional): "basic" or "comprehensive" (default: "basic")

  • max_results (optional): Maximum number of results (1-20, default: 10)

  • from_date (optional): Start date in YYYY-MM-DD format

  • to_date (optional): End date in YYYY-MM-DD format

health_check

Check server health and API connectivity status.

Parameters: None

Response Formats

Basic Mode Response

{
  "query": "search query",
  "analysis_mode": "basic",
  "results": [
    {
      "title": "Result Title",
      "snippet": "Brief description or excerpt",
      "url": "https://example.com",
      "source": "source-name",
      "published_date": "2025-06-24",
      "author": "Author Name",
      "citation_url": "https://example.com",
      "citation_metadata": {
        "domain": "example.com",
        "is_secure": true
      }
    }
  ],
  "citations": ["https://example.com"],
  "summary": "Brief overview of findings",
  "total_results": 5,
  "search_time": "2025-06-24T12:00:00.000Z",
  "source": "grok-live-search"
}

Comprehensive Mode Response

{
  "query": "search query",
  "analysis_mode": "comprehensive",
  "comprehensive_analysis": "Detailed analysis with context and implications...",
  "key_findings": [
    {
      "category": "main_story",
      "title": "Primary Development",
      "content": "Detailed explanation with specifics",
      "sources": ["https://source1.com", "https://source2.com"],
      "confidence": "high"
    }
  ],
  "timeline": [
    {
      "date": "2025-06-21",
      "event": "Initial event occurred",
      "source": "News Source",
      "significance": "This marked the beginning of..."
    }
  ],
  "direct_quotes": [
    {
      "quote": "This is an exact quote from the source",
      "speaker": "Official Name",
      "context": "During a press conference on Monday",
      "source_url": "https://source.com",
      "significance": "This statement clarifies the position..."
    }
  ],
  "related_context": "Historical background and connections...",
  "multiple_perspectives": [
    {
      "viewpoint": "Supporters",
      "content": "Analysis from this perspective",
      "sources": ["https://supporting-source.com"],
      "reasoning": "This group supports because..."
    }
  ],
  "implications": {
    "short_term": "Immediate consequences include...",
    "long_term": "Potential long-term impacts are...",
    "stakeholders_affected": ["Group 1", "Group 2"]
  },
  "verification_status": {
    "confirmed_facts": ["Verified information"],
    "unconfirmed_claims": ["Unverified claims"],
    "contradictory_information": ["Conflicting reports"]
  },
  "raw_results": [
    {
      "title": "Source Article",
      "snippet": "Brief description",
      "url": "https://example.com",
      "relevance_score": 9
    }
  ],
  "summary": "Executive summary of the entire analysis",
  "total_results": 10,
  "search_time": "2025-06-24T12:00:00.000Z",
  "source": "grok-comprehensive-analysis"
}

Configuration

Environment Variables

  • XAI_API_KEY (required): Your xAI API key

  • GROK_TIMEOUT (optional): Request timeout in milliseconds (default: 30000)

  • GROK_MAX_RETRIES (optional): Maximum retry attempts (default: 3)

Claude Desktop Configuration Example

{
  "mcpServers": {
    "grok-search": {
      "command": "npx",
      "args": ["grok-search-mcp"],
      "env": {
        "XAI_API_KEY": "your-api-key-here",
        "GROK_TIMEOUT": "45000",
        "GROK_MAX_RETRIES": "5"
      }
    }
  }
}

Error Handling

The server includes comprehensive error handling with standardized error responses:

  • Invalid API Key: Graceful degradation with clear error messages

  • Empty Query: Enhanced validation with detailed feedback

  • API Rate Limits: Automatic retry with exponential backoff

  • Network Issues: Connection error handling with retry logic

  • Timeout Issues: Configurable timeouts with clear error reporting

  • JSON Parsing: Multiple parsing strategies with fallback handling

Error Response Format

{
  "error": "Detailed error message",
  "status": "failed",
  "query": "original query",
  "search_type": "web",
  "analysis_mode": "basic",
  "timestamp": "2025-06-24T12:00:00.000Z",
  "request_id": "req_1234567890_abc123"
}

Performance Features

Caching

  • Comprehensive Analysis Caching: Intelligent caching for expensive comprehensive analyses

  • TTL Management: Configurable cache expiration (default: 30 minutes)

  • Memory Management: Automatic cache size limits to prevent memory issues

Monitoring

  • Health Checks: Built-in health monitoring with detailed status reporting

  • Performance Metrics: Request tracking, success rates, and timing analysis

  • Structured Logging: JSON-formatted logs for easy parsing and monitoring

Reliability

  • Retry Logic: Exponential backoff for transient failures

  • Circuit Breaking: Graceful degradation when API is unavailable

  • Input Sanitization: Comprehensive input validation and cleaning

  • Error Recovery: Multiple JSON parsing strategies for robust response handling

Troubleshooting

Common Issues

  1. "API service is not available"

    • Check if XAI_API_KEY is set correctly

    • Verify your API key is valid and active

    • Use the health_check tool to diagnose API connectivity

  2. "Request timeout after Xms"

    • Increase GROK_TIMEOUT environment variable

    • Check your internet connection

    • Consider using basic mode for faster responses

  3. "Search query too long"

    • Queries are limited to 1000 characters

    • Break down complex queries into smaller parts

  4. Empty or poor results in comprehensive mode

    • Try different query phrasings

    • Use basic mode for simple searches

    • Check if the topic has sufficient recent coverage

Health Monitoring

Use the health_check tool to get detailed status:

{
  "tool": "health_check"
}

Example health response:

{
  "server_healthy": true,
  "api_healthy": true,
  "uptime_ms": 3600000,
  "total_requests": 150,
  "error_count": 3,
  "success_rate": "98.00%",
  "api_details": {
    "hasApiKey": true,
    "cacheSize": 12
  }
}

Debugging

The server provides structured logging. Monitor stderr output for detailed logs:

npx grok-search-mcp 2>debug.log

Testing

Run the test suite to verify functionality:

# With API key
XAI_API_KEY=your-key npm test

# Basic functionality test (may skip API calls)
npm test

Usage Examples

{
  "query": "latest technology news",
  "search_type": "news",
  "max_results": 5
}

Comprehensive Analysis

{
  "query": "climate change policy 2025",
  "analysis_mode": "comprehensive",
  "search_type": "news",
  "from_date": "2025-01-01",
  "max_results": 15
}

Twitter Analysis with Specific Handles

{
  "query": "AI developments",
  "handles": ["elonmusk", "OpenAI", "AnthropicAI"],
  "analysis_mode": "comprehensive",
  "max_results": 10
}
{
  "query": "quantum computing breakthroughs",
  "search_type": "web",
  "from_date": "2025-06-01",
  "to_date": "2025-06-24",
  "max_results": 8
}

API Limits

  • Rate limits depend on your xAI API plan

  • Monitor usage through the xAI Developer Portal

  • Comprehensive mode uses more tokens than basic mode

  • Caching helps reduce API usage for repeated queries

License

This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.

Support

For issues and feature requests, please create an issue in the repository.

Contributing

  1. Fork the repository

  2. Create a feature branch

  3. Make your changes

  4. Add tests for new functionality

  5. Update documentation

  6. Submit a pull request

Changelog

Version 2.0.0 (Enhanced)

  • ✅ Added comprehensive analysis mode with rich context

  • ✅ Implemented timeline extraction and direct quotes

  • ✅ Added multiple perspectives analysis

  • ✅ Enhanced error handling with retry logic

  • ✅ Added intelligent caching for comprehensive analyses

  • ✅ Implemented health monitoring and performance metrics

  • ✅ Added structured logging system

  • ✅ Enhanced input validation and sanitization

  • ✅ Added configurable timeouts and retry settings

  • ✅ Improved JSON parsing with multiple fallback strategies

Available Tools

5 tools
grok_twitterC

Search Twitter/X posts using Grok's X search capabilities, optionally filtered by specific handles. Comprehensive mode analyzes social media trends and sentiment.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYesThe search query to find tweets/posts about
handlesNoOptional list of Twitter handles to search from (without @ symbol, e.g., ['elonmusk', 'twitter'])
analysis_modeNoAnalysis mode: 'basic' returns simple search results, 'comprehensive' provides detailed analysis with timelines, quotes, multiple perspectives, and contextbasic
max_resultsNoMaximum number of tweet results to return
from_dateNoOptional start date for search in ISO8601 format (YYYY-MM-DD). Limits search to content from this date onwards.
to_dateNoOptional end date for search in ISO8601 format (YYYY-MM-DD). Limits search to content up to this date.

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions 'comprehensive mode analyzes social media trends and sentiment' which adds some behavioral context, but doesn't address critical aspects like rate limits, authentication requirements, data freshness, or what happens when no results are found. The description is insufficient for a search tool with 6 parameters.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately concise with two sentences. The first sentence states the core functionality, and the second adds important context about the comprehensive mode. However, the second sentence could be more tightly integrated with the first for better flow.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a search tool with 6 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what the tool returns (tweet objects, analysis results, error conditions), doesn't mention pagination or result format, and provides minimal behavioral context. The comprehensive mode mention helps but doesn't compensate for the overall gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all 6 parameters thoroughly. The description mentions 'optionally filtered by specific handles' and 'comprehensive mode analyzes social media trends and sentiment', which adds minor context about the 'handles' and 'analysis_mode' parameters, but doesn't provide significant value beyond what's already in the schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Search Twitter/X posts using Grok's X search capabilities' with optional filtering. It specifies the verb ('search') and resource ('Twitter/X posts'), but doesn't explicitly differentiate from sibling tools like 'grok_search' or 'grok_web_search' beyond mentioning 'Twitter/X' specifically.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description mentions 'comprehensive mode analyzes social media trends and sentiment' which implies some usage context, but provides no explicit guidance on when to use this tool versus alternatives like 'grok_search' or 'grok_web_search'. There's no mention of prerequisites, limitations, or comparative scenarios.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

health_checkB

Check the health status of the Grok Search MCP server and API connectivity

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.2/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden. It mentions checking 'health status' and 'API connectivity' but doesn't disclose behavioral traits like what specific metrics are returned, whether it performs active tests or passive checks, expected response format, or potential side effects. The description is functional but lacks operational transparency needed for informed tool selection.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that clearly communicates the core purpose without any wasted words. It's appropriately sized for a simple health check tool and front-loads the essential information. Every word earns its place in conveying what the tool does.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (0 parameters, no output schema), the description is reasonably complete for understanding its basic purpose. However, without annotations or output schema, it doesn't provide enough information about what health data is returned or how to interpret results. For a diagnostic tool, users need more context about expected outputs and success/failure indicators.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has 0 parameters with 100% schema description coverage, so the schema already fully documents the parameter situation. The description appropriately doesn't discuss parameters since none exist. It focuses correctly on the tool's purpose rather than attempting to describe non-existent inputs.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Check') and resource ('health status of the Grok Search MCP server and API connectivity'). It distinguishes itself from sibling tools like grok_search or grok_web_search by focusing on system health rather than data retrieval. However, it doesn't explicitly differentiate from all siblings (e.g., grok_news_search also involves checking/searching).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention scenarios like troubleshooting connectivity issues, verifying server availability before other operations, or whether it should be used proactively. With sibling tools focused on search functionality, there's no explicit comparison or exclusion criteria provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 5 tool updatesv1.0.0
    • First observedgrok_news_search
    • First observedgrok_search
    • First observedgrok_twitter
    • First observedgrok_web_search
    • First observedhealth_check

TDQS

B3/5.0

Scored across 5 tools

Disambiguation2/5

Multiple tools have overlapping purposes that could cause confusion. grok_search, grok_web_search, and grok_news_search all perform web searches with similar comprehensive analysis modes, making it difficult for an agent to choose the right tool. Only grok_twitter and health_check have clearly distinct functions.

Naming Consistency4/5

The naming follows a consistent snake_case pattern with a 'grok_' prefix for most tools, which is predictable and readable. The only deviation is health_check, which lacks the prefix but maintains the same naming style, keeping the set mostly consistent.

Tool Count3/5

With 5 tools, the count is reasonable for a search-focused server, but it feels borderline due to redundancy. The set could be streamlined without losing functionality, as multiple tools cover similar search domains, making the number slightly heavy for the apparent scope.

Completeness3/5

The server covers news, web, and Twitter search with health monitoring, but there are notable gaps. For a search domain, missing tools for filtering, saving results, or handling advanced queries limit agent workflows. The surface is functional but incomplete for comprehensive search operations.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    Enables real-time search of X.com (Twitter) posts, users, threads, and trends via xAI's Grok API, directly from Claude.
    5
    3
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Live X (Twitter) and web search for any coding agent through your existing Grok subscription. Exposes a grok_search MCP tool, so no X API key or X developer account is needed.
    21 npm
    28
    Apache 2.0
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables real-time web and Twitter/X search via Grok, returning structured results with source URLs, confidence scores, and key points. Supports multiple output modes, language options, and time range filtering.
    19 npm
    4
    MIT

Appeared in Searches