Skip to main content
Glama
GreptimeDB MCP Server

GreptimeDB MCP Server

Official
by GreptimeTeam

greptimedb-mcp-server

PyPI - Version build workflow MCP Registry MIT License

A Model Context Protocol (MCP) server for GreptimeDB — an open-source observability database that handles metrics, logs, and traces in one engine.

Enables AI assistants to query and analyze GreptimeDB using SQL, TQL (PromQL-compatible), and RANGE queries, with built-in security features like read-only enforcement and data masking.

Quick Start

# Install
pip install greptimedb-mcp-server

# Run (connects to localhost:4002 by default)
greptimedb-mcp-server --host localhost --database public

For Claude Desktop, add this to your config (~/Library/Application Support/Claude/claude_desktop_config.json on macOS):

{
  "mcpServers": {
    "greptimedb": {
      "command": "greptimedb-mcp-server",
      "args": ["--host", "localhost", "--database", "public"]
    }
  }
}

Related MCP server: SQLite MCP Server

Features

Tools

Tool

Description

execute_sql

Execute SQL queries with format (csv/json/markdown) and limit options

execute_tql

Execute TQL (PromQL-compatible) queries for time-series analysis

query_range

Execute time-window aggregation queries with RANGE/ALIGN syntax

search_table_semantics

Find tables by observability concept, ranked by matched terms; searches table names, semantic options, and entity declarations. schema selects the database to search

query_semantic_graph

Query the semantic graph: summary (what it contains), entities (nodes), relationships (edges) over a required time window

describe_table

Inspect a table profile: schema, semantic metadata, latest sample rows, and query guidance

explain_query

Analyze SQL or TQL query execution plans (analyze=true for runtime stats; add verbose=true alongside analyze=true for per-partition scan metrics and index-pruning counters)

health_check

Check database connection status and server version

search_table_semantics and the semantic metadata in describe_table read information_schema.table_semantics. A table appears there when it carries a greptime.semantic.* option or a built-in convention derives an entity declaration for it; other tables are absent. The server reads the view's column list once per process and selects only the columns it exposes. entity_declarations requires GreptimeDB 1.3; on earlier versions it is reported as a missing column rather than as an empty declaration set.

Tool results are bounded by GREPTIMEDB_MAX_RESULT_BYTES (default 1048576, or 1 MiB). A query result over the budget returns fewer rows and reports it in truncated and truncation_reason; a result with no rows to shed is cut with a notice at the end. The budget is a backstop against a result too large to be consumed, so lower it if your MCP client rejects results before it is reached.

Cross-database queries

The server connects to one database, but reads are not restricted to it:

Tool

How to reach another database

execute_sql, query_range, describe_table

Qualify the table as schema.table

execute_tql

metric{__schema__="other_db"}, which accepts = only

search_table_semantics

Pass schema

query_semantic_graph

Catalog-wide already; no scoping needed

The connected account needs read permission on the target database. Use SHOW DATABASES to list them.

query_semantic_graph reads greptime_private.semantic_entities and greptime_private.semantic_relationships, which require GreptimeDB 1.3. At startup the server checks that both views exist, carry the columns it reads, and are readable by the connected account; when they are not, the tool is not offered and the reason is logged. Its time window is required and half-open, [start_time, end_time) over observed_at, and rows are aggregated across the 60-second observation buckets in that window.

Pipeline Management

Tool

Description

list_pipelines

List all pipelines or get details of a specific pipeline

create_pipeline

Create a new pipeline with YAML configuration

dryrun_pipeline

Test a pipeline with sample data without writing to database

delete_pipeline

Delete a specific version of a pipeline

Dashboard Management

Tool

Description

list_dashboards

List all Perses dashboard definitions

create_dashboard

Create or update a Perses dashboard definition

delete_dashboard

Delete a dashboard definition

Resources & Prompts

  • Resources: Browse tables via greptime://<table>/data URIs

  • Prompts: Built-in Jinja templates for common tasks — pipeline_creator, log_pipeline, metrics_analysis, promql_analysis, trace_analysis, table_operation, schema_design_advisor, observability_correlation, ingestion_troubleshooting, query_performance_tuning

