Skip to main content
Glama
README.md
# grok2api-mcp

[![npm version](https://img.shields.io/npm/v/grok2api-mcp.svg)](https://www.npmjs.com/package/grok2api-mcp)
[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)
[![Node.js Version](https://img.shields.io/badge/node-%3E%3D18-green.svg)](https://nodejs.org/)

A Node.js/TypeScript-based **MCP (Model Context Protocol) Server** that provides an interface to the [Grok AI API](https://x.ai/) (X/Twitter's AI model). This server runs over stdio and acts as a bridge between MCP clients (like Claude Desktop) and Grok's OpenAI-compatible API endpoints.

[中文文档](./README_CN.md)

## Features

- **X Search** - Search and summarize X (Twitter) content using Grok
- **General Search** - General web search and summarization
- **Image Generation** - Generate images via Grok's image API
- **Video Generation** - Generate videos via Grok's video API

## Requirements

- Node.js >= 18
- Grok API access (API token from X.AI)

## Installation

### Quick Start with npx

```bash
npx grok2api-mcp
```

### Global Installation

```bash
npm install -g grok2api-mcp
grok2api-mcp
```

### From Source

```bash
git clone https://github.com/1WorldCapture/grok2api-mcp.git
cd grok2api-mcp
npm install
npm run build
```

## Configuration

### Required Environment Variables

| Variable | Description |
|----------|-------------|
| `GROK_BASE_URL` | Grok API base URL (e.g., `https://api.x.ai`) |
| `GROK_API_TOKEN` | Your Grok API authentication token |

### Optional Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `GROK_REQUEST_TIMEOUT_MS` | `120000` | Global request timeout (ms) |
| `GROK_X_SEARCH_TIMEOUT_MS` | (global) | Timeout for x_search tool |
| `GROK_GENERAL_SEARCH_TIMEOUT_MS` | (global) | Timeout for general_search tool |
| `GROK_IMAGE_TIMEOUT_MS` | (global) | Timeout for image_generation tool |
| `GROK_VIDEO_TIMEOUT_MS` | (global) | Timeout for video_generation tool |
| `GROK_SEARCH_MODEL` | `grok-4.20-beta` | Model for search tools |
| `GROK_IMAGE_MODEL` | `grok-imagine-1.0` | Model for image generation |
| `GROK_VIDEO_MODEL` | `grok-imagine-1.0-video` | Model for video generation |

### Base URL Notes

The `GROK_BASE_URL` supports the following formats:

- `https://api.example.com`
- `https://api.example.com/v1`
- `https://api.example.com/proxy`
- `https://api.example.com/proxy/v1`

The server automatically handles `/v1` path normalization to avoid duplicate path segments.

## Usage

### Running the Server

```bash
GROK_BASE_URL=https://api.x.ai GROK_API_TOKEN=your-token npx grok2api-mcp
```

### Development Mode

```bash
npm run dev
```

### Integration with Claude Desktop

Add the following to your Claude Desktop configuration file:

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

```json
{
  "mcpServers": {
    "grok": {
      "command": "npx",
      "args": ["-y", "grok2api-mcp"],
      "env": {
        "GROK_BASE_URL": "https://api.x.ai",
        "GROK_API_TOKEN": "your-api-token"
      }
    }
  }
}
```

Or with global installation:

```json
{
  "mcpServers": {
    "grok": {
      "command": "grok2api-mcp",
      "env": {
        "GROK_BASE_URL": "https://api.x.ai",
        "GROK_API_TOKEN": "your-api-token"
      }
    }
  }
}
```

## MCP Tools

### 1. x_search

Search and summarize X (Twitter) content.

- **Model**: `grok-4.20-beta` (default)
- **Endpoint**: `POST /v1/chat/completions`
- **Stream**: disabled (`stream=false`)

### 2. general_search

Perform general web search and summarization.

- **Model**: `grok-4.20-beta` (default)
- **Endpoint**: `POST /v1/chat/completions`
- **Stream**: disabled (`stream=false`)

### 3. image_generation

Generate images using Grok's image generation API.

- **Model**: `grok-imagine-1.0` (default)
- **Endpoint**: `POST /v1/images/generations`
- **Stream**: disabled (`stream=false`)

### 4. video_generation

Generate videos using Grok's video generation API.

- **Model**: `grok-imagine-1.0-video` (default)
- **Endpoint**: `POST /v1/chat/completions`
- **Stream**: disabled (`stream=false`)

## Project Structure

```
grok2api-mcp/
├── src/
│   ├── index.ts        # Main entry point - MCP server setup
│   ├── config.ts       # Environment variable loading and validation
│   ├── tools.ts        # MCP tool definitions and handlers
│   ├── grokClient.ts   # Grok API client wrapper
│   ├── httpClient.ts   # HTTP client with timeout/abort handling
│   ├── errors.ts       # Error types and normalization
│   ├── logger.ts       # Simple stderr logger
│   └── utils.ts        # Utility functions
├── dist/               # Compiled JavaScript output
├── package.json
├── tsconfig.json
└── README.md
```

## Architecture

```
MCP Client (stdio)
        │
        ▼
┌─────────────────────────────────────────┐
│  index.ts - MCP Server                  │
│  - ListToolsRequestSchema handler       │
│  - CallToolRequestSchema handler        │
└─────────────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────┐
│  tools.ts - Tool Definitions            │
│  - Zod schema validation                │
│  - x_search, general_search, etc.       │
└─────────────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────┐
│  grokClient.ts - Grok API Client        │
│  - chatCompletions()                    │
│  - imageGenerations()                   │
└─────────────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────┐
│  httpClient.ts - HTTP Client            │
│  - Bearer token auth                    │
│  - Timeout & AbortController            │
│  - URL path normalization               │
└─────────────────────────────────────────┘
```

## Error Handling

- **Parameter Validation**: All tool arguments are validated with Zod schemas
- **Unified HTTP Client**: Single client handles timeouts, abort signals, and error normalization
- **Startup Validation**: Required environment variables are checked at startup
- **Rich Error Context**: Errors include timeout thresholds, URLs, elapsed time, and hints
- **SSE Detection**: Explicit error if server returns SSE instead of JSON

## Development

### Scripts

| Command | Description |
|---------|-------------|
| `npm run clean` | Remove dist directory |
| `npm run build` | Clean and compile TypeScript |
| `npm run dev` | Development mode with hot reload |
| `npm start` | Run compiled server |

### Build

```bash
npm run build
```

## Dependencies

- [@modelcontextprotocol/sdk](https://www.npmjs.com/package/@modelcontextprotocol/sdk) - Official MCP SDK
- [zod](https://www.npmjs.com/package/zod) - Runtime type validation

## License

[ISC](LICENSE)

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

TDQS

B3/5.0

Scored across 4 tools

Disambiguation4/5

The four tools cover distinct modalities: X search, general search, image generation, and video generation. The two search tools could be slightly confused when a query spans X and the broader web, but the descriptions make the intended source clear.

Naming Consistency5/5

All tool names use consistent snake_case with a clear [scope/modality]_[action] pattern: x_search, general_search, image_generation, video_generation. The convention is predictable across the whole set.

Tool Count5/5

Four tools is well-scoped for this API wrapper, with each tool representing a distinct capability. There is no obvious bloat or missing basic operation in the count itself.

Completeness3/5

The surface covers search plus image/video generation, but there are notable gaps: no general text/chat completion tool and no explicit status or retrieval operation for potentially asynchronous video generation. These gaps could force workarounds for some workflows.