OpenCode MCP 服务器完全指南

MCP(Model Context Protocol)是 Anthropic 提出的开源协议,让 AI 模型能够与外部工具和数据源进行标准化交互。OpenCode 内置了 MCP 客户端支持,通过配置 MCP 服务器,你可以让 AI 编程助手接入数据库、文件系统、GitHub、浏览器等无限的外部生态。本文将全面覆盖 MCP 的配置、使用和自定义开发。

MCP 是什么?

简单来说,MCP 就是 AI 的「USB 协议」——它为 AI 模型连接外部世界提供了统一的标准接口。有了 MCP,AI 不再只能操作本地文件,还可以:

  • 查询数据库并理解表结构
  • 访问 GitHub Issues 和 Pull Requests
  • 搜索网页并获取实时信息
  • 调用公司的内部 API
  • 操控浏览器完成端到端任务

架构概念

OpenCode (MCP Client)
    │
    ├── MCP Server: Filesystem ─── 本地文件系统
    ├── MCP Server: PostgreSQL ─── 数据库服务器
    ├── MCP Server: GitHub    ─── GitHub API
    └── MCP Server: Custom    ─── 你的自定义服务

MCP 传输类型

OpenCode 支持两种 MCP 传输协议:

stdio(标准输入输出)

MCP 服务器作为子进程运行,通过标准输入输出通信:

{
  "mcp": {
    "filesystem": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/data"]
    }
  }
}
  • 优点:简单直接、无需网络配置、安全性高
  • 适用:本地工具、文件操作、CLI 工具

SSE(Server-Sent Events)

MCP 服务器作为远程 HTTP 服务运行,通过 SSE 推送事件:

{
  "mcp": {
    "remote-api": {
      "type": "sse",
      "url": "https://my-mcp-server.example.com/sse"
    }
  }
}
  • 优点:远程访问、多客户端共享、持续运行
  • 适用:团队共享的 MCP 服务、需要持久化连接的工具

配置 MCP 服务器

在 opencode.json 中配置

{
  "mcp": {
    "filesystem": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/Documents"],
      "env": {
        "HOME": "/Users/me"
      }
    },
    "postgres": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://localhost:5432/mydb"
      }
    },
    "github": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "puppeteer": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-puppeteer"]
    },
    "brave-search": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": {
        "BRAVE_API_KEY": "${BRAVE_API_KEY}"
      }
    }
  }
}

在 .opencode/mcp/ 目录中配置

也可以创建专门的 MCP 配置文件:

.opencode/mcp/
├── filesystem.json
├── postgres.json
└── github.json

每个 JSON 文件的格式:

{
  "type": "stdio",
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-filesystem", "/data"],
  "env": {}
}

常用 MCP 服务器推荐

官方 MCP 服务器

| 服务器 | 包名 | 功能 |
|--------|------|------|
| Filesystem | @modelcontextprotocol/server-filesystem | 读写文件系统 |
| GitHub | @modelcontextprotocol/server-github | 管理 Issues、PR、仓库 |
| PostgreSQL | @modelcontextprotocol/server-postgres | 查询和管理数据库 |
| SQLite | @modelcontextprotocol/server-sqlite | SQLite 数据库操作 |
| Puppeteer | @modelcontextprotocol/server-puppeteer | 浏览器自动化 |
| Brave Search | @modelcontextprotocol/server-brave-search | 网络搜索 |
| Google Drive | @modelcontextprotocol/server-gdrive | Google Drive 文件管理 |
| Slack | @modelcontextprotocol/server-slack | Slack 消息管理 |
| Memory | @modelcontextprotocol/server-memory | 持久化记忆存储 |

安装和启动

# 文件系统服务器
npx -y @modelcontextprotocol/server-filesystem /path/to/workspace

# GitHub 服务器
GITHUB_PERSONAL_ACCESS_TOKEN=ghp_xxx \
npx -y @modelcontextprotocol/server-github

# PostgreSQL 服务器
DATABASE_URL=postgresql://user:pass@localhost:5432/db \
npx -y @modelcontextprotocol/server-postgres

# 浏览器自动化
npx -y @modelcontextprotocol/server-puppeteer