For LLM integration and prompt usage, see docs/llm-instructions.md.

These tools cover querying and managing data in an existing GreptimeDB. For deployment, server configuration, write protocols, pipeline syntax, schema design, and performance diagnosis, point the assistant at the GreptimeDB skills index at https://docs.greptime.com/SKILL.md.

Configuration

Environment Variables

GREPTIMEDB_HOST=localhost      # Database host
GREPTIMEDB_PORT=4002           # MySQL protocol port (default: 4002)
GREPTIMEDB_USER=root           # Database user
GREPTIMEDB_PASSWORD=           # Database password
GREPTIMEDB_DATABASE=public     # Database name
GREPTIMEDB_TIMEZONE=UTC        # Session timezone

# Optional
GREPTIMEDB_HTTP_PORT=4000      # HTTP API port for pipeline/dashboard management
GREPTIMEDB_HTTP_PROTOCOL=http  # HTTP protocol (http/https)
GREPTIMEDB_POOL_SIZE=5         # Connection pool size
GREPTIMEDB_MASK_ENABLED=true   # Enable sensitive data masking
GREPTIMEDB_MASK_PATTERNS=      # Additional patterns (comma-separated)
GREPTIMEDB_AUDIT_ENABLED=true  # Enable audit logging
GREPTIMEDB_ALLOW_WRITE=false   # Allow writes: DDL/DML plus pipeline and dashboard changes (DANGEROUS, local/test only)
GREPTIMEDB_MAX_RESULT_BYTES=1048576 # Byte budget for a single tool result (1 MiB)

# Transport (for HTTP server mode)
GREPTIMEDB_TRANSPORT=stdio     # stdio, sse, or streamable-http
GREPTIMEDB_LISTEN_HOST=0.0.0.0 # HTTP server bind host
GREPTIMEDB_LISTEN_PORT=8080    # HTTP server bind port
GREPTIMEDB_ALLOWED_HOSTS=      # DNS rebinding protection (comma-separated)
GREPTIMEDB_ALLOWED_ORIGINS=    # CORS allowed origins (comma-separated)

CLI Arguments

greptimedb-mcp-server \
  --host localhost \
  --port 4002 \
  --database public \
  --user root \
  --password "" \
  --timezone UTC \
  --pool-size 5 \
  --mask-enabled true \
  --allow-write false \
  --transport stdio

HTTP Server Mode

For containerized or Kubernetes deployments:

# Streamable HTTP (recommended for production)
greptimedb-mcp-server --transport streamable-http --listen-port 8080

# SSE mode (legacy)
greptimedb-mcp-server --transport sse --listen-port 3000

DNS Rebinding Protection

By default, DNS rebinding protection is disabled for compatibility with proxies, gateways, and Kubernetes services. To enable it, use --allowed-hosts:

# Enable DNS rebinding protection with allowed hosts
greptimedb-mcp-server --transport streamable-http \
  --allowed-hosts "localhost:*,127.0.0.1:*,my-service.namespace:*"

# With custom allowed origins for CORS
greptimedb-mcp-server --transport streamable-http \
  --allowed-hosts "my-service.namespace:*" \
  --allowed-origins "http://localhost:*,https://my-app.example.com"

# Or via environment variables
GREPTIMEDB_ALLOWED_HOSTS="localhost:*,my-service.namespace:*" \
GREPTIMEDB_ALLOWED_ORIGINS="http://localhost:*" \
  greptimedb-mcp-server --transport streamable-http

If you encounter 421 Invalid Host Header errors, either disable protection (default) or add your host to the allowed list.

Security

Create a read-only user in GreptimeDB using static user provider:

mcp_readonly:readonly=your_secure_password

Application-Level Security Gate

