☰
如何构建 SRE 故障响应 Agent:读写 MCP 工具修复问题并写事后复盘文档
2026/10/4 1:21:50 网站建设 项目流程

如何构建 SRE 故障响应 Agent:读写 MCP 工具修复问题并写事后复盘文档

【免费下载链接】claude-cookbooksA collection of notebooks/recipes showcasing some fun and effective ways of using Claude.项目地址: https://gitcode.com/GitHub_Trending/an/claude-cookbooks

本文基于 claude-cookbooks 项目中的claude_agent_sdk/site_reliability_agent场景,教你用 Claude Agent SDK 构建一个 SRE 故障响应 Agent:它通过 MCP 子进程调用 Prometheus 查询指标、读取容器日志和配置文件(只读工具)完成调查,再用受限的写工具修改配置、重启服务完成修复,最后调用write_postmortem工具把事后复盘文档写入postmortems/目录。整套流程在本地 Docker 模拟环境中完成,不需要任何外部生产账号。

完成后的效果:你手动把一个配置项改坏(数据库连接池从 20 降到 1),Agent 自主定位根因、把配置改回 20、重新部署,并生成一份包含摘要、根因、时间线和处理步骤的 postmortem 文档。

准备条件

按 03_The_site_reliability_agent.ipynb 中列出的前置要求:

  • 本地运行 Docker,用于承载模拟的基础设施(PostgreSQL、API server、流量发生器、Prometheus);
  • Anthropic API key,写入claude_agent_sdk/site_reliability_agent/目录下的.env文件:
ANTHROPIC_API_KEY=your-key-here
  • Python 3.11+,安装 SDK 与依赖:
%pip install claude-agent-sdk httpx python-dotenv
  • 运行 notebook 前,确认工作目录是claude_agent_sdk/site_reliability_agent/,且 infra_setup.py 与 sre_mcp_server.py 与 notebook 在同一目录(仓库已附带)。

用 infra_setup.py 生成本地故障模拟环境

在 notebook 中执行python infra_setup.py(等价于直接在目录里运行该脚本),它会生成整套模拟生产环境的文件:

创建目录:config/、services/、scripts/、hooks/、postmortems/ Docker Compose: config/docker-compose.yml Prometheus 配置: config/prometheus.yml API server: services/api_server.py 流量发生器: scripts/traffic_generator.py 安全 hook: hooks/validate_pool_size.sh, hooks/validate_config_before_deploy.sh

各文件的作用(来自 infra_setup.py 的注释):

  • config/docker-compose.yml定义六个服务:postgres(PostgreSQL 15)、api-server(FastAPI 应用,暴露 Prometheus 指标)、healthy-services(模拟始终健康的 payment-svc / auth-svc 指标)、traffic-generator(约 50 req/s 的持续流量,保证 Prometheus 始终有数据可抓)、prometheus(每 5 秒抓取 api-server 的/metrics)、grafana(可选看板,localhost:3000);
  • config/api-server.env是 api-server 的环境变量文件,其中DB_POOL_SIZE=20就是后面要被"改坏"的参数;同时生成一份已知正常值的备份config/api-server.env.backup,供 Agent 调查时对照;
  • postmortems/是 Agent 写复盘文档的目标目录。

理解 MCP 工具服务器:读工具与写工具

sre_mcp_server.py 是 Claude Agent SDK 在 Agent 执行时以子进程方式启动的工具服务器,通过 stdin/stdout 上的 JSON-RPC 协议通信(处理initialize、tools/list、tools/call等方法)。它独立于 notebook 进程运行,某个工具 handler 崩溃或挂起不会拖垮 Agent 本身,也便于直接阅读和修改。

服务器注册了 12 个基础工具,按用途分四类:

类别工具用途
Prometheusquery_metrics、list_metrics、get_service_health查指标、发现可用指标、健康汇总
基础设施read_config_file、edit_config_file、run_shell_command、get_container_logs读写配置、执行 Docker 命令、查看日志
诊断get_logs、get_alerts、get_recent_deployments、execute_runbook应用日志、告警、部署记录、结构化 runbook
文档write_postmortem把事后复盘写入postmortems/

每个工具都带 JSON Schema 定义和详细描述,Agent 正是靠这些描述自主决定何时调用哪个工具。写工具在 handler 内内置了安全限制,这是让 Agent 安全接触基础设施的关键:

  • read_config_file/edit_config_file只允许操作config/目录,其他路径直接返回错误;
  • run_shell_command只允许docker-compose(up、down、ps、logs、restart、build)和docker(compose、ps、logs)命令,命令经shlex解析后用exec直接执行、不走 shell,超时 60 秒;
  • get_container_logs只接受白名单容器名:api-server、postgres、traffic-generator、prometheus、grafana,日志行数上限 200 行。

