Grok CLI MCP Server
Click on "Install 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 CLI MCP ServerExplain quantum computing in simple terms using grok_query"
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-cli-mcp
MCP server that wraps the Grok CLI, providing seamless access to Grok AI models through the Model Context Protocol.
What is this?
grok-cli-mcp is a Model Context Protocol (MCP) server that acts as a bridge between MCP clients (like Claude Code, Cline, Cursor) and the Grok CLI. Instead of implementing direct API calls, it leverages the official Grok CLI tool, providing:
Three specialized tools:
grok_query(general queries),grok_chat(multi-turn conversations),grok_code(code generation)Simple configuration: Just install the Grok CLI and set your API key
Future-proof: Automatically benefits from CLI improvements (OAuth, pricing plans, etc.)
Minimal maintenance: No need to track Grok API changes
Related MCP server: Gemini Agent MCP Server
Why a CLI Wrapper?
Benefits
✅ Leverage existing tooling: Uses the official Grok CLI, ensuring compatibility and stability
✅ Future OAuth support: When Grok CLI adds OAuth authentication, this wrapper will support it automatically without code changes
✅ Fixed pricing plans: Can benefit from fixed monthly pricing (like Codex/ChatGPT/Gemini) when Grok introduces CLI-specific plans, rather than paying per API token
✅ Organization-friendly: Many organizations prefer audited CLI tools over direct API integrations for security and compliance
✅ Simpler codebase: ~400 lines vs 1500+ for a full API client implementation
✅ Fewer dependencies: No HTTP client libraries, request/response handling, or complex networking code
✅ Automatic updates: CLI bug fixes and new features propagate without code changes
Tradeoffs
⚠️ Performance overhead: Extra process spawning adds ~50-200ms latency per request
⚠️ CLI dependency: Requires Grok CLI to be installed and in PATH
⚠️ Limited control: Can't access low-level API features not exposed by CLI
⚠️ Error handling: CLI error messages may be less structured than API responses
⚠️ No streaming: Limited to CLI streaming capabilities (if any)
When to use this
Perfect for:
Development and prototyping workflows
Internal tools and automation (<100 req/min)
Organizations preferring CLI tools over API libraries
Workflows where convenience matters more than milliseconds
Teams wanting to benefit from future CLI-specific pricing/features
Consider direct API for:
High-throughput production systems (>1000 req/min)
Latency-critical applications (<50ms requirements)
Advanced API features not exposed by CLI
Streaming response requirements
Prerequisites
Before installing grok-cli-mcp, ensure you have:
Grok CLI: Install from X.AI's documentation
# Installation instructions vary by platform # See https://docs.x.ai/docs for latest instructionsPython 3.10+: Check your version
python3 --versionGrok API Key: Obtain from X.AI console
Installation
Option 1: Install from PyPI (Recommended)
pip install grok-cli-mcpOption 2: Install with uv
uv pip install grok-cli-mcpOption 3: Install with pipx (isolated environment)
pipx install grok-cli-mcpOption 4: Install from source
git clone https://github.com/BasisSetVentures/grok-cli-mcp.git
cd grok-cli-mcp
pip install -e .Option 5: Development installation
git clone https://github.com/BasisSetVentures/grok-cli-mcp.git
cd grok-cli-mcp
pip install -e ".[dev]"Quick Start
1. Set up your environment
# Required: Set your Grok API key
export GROK_API_KEY="your-api-key-here"
# Optional: Specify custom Grok CLI path
export GROK_CLI_PATH="/custom/path/to/grok"For permanent setup, add to your shell profile (~/.bashrc, ~/.zshrc, etc.):
echo 'export GROK_API_KEY="your-api-key-here"' >> ~/.bashrc
source ~/.bashrc2. Test the server
# Run the server directly
python -m grok_cli_mcp
# Or use the command
grok-mcp
# Should start and wait for stdin (Ctrl+C to exit)3. Configure for MCP clients
For Claude Code
Add to your .mcp.json:
{
"mcpServers": {
"grok": {
"type": "stdio",
"command": "python",
"args": ["-m", "grok_cli_mcp"],
"env": {
"GROK_API_KEY": "your-api-key-here"
}
}
}
}For Cline (VS Code)
Add to ~/.cline/mcp_settings.json:
{
"mcpServers": {
"grok": {
"command": "python",
"args": ["-m", "grok_cli_mcp"],
"env": {
"GROK_API_KEY": "your-api-key-here"
}
}
}
}For Cursor
Add to ~/.cursor/mcp.json:
{
"grok": {
"command": "python",
"args": ["-m", "grok_cli_mcp"],
"env": {
"GROK_API_KEY": "your-api-key-here"
}
}
}⚠️ Security Warning: Never commit API keys to version control. Use environment variables or a secrets manager.
Usage Examples
Tool: grok_query
Send a simple prompt to Grok:
{
"tool": "grok_query",
"arguments": {
"prompt": "Explain quantum computing in simple terms",
"model": "grok-code-fast-1",
"timeout_s": 120
}
}Response: Plain text answer from Grok
Tool: grok_chat
Multi-turn conversation with message history:
{
"tool": "grok_chat",
"arguments": {
"messages": [
{"role": "user", "content": "What is MCP?"},
{"role": "assistant", "content": "MCP is Model Context Protocol..."},
{"role": "user", "content": "How does it work?"}
],
"model": "grok-code-fast-1",
"timeout_s": 120
}
}Response: Grok's answer considering the conversation history
Tool: grok_code
Code generation with language hints and context:
{
"tool": "grok_code",
"arguments": {
"task": "Create a Python function to parse JSON with error handling",
"language": "python",
"context": "Using standard library only, no external dependencies",
"timeout_s": 180
}
}Response: Complete, usable Python code with explanations
Advanced: Raw Output Mode
Get structured response with full details:
{
"tool": "grok_query",
"arguments": {
"prompt": "Explain async/await",
"raw_output": true
}
}Response:
{
"text": "Async/await is...",
"messages": [{"role": "assistant", "content": "..."}],
"raw": "...",
"model": "grok-code-fast-1"
}Configuration
Environment Variables
Variable | Required | Default | Description |
| Yes | - | Your Grok API key from X.AI console |
| No |
| Path to Grok CLI binary |
Model Selection
Available models (as of 2025-12):
grok-code-fast-1- Fast model for code tasksgrok-2- Main model for general tasksOther models per Grok CLI documentation
Specify model in each tool call or omit for CLI default.
Timeout Configuration
Default timeouts by tool:
grok_query: 120 secondsgrok_chat: 120 secondsgrok_code: 180 seconds
Adjust via timeout_s parameter for complex tasks.
Troubleshooting
"Grok CLI not found"
Problem: Server can't locate the Grok CLI binary
Solutions:
Verify installation:
which grokSet explicit path:
export GROK_CLI_PATH="/path/to/grok"Add to PATH:
export PATH="$PATH:/opt/homebrew/bin"
"GROK_API_KEY is not set"
Problem: API key not in environment
Solutions:
Export in shell:
export GROK_API_KEY="xai-..."Add to shell profile (
.bashrc,.zshrc):echo 'export GROK_API_KEY="xai-..."' >> ~/.zshrc source ~/.zshrcUse
.envfile with python-dotenv (seeexamples/.env.example)
"Grok CLI timed out"
Problem: Request took too long
Solutions:
Increase timeout:
{"timeout_s": 300}Simplify prompt or break into smaller requests
Check network connectivity
JSON parsing errors
Problem: CLI output isn't valid JSON
Solutions:
Update Grok CLI to latest version:
# Update instructions vary by installation methodCheck for CLI warnings/errors
Use
raw_output=trueto see raw CLI response:{"raw_output": true}
Permission errors
Problem: Can't execute Grok CLI
Solutions:
Make CLI executable:
chmod +x /path/to/grokCheck file ownership and permissions
Verify CLI works standalone:
grok -p "test"
For more solutions, see docs/troubleshooting.md.
Security Best Practices
Never Commit Secrets
❌ DO NOT:
Commit
.envfiles with real API keysInclude API keys in
.mcp.jsontracked by gitShare API keys in issues or pull requests
Hardcode keys in Python files
✅ DO:
Use environment variables:
export GROK_API_KEY="..."Use shell RC files:
~/.bashrc,~/.zshrcUse secrets managers in production: AWS Secrets Manager, HashiCorp Vault
Rotate keys immediately if accidentally exposed
Obtaining API Keys
Visit X.AI Console
Sign in with your X.AI account
Navigate to API Keys section
Generate a new key
Store securely (1Password, Bitwarden, etc.)
Set as environment variable
Key Rotation
If you accidentally expose your API key:
Immediately revoke the key in X.AI console
Generate a new key
Update environment variables
Check git history for exposed keys
Consider using tools like
gitleaksto scan for secrets
Reporting Security Issues
Do NOT open public issues for security vulnerabilities.
Please report security concerns responsibly through GitHub Security Advisories or by contacting the maintainers directly.
Architecture & Design
This project follows a CLI wrapper pattern rather than direct API integration. Key design decisions:
Process isolation: Each Grok request spawns a subprocess for CLI execution
JSON parsing with fallback: Attempts structured parsing, falls back to raw output
Context propagation: Uses FastMCP's Context for logging and progress updates
Async execution: All operations are async-first for non-blocking behavior
For detailed architecture discussion, see docs/architecture.md.
Development
Running tests
# Install dev dependencies
pip install -e ".[dev]"
# Run all tests
pytest
# Run with coverage
pytest --cov=grok_cli_mcp --cov-report=html
# Run specific test file
pytest tests/test_utils.pyCode formatting
# Format code
black .
# Lint code
ruff check --fix .Type checking
mypy src/Contributing
Contributions are welcome! Please:
Fork the repository
Create a feature branch (
git checkout -b feature/amazing-feature)Commit your changes (
git commit -m 'Add amazing feature')Push to the branch (
git push origin feature/amazing-feature)Open a Pull Request
Please ensure:
Tests pass (
pytest)Code is formatted (
black,ruff)Type hints are correct (
mypy)Documentation is updated
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
Built with FastMCP by Jeremiah Lowin
Uses Model Context Protocol SDK by Anthropic
Wraps Grok CLI from X.AI
Support
Documentation: README • Architecture • Troubleshooting
Issues: GitHub Issues
Discussions: GitHub Discussions
Grok Documentation: docs.x.ai
Made by Basis Set Ventures with Claude Code and FastMCP
Available Tools
3 toolsgrok_chatGrok ChatB
Send a list of role/content messages to Grok by flattening into a single prompt. Useful for multi-turn context when the CLI only supports a single '-p' prompt.
| Name | Required | Description | Default |
|---|---|---|---|
| messages | Yes | ||
| model | No | ||
| raw_output | No | ||
| timeout_s | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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. The description mentions flattening messages into a single prompt, which is useful context. However, it doesn't disclose important behavioral traits like authentication requirements, rate limits, error handling, or what the output looks like (though an output schema exists). For a tool with no annotation coverage, this leaves significant gaps in understanding how the tool behaves.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is perfectly concise with just two sentences. The first sentence states the core functionality, and the second sentence provides the key usage context. Every word earns its place with zero waste or redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given that there's an output schema (which handles return values) and no annotations, the description provides adequate basic context about what the tool does and when to use it. However, with 4 parameters and 0% schema description coverage, the lack of parameter guidance in the description creates a significant gap. The description is complete enough for understanding the tool's purpose but insufficient for effective parameter usage.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, meaning none of the 4 parameters have descriptions in the schema. The tool description doesn't mention any parameters at all, failing to compensate for the lack of schema documentation. While the description implies the 'messages' parameter is central, it provides no guidance on what 'model', 'raw_output', or 'timeout_s' do or how to use them effectively.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: 'Send a list of role/content messages to Grok by flattening into a single prompt.' This specifies the verb ('send'), resource ('messages to Grok'), and transformation ('flattening'). However, it doesn't explicitly differentiate from sibling tools like grok_code or grok_query, which likely handle different types of interactions.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides clear context for when to use this tool: 'Useful for multi-turn context when the CLI only supports a single '-p' prompt.' This explains the specific scenario where this tool is valuable (multi-turn conversations with a CLI limitation). However, it doesn't explicitly mention when NOT to use it or provide alternatives to sibling tools.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
grok_codeGrok Code TaskB
Ask Grok for code or code-related guidance. You can provide a language hint and context (e.g., file snippets or requirements). Returns assistant text by default.
| Name | Required | Description | Default |
|---|---|---|---|
| task | Yes | ||
| language | No | ||
| context | No | ||
| model | No | ||
| raw_output | No | ||
| timeout_s | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It mentions 'Returns assistant text by default,' which hints at output behavior, but doesn't disclose critical traits like whether this is a read-only or mutating operation, authentication needs, rate limits, error handling, or what 'raw_output' and 'timeout_s' parameters imply. For a tool with 6 parameters and no annotations, this is insufficient.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is appropriately sized and front-loaded, with the core purpose stated first. Both sentences add value: the first defines the tool's function, and the second clarifies parameters and output. There's no wasted text, making it efficient.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's complexity (6 parameters, no annotations, but with an output schema), the description is moderately complete. It covers the basic purpose and hints at some parameters, but since there's an output schema, it doesn't need to detail return values. However, the lack of behavioral disclosure and incomplete parameter semantics make it inadequate for full understanding.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate. It mentions 'language hint and context (e.g., file snippets or requirements),' which adds meaning for 'language' and 'context' parameters, but doesn't explain 'task,' 'model,' 'raw_output,' or 'timeout_s.' With 6 parameters, this partial coverage leaves significant gaps in understanding.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: 'Ask Grok for code or code-related guidance.' It specifies the verb ('Ask Grok') and resource ('code or code-related guidance'), making it understandable. However, it doesn't explicitly differentiate from sibling tools like grok_chat or grok_query, which likely handle different types of queries.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides some implied usage context by mentioning 'code or code-related guidance' and suggesting parameters like language hint and context. However, it lacks explicit guidance on when to use this tool versus alternatives (e.g., grok_chat for general chat, grok_query for non-code queries), and doesn't specify prerequisites or exclusions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
grok_queryGrok QueryB
Send a single prompt to Grok via CLI headless mode. Returns the assistant's text. Use raw_output=true to get raw CLI output and parsed messages.
| Name | Required | Description | Default |
|---|---|---|---|
| prompt | Yes | ||
| model | No | ||
| raw_output | No | ||
| timeout_s | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden. It discloses that the tool returns 'the assistant's text' and mentions a 'raw_output' option for CLI output, adding some behavioral context. However, it doesn't cover critical aspects like error handling, rate limits, authentication needs, or what 'CLI headless mode' entails operationally.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is brief and front-loaded with the core purpose, followed by a specific usage tip. Both sentences earn their place by adding value, though it could be slightly more structured for clarity.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the complexity of a 4-parameter tool with no annotations and 0% schema coverage, the description is incomplete. It covers basic purpose and one parameter nuance, but lacks details on other parameters, error cases, or operational constraints. The presence of an output schema helps, but doesn't fully compensate for the gaps.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate. It adds meaning for 'raw_output' by explaining its effect ('to get raw CLI output and parsed messages'), but doesn't address other parameters like 'model', 'timeout_s', or 'prompt' beyond what the schema titles imply. This partial compensation meets the baseline for low coverage.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the action ('Send a single prompt to Grok via CLI headless mode') and the resource (Grok), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'grok_chat' or 'grok_code', which likely have overlapping functionality with Grok interactions.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides some implied usage context by mentioning 'raw_output=true' for specific output formats, but it lacks explicit guidance on when to use this tool versus alternatives like 'grok_chat' or 'grok_code'. No exclusions or prerequisites are stated.
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. Dates show when Glama detected each change.
3 tool updates
- First observed
grok_chat - First observed
grok_code - First observed
grok_query
TDQS
The tools have distinct primary purposes: grok_chat handles multi-turn conversations by flattening messages, grok_code focuses on code-related queries with language hints, and grok_query is for single-prompt interactions with raw output options. However, grok_chat and grok_query both involve sending prompts to Grok, which could cause minor confusion about when to use each for simple queries.
All tool names follow a consistent 'grok_' prefix pattern with descriptive suffixes (chat, code, query), using snake_case uniformly. This makes the tools easily identifiable and predictable within the server's domain.
With 3 tools, the count is reasonable for a CLI server focused on interacting with Grok, covering chat, code, and general query use cases. It is slightly lean but not insufficient, as each tool addresses a specific aspect of the Grok interface.
The tools cover core functionalities for querying Grok (chat, code, general queries), but there are notable gaps such as missing operations for managing sessions, handling file uploads, or configuring settings, which might limit advanced workflows in a CLI context.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Source-checked CLI guides and model-aware planning for Claude Code, Codex, and Grok Build.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Share one project context across ChatGPT, Claude, Telegram and any MCP client.
- QuallaaOAuthcom.quallaa
Talk to your public-facing AI from any MCP client — Claude, ChatGPT, Cursor, Cline, Windsurf.
Related MCP Servers
- AlicenseBqualityDmaintenanceProvides seamless access to Grok AI's capabilities (chat completion, image understanding, and function calling) directly from Cline via the Model Context Protocol.34825MIT
- AlicenseNot gradedqualityCmaintenanceProvides a Model Context Protocol interface to the Gemini CLI, enabling AI agents to call the Gemini model and interact with development tools like code linting, GitHub operations, and documentation generation. Includes security measures to prevent unauthorized file access through path validation.3MIT
- AlicenseNot gradedqualityDmaintenanceWraps the GitHub Copilot CLI to provide natural language command suggestions, explanations, and shell configuration for shell, git, and GitHub CLI commands through the Model Context Protocol.1MIT
- AlicenseNot gradedqualityCmaintenanceEnables natural language interaction with any Python CLI application (Click, Typer, Argparse) through the Model Context Protocol.23MIT
Appeared in Searches
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/BasisSetVentures/grok-cli-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server