MCP(Model Context Protocol)是 Anthropic 提出的开源协议,让 AI 模型能够与外部工具和数据源进行标准化交互。OpenCode 内置了 MCP 客户端支持,通过配置 MCP 服务器,你可以让 AI 编程助手接入数据库、文件系统、GitHub、浏览器等无限的外部生态。本文将全面覆盖 MCP 的配置、使用和自定义开发。
简单来说,MCP 就是 AI 的「USB 协议」——它为 AI 模型连接外部世界提供了统一的标准接口。有了 MCP,AI 不再只能操作本地文件,还可以:
OpenCode (MCP Client)
│
├── MCP Server: Filesystem ─── 本地文件系统
├── MCP Server: PostgreSQL ─── 数据库服务器
├── MCP Server: GitHub ─── GitHub API
└── MCP Server: Custom ─── 你的自定义服务
OpenCode 支持两种 MCP 传输协议:
MCP 服务器作为子进程运行,通过标准输入输出通信:
{
"mcp": {
"filesystem": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/data"]
}
}
}
MCP 服务器作为远程 HTTP 服务运行,通过 SSE 推送事件:
{
"mcp": {
"remote-api": {
"type": "sse",
"url": "https://my-mcp-server.example.com/sse"
}
}
}
{
"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}"
}
}
}
}
也可以创建专门的 MCP 配置文件:
.opencode/mcp/ ├── filesystem.json ├── postgres.json └── github.json
每个 JSON 文件的格式:
{
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/data"],
"env": {}
}
| 服务器 | 包名 | 功能 |
|--------|------|------|
| 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
{
"mcp": {
"postgres": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
}
}
}
配置后,你可以在对话中直接说:
帮我看看 users 表的结构,然后查一下最近 30 天注册的用户数量
OpenCode 会通过 MCP 连接数据库,自动执行 DESC users 和 SELECT 查询。
{
"mcp": {
"github": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}
对话示例:
帮我在这个仓库创建一个 Issue,标题是「优化首页加载速度」,描述里引用一下 Lighthouse 报告中速度慢的几项指标。然后关联到 sprint-23 milestone。
{
"mcp": {
"puppeteer": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-puppeteer"]
}
}
}
对话示例:
打开 https://example.com/login,输入用户名 admin 密码 test123,点击登录按钮,验证是否跳转到了 dashboard 页面
{
"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 服务器。以下是 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": {
"weather": {
"type": "stdio",
"command": "node",
"args": ["/path/to/my-mcp-server/build/index.js"]
}
}
}
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 服务器 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 配置添加必要的环境变量和权限。
${ENV_VAR} 语法引用环境变量MCP 是 OpenCode 扩展能力边界的关键协议。通过接入 MCP 服务器,AI 编程助手可以访问数据库、搜索引擎、浏览器、云服务等几乎所有外部系统。掌握 MCP 配置后,你的 AI 助手将不再局限于代码编辑——它是一个能打通全部工作流的智能中枢。
下一篇我们将深入 OpenCode 的 Provider 与模型配置,学习如何选择和配置 75+ LLM 模型,包括本地模型的搭建。