使用 mcp-agent 构建 GitHub PR 到 Slack 的智能摘要 Agent
2026/9/16 19:22:21 网站建设 项目流程

使用 mcp-agent 构建 GitHub PR 到 Slack 的智能摘要 Agent

【免费下载链接】mcp-agentBuild effective agents using Model Context Protocol and simple workflow patterns项目地址: https://gitcode.com/GitHub_Trending/mc/mcp-agent

本篇技术指南以mcp-agent框架为例,完整讲解如何构建一个监听 GitHub Pull Request 并自动生成优先级摘要、投递到指定 Slack 频道的 MCP Agent。文章涵盖整体工作流程、GitHub/Slack 双 MCP Server 的配置、密钥管理、核心源码逐段拆解、本地运行,以及将 Agent 部署到云端并通过任意 MCP 客户端触发的完整链路。读完本文,你将掌握基于mcp-agent聚合多个 MCP Server、借助 LLM 完成跨工具任务编排的实战方法。

案例背景:一个 Agent 串起 GitHub 与 Slack

示例应用位于 examples/usecases/mcp_github_to_slack_agent,它创建的 MCP Agent 会持续监控指定 GitHub 仓库的 Pull Request,并使用 LLM 分析 PR 信息、按重要性排序,最终把一份专业摘要提交到 Slack 频道。整个应用只依赖两个 MCP Server:一个提供 GitHub 只读能力的云端 MCP Server,以及一个运行在本地 stdio 的 Slack MCP Server。

从 README 描述的整体工作流程来看,一次完整运行包含五个环节:

  1. 应用同时通过 GitHub 与 Slack 各自的 MCP Server 建立连接;
  2. Agent 从指定仓库拉取最近 10 个 Pull Request;
  3. Agent 依据重要性因子对每个 PR 进行分析与排序:
    • 标题或描述中被标记为 high priority / urgent 的 PR;
    • 涉及安全漏洞修复的 PR;
    • 修复关键 bug 的 PR;
    • 阻塞其他工作的 PR;
    • 长期未关闭(open 很久)的 PR;
  4. Agent 将高优先级项格式化为专业的摘要文本;
  5. 摘要被投递到指定的 Slack 频道。

这里的"重要性排序"并不是写死的规则引擎,而是交给 LLM 在指令(instruction)和提示词(prompt)约束下自主判断的,体现了mcp-agent框架"以 Agent 为核心、以 MCP 为工具"的编程范式。

环境准备与前置条件

在动手前,需要确认以下前置条件(来自 README):

  • Python 3.10 或更高版本;
  • mcp-agent框架(requirements.txt中声明mcp-agent>=0.0.14,另需anthropic>=0.48.0instructor[anthropic]>=1.7.2,见 requirements.txt);
  • GitHub Copilot 访问权限(用于云端的 GitHub MCP Server,通过 GitHub API 获取 PR 数据);
  • Slack MCP Server(对应 npm 包slack-mcp-server@latest,需要 Node.js 与 npm 环境);
  • 一个可访问的 GitHub 仓库;
  • 一个可访问的 Slack 工作区。

依赖统一通过uv管理。在示例目录下执行:

uv sync --dev

随后创建一个mcp_agent.secrets.yaml密钥文件,并把 API Key 与 Token 写入其中(详见下文"密钥配置"一节)。

获取 Slack Bot Token 与 Team ID

Slack 侧需要两个关键值:Bot User OAuth Token 与 Team ID。获取步骤如下:

  1. 打开 Slack API 的应用管理页面(Slack API apps),创建一个New App
  2. 选择Create from scratch(从零创建);
  3. 进入应用视图后,在左侧导航中找到OAuth & Permissions
  4. 复制Bot User OAuth Token
  5. (可选)在 OAuth & Permissions 中为 Bot Token Scopes 追加chat:writeusers:readim:historychat:write.public等权限范围;
  6. 获取Team ID:用浏览器登录你的工作区,从地址栏 URL 中截取,形如https://app.slack.com/client/TEAM_ID,其中TEAM_ID就是所需值;
  7. OAuth TokenTeam ID写入mcp_agent.secrets.yaml
  8. (可选)确保已启动并把 Slack 机器人安装到工作区,同时把新机器人邀请进目标频道,否则它无法向该频道发消息。

配置双 MCP Server:GitHub 与 Slack

框架的服务器配置集中在mcp_agent.config.yaml。示例的完整配置如下(见 mcp_agent.config.yaml):

