Skip to main content
Glama
joemccann

xAI MCP Server

by joemccann

xAI MCP Server

A Model Context Protocol (MCP) server that brings xAI's Grok APIs to Claude Code. Generate images, chat with Grok, analyze images, search the web, and create videos—all from natural language prompts in your Claude Code session.

Features

Tool

Description

generate_image

Generate images using Grok Imagine

chat

Chat with Grok models (grok-3, grok-4, grok-3-mini)

analyze_image

Analyze and describe images with Grok Vision

live_search

Real-time web, news, and X/Twitter search

generate_video

Generate videos from text prompts

Related MCP server: grok-quorum-mcp

Prerequisites

  • Node.js 18.0.0 or higher

  • xAI API Key from x.ai/api

  • Claude Code installed

Installation

curl -fsSL https://raw.githubusercontent.com/joemccann/xai-mcp-server/main/install.sh | bash

This installs the server and automatically configures Claude Code. You'll be prompted for your xAI API key.

Option 2: npx from GitHub

No installation needed - runs directly from GitHub:

npx github:joemccann/xai-mcp-server

Option 3: npm Global Install

npm install -g @joemccann/xai-mcp-server

Option 4: Clone and Build

git clone https://github.com/joemccann/xai-mcp-server.git
cd xai-mcp-server
npm install

Configuration for Claude Code

Step 1: Get Your xAI API Key

  1. Go to x.ai/api

  2. Sign up or log in

  3. Create an API key

  4. Copy the key (starts with xai-)

Step 2: Configure Claude Code

Note: If you used the Quick Install (Option 1), this is already done for you.

Add the MCP server using the Claude CLI:

claude mcp add xai -e XAI_API_KEY=xai-your-key-here -- node ~/.xai-mcp-server/dist/index.js

For nvm users, use the absolute path to node:

claude mcp add xai -e XAI_API_KEY=xai-your-key-here -- $(which node) ~/.xai-mcp-server/dist/index.js

Verify it's configured:

claude mcp list

You should see:

xai: ... - ✓ Connected

Step 3: Restart Claude Code

Restart Claude Code to load the new MCP server. You should see the xAI tools available.

Usage

Once configured, you can use natural language to invoke xAI capabilities:

Image Generation

Generate an image of a cyberpunk cityscape at night with neon lights.
Using grok imagine, create a watercolor painting of a mountain landscape.
Generate 3 variations of a logo for a coffee shop called "Bean There".

Chat with Grok

Ask Grok to explain the theory of relativity in simple terms.
Have Grok write a haiku about programming.

Image Analysis

Analyze this image and describe what you see: https://example.com/photo.jpg
What text is visible in this screenshot: [image URL]
Search for the latest news about SpaceX launches.
Find recent tweets about the new iPhone release.
Search the web for Python best practices 2024.

Video Generation

Generate a 5-second video of clouds moving across a blue sky.
Create a video animation of a bouncing ball.

Tool Reference

generate_image

Generate images from text descriptions using Grok Imagine.

Parameter

Type

Required

Default

Description

prompt

string

Yes

-

Text description of the image

n

number

No

1

Number of images (1-10)

model

string

No

grok-2-image-1212

Image generation model

aspect_ratio

string

No

-

Aspect ratio (e.g., "16:9", "1:1", "4:3")

response_format

string

No

url

Output format: "url" or "b64_json"

Example Response:

{
  "success": true,
  "images": [
    {
      "index": 1,
      "url": "https://api.x.ai/images/generated/abc123.png",
      "revised_prompt": "A detailed cyberpunk cityscape..."
    }
  ]
}

chat

Chat with Grok language models.

Parameter

Type

Required

Default

Description

message

string

Yes

-

Message to send to Grok

model

string

No

grok-3

Model: grok-3, grok-4, grok-3-mini

system_prompt

string

No

-

System context/instructions

temperature

number

No

0.7

Sampling temperature (0-2)