write_postmortem工具接收title、summary、root_cause(必填)以及timeline、remediation、action_items(可选),在postmortems/下生成时间戳命名的 Markdown 文件(如postmortem_20260909_084901.md),内含 Summary、Root Cause、Timeline、Remediation、Action Items 各节。

启动环境并跑基线健康检查

先启动 Docker 栈并等待指标开始流动(注意:up -d会在本机拉起上述六个容器,占用 5432、8080、9090、3000 端口):

config_path = os.path.join(SRE_PROJECT_ROOT, "config", "api-server.env") with open(config_path, "r") as f: content = f.read() if "DB_POOL_SIZE=1" in content: with open(config_path, "w") as f: f.write(content.replace("DB_POOL_SIZE=1", "DB_POOL_SIZE=20")) result = subprocess.run( ["docker-compose", "-f", "config/docker-compose.yml", "up", "-d"], cwd=SRE_PROJECT_ROOT, capture_output=True, text=True, check=True, ) print("Waiting for Prometheus to begin scraping metrics...") time.sleep(30) print("Metrics are flowing.")

系统提示词刻意保持简单:只给出调查方法论(先健康总览、再看错误率、延迟、DB 连接、日志、配置,最后关联根因),不规定具体调用顺序,工具选择交给 Agent 根据工具描述自行决定。

SYSTEM_PROMPT = """You are an expert SRE incident response bot. Your job is to investigate production incidents quickly and thoroughly. Investigation approach: 1. Start with get_service_health for a quick overview 2. Drill into error rates to identify affected services 3. Check latency — high latency often precedes errors 4. Investigate resources — DB connections, CPU, memory 5. Read container logs for specific error messages 6. Check config files for misconfigurations 7. Correlate and conclude — connect symptoms to root cause Note: The api-server has baseline error noise (~0.1-0.2 errors/sec). Focus on significant spikes. Be thorough but efficient. Always explain your reasoning."""

配置 Agent:MCP 服务器、工具白名单与写操作钩子

ClaudeAgentOptions把三样东西组装起来:MCP 子进程、允许调用的工具列表、以及PreToolUse钩子。钩子是写操作的第二道防线——MCP handler 限制的是"能在哪里改",钩子校验的是"改的内容是否安全"。钩子在工具执行前自动运行,以非零状态退出时该次工具调用被阻断,Agent 会看到错误并调整做法。

infra_setup.py 生成的两个钩子:

  1. hooks/validate_pool_size.sh——在edit_config_file前触发,解析new_value,若DB_POOL_SIZE超出安全范围 5–100 则阻断;
  2. hooks/validate_config_before_deploy.sh——在重新部署 api-server 的run_shell_command前触发,读取config/api-server.env,DB_POOL_SIZE超出 5–100 时阻断部署。
