Skip to main content
Glama
README.md
# x-search-mcp

[中文说明](README.zh-CN.md)

A standalone [MCP](https://modelcontextprotocol.io) server that gives any MCP client (Claude Code, Codex, Cursor, Orca, …) live search over X (Twitter) through xAI's server-side **X Search** tool. Grok fetches and reads the posts, then answers with citations to the posts it used.

- One Python file, standard library only, no dependencies.
- stdio transport, JSON-RPC 2.0.
- Two tools: `x_search` and `x_search_status`.
- Three depths per call: `standard` (one agent), `deep` (4 agents), `deep_max` (16 agents).
- Auth with an `XAI_API_KEY`, or with an optional xAI OAuth login (read the [Authentication](#authentication) caveats first).

## Why this over Hermes' built-in `x_search`

This project started as a standalone port of the `x_search` tool in [Hermes Agent](https://github.com/NousResearch/hermes-agent) (MIT, Nous Research; see [NOTICE](NOTICE)). The request format, filters, validation and `degraded` flag come from there. What it adds is per-call control over how hard Grok searches, and the ability to run outside Hermes.

The comparison below is against the Hermes `tools/x_search_tool.py` source as of November 2026. Hermes changes quickly, so check the current source before relying on it.

| | x-search-mcp | Hermes built-in `x_search` |
|---|---|---|
| Depth per call | `depth`: `standard` (grok-4.7, one agent), `deep` (`grok-4.20-multi-agent`, 4 agents), `deep_max` (16 agents) | No per-call depth. One model for every call, set in config (`x_search.model`, default `grok-4.5`). You can set the multi-agent model there, but then every call uses it. |
| Reasoning effort | `reasoning_effort` per call (`low` / `medium` / `high` / `xhigh`), default `high` | Config only (`x_search.reasoning_effort`); unset by default, so the model default applies |
| Default model | `grok-4.7` (override with `X_SEARCH_MCP_MODEL`) | `grok-4.5` |
| Handle filters | `allowed_x_handles` / `excluded_x_handles`, up to 20 (xAI's documented limit) | Same filters, capped at 10 |
| Date range, image / video understanding | Yes | Yes (same) |
| Client-side date validation (format, order, not in the future) | Yes | Yes (same) |
| `degraded` flag | Yes | Yes (same logic) |
| Where it runs | Any MCP client, as its own process | Inside Hermes only |
| Dependencies | Python standard library | Hermes runtime (`requests`, config system) |
| Tool description guides the calling agent | Says when to escalate depth, and what to do on timeout or no citations | Shorter, read-only usage note |

What Hermes has and this project does not:

- **API key first.** Hermes uses `XAI_API_KEY` before OAuth when both exist. Its source notes that the subscription OAuth token can answer `/v1/responses` without citations. This project tries OAuth first (see [Authentication](#authentication)).
- **Config file.** Hermes reads model, effort, timeout and retries from its config. This project uses environment variables and tool arguments.
- **More retries.** Hermes retries 5xx and timeouts twice by default; this project retries once.
- **Richer HTTP error messages** (Hermes includes the xAI error code).
- **Earlier OAuth refresh.** Hermes refreshes the token up to an hour before expiry; this project refreshes 2 minutes before.

Neither one exposes xAI's `max_turns` or returns the per-request post counts (`x_posts_fetched`).

## How it differs from asking Grok on grok.com or in the X app

- You call it from your own agent, so the agent decides the query, filters and depth, and gets JSON back (answer, citations, inline citation spans, `degraded`).
- You can scope a search to specific accounts and a date range. These filters are applied by xAI to every keyword and semantic search the model runs.
- The API bills per post fetched (see [Cost](#cost)). The consumer Grok apps are covered by your subscription instead.
- No chat history is stored: requests are sent with `store: false`.

## Install

Requires Python 3.9+. The package is not on PyPI. Install from GitHub, not by bare name.

```bash
# pipx
pipx install git+https://github.com/wousp112/x-search-mcp.git

# or uv
uv tool install git+https://github.com/wousp112/x-search-mcp.git
```

Either one puts an `x-search-mcp` command on your PATH.

Or run it from a clone with no install at all:

```bash
git clone https://github.com/wousp112/x-search-mcp.git
cd x-search-mcp
./bin/x-search-mcp --help          # or: python3 x_search_mcp.py --help
```

## Authentication

The server looks for credentials in this order:

1. A stored OAuth login in `~/.x-search-mcp/auth.json` (refreshed automatically).
2. The `XAI_API_KEY` environment variable (optional `XAI_BASE_URL`, default `https://api.x.ai/v1`).

If an OAuth login exists, it wins over `XAI_API_KEY`. Run `x-search-mcp auth logout` if you want the API key to be used.

### Option A: API key (recommended)

Create a key at [console.x.ai](https://console.x.ai) and pass it to the server as `XAI_API_KEY`. This is xAI's documented way to use the API, it is billed to your API account, and citations are returned reliably.

### Option B: xAI OAuth login (read this first)

```bash
x-search-mcp auth login               # opens a browser
x-search-mcp auth login --no-browser  # prints the URL instead
x-search-mcp auth status              # add --json for machine-readable output
x-search-mcp auth logout
```

What this does, exactly:

- It runs an OAuth 2.0 authorization-code flow with PKCE against `auth.x.ai`, with a local callback on `127.0.0.1:56121`.
- **It does not use a client registered for this project.** The `client_id` (`b1a00492-073a-47ea-816f-4c329264a828`) and the scope (`openid profile email offline_access grok-cli:access api:access`) are copied from Hermes Agent's xAI login. The `grok-cli:access` scope suggests the client was issued for a Grok CLI integration.
- Hermes describes this login as "sign in with your SuperGrok subscription". So you probably need a SuperGrok (or similar paid Grok) subscription. We have not verified which plans work.
- We do not know how xAI bills X Search calls made with a subscription token, or whether they count against subscription limits.
- Hermes' source notes that this token can return answers **without citations**. When that happens and you used a handle or date filter, the result is marked `degraded: true`. Without filters, an uncited answer is not flagged, so check the `citations` field yourself.
- Tokens are stored in plain JSON at `~/.x-search-mcp/auth.json` with file mode `0600`.

**Check xAI's terms yourself before you use Option B.** Using another application's OAuth client may not be allowed. If you are unsure, use an API key.

## Configure your MCP client

The examples assume the `x-search-mcp` command is on your PATH. From a clone, use the absolute path to `bin/x-search-mcp` instead. The server subcommand is always `serve`.

### Claude Code

```bash
claude mcp add x-search -e XAI_API_KEY=xai-your-key -- x-search-mcp serve
# add --scope user to make it available in every project
```

### Codex CLI

```bash
codex mcp add x-search --env XAI_API_KEY=xai-your-key -- x-search-mcp serve
```

Or edit `~/.codex/config.toml`:

```toml
[mcp_servers.x-search]
command = "x-search-mcp"
args = ["serve"]
env = { XAI_API_KEY = "xai-your-key" }
# deep_max can take several minutes:
tool_timeout_sec = 600
```

### Cursor

`~/.cursor/mcp.json` (global) or `.cursor/mcp.json` (project):

```json
{
  "mcpServers": {
    "x-search": {
      "command": "x-search-mcp",
      "args": ["serve"],
      "env": { "XAI_API_KEY": "xai-your-key" }
    }
  }
}
```

### Orca

Give a bot the server as its own tool:

```bash
orca bot tools add "x-search-mcp serve" --name x-search --bot <bot-name>
```

The server process needs `XAI_API_KEY` in its environment, or a prior `x-search-mcp auth login`.

### Any other client

Run `x-search-mcp serve` as a stdio MCP server. It speaks newline-delimited JSON-RPC 2.0 and implements `initialize`, `tools/list` and `tools/call`.

## Tools

### `x_search`

| Argument | Type | Default | Meaning |
|---|---|---|---|
| `query` | string | required | What to look up on X. Plain language works, Chinese included. |
| `depth` | `standard` \| `deep` \| `deep_max` | `standard` | `standard`: `grok-4.7`, one agent, for facts and normal research. `deep`: `grok-4.20-multi-agent` with 4 agents that search and cross-check in parallel. `deep_max`: 16 agents, for questions that split into several independent sub-questions or when `deep` returns conflicting or thin evidence. |
| `reasoning_effort` | `low` \| `medium` \| `high` \| `xhigh` | `high` | Only used with `depth=standard`. For the deep depths, the effort is fixed (`medium` = 4 agents, `high` = 16 agents), because on the multi-agent model the effort sets the agent count. |
| `allowed_x_handles` | string[] | — | Only posts from these accounts, without `@`, max 20. |
| `excluded_x_handles` | string[] | — | Ignore posts from these accounts, max 20. Cannot be combined with `allowed_x_handles`. |
| `from_date` | `YYYY-MM-DD` | — | Start date (00:00 UTC). Must not be in the future. |
| `to_date` | `YYYY-MM-DD` | — | End date, exclusive. For one day, set it to the next day. |
| `enable_image_understanding` | bool | `false` | Let Grok look at images in matching posts (billed as image tokens). |
| `enable_video_understanding` | bool | `false` | Let Grok watch videos in matching posts. |

Bad dates, conflicting handle filters and unknown depths are rejected before any network call, so they cost nothing.

The result is JSON:

```json
{
  "success": true,
  "credential_source": "xai",
  "model": "grok-4.7",
  "depth": "standard",
  "reasoning_effort": "high",
  "query": "...",
  "answer": "...",
  "citations": ["https://x.com/..."],
  "inline_citations": [{"url": "...", "title": "...", "start_index": 0, "end_index": 42}],
  "degraded": false,
  "degraded_reason": null
}
```

`degraded: true` means you used a handle or date filter, but xAI returned no citations at all. The answer then probably came from the model's own knowledge, not from X. Treat it as unverified.

On failure you get `success: false` with `error`, `error_type`, and `status_code` for HTTP errors.

### `x_search_status`

No arguments. It reports whether a credential is available, which source is active, and whether the OAuth token is expired. Tokens and keys are shown redacted (first 4 and last 4 characters).

### Environment variables

| Variable | Default | Meaning |
|---|---|---|
| `XAI_API_KEY` | — | xAI API key |
| `XAI_BASE_URL` | `https://api.x.ai/v1` | API base URL used with `XAI_API_KEY` |
| `X_SEARCH_MCP_MODEL` | `grok-4.7` | Model for `depth=standard` |
| `X_SEARCH_MCP_DEEP_MODEL` | `grok-4.20-multi-agent` | Model for `deep` and `deep_max` |
| `X_SEARCH_MCP_TIMEOUT_SECONDS` | `180` | Request timeout (doubled for deep depths) |
| `X_SEARCH_MCP_RETRIES` | `1` | Retries on 5xx and network errors |
| `X_SEARCH_MCP_XAI_BASE_URL` | — | Base URL stored at OAuth login (must be on `x.ai`) |

## Cost

With an API key, xAI bills two things ([pricing](https://docs.x.ai/developers/pricing), checked November 2026):

- **Tokens** for the model you use (input, reasoning, output, and image tokens if image or video understanding is on).
- **X Search items fetched:** $5 per 1,000 posts and $10 per 1,000 user profiles. Every post returned by a search or thread fetch counts, including parent and quoted posts. Duplicates count again.

The model decides how many searches to run, so cost grows with the question. `deep` and `deep_max` cost more, because each agent runs its own searches and reasoning. xAI says the 16-agent setup "uses significantly more tokens" than the 4-agent one.

To spend less: use `standard` unless you need cross-checking, narrow the query with handles and dates, and split broad questions into smaller ones.

## FAQ

**I get answers with no citations.**
If you are logged in with OAuth, try an API key: run `x-search-mcp auth logout` and set `XAI_API_KEY`. Also narrow the query. Don't resend the same query unchanged.

**A call timed out.**
`deep_max` can take minutes. Raise your MCP client's tool timeout and `X_SEARCH_MCP_TIMEOUT_SECONDS`. Or use `deep`, or split the question.

**Can it post, like, or read my DMs?**
No. It is read-only search over public X content through xAI. It never touches your X account.

**Which depth should I use?**
`standard` for most questions. `deep` when the answer matters and you want 4 agents to cross-check. `deep_max` when the question has 4 or more independent parts, or when `deep` came back with conflicting claims or too few citations. More agents help little on a narrow question.

**Where are my credentials stored?**
Only in `~/.x-search-mcp/auth.json`, and only if you use `auth login`. API keys are read from the environment and never written to disk.

**Is this affiliated with xAI, X, or Nous Research?**
No.

## Agent skill

[`skills/x-search/SKILL.md`](skills/x-search/SKILL.md) is a short skill for Claude Code, Codex and other agents that support skills. It tells the agent when to use the tool, how to pick a depth, and how to treat `degraded` results. Copy the `skills/x-search` folder into your agent's skills directory (for example `~/.claude/skills/`).

## Development

```bash
python3 -m unittest discover -s tests -v
```

The tests mock all network calls.

## License

MIT. See [LICENSE](LICENSE) and [NOTICE](NOTICE).

TDQS

A3.9/5.0

Scored across 2 tools

Disambiguation5/5

The two tools serve entirely different purposes: x_search performs the search operation, while x_search_status only reports credential validity. There is no realistic scenario where an agent would confuse them, and the status tool is clearly framed as a diagnostic rather than a search variant.

Naming Consistency5/5

Both names use a shared snake_case prefix (x_search, x_search_status), with the status tool predictably derived from the base name. The convention is simple and uniformly applied across the entire surface.

Tool Count3/5

Two tools is on the thin side even for a single-capability server; the status check is a sensible addition but the surface still boils down to one real operation. It is not mismatched to the narrow purpose, but there is little room for an agent to choose or compose.

Completeness3/5

Search is covered, but there is no direct way to fetch a specific post, thread, or profile by ID, and no exposed parameter surface (date range, account filters, pagination) beyond what the description says to embed in the query. Agents hitting timeouts or empty citations are told to fall back to other sources rather than to a complementary tool in this server.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues