Teradata工作负载管理(TDWM)MCP服务器
  
用于Teradata工作负载管理(TDWM)的模型控制协议(MCP)服务器,为Teradata系统提供全面的监控和管理功能。
特性
此MCP服务器为Teradata工作负载管理提供了一整套功能:
- 46管理工具:33个核心监控工具+13个配置管理工具
- 39 MCP资源:参考数据、模板、规则集探索和工作流指导
- 自动连接弹性:具有指数回退的智能重试
- 连接健康监控:自动健康检查和恢复
- 模板驱动配置:常见TDWM配置的预构建模式
- 修改前的发现:通过资源探索现有配置
- 多步骤工作流程指南:复杂操作的分步模板
用例
🔍 性能故障排除
场景:确定查询运行缓慢或延迟的原因
使用工具:
show_sessions-识别活动会话及其状态identify_blocking-查找导致阻塞的会话show_session_sql_text-查看正在运行的SQLmonitor_amp_load-检查AMP利用率display_delay_queue-查看查询是否延迟show_tasm_statistics-分析TASM工作负载分布
可供探索的资源:
tdwm://summary-系统总体状态tdwm://throttle-statistics-当前油门限制和延迟
⚡ 应急响应
场景:系统过载,需要快速限制工作负载
工作流程:
- 使用
tdwm://workflow/emergency-throttle分步指南资源 - 使用
tdwm://template/throttle/application-basic用于快速节流模式 create_system_throttle具有低并发限制enable_throttle激活activate_ruleset立即应用更改- 监视器
show_trottle_statistics
预期结果:立即减少工作量,稳定系统
🎯 工作负载优化
场景:优化不同应用程序类型的资源分配
发现阶段:
list_rulesets-查看现有配置tdwm://rulesets资源-探索规则集详细信息show_tasm_statistics-了解当前的工作负载模式show_top_users-识别资源消费者
配置阶段:
- 使用模板资源(
tdwm://templates/throttle,tdwm://templates/filter) - 使用创建特定于应用程序的节流阀
create_system_throttle - 添加分类标准
add_classification_to_rule - 启用和激活
enable_throttle+activate_ruleset
验证:
- 查询
tdwm://ruleset/{name}/throttles确认配置 - 监视器
show_trottle_statistics查看效果
🛠️ 定期维护
场景:在维护窗口期间阻止用户访问
工作流程:
- 使用
tdwm://workflow/maintenance-window获取完整指南 - 使用
tdwm://template/filter/maintenance-window模板 - 使用创建筛选器
create_filter针对所有用户或特定应用 enable_filter+activate_ruleset阻止访问- 进行维护
disable_filter+activate_ruleset恢复访问权限
安全:筛选器阻止新连接,但不会终止现有会话
📊 容量规划
场景:分析使用模式以规划资源分配
数据收集:
show_query_log-历史查询模式show_tasm_statistics-工作量分配show_cod_limits-当前容量限制list_utility_stats-公用设施使用模式show_top_users-用户资源消耗
分析:
- 确定高峰使用时间
- 了解应用程序工作负载模式
- 计划节流/过滤策略
- COD容量需求
安装
pip install tdwm-mcp快速开始
通过4个步骤开始跑步:
# 1. Install the package
pip install tdwm-mcp
# 2. Configure database connection
export DATABASE_URI="teradata://username:password@hostname/database"
# 3. Start the MCP server
uv run tdwm-mcp
# 4. Test with a simple tool call
# Use your MCP client (e.g., Claude Desktop) to call:
# Tool: show_sessions
# Expected: List of your active Teradata sessions服务器将启动并连接到您的Teradata系统。您可以立即开始使用监控工具或探索资源。
配置
数据库连接
将数据库连接URL设置为环境变量或命令行参数:
# Environment variable (recommended)
export DATABASE_URI="teradata://username:password@hostname/database"
# Or as command-line argument
uv run tdwm-mcp "teradata://username:password@hostname/database"连接URL格式:
teradata://username:password@hostname[:port]/database[?param=value]例子:
# Basic connection
export DATABASE_URI="teradata://dbc:dbc@192.168.1.100/DBC"
# With custom port
export DATABASE_URI="teradata://myuser:mypass@tdhost.company.com:1025/prod_db"
# With SSL
export DATABASE_URI="teradata://user:pass@host/db?sslmode=require"重试配置
自定义连接失败的自动重试行为:
# Maximum number of retry attempts (default: 2)
export TOOL_MAX_RETRIES=3
# Initial retry delay in seconds (default: 0.5)
export TOOL_RETRY_INITIAL_DELAY=1.0
# Maximum retry delay in seconds (default: 2.0)
export TOOL_MAX_RETRY_DELAY=5.0日志记录配置
控制日志详细程度:
# Set logging level (DEBUG, INFO, WARNING, ERROR)
export LOG_LEVEL=INFO
# Enable detailed retry logging
export LOG_LEVEL=DEBUG连接弹性
TDWM MCP服务器包括用于处理Teradata连接失败的自动重试逻辑。如果工具执行因连接丢失而失败,服务器将自动重试操作,而不需要手动干预或重新启动服务器。
运作原理
所有工具和资源都包含一个智能重试装饰器,该装饰器:
- 检测连接错误 -区分连接失败(可以重试)和SQL/数据错误(应该立即失败)
- 智能重试逻辑 -根据安全分类自动重试操作:
- 读取操作 (查询、监视):最多重试2次 - 写入操作 (创建、更新):最多重试1次 - 危险作业 (删除、删除、中止):不自动重试
- 指数退避 -使用渐进延迟(0.5秒→ 1.0s → 2.0s) 通过抖动来避免数据库不堪重负
- 详细日志记录 -记录所有重试尝试以进行故障排除
连接错误检测
重试机制会自动检测这些Teradata连接问题:
- 网络超时和断开连接
- 连接被拒绝/重置错误
- 会话断开连接(错误3126)
- 由于TDWM终止,交易中止(错误2631)
- 超出会话限制(错误8017)
- 通信链路故障
配置
您可以使用环境变量自定义重试行为:
# Maximum number of retry attempts (default: 2)
export TOOL_MAX_RETRIES=3
# Initial retry delay in seconds (default: 0.5)
export TOOL_RETRY_INITIAL_DELAY=1.0
# Maximum retry delay in seconds (default: 2.0)
export TOOL_MAX_RETRY_DELAY=5.0好处
- 无需手动重新启动 -如果Teradata重新连接,操作将自动恢复
- 无缝恢复 -用户不需要手动重新调用失败的操作
- 默认安全 -从不重试危险操作,以防止意外的副作用
- LLM友好 -对法学硕士代理人透明;一旦重试成功,它们就会收到结果
建筑
系统概述
┌─────────────────────────────────────────────────────────┐
│ MCP Client │
│ (Claude Desktop, etc.) │
└───────────────────┬─────────────────────────────────────┘
│ MCP Protocol
┌───────────────────▼─────────────────────────────────────┐
│ TDWM MCP Server │
│ ┌────────────────────────────────────────────────┐ │
│ │ server.py - FastMCP App │ │
│ └────────────────┬───────────────────────────────┘ │
│ │ │
│ ┌────────────────▼───────────────────────────────┐ │
│ │ fnc_common.py │ │
│ │ • Connection Manager (_connection_manager) │ │
│ │ • get_connection() │ │
│ │ • @with_connection_retry decorator │ │
│ │ • Response formatting │ │
│ └────────┬────────────────┬──────────────────────┘ │
│ │ │ │
│ ┌────────▼─────┐ ┌──────▼──────────┐ ┌───────────┐ │
│ │ fnc_tools.py │ │ fnc_tools_ │ │ fnc_ │ │
│ │ │ │ priority1.py │ │ resources │ │
│ │ 33 core │ │ │ │ .py │ │
│ │ monitoring │ │ 13 config │ │ │ │
│ │ tools │ │ management │ │ 39 │ │
│ │ │ │ tools │ │ resources │ │
│ └──────────────┘ └─────────────────┘ └───────────┘ │
│ │ │ │ │
│ ┌────────▼────────────────▼─────────────────────▼───┐ │
│ │ retry_utils.py │ │
│ │ • is_connection_error() │ │
│ │ • categorize_operation() │ │
│ │ • Exponential backoff logic │ │
│ └───────────────────────────────────────────────────┘ │
└───────────────────┬─────────────────────────────────────┘
│ teradatasql
┌───────────────────▼─────────────────────────────────────┐
│ Teradata Database │
│ (TDWM/TASM System) │
└─────────────────────────────────────────────────────────┘模块组织
服务器被组织成专门的模块,用于可维护性和关注点分离:
核心模块
fnc_common.py -共享公用设施和连接管理
- 具有健康检查功能的集中式连接管理器
get_connection()-提供健康的数据库连接set_tools_connection()-初始化连接管理器- 响应格式化功能
- 类型定义(ResponseType)
- 自动导入重试装饰器
fnc_tools.py -堆芯监测工具(33个工具)
- 会话管理和监控
- 查询频段跟踪
- 系统资源监控
- 工作量管理
- 延迟队列操作
- TASM统计与分析
- 性能监控
fnc_tools_priority1.py -配置管理(13个工具)
- 限制创建、修改、删除
- 过滤器创建和管理
- 分类标准管理
- 规则集激活
- TDWM配置的所有写入操作
fnc_resources.py -MCP资源(39个资源)
- 资源目录和路由
- 从resource_reference、resource_templates、resource_query导入
- 处理基于URI的资源请求
- 返回JSON格式的引用数据
支持模块
retry_utils.py -重试逻辑
@with_connection_retry()装饰器is_connection_error()-检测连接与SQL错误categorize_operation()-按安全性分类(读/写/危险)- 具有抖动的指数回退
- Teradata错误代码检测
resource_reference.py -参考数据资源(8个资源)
- 分类类型目录
- 操作员参考
- 子标准类型
- 动作类型、油门类型、状态
resource_templates.py -配置模板(13个资源)
- 节流模板(4个预构建模式)
- 过滤器模板(4个预构建模式)
- 工作流模板(5个多步骤指南)
- 模板目录
resource_queries.py -规则集探索(8个资源)
- 规则集列表和详细信息
- 节气门/滤清器检查
- 待定更改检测
- 活动规则集标识
connection_manager.py -连接健康管理
TeradataConnectionManager类- 健康检查监测(间隔5分钟)
- 自动重新连接并重试
- 连接池
- 查询频段设置
模块依赖关系图
retry_utils.py (no dependencies on fnc modules)
↓
fnc_common.py (imports retry_utils)
↓
├─→ fnc_tools_priority1.py (imports fnc_common)
│ ↓
├─→ fnc_tools.py (imports fnc_common + fnc_tools_priority1)
│ ↓
└─→ fnc_resources.py (imports fnc_common)
↓
server.py (imports all above)关键设计原则:非循环依赖图可防止循环导入,同时允许代码重用。
连接管理流程
1. Server Startup
└─→ server.py::initialize_database()
└─→ Creates TeradataConnectionManager
└─→ Sets query band: ApplicationName=TDWM_MCP
└─→ Calls set_tools_connection(_connection_manager, _db)
└─→ Sets global in fnc_common.py
2. Tool Execution
└─→ Tool function decorated with @with_connection_retry()
└─→ Calls get_connection() from fnc_common
└─→ Checks global _connection_manager
└─→ Performs health check (if interval elapsed)
├─→ If healthy: Returns existing connection
└─→ If unhealthy: Creates new connection with retry
└─→ Retry logic: 3 attempts, exponential backoff
└─→ Returns healthy connection
3. Connection Lost During Query
└─→ @with_connection_retry() decorator catches error
└─→ is_connection_error() analyzes exception
├─→ If connection error: Retry based on operation category
│ ├─→ Read operation: Up to 2 retries
│ ├─→ Write operation: Up to 1 retry
│ └─→ Dangerous operation: No retry, raise immediately
└─→ If SQL error: Raise immediately, no retry健康检查机制
连接管理器会自动监视连接运行状况:
- 健康检查间隔:5分钟(300秒)
- 健康检查查询:
SELECT 1 - 失败时:连接标记为不健康、已关闭并已重新创建
- 论成功:连接被重新用于后续请求
- 好处:防止使用过时的连接,自动恢复
重试机制
智能重试系统,可区分错误并对操作进行分类:
错误检测:
# Connection errors (RETRY)
- OperationalError
- InterfaceError
- ConnectionError
- Teradata Error Codes: 2631, 3126, 3127, 8017
- Patterns: "connection", "network", "timeout", etc.
# SQL errors (NO RETRY)
- ProgrammingError (syntax errors)
- DataError (type mismatches)
- IntegrityError (constraint violations)操作分类:
# Read operations (max 2 retries)
Keywords: show, get, list, query, search, find, check, view, display
# Write operations (max 1 retry)
Keywords: create, update, set, modify, add, enable, disable, activate
# Dangerous operations (no retry)
Keywords: delete, drop, remove, purge, terminate, abort, kill, force指数退避:
- 初始延迟:0.5秒
- 倍数:每次重试2倍
- 最大延迟:2.0秒
- 抖动:±25%,防止群体打雷
可用工具
会话管理
- show_sessions -显示我的活动会话
- show_sql_steps_for_session -显示特定会话的SQL执行步骤
- show_sql_text_for_session -显示特定会话的SQL文本
- abort_sessions_user -中止特定用户的所有会话
- 识别阻塞 -识别导致阻塞情况的用户
查询频带和监控
- 监视器会话查询带 -监视特定会话的查询带
- list_query_band -按类型列出查询带(事务、概要、会话或全部)
- show_query_log -显示特定用户的查询日志
系统资源监控
- show_physical_resources -监控系统物理资源
- monitor_amp_load -监控AMP(访问模块处理器)负载
- 监视器\_ awt -监控AWT(AMP Worker Task)资源
- monitor_config -监控虚拟配置
负载管理
- list_active_WD -列出活动工作负载(WD)
- 列表_WD -列出所有工作负载(WD)
- show_tdwm_summary -显示工作负载摘要信息
延迟队列管理
- list_delayed_request -列出所有延迟查询
- 中止延迟请求 -中止特定会话的延迟请求
- display_delay_queue -按类型显示延迟队列详细信息(工作负载、系统、公用事业或全部)
- release_delay_queue -释放会话或用户的延迟请求
油门和性能
- show_trottle_统计 -显示油门统计信息(全部、查询、会话、工作负载)
- list_utility_stats -列出系统上公用设施使用情况的统计信息
系统信息
- show_cod_限制 -显示COD(按需容量)限制
- show_top_users -显示消耗最多资源的用户
- show_sw_event_log -显示系统软件事件日志(操作或全部)
Teradata主动系统管理
- tdwm_list_分类 -列出工作负载(TASM)规则的分类类型
- show_tasm_统计 -显示TASM性能统计数据
- show_tasm_even_history -显示TASM事件历史记录
- show_tasm_rule_history_red -显示导致系统进入红色状态的原因
配置管理(优先级1-新增!)
通过对节流阀、过滤器和规则的程序化控制,实现自主的工作负载管理操作。
油门管理
- create_system_throttle -创建具有并发限制的系统级限制
- 修改油门限制 -动态调整油门并发限制
- 删除_删除 -删除油门定义
- enable_throttle -激活油门规则
- disable_throttle -停用油门规则
过滤器管理
- create_filter -创建过滤器以阻止/拒绝查询
- delete_filter -删除筛选器定义
- 启用筛选器 -激活筛选规则
- disable_filter -停用筛选规则
规则管理
- 添加分类到规则 -将分类标准添加到任何规则中
- add_subcriteria_to_target -添加子标准(例如,表格的FTSCAN)
- 激活规则集 -应用所有待定更改以使其生效
- list_rulesets -列出所有可用的规则集
⚠️ 弃用的工具-请勿使用
重要:这些工具是为了向后兼容性而留下的非功能性存根。使用 优先级1配置管理 相反,工具。
- create_filter_rule ❌ 已弃用→ Use
create_filter优先级1 - add_class_criteria ❌ 已弃用→ Use
add_classification_to_rule优先级1 - enable_filter_in-default ❌ 已弃用→ Use
enable_filter+activate_ruleset优先级1 - enable_filter_rule ❌ 已弃用→ Use
enable_filter优先级1 - activate_rulset ❌ 已弃用→ Use
activate_ruleset来自优先级1(注意拼写修复)
这些函数不包含实现,将返回空结果。它们计划在v2.0中删除。
可用资源
MCP资源提供只读的上下文信息,帮助LLM在调用工具之前理解有效值、发现模板和探索现有配置。
参考数据资源
为配置工具提供有效的值和参数格式。
tdwm://reference/classification-types-所有31种分类类型tdwm://reference/classification-types/{category}-按类别筛选(请求源、目标、查询特征)tdwm://reference/operators-带用例的分类运算符(I、O、IO)tdwm://reference/subcriteria-types-子标准类型(FTSCAN、MINSTEPTIME、JOIN、MEMORY等)tdwm://reference/actions-筛选操作类型(E=异常,A=中止)tdwm://reference/throttle-types-油门类型(DM、M)tdwm://reference/states-TASM系统状态(绿色、黄色、橙色、红色)tdwm://reference/catalog-所有参考资源的综合目录
配置模板
常见节流阀和过滤器配置的预构建模式。
油门模板:
tdwm://templates/throttle-列出所有油门模板tdwm://template/throttle/application-basic-按应用程序限制查询tdwm://template/throttle/table-fullscan-限制全表扫描tdwm://template/throttle/user-concurrency-限制每个用户的并发性tdwm://template/throttle/time-based-etl-基于时间的ETL限制
筛选器模板:
tdwm://templates/filter-列出所有筛选器模板tdwm://template/filter/maintenance-window-在维护期间阻止查询tdwm://template/filter/user-restriction-阻止特定用户tdwm://template/filter/table-protection-保护敏感表tdwm://template/filter/application-restriction-阻止特定应用程序
规则集探索
发现并检查现有的TDWM配置。
tdwm://rulesets-列出所有可用的规则集tdwm://system/active-ruleset-获取当前活动的规则集名称tdwm://ruleset/{ruleset_name}-详细的规则集信息tdwm://ruleset/{ruleset_name}/throttles-规则集中的列表限制tdwm://ruleset/{ruleset_name}/throttle/{throttle_name}-油门详细信息tdwm://ruleset/{ruleset_name}/filters-在规则集中列出筛选器tdwm://ruleset/{ruleset_name}/filter/{filter_name}-筛选器详细信息tdwm://ruleset/{ruleset_name}/pending-changes-检查待处理的更改
工作流模板
常见多步骤操作的分步指南。
tdwm://workflows-列出所有可用工作流tdwm://workflow/create-throttle-完成油门创建工作流程tdwm://workflow/create-filter-完成过滤器创建工作流程tdwm://workflow/maintenance-window-启用/禁用过滤器进行维护tdwm://workflow/emergency-throttle-快速应急响应工作流程tdwm://workflow/modify-existing-throttle-修改现有节流工作流
遗留资源
基本监测资源(原始实施)。
tdwm://sessions-当前数据库会话tdwm://workloads-所有工作负载定义tdwm://active-workloads-仅限活动工作负载tdwm://summary-TDWM系统概述tdwm://delayed-queries-延迟查询列表tdwm://throttle-statistics-油门统计tdwm://physical-resources-物理系统资源tdwm://amp-load-AMP负载信息tdwm://classification-types-分类类型(传统格式)
使用示例
基本会话监控
# Show all my sessions
await call_tool("show_sessions")
# Show SQL text for session 1234
await call_tool("show_sql_text_for_session", {"sessionNo": 1234})
# Show SQL execution steps for session 1234
await call_tool("show_sql_steps_for_session", {"sessionNo": 1234})系统资源监控
# Monitor AMP load
await call_tool("monitor_amp_load")
# Monitor physical resources
await call_tool("show_physical_resources")
# Monitor AWT resources
await call_tool("monitor_awt")负载管理
# List active workloads
await call_tool("list_active_WD")
# Show workload summary
await call_tool("show_tdwm_summary")
# Show throttle statistics for all types
await call_tool("show_trottle_statistics", {"type": "ALL"})查询分析
# Show query log for user 'john_doe'
await call_tool("show_query_log", {"user": "john_doe"})
# Show top resource-consuming users
await call_tool("show_top_users", {"type": "TOP"})延迟队列管理
# List all delayed requests
await call_tool("list_delayed_request")
# Display system delay queue
await call_tool("display_delay_queue", {"type": "SYSTEM"})
# Release delayed requests for session 1234
await call_tool("release_delay_queue", {"sessionNo": 1234})TASM监控
# Show TASM statistics
await call_tool("show_tasm_statistics")
# Show what caused RED state
await call_tool("show_tasm_rule_history_red")
# List classification types for rules
await call_tool("tdwm_list_clasification")配置管理(新增!)
创建系统节流阀
# Limit ETL queries to 5 concurrent with application classification
await call_tool("create_system_throttle", {
"ruleset_name": "MyFirstConfig",
"throttle_name": "ETL_THROTTLE",
"description": "Limit ETL workload concurrency during business hours",
"throttle_type": "DM", # Disable override member
"limit": 5,
"classification_criteria": [
{
"description": "ETL Application",
"type": "APPL",
"value": "ETL_APP",
"operator": "I"
}
]
})动态调整油门
# Increase ETL throttle limit during off-peak hours
await call_tool("modify_throttle_limit", {
"ruleset_name": "MyFirstConfig",
"throttle_name": "ETL_THROTTLE",
"new_limit": 10
})
# Decrease back during business hours
await call_tool("modify_throttle_limit", {
"ruleset_name": "MyFirstConfig",
"throttle_name": "ETL_THROTTLE",
"new_limit": 5
})创建维护窗口筛选器
# Block reporting user queries during backup
await call_tool("create_filter", {
"ruleset_name": "MyFirstConfig",
"filter_name": "MAINTENANCE_BLOCK",
"description": "Block non-critical queries during maintenance",
"classification_criteria": [
{
"description": "Reporting Users",
"type": "USER",
"value": "reporting_user",
"operator": "I"
}
],
"action": "E" # Exception (reject)
})启用/禁用过滤器和油门
# Enable maintenance filter before backup
await call_tool("enable_filter", {
"ruleset_name": "MyFirstConfig",
"filter_name": "MAINTENANCE_BLOCK"
})
# Disable after backup completes
await call_tool("disable_filter", {
"ruleset_name": "MyFirstConfig",
"filter_name": "MAINTENANCE_BLOCK"
})
# Temporarily disable a throttle
await call_tool("disable_throttle", {
"ruleset_name": "MyFirstConfig",
"throttle_name": "ETL_THROTTLE"
})向现有规则添加分类
# Add additional application to existing throttle
await call_tool("add_classification_to_rule", {
"ruleset_name": "MyFirstConfig",
"rule_name": "ETL_THROTTLE",
"description": "Add secondary ETL application",
"classification_type": "APPL",
"classification_value": "ETL_APP_V2",
"operator": "IO" # Inclusion with ORing
})为高级规则添加子标准
# Add full table scan sub-criterion to table throttle
await call_tool("add_subcriteria_to_target", {
"ruleset_name": "MyFirstConfig",
"rule_name": "TABLE_THROTTLE",
"target_type": "TABLE",
"target_value": "myDB.LargeTable",
"description": "Full table scan detection",
"subcriteria_type": "FTSCAN",
"operator": "I"
})管理规则集
# List all available rulesets
await call_tool("list_rulesets")
# Activate ruleset to apply all changes
await call_tool("activate_ruleset", {
"ruleset_name": "MyFirstConfig"
})使用资源进行引导配置
资源提供了上下文和模板,使配置更容易,更不容易出错。
发现可用模板
# List throttle templates
resource = await read_resource("tdwm://templates/throttle")
# Returns: List of available templates (application-basic, table-fullscan, etc.)
# Get specific template details
template = await read_resource("tdwm://template/throttle/application-basic")
# Returns: Complete template with parameters, tool calls, and examples了解有效参数值
# Get all classification types
types = await read_resource("tdwm://reference/classification-types")
# Returns: 31 classification types with categories and expected values
# Get only "Request Source" classification types
request_types = await read_resource("tdwm://reference/classification-types/Request Source")
# Returns: USER, APPL, CLIENTADDR, CLIENTID, etc.
# Understand operators
operators = await read_resource("tdwm://reference/operators")
# Returns: I, O, IO with descriptions and use cases
# Learn about sub-criteria
subcriteria = await read_resource("tdwm://reference/subcriteria-types")
# Returns: FTSCAN, MINSTEPTIME, JOIN, MEMORY with examples探索现有配置
# Find active ruleset
active = await read_resource("tdwm://system/active-ruleset")
# Returns: Name of currently active ruleset (e.g., "MyFirstConfig")
# Get ruleset details
ruleset = await read_resource("tdwm://ruleset/MyFirstConfig")
# Returns: All throttles, filters, and rules in the ruleset
# Inspect specific throttle
throttle = await read_resource("tdwm://ruleset/MyFirstConfig/throttle/ETL_THROTTLE")
# Returns: Throttle configuration, limits, and classification criteria
# Check what filters exist
filters = await read_resource("tdwm://ruleset/MyFirstConfig/filters")
# Returns: List of all filters in the ruleset遵循复杂操作的工作流程
# Get workflow guidance for creating a throttle
workflow = await read_resource("tdwm://workflow/create-throttle")
# Returns: Step-by-step guidance including:
# 1. Discover templates
# 2. Review template details
# 3. Identify target ruleset
# 4. Review reference data
# 5. Create throttle
# 6. Add sub-criteria (if needed)
# 7. Activate changes
# 8. Verify configuration
# 9. Monitor effectiveness
# Emergency response workflow
emergency = await read_resource("tdwm://workflow/emergency-throttle")
# Returns: Quick steps for performance crisis response完整示例:模板驱动油门创建
# Step 1: Read template
template = await read_resource("tdwm://template/throttle/application-basic")
# Step 2: Get active ruleset
active_ruleset = await read_resource("tdwm://system/active-ruleset")
ruleset_name = active_ruleset["active_ruleset"]
# Step 3: Create throttle using template structure
await call_tool("create_system_throttle", {
"ruleset_name": ruleset_name,
"throttle_name": "MY_APP_THROTTLE",
"description": f"Limit MyApp to 5 concurrent queries",
"throttle_type": "DM",
"limit": 5,
"classification_criteria": [
{
"description": "Application classification",
"type": "APPL", # From template
"value": "MyApp",
"operator": "I" # From tdwm://reference/operators
}
]
})
# Step 4: Activate
await call_tool("activate_ruleset", {"ruleset_name": ruleset_name})
# Step 5: Verify
result = await read_resource(f"tdwm://ruleset/{ruleset_name}/throttle/MY_APP_THROTTLE")
# Confirm throttle is created and enabled完整的工作流程
紧急油门创建(5分钟)
场景:系统过载,需要立即限制工作负载
# Step 1: Assess current load
sessions = await call_tool("show_sessions")
throttle_stats = await call_tool("show_trottle_statistics", {"type": "ALL"})
summary = await read_resource("tdwm://summary")
# Step 2: Get emergency throttle template
template = await read_resource("tdwm://template/throttle/application-basic")
# Template provides structure and best practices
# Step 3: Create emergency throttle (low limit)
result = await call_tool("create_system_throttle", {
"ruleset_name": "Tactical",
"throttle_name": "EMERGENCY_LIMIT",
"throttle_type": "DM", # Delay Management
"limit": 3, # Very restrictive
"classification_criteria": [{
"description": "All user queries",
"type": "APPL",
"value": "*", # All applications
"operator": "I"
}]
})
# Step 4: Enable and activate immediately
await call_tool("enable_throttle", {
"ruleset_name": "Tactical",
"throttle_name": "EMERGENCY_LIMIT"
})
await call_tool("activate_ruleset", {"ruleset_name": "Tactical"})
# Step 5: Monitor effect
await asyncio.sleep(30) # Wait 30 seconds
new_stats = await call_tool("show_trottle_statistics", {"type": "ALL"})
# Check delayed count - should show queries being throttled
# Step 6: Gradual recovery
await call_tool("modify_throttle_limit", {
"ruleset_name": "Tactical",
"throttle_name": "EMERGENCY_LIMIT",
"new_limit": 10 # Increase gradually
})
await call_tool("activate_ruleset", {"ruleset_name": "Tactical"})预期结果:立即减少工作负载,延迟队列增加,系统稳定
发现→ 修改→ 验证图案
场景:了解当前状态后安全修改现有油门
# Phase 1: Discovery
# List all rulesets
rulesets = await call_tool("list_rulesets")
# Returns: ["Tactical", "Production", ...]
# Explore specific ruleset
ruleset_info = await read_resource("tdwm://ruleset/Tactical")
# Shows: throttles, filters, pending changes
# Get list of throttles
throttles = await read_resource("tdwm://ruleset/Tactical/throttles")
# Returns: [{"name": "APP_LIMIT", "enabled": true, ...}, ...]
# Inspect specific throttle
throttle_detail = await read_resource("tdwm://ruleset/Tactical/throttle/APP_LIMIT")
# Shows: current limit, classifications, enabled state
# Phase 2: Modification
# Modify throttle limit
result = await call_tool("modify_throttle_limit", {
"ruleset_name": "Tactical",
"throttle_name": "APP_LIMIT",
"new_limit": 15 # Increase from current value
})
# Check pending changes
pending = await read_resource("tdwm://ruleset/Tactical/pending-changes")
# Shows what will happen when activated
# Phase 3: Activation
await call_tool("activate_ruleset", {"ruleset_name": "Tactical"})
# Phase 4: Verification
# Confirm change applied
updated_throttle = await read_resource("tdwm://ruleset/Tactical/throttle/APP_LIMIT")
# Verify limit is now 15
# Monitor impact
stats = await call_tool("show_trottle_statistics", {"type": "ALL"})
# Check delayed counts, ensure expected behavior主要优势:
- 没有意外-在激活之前看看会有什么变化
- 审计跟踪-待定更改可见
- 安全迭代-在继续之前验证每个步骤
维护窗口设置
场景:在2小时的维护窗口期间阻止所有非管理员用户
# Step 1: Get maintenance window template
template = await read_resource("tdwm://template/filter/maintenance-window")
workflow = await read_resource("tdwm://workflow/maintenance-window")
# Step 2: Create filter to block users
result = await call_tool("create_filter", {
"ruleset_name": "Tactical",
"filter_name": "MAINT_BLOCK",
"action": "E", # Exception (reject)
"message": "System under maintenance until 10:00 PM",
"classification_criteria": [{
"description": "Block non-DBA users",
"type": "USER",
"value": "dba", # DBA user allowed
"operator": "O" # OR with other criteria (exclude DBA)
}]
})
# Step 3: Enable filter
await call_tool("enable_filter", {
"ruleset_name": "Tactical",
"filter_name": "MAINT_BLOCK"
})
# Step 4: Activate (maintenance window starts)
await call_tool("activate_ruleset", {"ruleset_name": "Tactical"})
print("Maintenance window active - non-admin users blocked")
# ... Perform maintenance tasks ...
# Step 5: Disable filter (maintenance window ends)
await call_tool("disable_filter", {
"ruleset_name": "Tactical",
"filter_name": "MAINT_BLOCK"
})
await call_tool("activate_ruleset", {"ruleset_name": "Tactical"})
print("Maintenance window ended - all users can connect")
# Step 6: Optional cleanup
await call_tool("delete_filter", {
"ruleset_name": "Tactical",
"filter_name": "MAINT_BLOCK"
})
await call_tool("activate_ruleset", {"ruleset_name": "Tactical"})安全注意事项:
- 筛选器仅阻止新连接(不会终止现有会话)
- 管理员/DBA用户仍然可以连接
- 如果急需,易于禁用
故障排除
连接问题
“数据库连接未初始化”
原因:DATABASE_URI未设置或服务器启动失败
解决方案:
# Check environment variable
echo $DATABASE_URI
# Should show: teradata://user:pass@host/db
# If empty, set it:
export DATABASE_URI="teradata://username:password@hostname/database"
# Restart server
uv run tdwm-mcp“会话已断开连接”(错误3126)
原因:查询执行过程中连接丢失
预期行为:自动重试(读取操作最多2次)
检查什么:
# Enable debug logging to see retry attempts
export LOG_LEVEL=DEBUG
uv run tdwm-mcp
# In logs, look for:
# "Tool 'show_sessions' connection error on attempt 1/3. Retrying in 0.5s..."
# "Tool 'show_sessions' succeeded on retry attempt 1/2"如果重试失败:
- 检查与Teradata的网络连接
- 验证Teradata系统是否联机
- 检查防火墙规则
- 增加重试次数:
export TOOL_MAX_RETRIES=5
持续连接失败
原因:网络问题、凭据或Teradata系统故障
调试步骤:
# 1. Test basic connectivity
ping teradata-host
# 2. Test Teradata port (default 1025)
telnet teradata-host 1025
# 3. Verify credentials with direct connection
python3 &1 | grep -i error重试行为
请参阅日志中的重试尝试
# Enable DEBUG logging
export LOG_LEVEL=DEBUG
# Start server
uv run tdwm-mcp
# Look for retry messages:
# WARNING: Tool 'list_sessions' (category: read) connection error on attempt 1/3.
# Retrying in 0.47s... Error: [Error 3126] Session has been disconnected
# INFO: Tool 'list_sessions' succeeded on retry attempt 1/2禁用测试重试
# Disable all retries
export TOOL_MAX_RETRIES=0
# Now connection errors will fail immediately (useful for debugging)调整重试时间
# Faster retries (for testing)
export TOOL_RETRY_INITIAL_DELAY=0.1
export TOOL_MAX_RETRY_DELAY=0.5
# Slower retries (for flaky networks)
export TOOL_RETRY_INITIAL_DELAY=2.0
export TOOL_MAX_RETRY_DELAY=10.0SQL错误与连接错误
SQL语法错误-无需重试
Error: [Error 3706] Syntax error: expected something between 'SELCT' and '*'.行为:立即失败,不重试(修复代码中的SQL)
连接错误-自动重试
Error: [Error 3126] Session has been disconnected
Error: connection timeout
Error: broken pipe行为:根据操作类型自动重试:
- 读取操作:最多重试2次
- 写入操作:最多重试1次
- 危险操作(删除/中止):不重试
工具执行错误
错误:预期的字符串或字节类似于对象,得到“AnyUrl”
原因:资源URI类型不匹配(v1.5.0中已修复)
如果你在旧版本中看到这个:
# In fnc_resources.py, handle_read_resource():
# Add this at the start of the function:
uri = str(uri) # Convert AnyUrl to string工具返回空结果
可能原因:
- 弃用的工具:检查工具是否在“⚠️ “弃用工具”部分
- 无匹配数据:查询未返回任何行
- 权限不足:用户无法查看数据
调试:
# Enable debug logging
export LOG_LEVEL=DEBUG
# Check logs for SQL errors or empty result sets健康检查问题
经常重新创建连接
症状:日志反复显示“现有连接不健康,正在关闭”
可能原因:
- 网络不稳定
- Teradata空闲超时过于激进
- 健康检查间隔太短
解决方案:
# Increase health check interval in connection_manager.py:
self._health_check_interval = 600 # 10 minutes instead of 5
# Or reduce network timeouts
# In teradatasql connection, add timeout parameters资源加载错误
“找不到资源”
原因:URI与任何注册的资源都不匹配
解决方案:检查可用资源:
resources = await list_resources()
# Returns list of all 39 available resources with URIs资源返回错误
原因:资源实现中的数据库查询失败
调试:
# Check logs for SQL errors in resource functions
export LOG_LEVEL=DEBUG
# Look for errors in resource_reference.py, resource_templates.py, resource_queries.py性能问题
工具响应缓慢
可能原因:
- 复杂的查询需要很长时间
- 大型结果集
- 网络延迟
- 连接健康检查延迟
调试:
# Check query execution time in logs
export LOG_LEVEL=DEBUG
# Look for:
# "Tool 'show_tasm_statistics' took 15.3 seconds"优化:
- 在查询中使用更具体的筛选器
- 限制结果集
- 监控Teradata系统性能
常见错误消息
| 错误消息 | 原因 | 解决方案 |
|---|---|---|
Database connection not initialized | 缺少DATABASE_URI | 设置环境变量 |
Session has been disconnected | 连接丢失 | 将自动重试 |
Syntax error | 工具中的SQL错误 | 报告为错误 |
Permission denied | 用户缺乏权限 | 授予Teradata权限 |
Session limit exceeded | 连接太多 | 关闭未使用的会话 |
Transaction ABORTed due to TDWM | 系统限制查询 | 预期行为 |
工具参数
必需参数
- 会话No (整数)-会话特定操作的会话号
- 用户 (string)-用户特定操作的用户名
- 规则Name (string)-规则激活的规则名称
可选参数
- 类型 (string)-各种工具的类型规范(例如,“ALL”、“TOP”、“SYSTEM”、“WORKLOAD”)
- 用户名 (string)-某些操作的可选用户名参数
静态参考数据
服务器包括TDWM分类类型的静态参考表:
- TDWM_规格_类型 -分类类型及其类别和期望值
- TDWM_分类_值 -分类值及其描述
错误处理
所有工具都包括全面的错误处理,如果操作失败,将返回描述性错误消息。
日志记录
服务器使用名为“teradata_mcp”的Python日志模块进行调试和监控。
依赖项
teradatasql-Teradata SQL驱动程序mcp-模型控制协议框架pydantic-数据验证PyYAML-YAML配置支持fastmcp-快速MCP服务器框架
发展
项目结构
tdwm-mcp/
├── src/tdwm_mcp/
│ ├── __init__.py
│ ├── server.py # FastMCP app and server initialization
│ ├── fnc_common.py # Shared utilities & connection management
│ ├── fnc_tools.py # Core monitoring tools (33 tools)
│ ├── fnc_tools_priority1.py # Configuration management (13 tools)
│ ├── fnc_resources.py # Resource routing (39 resources)
│ ├── fnc_prompts.py # MCP prompts
│ ├── retry_utils.py # Retry decorator & error detection
│ ├── connection_manager.py # Connection health management
│ ├── resource_reference.py # Reference data resources
│ ├── resource_templates.py # Configuration templates
│ ├── resource_queries.py # Ruleset exploration queries
│ ├── tdwm_static.py # Static reference data
│ ├── tdsql.py # Teradata SQL wrapper
│ └── oauth_context.py # OAuth support
├── pyproject.toml # Package configuration
├── uv.lock # Dependency lock file
└── README.md # This file添加新工具
要添加新的监控工具,请执行以下操作:
# In fnc_tools.py
@with_connection_retry()
async def my_new_tool(param1: str, param2: int) -> ResponseType:
"""
Description of what the tool does.
Args:
param1: Description of parameter
param2: Description of parameter
Returns:
ResponseType: Formatted tool response
"""
try:
tdconn = await get_connection()
cur = tdconn.cursor()
# Your SQL query
query = "SELECT * FROM my_table WHERE col1 = ? AND col2 = ?"
rows = cur.execute(query, [param1, param2])
result = list([row for row in rows.fetchall()])
return format_text_response(result)
except Exception as e:
logger.error(f"Error in my_new_tool: {e}")
return format_error_response(str(e))
# Register in handle_list_tools()
types.Tool(
name="my_new_tool",
description="Detailed description for LLMs explaining what, when, why to use this tool",
inputSchema={
"type": "object",
"properties": {
"param1": {
"type": "string",
"description": "Description of param1"
},
"param2": {
"type": "integer",
"description": "Description of param2"
}
},
"required": ["param1", "param2"]
}
)要点:
- 使用
@with_connection_retry()用于自动重试的装饰器 - 呼叫
get_connection()来自fnc_common的数据库访问 - 使用
format_text_response()或format_error_response()用于输出 - 在中注册该工具
handle_list_tools()附有详细说明 - 包括全面的输入模式和描述
添加新资源
要添加新的MCP资源,请执行以下操作:
# In resource_reference.py (or appropriate resource module)
async def get_my_new_resource() -> str:
"""Get my new reference data."""
data = {
"resource_name": "My Resource",
"description": "What this resource provides",
"items": [
{"key": "value1", "description": "Description"},
{"key": "value2", "description": "Description"}
]
}
return format_text_response(data)
# In fnc_resources.py - add to handle_list_resources()
types.Resource(
uri="tdwm://category/my-resource",
name="My Resource Name",
description="Detailed description of what this resource provides",
mimeType="application/json"
)
# In fnc_resources.py - add to handle_read_resource()
elif uri == "tdwm://category/my-resource":
return await get_my_new_resource()测试
# Install dependencies
uv sync
# Run server locally
export DATABASE_URI="teradata://user:pass@host/db"
uv run tdwm-mcp
# Test with MCP Inspector
npx @modelcontextprotocol/inspector uv run tdwm-mcp
# Compile check
python3 -m py_compile src/tdwm_mcp/*.py贡献指南
- 代码风格:遵循PEP 8 Python风格指南
- 类型提示:对所有函数参数和返回值使用类型提示
- 文档字符串:包括带参数/返回值的综合文档字符串
- 错误处理:始终包含try/,除非有描述性错误
- 日志记录:使用记录器进行调试,而不是打印语句
- 测试:提交前针对真实Teradata系统的测试工具
- 文档:使用新的工具/资源更新README.md
版本历史
v1.5.0(2025-01-05)-当前版本
- 添加:连接弹性的自动重试机制
- 添加:带健康检查的连接管理器(间隔5分钟)
- 固定的:通过提取fnc_common.py进行循环导入
- 固定的:跨40个功能的连接管理器访问模式
- 增强:更好地理解LLM的工具描述(46个工具)
- 增强:建筑部分的综合文件
v1.4.0(2024)
- 添加:39 MCP资源(参考数据、模板、工作流程)
- 添加:修改模式前基于资源的发现
- 添加:模板驱动的配置示例
v1.3.0(2024)
- 添加:优先级1配置管理(13个工具)
- 添加:限制管理(创建、修改、删除、启用、禁用)
- 添加:筛选器管理(创建、删除、启用、禁用)
- 添加:分类和规则集管理工具
v1.2.0(2024)
- 添加:TASM统计和分析工具
- 添加:查询频段监控
- 增强:工作量管理能力
v1.1.0(2024)
- 添加:延迟队列管理工具
- 添加:系统资源监控
- 增强:会话管理工具
v1.0.0(2024)-初始版本
- 会话、工作负载和资源的核心监控工具
- TDWM基本功能
- MCP服务器实现
即将发布(v2.0.0)
- 霹雳舞:删除已弃用的旧工具
- 添加:高级TASM规则管理
- 添加:工作量分析和建议
- 增强:OAuth 2.0身份验证支持
许可证
此MCP服务器根据MIT许可证获得许可。这意味着您可以根据MIT许可证的条款和条件自由使用、修改和分发软件。有关更多详细信息,请参阅项目存储库中的LICENSE文件。
