# MCP Server

chmonitor exposes a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server at `/api/mcp`. It lets external AI tools — Claude, Cursor, and any MCP-compatible client — query your ClickHouse clusters through the same read-only access the dashboard uses.

---

## Endpoint

| Property | Value |
|---|---|
| URL | `https://your-deployment.example.com/api/mcp` |
| Transport | Streamable HTTP (`POST` / `GET` / `DELETE`) |
| Session | Stateless — no session id required |
| Access | Read-only ClickHouse queries |

The server identifies itself as `clickhouse-monitor`. Pass `hostId` (default `0`) to target a specific host from `CLICKHOUSE_HOST`.

---

## Connect an MCP client

### Claude Desktop

Add to your MCP client config file:

```json
{
  "mcpServers": {
    "clickhouse-monitor": {
      "url": "https://your-deployment.example.com/api/mcp",
      "headers": {
        "Authorization": "Bearer chm_your_api_key"
      }
    }
  }
}
```

Omit `headers` only for a local unauthenticated instance (see [Security](#security) below).

### Cursor

Settings → **MCP** → **Add Server** → paste the endpoint URL. Add an `Authorization: Bearer chm_...` header if auth is enabled.

### Test the connection

```bash
curl -X POST https://your-deployment.example.com/api/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer chm_your_api_key" \
  -d '{"jsonrpc":"2.0","method":"tools/list","id":1}'
```

---

## Authentication

Production deployments should protect the MCP endpoint. Two methods are supported; either one authenticates a request:

**API keys (recommended for scripts and MCP clients):**

Set `CHM_API_KEY_SECRET` and issue `chm_` tokens at `POST /api/v1/auth/api-key`. Send as `Authorization: Bearer chm_...`. Tokens are HMAC-SHA-256 and time-limited.

See [API Keys](/authentication/api-keys) for setup.

**Clerk OAuth (for browser-based MCP clients):**

When `CHM_AUTH_PROVIDER=clerk` is set, `/api/mcp` also accepts Clerk OAuth bearer tokens. The client completes a standard OAuth browser flow; chmonitor acts as the resource server and verifies tokens via Clerk REST introspection using `CLERK_SECRET_KEY`.

See [Authentication](/authentication) for provider setup.

---

## Available tools

The MCP server exposes the same read-only capabilities as the dashboard agent. For a full list of tools, see [AI Agent — Capabilities](/ai-agent/capabilities).

Quick summary of core tools:

| Tool | Description |
|---|---|
| `query` | Execute a read-only SQL query (SELECT only). |
| `list_databases` | List databases with engines and comments. |
| `list_tables` | List tables in a database with row counts and sizes. |
| `get_table_schema` | Column definitions, types, defaults, and comments. |
| `get_metrics` | Server version, uptime, connections, memory. |
| `get_running_queries` | Currently running queries by elapsed time. |
| `get_slow_queries` | Slowest completed queries from the query log. |
| `get_merge_status` | Running merge operations with progress. |
| `explore_table_schema` | Schema exploration with relationship discovery. |
| `analyze_performance` | Combined health report: slow queries, parts, merges, memory, disk. |

All tools are read-only and respect the same `CLICKHOUSE_MAX_EXECUTION_TIME` timeout as the dashboard.

---

## Resources and prompts

The server exposes static and templated resources for context loading:

| Resource | URI |
|---|---|
| System tables reference | `clickhouse://system-tables` |
| Query examples | `clickhouse://query-examples` |
| Database list | `clickhouse://databases` |
| Tables in a database | `clickhouse://databases/{database}/tables` |
| Table schema | `clickhouse://databases/{database}/tables/{table}/schema` |
| Table parts | `clickhouse://databases/{database}/tables/{table}/parts` |

Pre-built prompts for common workflows: `health-check`, `slow-query-analysis`, `storage-audit`, `replication-check`, `capacity-report`.

---

## Security

- **Read-only.** All tools run read-only queries. The server never mutates data.
- **Auth is opt-in.** The endpoint requires a token only once an auth scheme is configured. It accepts a `chm_` API key (`CHM_API_KEY_SECRET`) or a Clerk OAuth bearer token (`CHM_AUTH_PROVIDER=clerk`). Either scheme alone is sufficient; they can coexist on the same endpoint. When a scheme is configured, a missing or invalid token is rejected with `401`.
- **Open when nothing is configured.** If neither `CHM_API_KEY_SECRET` nor Clerk is configured, the endpoint serves anonymous requests — regardless of `NODE_ENV`. This is the self-hosted default; close it by configuring either scheme. Keep an unconfigured endpoint on a trusted network.
- **Shared credentials.** Queries use the dashboard's configured ClickHouse user. Visibility is bounded by that user's grants.

> Do not expose the MCP endpoint publicly without setting `CHM_API_KEY_SECRET`. Anyone with access can read all data the ClickHouse user can see.

See [Environment Variables](/reference/environment-variables) for `CHM_API_KEY_SECRET` and auth variables.
See [Features — MCP](/features/mcp) for more on the MCP feature and how to gate it.