execution_engine: asyncio logger: transports: [console, file] level: info show_progress: true path: "logs/github-to-slack.jsonl" path_settings: path_pattern: "logs/github-to-slack-{unique_id}.jsonl" unique_id: "timestamp" timestamp_format: "%Y%m%d_%H%M%S" mcp: servers: github: transport: "streamable_http" url: "https://api.githubcopilot.com/mcp/x/pull_requests/readonly" headers: Content-Type: "application/json" http_timeout_seconds: 30 read_timeout_seconds: 60 description: "Access GitHub API operations" allowed_tools: - "list_pull_requests" - "get_pull_request" slack: command: "npx" args: ["-y", "slack-mcp-server@latest", "--transport", "stdio"] env: SLACK_TEAM_ID: "T0123213213" SLACK_MCP_ADD_MESSAGE_TOOL: "true" description: "Access Slack API operations" allowed_tools: - "conversations_add_message"

GitHub Server(streamable_http 远程连接)

  • transport: "streamable_http"url:以流式 HTTP 方式连接 GitHub Copilot 提供的只读 PR MCP 端点,连接鉴权依赖Authorization请求头,Token 通过 secrets 文件注入(详见下一节);
  • http_timeout_seconds: 30read_timeout_seconds: 60:分别控制 HTTP 连接建立与数据读取的超时时间;
  • allowed_tools:白名单机制,只暴露list_pull_requestsget_pull_request两个工具给 Agent,避免 LLM 拿到不必要的操作面,这也是mcp-agent控制工具面(tool surface)的推荐做法。

Slack Server(本地 stdio 进程)

  • command: "npx"+args:以子进程方式启动 npm 包slack-mcp-server@latest--transport stdio表示通过标准输入输出与 MCP 客户端通信;
  • env.SLACK_TEAM_ID:示例中为占位值,实际应替换为你获取到的 Team ID;SLACK_MCP_ADD_MESSAGE_TOOL: "true"用于开启发消息工具;
  • allowed_tools:仅暴露conversations_add_message,确保 Agent 只能发消息,不能做越权操作。

密钥配置:secrets 文件与 Token 注入

敏感信息不写入主配置文件,而是放在mcp_agent.secrets.yaml。模板见 mcp_agent.secrets.yaml.example:

$schema: ../../../schema/mcp-agent.config.schema.json mcp: servers: # Slack configuration # Create a Slack App Oauth Token and get your Team ID # https://api.slack.com/apps slack: env: SLACK_MCP_XOXP_TOKEN: "xoxp-oauth-token" # GitHub configuration # Create a GitHub Personal Access Token with repo scope # https://github.com/settings/tokens github: headers: Authorization: "Bearer ghp_xxxxxxxxxxx" anthropic: api_key: your-anthropic-api-key

配置要点:

  • SlackSLACK_MCP_XOXP_TOKEN存放第一步拿到的 Bot User OAuth Token(xoxp-...),框架会在启动 Slack MCP Server 子进程时注入到其环境变量;
  • GitHub:在github服务器下通过headers.Authorization注入Bearer <PAT>,其中 PAT 是 GitHub Personal Access Token(需要reposcope),该头会附加到对 GitHub 远程 MCP Server 的每个 HTTP 请求上;
  • Anthropicanthropic.api_key提供驱动 Agent 决策的 LLM 密钥。示例中 LLM 显式选用 Anthropic(见下文的AnthropicAugmentedLLM),因此必须配置对应 Key。

从配置分层可以清楚看到mcp-agent的设计哲学:mcp_agent.config.yaml只描述"连接哪些服务器、开放哪些工具",mcp_agent.secrets.yaml专门承载 Token/Key,两类文件按服务器名与键路径合并生效。部署到云端时,MCP Agent Cloud 还会提供托管密钥的能力,本地明文 Token 不必进入线上代码包。

源码拆解:Agent 如何完成跨工具编排

核心实现位于 main.py,整个程序只有约 100 行,却完整覆盖了"应用初始化 → 服务器连接 → Agent 定义 → LLM 挂载 → 提示词执行 → 资源清理"的全部环节。

1. 创建应用并声明一个异步工具

from mcp_agent.app import MCPApp from mcp_agent.agents.agent import Agent from mcp_agent.mcp.mcp_connection_manager import MCPConnectionManager from mcp_agent.workflows.llm.augmented_llm_anthropic import AnthropicAugmentedLLM from rich import print app = MCPApp(name="github_to_slack") @app.async_tool( name="github_to_slack", description="Tool to list GitHub pull requests and provides summaries to Slack", ) async def github_to_slack(github_owner: str, github_repo: str, slack_channel: str): ...
  • MCPApp(name="github_to_slack")是应用实例,负责管理全局上下文、服务器注册表、日志与生命周期。配置默认从mcp_agent.config.yaml加载(见 app.py);
  • @app.async_tool(...)装饰器把函数声明为一个异步 MCP 工具。从框架源码看,async_tool会基于被装饰函数动态生成一个 Workflow 类,并在 MCP Server 创建后注册该工具,同时提供对应的 run/get_status 端点(见 app.py)。这正是云端部署后能以"工具"形式被任意 MCP 客户端调用的底层机制;
  • 函数签名github_to_slack(github_owner, github_repo, slack_channel)中的三个参数会被自动转换为工具的 JSON Schema 入参,本地运行通过命令行--owner/--repo/--channel传入(见文件末尾的parse_args())。