All queries go through a security gate that tokenizes SQL with the MySQL dialect rules GreptimeDB applies to the MySQL protocol, so strings, quoted identifiers and comments are delimited the same way the server delimits them.

  • Allows: statements starting with SELECT, WITH, SHOW, DESC, DESCRIBE, EXPLAIN or TQL. Every statement in a multi-statement query is checked.

  • Blocks: every other statement, including DROP, DELETE, UPDATE, INSERT, ALTER, CREATE, TRUNCATE, GRANT, REVOKE, ADMIN, SET, COPY and LOAD

  • Blocks: INSERT, UPDATE, DELETE, MERGE and INTO inside an allowed SQL statement (TQL expressions are not checked for them), and EXPLAIN of a blocked statement

  • Blocks: MySQL executable comments (/*! ... */), prefixed string literals (X'..', N'..'), and unterminated strings or comments

  • Blocks: the word delimiter followed by whitespace outside quotes, because the MySQL client driver rewrites such SQL as a DELIMITER command

Write Mode (Disabled by Default)

The server is read-only by default. Write mode enables every operation that changes stored state:

  • destructive SQL (DDL/DML such as CREATE, DROP, ALTER, INSERT, UPDATE, DELETE) through execute_sql

  • create_pipeline, delete_pipeline, create_dashboard, delete_dashboard

# Environment variable
GREPTIMEDB_ALLOW_WRITE=true greptimedb-mcp-server

# Or CLI argument
greptimedb-mcp-server --allow-write true

When enabled, the security gate is bypassed for execute_sql, and the server logs a warning on startup. With write mode off, those four tools return an error without contacting the server; list_pipelines, list_dashboards and dryrun_pipeline are read-only and stay available.

⚠️ Danger: This lets an AI assistant run destructive statements against your database. Never enable it against production data. Combine with a read-only database user if you only need read access.

Data Masking

Sensitive columns are automatically masked (******) based on column name patterns:

  • Authentication: password, secret, token, api_key, credential

  • Financial: credit_card, cvv, bank_account

  • Personal: ssn, id_card, passport

Configure with --mask-patterns phone,email to add custom patterns.

Audit Logging

All tool invocations are logged:

2025-12-10 10:30:45 - greptimedb_mcp_server.audit - INFO - [AUDIT] execute_sql | query="SELECT * FROM cpu LIMIT 10" | success=True | duration_ms=45.2

Disable with --audit-enabled false.

Development

# Clone and setup
git clone https://github.com/GreptimeTeam/greptimedb-mcp-server.git
cd greptimedb-mcp-server
uv venv && source .venv/bin/activate
uv sync

# Run tests
pytest

# Format & lint
uv run black .
uv run flake8 src

# Debug with MCP Inspector
npx @modelcontextprotocol/inspector uv --directory . run -m greptimedb_mcp_server.server

License

MIT License - see LICENSE.md.

Acknowledgement

Inspired by:

Available Tools

15 tools
create_dashboardA

Create or update a Perses dashboard definition in GreptimeDB.

Overwrites any dashboard already stored under this name. Refused unless the server runs with write mode enabled.

Inputs: name (required), definition (required).

create_pipelineA

Create a new pipeline in GreptimeDB.

Stores a new version of the pipeline; it does not replace existing ones. Refused unless the server runs with write mode enabled.

Inputs: name (required), pipeline (required).

delete_dashboardA

Delete a Perses dashboard definition from GreptimeDB.

Irreversible, and refused unless the server runs with write mode enabled.

Inputs: name (required).

delete_pipelineA

Delete a specific version of a pipeline from GreptimeDB.

Irreversible, and refused unless the server runs with write mode enabled.

Inputs: name (required), version (required).

describe_tableA

Get a table profile: schema, semantic metadata, sample rows, and guidance.

Use it when deciding how to query an unfamiliar table. When the right table
is not known yet, search_table_semantics first; describing candidates one
by one is slower than querying the data.

The semantic profile says what the table means, not what its data says.
signal_type is metric, log, trace, or event; source and source_version name
the ingestion protocol; pipeline names the schema that shaped the rows;
semantic_options carries signal-specific facts such as metric type and
unit. metadata_quality describes how the metric type was obtained --
`declared` by the protocol or `inferred` from the name -- and says nothing
about telemetry quality. entity_declarations lists the entities the table
contributes to the semantic graph. A null or missing semantic field means
unknown, not the opposite fact.

Inputs: table (required), sample_limit, include_samples, include_semantics.

dryrun_pipelineA

Test a pipeline with sample data without writing to the database.

