**系列**: AI Agent 实战笔记 **日期**: 2026-05-22 **标签**: OpenCode, MCP, Model Context Protocol, 工具集成 **难度**: ⭐⭐⭐⭐

MCP 集成实战 —— Server 配置、工具注册与结果处理

系列: AI Agent 实战笔记 日期: 2026-05-22 标签: OpenCode, MCP, Model Context Protocol, 工具集成 难度: ⭐⭐⭐⭐

简介

在之前的文章中,我们系统学习了 OpenCode 的安装配置、命令运行、TUI 交互、Session 管理、Agent 模式、PR 审查实战、并行工作、提示词工程以及自定义配置。但所有这些能力都集中在 OpenCode 自带的工具集上——文件读写、代码搜索、终端执行等。

如果你想让 OpenCode 连接外部系统呢?

  • 调用 GitHub API 自动创建 Issue 和 PR
  • 查询数据库获取运行时信息
  • 对接 Jira、飞书、钉钉等项目管理系统
  • 使用自定义的 API 服务获取业务数据

这就是 MCP(Model Context Protocol) 发挥威力的地方。

MCP 是由 Anthropic 提出的开放协议,定义了 AI 模型与外部工具之间的标准交互方式。OpenCode 原生支持 MCP,意味着你可以用标准化的方式,为 Agent 扩展几乎无限的外部能力。

本文将深入讲解 OpenCode 的 MCP 集成:

  • MCP 协议基础:架构、通信模式、核心概念
  • Server 配置:如何声明和管理 MCP Server
  • 工具注册:工具发现、参数定义、动态加载
  • 结果处理:输出解析、错误处理、上下文传递
  • 实战场景:从配置到落地的完整示例

一、MCP 协议基础

1.1 什么是 MCP

MCP(Model Context Protocol)是一个开放标准协议,用于在 AI 模型和外部数据/工具之间建立标准化的连接通道。你可以把它理解为 AI 领域的 USB 接口——只要遵循协议标准,任何工具都能即插即用地接入 AI Agent。

核心设计原则:

text
┌─────────────┐         ┌─────────────┐         ┌─────────────┐
│  AI Model   │◄───────►│    Host     │◄───────►│   Server    │
│  (OpenCode) │         │  (Agent)    │         │  (Tool API) │
└─────────────┘         └─────────────┘         └─────────────┘
                              │
                        MCP Protocol
                    (JSON-RPC over stdio/HTTP)

三个核心角色

  1. Host(宿主):运行 Agent 的程序(OpenCode),负责管理连接和调度工具调用
  2. Server(服务端):提供具体工具能力的服务(如 GitHub MCP Server、数据库 MCP Server)
  3. Client(客户端):嵌入在 Host 中的 MCP 协议客户端,负责与 Server 通信

1.2 MCP 通信模式

MCP 支持两种通信传输方式:

stdio 模式(本地进程):

bash
# 通过标准输入/输出与子进程通信
# 适用于本地安装的 CLI 工具
mcp-server-github → stdio → OpenCode

HTTP/SSE 模式(网络服务):

bash
# 通过 HTTP 协议与远程服务通信
# 适用于远程部署的 MCP Server
https://mcp.example.com → HTTP/SSE → OpenCode

OpenCode 同时支持这两种模式,你可以根据实际场景选择。

1.3 MCP 核心概念

MCP 协议定义了三种核心能力:

能力类型 描述 示例
Tools(工具) 可被 AI 调用的操作 github.create_issuedb.query
Resources(资源) 可被 AI 读取的数据源 file://README.mdpostgres://table/users
Prompts(提示词模板) 预定义的交互模板 code-reviewbug-report

在 OpenCode 中,最常用的是 Tools——这也是本文的重点。

二、Server 配置

2.1 在 settings.json 中声明 MCP Server

OpenCode 的 MCP Server 配置在 settings.jsonmcpServers 字段中。你可以在全局配置或项目配置中添加:

json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-github"
      ],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/home/user/projects",
        "/home/user/docs"
      ]
    }
  }
}

2.2 配置字段详解

每个 MCP Server 条目包含以下字段:

字段 类型 必填 描述
command string 启动 Server 的命令
args string[] 命令参数列表
env object 环境变量(支持 ${VAR} 模板)
disabled boolean 是否禁用此 Server
timeout number 工具调用超时(毫秒)
type string 传输类型:stdio(默认)或 http

