# Altinity MCP Server [![Coverage Status](https://coveralls.io/repos/github/Altinity/altinity-mcp/badge.svg)](https://coveralls.io/github/Altinity/altinity-mcp) A Model Context Protocol (MCP) server that provides tools for interacting with ClickHouse® databases. This server enables AI assistants and other MCP clients to query, analyze, and interact with ClickHouse® databases through a standardized protocol. ## Features - **Multiple Transport Options**: Support for STDIO, HTTP, and Server-Sent Events (SSE) transports - **Stateless MCP Protocol**: The HTTP transport serves the stateless MCP protocol (spec revision 2026-07-28) — no session affinity required, safe to run behind round-robin load balancers; older clients transparently negotiate down to 2025-11-25 and earlier - **OAuth 2.0 Authorization**: Broker OAuth flows from MCP clients against any OIDC provider; auto-detects Bearer vs Basic auth for ClickHouse (see [OAuth 2.0 Documentation](docs/oauth_authorization.md)) - **JWE Authentication**: Optional JWE-based authentication with encryption for secure database access - **TLS Support**: Full TLS encryption support for both ClickHouse® connections and MCP server endpoints - **Comprehensive Tools**: Built-in tools for listing tables, describing schemas, and executing queries - **Dynamic Tools**: Automatically generate MCP tools from ClickHouse® views and tables (see [Tools Documentation](docs/tools.md)) - **Resource Templates**: Dynamic resource discovery for database schemas and table information - **Query Prompts**: AI-assisted query building and optimization prompts - **Configuration Management**: Flexible configuration via files, environment variables, or CLI flags - **Hot Reload**: Dynamic configuration reloading without server restart ## Table of Contents - [Quick Start](#quick-start) - [Integration Guide](#integration-guide) - [Installation & Deployment](#installation--deployment) - [Configuration](#configuration) - [Available Tools](#available-tools) - [Available Resources](#available-resources) - [Available Prompts](#available-prompts) - [OpenAI GPTs Integration](#openai-gpts-integration) - [OAuth 2.0 Authorization](#oauth-20-authorization) - [JWE Authentication](#jwe-authentication) - [TLS Configuration](#tls-configuration) - [Development & Testing](#development--testing) - [CLI Reference](#cli-reference) - [Contributing](#contributing) - [License](#license) - [Support](#support) ## Quick Start ### Using STDIO Transport (Default) ```bash # Basic usage with default settings ./altinity-mcp --clickhouse-host localhost --clickhouse-port 8123 # With custom database and credentials ./altinity-mcp \ --clickhouse-host clickhouse.example.com \ --clickhouse-port 9000 \ --clickhouse-protocol tcp \ --clickhouse-database analytics \ --clickhouse-username reader \ --clickhouse-password secret123 \ --clickhouse-limit 5000 ``` ### Using HTTP Transport with OpenAPI ```bash ./altinity-mcp \ --transport http \ --address 0.0.0.0 \ --port 8080 \ --clickhouse-host localhost \ --openapi http ``` ### Using SSE Transport with JWE Authentication and OpenAPI ```bash ./altinity-mcp \ --transport sse \ --port 8080 \ --allow-jwe-auth \ --jwe-secret-key "your-jwe-encryption-secret" \ --jwt-secret-key "your-jwt-signing-secret" \ --clickhouse-host localhost \ --openapi http ``` ## Integration Guide For detailed instructions on integrating Altinity MCP with various AI tools and platforms, see our [Integration Guide](docs/howto_integrate.md). ## Installation & Deployment ### Using Docker ```bash docker run -it --rm ghcr.io/altinity/altinity-mcp:latest --clickhouse-host clickhouse ``` ### Kubernetes with Helm From OCI helm registry (recommended) ```bash # Install from OCI registry helm install altinity-mcp oci://ghcr.io/altinity/altinity-mcp/helm/altinity-mcp \ --set config.clickhouse.host=clickhouse.example.com \ --set config.clickhouse.database=default \ --set config.clickhouse.limit=5000 ``` From local helm chart ```bash git clone https://github.com/Altinity/altinity-mcp cd altinity-mcp helm install altinity-mcp ./helm/altinity-mcp \ --set config.clickhouse.host=clickhouse-service \ --set config.clickhouse.database=analytics \ --set config.server.transport=http \ --set config.server.port=8080 ``` From a tag-published GHCR image ```bash helm install altinity-mcp oci://ghcr.io/altinity/altinity-mcp/helm/altinity-mcp \ --set image.tag= \ --set config.clickhouse.host=clickhouse.example.com \ --set config.clickhouse.database=default ``` For detailed Helm chart configuration options, see [Helm Chart README](helm/altinity-mcp/README.md). ### Docker Compose ```yaml version: '3.8' services: altinity-mcp: build: . ports: - "8080:8080" environment: - CLICKHOUSE_HOST=clickhouse - MCP_TRANSPORT=http - MCP_PORT=8080 depends_on: - clickhouse entrypoint: ["/bin/sh", "-c", "/bin/altinity-mcp"] clickhouse: image: clickhouse/clickhouse-server:latest ports: - "8123:8123" ``` ### With installed golang ```bash go install github.com/altinity/altinity-mcp/cmd/altinity-mcp@latest $(go env GOPATH)/bin/altinity-mcp --help ``` ### From Source ```bash git clone https://github.com/altinity/altinity-mcp.git cd altinity-mcp go build -o altinity-mcp ./cmd/altinity-mcp ``` ## Configuration ### Configuration File Create a YAML or JSON configuration file: ```yaml # config.yaml clickhouse: host: "localhost" # Optional TCP destination override. The logical host above remains the # HTTP Host header and TLS SNI/certificate verification name. connect_host: "" port: 8123 database: "default" username: "default" password: "" protocol: "http" read_only: false max_execution_time: 600 tls: enabled: false ca_cert: "" client_cert: "" client_key: "" insecure_skip_verify: false server: transport: "stdio" address: "0.0.0.0" port: 8080 tls: enabled: false cert_file: "" key_file: "" ca_cert: "" jwt: enabled: false secret_key: "" openapi: enabled: false tls: false metrics: enabled: false dynamic_tools: - regexp: "mydb\\..*" prefix: "db_" - name: "get_user_data" regexp: "users\\.user_info_view" logging: level: "info" ``` When `connect_host` is set, it takes precedence over `HTTP_PROXY` and `HTTPS_PROXY` for ClickHouse HTTP connections so the configured address is always the TCP destination. Environment proxy behavior is unchanged when `connect_host` is empty. > **Note**: For detailed information about dynamic tools configuration, see the [Tools Documentation](docs/tools.md). Use the configuration file: ```bash ./altinity-mcp --config config.yaml ``` ### Environment Variables Every configuration field with a `flag:` tag in [pkg/config/config.go](pkg/config/config.go) is settable via CLI flag or env var. The CLI flag and env-var name are listed in the field's `flag:` and `env:` tags. `altinity-mcp --help` prints the full surface. Common examples: ```bash export CLICKHOUSE_HOST=localhost export CLICKHOUSE_PORT=8123 export CLICKHOUSE_DATABASE=analytics export CLICKHOUSE_LIMIT=5000 export MCP_TRANSPORT=http export MCP_PORT=8080 export MCP_METRICS_ENABLED=true export LOG_LEVEL=debug # OAuth — env-var injection lets operators pull secrets from a Kubernetes # Secret via `valueFrom.secretKeyRef` instead of committing them to YAML. export MCP_OAUTH_ENABLED=true export MCP_OAUTH_BROKER=true export MCP_OAUTH_ISSUER=https://accounts.example.com export MCP_OAUTH_SIGNING_SECRET=... ./altinity-mcp ``` Special flags that don't follow this pattern: `--config` (config file path), `--config-reload-time`, `--openapi` (one flag → two struct fields). See `altinity-mcp --help`. ### Prometheus metrics HTTP and SSE transports (including JWE and multicluster modes) expose `/metrics` when `server.metrics.enabled`, `MCP_METRICS_ENABLED`, or `--metrics-enabled` is true. Metrics are disabled by default, and a disabled server is a true no-op: no `/metrics` route, no request middleware, no query instrumentation, and no collectors registered. `server.metrics.enabled` is **restart-only**. A config reload that changes it logs a warning and keeps the running value, because the route and middleware are bound when the HTTP server starts. The endpoint serves the standard Go runtime and process collectors plus: | Metric | Type | Labels | Meaning | |---|---|---|---| | `altinity_mcp_http_requests_total` | counter | `route`, `method`, `status` | Requests by registered route pattern, normalized method (`GET`, `POST`, ..., `other`) and status class (`2xx`, `4xx`, ...) | | `altinity_mcp_http_request_duration_seconds` | histogram | `route` | End-to-end handler latency | | `altinity_mcp_clickhouse_queries_total` | counter | `kind`, `outcome` | ClickHouse queries by `select`/`execute` and `ok`/`error` | | `altinity_mcp_clickhouse_query_duration_seconds` | histogram | `kind` | ClickHouse round-trip latency | | `altinity_mcp_clickhouse_query_rows` | histogram | `kind` | Rows returned by successful queries | | `altinity_mcp_clickhouse_query_bytes` | histogram | `kind` | Approximate bytes returned by successful queries | | `altinity_mcp_blocked_clause_rejections_total` | counter | `clause` | Queries rejected by `blocked_query_clauses` | | `altinity_mcp_clickhouse_up` | gauge | | `1`/`0` from the last `/health` readiness ping; `NaN` in JWE/OAuth modes where no static credentials exist | | `altinity_mcp_catalog_cache_*` | gauge/counter | | Multicluster catalog-cache activity (multicluster mode only) | Every label is drawn from a fixed set: route labels use registered patterns rather than raw URLs (so JWE tokens never appear), methods outside the standard set collapse to `other`, and status codes collapse to their class. The `/metrics` endpoint is unauthenticated. Restrict network access to it in the same way you would for `/health`. The Helm chart uses `metrics.enabled` for the endpoint. Set `metrics.serviceMonitor.enabled` as well to create a Prometheus Operator `ServiceMonitor` that scrapes the existing HTTP service port. When `config.server.tls.enabled` is true the ServiceMonitor scrapes over `https` automatically; supply `metrics.serviceMonitor.tlsConfig` if Prometheus does not trust the server certificate. ## Available Tools ### `execute_query` Executes SQL queries against ClickHouse® with optional result limiting. MCP tool safety annotations: - When the server runs with `--read-only`, `execute_query` is exposed as read-only. - Otherwise `execute_query` is marked as potentially destructive. **Parameters:** - `query` (required): The SQL query to execute - `limit` (optional): Maximum number of rows to return (default: server configured limit, max: 10,000) ### Dynamic Tools Dynamic tools generated from ClickHouse views are always exposed as read-only MCP tools with explicit safety hints. View `COMMENT` supports either: - A plain string description. - A strict JSON object with top-level `title`, `description`, and `annotations`. See [Tools Documentation](docs/tools.md) for examples and supported metadata. ## Available Resources ### `clickhouse://schema` Provides complete schema information for the ClickHouse® database in JSON format. ### `clickhouse://table/{database}/{table}` Provides detailed information about a specific table including schema, sample data, and statistics. ## Available Prompts No prompts currently available ## OpenAI GPTs Integration The Altinity MCP Server supports seamless integration with OpenAI GPTs through its OpenAPI-compatible endpoints. These endpoints enable GPT assistants to perform ClickHouse® database operations directly. OpenAI MCP/tooling references: - [Apps SDK Reference](https://developers.openai.com/apps-sdk/reference) - [Define tools](https://developers.openai.com/apps-sdk/plan/tools) - [Build your MCP server](https://developers.openai.com/apps-sdk/build/mcp-server) - [MCP concepts / server docs](https://developers.openai.com/apps-sdk/concepts/mcp-server) ### Authentication - **With JWE**: Add the JWE token to either: 1. Path parameter: `/{jwe_token}/openapi/...` 2. Authorization header: `Bearer {token}` (alternative) 3. `x-altinity-mcp-key` header (alternative) - **With OAuth**: Send `Authorization: Bearer {token}`. - **With both**: A self-contained JWE takes priority; otherwise OAuth supplies the credentials. - **With both disabled**: Use server-configured ClickHouse credentials. The exact `/openapi` schema route also requires authentication when either mode is enabled. Dynamic HTTP/SSE tools and OpenAPI schemas use catalogs isolated by the caller's effective credential; server credentials are never a fallback under authentication. An effective configuration change resets catalog generations and requires existing SSE clients to reconnect. Unchanged reload polls preserve sessions. See [dynamic discovery](docs/tools.md#dynamic-discovery). ### Available Actions #### 1. Execute Read-only SQL Query **Path**: `/openapi/execute_query` **Parameters**: - `jwe_token` (path param): JWE authentication token - `query` (query param): Read-only SQL query to execute (required); writes are always rejected, even when `clickhouse.read_only: false`. - `limit` (query param): Maximum rows to return (optional, default 1000, max 10000) **Example OpenAPI Path**: ``` GET /{jwe_token}/openapi/execute_query?query=SELECT%20*%20FROM%20table&limit=500 ``` `clickhouse.max_query_length` bounds the query in bytes and dynamic-tool JSON bodies (default 10 MiB; negative disables the limit). Oversized inputs return HTTP 413 before contacting ClickHouse. OpenAPI does not expose `write_query`. ### Configuration Example for GPTs ```json { "openapi": "3.1.0", "info": { "title": "ClickHouse® SQL Interface", "version": "1.0.0" }, "servers": [ {"url": "https://your-server:8080/{token}"} ], "paths": { "/{jwe_token}/openapi/execute_query": { "get": { "operationId": "execute_query", "parameters": [ { "name": "jwe_token", "in": "path", "required": true, "schema": {"type": "string"} }, { "name": "query", "in": "query", "required": true, "schema": {"type": "string"} }, { "name": "limit", "in": "query", "schema": {"type": "integer"} } ] } } } } ``` > **Note**: For Altinity Cloud deployments, use the provided endpoint URL with your organization-specific token. ## Authentication and Authorization JWE takes priority when the token carries nonempty `host` and `username` claims. A complete JWE uses its own connection fields without OAuth overrides. Partial JWE claims fall through to OAuth and cannot alter its configured endpoint. Invalid encrypted tokens are rejected. ### OAuth 2.0 Authorization The MCP server supports OAuth 2.0/OpenID Connect authentication, with Bearer tokens presented to ClickHouse or verified locally. This enables MCP clients to authenticate via an Identity Provider (Keycloak, Azure AD, Google, AWS Cognito) and use token-based ClickHouse authentication via `token_processors`. OAuth headers, query settings, and role activation are isolated per request and cluster; forwarding a caller's bearer token does not change the configured ClickHouse headers or later requests. For full setup instructions, provider-specific guides, and ClickHouse configuration, see the [OAuth 2.0 Authorization Documentation](docs/oauth_authorization.md). ### JWE Authentication When JWE authentication is enabled, the server expects tokens encrypted using AES Key Wrap (A256KW) and AES-GCM (A256GCM). These tokens contain ClickHouse® connection parameters: ```json { "host": "clickhouse.example.com", "port": 8123, "database": "analytics", "username": "user123", "password": "secret", "protocol": "http", "secure": "false" } ``` JWE tokens are self-contained: `host` and `username` are required. An absent or empty `password` remains empty. Server endpoint, credentials, headers, roles, and TLS settings never fill missing claims. Only operational protocol and query settings are inherited; an omitted port defaults to 8123 (HTTP) or 9000 (TCP). Regenerate older tokens that relied on server connection defaults. Nonempty token TLS file paths require `server.jwe.tls_material_dir` (`--jwe-tls-material-dir`, `MCP_JWE_TLS_MATERIAL_DIR`). Paths must remain inside that operator-controlled directory after symlink resolution. See the [JWE migration and TLS allowlist guide](docs/jwe_authentication.md#self-contained-connection-contract). The HTTP/SSE `/jwe-token-generator` endpoint is disabled by default. To enable administrative issuance, set `server.jwe.token_generator.enabled: true` and inject `MCP_JWE_TOKEN_GENERATOR_ADMIN_TOKEN` with at least 32 bytes. Each request requires that secret as an `Authorization: Bearer` token. Keep this endpoint on a trusted administrative network and exclude it from public ingress. See the [generator setup and request limits](docs/jwe_authentication.md#jwe-token-generation-endpoint). Generate tokens using the provided utility. ```bash go run ./cmd/jwe_auth/jwe_token_generator.go \ --jwe-secret-key "your-jwe-encryption-secret" \ --jwt-secret-key "your-jwt-signing-secret" \ --host "clickhouse.example.com" \ --port 8123 \ --database "analytics" \ --username "user123" \ --password "password123" \ --expiry 86400 ``` More details in [jwe_authentication.md](docs/jwe_authentication.md) ## TLS Configuration ### ClickHouse® TLS ```bash ./altinity-mcp \ --clickhouse-tls \ --clickhouse-tls-ca-cert /path/to/ca.crt \ --clickhouse-tls-client-cert /path/to/client.crt \ --clickhouse-tls-client-key /path/to/client.key ``` ### Server TLS ```bash ./altinity-mcp \ --transport https \ --server-tls \ --server-tls-cert-file /path/to/server.crt \ --server-tls-key-file /path/to/server.key ``` ## Development & Testing Development workflow, build commands, test tiers, and the optional OAuth Docker e2e flow are documented in [docs/development_and_testing.md](docs/development_and_testing.md). For the full OAuth setup and ClickHouse-specific details, see the [OAuth 2.0 Authorization Documentation](docs/oauth_authorization.md). ## CLI Reference ### Global Flags - `--config`: Path to configuration file (YAML or JSON) - `--log-level`: Logging level (debug/info/warn/error) - `--clickhouse-limit`: Default limit for query results (default: 1000) - `--openapi`: Enable OpenAPI endpoints (disable/http/https) (default: disable) ### ClickHouse® Flags - `--clickhouse-host`: ClickHouse® server host - `--clickhouse-connect-host`: Optional hostname or IP used only for the underlying TCP connection (`CLICKHOUSE_CONNECT_HOST`) - `--clickhouse-port`: ClickHouse® server port - `--clickhouse-database`: Database name - `--clickhouse-username`: Username - `--clickhouse-password`: Password - `--clickhouse-protocol`: Protocol (http/tcp) - `--read-only`: Read-only mode (prevents non-read SQL and avoids setting session variables) - `--clickhouse-max-execution-time`: Query timeout in seconds - `--clickhouse-http-headers`: HTTP headers for ClickHouse requests (key=value pairs) ### Server Flags - `--transport`: Transport type (stdio/http/sse) - `--address`: Server address - `--port`: Server port - `--allow-jwe-auth`: Enable JWE authentication - `--jwe-secret-key`: Secret key for JWE token decryption (must be 32 bytes for A256KW). - `--jwt-secret-key`: Secret key for JWT signature verification - `--jwe-tls-material-dir`: Directory allowlist for JWE TLS file paths (empty denies token file paths) - `--jwe-token-generator`: Enable administrative JWE token issuance (default false; `MCP_JWE_TOKEN_GENERATOR_ENABLED`) - `--jwe-token-generator-admin-token`: Admin bearer secret of at least 32 bytes (prefer `MCP_JWE_TOKEN_GENERATOR_ADMIN_TOKEN` secret injection) - `--jwe-token-generator-max-expiry-seconds`: Maximum issued token lifetime (default 86400; `MCP_JWE_TOKEN_GENERATOR_MAX_EXPIRY_SECONDS`) ### Commands - `version`: Show version information - `test-connection`: Test ClickHouse® connection ## Contributing 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests 5. Run the test suite 6. Submit a pull request ## License This project is licensed under the Apache License 2.0. See the LICENSE file for details. ## Support For support and questions: - GitHub Issues: [https://github.com/altinity/altinity-mcp/issues](https://github.com/altinity/altinity-mcp/issues) - Email: support@altinity.com