grok-mcp
by ruji9527
README.md
# grok-mcp
**Grok as a tool for every agent.** An MCP server for the xAI API — live X and web search with citations, schema-locked extraction, image generation, and a token/cost ledger that keeps autonomous agents from quietly burning a budget.
[](https://github.com/ruji9527/grok-mcp/actions/workflows/ci.yml)
[](pyproject.toml)
[](LICENSE)
[](https://modelcontextprotocol.io)
Any MCP client — Claude Code, Cursor, Codex, Zed, your own agent loop — gets seven tools: `grok_ask`, `grok_web_search`, `grok_x_search`, `grok_structured`, `grok_imagine`, `grok_models`, `grok_usage`.
```
┌──────────────────────┐ MCP (stdio / HTTP) ┌───────────────────────┐
│ Claude Code │ ───────────────────────────────▶ │ grok-mcp │
│ Cursor · Codex │ tools · resources · JSON Schema │ ┌─────────────────┐ │
│ your agent │ ◀─────────────────────────────── │ │ validation │ │
└──────────────────────┘ results + usage + citations │ │ retry/backoff │ │
│ │ cost ledger │ │
│ └────────┬────────┘ │
└───────────┼───────────┘
▼
api.x.ai/v1 · responses
x_search · web_search
```
## Why another Grok wrapper
Because an agent needs four things a raw API call does not give it:
| Problem | What this server does |
| --- | --- |
| "Which endpoint do I hit?" | One tool per capability. No URLs, no payload assembly, no guessing. |
| "Where did that answer come from?" | Citations are parsed from **all three** places Grok puts them (inline `[[1]](url)` markers, block annotations, top-level list) and deduplicated into one list. |
| "What will this cost?" | Every result carries token counts and an estimated `cost_usd`. `grok_usage` reports the running total, grouped by model and tool. X Search is priced per post fetched, which is exactly the trap a naive loop falls into. |
| "Why did my agent tool call fail mysteriously?" | Validation errors are *anticipated* failures: the model receives the actual message ("from_date must look like YYYY-MM-DD") instead of `Error executing tool`. |
Plus the boring things that make it usable: retries with `Retry-After` handling, a concurrency cap, typed results (`outputSchema` for every tool), structured logs on **stderr** only, and an offline mock backend so the whole thing runs without an API key.
## Quick start
```bash
# try it with zero credentials — deterministic fixtures, no network
GROK_MCP_MOCK=1 uvx --from git+https://github.com/ruji9527/grok-mcp grok-mcp
```
Real usage:
```bash
export GROK_API_KEY="xai-..." # https://console.grok.com
uvx --from git+https://github.com/ruji9527/grok-mcp grok-mcp # stdio
# or, from a clone: pip install -e . && grok-mcp --transport streamable-http --port 8765
```
### Claude Code
```bash
claude mcp add grok \
--env GROK_API_KEY=xai-... \
-- uvx --from git+https://github.com/ruji9527/grok-mcp grok-mcp
```
### Cursor / Claude Desktop / any JSON config
```json
{
"mcpServers": {
"grok": {
"command": "uvx",
"args": ["--from", "git+https://github.com/ruji9527/grok-mcp", "grok-mcp"],
"env": { "GROK_API_KEY": "xai-..." }
}
}
}
```
Typical session:
> **You:** What are people on X saying about the new Grok release since Monday? Cite the posts.
>
> **Agent:** *(calls `grok_x_search` with `from_date`, then `grok_structured` to normalize the sentiment into a table)* → answer with `x.com` links, plus `cost_usd` for both calls.
## Tools
| Tool | Use it when | Notes |
| --- | --- | --- |
| `grok_ask` | reasoning, writing, code, explanations | no network; `model`, `system`, `max_output_tokens`, `temperature` |
| `grok_web_search` | anything after the training cutoff | `allowed_domains` / `excluded_domains` (max 5) |
| `grok_x_search` | sentiment, breaking discussion, what specific accounts said | `x_handles` (max 20, `@` optional), `from_date` / `to_date` (UTC, end-exclusive), image/video understanding |
| `grok_structured` | any output you intend to parse | JSON Schema string; the API enforces it, result arrives in `parsed` |
| `grok_imagine` | image generation | 1–4 images, `aspect_ratio`, returns temporary URLs |
| `grok_models` | picking a model on price, not vibes | context window + per-MTok prices per model |
| `grok_usage` | before/after a batch | calls, tokens, estimated spend, by model and tool; `reset=true` zeroes it |
Resources: `grok://models` (price table) and `grok://usage` (session totals) — cacheable context instead of a tool round-trip.
Full argument reference: [docs/TOOLS.md](docs/TOOLS.md). Cost model and how to cap spend: [docs/COST.md](docs/COST.md).
## Offline demo

Real output from `python scripts/demo.py --mock` (fixtures, no API key):
```console
grok-mcp demo · backend=mock · model=grok-4.7 · base_url=https://api.x.ai/v1
2. grok_web_search
The Responses API is the recommended surface: it takes `tools` (`web_search`, `x_search`,
`code_execution`), returns `citations` at the top level, and accepts `text.format` for
schema-locked JSON. [[1]](https://docs.grok.com/…)
citations: 2 · cost: $0.005836
3. grok_x_search
Sentiment around the launch splits in two. Builders are enthusiastic about live search with
inline citations, and pragmatic about cost: per-post billing shows up in every comparison
thread. [[1]](https://x.com/example/st…)
[1] https://x.com/example/status/1000000000000000001
[2] https://x.com/example/status/1000000000000000002
cost: $0.010840
6. grok_models
grok-4.7 context 500,000 $2.00/M in, $6.00/M out
grok-4.3 context 1,000,000 $1.25/M in, $2.50/M out
7. grok_usage
5 calls · 532 in / 265 out tokens · estimated $0.057654
cost_is_estimate=True
```
The answers above are fixtures; the envelope, usage accounting, citation parsing, and cost math are the same code paths a live call takes.
## Configuration
| Env var | Default | Meaning |
| --- | --- | --- |
| `GROK_API_KEY` | — | xAI API key (`XAI_API_KEY` also accepted) |
| `GROK_MODEL` | `grok-4.7` | Default model for every tool |
| `GROK_BASE_URL` | `https://api.x.ai/v1` | Point at a proxy or regional endpoint |
| `GROK_TIMEOUT` | `120` | Per-request timeout, seconds |
| `GROK_MAX_RETRIES` | `3` | Retries for 429/5xx/network errors |
| `GROK_BACKOFF` | `0.8` | Base backoff, seconds (doubles per attempt, plus jitter) |
| `GROK_MAX_CONCURRENCY` | `4` | In-flight request cap |
| `GROK_MAX_OUTPUT_TOKENS` | — | Global output cap |
| `GROK_MAX_TEXT_CHARS` | `20000` | Truncate long answers (flagged via `truncated`) |
| `GROK_LEDGER` | — | Append every call to a JSONL file |
| `GROK_MCP_MOCK` | `0` | `1` = offline fixture backend |
| `GROK_LOG_LEVEL` | `WARNING` | Logs go to stderr |
`.env` is read from the working directory; real environment variables win. See [.env.example](.env.example).
CLI flags: `--transport stdio|sse|streamable-http`, `--host`, `--port`, `--model`, `--mock`, `--log-level`, `--print-config`, `--version`.
## Design notes
- **Capability tools, not a passthrough.** A generic `grok(payload)` tool pushes the API surface into the model's context and invites malformed calls. Each tool here validates its arguments before a request is spent.
- **Errors as data.** Validation problems and API failures are re-raised as anticipated tool errors, so the calling model gets a message it can act on and the server logs one line instead of a traceback.
- **Everything is metered.** `GrokClient` owns a `UsageLedger`; no call path can skip accounting. Costs are estimates by construction (see [docs/COST.md](docs/COST.md)) and labelled as such rather than presented as invoices.
- **Stdout is sacred.** On stdio transports stdout is the protocol channel. Logging is configured to stderr and the end-to-end test would catch a stray `print`.
- **Mock backend, not mock tests.** CI runs the real process over real MCP, so a broken handshake or a renamed field fails the build.
More in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
## Development
```bash
git clone https://github.com/ruji9527/grok-mcp && cd grok-mcp
uv venv && uv pip install -e ".[dev]"
make check # ruff + mypy + pytest
make demo # offline end-to-end run
```
69 tests, including one that spawns the server over stdio and speaks MCP to it. No API key required for the suite.
## Roadmap
- [ ] Streaming results (`stream=true`) with progress notifications
- [ ] `grok_deep_search` — multi-step research loop with a token budget
- [ ] Vision input: pass an image URL to `grok_ask`
- [ ] Collections/RAG tools (`collections_search`)
- [ ] Price-table auto-refresh from `/v1/models` metadata
- [ ] Docker image for `--transport streamable-http`
Issues and PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). If a tool surprises you, that is a bug report I want.
## License
MIT. Not affiliated with xAI; "Grok" is their trademark, used here to describe what the code talks to.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues