返回 MCP 目录
public公开dns本地运行

citus-mcp

Citus MCP是一个基于Model Context Protocol的AI助手服务器,专为管理Citus分布式PostgreSQL集群设计,提供集群检查、监控、智能建议和安全操作功能。

article

README

🚀 Citus MCP 服务器

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

本项目借助先进的人工智能技术,为 Citus 分布式 PostgreSQL 集群提供高效、智能的管理方案,能显著提升集群的管理效率和稳定性。

Go 版本 许可证 Citus

快速开始主要特性安装指南配置说明工具参考使用示例


🚀 快速开始

前提条件

  • Go 1.23 及以上版本(用于从源代码构建)
  • 可访问协调器的 Citus 12.x - 14.x 集群
  • 支持 MCP 的 GitHub Copilot(VS Code 或 CLI)

1. 构建服务器

git clone https://github.com/citusdata/citus-mcp.git
cd citus-mcp
make build
# 二进制文件将生成在 ./bin/citus-mcp

或者直接使用 Go 进行构建:

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

2. 配置连接

~/.config/citus-mcp/config.yaml 中创建配置文件:

# 最低要求的配置
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 Code

在工作区创建 .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 聊天中输入:

@citus-mcp ping

若看到 "pong" 响应,则表明连接正常。


✨ 主要特性

🔍 集群检查(只读)

| 工具 | 描述 | |------|-------------| | citus_cluster_summary | 协调器、工作节点、表数量和配置健康状况的概述 | | list_nodes | 列出所有协调器和工作节点 | | list_distributed_tables | 列出分布式表和引用表 | | citus_list_distributed_tables | 带过滤器的分布式表分页列表 | | citus_list_reference_tables | 引用表的分页列表 | | list_shards | 列出分片及其位置和大小 | | citus_table_inspector | 深入查看表元数据、索引和统计信息 | | citus_colocation_inspector | 分析 coloc 组和共置表 |

📊 监控与分析

| 工具 | 描述 | |------|-------------| | citus_activity | 集群范围内的活动查询和连接 | | citus_lock_inspector | 查看锁等待和阻塞查询 | | citus_job_inspector | 后台作业进度(重新平衡、复制) | | citus_shard_heatmap | 热点分片和节点分布 | | citus_shard_skew_report | 每个节点的数据倾斜分析 | | citus_explain_query | 解释分布式查询 |

🤖 智能顾问

| 工具 | 描述 | |------|-------------| | citus_advisor | 提供可操作建议的 SRE 和性能顾问 | | citus_config_advisor | 全面的 Citus 和 PostgreSQL 配置分析 | | citus_snapshot_source_advisor | 为基于快照的扩展推荐源节点 | | citus_validate_rebalance_prereqs | 检查表是否准备好进行重新平衡 | | citus_metadata_health | 检测元数据损坏和不一致,并提供修复建议 | | citus_node_prepare_advisor | 为添加新节点进行预检查和准备脚本 |

⚡ 执行操作(需要批准)

| 工具 | 描述 | |------|-------------| | citus_rebalance_plan | 预览重新平衡操作 | | citus_rebalance_execute | 启动集群重新平衡 | | citus_rebalance_status | 监控重新平衡进度 | | citus_move_shard_plan | 预览分片移动 | | citus_move_shard_execute | 将分片移动到不同节点 | | citus_request_approval_token | 请求限时批准令牌 |


📦 安装指南

选项 1:从源代码构建

# 克隆仓库
git clone https://github.com/citusdata/citus-mcp.git
cd citus-mcp

# 使用 Make 进行构建
make build

# 或者直接使用 Go 构建
go build -o bin/citus-mcp ./cmd/citus-mcp

# (可选)安装到系统路径
sudo cp bin/citus-mcp /usr/local/bin/

选项 2:使用 Go 安装

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

验证安装

citus-mcp --help

⚙️ 配置说明

连接字符串(DSN)

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

postgres://[用户]:[密码]@[主机]:[端口]/[数据库]?sslmode=[模式]

示例:

# 本地开发(无 SSL)
postgres://postgres:secret@localhost:5432/mydb?sslmode=disable

# 生产环境使用 SSL
postgres://admin:secret@citus-coord.example.com:5432/production?sslmode=require

# 指定特定模式
postgres://user:pass@host:5432/db?sslmode=require&search_path=myschema

配置方法

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

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

方法 1:环境变量

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

# 可选
export CITUS_MCP_MODE="read_only"           # 只读(默认)或管理员模式
export CITUS_MCP_ALLOW_EXECUTE="false"      # 启用执行操作
export CITUS_MCP_APPROVAL_SECRET="secret"   # 如果 allow_execute=true 则必需
export CITUS_MCP_LOG_LEVEL="info"           # 调试、信息、警告、错误

方法 2:配置文件

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

# ===========================================
# Citus MCP 服务器配置
# ===========================================

# 数据库连接(必需)
# -----------------------------
coordinator_dsn: postgres://user:password@localhost:5432/mydb?sslmode=disable