MCP_SERVER_PATH = Path(SRE_PROJECT_ROOT) / "sre_mcp_server.py" assert MCP_SERVER_PATH.exists(), f"MCP server not found at {MCP_SERVER_PATH}" HOOKS_DIR = os.path.join(SRE_PROJECT_ROOT, "hooks") options = ClaudeAgentOptions( system_prompt=SYSTEM_PROMPT, mcp_servers={ "sre": { "command": sys.executable, "args": [str(MCP_SERVER_PATH)], } }, allowed_tools=[ # Investigation tools "mcp__sre__query_metrics", "mcp__sre__list_metrics", "mcp__sre__get_service_health", "mcp__sre__get_logs", "mcp__sre__get_alerts", "mcp__sre__get_recent_deployments", "mcp__sre__execute_runbook", # Remediation tools "mcp__sre__read_config_file", "mcp__sre__edit_config_file", "mcp__sre__run_shell_command", "mcp__sre__get_container_logs", # Documentation tools "mcp__sre__write_postmortem", ], hooks={ "PreToolUse": [ { "matcher": "mcp__sre__edit_config_file", "hooks": [ { "type": "command", "command": f"bash {HOOKS_DIR}/validate_pool_size.sh", } ], }, { "matcher": "mcp__sre__run_shell_command", "hooks": [ { "type": "command", "command": f"bash {HOOKS_DIR}/validate_config_before_deploy.sh", } ], }, ], }, permission_mode="acceptEdits", model=MODEL, )

先跑一遍健康系统的基线:给 Agent 一个"检查所有服务健康状况"的提示词,它应当查询指标、核对服务状态并报告一切正常。这一步确认工具链(Prometheus、日志、配置读取)在注入故障前已经可用。

注入故障并在 Prometheus 中确认

把DB_POOL_SIZE从 20 改成 1 并重新部署 api-server。注意副作用:该单元格会修改config/api-server.env并重启 api-server 容器,30 秒后错误指标开始累积:

config_path = os.path.join(SRE_PROJECT_ROOT, "config", "api-server.env") with open(config_path, "r") as f: content = f.read() content = content.replace("DB_POOL_SIZE=20", "DB_POOL_SIZE=1") with open(config_path, "w") as f: f.write(content) subprocess.run( ["docker-compose", "-f", "config/docker-compose.yml", "up", "-d", "api-server"], cwd=SRE_PROJECT_ROOT, capture_output=True, text=True, check=True, ) print("Fault injected: DB_POOL_SIZE=1. Waiting 30s for error metrics to accumulate...") time.sleep(30) print("Error successfully injected.")

注入后先在浏览器打开http://localhost:9090,执行 PromQL:

rate(http_requests_total{status="500"}[1m])

切换到 Graph 标签,应当看到/api/users端点的错误率明显上升(基线时接近零)。这些信号与 Agent 稍后自主发现的是同一组数据。

分两步交给 Agent:先调查,后修复

调查阶段只给一个模糊的"用户投诉"式提示词,要求报告发现但不要执行修复:

incident_report = """We're getting reports of API errors and timeouts from users. Something is wrong with the api-server. Please investigate thoroughly: - Check service health and error rates - Look at DB connections and latency - Check container logs for errors - Look at the config files for any misconfigurations - Identify the root cause Report your findings but do NOT apply any fixes yet."""

通过query(prompt=incident_report, options=options)流式消费消息,AssistantMessage中的ToolUseBlock会显示 Agent 实际调用了哪些工具。预期结果:Agent 自己选择查询(错误率、db_connections_active、P99 延迟)、读日志和配置文件,最终把根因定位到DB_POOL_SIZE=1。

确认诊断无误后再下达修复指令,这是有意设计的 human-in-the-loop 分界点:

fix_prompt = """Based on your investigation, the root cause is DB_POOL_SIZE=1 in config/api-server.env. Please: 1. Fix the configuration by editing config/api-server.env to set DB_POOL_SIZE back to 20 2. Redeploy the api-server using run_shell_command with docker-compose 3. Wait a moment, then verify the fix by checking service health metrics 4. Write a post-mortem using the write_postmortem tool documenting what happened, the root cause, and the fix."""

Agent 应当完成四件事:edit_config_file把配置改回 20、run_shell_command执行docker-compose -f config/docker-compose.yml up -d api-server重新部署(注意工具描述中特别强调必须用up -d而非restart,因为restart不会重新加载 env 文件)、重新查询健康指标验证修复、调用write_postmortem写出复盘文档。

验证结果

修复完成后做两项检查:

  1. 打开config/api-server.env,确认DB_POOL_SIZE已恢复为20;
  2. 查看postmortems/目录,Agent 生成的复盘文档(postmortem_<时间戳>.md)应包含 Summary、Root Cause、Timeline、Remediation、Action Items 各节,文件名和正文均由write_postmortemhandler 生成。

收尾单元格还会在配置仍未恢复时强制改回 20,然后执行docker-compose -f config/docker-compose.yml down停止整个 Docker 栈(会停掉上面拉起的六个容器),并打印最后一份 postmortem 的全文供你核对。

可选扩展:接入 PagerDuty 与 Confluence

sre_mcp_server.py 已内置 PagerDuty(4 个工具:创建/更新/查询/列出事件)和 Confluence(3 个工具:confluence_create_postmortem、confluence_get_page、confluence_list_postmortems)的完整实现,它们是条件注册的:服务器启动时检查环境变量,只有凭证齐全时对应工具才会出现在tools/list中。在项目根的.env中补充:

# PagerDuty PAGERDUTY_API_KEY=your-pagerduty-api-key PAGERDUTY_SERVICE_ID=your-service-id PAGERDUTY_FROM_EMAIL=oncall@yourcompany.com # Confluence CONFLUENCE_BASE_URL=https://yourcompany.atlassian.net/wiki CONFLUENCE_API_TOKEN=your-confluence-api-token CONFLUENCE_USER_EMAIL=you@yourcompany.com CONFLUENCE_SPACE_KEY=SRE CONFLUENCE_PARENT_PAGE_ID=12345

然后把这些工具加入allowed_tools(如mcp__sre__pagerduty_create_incident、mcp__sre__confluence_create_postmortem)即可,无需改动系统提示词或 MCP 服务器代码,Agent 会自动发现并使用它们。启用后,confluence_create_postmortem可在 Confluence 中生成结构化的 postmortem 页面,替代本地的write_postmortem文件输出。

以上路径都限定在本地 Docker 模拟环境:get_alerts与get_recent_deployments在该演示中是模拟数据,runbook 内容(execute_runbook)也是文档化的结构化步骤而非真实执行逻辑。若要把 Agent 指向真实服务,需要按 notebook 的说明把生成的文件替换为对真实服务的连接,并保留同样的"读工具宽、写工具窄 + 钩子校验"结构。

【免费下载链接】claude-cookbooksA collection of notebooks/recipes showcasing some fun and effective ways of using Claude.项目地址: https://gitcode.com/GitHub_Trending/an/claude-cookbooks

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询