```
feat(main): 添加MCP工具列表API和优化服务器路由 - 新增getToolsList函数,提供完整的编辑器操作工具集 - 包含节点操作、场景管理、预制体创建等9个核心功能 - 重构HTTP服务器路由逻辑,分离工具列表和调用接口 - 移除冗余的CORS头设置,简化请求处理流程 - 统一错误处理和日志记录机制 feat(proxy): 实现MCP协议代理服务 - 创建mcp-proxy.js作为独立的协议转换层 - 支持initialize、tools/list、tools/call方法 - 实现与Cocos编辑器的HTTP通信桥接 - 提供详细的调试日志和错误处理机制 ```
This commit is contained in:
150
main.js
150
main.js
@@ -63,57 +63,8 @@ const getNewSceneTemplate = () => {
|
||||
return JSON.stringify(sceneData);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
"scene-script": "scene-script.js",
|
||||
load() {
|
||||
addLog("info", "MCP Bridge Plugin Loaded");
|
||||
// 读取配置
|
||||
let profile = this.getProfile();
|
||||
serverConfig.port = profile.get("last-port") || 3456;
|
||||
let autoStart = profile.get("auto-start");
|
||||
|
||||
if (autoStart) {
|
||||
addLog("info", "Auto-start is enabled. Initializing server...");
|
||||
// 延迟一点启动,确保编辑器环境完全就绪
|
||||
setTimeout(() => {
|
||||
this.startServer(serverConfig.port);
|
||||
}, 1000);
|
||||
}
|
||||
},
|
||||
// 获取配置文件的辅助函数
|
||||
getProfile() {
|
||||
// 'local' 表示存储在项目本地(local/mcp-bridge.json)
|
||||
return Editor.Profile.load("profile://local/mcp-bridge.json", "mcp-bridge");
|
||||
},
|
||||
|
||||
unload() {
|
||||
this.stopServer();
|
||||
},
|
||||
startServer(port) {
|
||||
if (mcpServer) this.stopServer();
|
||||
|
||||
try {
|
||||
mcpServer = http.createServer((req, res) => {
|
||||
// 设置 CORS 方便调试
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
let body = "";
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
req.on("end", () => {
|
||||
try {
|
||||
// 简单的路由处理
|
||||
if (req.url === "/list-tools" && req.method === "GET") {
|
||||
// 1. 返回工具定义 (符合 MCP 规范)
|
||||
const tools = [
|
||||
const getToolsList = () => {
|
||||
return [
|
||||
{
|
||||
name: "get_selected_node",
|
||||
description: "获取当前编辑器中选中的节点 ID",
|
||||
@@ -215,16 +166,61 @@ module.exports = {
|
||||
},
|
||||
},
|
||||
];
|
||||
return res.end(JSON.stringify({ tools }));
|
||||
}
|
||||
if (req.url === "/call-tool" && req.method === "POST") {
|
||||
try {
|
||||
const { name, arguments: args } = JSON.parse(body);
|
||||
};
|
||||
|
||||
addLog("mcp", `REQ -> [${name}] ${JSON.stringify(args)}`);
|
||||
module.exports = {
|
||||
"scene-script": "scene-script.js",
|
||||
load() {
|
||||
addLog("info", "MCP Bridge Plugin Loaded");
|
||||
// 读取配置
|
||||
let profile = this.getProfile();
|
||||
serverConfig.port = profile.get("last-port") || 3456;
|
||||
let autoStart = profile.get("auto-start");
|
||||
|
||||
if (autoStart) {
|
||||
addLog("info", "Auto-start is enabled. Initializing server...");
|
||||
// 延迟一点启动,确保编辑器环境完全就绪
|
||||
setTimeout(() => {
|
||||
this.startServer(serverConfig.port);
|
||||
}, 1000);
|
||||
}
|
||||
},
|
||||
// 获取配置文件的辅助函数
|
||||
getProfile() {
|
||||
// 'local' 表示存储在项目本地(local/mcp-bridge.json)
|
||||
return Editor.Profile.load("profile://local/mcp-bridge.json", "mcp-bridge");
|
||||
},
|
||||
|
||||
unload() {
|
||||
this.stopServer();
|
||||
},
|
||||
startServer(port) {
|
||||
if (mcpServer) this.stopServer();
|
||||
|
||||
try {
|
||||
mcpServer = http.createServer((req, res) => {
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
|
||||
let body = "";
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
req.on("end", () => {
|
||||
const url = req.url;
|
||||
if (url === "/list-tools") {
|
||||
const tools = getToolsList();
|
||||
addLog("info", `AI Client requested tool list`);
|
||||
// 明确返回成功结构
|
||||
res.writeHead(200);
|
||||
return res.end(JSON.stringify({ tools: tools }));
|
||||
}
|
||||
if (url === "/call-tool") {
|
||||
try {
|
||||
const { name, arguments: args } = JSON.parse(body || "{}");
|
||||
addLog("mcp", `REQ -> [${name}]`);
|
||||
|
||||
this.handleMcpCall(name, args, (err, result) => {
|
||||
// 3. 构建 MCP 标准响应格式
|
||||
const response = {
|
||||
content: [
|
||||
{
|
||||
@@ -237,42 +233,32 @@ module.exports = {
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// 4. 记录返回日志
|
||||
if (err) {
|
||||
addLog("error", `RES <- [${name}] Failed: ${err}`);
|
||||
} else {
|
||||
// 日志里只显示简短的返回值,防止长 JSON(如 hierarchy)刷屏
|
||||
const logRes = typeof result === "object" ? "[Object Data]" : result;
|
||||
addLog("success", `RES <- [${name}] Success: ${logRes}`);
|
||||
}
|
||||
addLog(err ? "error" : "success", `RES <- [${name}]`);
|
||||
res.writeHead(200);
|
||||
res.end(JSON.stringify(response));
|
||||
});
|
||||
} catch (e) {
|
||||
addLog("error", `Parse Error: ${e.message}`);
|
||||
res.end(JSON.stringify({ content: [{ type: "text", text: `Error: ${e.message}` }] }));
|
||||
addLog("error", `JSON Parse Error: ${e.message}`);
|
||||
res.writeHead(400);
|
||||
res.end(JSON.stringify({ error: "Invalid JSON" }));
|
||||
}
|
||||
} else {
|
||||
res.statusCode = 404;
|
||||
res.end(JSON.stringify({ error: "Not Found" }));
|
||||
}
|
||||
} catch (e) {
|
||||
res.statusCode = 500;
|
||||
res.end(JSON.stringify({ error: e.message }));
|
||||
return;
|
||||
}
|
||||
|
||||
// --- 兜底处理 (404) ---
|
||||
res.writeHead(404);
|
||||
res.end(JSON.stringify({ error: "Not Found", url: url }));
|
||||
});
|
||||
});
|
||||
|
||||
mcpServer.on("error", (e) => {
|
||||
addLog("error", `Server Error: ${e.message}`);
|
||||
});
|
||||
mcpServer.listen(port, () => {
|
||||
serverConfig.active = true;
|
||||
addLog("success", `Server started on port ${port}`);
|
||||
addLog("success", `MCP Server running at http://127.0.0.1:${port}`);
|
||||
Editor.Ipc.sendToPanel("mcp-bridge", "mcp-bridge:state-changed", serverConfig);
|
||||
});
|
||||
|
||||
mcpServer.on("error", (err) => {
|
||||
addLog("error", `Server Error: ${err.message}`);
|
||||
this.stopServer();
|
||||
});
|
||||
// 启动成功后顺便存一下端口
|
||||
this.getProfile().set("last-port", port);
|
||||
this.getProfile().save();
|
||||
|
||||
101
mcp-proxy.js
Normal file
101
mcp-proxy.js
Normal file
@@ -0,0 +1,101 @@
|
||||
const http = require('http');
|
||||
const COCOS_PORT = 3456;
|
||||
|
||||
function debugLog(msg) {
|
||||
process.stderr.write(`[Proxy Debug] ${msg}\n`);
|
||||
}
|
||||
|
||||
process.stdin.on('data', (data) => {
|
||||
const lines = data.toString().split('\n');
|
||||
lines.forEach(line => {
|
||||
if (!line.trim()) return;
|
||||
try {
|
||||
const request = JSON.parse(line);
|
||||
handleRequest(request);
|
||||
} catch (e) {}
|
||||
});
|
||||
});
|
||||
|
||||
function handleRequest(req) {
|
||||
const { method, id, params } = req;
|
||||
|
||||
if (method === 'initialize') {
|
||||
sendToAI({
|
||||
jsonrpc: "2.0", id: id,
|
||||
result: {
|
||||
protocolVersion: "2024-11-05",
|
||||
capabilities: { tools: {} },
|
||||
serverInfo: { name: "cocos-bridge", version: "1.0.0" }
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'tools/list') {
|
||||
// 使用 GET 获取列表
|
||||
forwardToCocos('/list-tools', null, id, 'GET');
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'tools/call') {
|
||||
// 使用 POST 执行工具
|
||||
forwardToCocos('/call-tool', {
|
||||
name: params.name,
|
||||
arguments: params.arguments
|
||||
}, id, 'POST');
|
||||
return;
|
||||
}
|
||||
|
||||
if (id !== undefined) sendToAI({ jsonrpc: "2.0", id: id, result: {} });
|
||||
}
|
||||
|
||||
function forwardToCocos(path, payload, id, method = 'POST') {
|
||||
const postData = payload ? JSON.stringify(payload) : '';
|
||||
|
||||
const options = {
|
||||
hostname: '127.0.0.1',
|
||||
port: COCOS_PORT,
|
||||
path: path,
|
||||
method: method,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
};
|
||||
|
||||
if (postData) {
|
||||
options.headers['Content-Length'] = Buffer.byteLength(postData);
|
||||
}
|
||||
|
||||
const request = http.request(options, (res) => {
|
||||
let resData = '';
|
||||
res.on('data', d => resData += d);
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const cocosRes = JSON.parse(resData);
|
||||
|
||||
// 检查关键字段
|
||||
if (path === '/list-tools' && !cocosRes.tools) {
|
||||
// 如果报错,把 Cocos 返回的所有内容打印到 Trae 的 stderr 日志里
|
||||
debugLog(`CRITICAL: Cocos returned no tools. Received: ${resData}`);
|
||||
sendError(id, -32603, "Invalid Cocos response: missing tools array");
|
||||
} else {
|
||||
sendToAI({ jsonrpc: "2.0", id: id, result: cocosRes });
|
||||
}
|
||||
} catch (e) {
|
||||
debugLog(`JSON Parse Error. Cocos Sent: ${resData}`);
|
||||
sendError(id, -32603, "Cocos returned non-JSON data");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
request.on('error', (e) => {
|
||||
debugLog(`Cocos is offline: ${e.message}`);
|
||||
sendError(id, -32000, "Cocos Plugin Offline");
|
||||
});
|
||||
|
||||
if (postData) request.write(postData);
|
||||
request.end();
|
||||
}
|
||||
|
||||
function sendToAI(obj) { process.stdout.write(JSON.stringify(obj) + '\n'); }
|
||||
function sendError(id, code, message) {
|
||||
sendToAI({ jsonrpc: "2.0", id: id, error: { code, message } });
|
||||
}
|
||||
Reference in New Issue
Block a user