opencode mcp服务
·
什么是 MCP?
MCP(Model Context Protocol)是让 AI 能够操作外部工具的标准协议。通过 MCP,opencode 可以连接数据库、文件系统等外部服务,让你用自然语言操作数据库。
配置组成
1. opencode.json - 配置文件
在项目根目录创建/编辑 opencode.json:
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"mysql": {
"type": "local",
"command": ["node", "mysql-mcp.js"],
"enabled": true
}
}
}
字段说明:
mysql:MCP 服务名称(可自定义)type:固定写localcommand:启动命令(数组形式)enabled:是否启用
2. mysql-mcp.js - MCP 服务端程序
创建 mysql-mcp.js 文件,内容如下:
const mysql = require('mysql2/promise');
const readline = require('readline');
// 1. 创建 MySQL 连接池
const pool = mysql.createPool({
host: '127.0.0.1',
port: 3306,
user: 'root',
password: 'root',
database: 'hanhe_init',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// 2. 初始化 MCP 通信通道
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
// 3. 发送响应的辅助函数
const sendResponse = (id, result) => {
console.log(JSON.stringify({
jsonrpc: "2.0",
id,
result
}));
};
const sendError = (id, code, message) => {
console.log(JSON.stringify({
jsonrpc: "2.0",
id,
error: { code, message }
}));
};
// 4. 处理 MCP 请求
const handleRequest = async (req) => {
const { jsonrpc, id, method, params } = req;
// 初始化握手
if (method === "initialize") {
sendResponse(id, {
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: { name: "mysql-mcp", version: "1.0.0" }
});
return;
}
// 列出可用工具
if (method === "tools/list") {
sendResponse(id, {
tools: [
{
name: "mysql_query",
description: "执行 MySQL 查询",
inputSchema: {
type: "object",
properties: {
sql: { type: "string", description: "SQL 语句" }
},
required: ["sql"]
}
}
]
});
return;
}
// 调用工具执行 SQL
if (method === "tools/call") {
const { name, arguments: args } = params;
if (name === "mysql_query") {
try {
const { sql } = args;
const [results] = await pool.query(sql);
sendResponse(id, {
content: [{ type: "text", text: JSON.stringify(results) }]
});
} catch (err) {
sendError(id, -32603, err.message);
}
} else {
sendError(id, -32601, "Method not found");
}
return;
}
sendError(id, -32601, "Method not found");
};
// 5. 启动服务
rl.on('line', async (line) => {
try {
const request = JSON.parse(line);
await handleRequest(request);
} catch (err) {
console.log(JSON.stringify({
jsonrpc: "2.0",
id: null,
error: { code: -32700, message: "Parse error" }
}));
}
});
process.on('SIGINT', async () => {
await pool.end();
process.exit(0);
});
修改数据库连接信息
在 mysql-mcp.js 中修改以下配置:
const pool = mysql.createPool({
host: '127.0.0.1', // 数据库地址
port: 3306, // 端口
user: 'root', // 用户名
password: 'root', // 密码
database: 'hanhe_init', // 数据库名
// ...
});
安装依赖
npm install mysql2
使用方法
- 重启 opencode
- 直接用自然语言提问,例如:
- “查看数据库有哪些表”
- “查询 users 表的前 10 条数据”
- “执行 SELECT * FROM orders”
工作流程图
用户 → opencode → mysql-mcp.js → MySQL 数据库
← 返回结果 ←
注意事项
- MCP 程序必须遵循 JSON-RPC 2.0 协议
- 必须实现
initialize、tools/list、tools/call三个方法 - 通过 stdin/stdout 与 opencode 通信
更多推荐

所有评论(0)