什么是 MCP

MCP(Model Context Protocol)是一个开放标准协议,用于为 AI Agent 添加外部工具能力。它定义了:

  • Tools:AI 可以调用的函数
  • Resources:AI 可以读取的数据源
  • Prompts:预定义的提示模板

通过 MCP,AI 编程助手可以访问数据库、调用 API、查询日志系统等,大大扩展了其能力边界。

MCP Server 类型

Local Server

本地运行的 MCP 服务器,通过 stdio 通信:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
    }
  }
}

Remote Server

远程 MCP 服务器,通过 HTTP/SSE 通信:

{
  "mcpServers": {
    "sentry": {
      "url": "https://mcp.sentry.dev/sse",
      "headers": {
        "Authorization": "Bearer ${SENTRY_TOKEN}"
      }
    }
  }
}

实战案例

案例一:Sentry 错误追踪

让 AI 直接查询 Sentry 中的错误信息:

{
  "mcpServers": {
    "sentry": {
      "url": "https://mcp.sentry.dev/sse",
      "headers": {
        "Authorization": "Bearer ${SENTRY_AUTH_TOKEN}"
      }
    }
  }
}

配置后,AI 可以:

  • 查询最近的错误
  • 获取错误堆栈信息
  • 分析错误趋势

使用示例:

> 查看最近 24 小时的错误

[AI 调用 Sentry MCP 工具]

发现 3 个新错误:
1. TypeError: Cannot read property 'id' of undefined
   - 文件:src/api/users.ts:42
   - 出现次数:15
2. ...

案例二:Context7 文档搜索

让 AI 搜索最新的技术文档:

{
  "mcpServers": {
    "context7": {
      "command": "npx",
      "args": ["-y", "@upstash/context7-mcp"]
    }
  }
}

使用示例:

> 查一下 React 19 的新特性

[AI 调用 Context7 搜索文档]

React 19 主要新特性:
1. Actions - 简化表单提交和数据变更
2. use() hook - 在渲染中读取资源
3. Server Components 稳定版
...

案例三:Grep 代码搜索

增强代码搜索能力:

{
  "mcpServers": {
    "grep": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-grep"]
    }
  }
}

案例四:GitHub

让 AI 操作 GitHub:

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

AI 可以创建 Issue、查看 PR、搜索代码等。

工具权限管理

OpenCode 对 MCP 工具实行权限控制:

{
  "permissions": {
    "mcp": {
      "sentry": {
        "allowedTools": ["list_issues", "get_issue"],
        "deniedTools": ["delete_issue"]
      }
    }
  }
}

权限模式:

  • allow:自动允许,不询问
  • ask:每次使用时询问
  • deny:禁止使用

OAuth 认证

对于需要 OAuth 认证的 Remote Server,OpenCode 自动处理认证流程:

{
  "mcpServers": {
    "slack": {
      "url": "https://mcp.slack.com/sse",
      "oauth": {
        "clientId": "${SLACK_CLIENT_ID}",
        "scopes": ["channels:read", "chat:write"]
      }
    }
  }
}

首次使用时,OpenCode 会打开浏览器引导完成授权。

调试连接问题

检查服务器状态

> /mcp status

MCP Servers:
✓ sentry - connected (3 tools)
✗ github - connection refused
? slack - not configured

常见问题

问题解决方案
Connection refused检查服务器是否启动,端口是否正确
Authentication failed检查 Token 是否有效
Tool not found确认工具名称拼写正确
Timeout检查网络连接,增加超时时间

启用调试日志

export OPENCODE_LOG_LEVEL=debug
opencode 2>&1 | grep mcp

编写自定义 MCP Server

使用 TypeScript 编写简单的 MCP Server:

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

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

server.setRequestHandler("tools/list", async () => ({
  tools: [{
    name: "hello",
    description: "Say hello",
    inputSchema: {
      type: "object",
      properties: {
        name: { type: "string" }
      }
    }
  }]
}));

server.setRequestHandler("tools/call", async (request) => {
  if (request.params.name === "hello") {
    return {
      content: [{
        type: "text",
        text: `Hello, ${request.params.arguments.name}!`
      }]
    };
  }
});

const transport = new StdioServerTransport();
await server.connect(transport);