# 网页搜索
BRAVE_API_KEY=your_key \
npx -y @modelcontextprotocol/server-brave-search

实战场景

场景 1:数据库分析与查询

{
  "mcp": {
    "postgres": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  }
}

配置后,你可以在对话中直接说:

帮我看看 users 表的结构,然后查一下最近 30 天注册的用户数量

OpenCode 会通过 MCP 连接数据库,自动执行 DESC usersSELECT 查询。

场景 2:GitHub 工作流自动化

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

对话示例:

帮我在这个仓库创建一个 Issue,标题是「优化首页加载速度」,描述里引用一下 Lighthouse 报告中速度慢的几项指标。然后关联到 sprint-23 milestone。

场景 3:全自动端到端测试

{
  "mcp": {
    "puppeteer": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-puppeteer"]
    }
  }
}

对话示例:

打开 https://example.com/login,输入用户名 admin 密码 test123,点击登录按钮,验证是否跳转到了 dashboard 页面

场景 4:实时网络搜索

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

对话示例:

帮我搜索一下 React 19 的新特性,特别是 Server Components 相关的内容

编写自定义 MCP 服务器

你可以用任何语言编写自定义 MCP 服务器。以下是 TypeScript 的最小示例:

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  ListToolsRequestSchema,
  CallToolRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";

const server = new Server(
  {
    name: "my-custom-mcp-server",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// 定义可用工具
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "get_weather",
      description: "Get the weather for a city",
      inputSchema: {
        type: "object",
        properties: {
          city: { type: "string" },
        },
        required: ["city"],
      },
    },
  ],
}));

// 实现工具逻辑
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "get_weather") {
    const city = request.params.arguments?.city as string;
    // 调用你的 API 获取天气
    return {
      content: [{ type: "text", text: `${city} 当前天气:晴天,26°C` }],
    };
  }
  throw new Error("Unknown tool");
});

// 启动服务器
const transport = new StdioServerTransport();
await server.connect(transport);

配置自定义 MCP 服务器

{
  "mcp": {
    "weather": {
      "type": "stdio",
      "command": "node",
      "args": ["/path/to/my-mcp-server/build/index.js"]
    }
  }
}

Python 版本示例

from mcp.server import Server, StdioServerTransport
from mcp.types import Tool

server = Server("my-server")

@server.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="hello",
            description="Say hello to someone",
            inputSchema={
                "type": "object",
                "properties": {
                    "name": {"type": "string"}
                }
            }
        )
    ]

@server.call_tool()
async def call_tool(name: str, arguments: dict) -> str:
    if name == "hello":
        return f"Hello, {arguments.get('name', 'world')}!"

async def main():
    transport = StdioServerTransport()
    await server.run(transport)

MCP 调试与故障排查

检查 MCP 服务器状态

# 查看已配置的 MCP 服务器
opencode mcp list

# 测试某个 MCP 服务器的连接
opencode mcp test postgres

常见问题

Q:启动 OpenCode 后 MCP 服务器没有加载?

A:检查以下几点:

MCP 服务器的 command 是否存在(执行 which npx 确认)

环境变量是否正确设置

在 opencode.json 中的 mcp 配置格式是否正确

Q:MCP 服务器报错连接超时?

A:检查:

网络连接是否正常

代理配置是否正确

MCP 服务器进程是否正常启动(手动执行 command 测试)

Q:权限不足?

A:为 MCP 服务器的 env 配置添加必要的环境变量和权限。

安全注意事项

  • MCP 服务器运行在你的机器上,确保来源可信
  • 不要在 MCP 配置中直接写入 Token 或密码,使用 ${ENV_VAR} 语法引用环境变量
  • 限制 MCP 服务器的文件访问范围
  • 为数据库 MCP 连接使用只读权限的账号

小结

MCP 是 OpenCode 扩展能力边界的关键协议。通过接入 MCP 服务器,AI 编程助手可以访问数据库、搜索引擎、浏览器、云服务等几乎所有外部系统。掌握 MCP 配置后,你的 AI 助手将不再局限于代码编辑——它是一个能打通全部工作流的智能中枢。

下一篇我们将深入 OpenCode 的 Provider 与模型配置,学习如何选择和配置 75+ LLM 模型,包括本地模型的搭建。