
使用 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 描述的整体工作流程来看一次完整运行包含五个环节应用同时通过 GitHub 与 Slack 各自的 MCP Server 建立连接Agent 从指定仓库拉取最近 10 个 Pull RequestAgent 依据重要性因子对每个 PR 进行分析与排序标题或描述中被标记为 high priority / urgent 的 PR涉及安全漏洞修复的 PR修复关键 bug 的 PR阻塞其他工作的 PR长期未关闭open 很久的 PRAgent 将高优先级项格式化为专业的摘要文本摘要被投递到指定的 Slack 频道。这里的重要性排序并不是写死的规则引擎而是交给 LLM 在指令instruction和提示词prompt约束下自主判断的体现了mcp-agent框架以 Agent 为核心、以 MCP 为工具的编程范式。环境准备与前置条件在动手前需要确认以下前置条件来自 READMEPython 3.10 或更高版本mcp-agent框架requirements.txt中声明mcp-agent0.0.14另需anthropic0.48.0与instructor[anthropic]1.7.2见 requirements.txtGitHub Copilot 访问权限用于云端的 GitHub MCP Server通过 GitHub API 获取 PR 数据Slack MCP Server对应 npm 包slack-mcp-serverlatest需要 Node.js 与 npm 环境一个可访问的 GitHub 仓库一个可访问的 Slack 工作区。依赖统一通过uv管理。在示例目录下执行uv sync --dev随后创建一个mcp_agent.secrets.yaml密钥文件并把 API Key 与 Token 写入其中详见下文密钥配置一节。获取 Slack Bot Token 与 Team IDSlack 侧需要两个关键值Bot User OAuth Token 与 Team ID。获取步骤如下打开 Slack API 的应用管理页面Slack API apps创建一个New App选择Create from scratch从零创建进入应用视图后在左侧导航中找到OAuth Permissions复制Bot User OAuth Token可选在 OAuth Permissions 中为 Bot Token Scopes 追加chat:write、users:read、im:history、chat:write.public等权限范围获取Team ID用浏览器登录你的工作区从地址栏 URL 中截取形如https://app.slack.com/client/TEAM_ID其中TEAM_ID就是所需值将OAuth Token与Team ID写入mcp_agent.secrets.yaml可选确保已启动并把 Slack 机器人安装到工作区同时把新机器人邀请进目标频道否则它无法向该频道发消息。配置双 MCP ServerGitHub 与 Slack框架的服务器配置集中在mcp_agent.config.yaml。示例的完整配置如下见 mcp_agent.config.yamlexecution_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-serverlatest, --transport, stdio] env: SLACK_TEAM_ID: T0123213213 SLACK_MCP_ADD_MESSAGE_TOOL: true description: Access Slack API operations allowed_tools: - conversations_add_messageGitHub Serverstreamable_http 远程连接transport: streamable_http与url以流式 HTTP 方式连接 GitHub Copilot 提供的只读 PR MCP 端点连接鉴权依赖Authorization请求头Token 通过 secrets 文件注入详见下一节http_timeout_seconds: 30与read_timeout_seconds: 60分别控制 HTTP 连接建立与数据读取的超时时间allowed_tools白名单机制只暴露list_pull_requests与get_pull_request两个工具给 Agent避免 LLM 拿到不必要的操作面这也是mcp-agent控制工具面tool surface的推荐做法。Slack Server本地 stdio 进程command: npxargs以子进程方式启动 npm 包slack-mcp-serverlatest--transport stdio表示通过标准输入输出与 MCP 客户端通信env.SLACK_TEAM_ID示例中为占位值实际应替换为你获取到的 Team IDSLACK_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 Tokenxoxp-...框架会在启动 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(namegithub_to_slack) app.async_tool( namegithub_to_slack, descriptionTool 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(namegithub_to_slack)是应用实例负责管理全局上下文、服务器注册表、日志与生命周期。配置默认从mcp_agent.config.yaml加载见 app.pyapp.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. 建立服务器连接并定义 Agentasync with app.run() as agent_app: context agent_app.context async with MCPConnectionManager(context.server_registry): github_to_slack_agent Agent( namegithub_to_slack_agent, instructionfYou 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)按配置为github、slack两个服务器建立/复用 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 fComplete 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 youve 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 whats 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(fError during execution: {e}) raise finally: end time.time() print(fTotal run time: {end - start:.2f}s)parse_args()定义三个必填参数--owner仓库所有者、--repo仓库名、--channelSlack 频道并通过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 客户端连接已部署的 AgentClaude 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按以下设置填写连接信息SettingValueTransport TypeSSESSEhttps://[your-agent-server-id].deployments.mcp-agent.com/sseHeader NameAuthorizationBearer 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: \Ill 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_id、run_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),仅供参考