You can test a pipeline in two ways:
- Provide 'pipeline' with inline YAML configuration
- Provide 'pipeline_name' to test a previously saved pipeline

Args:
    pipeline: Pipeline YAML configuration (inline)
    pipeline_name: Name of saved pipeline (mutually exclusive with pipeline)
    data: Test data in JSON/NDJSON format
    data_type: Optional content type (e.g., 'application/x-ndjson')

Inputs: data (required), pipeline, data_type, pipeline_name.

execute_sqlA

Execute SQL query against GreptimeDB. Please use MySQL dialect.

The general query entry point: use it for logs, traces, events, joins
across tables, and metadata queries such as SHOW TABLES. For a plain
metric time series prefer execute_tql, where the table name is the metric
name and PromQL states rate, increase and quantile directly.

Qualify a table as `schema.table` to read a database other than the one
this server connected to; the account needs read permission on it.

Read-only by default. When the server runs with write mode enabled
(--allow-write / GREPTIMEDB_ALLOW_WRITE), destructive SQL (DDL/DML) is
also permitted.

Results are bounded by a byte budget and a row limit clamped to 1-10000.
JSON row results report `truncated`; `truncation_reason` describes rows
dropped for the byte budget. CSV and Markdown report truncation in a text
notice. Lowering `limit` or narrowing filters does not make the original
result complete. SHOW TABLES and SHOW DATABASES return plain text regardless
of format.

Inputs: query (required), limit, format.

execute_tqlA

Execute TQL query for time-series analysis. TQL is PromQL-compatible.

Use it for metric tables, where the table name is the metric name and the
value columns are the PromQL fields. PromQL vector matching can combine
metrics from different tables. Use execute_sql for log or event rows,
trace analysis, and SQL JOINs.

`metric{__schema__="other_db"}` reads a database other than the connected
one. That matcher accepts `=` only.

Returns at most 10000 rows, also bounded by a byte budget. JSON reports
`truncated`; CSV and Markdown append a truncation notice. A shorter time
range or fewer series changes coverage; a larger step lowers resolution.
An untruncated retry with those changes does not cover the original query.

Inputs: end (required), step (required), query (required), start (required), +2 more.

explain_queryC

Analyze SQL or TQL query execution plan.

Inputs: query (required), analyze, verbose.

health_checkA

Check GreptimeDB connection status and server version.

Inputs: no named parameters.

list_dashboardsB

List all Perses dashboard definitions stored in GreptimeDB.

Inputs: no named parameters.

list_pipelinesB

List all pipelines or get details of a specific pipeline.

Inputs: name.

query_rangeA

Execute time-window aggregation query using GreptimeDB's RANGE query syntax.

The narrowest of the three query entry points. Use it for a window
aggregation over a non-metric table, or an alignment PromQL cannot state;
a metric time series is better served by execute_tql and anything else by
execute_sql.

`select` must carry at least one aggregate with its own RANGE, such as
`avg(cpu) RANGE '5m'`, and `align` supplies the step between windows. A
plain column list does not plan. `table` accepts `schema.table` to read a
database other than the connected one.

A larger align lowers resolution; tighter filters or a lower limit return
a subset. An untruncated retry with those changes does not cover the
original query.

Inputs: align (required), table (required), select (required), by, +5 more.

query_semantic_graphA

Query the semantic graph: which entities exist and which are related.

Use view=summary when the entity and relationship types in this graph are
not known yet; it reports them with the endpoint type pairs each
relationship connects. With a type or an id already in hand, query
entities or relationships directly.

The window is required and half-open, [start_time, end_time), over
observed_at. Derived observations use 60-second buckets. Declared edges
instead reflect validity overlapping the window: observed_at is the later
of the validity start and the window start, not a measured event time.

relationships groups by endpoints, relationship type, provenance, and
confidence. For trace-derived calls, the database reports confidence 1.0
for a bucket whose client and server spans paired and 0.5 for one where
only the client was seen, and it switches request_count, error_count and
the durations to whichever population that bucket describes: paired
requests timed by the server span, or unmatched clients
timed by their own. An edge observed both ways therefore comes back as two
rows. unmatched_count reports client spans with no paired server span.
Durations are in seconds. Attribute-derived edges describe identities
observed together, not measured calls. Declared edges retain their supplied
confidence and counts; these are assertions, not span-pairing evidence.

