redshift-utils-mcp
Redshift Utils MCP 服务器
概述
该项目实现了专门设计用于与 Amazon Redshift 数据库交互的模型上下文协议 (MCP) 服务器。
它弥合了大型语言模型 (LLM) 或 AI 助手(例如 Claude、Cursor 或自定义应用程序中的助手)与您的 Redshift 数据仓库之间的差距,从而实现了安全、标准化的数据访问和交互。这使得用户能够使用自然语言或 AI 驱动的提示来查询数据、理解数据库结构以及执行监控/诊断操作。
该服务器适用于希望以结构化和安全的方式将 LLM 功能直接与其 Amazon Redshift 数据环境集成的开发人员、数据分析师或团队。
Related MCP server: Redshift MCP Server
目录
特征
✨**安全的 Redshift 连接(通过数据 API):**通过 Boto3 使用 AWS Redshift 数据 API 连接到您的 Amazon Redshift 集群,利用 AWS Secrets Manager 通过环境变量安全地管理凭证。
🔍**模式发现:**公开 MCP 资源以列出指定模式内的模式和表。
📊**元数据和统计数据:**提供一个工具(
handle_inspect_table)来收集详细的表元数据、统计数据(如大小、行数、偏差、统计数据陈旧性)和维护状态。📝**只读查询执行:**提供安全的 MCP 工具(
handle_execute_ad_hoc_query)来对 Redshift 数据库执行任意 SELECT 查询,从而实现基于 LLM 请求的数据检索。📈**查询性能分析:**包括一个工具(
handle_diagnose_query_performance)来检索和分析特定查询 ID 的执行计划、指标和历史数据。🔍**表检查:**提供一个工具(
handle_inspect_table)对表进行全面检查,包括设计、存储、健康和使用情况。🩺**集群健康检查:**提供一个工具(
handle_check_cluster_health)来使用各种诊断查询对集群执行基本或完整的健康评估。🔒**锁诊断:**提供一个工具(
handle_diagnose_locks)来识别和报告当前的锁争用和阻塞会话。📊**工作负载监控:**包括一个工具(
handle_monitor_workload)来分析时间窗口内的集群工作负载模式,涵盖 WLM、热门查询和资源使用情况。📝 **DDL 检索:**提供一个工具(
handle_get_table_definition)来检索指定表的SHOW TABLE输出(DDL)。🛡️**输入清理:**在适用的情况下通过 Boto3 Redshift 数据 API 客户端利用参数化查询来减轻 SQL 注入风险。
🧩**标准化 MCP 接口:**遵循模型上下文协议规范,可与兼容客户端(例如,Claude Desktop、Cursor IDE、自定义应用程序)无缝集成。
先决条件
软件:
Python 3.8+
uv(推荐的包管理器)Git(用于克隆存储库)
基础设施与通道:
访问 Amazon Redshift 集群。
一个有权使用 Redshift Data API (
redshift-data:*) 并访问指定的 Secrets Manager 密钥 (secretsmanager:GetSecretValue) 的 AWS 账户。一个 Redshift 用户账户,其凭证存储在 AWS Secrets Manager 中。此用户需要在 Redshift 中拥有必要的权限才能执行此服务器启用的操作(例如,
CONNECT到数据库、在目标表上SELECT``SELECT操作、在相关系统视图(例如pg_class、pg_namespace、svv_all_schemas、svv_tables和 `svv_table_info``)上执行 SELECT 操作)。强烈建议使用遵循最小权限原则的角色。请参阅安全注意事项。
证书:
您的 Redshift 连接详细信息通过 AWS Secrets Manager 进行管理,服务器使用 Redshift Data API 进行连接。您需要:
Redshift 集群标识符。
集群内的数据库名称。
包含数据库凭证(用户名和密码)的 AWS Secrets Manager 机密的 ARN。
集群和密钥所在的 AWS 区域。
如果不使用默认凭证/区域,则可选地输入 AWS 配置文件名称。
这些详细信息将通过环境变量进行配置,如配置部分所述。
配置
设置环境变量:此服务器需要以下环境变量才能通过 AWS 数据 API 连接到您的 Redshift 集群。您可以直接在 Shell 中设置这些变量,也可以使用 systemd 服务文件、Docker 环境文件,或者在项目根目录中创建.env文件(如果使用uv或python-dotenv等支持从.env加载的工具)。
使用 shell 导出的示例:
export REDSHIFT_CLUSTER_ID="your-cluster-id"
export REDSHIFT_DATABASE="your_database_name"
export REDSHIFT_SECRET_ARN="arn:aws:secretsmanager:us-east-1:123456789012:secret:your-redshift-secret-XXXXXX"
export AWS_REGION="us-east-1" # Or AWS_DEFAULT_REGION
# export AWS_PROFILE="your-aws-profile-name" # Optional示例.env文件(参见.env.example ):
# .env file for Redshift MCP Server configuration
# Ensure this file is NOT committed to version control if it contains secrets. Add it to .gitignore.
REDSHIFT_CLUSTER_ID="your-cluster-id"
REDSHIFT_DATABASE="your_database_name"
REDSHIFT_SECRET_ARN="arn:aws:secretsmanager:us-east-1:123456789012:secret:your-redshift-secret-XXXXXX"
AWS_REGION="us-east-1" # Or AWS_DEFAULT_REGION
# AWS_PROFILE="your-aws-profile-name" # Optional必需变量表:
变量名称 | 必需的 | 描述 | 示例值 |
| 是的 | 您的 Redshift 集群标识符。 |
|
| 是的 | 要连接的数据库的名称。 |
|
| 是的 | 用于 Redshift 凭证的 AWS Secrets Manager ARN。 |
|
| 是的 | 数据 API 和 Secrets Manager 的 AWS 区域。 |
|
| 不 | 用于指定 AWS 区域的 |
|
| 不 | 凭证文件 (~/.aws/...) 中使用的 AWS 配置文件名称。 |
|
注意:确保 Boto3 使用的 AWS 凭证(通过环境、配置文件或 IAM 角色)有权访问指定的REDSHIFT_SECRET_ARN并使用 Redshift 数据 API( redshift-data:* )。
用法
与 Claude Desktop / Anthropic Console 连接:
将以下配置块添加到您的mcp.json文件。根据您的安装方法和设置调整command 、 args 、 env和workingDirectory 。
{
"mcpServers": {
"redshift-utils-mcp": {
"command": "uvx",
"args": ["redshift_utils_mcp"],
"env": {
"REDSHIFT_CLUSTER_ID":"your-cluster-id",
"REDSHIFT_DATABASE":"your_database_name",
"REDSHIFT_SECRET_ARN":"arn:aws:secretsmanager:...",
"AWS_REGION": "us-east-1"
}
}
}与 Cursor IDE 连接:
按照使用/快速启动部分中的说明在本地启动 MCP 服务器。
在 Cursor 中,打开命令面板 (Cmd/Ctrl + Shift + P)。
输入“连接到 MCP 服务器”或导航到 MCP 设置。
添加新的服务器连接。
选择
stdio传输类型。输入启动服务器所需的命令和参数 (
uvx run redshift_utils_mcp)。确保所有必要的环境变量都可用于正在运行的命令。光标应该检测服务器及其可用的工具/资源。
可用的 MCP 资源
资源 URI 模式 | 描述 | 示例 URI |
| 从服务器的 |
|
| 列出所连接数据库中所有可访问的用户定义模式。 |
|
| 检索当前工作负载管理 (WLM) 配置详细信息。 |
|
| 列出指定 |
|
发出请求时,请将{script_path}和{schema_name}替换为实际值。架构/表的可访问性取决于通过REDSHIFT_SECRET_ARN配置的 Redshift 用户的权限。
可用的 MCP 工具
工具名称 | 描述 | 关键参数(必填*) | 示例调用 |
| 使用一组诊断 SQL 脚本对 Redshift 集群执行健康评估。 |
|
|
| 识别集群中的活动锁争用和阻塞会话。 |
|
|
| 分析特定查询的执行性能,包括计划、指标和历史数据。 |
|
|
| 通过 Redshift Data API 执行用户提供的任意 SQL 查询。设计为一个逃生出口。 |
|
|
| 检索特定表的 DDL(数据定义语言)语句( |
|
|
| 检索有关特定 Redshift 表的详细信息,包括设计、存储、运行状况和使用情况。 |
|
|
| 使用各种诊断脚本分析指定时间窗口内的集群工作负载模式。 |
|
|
待办事项
[ ] 改进提示选项
[ ] 添加对更多凭证方法的支持
[ ] 添加对 Redshift Serverless 的支持
贡献
欢迎投稿!请遵循以下准则。
查找/报告问题:查看 GitHub 问题页面,查找现有错误或功能请求。如有需要,欢迎随时提交新问题。
通过 MCP 服务器提供数据库访问时,安全性至关重要。请注意以下事项:
🔒**凭证管理:**此服务器通过 Redshift Data API 使用 AWS Secrets Manager,这比直接将凭证存储在环境变量或配置文件中更安全。请确保 Boto3 使用的 AWS 凭证(通过环境变量、配置文件或 IAM 角色)得到安全管理,并拥有必要的最低权限。切勿将您的 AWS 凭证或包含机密信息的.env文件提交到版本控制中。
🛡️**最小权限原则:**将凭证存储在 AWS Secrets Manager 中的 Redshift 用户配置为服务器预期功能所需的最低权限。例如,如果只需要读取权限,则仅授予对必要架构/表的CONNECT和SELECT权限,以及对所需系统视图的SELECT权限。避免使用admin或集群超级用户等高权限用户。
有关创建受限 Redshift 用户和管理权限的指导,请参阅官方( https://docs.aws.amazon.com/redshift/latest/mgmt/security.html )。
执照
本项目遵循 MIT 许可证。详情请参阅 LICENSE 文件。
参考
该项目严重依赖于模型上下文协议规范。
使用Model Context Protocol提供的官方 MCP SDK 构建。
利用 AWS SDK for Python( Boto3 )与Amazon Redshift 数据 API进行交互。
许多诊断 SQL 脚本都是从优秀的awslabs/amazon-redshift-utils存储库改编而来的。
Available Tools
7 toolshandle_check_cluster_healthA
Performs a health assessment of the Redshift cluster.
Executes a series of diagnostic SQL scripts concurrently based on the
specified level ('basic' or 'full'). Aggregates raw results or errors
from each script into a dictionary.
Args:
ctx: The MCP context object.
level: Level of detail: 'basic' for operational status, 'full' for
comprehensive table design/maintenance checks. Defaults to 'basic'.
time_window_days: Lookback period in days for time-sensitive checks
(e.g., queue waits, commit waits). Defaults to 1.
Returns:
A dictionary where keys are script names and values are either the raw
list of dictionary results from the SQL query or an Exception object
if that specific script failed.
Raises:
DataApiError: If a critical error occurs during script execution that
prevents gathering results (e.g., config error). Individual
script errors are captured within the returned dictionary.
Inputs: level, time_window_days.
handle_diagnose_locksA
Identifies active lock contention in the cluster.
Fetches all current lock information and then filters it based on the
optional target PID, target table name, and minimum wait time.
Formats the results into a list of contention details and a summary.
Args:
ctx: The MCP context object.
target_pid: Optional: Filter results to show locks held by or waited
for by this specific process ID (PID).
target_table_name: Optional: Filter results for locks specifically on
this table name (schema qualification recommended
if ambiguous).
min_wait_seconds: Minimum seconds a lock must be in a waiting state
to be included. Defaults to 5.
Returns:
A list of dictionaries, where each dictionary represents a row
from the lock contention query result.
Raises:
DataApiError: If fetching the initial lock information fails.
Inputs: min_wait_seconds, target_pid, target_table_name.
handle_diagnose_query_performanceA
Analyzes a specific query's execution performance.
Fetches query text, execution plan, metrics, alerts, compilation info,
skew details, and optionally historical run data. Uses a formatting
utility to synthesize this into a structured report with potential issues
and recommendations.
Args:
ctx: The MCP context object.
query_id: The numeric ID of the Redshift query to analyze.
compare_historical: Fetch performance data for previous runs of the
same query text. Defaults to True.
Returns:
A dictionary conforming to DiagnoseQueryPerformanceResult structure:
- On success: Contains detailed performance breakdown, issues, recommendations.
- On query not found: Raises QueryNotFound exception.
- On other errors: Raises DataApiError or similar for FastMCP to handle.
Raises:
DataApiError: If a critical error occurs during script execution or parsing.
QueryNotFound: If the specified query_id cannot be found in key tables.
Inputs: query_id (required), compare_historical.
handle_execute_ad_hoc_queryA
Executes an arbitrary SQL query provided by the user via Redshift Data API.
Designed as an escape hatch for advanced users or queries not covered by
specialized tools. Returns a structured dictionary indicating success
(with results) or failure (with error details).
Args:
ctx: The MCP context object.
sql_query: The exact SQL query string to execute.
Returns:
A dictionary conforming to ExecuteAdHocQueryResult structure:
- On success: {"status": "success", "columns": [...], "rows": [...], "row_count": ...}
- On error: {"status": "error", "error_message": "...", "error_type": "..."}
(Note: Actual return might be handled by FastMCP error handling for raised exceptions)
Raises:
DataApiConfigError: If configuration is invalid.
SqlExecutionError: If the SQL execution itself fails.
DataApiTimeoutError: If the Data API call times out.
DataApiError: For other Data API related errors or unexpected issues.
ClientError: For AWS client-side errors.
Inputs: sql_query (required).
handle_get_table_definitionA
Retrieves the DDL (Data Definition Language) statement for a specific table.
Executes a SQL script designed to generate or retrieve the CREATE TABLE
statement for the given table.
Args:
ctx: The MCP context object.
schema_name: The schema name of the table.
table_name: The name of the table.
Returns:
A dictionary conforming to GetTableDefinitionResult structure:
- On success: {"status": "success", "ddl": "<CREATE TABLE statement>"}
- On table not found or DDL retrieval error:
{"status": "error", "error_message": "...", "error_type": "..."}
Raises:
TableNotFound: If the specified table is not found.
DataApiError: If a critical, unexpected error occurs during execution.
Inputs: schema_name (required), table_name (required).
handle_inspect_tableA
Retrieves detailed information about a specific Redshift table.
Fetches table OID, then concurrently executes various inspection scripts
covering design, storage, health, usage, and encoding.
Args:
ctx: The MCP context object.
schema_name: The schema name of the table.
table_name: The name of the table.
Returns:
A dictionary where keys are script names and values are either the raw
list of dictionary results from the SQL query, the extracted DDL string,
or an Exception object if that specific script failed.
- On success: Dictionary containing raw results or Exception objects for each script.
- On table not found: Raises TableNotFound exception.
- On critical errors (e.g., OID lookup failure): Raises DataApiError or similar.
Raises:
DataApiError: If a critical error occurs during script execution.
TableNotFound: If the specified table cannot be found via its OID.
Inputs: schema_name (required), table_name (required).
handle_monitor_workloadA
Analyzes cluster workload patterns over a specified time window.
Executes various SQL scripts concurrently to gather data on resource usage,
WLM performance, top queries, queuing, COPY performance, and disk-based
queries. Returns a dictionary containing the raw results (or Exceptions)
keyed by the script name.
Args:
ctx: The MCP context object.
time_window_days: Lookback period in days for the workload analysis.
Defaults to 2.
top_n_queries: Number of top queries (by total execution time) to
consider for the 'top_queries.sql' script. Defaults to 10.
Returns:
A dictionary where keys are script names (e.g., 'workload/top_queries.sql')
and values are either a list of result rows (as dictionaries) or the
Exception object if that script failed.
Raises:
DataApiError: If a critical error occurs during configuration loading.
(Note: Individual script errors are returned in the result dict).
Inputs: time_window_days, top_n_queries.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Each tool has a distinct purpose with clear boundaries: cluster health assessment, lock diagnosis, query performance analysis, ad-hoc query execution, table definition retrieval, table inspection, and workload monitoring. There is no functional overlap between tools, and the descriptions clearly differentiate their specific use cases.
All tools follow a 'handle_verb_noun' prefix pattern, which provides some consistency. However, the verb choices are mixed ('check', 'diagnose', 'execute', 'get', 'inspect', 'monitor'), making the naming somewhat inconsistent in terms of action semantics. The structure is predictable but the verb selection lacks uniformity.
With 7 tools, this server is well-scoped for Redshift cluster diagnostics and management. Each tool serves a specific, valuable function in the domain, and there are no redundant or trivial tools. The count is appropriate for covering key operational and troubleshooting tasks without being overwhelming.
The toolset covers essential diagnostic and operational areas for Redshift: health checks, lock analysis, query performance, ad-hoc queries, table definitions, table inspection, and workload monitoring. Minor gaps exist, such as lack of tools for cluster configuration changes, user/role management, or backup operations, but core diagnostic workflows are well-covered.
Maintenance
Related MCP Connectors
Hosted SQL Server MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Hosted BigQuery MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Hosted Amazon Seller and Vendor MCP server for Claude, ChatGPT, Cursor, Codex, Gemini, Copilot.
Hosted Amazon Seller Central and Amazon Ads MCP server for Claude, ChatGPT, Cursor, and agents.
Related MCP Servers
- AlicenseBqualityBmaintenanceModel Context Protocol (MCP) server that integrates Redash with AI assistants like Claude, allowing them to query data, manage visualizations, and interact with dashboards through natural language.674,563 npm108MIT
- AlicenseBqualityDmaintenanceA Model Context Protocol server that enables AI assistants to interact with Amazon Redshift databases, allowing for schema exploration, query execution, and statistics collection.32Apache 2.0
- AlicenseAqualityBmaintenanceA Snowflake MCP server — SQL queries, schema exploration, and data insights for AI assistants6307 PyPI2MIT
- AlicenseAqualityDmaintenanceModel Context Protocol (MCP) server for Redash - manage queries, dashboards, and visualizations through AI assistants like Claude.6202 PyPIMIT