第 2 / 8 节20 分钟
🔌
MCP 协议
高级通过 MCP 协议扩展 AI 能力
🎬
视频教程即将上线
MCP 协议
Model Context Protocol (MCP) 是一种开放协议,让 OpenCode 能够连接各种外部工具和数据源。
# 什么是 MCP?#
MCP 允许 AI 助手安全地访问:
- 文件系统 - 读写本地文件
- 数据库 - 查询和操作数据
- API - 调用外部服务
- 开发工具 - Git、Docker、K8s 等
- 自定义工具 - 你开发的任何工具
# MCP 架构#
┌─────────────────┐
│ OpenCode │
│ (Client) │
└────────┬────────┘
│ MCP Protocol
│
┌────────▼────────┐
│ MCP Server │
│ (Tools) │
└────────┬────────┘
│
┌────────▼────────┐
│ External System │
│ (DB/API/FS...) │
└─────────────────┘
# 安装 MCP 服务器#
## 官方服务器#
bash1# 文件系统服务器 2npm install -g @modelcontextprotocol/server-filesystem 3 4# GitHub 服务器 5npm install -g @modelcontextprotocol/server-github 6 7# PostgreSQL 服务器 8npm install -g @modelcontextprotocol/server-postgres
## 社区服务器#
访问 MCP Server Registry↗ 查看更多。
# 配置 MCP#
编辑 ~/.opencode/mcp.json:
json1{ 2 "mcpServers": { 3 "filesystem": { 4 "command": "npx", 5 "args": [ 6 "-y", 7 "@modelcontextprotocol/server-filesystem", 8 "/path/to/allowed/directory" 9 ] 10 }, 11 "github": { 12 "command": "npx", 13 "args": ["-y", "@modelcontextprotocol/server-github"], 14 "env": { 15 "GITHUB_TOKEN": "ghp_xxxxx" 16 } 17 }, 18 "postgres": { 19 "command": "npx", 20 "args": ["-y", "@modelcontextprotocol/server-postgres"], 21 "env": { 22 "DATABASE_URL": "postgresql://user:pass@localhost/db" 23 } 24 } 25 } 26}
# 使用 MCP 工具#
配置完成后,OpenCode 会自动发现可用工具:
❯ /tools
Available MCP tools:
filesystem:
• read_file - Read file contents
• write_file - Write to a file
• list_directory - List directory contents
github:
• search_repositories - Search GitHub repos
• create_issue - Create a new issue
• list_pull_requests - List PRs
postgres:
• query - Execute SQL query
• list_tables - List database tables
## 示例:文件操作#
❯ 读取 /projects/myapp/README.md 的内容
Using tool: filesystem.read_file
❯ 在该目录下创建一个 TODO.md 文件
Using tool: filesystem.write_file
## 示例:GitHub 操作#
❯ 搜索 React 相关的热门仓库
Using tool: github.search_repositories
❯ 给 facebook/react 创建一个 issue
Using tool: github.create_issue
## 示例:数据库查询#
❯ 列出所有数据库表
Using tool: postgres.list_tables
❯ 查询最近 10 个用户注册记录
Using tool: postgres.query
# 权限控制#
## 只读模式#
限制工具只能读取,不能写入:
json1{ 2 "mcpServers": { 3 "filesystem": { 4 "command": "npx", 5 "args": ["-y", "@modelcontextprotocol/server-filesystem", "/data"], 6 "permissions": { 7 "read": true, 8 "write": false 9 } 10 } 11 } 12}
## 路径限制#
只允许访问特定目录:
json1{ 2 "mcpServers": { 3 "filesystem": { 4 "command": "npx", 5 "args": [ 6 "-y", 7 "@modelcontextprotocol/server-filesystem", 8 "/home/user/projects", 9 "--allowed-paths", "/home/user/data" 10 ] 11 } 12 } 13}
## 确认模式#
敏感操作需要确认:
json1{ 2 "mcpServers": { 3 "postgres": { 4 "command": "npx", 5 "args": ["-y", "@modelcontextprotocol/server-postgres"], 6 "confirmOperations": ["query", "execute"] 7 } 8 } 9}
# 调试 MCP#
## 查看服务器状态#
❯ /mcp status
MCP Servers:
✓ filesystem - Running (pid: 12345)
✓ github - Running (pid: 12346)
✗ postgres - Failed (connection refused)
## 重启服务器#
❯ /mcp restart postgres
Restarting postgres server...
✓ Server restarted successfully
## 查看日志#
❯ /mcp logs filesystem
[2024-01-15 10:30:45] Connected to client
[2024-01-15 10:30:47] read_file: /projects/myapp/README.md
[2024-01-15 10:31:02] write_file: /projects/myapp/TODO.md
# 开发自定义 MCP 服务器#
创建 my-server.js:
javascript1import { Server } from '@modelcontextprotocol/sdk/server/index.js'; 2import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; 3 4const server = new Server({ 5 name: 'my-custom-server', 6 version: '1.0.0' 7}, { 8 capabilities: { 9 tools: {} 10 } 11}); 12 13// 定义工具 14server.setRequestHandler('tools/list', async () => ({ 15 tools: [{ 16 name: 'hello', 17 description: 'Say hello to someone', 18 inputSchema: { 19 type: 'object', 20 properties: { 21 name: { type: 'string', description: 'Name to greet' } 22 }, 23 required: ['name'] 24 } 25 }] 26})); 27 28// 实现工具 29server.setRequestHandler('tools/call', async (request) => { 30 if (request.params.name === 'hello') { 31 const { name } = request.params.arguments; 32 return { 33 content: [{ type: 'text', text: `Hello, ${name}!` }] 34 }; 35 } 36}); 37 38// 启动服务器 39const transport = new StdioServerTransport(); 40await server.connect(transport);
注册自定义服务器:
json1{ 2 "mcpServers": { 3 "my-server": { 4 "command": "node", 5 "args": ["/path/to/my-server.js"] 6 } 7 } 8}
# 常见问题#
## 服务器无法启动#
- 检查命令是否正确安装
- 检查环境变量是否设置
- 查看日志获取详细错误
## 工具调用超时#
增加超时时间:
json1{ 2 "mcpServers": { 3 "slow-server": { 4 "command": "...", 5 "timeout": 60000 6 } 7 } 8}
# 下一步#
掌握 MCP 后,学习如何创建自定义工具。