十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

如何用 Claude Agent SDK 构建可观测性 Agent:接入 GitHub MCP 监控 CI 流水线

如何用 Claude Agent SDK 构建可观测性 Agent:接入 GitHub MCP 监控 CI 流水线 如何用 Claude Agent SDK 构建可观测性 Agent接入 GitHub MCP 监控 CI 流水线【免费下载链接】claude-cookbooksA collection of notebooks/recipes showcasing some fun and effective ways of using Claude.项目地址: https://gitcode.com/GitHub_Trending/an/claude-cookbooks这篇文章面向想给 GitHub 仓库的 CI 流水线加一层自动监控的开发者使用 claude-cookbooks 仓库中的claude_agent_sdk教程通过 Claude Agent SDK 的ClaudeSDKClient接入官方 GitHub MCP Server让 Agent 只读地查询仓库的 workflow 文件、提交与 PR 状态输出一份可供 on-call 工程师判断的 CI 健康分析。适用前提已在仓库文档中写明Python 3.11–3.12、本机运行 Docker、持有 Anthropic API Key 和 GitHub Personal Access Token。准备条件按 claude_agent_sdk/README.md 的 Getting Started 一节完成环境安装uv、Node.js 与 Claude Code CLIcurl -LsSf https://astral.sh/uv/install.sh | sh npm install -g anthropic-ai/claude-code克隆仓库并进入claude_agent_sdk目录后执行uv sync安装依赖。依赖在 pyproject.toml 中声明关键约束是requires-python 3.11,3.13和claude-agent-sdk0.1.51。注册 Jupyter kernel供运行 02_The_observability_agent.ipynb 使用uv run python -m ipykernel install --user --namecc-sdk-tutorial --display-name Python (cc-sdk-tutorial)在.env文件中配置两个密钥ANTHROPIC_API_KEY你的 API Key GITHUB_TOKEN你的 token其中GITHUB_TOKEN按 README 与 notebook 的说明应选择 Fine-grained 类型的 token 并使用默认选项public repos无 account 权限。确认 Docker 正在运行因为 GitHub MCP Server 以容器方式启动notebook 建议用docker --version验证。配置 GitHub MCP ServerMCPModel Context Protocol负责把外部系统接入 Agent。接入官方 GitHub MCP Server 后Agent 获得 GitHub 平台相关的工具能力可查询 issues、PR、commits 和 workflow 等数据。配置本身就是一个commandargsenv的字典import os from typing import Any from dotenv import load_dotenv load_dotenv(overrideTrue) github_mcp: dict[str, Any] { github: { command: docker, args: [ run, -i, --rm, -e, GITHUB_PERSONAL_ACCESS_TOKEN, ghcr.io/github/github-mcp-server, ], env: {GITHUB_PERSONAL_ACCESS_TOKEN: os.environ.get(GITHUB_TOKEN)}, } }docker run --rm会在每次调用后清理容器GITHUB_PERSONAL_ACCESS_TOKEN从.env里的GITHUB_TOKEN读取。仓库中封装好的模块 observability_agent/agent.py 的get_github_mcp_server()逻辑与此一致并且当GITHUB_TOKEN未设置时直接返回空字典——也就是不配置 token 时 Agent 不会挂上任何 GitHub 工具。启动 Agent 并发起 CI 监控查询注意一个 notebook 中强调的细节allowed_tools只控制权限提示不控制工具可用性必须同时用disallowed_tools禁掉Bash、Task等Agent 才不会绕过 MCP 去用ghCLIimport os from typing import Any from dotenv import load_dotenv from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient from utils.agent_visualizer import print_activity load_dotenv(overrideTrue) prompt Analyze the CI health for facebook/react repository. Examine the most recent runs of the CI workflow and provide: 1. Current status and what triggered the run (push, PR, schedule, etc.) 2. If failing: identify the specific failing jobs/tests and assess severity 3. If passing: note any concerning patterns (long duration, flaky history) 4. Recommended actions with priority (critical/high/medium/low) Provide a concise operational summary suitable for an on-call engineer. Do not create issues or PRs - this is a read-only analysis. messages [] async with ClaudeSDKClient( optionsClaudeAgentOptions( modelclaude-opus-4-6, mcp_serversgithub_mcp, allowed_tools[mcp__github], # disallowed_tools ensures the agent ONLY uses MCP tools, not Bash with gh CLI disallowed_tools[Bash, Task, WebSearch, WebFetch], permission_modeacceptEdits, ) ) as agent: await agent.query(prompt) async for msg in agent.receive_response(): print_activity(msg) messages.append(msg)其中modelclaude-opus-4-6是 notebook 与 agent 模块DEFAULT_MODEL中使用的模型mcp_serversgithub_mcp挂接上面的 MCP 配置permission_modeacceptEdits沿用 notebook 的原始设置。仓库模块版还会附加一个系统提示词要求 Agent 以适合 on-call 工程师的简洁可操作洞察作答并专注于识别问题、评估严重度和给出下一步建议。监控目标仓库和 workflow 名都可以按你的情况替换 prompt 中的facebook/react与CI其余配置不变。验证运行结果执行过程中终端会实时打印工具调用流水文档示例例如 Using: mcp__github__get_file_contents() Using: mcp__github__list_commits() ✓ Tool completed Thinking...这说明 Agent 确实通过mcp__github__*工具在查询而不是走了 Bash 回退路径。最终结果在messages[-1].result中用 notebook 的方式渲染from IPython.display import Markdown, display display(Markdown(f\nResult:\n{messages[-1].result}))notebook 记录的一次示例输出文档示例显示Agent 依次调用了get_file_contents、list_commits、list_pull_requests、get_commit、pull_request_read、search_issues等工具产出的报告包含主要 workflow 清单及其触发条件、main 分支近期提交状态、活跃 PR 的检查状态、风险提示与按 critical/high/medium/low 分级建议的行动项。你的仓库不会得到同样的数值和结论但报告结构由 prompt 决定应保持一致。复用为模块并做多轮追问observability_agent/agent.py 把上述模式封装成可复用的send_query(prompt, ...)函数内部自动完成活动上下文重置、实时活动打印和结果渲染。在 notebook 环境里注意该目录需在导入路径上README 建议从claude_agent_sdk/目录运行或uv pip install -e .from observability_agent.agent import send_query result await send_query( Check the CI status for the last 2 runs in anthropics/claude-agent-sdk-python. Just do 3 tool calls, be efficient. )追问同一仓库时传continue_conversationTrue会话上下文会延续result2 await send_query( Are there any flaky tests in the recent failures? You can only make one tool call., continue_conversationTrue, )send_query还提供两个与当前场景直接相关的参数use_github默认True关闭后不挂载 GitHub MCP Server和restrict_to_mcp默认True即禁用Bash/Task/WebSearch/WebFetch设为False时 Agent 拥有 Bash 等回退选项。限制与边界该 Agent 定位为只读观测notebook 的 prompt 明确要求 Do not create issues or PRs模块 docstring 也说明它聚焦于只读的 GitHub 操作。不要把它当作自动修复工具使用。不配置GITHUB_TOKEN时get_github_mcp_server()返回空字典Agent 将没有任何 GitHub 工具可用查询不会报错但拿不到数据。GitHub MCP Server 支持公共仓库和私有仓库文档未区分权限差异token 的粒度决定了实际可见范围。notebook 的示例结果对应facebook/react在特定日期的状态属于历史示例不能作为预期输出。仓库observability_agent/docker/目录下另有一份docker-compose.yml映射端口 8001:8000、挂载 Docker socket用于容器化部署该 Agent其 Dockerfile 的 CMD 指向observability_agent.web.app当前仓库中并没有该 web 模块容器化路径以仓库现状为准需要自行核对。完成上面步骤后你可以把 prompt 中的仓库替换为自己要盯的项目定期触发同一查询需要更深入的诊断时用continue_conversationTrue在同一会话里继续追问而不是重新开会话丢失上下文。【免费下载链接】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),仅供参考
返回列表