基于 mcp-agent 构建 Slack MCP Agent:从本地读写到云端部署的完整实战
基于 mcp-agent 构建 Slack MCP Agent从本地读写到云端部署的完整实战【免费下载链接】mcp-agentBuild effective agents using Model Context Protocol and simple workflow patterns项目地址: https://gitcode.com/GitHub_Trending/mc/mcp-agent本篇技术指南围绕开源仓库 mcp-agent 中的 Slack Agent 示例examples/usecases/mcp_basic_slack_agent展开讲解如何通过 Model Context ProtocolMCP将 Slack 官方 MCP Server 与 Filesystem MCP Server 组合进同一个 Agent实现读取 Slack 消息 读写本地文件系统的复合能力。读完本文你将掌握 Slack Bot Token/Team ID 的申请与配置、mcp_agent.config.yaml与mcp_agent.secrets.yaml的完整填写方法、本地运行与源码级调用链分析以及通过mcp-agent login/mcp-agent deploy将 Agent 部署到 MCP Agent Cloud 并通过 Claude Desktop 与 MCP Inspector 接入的完整流程。示例概述一个Slack 文件系统的双 MCP Server Agent本示例演示了一个名为slack_finder的 Agent它同时拥有两个 MCP Server 的访问权slack官方 modelcontextprotocol/servers 中的 Slack MCP Server负责读取与写入 Slack 会话读历史消息、发消息等。filesystem官方modelcontextprotocol/server-filesystem负责本地文件系统的读写。二者的组合使 Agent 可以完成复合操作例如把 Slack 消息写入磁盘文件或读取磁盘文件并通过 Slack 发送出去。官方文档中的架构示意如下┌──────────────┐ ┌──────────────┐ │ Slack Finder │──┬──▶│ Slack │ │ Agent │ │ │ MCP Server │ └──────────────┘ │ └──────────────┘ │ ┌──────────────┐ └──▶│ Filesystem │ │ MCP Server │ └──────────────┘从源码结构看这个一对多的组合正是 mcp-agent 的核心抽象一个Agentsrc/mcp_agent/agents/agent.py通过server_names: List[str]声明可访问的 MCP Server 列表框架负责连接管理、工具聚合与命名空间隔离。示例入口文件 examples/usecases/mcp_basic_slack_agent/main.py 中创建 Agent 的代码与此一一对应slack_agent Agent( nameslack_finder, instructionYou are an agent with access to the filesystem, as well as the ability to look up Slack conversations. Your job is to identify the closest match to a users request, make the appropriate tool calls, and return the results., server_names[filesystem, slack], )其中instruction定义了 Agent 的职责边界server_names决定其能调用的工具集。该字段对应源码中 Agent.server_names 的定义List[str]即 MCP 服务器名称列表名称必须与配置文件mcp.servers下的键一致。第一步环境准备与依赖安装克隆仓库并进入示例目录git clone https://github.com/lastmile-ai/mcp-agent.git cd mcp-agent/examples/usecases/mcp_basic_slack_agent安装 uv 并同步依赖示例项目使用uv管理 Python 环境。若本机尚未安装 uv先通过 pip 安装pip install uv然后同步mcp-agent项目依赖并安装本示例特有的依赖uv sync uv pip install -r requirements.txt其中 examples/usecases/mcp_basic_slack_agent/requirements.txt 内容如下# Core framework dependency mcp-agent file://../../../ # Link to the local mcp-agent project root # Additional dependencies specific to this example anthropic openai可以看到它通过file://../../../直接链接到仓库根目录的 mcp-agent 本体并额外安装了anthropic与openai两个 LLM 提供方 SDK——这正是后文OpenAIAugmentedLLM与 Anthropic/OpenAI API Key 配置的依赖基础。第二步申请 Slack Bot Token 与 Team ID要让 Slack MCP Server 能够访问你的工作区需要先创建 Slack App 并获取两个凭证打开 Slack API apps点击Create New App选择Create from scratch方式创建在应用视图左侧导航进入OAuth Permissions复制页面上的Bot User OAuth Token形如xoxb-...可选在 OAuth Permissions 页面为 Bot Token Scopes 添加chat:write、users:read、im:history、chat:write.public等权限以支持写消息、读用户信息、读取 IM 历史等操作Team ID获取方式在浏览器中登录你的工作区从地址栏 URLhttps://app.slack.com/client/TEAM_ID中提取例如T01234567将OAuth Token与Team ID填入mcp_agent.secrets.yaml下一步可选确保已将 Slack Bot 安装Install到你的工作区并把 Bot 邀请到希望交互的频道中。提示Slack MCP Server 通过环境变量SLACK_BOT_TOKEN与SLACK_TEAM_ID完成鉴权。这两个值属于敏感信息官方强烈建议不要直接写入配置文件而是放入独立的 secrets 文件。第三步配置 secrets 与 MCP Server 环境变量复制示例提供的 secrets 模板cp mcp_agent.secrets.yaml.example mcp_agent.secrets.yaml打开 examples/usecases/mcp_basic_slack_agent/mcp_agent.secrets.yaml.example按实际值填写LLM 提供方的 API Key以及 Slack MCP Server 的token/team id。完整示例配置如下$schema: ../../../schema/mcp-agent.config.schema.json openai: api_key: openai_api_key anthropic: api_key: anthropic_api_key mcp: servers: slack: env: SLACK_BOT_TOKEN: xoxb-your-bot-token SLACK_TEAM_ID: T01234567其中mcp.servers.slack.env会在启动 Slack MCP Server 进程时注入为环境变量。与之配套examples/usecases/mcp_basic_slack_agent/mcp_agent.config.yaml 中声明了三个 MCP Server$schema: ../../../schema/mcp-agent.config.schema.json mcp: servers: slack: command: npx args: [-y, modelcontextprotocol/server-slack] # consider defining sensitive values in a separate mcp_agent.secrets.yaml file # env: # SLACK_BOT_TOKEN: xoxb-your-bot-token # SLACK_TEAM_ID: T01234567 fetch: command: uvx args: [mcp-server-fetch] filesystem: command: npx args: [-y, modelcontextprotocol/server-filesystem] openai: # Secrets (API keys, etc.) are stored in an mcp_agent.secrets.yaml file which can be gitignored default_model: gpt-4o这里有三点值得说明配置文件与 secrets 文件分离mcp_agent.config.yaml只声明服务器启动方式commandargs与非敏感参数SLACK_BOT_TOKEN/SLACK_TEAM_ID这类敏感值放在mcp_agent.secrets.yaml中便于加入.gitignore。secrets 文件中的mcp.servers.slack.env会与配置文件中的环境变量合并生效。默认模型openai.default_model: gpt-4o定义了 LLM 默认模型secrets 中提供openai.api_key后即可直接使用 OpenAI 后端。filesystem服务器的根目录配置文件中未显式传参而是在 main.py 运行时动态追加context.config.mcp.servers[filesystem].args.extend([os.getcwd()])即把当前工作目录作为文件系统根路径注入给 filesystem MCP Server。第四步本地运行在示例目录下直接运行uv run main.py下面结合 main.py 逐段拆解运行时发生了什么这也是一条完整的 mcp-agent 应用调用链import asyncio import os from mcp_agent.app import MCPApp from mcp_agent.agents.agent import Agent from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM app MCPApp(namemcp_basic_agent) app.tool async def fetch_latest_slack_message() - str: Get the latest message from general channel and provide a summary. async with app.run() as agent_app: logger agent_app.logger context agent_app.context slack_agent Agent( nameslack_finder, instructionYou are an agent with access to the filesystem, as well as the ability to look up Slack conversations. Your job is to identify the closest match to a users request, make the appropriate tool calls, and return the results., server_names[filesystem, slack], ) context.config.mcp.servers[filesystem].args.extend([os.getcwd()]) async with slack_agent: logger.info(slack: Connected to server, calling list_tools...) result await slack_agent.list_tools() logger.info(Tools available:, dataresult.model_dump()) llm await slack_agent.attach_llm(OpenAIAugmentedLLM) result await llm.generate_str( messageWhat was the latest message in the bot-commits channel?, ) logger.info(fResult: {result}) # Multi-turn conversations summary await llm.generate_str( messageCan you summarize what that commit was about?, ) logger.info(fResult: {summary}) final_result fLatest message: {result}\n\nSummary: {summary} return final_result if __name__ __main__: import time start time.time() asyncio.run(fetch_latest_slack_message()) end time.time() t end - start print(fTotal run time: {t:.2f}s)调用链剖析app.tool声明 MCP 工具fetch_latest_slack_message通过MCPApp.tool装饰器src/mcp_agent/app.py被声明为一个 MCP 工具。从源码注释与实现看该装饰器会把函数转换为 JSON Schema 可描述的工具validate_tool_schema前置校验并自动注册同名异步 Workflow从而暴露run/get_status端点——这正是后续云端部署后该工具可被外部 MCP 客户端调用的基础。async with app.run()启动应用MCPApp.run()src/mcp_agent/app.py是异步上下文管理器进入时调用initialize()初始化配置与上下文退出时执行cleanup()释放连接期间可通过agent_app.logger与agent_app.context获取日志与运行上下文。创建 Agent 并进入上下文async with slack_agent会按需初始化filesystem与slack两个 MCP Server 的连接支持连接持久化见 Agent.connection_persistence。list_tools()探测工具集await slack_agent.list_tools()src/mcp_agent/agents/agent.py返回ListToolsResult可传入server_name指定某个服务器或用tool_filter做工具级过滤示例中直接model_dump()打日志便于排查服务器是否连接成功。attach_llm(OpenAIAugmentedLLM)绑定 LLMOpenAIAugmentedLLM 是 mcp-agent 中基于 OpenAI ChatCompletion 的增强型 LLM 实现将LLM MCP 工具 检索/记忆整合为智能体核心组件。attach_llmsrc/mcp_agent/agents/agent.py将 LLM 实例绑定到 Agent并把instruction注入 LLM 的系统提示。多轮对话llm.generate_str连续发起两轮请求——先问bot-commits 频道最新消息是什么再基于上一轮结果追问这次 commit 是关于什么的体现 AugmentedLLM 保留多轮对话上下文的能力最终把两条结果拼接为final_result返回。运行结束后程序会打印总耗时Total run time: x.xx s可用于快速验证整条链路MCP 连接、工具枚举、LLM 推理是否通畅。第五步Beta部署到 MCP Agent Cloudmcp-agent 支持将上述 Agent 一键部署到 MCP Agent Cloud使fetch_latest_slack_message成为可通过标准 MCP 协议远程调用的云端工具。前置条件确保 Agent 是云兼容的即工具函数已使用app.tool装饰器声明本示例已包含部署后该工具才会作为 MCP 工具对外暴露。Step 1登录 MCP Agent Clouduv run mcp-agent login对应 CLI 实现位于 src/mcp_agent/cli/cloud/commands/auth/login/main.py默认会自动打开浏览器跳转至 API Keys 页面完成鉴权也支持--api-key或环境变量MCP_API_KEY直接传入已有 API Key 绕过手动登录以及--no-open禁止自动打开浏览器。Step 2部署 Agentuv run mcp-agent deploy basic-slack-agent部署过程中会逐个提示配置 secrets每个 secret 都有两种类型可选OpenAI API Keyopenai.api_keySelect secret type for openai.api_key 1: Deployment Secret: The secret value will be stored securely and accessible to the deployed application runtime. 2: User Secret: No secret value will be stored. The configure command must be used to create a configured application with this secret.个人使用、希望部署后立即可用 → 选Option 1Deployment Secret公开分享给其他用户、希望每位用户自带 API Key → 选Option 2User Secret。Slack Bot Tokenmcp.servers.slack.env.SLACK_BOT_TOKENSelect secret type for mcp.servers.slack.env.SLACK_BOT_TOKEN 1: Deployment Secret: The secret value will be stored securely and accessible to the deployed application runtime. 2: User Secret: No secret value will be stored. The configure command must be used to create a configured application with this secret.仅用于你自己的 Slack 工作区、希望开箱即用 → 选Option 1公开分享、希望每个用户连接各自的工作区 → 选Option 2。两种 secret 类型的差异本质上是运行时注入与用户侧配置的区别Deployment Secret 加密存储并由部署运行时读取User Secret 不落盘存储需通过configure命令生成已配置应用后才能提供该值。Step 3连接已部署的 Agent部署成功后你会获得一个形如https://[your-agent-server-id].deployments.mcp-agent.com的部署地址可通过两种 MCP 客户端接入。Claude Desktop 集成在~/.claude-desktop/config.json中新增一个 MCP Server 条目通过mcp-remote以 SSE 方式连接并携带 Bearer Token{ mcpServers: { basic-slack-agent: { 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 } } } }其中BEARER_TOKEN指向你在 MCP Agent Cloud 的 API Tokenmcp-remote负责完成远程 MCP 到本地 stdio 的桥接。配置完成后重启 Claude Desktop即可像使用本地 MCP Server 一样调用部署后的 Agent 工具。MCP Inspector 调试启动 MCP Inspectornpx modelcontextprotocol/inspector然后按下表填写连接参数SettingValueTransport TypeSSESSE URLhttps://[your-agent-server-id].deployments.mcp-agent.com/sseHeader NameAuthorizationBearer Tokenyour-mcp-agent-cloud-api-tokenTip建议在 Configuration 中调大请求超时时间因为 LLM 调用比普通 API 调用耗时更长。部署后暴露的工具部署完成后Agent 对外暴露fetch_latest_slack_message工具其能力包括从 bot-commits 频道抓取最新消息提供基于 AI 生成的消息内容摘要同时返回原始消息与摘要对应源码中final_result fLatest message: {result}\n\nSummary: {summary}的返回结构。常见问题与注意事项Bot 收不到消息请确认已在 Slack 工作区安装Install该 App并把 Bot 邀请进目标频道users:read、im:history等权限缺失时历史读取类操作会失败。Token 与 Team ID 填错SLACK_BOT_TOKEN必须以xoxb-开头且属于该 AppSLACK_TEAM_ID从工作区 URLhttps://app.slack.com/client/TEAM_ID提取二者必须匹配同一个工作区。敏感信息泄露风险Bot Token 与 API Key 一律放入mcp_agent.secrets.yaml并加入.gitignore不要提交到mcp_agent.config.yaml或版本库中。云端部署鉴权失败检查 Bearer Token 是否与登录时使用的 API Key 一致公开分享场景User Secret下需确认用户已执行configure补齐自身 secrets。SSE 连接超时LLM 推理耗时较长接入 MCP Inspector 或 Claude Desktop 时优先调大请求超时。总结本示例完整展示了 mcp-agent 的核心能力一个 Agent 聚合多个 MCP ServerSlack Filesystem实现跨域复合操作同时借助app.tool将 Agent 能力封装为标准 MCP 工具从本地uv run main.py一键延伸到云端 SSE 部署。无论是读取 Slack 消息并落盘归档还是读取本地文件通过 Slack 发送这套模式都可以直接套用——只需调整server_names、修改instruction、并维护好配置文件与 secrets 即可。相关源码与配置可进一步参考main.py、mcp_agent.config.yaml、mcp_agent.secrets.yaml.example以及框架核心实现 src/mcp_agent/agents/agent.py 与 src/mcp_agent/app.py。【免费下载链接】mcp-agentBuild effective agents using Model Context Protocol and simple workflow patterns项目地址: https://gitcode.com/GitHub_Trending/mc/mcp-agent创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考