max_tokens

number

No

-

Maximum response tokens

analyze_image

Analyze images using Grok's vision capabilities.

Parameter

Type

Required

Default

Description

image_url

string

Yes

-

Image URL or base64 data URL

prompt

string

No

"Describe this image"

Question or instruction

detail

string

No

auto

Detail level: "low", "high", "auto"

model

string

No

grok-2-vision-1212

Vision model

Perform real-time web searches using Grok.

Parameter

Type

Required

Default

Description

query

string

Yes

-

Search query

sources

array

No

["web"]

Sources: "web", "news", "x"

date_range

object

No

-

Date filter: { start, end } (YYYY-MM-DD)

max_results

number

No

10

Maximum results (1-20)

generate_video

Generate videos from text descriptions.

Parameter

Type

Required

Default

Description

prompt

string

Yes

-

Video description

model

string

No

grok-imagine-video

Video generation model

duration

number

No

5

Duration in seconds (1-15)

image

string

No

-

Input image URL to animate

video

string

No

-

Input video URL to edit

aspect_ratio

string

No

-

Aspect ratio (e.g., "16:9")

wait_for_completion

boolean

No

true

Wait for video to finish

Development

# Install dependencies
npm install

# Build TypeScript
npm run build

# Watch mode (rebuild on changes)
npm run dev

# Run the server directly
npm start

Testing

This project includes comprehensive unit tests with pretty table output:

# Run unit tests (mocked, no API calls)
npm run test

# Run tests with detailed output (shows every individual test)
npm run test:detailed

# Run tests in watch mode
npm run test:watch

# Run tests with coverage report
npm run test:coverage

# Run integration tests (requires XAI_API_KEY, makes real API calls)
npm run test:integration

Test Output Features:

  • Color-coded results with status indicators (✓ PASS, ✗ FAIL)

  • Performance metrics showing slowest/fastest test files

  • Summary table with total stats

  • Detailed mode shows individual test durations and suite hierarchy

  • All tests use mocked APIs by default (no cost, no API key needed)

Project Structure

xai-mcp-server/
├── src/
│   ├── index.ts           # MCP server entry point
│   ├── xai-client.ts      # xAI API client with types
│   └── tools/
│       ├── generate-image.ts
│       ├── chat.ts
│       ├── vision.ts
│       ├── live-search.ts
│       └── generate-video.ts
├── dist/                  # Compiled JavaScript
├── package.json
├── tsconfig.json
└── README.md

Troubleshooting

"XAI_API_KEY environment variable is required"

Re-add the MCP server with your API key:

claude mcp remove xai
claude mcp add xai -e XAI_API_KEY=xai-your-key-here -- $(which node) ~/.xai-mcp-server/dist/index.js

Tools not appearing in Claude Code

  1. Run claude mcp list to check server status

  2. If not listed, add it with claude mcp add (see Step 2 above)

  3. For nvm users, use absolute node path: $(which node)

  4. Ensure the project is built (npm run build)

  5. Restart Claude Code completely

API errors

  • Verify your API key is valid at x.ai

  • Check you have sufficient API credits

  • Some features may require specific API tier access

API Reference

This server uses the xAI API. For full API documentation, see:

License

MIT

Contributing

Contributions welcome! Please open an issue or submit a pull request.

Acknowledgments

Available Tools

5 tools
analyze_imageC

Analyze images using xAI's vision-capable Grok models. Describe, extract text, or answer questions about images.

ParametersJSON Schema
NameRequiredDescriptionDefault
image_urlYesURL of the image to analyze (or base64 data URL)
promptNoQuestion or instruction about the imageDescribe this image in detail.
detailNoImage detail level for analysisauto
modelNoVision model to usegrok-2-vision-1212

TDQS

