5.2 MCP 协议与工具集成


文档摘要

5.2 MCP 协议与工具集成 — 连接 Agent 与外部系统的标准桥梁 本节导读:掌握 MCP(Model Context Protocol)协议的设计原理与实战应用,学会创建自定义 MCP 连接器,让你的循环能触达 GitHub、数据库、Slack 等外部系统。 学习目标 理解 MCP 协议的核心架构与设计理念 掌握常用 MCP 连接器的配置与使用 学会创建自定义 MCP Server 理解 Connectors 与 Skills 的协作关系 核心概念 MCP(Model Context Protocol)是连接 AI Agent 与外部工具的标准协议。在循环工程的六大原语中,Connectors 是让循环"能触达真实世界"的关键。

5.2 MCP 协议与工具集成 — 连接 Agent 与外部系统的标准桥梁

本节导读:掌握 MCP(Model Context Protocol)协议的设计原理与实战应用,学会创建自定义 MCP 连接器,让你的循环能触达 GitHub、数据库、Slack 等外部系统。

学习目标

  • 理解 MCP 协议的核心架构与设计理念
  • 掌握常用 MCP 连接器的配置与使用
  • 学会创建自定义 MCP Server
  • 理解 Connectors 与 Skills 的协作关系

核心概念

MCP(Model Context Protocol)是连接 AI Agent 与外部工具的标准协议。在循环工程的六大原语中,Connectors 是让循环"能触达真实世界"的关键。Osmani 说:"A loop that can only see the filesystem is a tiny loop."(一个只能看到文件系统的循环只是一个小循环。)

MCP 的三层架构

组件 职责
传输层 JSON-RPC 2.0 over stdio/HTTP 消息传输
能力层 Tools, Resources, Prompts 功能定义
应用层 具体 MCP Server 业务逻辑

环境准备 / 前置知识

  • 已完成 5.1 节学习
  • 了解 REST API 基本概念
  • 有 Claude Code 或 Codex 使用经验
  • Node.js 或 Python 基础

分步实战

步骤 1:配置常用 MCP 连接器

// Claude Code 的 MCP 配置 (.claude/settings.json) { "mcpServers": { "github": { "command": "npx", "args": ["-y", "@anthropic/mcp-server-github"], "env": { "GITHUB_TOKEN": "ghp_xxxxx" } }, "linear": { "command": "npx", "args": ["-y", "@anthropic/mcp-server-linear"], "env": { "LINEAR_API_KEY": "lin_xxxxx" } }, "postgres": { "command": "npx", "args": ["-y", "@anthropic/mcp-server-postgres", "postgresql://..."] } } }

步骤 2:创建自定义 MCP Server

""" custom_mcp_server.py - 自定义 MCP Server 示例 使用 Python MCP SDK 实现一个简单的知识库连接器 """ from mcp.server import Server from mcp.server.stdio import stdio_server import json app = Server("knowledge-base") @app.list_tools() async def list_tools(): return [ { "name": "search_knowledge", "description": "搜索知识库中的文档", "inputSchema": { "type": "object", "properties": { "query": {"type": "string", "description": "搜索关键词"}, "limit": {"type": "number", "default": 5} }, "required": ["query"] } }, { "name": "get_document", "description": "获取指定文档内容", "inputSchema": { "type": "object", "properties": { "doc_id": {"type": "string"} }, "required": ["doc_id"] } } ] @app.call_tool() async def call_tool(name, arguments): if name == "search_knowledge": query = arguments["query"] limit = arguments.get("limit", 5) # 实际中查询数据库或搜索引擎 results = [ {"id": "doc-001", "title": f"关于 {query} 的文档", "relevance": 0.95} ] return results elif name == "get_document": doc_id = arguments["doc_id"] content = f"文档 {doc_id} 的内容..." return {"content": content} async def main(): async with stdio_server() as (read_stream, write_stream): await app.run(read_stream, write_stream) if __name__ == "__main__": import asyncio asyncio.run(main())

