Token导航 LogoToken导航TokenDH.com
Citus MCP logo
数据服务SSE官方级别未说明来源级核验

Citus MCP

MCP Server

Citus MCP是一个AI驱动的服务器,用于管理Citus分布式PostgreSQL集群,提供集群检查、智能建议和实时监控功能。

工具数

69

提示词数

0

GitHub Stars

2

资源数

0
集群管理PostgreSQLCursorCursorVS Code

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

codeforall

提供方

codeforall

最后核验

2026/5/17 20:43

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

详细介绍

Citus MCP服务器

用于管理Citus分布式PostgreSQL集群的人工智能驱动的MCP服务器

](https://golang.org) ![License](LICENSE) ![Citus](https://www.citusdata.com) ![PostgreSQL](https://www.postgresql.org)

快速开始特性安装配置工具参考示例

______________________________________________________________________

📖 什么是Citus MCP?

Citus MCP是一家 模型上下文协议(MCP) 服务器,使GitHub Copilot等AI助手能够与您的Citus分布式PostgreSQL集群进行交互。它提供:

特性描述
🔍 只读检查安全地探索分布式表、分片、节点和托管组
🤖 智能顾问获取重新平衡、偏斜分析、配置和操作健康的建议
🛡️ 有守卫的行动仅使用明确的批准令牌执行危险操作
📊 实时监控查看集群活动、锁、后台作业和热碎片

运作原理

┌─────────────────┐                      ┌──────────────┐                ┌─────────────────┐
│  GitHub Copilot │     MCP Protocol     │  citus-mcp   │      SQL       │  Citus Cluster  │
│  (VS Code/CLI)  │  │    server    │  │  (Coordinator)  │
└─────────────────┘      stdio/SSE       └──────────────┘                └─────────────────┘

______________________________________________________________________

🚀 快速开始

先决条件

  • 转到1.23+ (从源头建设)
  • PostgreSQL 13–17 在协调器上使用Citus扩展名(11.x或更高版本)
  • GitHub Copilot 支持MCP(VS代码或CLI)

1.构建服务器

git clone https://github.com/citusdata/citus-mcp.git
cd citus-mcp
make build
# Binary created at ./bin/citus-mcp

或者直接使用Go:

go build -o bin/citus-mcp ./cmd/citus-mcp

2.配置您的连接

在以下位置创建配置文件 ~/.config/citus-mcp/config.yaml:

# Minimum required configuration
coordinator_dsn: postgres://username:password@localhost:5432/mydb?sslmode=disable

或者设置环境变量:

export CITUS_MCP_COORDINATOR_DSN="postgres://username:password@localhost:5432/mydb?sslmode=disable"

3.设置VS代码

创建 .vscode/mcp.json 在您的工作区(或 mcp.json 在项目根节点):

{
  "mcpServers": {
    "citus-mcp": {
      "command": "/path/to/citus-mcp/bin/citus-mcp",
      "args": [],
      "env": {
        "CITUS_MCP_COORDINATOR_DSN": "postgres://username:password@localhost:5432/mydb?sslmode=disable"
      }
    }
  }
}

4.测试连接

在VS Code Copilot Chat中,键入:

@citus-mcp ping

您应该看到一个“pong”响应,确认连接正常。

______________________________________________________________________

✨ 特性

71个MCP工具,涵盖诊断、取证、容量规划、顾问、, 警报、时间序列和门控执行操作。单一覆盖工具 citus_full_report 一次性运行约30个只读诊断程序 总体健康状况、主要发现和具体建议。

查看完整 工具参考 下面是参数和详细信息。

🧭 报告和覆盖工具

工具说明
citus_full_report一个呼叫覆盖工具——运行每个只读诊断+顾问,并生成统一的健康/发现/建议报告
citus_cluster_summary协调员+工人概述; all:true 启用每个部分+跨工具运行状况汇总(内存、元数据缓存3-regulary、连接、漂移、MX、池器)

🔍 集群检查(只读)

工具说明
list_nodes / list_distributed_tables / list_shards传统列表
citus_list_distributed_tables / citus_list_reference_tables分页、可过滤的表列表
citus_table_inspector表元数据、索引、统计数据深度挖掘
citus_colocation_inspector托管小组和成员

📊 监控和活动

工具说明
citus_activity群集范围内的活动查询和连接
citus_lock_inspector锁定等待并阻止查询
citus_job_inspector后台作业进度(重新平衡、复制)
citus_proactive_health交易时间长,交易中空闲,2PC卡滞,膨胀,仪表板饱和
citus_shard_heatmap热碎片和节点分布
citus_shard_skew_report每个节点的数据倾斜分析
citus_explain_query解释分布式查询
citus_synthetic_probe端到端综合正确性探针

🧠 内存和容量规划

工具说明
citus_metadata_cache_footprint每个后端有三种机制Citus元数据缓存估计(典型/热路径/最坏情况)、实时最坏情况后端检测、分区爆炸模拟器、pg_stat_statements相关性
citus_pg_cache_footprint根据后端PG CacheMemoryContext 估计数
citus_worker_memcontexts扇出 pg_get_backend_memory_contexts()
citus_partition_growth_simulator添加分区的项目缓存成本
citus_memory_risk_report每个节点的OOM风险汇总 13消费者术语 (共享缓冲区、wal_buffers、lock_table、pred_lock_table、prepared_act_state、wal_senders、逻辑解码、bgworker_baseline、backend_process_baseline、每个后端缓存、work_mem峰值 hash_mem_multiplier +并行工作器、临时缓冲区、自动真空、Citus libpq缓冲区);支持 worst_case:true
citus_connection_capacity每种部署模式的有效客户端最大值(仅限coord与MX)
citus_connection_fanout_simulatormax_adaptive × peers × clients 压力模拟器
citus_pooler_advisorPgBouncer会话与交易指导
citus_pgbouncer_inspector连接PgBouncer诊断
citus_hardware_sizer根据当前+预计负载(RAM、CPU、IOPS、磁盘)调整大小
citus_shardcount_tradeoff_chart每张表的碎片计数权衡图

🛠️ MX和节点添加

工具说明
citus_add_node_preflight添加工人的协调员侧检查表(max_locks_per_transaction, max_worker_processes, max_connections, wal_level,复制插槽,…)
citus_node_prepare_advisor准备步骤+可选shell脚本
citus_metadata_sync_risk估计数 citus_activate_node 工作+超时/OOM/锁定风险;喷射混凝土 recommended_max_locks_per_transaction 准确无误 ALTER SYSTEM SET …
citus_mx_readiness启用MX之前的网状连接预算
citus_snapshot_source_advisor为基于快照的添加选择最佳源工作器

🚑 取证与恢复

工具说明
citus_2pc_recovery_inspector粉丝出去 pg_prepared_xacts 协调+工作者,解析Citus GID,与 pg_dist_transaction (键入 (groupid, gid))以及 get_all_active_transactions(),并将每个分类为 commit_needed / rollback_needed / in_flight / foreign_initiator (镜像Citus自己的 LIKE 'citus__%' filter——由不同工作程序启动的准备好的xact由该工作程序恢复,而不是由协调器恢复)。为每个节点发出准备运行 COMMIT PREPARED / ROLLBACK PREPARED 脚本(独立语句——没有事务块,因为PostgreSQL禁止)+提交积压和孤立xacts的警报。只读——从不自行发出COMMIT/ROLLBACK。
citus_rebalance_forensics诊断 为什么 再平衡(或任何bg作业)被卡住:检查 pg_dist_background_job/_task,将正在运行的任务与 pg_stat_activity 等待事件和 pg_blocking_pids (检查每个 阻断者 持有锁模式和查询文本(不是服务员要求的锁),计数 pg_dist_cleanup 积压,并将摊位分类为 blocked_by_ddl / blocked_by_lock / bg_worker_starvation / retry_backoff (可运行 not_before > now(),服务器端计算)/ error_with_retries_exhausted / finished_with_errors / cleanup_backlog.发出具体的剧本(citus_rebalance_stop / citus_cleanup_orphaned_resources / pg_cancel_backend)加上警报。解决引文数据/引文问题#6681、#7103、#8236、#1210。
citus_placement_integrity_checkCitus元数据之间的三向交叉检查(pg_dist_placement),工作人员的磁盘现实(pg_class 通过 run_command_on_workers,禁用Citus分片可见性挂钩),以及 pg_dist_cleanup。检测重影位置(元数据引用磁盘上丢失的分片——读取错误)、孤立表(没有位置行的workers上的分片后缀表)、数据处于非活动状态(shardstate!=1,但数据仍然存在)、大小漂移,以及 stale_stats (元数据 shardlength=0 但数据是存在的——再平衡者会做出错误的决定)。孤儿检测匹配打开 (base, shardid) 与实时元数据配对,以避免名称恰好以结尾的用户表出现误报 _。扇出失败的工人会被跟踪 skipped_workers[]partial_results=true --这些节点的重影检测被抑制,而不是发出假阳性的严重警报。发布每个班级的和解剧本(citus_copy_shard_placement / citus_cleanup_orphaned_resources / citus_update_shard_statistics).

🔧 元数据、扩展和路由

工具说明
citus_metadata_health具有修复提示的跨节点元数据一致性
citus_extension_drift_scanner跨节点的版本/可用性漂移
citus_routing_drift_detector检测路由到意外分片的查询
citus_planner_overhead_probe计划时间测量
citus_session_guardrails会话中的主动护栏设置

🤖 智能顾问

工具说明
citus_advisor顶级SRE+绩效顾问
citus_config_advisorCitus+PostgreSQL配置分析
citus_config_deep_inspect全PG+Citus GUC深潜,带漂移规则
citus_shard_advisor每表碎片计数建议
citus_columnar_advisor列式存储候选
citus_tenant_risk高风险/热门租户
citus_query_pathology病理分布式查询
citus_rebalance_cost_estimator估算再平衡成本(时间、WAL、字节)
citus_validate_rebalance_prereqs重新平衡准备情况检查表

🚨 警报

工具说明
citus_alarms_list / citus_alarms_ack / citus_alarms_clear列出、确认和批量清除其他工具发出的警报

📈 时间序列和快照

工具说明
citus_snapshot_record / citus_snapshot_list记录+列出快照(选择SQLite)
citus_trend / citus_growth_projection趋势线和线性/指数预测
citus_regression_detect / citus_what_changed与基线进行比较/比较两个快照

⚡ 执行操作(需要批准)

工具说明
citus_request_approval_tokenHMAC签名的限时批准令牌
citus_rebalance_plan / citus_rebalance_execute / citus_rebalance_status预览、运行、监控再平衡
citus_move_shard_plan / citus_move_shard_execute预览并执行分片移动
citus_isolate_tenant将租户隔离到自己的分片
citus_cleanup_orphaned清理孤儿安置
rebalance_table_plan / rebalance_table_execute传统的每表变量

______________________________________________________________________

📦 安装

选项1:从源代码构建

# Clone the repository
git clone https://github.com/citusdata/citus-mcp.git
cd citus-mcp

# Build using Make
make build

# Or build directly with Go
go build -o bin/citus-mcp ./cmd/citus-mcp

# (Optional) Install to your PATH
sudo cp bin/citus-mcp /usr/local/bin/

选项2:去安装

go install github.com/citusdata/citus-mcp/cmd/citus-mcp@latest

验证安装

citus-mcp --help

______________________________________________________________________

⚙️ 配置

连接字符串(DSN)

最重要的配置是PostgreSQL与Citus协调器的连接字符串:

postgres://[user]:[password]@[host]:[port]/[database]?sslmode=[mode]

示例:

# Local development (no SSL)
postgres://postgres:secret@localhost:5432/mydb?sslmode=disable

# Production with SSL
postgres://admin:secret@citus-coord.example.com:5432/production?sslmode=require

# With specific schema
postgres://user:pass@host:5432/db?sslmode=require&search_path=myschema

配置方法

配置可以通过以下方式提供(按优先级顺序):

  1. 命令行标志
  2. 环境变量
  3. 配置文件

方法1:环境变量

# Required
export CITUS_MCP_COORDINATOR_DSN="postgres://user:pass@localhost:5432/mydb?sslmode=disable"

# Optional
export CITUS_MCP_MODE="read_only"           # read_only (default) or admin
export CITUS_MCP_ALLOW_EXECUTE="false"      # Enable execute operations
export CITUS_MCP_APPROVAL_SECRET="secret"   # Required if allow_execute=true
export CITUS_MCP_LOG_LEVEL="info"           # debug, info, warn, error

方法2:配置文件

创建 ~/.config/citus-mcp/config.yaml:

# ===========================================
# Citus MCP Server Configuration
# ===========================================

# Database Connection (REQUIRED)
# -----------------------------
coordinator_dsn: postgres://user:password@localhost:5432/mydb?sslmode=disable

# Optional: Override credentials from DSN
# coordinator_user: myuser
# coordinator_password: mypassword

# Connection Mode (RECOMMENDED: true for production)
# --------------------------------------------------
# When true (default), worker data is fetched via run_command_on_workers() UDF.
# Set to false only for dev/test with direct worker access.
coordinator_only: true

# Optional: Direct worker connections (dev/test override only)
# If specified when coordinator_only=true, these take precedence (dev escape hatch)
# worker_dsns: postgres://user:pass@worker1:5432/db,postgres://user:pass@worker2:5432/db

# Server Mode
# -----------
# read_only: Only inspection tools available (default, safest)
# admin: All tools available including execute operations
mode: read_only

# Execute Operations (only if mode=admin)
# ---------------------------------------
allow_execute: false
# approval_secret: your-secret-key  # Required if allow_execute=true

# Performance Settings
# --------------------
cache_ttl_seconds: 5          # Cache duration for metadata queries
enable_caching: true          # Set to false to disable caching
max_rows: 200                 # Maximum rows returned per query
max_text_bytes: 200000        # Maximum text size in responses

# Timeouts
# --------
connect_timeout_seconds: 10   # Connection timeout
statement_timeout_ms: 30000   # Query timeout (30 seconds)

# Logging
# -------
log_level: info               # debug, info, warn, error

# Transport (NEW)
# ---------------
# stdio: Standard input/output (default, for VS Code/CLI integration)
# sse: Server-Sent Events over HTTP (for remote/network access)
# streamable: Streamable HTTP transport (for remote/network access)
transport: stdio

# HTTP Settings (only used when transport is sse or streamable)
# http_addr: 127.0.0.1        # Listen address (use 0.0.0.0 for all interfaces)
# http_port: 8080             # Listen port
# http_path: /mcp             # Endpoint path
# sse_keepalive_seconds: 30   # SSE keepalive interval

方法3:命令行标志

# Using flags (note: use underscores in flag names)
bin/citus-mcp --coordinator_dsn "postgres://..." --mode read_only

# Using positional argument for DSN
bin/citus-mcp "postgres://user:pass@localhost:5432/mydb?sslmode=disable"

# Specify config file
bin/citus-mcp --config /path/to/config.yaml

# Start with SSE transport
bin/citus-mcp --transport sse --http_port 8080 --coordinator_dsn "postgres://..."

配置文件位置

服务器按以下顺序搜索配置文件:

  1. --config / -c 旗帜
  2. CITUS_MCP_CONFIG 环境变量
  3. $XDG_CONFIG_HOME/citus-mcp/config.yaml
  4. ~/.config/citus-mcp/config.yaml
  5. ./citus-mcp.yaml (当前目录)

支持的格式:YAML、JSON、TOML

______________________________________________________________________

🌐 运输选项

Citus MCP支持三种不同部署场景的传输模式:

1.标准运输(默认)

标准输入/输出传输——服务器通过stdin/stdout进行通信。这是默认设置,用于与VS Code和GitHub Copilot CLI直接集成。

# Default - stdio transport
bin/citus-mcp --coordinator_dsn "postgres://..."

# Explicit
bin/citus-mcp --transport stdio --coordinator_dsn "postgres://..."

使用案例:

  • VS代码复制聊天集成
  • GitHub Copilot 命令行工具
  • 本地开发

2.SSE传输(服务器发送事件)

使用服务器发送事件的基于HTTP的传输。服务器作为HTTP守护进程运行,客户端可以远程连接。

# Start server on HTTP with SSE
bin/citus-mcp --transport sse --http_addr 0.0.0.0 --http_port 8080 --coordinator_dsn "postgres://..."

# Or via environment variables
export CITUS_MCP_TRANSPORT=sse
export CITUS_MCP_HTTP_ADDR=0.0.0.0
export CITUS_MCP_HTTP_PORT=8080
export CITUS_MCP_COORDINATOR_DSN="postgres://..."
bin/citus-mcp

终点:

  • GET /mcp -建立SSE连接
  • POST /mcp/session/{id} -向会话发送消息
  • GET /health -健康检查

使用案例:

  • 远程MCP服务器部署
  • Docker/Kubernetes部署
  • 多个客户端的共享服务器
  • 网络可访问的MCP服务

3.流式HTTP传输

支持流媒体的现代HTTP传输。建议用于新部署。

# Start server with streamable HTTP transport
bin/citus-mcp --transport streamable --http_addr 0.0.0.0 --http_port 8080 --coordinator_dsn "postgres://..."

终点:

  • POST /mcp -使用流式响应处理MCP请求
  • GET /health -健康检查

使用案例:

  • 与SSE相同,具有更好的流媒体支持
  • SSE不理想的环境

Docker部署示例

FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o citus-mcp ./cmd/citus-mcp

FROM alpine:latest
COPY --from=builder /app/citus-mcp /usr/local/bin/
EXPOSE 8080
CMD ["citus-mcp", "--transport", "sse", "--http-addr", "0.0.0.0", "--http-port", "8080"]
# docker-compose.yml
version: '3.8'
services:
  citus-mcp:
    build: .
    ports:
      - "8080:8080"
    environment:
      CITUS_MCP_TRANSPORT: sse
      CITUS_MCP_HTTP_ADDR: 0.0.0.0
      CITUS_MCP_HTTP_PORT: 8080
      CITUS_MCP_COORDINATOR_DSN: postgres://user:pass@citus-coordinator:5432/mydb?sslmode=disable

连接到远程服务器

对于SSE/Streamable传输,请将MCP客户端配置为通过HTTP连接:

{
  "mcpServers": {
    "citus-mcp": {
      "type": "sse",
      "url": "http://citus-mcp-server:8080/mcp"
    }
  }
}

______________________________________________________________________

🔌 使用GitHub Copilot进行设置

VS代码设置

  1. 安装先决条件

- 带有GitHub Copilot扩展的VS代码 - 在副驾驶设置中启用MCP支持

  1. 创建MCP配置

创建 .vscode/mcp.json 在您的工作空间中:

   {
     "mcpServers": {
       "citus-mcp": {
         "command": "/absolute/path/to/bin/citus-mcp",
         "args": [],
         "env": {
           "CITUS_MCP_COORDINATOR_DSN": "postgres://user:pass@localhost:5432/mydb?sslmode=disable"
         }
       }
     }
   }

或用于开发(使用 go run):

   {
     "mcpServers": {
       "citus-mcp": {
         "command": "go",
         "args": ["run", "./cmd/citus-mcp"],
         "cwd": "/path/to/citus-mcp",
         "env": {
           "CITUS_MCP_COORDINATOR_DSN": "postgres://user:pass@localhost:5432/mydb?sslmode=disable"
         }
       }
     }
   }
  1. 重新加载VS代码 并打开Copilot聊天
  1. 验证连接
   @citus-mcp ping

GitHub Copilot命令行界面设置

  1. 创建全局MCP配置

创建 ~/.config/github-copilot/mcp.json:

   {
     "mcpServers": {
       "citus-mcp": {
         "command": "/usr/local/bin/citus-mcp",
         "args": [],
         "env": {
           "CITUS_MCP_COORDINATOR_DSN": "postgres://user:pass@localhost:5432/mydb?sslmode=disable"
         }
       }
     }
   }
  1. 验证设置
   copilot mcp list
   copilot mcp test citus-mcp
  1. 在CLI中使用
   copilot -p "Show me the cluster summary"

______________________________________________________________________

💡 使用示例

以下示例是您可以在Copilot中输入的自然语言提示 聊天(VS代码/CLI)。Copilot将它们映射到底层MCP工具调用; JSON有效载荷显示在对自动化有用的地方。

基本集群检查

@citus-mcp Give me everything about this cluster

citus_cluster_summary 随着 {"all": true} --返回协调器/工作器拓扑、计数、GUC、配置报告和跨工具健康汇总(内存/连接/漂移/元数据同步/操作)。

@citus-mcp List all distributed and reference tables

citus_list_distributed_tables, citus_list_reference_tables

@citus-mcp Inspect the public.orders table including shards and indexes

citus_table_inspector 随着 {"table":"public.orders","include_shards":true,"include_indexes":true}

监控

@citus-mcp Show current cluster activity
@citus-mcp Are there any lock waits right now?
@citus-mcp Show background job progress
@citus-mcp Proactive health dashboard for the cluster

citus_activity, citus_lock_inspector, citus_job_inspector, citus_proactive_health

内存和容量规划

@citus-mcp Project per-backend Citus metadata cache memory

citus_metadata_cache_footprint --尺寸 MetadataCacheMemoryContext 基于当前形状的每个后端。

@citus-mcp Estimate PG CacheMemoryContext footprint on the coordinator and each worker

citus_pg_cache_footprint --relcache/catcache/plancache估计值。

@citus-mcp Is the cluster close to OOM? Use worst_case=true and 64 GiB per node

citus_memory_risk_report 随着 {"worst_case":true, "node_ram_bytes":68719476736} --13项预算(共享缓冲区、wal_buffers、锁/预锁表、wal发送方、逻辑解码、bgworker基线、每个后端进程基线+计划缓存、Citus元数据+PG CacheMemoryContext、, work_mem × hash_mem_multiplier × (1 + parallel_workers_per_gather) × plan_ops_per_query、温度缓冲、自动真空、低温↔worker libpq缓冲区)与节点RAM进行比较。

@citus-mcp Sample PostgreSQL MemoryContextStats on every node

citus_worker_memcontexts --现场直播 pg_get_backend_memory_contexts() 在集群中散开。

@citus-mcp What will happen to memory if I double the number of monthly partitions?

citus_partition_growth_simulator 随着 {"partitions_per_parent":24}

@citus-mcp How many clients can each node handle? Compare coord-only, MX, and PgBouncer

citus_connection_capacity --在每种部署模式下返回有效的最大客户端后端以及瓶颈解释。

@citus-mcp Simulate 400 concurrent multi-shard queries and tell me when max_shared_pool_size saturates

citus_connection_fanout_simulator 随着 {"concurrent_clients":400}

@citus-mcp Should I use PgBouncer session or transaction mode with this workload?

citus_pooler_advisor

@citus-mcp Size hardware for 5× projected load: 50k IOPS, 2 TB data, 200 active clients

citus_hardware_sizer 随着 {"projected_data_gb":2000,"projected_active_clients":200,"projected_iops":50000}

@citus-mcp Is 32 shards the right number? Chart the trade-offs

citus_shardcount_tradeoff_chart

MX和节点添加

@citus-mcp Run pre-flight checks for adding a worker at newworker.prod:5432

citus_add_node_preflight 随着 {"host":"newworker.prod","port":5432} --协调方检查表(扩展、类型、模式、角色、版本匹配、, max_locks_per_transaction/max_worker_processes/max_connections 地板, wal_level=logical,复制插槽)。

@citus-mcp Advise how to prepare newworker.prod:5432 before I call citus_add_node and generate a shell script

citus_node_prepare_advisor 随着 {"host":"newworker.prod","port":5432,"generate_script":true}

@citus-mcp Will metadata sync succeed on the new node, or should I use nontransactional mode? Target has 16 GiB RAM

citus_metadata_sync_risk 随着 {"target_node_ram_gib":16} --DDL计数、tx锁定、持续时间、超时相关性。

@citus-mcp Is the cluster ready for MX with 2 concurrent queries per peer and new nodes sized at max_connections=300?

citus_mx_readiness 随着 {"concurrent_queries_per_peer":2,"new_node_max_connections":300,"expected_clients_per_node":100}

@citus-mcp Which existing worker should I snapshot from when adding a new one?

citus_snapshot_source_advisor

元数据、扩展和路由

@citus-mcp Deep metadata consistency check across every node

citus_metadata_health 随着 {"check_level":"deep","include_fixes":true}

@citus-mcp Are all extensions at the same version on every node?

citus_extension_drift_scanner

@citus-mcp Measure planner overhead across the cluster

citus_planner_overhead_probe

@citus-mcp Detect routing drift — are any queries landing on the wrong shard?

citus_routing_drift_detector

@citus-mcp Run a synthetic probe to validate end-to-end correctness

citus_synthetic_probe

@citus-mcp Dump the session's active guardrails (statement timeout, read-only, row caps)

citus_session_guardrails

顾问(只读建议)

@citus-mcp Run the Citus advisor focused on skew and include SQL fixes

citus_advisor 随着 {"focus":"skew","include_sql_fixes":true}

@citus-mcp Analyze configuration, all categories, warn level and above

citus_config_advisor 随着 {"severity_filter":"warning"}

@citus-mcp Deep inspection of PostgreSQL + Citus GUCs

citus_config_deep_inspect

@citus-mcp Advise on shard count per distributed table given current/projected load

citus_shard_advisor

@citus-mcp Which tables would benefit from columnar storage?

citus_columnar_advisor

@citus-mcp Show risky tenants (heavy shards, hot locks, outsized query share)

citus_tenant_risk

@citus-mcp Investigate which queries are pathological (cross-shard joins, broadcasts, repartitions)

citus_query_pathology

@citus-mcp Inspect the connected PgBouncer for pool health

citus_pgbouncer_inspector

碎片和偏斜分析

@citus-mcp Skew report for the orders table by row count
@citus-mcp Heatmap of the hottest shards in the last interval

citus_shard_skew_report, citus_shard_heatmap

@citus-mcp Estimate the cost (time, WAL, bytes) of rebalancing the current cluster

citus_rebalance_cost_estimator

时间序列/快照

@citus-mcp Record a snapshot named pre-deploy-2026-04
@citus-mcp List snapshots taken in the last 30 days
@citus-mcp Trend query latency over the last 7 days
@citus-mcp Detect regressions against the pre-deploy-2026-04 snapshot
@citus-mcp Project 12-month growth from snapshots
@citus-mcp What changed between snapshots A and B?

citus_snapshot_record, citus_snapshot_list, citus_trend, citus_regression_detect, citus_growth_projection, citus_what_changed

警报

@citus-mcp List open alarms
@citus-mcp Acknowledge alarm abc-123
@citus-mcp Clear all resolved alarms older than 7 days

citus_alarms_list, citus_alarms_ack, citus_alarms_clear

执行操作(需要批准)

@citus-mcp Plan a rebalance limited to 10 shard moves
@citus-mcp Request an approval token for rebalance
@citus-mcp Execute rebalance with token 
@citus-mcp Check rebalance status

citus_rebalance_plancitus_request_approval_tokencitus_rebalance_executecitus_rebalance_status

@citus-mcp Move shard 102008 from 10.0.0.5:5432 to 10.0.0.6:5432

citus_move_shard_plan + citus_move_shard_execute (带批准标志)

@citus-mcp Isolate tenant 42 to its own shard
@citus-mcp Clean up orphaned shard placements left by a failed move

citus_isolate_tenant, citus_cleanup_orphaned

______________________________________________________________________

📚 工具参考

以下所有工具名称都可以作为MCP工具调用直接调用。大多数 接受具有所列参数的可选对象; 指工具 不接受任何输入。

🧭 报告和覆盖工具

工具参数说明
citus_full_reportpartition_growth_factor?, memory_budget_bytes?, include_verbose_outputs?, synthetic_probe?, pgbouncer_admin_dsn?, hardware_sizer_targets?单覆盖工具。运行每个只读诊断+顾问(约30个工具),并生成一份综合报告,其中包含整体健康状况、主要发现、主要建议和每个工具的部分。执行类和输入特定工具被有意排除在外。

示例-- citus_full_report:

// Default invocation: runs all read-only diagnostics with sensible defaults
{}

// With partition what-if and a tighter memory budget
{
  "partition_growth_factor": 2.0,
  "memory_budget_bytes": 4294967296
}

// Include optional synthetic probe + raw per-tool outputs (verbose)
{
  "synthetic_probe": true,
  "include_verbose_outputs": true
}

岩芯检查(只读)

工具参数说明
pingmessage?活体检查
server_info--服务器元数据、构建信息、模式
list_nodeslimit?, offset?协调员+工人
list_distributed_tableslimit?, offset?传统表格列表
list_shardslimit?, offset?带有放置位置的碎片
citus_cluster_summaryall?, include_workers?, include_gucs?, include_config?, include_health?, include_operational?完整的集群概述; all: true 启用每个部分,包括跨工具运行状况汇总
citus_list_distributed_tablesschema?, table_type?, limit?, cursor?分页分布式表列表
citus_list_reference_tablesschema?, limit?, cursor?分页参考表列表
citus_table_inspectortable *(要求)*, include_shards?, include_indexes?桌上深潜
citus_colocation_inspectorcolocation_id?, limit?托管组+成员

监控和活动

工具参数说明
citus_activitylimit?, include_idle?, min_duration_secs?群集范围内的活动查询
citus_lock_inspectorinclude_locks?, limit?锁定等待和阻断器
citus_job_inspectorstate?, include_tasks?, limit?后台作业进度
citus_shard_heatmaptable?, metric?, group_by?, limit?热碎片地图
citus_shard_skew_reporttable?, metric?, include_top_shards?偏斜分析。每个节点的返回摘要(含 only_reference_tables 标记,以便将协调器等仅参考节点排除在集群偏斜度量之外),每个托管 max/avg 比率(判定关键≥5×/警告≥2×),以及a hot_shards[] 已准备好运行的列表 isolate_tenant_to_new_shard 修正SQL。
citus_explain_querysql *(要求)*, analyze?, verbose?, costs?分布式解释
citus_proactive_healthlong_tx_seconds?, idle_in_tx_seconds?, stuck_prepared_xact_seconds?, bloat_*?, include_workers?长tx/2PC/膨胀/饱和仪表板

内存和容量规划

工具参数说明
citus_metadata_cache_footprinttypical_tables_touched?, hot_path_tables_touched?, memory_budget_bytes?, partition_growth_factor?, skip_worst_case_scan?, skip_query_correlation?每个后端Citus元数据缓存估计有三种机制(典型/热路径/最坏情况)、并发上限净空、实时最坏情况后端检测、分区爆炸模拟器、pg_stat_statements查询相关性
citus_pg_cache_footprintinclude_shard_rels?根据后端PG CacheMemoryContext估计
citus_worker_memcontextstop_n?pg_get_backend_memory_contexts() 扇出
citus_partition_growth_simulatorpartitions_per_parent, period_days?添加分区的项目缓存成本
citus_memory_risk_reportnode_ram_bytes?, node_ram_bytes_by_node?, worst_case?, warn_pct?, crit_pct?, include_coordinator?, per_backend_app_overhead_bytes?, plan_ops_per_query?每个节点的OOM风险汇总——13个消费者术语:shared_buffers、wal_buffers、lock_table(max_locks_per_transaction × MaxBackends × 270 B)、pred_lock_table、prepared_xact_state、wal_senders、逻辑解码、bgworker_baseline、backend_process_baseline、per_backend_caches(Citus MetadataCache+PG CacheMemoryContext)、work_mem_peak(适用 hash_mem_multiplier + max_parallel_workers_per_gather + plan_ops_per_query)、temp_buffers、autovacuum_budget和coord↔协调器上的worker libpq连接缓冲区。
citus_connection_capacitysafety_fraction?, per_backend_override?, include_coordinator?, fanout_concurrency?每种部署模式的有效客户端最大值。Coord只返回两者 recommended_client_max (硬天花板假设每个coord后端都完全扇出 max_adaptive_executor_pool_size)以及 sustainable_client_max (现实的稳态信贷 fanout_concurrency,默认值为0.5)。
citus_connection_fanout_simulatorconcurrent_clients, peer_count?模拟 max_adaptive × peers × clients 压力
citus_pooler_advisorexpected_clients?, mode?PgBouncer会话与交易指导
citus_hardware_sizerprojected_data_gb?, projected_active_clients?, projected_iops?, retention_days?当前/预计负载的硬件尺寸
citus_shardcount_tradeoff_charttable?, candidate_counts?碎片计数权衡图

MX/节点添加

工具参数说明
citus_add_node_preflighthost *(要求)*, port?, database?添加工人的协调员侧检查表
citus_node_prepare_advisorhost *(要求)*, port?, database?, generate_script?准备步骤+可选shell脚本
citus_metadata_sync_risktarget_max_locks_per_transaction?, target_node_ram_gib?, assume_sync_mode?估计数 citus_activate_node 工作和超时/OOM/锁定风险。锁哈希容量是使用PostgreSQL的实际值计算的 NLOCKENTS 公式: max_locks_per_transaction × (MaxBackends + max_prepared_transactions) 哪里 MaxBackends = max_connections + autovacuum_max_workers + max_worker_processes + max_wal_senders两者都有 max_backendslock_table_capacity 被退回 coordinator_gucs.锁定tx需求使用 distributed_tables × (1 + avg_indexes_per_table) + distributed_objects + headroom.退货 recommended_max_locks_per_transaction (64值的具体倍数)当前设置将耗尽共享锁表时,加上确切的 ALTER SYSTEM SET … 声明在 recommendations[].
citus_mx_readinessexpected_clients_per_node?, target_node_ram_gib?, new_node_max_connections?, concurrent_queries_per_peer?MX之前的网状连接预算
citus_snapshot_source_advisorstrategy?, max_candidates?, include_simulation?为基于快照的添加选择最佳源工作器

取证与恢复

工具参数说明
citus_2pc_recovery_inspectorin_flight_threshold_seconds? (默认值60), stuck_orphan_seconds? (默认值600), include_non_citus?, suppress_recovery_script?对卡住的2PC/已准备交易状态进行取证。粉丝出去 pg_prepared_xacts 跨coord+工作人员,解析Citus GID(`citus__
__ --严格:3或4个部分,非负组/pid,存在时可解析的conn),与 pg_dist_transaction 键入 (groupid, gid) (不仅仅是gid,在不同群体中也不是独一无二的)以及 get_all_active_transactions(),将每个分类为 commit_needed / rollback_needed / in_flight / foreign_initiator / non_citus,并发出一个准备运行的每个节点恢复脚本。 foreign_initiator 镜像Citus自己的 RecoverWorkerTransactions 过滤器(LIKE 'citus__%'):工作程序启动的2PC由该工作程序的维护守护进程恢复,而不是由协调器恢复,因此不会为它们发出COMMIT/ROLLBACK SQL。生成的恢复脚本使用独立的顶级语句(PostgreSQL禁止 COMMIT PREPARED 在交易块内)。发射 two_pc.commit_backlog, two_pc.orphans (如果年龄超过 stuck_orphan_seconds), two_pc.slow_in_flight` 警报。只读——从不自行发出COMMIT/ROLLBACK。
citus_rebalance_forensicsjob_id?, stall_threshold_seconds? (默认值300), lookback_hours? (默认值24), include_finished_tasks?, retries_exhausted_threshold? (默认值3), cleanup_backlog_threshold? (默认值100)诊断 为什么 重新平衡或后台作业被搁置。读取 pg_dist_background_job/_task/_depend,将正在运行的任务与 pg_stat_activity 等待事件和 pg_blocking_pids (提取每个拦截器的PID+当前查询+ 最强授权锁定模式 --服务员请求的模式不是可靠的DDL信号),计数 pg_dist_cleanup 积压,读取 citus.max_background_task_executors.计算机 in_backoff 服务器端as not_before > now() (匹配Citus metadata_utility.c 可运行语义),因此时钟偏斜不会混淆分类。摊位类: blocked_by_ddl (阻塞查询是DDL或持有AccessExclusive/Exclusive)/ blocked_by_lock / bg_worker_starvation / retry_backoff / error_with_retries_exhausted / finished_with_errors (之前评估 cleanup_backlog 因此,留下清理残留物的失败作业按其真正原因分类)/ cleanup_backlog / no_stall.发出具体的恢复脚本(停止+清理+恢复SQL)和警报。

示例-- citus_rebalance_forensics:

// Default: find most recent stuck/running job within last 24h
{}

// Diagnose a specific job, include finished tasks for postmortem
{"job_id": 42, "include_finished_tasks": true}

// Tighter thresholds: flag retries earlier, warn on smaller cleanup backlogs
{"retries_exhausted_threshold": 1, "cleanup_backlog_threshold": 10}

| citus_placement_integrity_check | schemas? (默认值 ["public"]), skip_size_drift?, size_drift_factor? (默认值2.0), max_rows_per_class? (默认值200), check_inactive_placements? (默认为true)|Citus元数据之间的三向交叉检查(pg_dist_placement × pg_dist_shard × pg_dist_node),每个工作者的磁盘现实(pg_class 扫描通过 run_command_on_workers 禁用Citus分片可见性挂钩),以及 pg_dist_cleanup.检测:(a) ghost_placements --元数据引用磁盘上缺少的分片(读取WILL错误);b 孤儿表 --没有放置行的workers上的分片后缀表(标记是否排队 pg_dist_cleanupc 无数据无效shardstate != 1 但数据仍然存在;d 尺寸_漂移pg_relation_size 对比 placement.shardlength 偏离> size_drift_factore 跟踪统计placement.shardlength = 0 但是磁盘有数据(默默地导致重新平衡器做出错误的决定;用修复 SELECT citus_update_shard_statistics(shardid)citus_update_table_statistics(relname)).孤儿分类匹配 (base_name, shardid) 对元数据(不仅仅是基名称)进行配对,因此用户表像 events_123456 没有匹配的shardid不会被标记。 权衡: 如果一个分片被完全删除(放置行消失了,从未排队等待清理),但其磁盘上的表仍然存在,则配对匹配器不会将其检测为孤立分片——use SELECT run_command_on_workers($$SELECT oid::regclass FROM pg_class WHERE relname ~ '_[0-9]+$'$$); 就像用皮带和牙套清扫那个箱子一样。扇出失败的工人名单如下 skipped_workers[] 随着 partial_results=true;对这些节点抑制重影检测,以避免误报关键警报。发布每个班级的和解剧本(citus_copy_shard_placement / citus_cleanup_orphaned_resources / citus_update_shard_statistics)和警报(placement.ghost, placement.orphan_tables, placement.inactive_with_data, placement.stale_stats, placement.partial_results).只读。 |

示例-- citus_placement_integrity_check:

// Default — scan public schema, detect all 4 classes
{}

// Multi-schema, skip size drift for speed
{"schemas": ["public", "tenants"], "skip_size_drift": true}

// Strict size drift (flag any > 1.5× deviation)
{"size_drift_factor": 1.5}

示例-- citus_2pc_recovery_inspector:

// Default — detect commit_needed / rollback_needed / in_flight / foreign_initiator
{}

// Aggressive: treat anything >10s as orphan, escalate orphans older than 2 min
{"in_flight_threshold_seconds": 10, "stuck_orphan_seconds": 120}

// Compact output (no recovery script)
{"suppress_recovery_script": true}

// Include non-citus GIDs in the output (e.g. for third-party 2PC coordinators)
{"include_non_citus": true}

元数据/扩展/路由

工具参数说明
citus_metadata_healthcheck_level? (basic/thorough/deep), include_fixes?跨节点元数据一致性
citus_extension_drift_scannerextensions?跨节点的版本/可用性漂移
citus_planner_overhead_probeiterations?计划时间测量
citus_routing_drift_detectorsample_size?检测路由到意外分片的查询
citus_synthetic_probeverbose?端到端综合正确性探针
citus_session_guardrails--当前会话中的主动护栏设置

顾问(只读)

工具参数说明
citus_advisorfocus? (skew/ops), max_tables?, include_next_steps?, include_sql_fixes?顶级SRE顾问
citus_config_advisorinclude_all_gucs?, category?, severity_filter?, total_ram_gb?配置分析
citus_config_deep_inspect--全PG+Citus GUC深潜
citus_shard_advisortable?, projected_load_multiplier?碎片计数建议
citus_columnar_advisor--列式存储候选
citus_tenant_risktop_n?有风险的租户
citus_query_pathologylimit?, window_secs?病理分布式查询
citus_pgbouncer_inspectordsn?连接PgBouncer诊断
citus_rebalance_cost_estimatortable?, strategy?估算再平衡成本(时间、WAL、字节)
citus_validate_rebalance_prereqstable *(要求)*重新平衡准备情况检查表

警报

工具参数说明
citus_alarms_listkind?, severity?, acked?, limit?列出其他工具发出的警报
citus_alarms_ackid *(要求)*确认
citus_alarms_clearolder_than_seconds?, kind?散装货物清关

时间序列/快照

工具参数说明
citus_snapshot_recordname?, tags?录制快照(选择SQLite)
citus_snapshot_listlimit?, since?列出快照
citus_trendmetric *(要求)*, window_days?指标的趋势线
citus_regression_detectbaseline *(要求)*与基线快照进行比较
citus_growth_projectionmetric *(要求)*, horizon_months?线性/指数投影
citus_what_changeda *(要求)*, b *(要求)*两个快照之间的差异

执行操作(需要批准令牌)

工具参数说明
citus_request_approval_tokenaction *(要求)*, ttl_seconds?HMAC签名的批准令牌
citus_rebalance_plantable?, threshold?, max_shard_moves?, drain_only?预览重新平衡
citus_rebalance_executeapproval_token *(要求)*, table?, threshold?开始重新平衡
citus_rebalance_statusverbose?, limit?, cursor?重新平衡进度
citus_move_shard_planshard_id, source_host, source_port, target_host, target_port, colocated?预览碎片移动
citus_move_shard_executeapproval_token *(要求)*, shard_id, source_*, target_*, colocated?, drop_method?执行分片移动
citus_isolate_tenantapproval_token *(要求)*, table, tenant_id将租户隔离到自己的分片
citus_cleanup_orphanedapproval_token *(要求)*, dry_run?清理孤儿安置
rebalance_table_plantable *(要求)*传统按表再平衡计划
rebalance_table_executetable *(要求)*, approval_token *(要求)*执行传统的按表重新平衡

______________________________________________________________________

📋 内置提示

在Copilot Chat中使用以下提示进行指导工作流程:

提示描述
/citus.health_check群集运行状况检查表
/citus.rebalance_workflow分步再平衡指南
/citus.skew_investigation偏斜调查剧本
/citus.ops_triage操作分流工作流程

______________________________________________________________________

🔐 安全

只读模式(默认)

默认情况下,citus mcp在 只读模式这意味着:

  • ✅ 所有检查和监控工具均正常工作
  • ✅ 顾问提供建议
  • ❌ 执行操作已禁用
  • ❌ 无法修改任何数据

带有批准令牌的管理模式

要启用执行操作,请执行以下操作:

  1. 设置管理模式 在配置中:
   mode: admin
   allow_execute: true
   approval_secret: your-secret-key-here
  1. 请求批准令牌 执行前:
   @citus-mcp Request approval token for rebalance
  1. 使用令牌 在执行命令中:
   @citus-mcp Execute rebalance with token: 

令牌是有时间限制的,并且特定于操作(HMAC签名)。

______________________________________________________________________

🔧 故障排除

连接问题

错误: connection refused

  • 验证协调器主机和端口是否正确
  • 检查PostgreSQL是否正在运行并接受连接
  • 确保防火墙规则允许连接

错误: authentication failed

  • 验证DSN中的用户名和密码
  • 检查用户是否具有数据库权限
  • 对于SSL问题,请尝试 sslmode=disable 用于本地测试

MCP问题

副驾驶看不到citus mcp

  • 确保 mcp.json 位置正确
  • 检查命令路径是否为绝对路径
  • 更改配置后重新加载VS代码

工具返回错误

  • 检查日志: CITUS_MCP_LOG_LEVEL=debug bin/citus-mcp
  • 验证是否安装了Citus扩展: SELECT * FROM pg_extension WHERE extname = 'citus'

测试连接

# Test directly
CITUS_MCP_COORDINATOR_DSN="postgres://..." bin/citus-mcp

# Then send a ping via stdin
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | bin/citus-mcp

______________________________________________________________________

🛠️ 发展

运行测试

# Unit tests
make test

# With verbose output
go test -v ./...

# Integration tests (requires Docker)
make docker-up
make integration
make docker-down

代码检查

make lint

项目结构

citus-mcp/
├── cmd/citus-mcp/       # Main entry point
├── internal/
│   ├── mcpserver/       # MCP server implementation
│   │   ├── tools/       # Tool implementations (71 tools)
│   │   ├── prompts/     # Prompt templates
│   │   └── resources/   # Static resources
│   ├── db/              # Database layer and worker management
│   ├── citus/           # Citus-specific logic and queries
│   │   ├── advisor/     # Advisor implementations
│   │   └── guc/         # GUC (configuration) analysis
│   ├── cache/           # Query result caching
│   ├── config/          # Configuration management
│   ├── errors/          # Error types and codes
│   ├── fanout/          # Parallel query execution
│   ├── logging/         # Structured logging
│   └── safety/          # Guardrails and approval tokens
├── docker/              # Docker Compose setup for testing
├── docs/                # Additional documentation
└── tests/               # Integration tests

______________________________________________________________________

🤝 贡献

欢迎投稿!请参阅 贡献.md 作为指导方针。

______________________________________________________________________

📄 许可证

MIT许可证——见 许可证 了解详情。

______________________________________________________________________

⬆ 返回顶部

制作❤️ 为Citus社区

目录标签

目录标签

集群管理PostgreSQLCursor分布式数据库Go本地部署AI辅助数据库监控

支持客户端

CursorVS Code

接入字段

传输方式(transport,传输协议)

SSE

鉴权方式(authType,认证方式)

token

工具数量(toolCount,工具数)

69

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

SSEtoken部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

仍需确认:installCommand

来源信息

继续浏览同类 MCP