C2.9/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 the full burden of behavioral disclosure. While it mentions the tool uses 'xAI's vision-capable Grok models', it doesn't describe key behavioral traits like rate limits, authentication requirements, cost implications, error handling, or response format. For a tool with no annotation coverage, this leaves the agent with insufficient operational context.

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 clear sentences that efficiently state the tool's purpose and capabilities. It's front-loaded with the core function and avoids unnecessary details. However, it could be slightly more structured by explicitly separating use cases (e.g., 'Use this tool to: 1. Describe images...').

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?

Given the tool's complexity (image analysis with multiple parameters) and lack of both annotations and output schema, the description is incomplete. It doesn't explain what the tool returns, how to interpret results, or any limitations (e.g., image format support, size constraints). For a tool with no structured output documentation, the description should provide more context about expected behavior and results.

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 4 parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema—it doesn't explain parameter interactions, provide examples, or clarify edge cases. This meets the baseline of 3 when schema coverage is high, but adds no extra value.

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: 'Analyze images using xAI's vision-capable Grok models' with specific verbs like 'describe', 'extract text', and 'answer questions'. It distinguishes from siblings like generate_image or generate_video by focusing on analysis rather than creation. However, it doesn't explicitly differentiate from chat or live_search in terms of visual vs. text analysis.

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 mentions general capabilities but doesn't specify scenarios where analyze_image is preferred over chat for image-related queries or when not to use it. With sibling tools like chat potentially handling multimodal inputs, this lack of differentiation is a significant gap.

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

chatB

Chat with xAI's Grok models. Send messages and receive AI-generated responses.

ParametersJSON Schema
NameRequiredDescriptionDefault
messageYesThe user message to send to Grok
modelNoChat model (grok-3, grok-4, grok-3-mini)grok-3
system_promptNoOptional system prompt to set context
temperatureNoSampling temperature (0-2)
max_tokensNoMaximum tokens in response

TDQS

B3.1/5.0
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions sending messages and receiving responses but lacks details on rate limits, authentication needs, error handling, or response format. For a chat tool with potential API constraints, this leaves significant gaps in understanding operational behavior.

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 extremely concise and front-loaded, consisting of just two sentences that directly state the tool's function. Every word contributes to understanding without redundancy or fluff, making it efficient and easy to parse.

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 moderate complexity (5 parameters, no output schema, no annotations), the description is minimally adequate. It covers the basic purpose but lacks details on behavioral traits, usage context, and output expectations. With no output schema, the description should ideally hint at response structure, but it doesn't, leaving room for improvement.

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 input schema already documents all parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema, such as explaining interactions between parameters or typical use cases for optional fields. This meets the baseline for high schema coverage but doesn't enhance understanding.

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: 'Chat with xAI's Grok models. Send messages and receive AI-generated responses.' It specifies the action (chat/send/receive) and resource (Grok models), making it easy to understand. However, it doesn't explicitly differentiate from sibling tools like analyze_image or generate_image, which prevents a perfect score.

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 like live_search or other AI chat tools. It states what the tool does but offers no context about appropriate use cases, prerequisites, or limitations, leaving the agent to infer usage scenarios independently.

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

generate_imageB

Generate images from text descriptions using xAI's Grok Imagine model. Returns image URLs or base64 data.

ParametersJSON Schema
NameRequiredDescriptionDefault
promptYesText description of the image to generate
nNoNumber of images to generate (1-10)
modelNoImage generation model (default: grok-2-image)grok-2-image
aspect_ratioNoAspect ratio (e.g., '16:9', '1:1', '4:3')
response_formatNoResponse format: 'url' or 'b64_json'url

TDQS

B3.3/5.0
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the return format (image URLs or base64 data) but omits critical details like rate limits, authentication needs, costs, error handling, or generation time. For a generative AI tool, this is a significant gap.

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 extremely concise with two sentences that are front-loaded and waste no words. Every sentence directly contributes to understanding the tool's function and output, making it efficient and well-structured.

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 moderate complexity (5 parameters, no output schema, no annotations), the description is minimally adequate. It covers the basic purpose and output but lacks behavioral context, usage guidelines, and deeper parameter insights, leaving gaps for an AI agent to operate effectively.

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 fully documents all 5 parameters. The description adds no additional parameter semantics beyond what's in the schema, such as prompt best practices or model differences. Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose5/5

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