HTTP 模式的 Server 配置

json
{
  "mcpServers": {
    "remote-tools": {
      "type": "http",
      "url": "https://mcp.yourcompany.com/sse",
      "headers": {
        "Authorization": "Bearer ${MCP_API_TOKEN}"
      }
    }
  }
}

2.3 环境变量模板

env 字段支持 ${VAR} 形式的变量替换,OpenCode 会从系统环境变量中自动填充:

json
{
  "mcpServers": {
    "jira": {
      "command": "python",
      "args": ["-m", "mcp_jira_server"],
      "env": {
        "JIRA_URL": "${JIRA_URL}",
        "JIRA_API_TOKEN": "${JIRA_API_TOKEN}",
        "JIRA_EMAIL": "${JIRA_EMAIL}"
      }
    }
  }
}

这种方式非常安全——你的敏感 Token 不会硬编码在配置文件中,而是从环境变量动态获取。

2.4 管理多个 Server

在团队协作场景中,你可能需要同时连接多个 MCP Server:

json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
    },
    "slack": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-slack"],
      "env": { "SLACK_BOT_TOKEN": "${SLACK_TOKEN}" }
    },
    "custom-api": {
      "command": "node",
      "args": ["/opt/mcp-servers/custom-api/dist/index.js"],
      "env": {
        "API_KEY": "${CUSTOM_API_KEY}",
        "API_BASE_URL": "https://api.yourcompany.com/v2"
      },
      "timeout": 30000
    }
  }
}

2.5 启动与调试

启动 OpenCode 时,它会自动连接所有已配置的 MCP Server:

bash
# 查看 Server 连接状态
$ opencode run --prompt "list available tools"

# 在 TUI 中查看工具列表
# 按 / 打开工具列表,可以看到所有已注册的工具

# 调试 Server 启动问题
$ opencode run --verbose --prompt "test github tools"

如果某个 Server 启动失败,OpenCode 会在日志中输出错误信息:

bash
# 查看 MCP 连接日志
$ cat ~/.opencode/logs/mcp.log

# 输出示例:
# [2026-05-22T10:30:00Z] INFO: Connecting to github MCP server...
# [2026-05-22T10:30:01Z] INFO: github server connected, 12 tools available
# [2026-05-22T10:30:02Z] ERROR: postgres server failed: connection refused

三、工具注册

3.1 工具发现机制

当 OpenCode 连接到 MCP Server 后,会自动发送 tools/list 请求,获取该 Server 提供的所有工具:

json
// OpenCode → MCP Server
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list"
}

// MCP Server → OpenCode
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [
      {
        "name": "github_create_issue",
        "description": "Create a new GitHub issue in the specified repository",
        "inputSchema": {
          "type": "object",
          "properties": {
            "owner": { "type": "string", "description": "Repository owner" },
            "repo": { "type": "string", "description": "Repository name" },
            "title": { "type": "string", "description": "Issue title" },
            "body": { "type": "string", "description": "Issue body (markdown)" },
            "labels": {
              "type": "array",
              "items": { "type": "string" },
              "description": "Issue labels"
            }
          },
          "required": ["owner", "repo", "title"]
        }
      }
    ]
  }
}

3.2 工具的参数定义

MCP 工具的参数使用 JSON Schema 定义,这让 OpenCode 能够:

  1. 自动理解参数类型(string、number、boolean、array、object)
  2. 识别必填参数(required 字段)
  3. 生成友好的调用提示(description 字段)
  4. 进行参数校验(在调用前验证参数格式)

复杂参数的定义示例

json
{
  "name": "db_query_with_join",
  "description": "Execute a SQL query with table joins",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": {
        "type": "string",
        "description": "SQL query text"
      },
      "params": {
        "type": "array",
        "items": { "type": "string" },
        "description": "Query parameters for prepared statements"
      },
      "timeout_ms": {
        "type": "integer",
        "description": "Query timeout in milliseconds",
        "default": 5000
      },
      "options": {
        "type": "object",
        "properties": {
          "format": {
            "type": "string",
            "enum": ["json", "csv", "table"],
            "default": "json"
          },
          "max_rows": {
            "type": "integer",
            "default": 100
          }
        }
      }
    },
    "required": ["query"]
  }
}