步骤 3:在循环中集成 MCP 连接器

""" mcp_integrated_loop.py - 集成 MCP 的循环示例 展示循环如何通过 Connectors 触达外部系统 """ class MCPIntegratedLoop: """ 集成 MCP 的 Issue 修复循环 Agent 通过 MCP 连接器:读取 Issue → 修复代码 → 创建 PR → 更新状态 """ def run(self, issue_id: str): # Discover: 通过 MCP 读取 Issue 详情 issue = self.mcp_call("github", "get_issue", {"number": issue_id}) print(f"📋 Issue: {issue['title']}") # Plan: 通过 MCP 查询相关代码 files = self.mcp_call("github", "search_code", {"q": issue["title"]}) print(f"📂 相关文件: {files[:5]}") # Execute: 在 worktree 中修复 self.create_worktree(f"fix-{issue_id}") fix_result = self.agent_fix(issue, files) # Verify: 运行测试 test_passed = self.run_tests() if test_passed: # 通过 MCP 创建 PR pr = self.mcp_call("github", "create_pr", { "title": f"Fix #{issue_id}: {issue['title']}", "body": f"自动修复 Issue #{issue_id}" }) # 通过 MCP 更新 Issue 状态 self.mcp_call("github", "update_issue", { "number": issue_id, "state": "closed" }) # 通过 MCP 通知 Slack self.mcp_call("slack", "send_message", { "channel": "#dev", "text": f"PR 已创建: {pr['url']}" }) print(f"✅ 完整闭环: Issue #{issue_id} → PR → Slack 通知") def mcp_call(self, server: str, tool: str, args: dict): """调用 MCP Server 的工具""" # 实际中通过 JSON-RPC 调用 return {"result": "ok"}

常见问题 FAQ

Q1:MCP 和普通 API 调用有什么区别?

A:MCP 是标准化的 API 抽象层。普通 API 调用需要你写具体的 HTTP 请求,不同服务的 API 格式不同。MCP 用统一的 JSON-RPC 协议和标准的 Tool/Resource/Prompt 三大能力模型,Agent 不需要知道底层 API 的细节——MCP Server 负责转换。更关键的是,MCP 连接器在 Claude Code 和 Codex 之间可以通用。

Q2:MCP 连接器的安全风险怎么控制?

A:三层安全控制:(1) MCP Server 级别的权限控制——每个 Server 只暴露必要的工具;(2) Agent 级别的工具白名单——限制 Agent 可以调用哪些 MCP 工具;(3) 审计日志——记录所有 MCP 调用的输入和输出。TrueFoundry 的 Agent Gateway 提供了企业级的 MCP 治理能力。

Q3:如何调试 MCP 连接器?

A:Claude Code 支持 MCP 调试模式。使用 claude --mcp-debug 启动,可以看到所有 MCP 调用的详细信息。MCP SDK 也提供了日志功能。常见问题包括:权限配置错误、环境变量缺失、Server 启动失败。

最佳实践与避坑

  • 从官方连接器开始:GitHub、Linear、PostgreSQL 等有官方 MCP Server
  • 最小权限原则:每个 MCP Server 只授予必要的 API 权限
  • 缓存高频调用:避免重复查询同一个 API
  • 超时保护:所有 MCP 调用设置合理的超时时间
  • 错误处理:MCP Server 不可用时循环应该优雅降级

本节小结

本节深入介绍了 MCP 协议的架构和实战应用。MCP 是循环工程中 Connectors 的标准协议,让循环能触达 GitHub、数据库、Slack 等外部系统。我们学习了配置常用连接器、创建自定义 MCP Server、以及在循环中集成 MCP 的完整方法。

下一节我们将学习 Skills 技能系统的设计。

延伸阅读

关键词:Loop Engineering, MCP, Model Context Protocol, 工具集成, Connectors, MCP Server, Claude Code, 教程, 实战


发布者: 作者: 转发
评论区 (0)
U