# 可选:覆盖 DSN 中的凭据
# coordinator_user: myuser
# coordinator_password: mypassword

# 可选:直接连接工作节点(逗号分隔)
# worker_dsns: postgres://user:pass@worker1:5432/db,postgres://user:pass@worker2:5432/db

# 服务器模式
# -----------
# read_only: 仅提供检查工具(默认,最安全)
# admin: 提供所有工具,包括执行操作
mode: read_only

# 执行操作(仅当 mode=admin 时)
# ---------------------------------------
allow_execute: false
# approval_secret: your-secret-key  # 如果 allow_execute=true 则必需

# 性能设置
# --------------------
cache_ttl_seconds: 5          # 元数据查询的缓存持续时间
enable_caching: true          # 设置为 false 可禁用缓存
max_rows: 200                 # 每个查询返回的最大行数
max_text_bytes: 200000        # 响应中的最大文本大小

# 超时设置
# --------
connect_timeout_seconds: 10   # 连接超时时间
statement_timeout_ms: 30000   # 查询超时时间(30 秒)

# 日志记录
# -------
log_level: info               # 调试、信息、警告、错误

# 传输方式(新增)
# ---------------
# stdio: 标准输入/输出(默认,用于 VS Code/CLI 集成)
# sse: 通过 HTTP 的服务器发送事件(用于远程/网络访问)
# streamable: 可流式传输的 HTTP 传输(用于远程/网络访问)
transport: stdio

# HTTP 设置(仅当传输方式为 sse 或 streamable 时使用)
# http_addr: 127.0.0.1        # 监听地址(使用 0.0.0.0 表示所有接口)
# http_port: 8080             # 监听端口
# http_path: /mcp             # 端点路径
# sse_keepalive_seconds: 30   # SSE 保持活动间隔

方法 3:命令行标志

# 使用标志(注意:标志名使用下划线)
bin/citus-mcp --coordinator_dsn "postgres://..." --mode read_only

# 使用位置参数指定 DSN
bin/citus-mcp "postgres://user:pass@localhost:5432/mydb?sslmode=disable"

# 指定配置文件
bin/citus-mcp --config /path/to/config.yaml

# 使用 SSE 传输方式启动
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. 标准输入/输出传输(默认)

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

# 默认 - 标准输入/输出传输
bin/citus-mcp --coordinator_dsn "postgres://..."

# 显式指定
bin/citus-mcp --transport stdio --coordinator_dsn "postgres://..."

使用场景:

  • VS Code Copilot 聊天集成
  • GitHub Copilot CLI
  • 本地开发

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

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

# 使用 SSE 在 HTTP 上启动服务器
bin/citus-mcp --transport sse --http_addr 0.0.0.0 --http_port 8080 --coordinator_dsn "postgres://..."

# 或者通过环境变量设置
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 传输方式,推荐用于新的部署。

# 使用可流式传输的 HTTP 传输启动服务器
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/可流式传输的传输方式,配置 MCP 客户端通过 HTTP 连接:

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

🔌 与 GitHub Copilot 集成设置

VS Code 设置

  1. 安装先决条件
    • 安装带有 GitHub Copilot 扩展的 VS Code
    • 在 Copilot 设置中启用 MCP 支持
  2. 创建 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"
          }
        }
      }
    }
    
  3. 重新加载 VS Code 并打开 Copilot 聊天
  4. 验证连接
    @citus-mcp ping
    

GitHub Copilot CLI 设置

  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"
          }
        }
      }
    }
    
  2. 验证设置
    copilot mcp list
    copilot mcp test citus-mcp
    
  3. 在 CLI 中使用
    copilot -p "Show me the cluster summary"
    

💻 使用示例

基础集群检查

@citus-mcp Show me the cluster summary
@citus-mcp List all distributed tables
@citus-mcp Inspect the public.users table including shards and indexes

监控

@citus-mcp Show current cluster activity
@citus-mcp Are there any lock waits in the cluster?
@citus-mcp Show background job progress

分析

@citus-mcp Analyze shard skew for the orders table
@citus-mcp Show me the shard heatmap grouped by node
@citus-mcp Explain this query: SELECT * FROM orders WHERE customer_id = 123

顾问

@citus-mcp Run the advisor with focus on skew
@citus-mcp Check operational health (long queries, locks, jobs)
@citus-mcp Suggest the best source node for snapshot-based scaling
@citus-mcp Check metadata health with deep validation across nodes

配置分析

@citus-mcp Analyze cluster configuration and recommend improvements
@citus-mcp Run config advisor with focus on memory settings

共置分析

@citus-mcp Show all colocation groups
@citus-mcp Which tables are colocated with the orders table?

节点添加

@citus-mcp Run pre-flight checks for adding node at postgres://user:pass@newworker:5432/db

📚 工具参考

检查工具