entities returns one row per distinct set of attributes, so an entity whose
descriptive attributes changed inside the window appears more than once;
item_count counts rows, not entities. first_seen and last_seen bound where
the row was observed inside this window, not when the entity first existed.

Ordering is by type and endpoint. Pass rel_type=calls to order by error
and request count instead. When complete is false, more rows matched than
the limit and later types may be absent entirely rather than merely cut short.

A missing edge is not evidence that two entities are unrelated: it can also
mean the call was not instrumented, was sampled out, or fell outside this
window. Entities are not deduplicated across identity schemes, so one
process can appear under two ids if two sources named it differently.

entity_id_attrs names the attributes an id was assembled from and
source_tables names the telemetry tables that witnessed it. Identifiers
from alerts and other tools are not graph ids unless a query here returned
that exact string.

When masking is on, a returned field is hidden if its own name matches a
sensitive pattern, and an attribute map is also masked by the names inside
it. entities additionally hides entity_id when a masked attribute helped
build it; relationships cannot do the same, because its view does not carry
attribute names, so such a value can still appear there as src_id or
dst_id.

Inputs: view (required), end_time (required), start_time (required), limit, +9 more.

search_table_semanticsA

Find tables by observability concept when the right table name is unknown.

Searches table names, semantic options, and entity declarations, and ranks
tables by how many query terms they matched. Use it before describe_table
when the schema is wide or table names do not say what they hold.

It searches schema metadata only, never telemetry row values, so it can say
which table holds Redis memory usage but not which row belongs to
`Redis02`. It ranks on the values in that metadata, not on the schema's own
key names, so search for `gauge` or `bytes` rather than `metric type`. Once
it returns candidates, query their data or describe one of them; do not
describe every candidate in turn.

It searches one database at a time: the connected one by default, or the
one named by `schema`. Use SHOW DATABASES to see what else is there.

Only tables carrying a `greptime.semantic.*` option, or one a built-in
convention derives a declaration for, are visible here. A table absent from
the results may still exist and hold the data, so fall back to SHOW TABLES
rather than concluding it is not there.

Inputs: query (required), limit, schema, signal_type.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 15 tools

    Disambiguation4/5

    The three query entry points (execute_sql, execute_tql, query_range) inherently overlap, but the descriptions explicitly delineate them (query_range is 'the narrowest of the three', metrics go to execute_tql, everything else to execute_sql). describe_table vs. search_table_semantics and the dashboard/pipeline CRUD groups are also clearly separated. Only the query trio carries any residual selection risk.

    Naming Consistency4/5

    Nearly everything is snake_case verb_noun (execute_sql, describe_table, create_pipeline, delete_dashboard), which is predictable. Minor deviations exist: 'dryrun_pipeline' should be 'dry_run_pipeline', and 'health_check' is noun-based rather than verb-based, but these are small blemishes on an otherwise consistent scheme.

    Tool Count5/5

    15 tools is at the top of the ideal band but every one earns its place: query entry points, schema discovery, health, plus compact CRUD for pipelines and dashboards. No filler or duplicate variants.

    Completeness4/5

    Query, discovery, explanation, pipeline CRUD+dryrun, and dashboard create/list/delete are covered, and write-mode gating for DML/DDL is documented. Small gaps remain: there is no get-single-dashboard tool and pipelines lack an explicit version/detail retrievable beyond list_pipelines' overloaded 'details' behavior.

    Maintenance

    ActivityActive
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      A Model Context Protocol server implementation that enables AI assistants to execute SQL queries and interact with SQLite databases through a structured interface.
      7
      MIT
    • A
      license
      B
      quality
      C
      maintenance
      A Model Context Protocol (MCP) server that provides read-only TDengine database queries for AI assistants, allowing users to execute queries, explore database structures, and investigate data directly from AI-powered tools.
      6
      11
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A Model Context Protocol server that provides AI assistants with comprehensive access to SQL databases, enabling schema inspection, query execution, and database operations with enterprise-grade security.
      33 npm
      9
      MIT