3.3 在 OpenCode 中查看已注册工具

方法一:通过 TUI 查看

text
# 在 TUI 界面中
1. 按 / 打开命令面板
2. 输入 "tools" 查看所有可用工具
3. 每个工具显示名称、描述和参数信息

方法二:通过命令行查询

bash
# 列出所有可用工具
$ opencode run --prompt "列出所有可用的 MCP 工具,按 Server 分组"

# 输出示例:
# GitHub Server (12 tools):
#   - github_create_issue: 创建 GitHub Issue
#   - github_search_repos: 搜索仓库
#   - github_get_pr: 获取 PR 详情
#   - github_create_pr: 创建 Pull Request
#
# PostgreSQL Server (5 tools):
#   - db_query: 执行 SQL 查询
#   - db_list_tables: 列出所有表
#   - db_describe_table: 查看表结构

3.4 动态工具注册与注销

OpenCode 支持在运行时动态启用/禁用 MCP Server:

json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" }
    },
    "experimental-api": {
      "command": "node",
      "args": ["./experimental-mcp-server.js"],
      "disabled": true
    }
  }
}

设置 "disabled": true 后,该 Server 不会在启动时连接,但你可以在需要时手动启用。

四、结果处理

4.1 工具调用流程

完整的 MCP 工具调用流程如下:

text
┌──────────┐    ①选择工具     ┌──────────┐
│  用户     │ ──────────────► │ OpenCode │
│  输入    │                 │ (Agent)  │
└──────────┘                 └────┬─────┘
                                  │ ②tools/call
                                  ▼
                           ┌─────────────┐
                           │ MCP Server  │
                           │ (工具执行)   │
                           └──────┬──────┘
                                  │ ③返回结果
                                  ▼
                           ┌─────────────┐
                           │  结果处理    │
                           │ 解析/格式化  │
                           └──────┬──────┘
                                  │ ④渲染输出
                                  ▼
                           ┌─────────────┐
                           │  用户看到    │
                           │  结果       │
                           └─────────────┘

4.2 调用工具

OpenCode Agent 在执行任务时,会自动选择合适的 MCP 工具并调用:

json
// OpenCode → MCP Server
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "github_create_issue",
    "arguments": {
      "owner": "nousresearch",
      "repo": "hermes-agent",
      "title": "Memory 系统需要支持向量检索",
      "body": "## 需求描述\n\n当前 Memory 系统使用简单的 KV 存储,\n建议增加向量检索能力,支持语义相似度搜索。\n\n## 预期效果\n\n- 支持 embedding 向量存储\n- 支持 top-K 相似度检索\n- 与现有 Memory API 保持兼容",
      "labels": ["enhancement", "memory"]
    }
  }
}

4.3 结果解析

MCP Server 返回的结果格式:

json
// MCP Server → OpenCode
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Issue created: https://github.com/nousresearch/hermes-agent/issues/42"
      },
      {
        "type": "text",
        "text": "Issue ID: 42\nState: open\nCreated at: 2026-05-22T10:35:00Z"
      }
    ],
    "isError": false
  }
}

OpenCode 会解析这些结果并呈现给用户。

4.4 错误处理

当工具调用失败时,MCP Server 会返回错误信息:

json
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Error: Repository not found. Please check the owner/repo path and your access token permissions."
      }
    ],
    "isError": true
  }
}

OpenCode 会:

  1. 识别错误(isError: true
  2. 将错误信息纳入上下文
  3. Agent 可以根据错误信息调整策略或向用户报告

4.5 结果在上下文中的传递

MCP 工具的结果会被自动添加到对话上下文中,Agent 可以在后续推理中使用这些结果:

text
用户: 帮我查一下 hermes-agent 仓库最近的 Issue

Agent: [调用 github_list_issues 工具]
       [工具返回: 3 个 open issue]

Agent: hermes-agent 仓库目前有 3 个开放的 Issue1. #42 - Memory 系统需要支持向量检索 (enhancement)
       2. #41 - 增加 Discord 频道支持 (feature)
       3. #40 - 修复 session_search 的分页问题 (bug)

用户: 帮我总结一下 #42 的内容并回复一条评论

Agent: [已经在上文中获取了 #42 的信息]
       [调用 github_add_comment 工具]
       [成功添加评论]

这就是 上下文传递 的力量——Agent 不需要重复获取信息,一次工具调用的结果可以在整个对话中被复用。

五、实战场景

5.1 场景一:GitHub 自动化工作流

配置

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

使用

bash
# 自动创建带有标签的 Issue
$ opencode run --prompt "
  在 nousresearch/hermes-agent 仓库创建一个 Issue:
  标题:优化 TUI 渲染性能
  内容:当前 TUI 在处理大量输出时出现卡顿,
       建议优化渲染管线,引入虚拟滚动。
  关键词:performance, TUI
"

# 搜索相关的 Issue
$ opencode run --prompt "搜索 hermes-agent 中所有标记为 performance 的 Issue"

# 审查 PR 并评论
$ opencode run --prompt "审查 PR #123,重点关注安全和性能问题,然后留下 review 评论"

5.2 场景二:数据库查询与分析

配置

json
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://user:pass@localhost:5432/analytics"
      ]
    }
  }
}