2. 建立服务器连接并定义 Agent

async with app.run() as agent_app: context = agent_app.context async with MCPConnectionManager(context.server_registry): github_to_slack_agent = Agent( name="github_to_slack_agent", instruction=f"""You are an agent that monitors GitHub pull requests and provides summaries to Slack. Your tasks are: 1. Use the GitHub server to retrieve information about the last 10 pull requests for the repository {github_owner}/{github_repo} 2. Analyze and prioritize the pull requests based on their importance, urgency, and impact 3. Format a concise summary of high-priority items 4. Submit this summary to the Slack server in the channel {slack_channel} For prioritization, consider: - PRs marked as high priority or urgent - PRs that address security vulnerabilities - PRs that fix critical bugs - PRs that are blocking other work - PRs that have been open for a long time Your Slack summary should be professional, concise, and highlight the most important information.""", server_names=["github", "slack"], )
  • async with app.run()以上下文管理器方式完成应用初始化与清理;
  • MCPConnectionManager(context.server_registry)按配置为githubslack两个服务器建立/复用 MCP 连接;
  • Agent(...)的核心字段与 Agent 类定义一一对应:name是 Agent 标识;instruction即系统提示词,约束 Agent 的任务边界与排序标准;server_names声明该 Agent 可访问哪些 MCP 服务器,框架会把这两个服务器的工具聚合后交给 LLM 调用。

3. 挂载 LLM 并执行提示词工作流

try: llm = await github_to_slack_agent.attach_llm(AnthropicAugmentedLLM) prompt = f"""Complete the following workflow: 1. Retrieve the last 10 pull requests from the GitHub repository {github_owner}/{github_repo}. Use the GitHub server to get this information. Gather details such as PR title, author, creation date, status, and description. 2. Analyze the pull requests you've retrieved and prioritize them. Identify high-priority items based on: - PRs marked as high priority or urgent in their title or description - PRs that address security vulnerabilities - PRs that fix critical bugs - PRs that are blocking other work - PRs that have been open for a long time Create a list of high-priority PRs with brief explanations of why they are prioritized. 3. Format a professional and concise summary of the high-priority pull requests to share on Slack. The summary should: - Start with a brief overview of what's included - List each high-priority PR with its key details - Include links to the PRs - End with any relevant action items or recommendations 4. Use the Slack server to post this summary to the channel {slack_channel}. If you do not have Slack tool access, just return the final summary. """ # Execute the workflow print("Executing GitHub to Slack workflow...") result = await llm.generate_str(prompt) print("Workflow completed successfully!") print(result) return result finally: # Clean up the agent await github_to_slack_agent.close()
  • attach_llm(AnthropicAugmentedLLM)把增强型 LLM 挂到 Agent 上,之后 LLM 即可调用聚合后的 GitHub/Slack 工具;
  • generate_str(prompt)是带工具循环(tool-calling loop)的生成方法:LLM 先调用 GitHub 工具取 PR,再按提示词排序并组织摘要,最后调用 Slack 工具发消息,一次调用完成整条跨系统链路;
  • 提示词中对排序维度做了双保险:instruction负责稳定行为,运行时prompt再次细化"取什么字段、摘要包含什么、如何收尾",这种"系统指令 + 运行时提示"的分层设计值得复用;
  • finally中的agent.close()确保 Agent 及其连接被及时释放,避免资源泄漏。

4. 入口与参数解析

if __name__ == "__main__": args = parse_args() start = time.time() try: asyncio.run(github_to_slack(args.owner, args.repo, args.channel)) except KeyboardInterrupt: print("\nReceived keyboard interrupt, shutting down gracefully...") except Exception as e: print(f"Error during execution: {e}") raise finally: end = time.time() print(f"Total run time: {end - start:.2f}s")

parse_args()定义三个必填参数:--owner(仓库所有者)、--repo(仓库名)、--channel(Slack 频道),并通过asyncio.run驱动整个异步链路;程序同时捕获KeyboardInterrupt实现优雅退出,并打印总耗时便于观察 LLM 工具调用的开销。

本地运行

在示例目录下准备好依赖、配置与密钥后,用一条命令运行:

uv run main.py --owner <github-owner> --repo <repository-name> --channel <slack-channel>