| 工具 | 参数 | 描述 | |------|------------|-------------| | ping | message? | 健康检查 | | server_info | — | 服务器元数据和模式 | | list_nodes | limit?, offset? | 协调器和工作节点 | | list_distributed_tables | limit?, offset? | 所有分布式表 | | list_shards | limit?, offset? | 带位置信息的分片 | | citus_cluster_summary | include_workers?, include_gucs?, include_config? | 包含配置健康状况的完整集群概述 | | citus_list_distributed_tables | schema?, table_type?, limit?, cursor? | 分页表列表 | | citus_list_reference_tables | schema?, limit?, cursor? | 分页引用表列表 | | citus_table_inspector | table (必需), include_shards?, include_indexes? | 深入查看表 | | citus_colocation_inspector | colocation_id?, limit? | 共置组 |

监控工具

| 工具 | 参数 | 描述 | |------|------------|-------------| | citus_activity | limit?, include_idle?, min_duration_secs? | 活动查询 | | citus_lock_inspector | include_locks?, limit? | 锁等待 | | citus_job_inspector | state?, include_tasks?, limit? | 后台作业 | | citus_shard_heatmap | table?, limit?, metric?, group_by? | 热点分片 | | citus_shard_skew_report | table?, metric?, include_top_shards? | 倾斜分析 | | citus_explain_query | sql (必需), analyze?, verbose?, costs? | 解释查询 |

顾问工具

| 工具 | 参数 | 描述 | |------|------------|-------------| | citus_advisor | focus? (skew/ops), max_tables?, include_next_steps?, include_sql_fixes? | SRE 顾问 | | citus_config_advisor | include_all_gucs?, category?, severity_filter?, total_ram_gb? | 配置分析 | | citus_snapshot_source_advisor | strategy?, max_candidates?, include_simulation? | 节点添加建议 | | citus_validate_rebalance_prereqs | table (必需) | 重新平衡准备情况 | | citus_metadata_health | check_level? (basic/thorough/deep), include_fixes? | 元数据一致性检查 | | citus_node_prepare_advisor | host (必需), port?, database?, generate_script? | 预检查和准备脚本 |

执行工具(需要批准)

| 工具 | 参数 | 描述 | |------|------------|-------------| | citus_rebalance_plan | table?, threshold?, max_shard_moves?, drain_only? | 预览重新平衡 | | citus_rebalance_execute | approval_token (必需), table?, threshold? | 启动重新平衡 | | citus_rebalance_status | verbose?, limit?, cursor? | 重新平衡进度 | | citus_move_shard_plan | shard_id, source_host, source_port, target_host, target_port, colocated? | 预览分片移动 | | citus_move_shard_execute | approval_token (必需), shard_id, source_*, target_*, colocated?, drop_method? | 执行分片移动 | | citus_request_approval_token | action (必需), ttl_seconds? | 获取批准令牌 | | rebalance_table_plan | table (必需) | 旧版:计划表重新平衡 | | rebalance_table_execute | table (必需), approval_token (必需) | 旧版:执行表重新平衡 |


📋 内置提示

在 Copilot 聊天中使用这些提示以获得引导式工作流程: | 提示 | 描述 | |--------|-------------| | /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
    
  2. 执行前请求批准令牌
    @citus-mcp Request approval token for rebalance
    
  3. 在执行命令中使用令牌
    @citus-mcp Execute rebalance with token: <token>
    

令牌具有时间限制且特定于操作(使用 HMAC 签名)。


🔧 故障排除

连接问题

错误:connection refused

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

错误:authentication failed

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

MCP 问题

Copilot 无法识别 citus-mcp

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

工具返回错误

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

测试连接

# 直接测试
CITUS_MCP_COORDINATOR_DSN="postgres://..." bin/citus-mcp

# 然后通过标准输入发送 ping 请求
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | bin/citus-mcp

🛠️ 开发说明

运行测试

# 单元测试
make test

# 详细输出
go test -v ./...

# 集成测试(需要 Docker)
make docker-up
make integration
make docker-down

代码检查

make lint

项目结构

citus-mcp/
├── cmd/citus-mcp/       # 主入口点
├── internal/
│   ├── mcpserver/       # MCP 服务器实现
│   │   ├── tools/       # 工具实现(30 多个工具)
│   │   ├── prompts/     # 提示模板
│   │   └── resources/   # 静态资源
│   ├── db/              # 数据库层和工作节点管理
│   ├── citus/           # Citus 特定逻辑和查询
│   │   ├── advisor/     # 顾问实现
│   │   └── guc/         # GUC(配置)分析
│   ├── cache/           # 查询结果缓存
│   ├── config/          # 配置管理
│   ├── errors/          # 错误类型和代码
│   ├── fanout
help

运行方式说明

cloud

托管运行

托管运行通常表示这个 MCP Server 由服务方环境承载,用户一般按页面提供的连接方式或授权流程接入,不需要在本地长期启动一个 MCP 进程

  1. 打开服务方连接页
  2. 完成授权或复制端点
  3. 在 MCP 客户端中连接
terminal

本地运行 / 其它方式

本地运行通常需要用户在自己的电脑或服务器上安装依赖,把 server_config 复制到 MCP 客户端,并按 env_schema 补齐环境变量、密钥或其它配置

  1. 复制 server_config
  2. 安装所需依赖
  3. 补齐环境变量后重启客户端