Skip to content

5.7a MCP 基础

💡 一句话总结:了解 MCP 协议,连接外部服务和工具。


学完你能做什么

  • 理解 MCP 协议的概念
  • 能配置 MCP 服务器
  • 能使用 MCP 工具
  • 能创建简单的 MCP 连接

🎒 开始前的准备

确保你已经完成以下事项:

  • [ ] 完成必修课程
  • [ ] 了解基本配置

核心思路

什么是 MCP

MCP (Model Context Protocol) 是一个开放协议,用于连接 AI 模型和外部工具/服务。

AI 模型 ←→ MCP 客户端 ←→ MCP 服务器 ←→ 外部服务

MCP 优势

  • 标准化接口
  • 易于扩展
  • 安全可控
  • 社区共享

配置结构

连接 MCP 服务器

yaml
mcp:
  servers:
    filesystem:
      command: "npx"
      args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
      env:
        NODE_ENV: "production"
    
    github:
      command: "npx"
      args: ["-y", "@modelcontextprotocol/server-github"]
      env:
        GITHUB_TOKEN: "${GITHUB_TOKEN}"
    
    postgres:
      command: "uvx"
      args: ["mcp-server-postgres", "--connection-string", "${DATABASE_URL}"]

服务器配置

yaml
mcp:
  servers:
    my-server:
      command: "./mcp-server"
      args: ["--port", "3000"]
      
      settings:
        timeout: 30000
        retries: 3
        
      permissions:
        read: true
        write: false
        execute: false

常用 MCP 服务器

文件系统

bash
npx -y @modelcontextprotocol/server-filesystem ~/projects

GitHub

bash
npx -y @modelcontextprotocol/server-github

数据库

bash
uvx mcp-server-postgres --connection-string "postgresql://user:pass@localhost/db"

Puppeteer

bash
npx -y @modelcontextprotocol/server-puppeteer

跟我做

实战:配置文件系统 MCP 服务器

  1. 安装 MCP 服务器:
bash
npm install -g @modelcontextprotocol/server-filesystem
  1. 配置 OpenCode:
yaml
mcp:
  servers:
    files:
      command: "npx"
      args: ["-y", "@modelcontextprotocol/server-filesystem", "~/my-projects"]
      enabled: true
      
      permissions:
        read: true
        write: true
        
      settings:
        allowedDirectories:
          - "~/my-projects"
  1. 测试连接:
列出 ~/my-projects 目录下的文件

检查点 ✅

全部通过才能继续

  • [ ] 理解 MCP 协议
  • [ ] 能配置 MCP 服务器
  • [ ] 能使用 MCP 工具

本课小结

你学会了:

  1. MCP 协议概念
  2. 服务器配置方法
  3. 常用 MCP 服务器
  4. 实战配置

下一课预告

下一课我们将学习 MCP 进阶,掌握高级配置和自定义服务器。


📚 更多完整模板Prompt 模板库