运行期间控制台会打印Executing GitHub to Slack workflow...与最终生成的摘要文本(对应generate_str的返回值)。日志默认同时输出到控制台与文件logs/github-to-slack.jsonl,文件名按时间戳生成(path_pattern中的{unique_id}timestamp_format控制)。如果 Agent 未获得 Slack 工具访问权限,提示词第 4 步设计了兜底逻辑:直接返回摘要文本而不发消息,保证流程不因工具缺失而中断。

(Beta)部署到云端并通过 MCP 客户端调用

示例还演示了将 Agent 部署到 MCP Agent Cloud(详见 云端概述)的三步流程。

步骤 a:登录云端

uv run mcp-agent login

部署过程中可以选择密钥管理方式(例如由云端托管mcp_agent.secrets.yaml中的敏感值)。

步骤 b:一条命令部署

uv run mcp-agent deploy my-first-agent

步骤 c:通过任意 MCP 客户端连接已部署的 Agent

Claude Desktop 集成:在~/.claude-desktop/config.json中注册你的 Agent 服务器:

"my-agent-server": { "command": "/path/to/npx", "args": [ "mcp-remote", "https://[your-agent-server-id].deployments.mcp-agent.com/sse", "--header", "Authorization: Bearer ${BEARER_TOKEN}" ], "env": { "BEARER_TOKEN": "your-mcp-agent-cloud-api-token" } }

MCP Inspector 调试:用官方检查器探索并测试你的 Agent 服务器:

npx @modelcontextprotocol/inspector

按以下设置填写连接信息:

SettingValue
Transport TypeSSE
SSEhttps://[your-agent-server-id].deployments.mcp-agent.com/sse
Header NameAuthorization
Bearer Tokenyour-mcp-agent-cloud-api-token

提示:在 Configuration 中把请求超时调长一些。Agent 内部有 LLM 调用,耗时天然高于普通 API 请求。

触发云端运行:连接成功后,工具列表中会出现两类工具:

  • MCP Agent Cloud 默认工具:
    • workflow-list:列出工作流(一般用不到);
    • workflow-run-list:列出 Agent 的执行记录;
    • workflow-run:创建工作流运行(一般用不到);
    • workflows-get_status:查询 Agent 运行状态;
    • workflows-resume:向暂停的工作流发送信号继续执行;
    • workflows-cancel:发送信号取消工作流;
  • Agent 自身暴露的工具:
    • github_to_slack:即@app.async_tool注册的工具名,填入参数即可触发一次工作流运行。

成功触发后,会返回一个包含运行元数据的workflow_run对象,从中可取得 run id 用于后续状态查询:

{ "workflow_id": "github_to_slack-uuid", "run_id": "uuid", "execution_id": "uuid" }

若触发报错,可跟踪云端日志排查:

uv run mcp-agent cloud logger tail "app_id" -f

当运行成功结束后,Slack 频道中会收到 Agent 发布的摘要消息;同时通过workflows-get_status可以读到 Agent 的文本响应,例如:

{ "result": { "id": "run-uuid", "name": "github_to_slack", "status": "completed", "running": false, "state": { "status": "completed", "metadata": {}, "updated_at": 1757705891.842188, "error": null }, "result": "{'kind': 'workflow_result', 'value': \"I'll help you complete this workflow. Let me start by retrieving the last 10 pull requests from the GitHub repository lastmile-.......", "completed": true, "error": null, "temporal": { "id": "github_to_slack-uuid", "workflow_id": "github_to_slack-uuid", "run_id": "uuid", "status": "xxxxx", "error": "xxxxx" } } }

从返回结构可以看到云端运行基于 Temporal 工作流引擎(temporal字段携带workflow_idrun_id与状态),result.value中保存的是 Agent 的最终文本响应。

小结与扩展方向

本示例展示了mcp-agent最具代表性的用法:一个 Agent 同时挂载多个 MCP Server,用 LLM 完成跨系统的"取数 → 分析 → 决策 → 执行"闭环。可复用的要点包括:

  • allowed_tools白名单收紧工具面,降低 LLM 误操作风险;
  • 把"行为约束"放instruction、把"任务细节"放运行时prompt
  • @app.async_tool把整套流程封装成可被远程调用的 MCP 工具,本地asyncio.run与云端工作流引擎共用同一入口;
  • 密钥与配置分离,本地与云端均能安全注入 Token。

若需进一步扩展,可参考仓库中的其他实战案例(如 mcp_financial_analyzer、mcp_marketing_assistant_agent)以及执行引擎与工作流相关文档,把同样的模式推广到更多业务场景。

【免费下载链接】mcp-agentBuild effective agents using Model Context Protocol and simple workflow patterns项目地址: https://gitcode.com/GitHub_Trending/mc/mcp-agent

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

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

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

立即咨询