如何构建 SRE 故障响应 Agent:读写 MCP 工具修复问题并写事后复盘文档
发布时间:2026/9/11 1:38:52 锦皓数字建站

如何构建 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 降到 1Agent 自主定位根因、把配置改回 20、重新部署并生成一份包含摘要、根因、时间线和处理步骤的 postmortem 文档。准备条件按 03_The_site_reliability_agent.ipynb 中列出的前置要求本地运行 Docker用于承载模拟的基础设施PostgreSQL、API server、流量发生器、PrometheusAnthropic API key写入claude_agent_sdk/site_reliability_agent/目录下的.env文件ANTHROPIC_API_KEYyour-key-herePython 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定义六个服务postgresPostgreSQL 15、api-serverFastAPI 应用暴露 Prometheus 指标、healthy-services模拟始终健康的 payment-svc / auth-svc 指标、traffic-generator约 50 req/s 的持续流量保证 Prometheus 始终有数据可抓、prometheus每 5 秒抓取 api-server 的/metrics、grafana可选看板localhost:3000config/api-server.env是 api-server 的环境变量文件其中DB_POOL_SIZE20就是后面要被改坏的参数同时生成一份已知正常值的备份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-composeup、down、ps、logs、restart、build和dockercompose、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_SIZE1 in content: with open(config_path, w) as f: f.write(content.replace(DB_POOL_SIZE1, DB_POOL_SIZE20)) result subprocess.run( [docker-compose, -f, config/docker-compose.yml, up, -d], cwdSRE_PROJECT_ROOT, capture_outputTrue, textTrue, checkTrue, ) 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.配置 AgentMCP 服务器、工具白名单与写操作钩子ClaudeAgentOptions把三样东西组装起来MCP 子进程、允许调用的工具列表、以及PreToolUse钩子。钩子是写操作的第二道防线——MCP handler 限制的是能在哪里改钩子校验的是改的内容是否安全。钩子在工具执行前自动运行以非零状态退出时该次工具调用被阻断Agent 会看到错误并调整做法。infra_setup.py 生成的两个钩子hooks/validate_pool_size.sh——在edit_config_file前触发解析new_value若DB_POOL_SIZE超出安全范围 5–100 则阻断hooks/validate_config_before_deploy.sh——在重新部署 api-server 的run_shell_command前触发读取config/api-server.envDB_POOL_SIZE超出 5–100 时阻断部署。MCP_SERVER_PATH Path(SRE_PROJECT_ROOT) / sre_mcp_server.py assert MCP_SERVER_PATH.exists(), fMCP server not found at {MCP_SERVER_PATH} HOOKS_DIR os.path.join(SRE_PROJECT_ROOT, hooks) options ClaudeAgentOptions( system_promptSYSTEM_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: fbash {HOOKS_DIR}/validate_pool_size.sh, } ], }, { matcher: mcp__sre__run_shell_command, hooks: [ { type: command, command: fbash {HOOKS_DIR}/validate_config_before_deploy.sh, } ], }, ], }, permission_modeacceptEdits, modelMODEL, )先跑一遍健康系统的基线给 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_SIZE20, DB_POOL_SIZE1) with open(config_path, w) as f: f.write(content) subprocess.run( [docker-compose, -f, config/docker-compose.yml, up, -d, api-server], cwdSRE_PROJECT_ROOT, capture_outputTrue, textTrue, checkTrue, ) print(Fault injected: DB_POOL_SIZE1. Waiting 30s for error metrics to accumulate...) time.sleep(30) print(Error successfully injected.)注入后先在浏览器打开http://localhost:9090执行 PromQLrate(http_requests_total{status500}[1m])切换到 Graph 标签应当看到/api/users端点的错误率明显上升基线时接近零。这些信号与 Agent 稍后自主发现的是同一组数据。分两步交给 Agent先调查后修复调查阶段只给一个模糊的用户投诉式提示词要求报告发现但不要执行修复incident_report Were 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(promptincident_report, optionsoptions)流式消费消息AssistantMessage中的ToolUseBlock会显示 Agent 实际调用了哪些工具。预期结果Agent 自己选择查询错误率、db_connections_active、P99 延迟、读日志和配置文件最终把根因定位到DB_POOL_SIZE1。确认诊断无误后再下达修复指令这是有意设计的 human-in-the-loop 分界点fix_prompt Based on your investigation, the root cause is DB_POOL_SIZE1 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写出复盘文档。验证结果修复完成后做两项检查打开config/api-server.env确认DB_POOL_SIZE已恢复为20查看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 与 Confluencesre_mcp_server.py 已内置 PagerDuty4 个工具创建/更新/查询/列出事件和 Confluence3 个工具confluence_create_postmortem、confluence_get_page、confluence_list_postmortems的完整实现它们是条件注册的服务器启动时检查环境变量只有凭证齐全时对应工具才会出现在tools/list中。在项目根的.env中补充# PagerDuty PAGERDUTY_API_KEYyour-pagerduty-api-key PAGERDUTY_SERVICE_IDyour-service-id PAGERDUTY_FROM_EMAILoncallyourcompany.com # Confluence CONFLUENCE_BASE_URLhttps://yourcompany.atlassian.net/wiki CONFLUENCE_API_TOKENyour-confluence-api-token CONFLUENCE_USER_EMAILyouyourcompany.com CONFLUENCE_SPACE_KEYSRE CONFLUENCE_PARENT_PAGE_ID12345然后把这些工具加入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),仅供参考
锦
锦皓数字建站
深耕本土企业品牌数字化升级,专注原创端正雅致商务官网,从视觉设计到稳定运维全程保驾护航。