🚀 grok-cli-mcp
grok-cli-mcp is an MCP server that wraps the Grok CLI, enabling seamless access to Grok AI models via the Model Context Protocol.
🚀 Quick Start
Prerequisites
Before installing grok-cli-mcp, make sure you have the following:
- Grok CLI: Install it from X.AI's documentation.
- Python 3.10+: Check your Python version.
python3 --version
- Grok API Key: Obtain it from X.AI console.
Installation
You can choose one of the following installation methods:
- Option 1: Install from PyPI (Recommended)
pip install grok-cli-mcp
- Option 2: Install with uv
uv pip install grok-cli-mcp
- Option 3: Install with pipx (isolated environment)
pipx install grok-cli-mcp
- Option 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]"
Set up your environment
export GROK_API_KEY="your-api-key-here"
export GROK_CLI_PATH="/custom/path/to/grok"
For a permanent setup, add the following to your shell profile (~/.bashrc, ~/.zshrc, etc.):
echo 'export GROK_API_KEY="your-api-key-here"' >> ~/.bashrc
source ~/.bashrc
Test the server
python -m grok_cli_mcp
grok-mcp
Configure for MCP clients
For Claude Code
Add the following 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 the following 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 the following to ~/.cursor/mcp.json:
{
"grok": {
"command": "python",
"args": ["-m", "grok_cli_mcp"],
"env": {
"GROK_API_KEY": "your-api-key-here"
}
}
}
⚠️ Important Note
Never commit API keys to version control. Use environment variables or a secrets manager.
✨ Features
What is grok-cli-mcp?
grok-cli-mcp is a Model Context Protocol (MCP) server that serves as a bridge between MCP clients (such as Claude Code, Cline, Cursor) and the Grok CLI. Instead of implementing direct API calls, it utilizes the official Grok CLI tool, offering the following:
- Three specialized tools:
grok_query (for general queries), grok_chat (for multi - turn conversations), grok_code (for 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
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.
💻 Usage Examples
Basic Usage
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 Usage
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"
}
📚 Documentation
Configuration
Environment Variables
| Property |
Details |
GROK_API_KEY |
Required. Your Grok API key from X.AI console. |
GROK_CLI_PATH |
Optional. Default is /opt/homebrew/bin/grok. Path to Grok CLI binary. |
Model Selection
Available models (as of 2025 - 12):
grok-code-fast-1 - Fast model for code tasks.
grok-2 - Main model for general tasks.
- Other models per Grok CLI documentation.
Specify the model in each tool call or omit it for the CLI default.
Timeout Configuration
Default timeouts by tool:
grok_query: 120 seconds.
grok_chat: 120 seconds.
grok_code: 180 seconds.
Adjust via the timeout_s parameter for complex tasks.
Troubleshooting
"Grok CLI not found"
Problem: The server can't locate the Grok CLI binary.
Solutions:
- Verify installation:
which grok
- Set 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: The API key is not in the environment.
Solutions:
- Export in shell:
export GROK_API_KEY="xai-..."
- Add to shell profile (
.bashrc, .zshrc):echo 'export GROK_API_KEY="xai-..."' >> ~/.zshrc
source ~/.zshrc
- Use
.env file with python - dotenv (see examples/.env.example).
"Grok CLI timed out"
Problem: The request took too long.
Solutions:
- Increase timeout:
{"timeout_s": 300}
- Simplify the prompt or break it into smaller requests.
- Check network connectivity.
JSON parsing errors
Problem: The CLI output isn't valid JSON.
Solutions:
- Update Grok CLI to the latest version:
- Check for CLI warnings/errors.
- Use
raw_output=true to see the raw CLI response:{"raw_output": true}
Permission errors
Problem: Can't execute Grok CLI.
Solutions:
- Make the CLI executable:
chmod +x /path/to/grok
- Check file ownership and permissions.
- Verify the CLI works standalone:
grok -p "test"
For more solutions, see docs/troubleshooting.md.
Security Best Practices
Never Commit Secrets
❌ DO NOT:
- Commit
.env files with real API keys.
- Include API keys in
.mcp.json tracked by git.
- Share 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, ~/.zshrc.
- Use 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 the API Keys section.
- Generate a new key.
- Store it securely (1Password, Bitwarden, etc.).
- Set it as an environment variable.
Key Rotation
If you accidentally expose your API key:
- Immediately revoke the key in the X.AI console.
- Generate a new key.
- Update environment variables.
- Check git history for exposed keys.
- Consider using tools like
gitleaks to 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
pip install -e ".[dev]"
pytest
pytest --cov=grok_cli_mcp --cov-report=html
pytest tests/test_utils.py
Code formatting
black .
ruff check --fix .
Type checking
mypy src/
Contributing
Contributions are welcome! Please follow these steps:
- 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.
🔧 Technical Details
This project follows a CLI wrapper pattern. Key details include:
- 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 more details, see docs/architecture.md.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
Support
Made by Basis Set Ventures with Claude Code and FastMCP