使用

bash
# 查询数据
$ opencode run --prompt "
  查询 analytics 数据库中过去 7 天的 API 调用量,
  按 endpoint 分组,按调用量降序排列,
  只显示前 10 个 endpoint
"

# Agent 自动构建并执行 SQL
# 结果格式化后展示

5.3 场景三:自定义 MCP Server

你也可以编写自己的 MCP Server:

javascript
// custom-mcp-server.js
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new McpServer({
  name: "weather-service",
  version: "1.0.0"
});

// 注册工具
server.tool("get_weather",
  "获取指定城市的天气信息",
  {
    city: { type: "string", description: "城市名称" },
    unit: {
      type: "string",
      enum: ["celsius", "fahrenheit"],
      default: "celsius",
      description: "温度单位"
    }
  },
  async ({ city, unit }) => {
    // 调用天气 API
    const response = await fetch(
      `https://api.weather.com/v1/weather?city=${city}&unit=${unit}`,
      { headers: { "X-API-Key": process.env.WEATHER_API_KEY } }
    );
    const data = await response.json();

    return {
      content: [
        {
          type: "text",
          text: `${city} 当前天气:${data.condition},温度 ${data.temp}°${unit === 'celsius' ? 'C' : 'F'}`
        }
      ]
    };
  }
);

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

配置

json
{
  "mcpServers": {
    "weather": {
      "command": "node",
      "args": ["/opt/mcp-servers/weather/custom-mcp-server.js"],
      "env": {
        "WEATHER_API_KEY": "${WEATHER_API_KEY}"
      }
    }
  }
}

六、最佳实践与注意事项

6.1 工具选择策略

  1. 优先使用专用工具:当有多个工具可以完成同一任务时,选择最专用的那个
  2. 善用工具描述:为你的工具编写清晰、准确的描述,这直接影响 Agent 的工具选择准确率
  3. 参数精简:只提供必要的参数,过多的可选参数会增加 Agent 的决策负担

6.2 安全性考虑

  1. 最小权限原则:MCP Server 的 Token 只授予完成任务所需的最小权限
  2. 环境变量管理:敏感信息永远通过环境变量传递,不要硬编码
  3. 输入校验:MCP Server 端应该对所有输入参数进行严格校验
  4. 结果过滤:敏感数据在返回给 Agent 前应该进行脱敏处理

6.3 性能优化

  1. 合理设置超时:根据工具的实际响应时间设置 timeout,避免不必要的等待
  2. 批量操作:如果工具支持批量操作,优先使用批量接口减少调用次数
  3. 结果缓存:对于不经常变化的数据,考虑在 MCP Server 端实现缓存

总结

本文系统讲解了 OpenCode 的 MCP 集成能力:

  • MCP 协议是 AI 工具集成的开放标准,让外部工具可以即插即用地接入 Agent
  • Server 配置通过 settings.json 中的 mcpServers 字段声明,支持 stdio 和 HTTP 两种传输模式
  • 工具注册是自动化的——OpenCode 连接 Server 后自动发现所有可用工具及其参数定义
  • 结果处理包括调用、解析、错误处理和上下文传递,确保 Agent 能有效利用工具输出
  • 实战场景展示了 GitHub 自动化、数据库查询和自定义 Server 的完整流程

MCP 让 OpenCode 的能力边界不再受限于内置工具——你可以为它连接几乎任何外部系统,真正打造出适合你工作流的 AI 编程助手。