Grok MCP
Grok MCP is an MCP server that provides comprehensive access to xAI's Grok API capabilities. You can access multiple Grok models (Grok-4, Grok-4-Fast, Grok-3-Mini, and more) for chat completion with extensive customization options including temperature, max tokens, and system prompts. The server supports reasoning models that provide detailed reasoning alongside responses, image generation from text descriptions, and vision analysis of images using natural language queries (supporting both local files and URLs). It offers live web search with real-time results, source citations, date range filters, country localization, and custom RSS feed integration from news, web, X (Twitter), and RSS sources. You can maintain stateful conversations with context preserved across multiple requests, conversation history management, and the ability to retrieve and delete stored responses (kept for 30 days). Additional features include model discovery to list all available Grok models with their details and creation information.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Grok MCP generate an image of a futuristic city skyline at sunset"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Grok-MCP
MCP server for xAI’s Grok API with Web/X search, vision, image/video generation and file support.
Features
Agentic Tool Calling: Web search, X search, code execution, and image generation with multi-step reasoning
Multiple Grok Models: Access to latest models such as grok-4.6, grok-4.5, grok-build-0.1 and more
Image and Video Generation: Create images and videos using Grok Imagine
Vision Capabilities: Analyze images with Grok's vision models
Files API: Upload, manage, and chat with documents
Stateful Conversations: Maintain conversation context as id across multiple requests
Local Chat History: Option to save persistent client side chat history as JSON files in chats/
Related MCP server: Grok Image MCP
Prerequisites
Python 3.11 or higher
xAI API key (Get one here)
Installation
Clone the repository:
git clone https://github.com/merterbak/Grok-MCP.git
cd Grok-MCPCreate a venv environment:
uv venv
source .venv/bin/activate # macOS/Linux or .venv\Scripts\activate on WindowsInstall dependencies:
uv syncConfiguration
Claude Desktop Integration
Add this to your Claude Desktop configuration file:
{
"mcpServers": {
"grok": {
"command": "uv",
"args": [
"--directory",
"/path/to/Grok-MCP",
"run",
"python",
"main.py"
],
"env": {
"XAI_API_KEY": "your_api_key_here"
}
}
}
}Claude Code Integration
Run this command from inside the project directory:
claude mcp add grok-mcp -e XAI_API_KEY=your_api_key_here -- uv run --directory /path/to/Grok-MCP python main.pyOr if you have a .env file with your key:
claude mcp add grok-mcp -- uv run --directory /path/to/Grok-MCP python main.pyVerify it's registered:
claude mcp listFilesystem MCP (Optional)
Claude Desktop can't send uploaded images in the chat to an MCP tool. The easiest way to give access to files directly from your computer is official Filesystem MCP server. After setting it up you’ll be able to just write the image’s file path (such as /Users/mert/Desktop/image.png) in chat and Claude can use it with any vision chat tool.
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/<your-username>/Desktop",
"/Users/<your-username>/Downloads"
]
}
}
}
For stdio:
uv run python main.pyDocker:
docker compose up --buildMcp Inspector:
mcp dev main.pyAvailable Tools
Each tool has a full docstring in src/server.py with its arguments and return format. MCP client surfaces those directly, so this list is just a quick map of what's available.
Note: For using images and files, you must provide paths to chat. See Filesystem MCP (Optional) for setup.
Chat and reasoning
chat— standard chat completion with optional persistent history, multi-agent support, and a per requestservice_tier.chat_with_vision— analyze local or remote images with a Grok vision model.chat_with_files— chat grounded on previously uploaded documents.stateful_chat— continue a server-side stored conversation viaresponse_id.retrieve_stateful_response— fetch a stored response by ID.delete_stateful_response— delete a stored response by ID.
Agentic tools
web_search— autonomous web research with domain filters and citations.x_search— autonomous search over X (Twitter) posts, with handle and date filters.code_executor— solve tasks by running Python in a sandbox.grok_agent— unified agent that mixes files, images, web search, X search, code execution, and server-side image generation. Generated images are written toimages/.
Image and video
generate_image— create or edit images with Grok Imagine (multi-reference editing supported). Passsave=trueto write the results toimages/instead of returning temporary URLs.generate_video— text-to-video, image-to-video, or video editing with Grok Imagine.extend_video— extend an existing generated video with a follow-up prompt.
Files
upload_file— upload a local document.list_files— list uploaded files with sorting.get_file— fetch file metadata by ID.get_file_content— download file content as text.delete_file— delete a file by ID.
Local chat history
list_chat_sessions— list saved sessions inchats/.get_chat_history— get a session's full transcript.clear_chat_history— delete a session's local history file.
Models
list_models— list all Grok language and image models with live pricing.
License
This project is open source and available under the MIT License.
Available Tools
22 toolschatA
Send a text prompt to a Grok model and return its reply.
Replays prior turns from `chats/{session}.json` when a session is given,
then appends the new user message and saves the round trip.
Args:
prompt: User message to send to the model.
session: Optional session name. Loads and appends history to `chats/{session}.json`.
model: Grok model id (default `grok-4.6`).
system_prompt: Optional system instruction prepended to the conversation.
agent_count: 4 or 16. Only valid with `grok-4.20-multi-agent` for multi-agent research.
service_tier: `"default"` or `"priority"`. Priority is processed faster at a higher token price.
show_usage: Append a token usage and cost footer to the reply (default False).
Returns:
The assistant's reply text, plus a token usage and cost footer when `show_usage` is true.
Inputs: prompt (required), model, session, show_usage, +3 more.
chat_with_filesA
Chat with Grok using one or more previously uploaded files as context.
Attaches the given `file_ids` to the user turn so Grok can read/quote their
contents. Optional `session` persists local chat history across calls.
Args:
prompt: Question or instruction about the attached files.
file_ids: IDs of files previously returned by `upload_file`.
session: Optional session name for persistent history in `chats/{session}.json`.
model: Grok model id (default `grok-4.6`).
system_prompt: Optional system instruction prepended to the conversation.
show_usage: Append a token usage and cost footer to the reply (default False).
Returns:
Assistant reply, followed by a `**Sources:**` list when the model cites URLs.
Inputs: prompt (required), file_ids (required), model, session, +2 more.
chat_with_visionA
Analyze one or more images with a Grok vision model.
Accepts local image paths and/or public URLs in the same call. Local images
are sent as base64 data URIs (JPG/JPEG/PNG only, max 20 MiB each).
Args:
prompt: Question or instruction about the image(s).
session: Optional session name for persistent history in `chats/{session}.json`.
model: Vision-capable Grok model (default `grok-4.6`).
image_paths: Local image file paths to analyze.
image_urls: Public image URLs to analyze.
detail: Image detail level. One of `"auto"`, `"low"`, or `"high"`.
show_usage: Append a token usage and cost footer to the reply (default False).
Returns:
The model's textual answer about the image(s).
Inputs: prompt (required), model, detail, session, +3 more.
clear_chat_historyA
Delete the local history file for a chat session.
Only removes the client-side JSON file. Server-side stored responses are untouched.
Args:
session: Session name whose `chats/{session}.json` file should be deleted.
Returns:
Confirmation string or a not-found message.
Inputs: session.
code_executorA
Solve a task by letting Grok run Python in a stateful sandbox.
The agent iteratively writes and executes Python (with common scientific
libraries) to arrive at a numeric, data, or analysis answer.
Args:
prompt: Task or question requiring computation.
model: Grok model driving the agent (default `grok-4.6`).
max_turns: Cap the number of reasoning/execution turns.
show_usage: Append a token usage and cost footer to the answer (default False).
Returns:
Markdown with the final answer followed by each code execution block's stdout.
Inputs: prompt (required), model, max_turns, show_usage.
delete_fileA
Permanently delete an uploaded file from xAI.
Args:
file_id: ID of the file to remove.
Returns:
Confirmation string with the deleted file ID.
Inputs: file_id (required).
delete_stateful_responseA
Delete a stored chat completion from xAI's servers.
Args:
response_id: ID of the stored response to remove.
Returns:
Confirmation string with the deleted response ID.
Inputs: response_id (required).
extend_videoA
Extend an existing video with a follow-up prompt.
Continues the source video seamlessly from its last frame. `duration` sets
the length of the extension only, not the total output. For example, a
10 second input plus `duration=5` yields a 15 second final video.
Args:
prompt: What should happen in the extended segment.
video_url: Public URL of the source video (.mp4, 2–15 s).
model: Video model (default `grok-imagine-video`).
duration: Length of the extension in seconds (2–10, default 6).
show_usage: Append a token usage and cost footer to the result (default False).
Returns:
Markdown block with the extended video URL and total duration.
Inputs: prompt (required), video_url (required), model, duration, +1 more.
generate_imageA
Generate new images or edit existing ones with Grok Imagine.
Pass `image_paths` and/or `image_urls` to edit images or use them as
visual references. Multiple references are combined in a single call.
Args:
prompt: Image description, or the edit instruction when references are provided.
model: Image model (`grok-imagine-image` or `grok-imagine-image-pro`).
image_paths: Local image files (JPG/PNG) used as edit sources or references.
image_urls: Public image URLs used as edit sources or references.
n: Number of images to generate (1–10).
image_format: `"url"` (default) or `"base64"`. Base64 responses carry no URL,
so they are always saved locally.
aspect_ratio: Aspect ratio like `"16:9"`, `"1:1"`, or `"9:16"`.
resolution: `"1k"` or `"2k"`.
save: Write each image to `images/` and report the local path instead of the
remote URL. Remote URLs are temporary, so save anything you want to keep.
show_usage: Append a token usage and cost footer to the result (default False).
Returns:
Markdown block listing each image as a saved local path when saving, otherwise
as a temporary remote URL.
Inputs: prompt (required), n, save, model, +6 more.
generate_videoA
Generate or edit videos with Grok Imagine.
Text-to-video by default. Provide an image to animate (image-to-video), or
a source video to edit. Only one mode per call. Reference images can be
added to guide style and subjects. Generation polls synchronously (xAI's
default timeout is 10 minutes).
Args:
prompt: Video description, or the edit instruction for video editing.
model: Video model (default `grok-imagine-video`).
image_path: Local image to use as the starting frame.
image_url: Public image URL to use as the starting frame.
video_path: Local video to edit (max 20 MB, .mp4, ≤ 8.7s).
video_url: Public video URL to edit (.mp4, ≤ 8.7s).
reference_image_paths: Local images used as style/subject references.
reference_image_urls: Public image URLs used as style/subject references.
duration: Video length in seconds (1–15, ignored when editing).
aspect_ratio: Aspect ratio like `"16:9"` or `"9:16"` (ignored when editing).
resolution: `"480p"` or `"720p"` (ignored when editing).
show_usage: Append a token usage and cost footer to the result (default False).
Returns:
Markdown block with the generated video URL and actual duration.
Inputs: prompt (required), model, duration, image_url, +8 more.
get_chat_historyARead-only
Return the full message history for a local chat session.
Args:
session: Session name to load from `chats/{session}.json` (default `default`).
Returns:
Formatted transcript with timestamps and roles, or a not-found message.
Inputs: session.
get_fileARead-only
Fetch metadata for a single uploaded file.
Args:
file_id: ID returned by `upload_file`.
Returns:
Markdown block with the file's ID, filename, size, and creation time.
Inputs: file_id (required).
get_file_contentARead-only
Download the raw content of an uploaded file as text.
Bytes are decoded as UTF-8 with replacement for invalid sequences. Output
is truncated to `max_bytes` to avoid overwhelming the response.
Args:
file_id: ID of the uploaded file.
max_bytes: Maximum bytes to return (default 500 000).
Returns:
File text, with a truncation note appended when the content exceeds `max_bytes`.
Inputs: file_id (required), max_bytes.
grok_agentA
All-in-one Grok agent combining files, vision, web/X search, code execution, and image generation.
Enable any subset of tools and attach any mix of uploaded files and images.
The agent decides which tools to use per turn. Supports optional local
session history and multi-agent research via `agent_count`.
Args:
prompt: Task or question for the agent.
session: Optional session name for persistent history in `chats/{session}.json`.
model: Grok model driving the agent (default `grok-4.6`).
file_ids: IDs of previously uploaded files to attach as context.
image_urls: Public image URLs to attach.
image_paths: Local image files to attach (sent as base64 data URIs).
use_web_search: Enable the agentic web search tool.
use_x_search: Enable the agentic X (Twitter) search tool.
use_code_execution: Enable the Python code execution tool.
use_image_generation: Enable the server-side image generation tool, letting the agent
create and edit images mid-conversation. Images are saved under `images/`.
image_generation_action: Which image capabilities to expose: `"auto"` (default, generate
and edit), `"generate"` (text-to-image only), or `"edit"` (editing only).
allowed_domains: Web search allow-list (max 5, mutually exclusive with excluded).
excluded_domains: Web search deny-list (max 5).
allowed_x_handles: X search handle allow-list (max 10, mutually exclusive with excluded).
excluded_x_handles: X search handle deny-list (max 10).
from_date: X search inclusive start date as `DD-MM-YYYY`.
to_date: X search inclusive end date as `DD-MM-YYYY`.
enable_image_understanding: Let search tools analyze images they encounter.
enable_video_understanding: Let X search analyze videos in posts.
enable_image_search: Let web search find and return image results.
include_inline_citations: Embed `[1]`-style citation markers into the answer.
system_prompt: Optional system instruction prepended to the conversation.
max_turns: Cap the agent's reasoning/tool turns.
agent_count: 4 or 16. Only valid with `grok-4.20-multi-agent`.
service_tier: `"default"` or `"priority"`. Priority is processed faster at a higher token price.
show_usage: Append a token usage and cost footer to the answer (default False).
Returns:
Markdown with the answer body, then a `**Generated Images:**` list of saved file paths
when the agent produced images, then a `**Sources:**` list when citations exist.
Inputs: prompt (required), model, session, to_date, +22 more.
list_chat_sessionsARead-only
List all local chat sessions stored under chats/.
Returns:
Markdown list of session names with turn counts and last-message timestamps,
or a placeholder message when no sessions exist.
Inputs: no named parameters.
list_filesARead-only
List files previously uploaded to xAI.
Args:
limit: Maximum number of files to return (default 100).
order: `"asc"` or `"desc"` sort order (default `"desc"`).
sort_by: Field to sort by, such as `"created_at"`.
Returns:
Markdown list of files with ID, filename, and size, or a placeholder when empty.
Inputs: limit, order, sort_by.
list_modelsARead-only
List all Grok language and image models with live pricing from the xAI API.
Returns:
Markdown sections for language models (input/output $/M tokens) and
image generation models ($/image), each with the model's release date.
Inputs: no named parameters.
retrieve_stateful_responseARead-only
Fetch a stored chat completion from xAI by its response ID.
Args:
response_id: ID returned by a prior `stateful_chat` call.
Returns:
The stored assistant reply and its `**Response ID:**`, or a not-found message.
Inputs: response_id (required).
stateful_chatA
Continue a server-side stored conversation using xAI's deferred/stateful chat.
The xAI API stores every turn so the client only needs to send the latest
prompt plus `previous_response_id`. Omit `response_id` to start a new thread.
Args:
prompt: User message to append.
model: Grok model id (default `grok-4.6`).
response_id: ID of the previous response to continue from (omit to start fresh).
system_prompt: Optional system instruction. Applied only on the first turn.
show_usage: Append a token usage and cost footer to the reply (default False).
Returns:
Assistant reply followed by the new `**Response ID:**` to pass back next turn.
Inputs: prompt (required), model, show_usage, response_id, +1 more.
upload_fileA
Upload a local file to xAI so it can be attached to later chats.
Supported types include PDFs and text documents (see xAI file docs). The
returned file ID can be passed to `chat_with_files` or `grok_agent`.
Args:
file_path: Absolute or relative path to the local file.
expires_after: Optional TTL in seconds. The file is deleted from xAI
automatically once it expires (omit to keep the file indefinitely).
Returns:
Markdown block with the assigned file ID, filename, and size.
Inputs: file_path (required), expires_after.
web_searchARead-only
Answer a query using agentic real-time web search.
Grok browses the web across multiple turns, optionally inspecting images on
pages, then synthesizes an answer with citations.
Args:
prompt: Search query or research question.
model: Grok model used to drive the agent (default `grok-4.6`).
allowed_domains: Restrict search to these domains (max 5, mutually exclusive with excluded).
excluded_domains: Exclude these domains from search (max 5).
enable_image_understanding: Let the agent analyze images it encounters.
enable_image_search: Let the agent search for and return image results.
include_inline_citations: Embed `[1]`-style citation markers into the answer text.
max_turns: Cap the agent's reasoning/tool turns.
show_usage: Append a token usage and cost footer to the answer (default False).
Returns:
Markdown with the answer body followed by a `**Sources:**` list of cited URLs.
Inputs: prompt (required), model, max_turns, show_usage, +5 more.
x_searchARead-only
Answer a query using agentic search over X (Twitter).
Searches posts, threads, and users on X. Can filter by handle allow/deny
lists and a date range, and optionally analyze images/videos attached to posts.
Args:
prompt: Search query or question about X content.
model: Grok model driving the agent (default `grok-4.6`).
allowed_x_handles: Restrict search to these handles (max 10, mutually exclusive with excluded).
excluded_x_handles: Exclude these handles (max 10).
from_date: Inclusive start date as `DD-MM-YYYY`.
to_date: Inclusive end date as `DD-MM-YYYY`.
enable_image_understanding: Let the agent analyze images in posts.
enable_video_understanding: Let the agent analyze videos in posts (X Search only).
include_inline_citations: Embed `[1]`-style citation markers into the answer.
max_turns: Cap the agent's reasoning/tool turns.
show_usage: Append a token usage and cost footer to the answer (default False).
Returns:
Markdown with the answer body followed by a `**Sources:**` list of cited posts.
Inputs: prompt (required), model, to_date, from_date, +7 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 22 tools
Most tools are distinct, but `grok_agent` explicitly subsumes vision, files, web/X search, code execution, and image generation, overlapping heavily with `chat_with_vision`, `chat_with_files`, `web_search`, `x_search`, `code_executor`, and `generate_image`. `chat`, `stateful_chat`, and `chat_with_files` also have fuzzy boundaries between simple chat and agentic chat. Descriptions do help, but an agent could easily misselect.
The set is dominated by a clear verb_noun pattern (delete_file, get_file, generate_image, list_files, upload_file, web_search, extend_video). A few outliers (`chat`, `stateful_chat`, `grok_agent`, `code_executor`) are noun- or adjective-led, but overall the convention is readable and mostly predictable.
At 22 tools this sits at the heavy end, but the breadth (chat, stateful chat, files, vision, image, video, web/X search, code, models) genuinely justifies a large surface. The only redundancy is the all-in-one `grok_agent` duplicating several specialized tools, which could arguably be folded in.
File lifecycle is fully covered (upload, list, get metadata, get content, delete), chat and stateful-chat lifecycles are covered, and media generation includes image, video, and extend. Minor gaps remain (no listing of stateful responses, no video delete), but core workflows have no dead ends.
Maintenance
Related MCP Connectors
MCP server for Grok Imagine AI video generation
MCP server for OpenAI API (chat completions, image generation, embeddings) via AceDataCloud
MCP server for building and testing AI agents with multi-model experimentation and insights.
Chat, image, video, and audio models from many vendors behind one remote MCP server and one key.
Related MCP Servers
- AlicenseAqualityDmaintenanceModel Context Protocol (MCP) server implementation that enables Claude Desktop to interact with Google's Gemini AI models.675 npm260MIT
- AlicenseAqualityBmaintenanceMCP server for generating and editing images using xAI's Grok image model, supporting text prompts, batch generation, local files, and optional proxy configurations.234 npm29MIT
- AlicenseAqualityFmaintenanceProduction-grade MCP server for image and video understanding and generation across Gemini, OpenAI, and Grok.54Apache 2.0
- AlicenseNot gradedqualityCmaintenanceMCP server for xAI Grok API with 19 tools for chat, web and X search, session management, tool chaining, image and video generation, and documentation.2MIT