Sooua
登录
返回文章列表
OpenCode··5 分钟阅读

MCP 服务器集成

flowchart TB

目标:通过 MCP 扩展 OpenCode 的能力边界,连接外部工具生态


MCP 架构概览


什么是 MCP

MCP(Model Context Protocol)是由 Anthropic 提出的开放协议,用于标准化 AI 与外部工具的交互。

类比:

  • USB 统一了外设连接
  • MCP 统一了 AI 工具连接

MCP 核心概念

概念说明类比
Server提供工具的服务端应用服务器
Client使用工具的客户端OpenCode
Tool可执行的功能API 接口
Resource可读的数据源数据库

配置 MCP 服务器

本地 MCP(Stdio 模式)

// opencode.json
{
  "mcp": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"]
    }
  }
}

远程 MCP(SSE 模式)

{
  "mcp": {
    "remote-docs": {
      "url": "https://docs.company.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer ${DOCS_TOKEN}"
      }
    }
  }
}

启用与禁用

{
  "mcp": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "enabled": true      // ← 启用
    },
    "postgres": {
      // ...
      "enabled": false     // ← 禁用
    }
  }
}

常用 MCP 服务器配置库

文件系统访问

{
  "mcp": {
    "fs": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"]
    }
  }
}

可用工具

  • fs_read_file — 读取文件
  • fs_write_file — 写入文件
  • fs_list_directory — 列出目录
  • fs_search_files — 搜索文件

GitHub 集成

{
  "mcp": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

可用工具

  • github_create_issue — 创建 Issue
  • github_create_pull_request — 创建 PR
  • github_search_code — 搜索代码
  • github_get_file_contents — 获取文件内容

PostgreSQL 数据库

{
  "mcp": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/mydb"]
    }
  }
}

可用工具

  • postgres_query — 执行查询
  • postgres_list_tables — 列出表
  • postgres_describe_table — 查看表结构

Brave 搜索

{
  "mcp": {
    "brave": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": {
        "BRAVE_API_KEY": "${BRAVE_API_KEY}"
      }
    }
  }
}

可用工具

  • brave_web_search — 网页搜索
  • brave_local_search — 本地搜索

上下文消耗分析

各 MCP 的上下文开销

MCP 服务器工具数量上下文开销建议
filesystem5-8~500 tokens可控
GitHub15+~2000+ tokens⚠️ 较大
PostgreSQL5-8~800 tokens可控
Brave Search2-3~300 tokens

优化策略

{
  "mcp": {
    // 只启用当前任务需要的
    "github": { "enabled": false },
    "postgres": { "enabled": true },
    "fs": { "enabled": true }
  }
}

实战:完整 MCP 配置示例

场景:全栈开发环境

// opencode.json
{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic/claude-sonnet-4-5",
  
  "mcp": {
    "fs": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"]
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://dev:dev@localhost:5432/myapp"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      },
      "enabled": false  // 默认禁用,需要时启用
    }
  },
  
  "permission": {
    "fs_*": "allow",
    "postgres_query": "allow",
    "postgres_list_tables": "allow",
    "github_*": "ask"
  }
}

使用 MCP 的工作流


MCP 开发指南

开发自定义 MCP 服务器

// my-mcp-server.ts
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
 
const server = new Server({
  name: 'my-custom-mcp',
  version: '1.0.0'
}, {
  capabilities: {
    tools: {}
  }
});
 
// 注册工具
server.setRequestHandler('tools/list', async () => {
  return {
    tools: [{
      name: 'custom_search',
      description: '搜索内部知识库',
      inputSchema: {
        type: 'object',
        properties: {
          query: { type: 'string' }
        },
        required: ['query']
      }
    }]
  };
});
 
// 处理工具调用
server.setRequestHandler('tools/call', async (request) => {
  if (request.params.name === 'custom_search') {
    const { query } = request.params.arguments;
    const results = await searchInternalKB(query);
    return {
      content: [{ type: 'text', text: JSON.stringify(results) }]
    };
  }
});
 
const transport = new StdioServerTransport();
await server.connect(transport);

安全隔离策略

权限矩阵

MCP读取写入执行建议权限
filesystem⚠️ask
github⚠️ask
postgres⚠️⚠️ask
bash⚠️deny

环境隔离


FAQ

Q: MCP 和自定义工具有什么区别?

MCP 是标准化协议,可复用;自定义工具是 OpenCode 特有配置,更简单。

Q: MCP 会占用多少 Token?

取决于工具数量和描述长度。GitHub MCP 可能占用 2000+ tokens,建议按需启用。

Q: 可以开发私有 MCP 吗?

可以!开发后通过 commandurl 配置即可。


练习

  1. 添加文件系统 MCP,让 AI 访问你的文档目录
  2. 配置 PostgreSQL MCP,让 AI 帮你写 SQL
  3. 尝试 GitHub MCP,查询一个仓库的 Issue
  4. 观察启用 MCP 前后的 Token 消耗差异

下一篇:13. GitHub/GitLab 集成

分享

评论

登录 后参与讨论。

加载中…

相关文章