The description clearly states the specific action ('Generate images'), resource ('from text descriptions'), and technology ('using xAI's Grok Imagine model'), distinguishing it from sibling tools like analyze_image, generate_video, and chat. It's not a tautology of the name.

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 like generate_video or analyze_image. It lacks explicit when/when-not scenarios or prerequisites, offering only a basic functional statement without context.

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

generate_videoB

Generate videos from text descriptions using xAI. Can also animate images or edit existing videos.

ParametersJSON Schema
NameRequiredDescriptionDefault
promptYesText description of the video to generate
modelNoVideo generation modelgrok-2-video
imageNoOptional input image URL or base64 to animate
videoNoOptional input video URL to edit/extend
durationNoVideo duration in seconds (1-15)
aspect_ratioNoAspect ratio (e.g., '16:9', '9:16', '1:1')
wait_for_completionNoWait for video generation to complete

TDQS

B3.4/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 but only mentions capabilities without behavioral details like processing time, rate limits, authentication requirements, output format, or error conditions. It doesn't contradict annotations (none exist).

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 front-loads the core functionality and lists additional capabilities without wasted words. Every phrase earns its place by clarifying scope.

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 complex video generation tool with 7 parameters, no annotations, and no output schema, the description is insufficient. It lacks critical context like output format, processing behavior, limitations, or error handling, leaving significant gaps for agent understanding.

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 fully documents all 7 parameters. The description adds no additional parameter semantics beyond what's in the schema, maintaining the baseline score of 3 for adequate but no extra value.

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

Purpose5/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 specific verbs ('generate', 'animate', 'edit') and resources ('videos', 'images', 'existing videos'), and distinguishes it from siblings like generate_image (static images) and analyze_image (analysis rather than generation).

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

Usage Guidelines3/5

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

The description implies usage scenarios (text-to-video, image animation, video editing) but doesn't explicitly state when to choose this tool over alternatives like generate_image for static content or when not to use it. No sibling tool comparisons are 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 observedanalyze_image
    • First observedchat
    • First observedgenerate_image
    • First observedgenerate_video
    • First observedlive_search

TDQS

A3.6/5.0

Scored across 5 tools

Disambiguation5/5

Each tool has a clearly distinct purpose with no overlap: analyze_image handles image analysis, chat is for text conversations, generate_image creates images, generate_video creates videos, and live_search performs web searches. The descriptions reinforce these distinct domains, making tool selection unambiguous.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern (e.g., analyze_image, generate_video, live_search) using snake_case throughout. This predictable naming scheme makes the tool set easy to navigate and understand at a glance.

Tool Count5/5

With 5 tools, this server is well-scoped for its purpose of interacting with xAI's Grok models across different modalities (text, image, video, search). Each tool earns its place by covering a distinct aspect of the AI service without being overly sparse or bloated.

Completeness4/5

The tool set covers core AI functionalities: chat, image analysis/generation, video generation, and web search. A minor gap is the lack of audio-related tools (e.g., speech-to-text or text-to-speech), but agents can work around this given the comprehensive coverage of visual and text domains.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    Not graded
    maintenance
    Enables Claude to query Grok as a peer for collaborative reasoning, code reviews, and architecture debates. It provides access to real-time web research and multiple specialized reasoning modes through the xAI API.
    -
  • F
    license
    B
    quality
    Not graded
    maintenance
    Integrates Grok AI into Claude Code to enable real-time X/Twitter search and deep analysis of social media links. It supports a dual-mode architecture featuring a browser-based free mode for SuperGrok subscribers and a cost-controlled API mode.
    2
    26 npm
    1
    -

Appeared in Searches