feat: 支持多实例与配置隔离,全面本地化测试面板

- 实现多实例支持:自动扫描可用端口

- 实现项目级配置隔离:配置存储于项目 settings 目录

- 更新测试面板:界面完全汉化,端口显示实时同步

- 本地化:main.js 日志与 IPC 测试模块全面中文化
This commit is contained in:
火焰库拉
2026-02-14 13:08:58 +08:00
parent 24bc7b7b1f
commit 127fc684ca
5 changed files with 805 additions and 627 deletions

View File

@@ -47,6 +47,8 @@
- **端口**: 可以自定义 HTTP 服务监听的端口,默认为 3456 - **端口**: 可以自定义 HTTP 服务监听的端口,默认为 3456
- **自动启动**: 可以设置编辑器启动时自动开启服务 - **自动启动**: 可以设置编辑器启动时自动开启服务
- **多实例支持**: 如果默认端口 (3456) 被占用,插件会自动尝试端口+1 (如 3457),直到找到可用端口。
- **配置隔离**: 插件配置(是否自动启动、上次使用的端口)现已存储在项目目录 (`settings/mcp-bridge.json`) 中,不同项目的配置互不干扰。
## 连接 AI 编辑器 ## 连接 AI 编辑器

572
dist/IpcUi.js vendored
View File

@@ -1,233 +1,353 @@
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter =
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } (this && this.__awaiter) ||
return new (P || (P = Promise))(function (resolve, reject) { function (thisArg, _arguments, P, generator) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function adopt(value) {
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } return value instanceof P
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ? value
step((generator = generator.apply(thisArg, _arguments || [])).next()); : new P(function (resolve) {
}); resolve(value);
}; });
var __generator = (this && this.__generator) || function (thisArg, body) { }
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return new (P || (P = Promise))(function (resolve, reject) {
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function fulfilled(value) {
function verb(n) { return function (v) { return step([n, v]); }; } try {
function step(op) { step(generator.next(value));
if (f) throw new TypeError("Generator is already executing."); } catch (e) {
while (g && (g = 0, op[0] && (_ = 0)), _) try { reject(e);
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; }
if (y = 0, t) op = [op[0] & 2, t.value]; }
switch (op[0]) { function rejected(value) {
case 0: case 1: t = op; break; try {
case 4: _.label++; return { value: op[1], done: false }; step(generator["throw"](value));
case 5: _.label++; y = op[1]; op = [0]; continue; } catch (e) {
case 7: op = _.ops.pop(); _.trys.pop(); continue; reject(e);
default: }
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } function step(result) {
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } }
if (t[2]) _.ops.pop(); step((generator = generator.apply(thisArg, _arguments || [])).next());
_.trys.pop(); continue; });
} };
op = body.call(thisArg, _); var __generator =
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } (this && this.__generator) ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; function (thisArg, body) {
} var _ = {
}; label: 0,
sent: function () {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: [],
},
f,
y,
t,
g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return (
(g.next = verb(0)),
(g["throw"] = verb(1)),
(g["return"] = verb(2)),
typeof Symbol === "function" &&
(g[Symbol.iterator] = function () {
return this;
}),
g
);
function verb(n) {
return function (v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while ((g && ((g = 0), op[0] && (_ = 0)), _))
try {
if (
((f = 1),
y &&
(t =
op[0] & 2
? y["return"]
: op[0]
? y["throw"] || ((t = y["return"]) && t.call(y), 0)
: y.next) &&
!(t = t.call(y, op[1])).done)
)
return t;
if (((y = 0), t)) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (
!((t = _.trys), (t = t.length > 0 && t[t.length - 1])) &&
(op[0] === 6 || op[0] === 2)
) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.IpcUi = void 0; exports.IpcUi = void 0;
// @ts-ignore // @ts-ignore
var Editor = window.Editor; var Editor = window.Editor;
var IpcUi = /** @class */ (function () { var IpcUi = /** @class */ (function () {
function IpcUi(root) { function IpcUi(root) {
this.logArea = null; this.logArea = null;
this.ipcList = null; this.ipcList = null;
this.allMessages = []; this.allMessages = [];
this.filterSelect = null; this.filterSelect = null;
this.paramInput = null; this.paramInput = null;
this.root = root; this.root = root;
this.bindEvents(); this.bindEvents();
} }
IpcUi.prototype.bindEvents = function () { IpcUi.prototype.bindEvents = function () {
var _this = this; var _this = this;
var btnScan = this.root.querySelector("#btnScanIpc"); var btnScan = this.root.querySelector("#btnScanIpc");
var btnTest = this.root.querySelector("#btnTestIpc"); var btnTest = this.root.querySelector("#btnTestIpc");
var cbSelectAll = this.root.querySelector("#cbSelectAllIpc"); var cbSelectAll = this.root.querySelector("#cbSelectAllIpc");
this.logArea = this.root.querySelector("#ipcLog"); this.logArea = this.root.querySelector("#ipcLog");
this.ipcList = this.root.querySelector("#ipcList"); this.ipcList = this.root.querySelector("#ipcList");
this.filterSelect = this.root.querySelector("#ipcFilter"); this.filterSelect = this.root.querySelector("#ipcFilter");
this.paramInput = this.root.querySelector("#ipcParams"); this.paramInput = this.root.querySelector("#ipcParams");
if (btnScan) { if (btnScan) {
btnScan.addEventListener("confirm", function () { return _this.scanMessages(); }); btnScan.addEventListener("confirm", function () {
} return _this.scanMessages();
if (btnTest) { });
btnTest.addEventListener("confirm", function () { return _this.testSelected(); }); }
} if (btnTest) {
if (cbSelectAll) { btnTest.addEventListener("confirm", function () {
cbSelectAll.addEventListener("change", function (e) { return _this.toggleAll(e.detail ? e.detail.value : (e.target.value === 'true' || e.target.checked)); }); return _this.testSelected();
} });
if (this.filterSelect) { }
this.filterSelect.addEventListener("change", function () { return _this.filterMessages(); }); if (cbSelectAll) {
} cbSelectAll.addEventListener("change", function (e) {
}; return _this.toggleAll(e.detail ? e.detail.value : e.target.value === "true" || e.target.checked);
IpcUi.prototype.scanMessages = function () { });
var _this = this; }
this.log("Scanning IPC messages..."); if (this.filterSelect) {
// @ts-ignore this.filterSelect.addEventListener("change", function () {
Editor.Ipc.sendToMain("mcp-bridge:scan-ipc-messages", function (err, msgs) { return _this.filterMessages();
if (err) { });
_this.log("Scan Error: ".concat(err)); }
return; };
} IpcUi.prototype.scanMessages = function () {
if (msgs) { var _this = this;
_this.allMessages = msgs; this.log("正在扫描 IPC 消息...");
_this.filterMessages(); // @ts-ignore
_this.log("Found ".concat(msgs.length, " messages.")); Editor.Ipc.sendToMain("mcp-bridge:scan-ipc-messages", function (err, msgs) {
} if (err) {
else { _this.log("扫描错误: ".concat(err));
_this.log("No messages found."); return;
} }
}); if (msgs) {
}; _this.allMessages = msgs;
IpcUi.prototype.filterMessages = function () { _this.filterMessages();
if (!this.allMessages) _this.log("找到 ".concat(msgs.length, " 条消息。"));
return; } else {
var filter = this.filterSelect ? this.filterSelect.value : "all"; _this.log("未找到任何消息。");
var filtered = this.allMessages; }
if (filter === "available") { });
filtered = this.allMessages.filter(function (m) { return m.status === "可用"; }); };
} IpcUi.prototype.filterMessages = function () {
else if (filter === "unavailable") { if (!this.allMessages) return;
filtered = this.allMessages.filter(function (m) { return m.status && m.status.includes("不可用"); }); var filter = this.filterSelect ? this.filterSelect.value : "all";
} var filtered = this.allMessages;
else if (filter === "untested") { if (filter === "available") {
filtered = this.allMessages.filter(function (m) { return !m.status || m.status === "未测试"; }); filtered = this.allMessages.filter(function (m) {
} return m.status === "可用";
this.renderList(filtered); });
}; } else if (filter === "unavailable") {
IpcUi.prototype.renderList = function (msgs) { filtered = this.allMessages.filter(function (m) {
var _this = this; return m.status && m.status.includes("不可用");
if (!this.ipcList) });
return; } else if (filter === "untested") {
this.ipcList.innerHTML = ""; filtered = this.allMessages.filter(function (m) {
msgs.forEach(function (msg) { return !m.status || m.status === "未测试";
var item = document.createElement("div"); });
item.className = "ipc-item"; }
item.style.padding = "4px"; this.renderList(filtered);
item.style.borderBottom = "1px solid #333"; };
item.style.display = "flex"; IpcUi.prototype.renderList = function (msgs) {
item.style.alignItems = "center"; var _this = this;
// Checkbox if (!this.ipcList) return;
var checkbox = document.createElement("ui-checkbox"); this.ipcList.innerHTML = "";
// @ts-ignore msgs.forEach(function (msg) {
checkbox.value = false; var item = document.createElement("div");
checkbox.setAttribute("data-name", msg.name); item.className = "ipc-item";
checkbox.style.marginRight = "8px"; item.style.padding = "4px";
// Content item.style.borderBottom = "1px solid #333";
var content = document.createElement("div"); item.style.display = "flex";
content.style.flex = "1"; item.style.alignItems = "center";
content.style.fontSize = "11px"; // Checkbox
var statusColor = "#888"; // Untested var checkbox = document.createElement("ui-checkbox");
if (msg.status === "可用") // @ts-ignore
statusColor = "#4CAF50"; // Green checkbox.value = false;
else if (msg.status && msg.status.includes("不可用")) checkbox.setAttribute("data-name", msg.name);
statusColor = "#F44336"; // Red checkbox.style.marginRight = "8px";
content.innerHTML = "\n <div style=\"display:flex; justify-content:space-between;\">\n <span style=\"color: #4CAF50; font-weight: bold;\">".concat(msg.name, "</span>\n <span style=\"color: ").concat(statusColor, "; font-size: 10px; border: 1px solid ").concat(statusColor, "; padding: 0 4px; border-radius: 4px;\">").concat(msg.status || "未测试", "</span>\n </div>\n <div style=\"color: #888;\">").concat(msg.description || "No desc", "</div>\n <div style=\"color: #666; font-size: 10px;\">Params: ").concat(msg.params || "None", "</div>\n "); // Content
// Action Button var content = document.createElement("div");
var btnRun = document.createElement("ui-button"); content.style.flex = "1";
btnRun.innerText = "Run"; content.style.fontSize = "11px";
btnRun.className = "tiny"; var statusColor = "#888"; // Untested
btnRun.style.height = "20px"; if (msg.status === "可用")
btnRun.style.lineHeight = "20px"; statusColor = "#4CAF50"; // Green
btnRun.addEventListener("confirm", function () { else if (msg.status && msg.status.includes("不可用")) statusColor = "#F44336"; // Red
_this.runTest(msg.name); content.innerHTML =
}); '\n <div style="display:flex; justify-content:space-between;">\n <span style="color: #4CAF50; font-weight: bold;">'
item.appendChild(checkbox); .concat(msg.name, '</span>\n <span style="color: ')
item.appendChild(content); .concat(statusColor, "; font-size: 10px; border: 1px solid ")
item.appendChild(btnRun); .concat(statusColor, '; padding: 0 4px; border-radius: 4px;">')
_this.ipcList.appendChild(item); .concat(
}); msg.status || "未测试",
}; '</span>\n </div>\n <div style="color: #888;">',
IpcUi.prototype.testSelected = function () { )
return __awaiter(this, void 0, void 0, function () { .concat(
var checkboxes, toTest, _i, toTest_1, name_1; msg.description || "无描述",
return __generator(this, function (_a) { '</div>\n <div style="color: #666; font-size: 10px;">参数: ',
switch (_a.label) { )
case 0: .concat(msg.params || "无", "</div>\n ");
checkboxes = this.root.querySelectorAll("#ipcList ui-checkbox"); // Action Button
toTest = []; var btnRun = document.createElement("ui-button");
checkboxes.forEach(function (cb) { btnRun.innerText = "执行";
// In Cocos 2.x, ui-checkbox value is boolean btnRun.className = "tiny";
if (cb.checked || cb.value === true) { btnRun.style.height = "20px";
toTest.push(cb.getAttribute("data-name")); btnRun.style.lineHeight = "20px";
} btnRun.addEventListener("confirm", function () {
}); _this.runTest(msg.name);
if (toTest.length === 0) { });
this.log("No messages selected."); item.appendChild(checkbox);
return [2 /*return*/]; item.appendChild(content);
} item.appendChild(btnRun);
this.log("Starting batch test for ".concat(toTest.length, " messages...")); _this.ipcList.appendChild(item);
_i = 0, toTest_1 = toTest; });
_a.label = 1; };
case 1: IpcUi.prototype.testSelected = function () {
if (!(_i < toTest_1.length)) return [3 /*break*/, 4]; return __awaiter(this, void 0, void 0, function () {
name_1 = toTest_1[_i]; var checkboxes, toTest, _i, toTest_1, name_1;
return [4 /*yield*/, this.runTest(name_1)]; return __generator(this, function (_a) {
case 2: switch (_a.label) {
_a.sent(); case 0:
_a.label = 3; checkboxes = this.root.querySelectorAll("#ipcList ui-checkbox");
case 3: toTest = [];
_i++; checkboxes.forEach(function (cb) {
return [3 /*break*/, 1]; // In Cocos 2.x, ui-checkbox value is boolean
case 4: if (cb.checked || cb.value === true) {
this.log("Batch test completed."); toTest.push(cb.getAttribute("data-name"));
return [2 /*return*/]; }
} });
}); if (toTest.length === 0) {
}); this.log("未选择任何消息。");
}; return [2 /*return*/];
IpcUi.prototype.runTest = function (name) { }
var _this = this; this.log("开始批量测试 ".concat(toTest.length, " 条消息..."));
return new Promise(function (resolve) { ((_i = 0), (toTest_1 = toTest));
var params = null; _a.label = 1;
if (_this.paramInput && _this.paramInput.value.trim()) { case 1:
try { if (!(_i < toTest_1.length)) return [3 /*break*/, 4];
params = JSON.parse(_this.paramInput.value.trim()); name_1 = toTest_1[_i];
} return [4 /*yield*/, this.runTest(name_1)];
catch (e) { case 2:
_this.log("[Error] Invalid JSON Params: ".concat(e)); _a.sent();
resolve(); _a.label = 3;
return; case 3:
} _i++;
} return [3 /*break*/, 1];
_this.log("Testing: ".concat(name, " with params: ").concat(JSON.stringify(params), "...")); case 4:
// @ts-ignore this.log("批量测试完成。");
Editor.Ipc.sendToMain("mcp-bridge:test-ipc-message", { name: name, params: params }, function (err, result) { return [2 /*return*/];
if (err) { }
_this.log("[".concat(name, "] Failed: ").concat(err)); });
} });
else { };
_this.log("[".concat(name, "] Success: ").concat(JSON.stringify(result))); IpcUi.prototype.runTest = function (name) {
} var _this = this;
resolve(); return new Promise(function (resolve) {
}); var params = null;
}); if (_this.paramInput && _this.paramInput.value.trim()) {
}; try {
IpcUi.prototype.toggleAll = function (checked) { params = JSON.parse(_this.paramInput.value.trim());
var checkboxes = this.root.querySelectorAll("#ipcList ui-checkbox"); } catch (e) {
checkboxes.forEach(function (cb) { _this.log("[错误] 无效的 JSON 参数: ".concat(e));
cb.value = checked; resolve();
}); return;
}; }
IpcUi.prototype.log = function (msg) { }
if (this.logArea) { _this.log("正在测试: ".concat(name, ",参数: ").concat(JSON.stringify(params), "..."));
// @ts-ignore // @ts-ignore
var time = new Date().toLocaleTimeString(); Editor.Ipc.sendToMain(
this.logArea.value += "[".concat(time, "] ").concat(msg, "\n"); "mcp-bridge:test-ipc-message",
this.logArea.scrollTop = this.logArea.scrollHeight; { name: name, params: params },
} function (err, result) {
}; if (err) {
return IpcUi; _this.log("[".concat(name, "] 失败: ").concat(err));
}()); } else {
_this.log("[".concat(name, "] 成功: ").concat(JSON.stringify(result)));
}
resolve();
},
);
});
};
IpcUi.prototype.toggleAll = function (checked) {
var checkboxes = this.root.querySelectorAll("#ipcList ui-checkbox");
checkboxes.forEach(function (cb) {
cb.value = checked;
});
};
IpcUi.prototype.log = function (msg) {
if (this.logArea) {
// @ts-ignore
var time = new Date().toLocaleTimeString();
this.logArea.value += "[".concat(time, "] ").concat(msg, "\n");
this.logArea.scrollTop = this.logArea.scrollHeight;
}
};
return IpcUi;
})();
exports.IpcUi = IpcUi; exports.IpcUi = IpcUi;

279
main.js
View File

@@ -704,8 +704,8 @@ module.exports = {
* @returns {Object} Editor.Profile 实例 * @returns {Object} Editor.Profile 实例
*/ */
getProfile() { getProfile() {
// 'local' 表示存储在项目本地(local/mcp-bridge.json // 'project' 表示存储在项目本地(settings/mcp-bridge.json,实现配置隔离
return Editor.Profile.load("profile://local/mcp-bridge.json", "mcp-bridge"); return Editor.Profile.load("profile://project/mcp-bridge.json", "mcp-bridge");
}, },
/** /**
@@ -721,139 +721,161 @@ module.exports = {
startServer(port) { startServer(port) {
if (mcpServer) this.stopServer(); if (mcpServer) this.stopServer();
try { const tryStart = (currentPort, retries) => {
mcpServer = http.createServer((req, res) => { if (retries <= 0) {
res.setHeader("Content-Type", "application/json"); addLog("error", `Failed to find an available port after multiple attempts.`);
res.setHeader("Access-Control-Allow-Origin", "*"); return;
}
let body = ""; try {
req.on("data", (chunk) => { mcpServer = http.createServer((req, res) => {
body += chunk; this._handleRequest(req, res);
}); });
req.on("end", () => {
const url = req.url; mcpServer.on("error", (e) => {
if (url === "/list-tools") { if (e.code === "EADDRINUSE") {
const tools = getToolsList(); addLog("warn", `Port ${currentPort} is in use, trying ${currentPort + 1}...`);
addLog("info", `AI Client requested tool list`);
// 明确返回成功结构
res.writeHead(200);
return res.end(JSON.stringify({ tools: tools }));
}
if (url === "/list-resources") {
const resources = this.getResourcesList();
addLog("info", `AI Client requested resource list`);
res.writeHead(200);
return res.end(JSON.stringify({ resources: resources }));
}
if (url === "/read-resource") {
try { try {
const { uri } = JSON.parse(body || "{}"); mcpServer.close();
addLog("mcp", `READ -> [${uri}]`); } catch (err) {
this.handleReadResource(uri, (err, content) => { // align
if (err) { }
addLog("error", `读取失败: ${err}`); mcpServer = null;
res.writeHead(500); // Delay slightly to ensure cleanup
return res.end(JSON.stringify({ error: err })); setTimeout(() => {
} tryStart(currentPort + 1, retries - 1);
addLog("success", `读取成功: ${uri}`); }, 100);
res.writeHead(200); } else {
// 返回 MCP Resource 格式: { contents: [{ uri, mimeType, text }] } addLog("error", `Server Error: ${e.message}`);
res.end( }
JSON.stringify({ });
contents: [
{ mcpServer.listen(currentPort, () => {
uri: uri, serverConfig.active = true;
mimeType: "application/json", serverConfig.port = currentPort;
text: typeof content === "string" ? content : JSON.stringify(content), addLog("success", `MCP Server running at http://127.0.0.1:${currentPort}`);
}, Editor.Ipc.sendToPanel("mcp-bridge", "mcp-bridge:state-changed", serverConfig);
],
}), // Important: Do NOT save the auto-assigned port to profile to avoid pollution
); });
}); } catch (e) {
} catch (e) { addLog("error", `Failed to start server: ${e.message}`);
}
};
// Start trying from the configured port, retry 10 times
tryStart(port, 10);
},
_handleRequest(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 === "/list-resources") {
const resources = this.getResourcesList();
addLog("info", `AI Client requested resource list`);
res.writeHead(200);
return res.end(JSON.stringify({ resources: resources }));
}
if (url === "/read-resource") {
try {
const { uri } = JSON.parse(body || "{}");
addLog("mcp", `READ -> [${uri}]`);
this.handleReadResource(uri, (err, content) => {
if (err) {
addLog("error", `读取失败: ${err}`);
res.writeHead(500); res.writeHead(500);
res.end(JSON.stringify({ error: e.message })); return res.end(JSON.stringify({ error: err }));
} }
return; addLog("success", `读取成功: ${uri}`);
} res.writeHead(200);
if (url === "/call-tool") { res.end(
try { JSON.stringify({
const { name, arguments: args } = JSON.parse(body || "{}"); contents: [
addLog("mcp", `REQ -> [${name}] (队列长度: ${commandQueue.length})`); {
uri: uri,
mimeType: "application/json",
text: typeof content === "string" ? content : JSON.stringify(content),
},
],
}),
);
});
} catch (e) {
res.writeHead(500);
res.end(JSON.stringify({ error: e.message }));
}
return;
}
if (url === "/call-tool") {
try {
const { name, arguments: args } = JSON.parse(body || "{}");
addLog("mcp", `REQ -> [${name}] (队列长度: ${commandQueue.length})`);
// 【关键修复】所有 MCP 指令通过队列串行化执行, enqueueCommand((done) => {
// 防止 AssetDB.refresh 等异步操作被并发请求打断导致编辑器卡死 this.handleMcpCall(name, args, (err, result) => {
enqueueCommand((done) => { const response = {
this.handleMcpCall(name, args, (err, result) => { content: [
const response = { {
content: [ type: "text",
{ text: err
type: "text", ? `Error: ${err}`
text: err : typeof result === "object"
? `Error: ${err}` ? JSON.stringify(result, null, 2)
: typeof result === "object" : result,
? JSON.stringify(result, null, 2) },
: result, ],
}, };
], if (err) {
}; addLog("error", `RES <- [${name}] 失败: ${err}`);
if (err) {
addLog("error", `RES <- [${name}] 失败: ${err}`);
} else {
// 成功时尝试捕获简单的结果预览(如果是字符串或简短对象)
let preview = "";
if (typeof result === "string") {
preview = result.length > 100 ? result.substring(0, 100) + "..." : result;
} else if (typeof result === "object") {
try {
const jsonStr = JSON.stringify(result);
preview =
jsonStr.length > 100 ? jsonStr.substring(0, 100) + "..." : jsonStr;
} catch (e) {
preview = "Object (Circular/Unserializable)";
}
}
addLog("success", `RES <- [${name}] 成功 : ${preview}`);
}
res.writeHead(200);
res.end(JSON.stringify(response));
done(); // 当前指令完成,释放队列给下一个指令
});
});
} catch (e) {
if (e instanceof SyntaxError) {
addLog("error", `JSON Parse Error: ${e.message}`);
res.writeHead(400);
res.end(JSON.stringify({ error: "Invalid JSON" }));
} else { } else {
addLog("error", `Internal Server Error: ${e.message}`); let preview = "";
res.writeHead(500); if (typeof result === "string") {
res.end(JSON.stringify({ error: e.message })); preview = result.length > 100 ? result.substring(0, 100) + "..." : result;
} else if (typeof result === "object") {
try {
const jsonStr = JSON.stringify(result);
preview = jsonStr.length > 100 ? jsonStr.substring(0, 100) + "..." : jsonStr;
} catch (e) {
preview = "Object (Circular/Unserializable)";
}
}
addLog("success", `RES <- [${name}] 成功 : ${preview}`);
} }
} res.writeHead(200);
return; res.end(JSON.stringify(response));
done();
});
});
} catch (e) {
if (e instanceof SyntaxError) {
addLog("error", `JSON Parse Error: ${e.message}`);
res.writeHead(400);
res.end(JSON.stringify({ error: "Invalid JSON" }));
} else {
addLog("error", `Internal Server Error: ${e.message}`);
res.writeHead(500);
res.end(JSON.stringify({ error: e.message }));
} }
}
return;
}
// --- 兜底处理 (404) --- res.writeHead(404);
res.writeHead(404); res.end(JSON.stringify({ error: "Not Found", url: url }));
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", `MCP Server running at http://127.0.0.1:${port}`);
Editor.Ipc.sendToPanel("mcp-bridge", "mcp-bridge:state-changed", serverConfig);
});
// 启动成功后顺便存一下端口
this.getProfile().set("last-port", port);
this.getProfile().save();
} catch (e) {
addLog("error", `Failed to start server: ${e.message}`);
}
}, },
/** /**
@@ -2273,7 +2295,12 @@ CCProgram fs %{
"toggle-server"(event, port) { "toggle-server"(event, port) {
if (serverConfig.active) this.stopServer(); if (serverConfig.active) this.stopServer();
else this.startServer(port); else {
// 用户手动启动时,保存偏好端口
this.getProfile().set("last-port", port);
this.getProfile().save();
this.startServer(port);
}
}, },
"clear-logs"() { "clear-logs"() {
logBuffer = []; logBuffer = [];

View File

@@ -1,316 +1,340 @@
<div class="mcp-container"> <div class="mcp-container">
<div class="tabs"> <div class="tabs">
<ui-button id="tabMain" class="tab-button active">Main</ui-button> <ui-button id="tabMain" class="tab-button active">主页</ui-button>
<ui-button id="tabTest" class="tab-button">Tool Test</ui-button> <ui-button id="tabTest" class="tab-button">工具测试</ui-button>
<ui-button id="tabIpc" class="tab-button">IPC Test</ui-button> <ui-button id="tabIpc" class="tab-button">IPC 测试</ui-button>
</div> </div>
<div id="panelMain" class="tab-content active"> <div id="panelMain" class="tab-content active">
<div class="toolbar"> <div class="toolbar">
<div class="ctrl-group"> <div class="ctrl-group">
<span>Port:</span> <span>端口:</span>
<ui-input id="portInput" style="width: 60px;"></ui-input> <ui-input id="portInput" style="width: 60px"></ui-input>
<ui-button id="btnToggle">Start</ui-button> <ui-button id="btnToggle">启动</ui-button>
</div> </div>
<div class="ctrl-group" style="margin-left: 10px"> <div class="ctrl-group" style="margin-left: 10px">
<ui-checkbox id="autoStartCheck">Auto Start</ui-checkbox> <ui-checkbox id="autoStartCheck">自动启动</ui-checkbox>
</div> </div>
<div class="spacer"></div> <div class="spacer"></div>
<ui-button id="btnClear" class="transparent">Clear</ui-button> <ui-button id="btnClear" class="transparent">清空日志</ui-button>
<ui-button id="btnCopy" class="transparent">Copy All</ui-button> <ui-button id="btnCopy" class="transparent">复制全部</ui-button>
</div> </div>
<div id="logConsole" class="log-view"></div> <div id="logConsole" class="log-view"></div>
</div> </div>
<div id="panelTest" class="tab-content"> <div id="panelTest" class="tab-content">
<!-- ... existing content ... --> <!-- ... existing content ... -->
<div class="test-layout"> <div class="test-layout">
<div class="left-panel" id="testLeftPanel"> <div class="left-panel" id="testLeftPanel">
<div class="form-item"> <div class="form-item">
<label>工具名称:</label> <label>工具名称:</label>
<ui-input id="toolName" placeholder="选中下方列表填充"></ui-input> <ui-input id="toolName" placeholder="选中下方列表填充"></ui-input>
</div> </div>
<label>可用工具列表:</label> <label>可用工具列表:</label>
<div class="tools-list" id="toolsList"></div> <div class="tools-list" id="toolsList"></div>
</div> </div>
<!-- 拖动条 --> <!-- 拖动条 -->
<div class="resizer" id="testResizer"></div> <div class="resizer" id="testResizer"></div>
<div class="right-panel"> <div class="right-panel">
<div class="tool-description"> <div class="tool-description">
<label>工具说明:</label> <label>工具说明:</label>
<div id="toolDescription" class="description-box">选择工具查看说明</div> <div id="toolDescription" class="description-box">选择工具查看说明</div>
</div> </div>
<div class="flex-v"> <div class="flex-v">
<label>工具参数 (JSON):</label> <label>工具参数 (JSON):</label>
<textarea id="toolParams" spellcheck="false" placeholder='{}'></textarea> <textarea id="toolParams" spellcheck="false" placeholder="{}"></textarea>
</div> </div>
<div class="button-group"> <div class="button-group">
<ui-button id="testBtn" class="green">测试工具</ui-button> <ui-button id="testBtn" class="green">测试工具</ui-button>
<ui-button id="listToolsBtn">刷新列表</ui-button> <ui-button id="listToolsBtn">刷新列表</ui-button>
<ui-button id="clearTestBtn">清空结果</ui-button> <ui-button id="clearTestBtn">清空结果</ui-button>
<ui-button id="probeApisBtn">探查 API</ui-button> <ui-button id="probeApisBtn">探查 API</ui-button>
</div> </div>
<div class="flex-v"> <div class="flex-v">
<label>测试结果:</label> <label>测试结果:</label>
<textarea id="resultContent" readonly spellcheck="false"></textarea> <textarea id="resultContent" readonly spellcheck="false"></textarea>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div id="panelIpc" class="tab-content"> <div id="panelIpc" class="tab-content">
<div class="toolbar"> <div class="toolbar">
<ui-button id="btnScanIpc">Scan Messages</ui-button> <ui-button id="btnScanIpc">扫描消息</ui-button>
<select id="ipcFilter" <select
style="margin-left: 5px; background: #333; color: #ccc; border: 1px solid #555; height: 25px;"> id="ipcFilter"
<option value="all">Check All</option> style="margin-left: 5px; background: #333; color: #ccc; border: 1px solid #555; height: 25px"
<option value="available">Show Available</option> >
<option value="unavailable">Show Unavailable</option> <option value="all">全部显示</option>
<option value="untested">Show Untested</option> <option value="available">仅显示可用</option>
</select> <option value="unavailable">仅显示不可用</option>
<div class="spacer"></div> <option value="untested">仅显示未测试</option>
<ui-button id="btnTestIpc" class="green">Test Selected</ui-button> </select>
</div> <div class="spacer"></div>
<div class="ipc-container" style="display:flex; flex:1; flex-direction:column; min-height:0;"> <ui-button id="btnTestIpc" class="green">测试选中项</ui-button>
<div class="ipc-list-header" style="padding: 5px; background: #222; border-bottom: 1px solid #444;"> </div>
<ui-checkbox id="cbSelectAllIpc">Select All/None</ui-checkbox> <div class="ipc-container" style="display: flex; flex: 1; flex-direction: column; min-height: 0">
</div> <div class="ipc-list-header" style="padding: 5px; background: #222; border-bottom: 1px solid #444">
<div id="ipcList" class="ipc-list" <ui-checkbox id="cbSelectAllIpc">全选/反选</ui-checkbox>
style="flex:1; overflow-y:auto; background: #1e1e1e; border: 1px solid #444;"></div> </div>
<div style="padding: 5px; border-top: 1px solid #444; display: flex; flex-direction: column;"> <div
<label>Parameters (JSON):</label> id="ipcList"
<textarea id="ipcParams" placeholder='e.g. {"uuid": "..."}' class="ipc-list"
style="height: 50px; width: 100%; box-sizing: border-box; background: #222; color: #ccc; border: 1px solid #444; margin-bottom: 5px;"></textarea> style="flex: 1; overflow-y: auto; background: #1e1e1e; border: 1px solid #444"
</div> ></div>
<div <div style="padding: 5px; border-top: 1px solid #444; display: flex; flex-direction: column">
style="height: 100px; display:flex; flex-direction:column; border-top: 1px solid #444; padding-top: 5px;"> <label>参数 (JSON):</label>
<label>Test Log:</label> <textarea
<textarea id="ipcLog" readonly style="flex:1; font-family:monospace; font-size:10px;"></textarea> id="ipcParams"
</div> placeholder='例如: {"uuid": "..."}'
</div> style="
</div> height: 50px;
width: 100%;
box-sizing: border-box;
background: #222;
color: #ccc;
border: 1px solid #444;
margin-bottom: 5px;
"
></textarea>
</div>
<div
style="
height: 100px;
display: flex;
flex-direction: column;
border-top: 1px solid #444;
padding-top: 5px;
"
>
<label>测试日志:</label>
<textarea id="ipcLog" readonly style="flex: 1; font-family: monospace; font-size: 10px"></textarea>
</div>
</div>
</div>
</div> </div>
<style> <style>
:host { :host {
height: 100%; height: 100%;
display: flex; display: flex;
background-color: #2d2d2d; background-color: #2d2d2d;
overflow: hidden; overflow: hidden;
} }
.mcp-container { .mcp-container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
width: 100%; width: 100%;
height: 100%; height: 100%;
padding: 5px; padding: 5px;
box-sizing: border-box; box-sizing: border-box;
} }
.tabs { .tabs {
display: flex; display: flex;
border-bottom: 1px solid #444; border-bottom: 1px solid #444;
margin-bottom: 5px; margin-bottom: 5px;
flex-shrink: 0; flex-shrink: 0;
} }
.tab-button { .tab-button {
padding: 4px 12px; padding: 4px 12px;
margin-right: 2px; margin-right: 2px;
background: #333; background: #333;
} }
.tab-button.active { .tab-button.active {
background: #4CAF50; background: #4caf50;
color: white; color: white;
} }
.tab-content { .tab-content {
display: none; display: none;
flex: 1; flex: 1;
flex-direction: column; flex-direction: column;
min-height: 0; min-height: 0;
overflow: hidden; overflow: hidden;
} }
.tab-content.active { .tab-content.active {
display: flex; display: flex;
} }
/* Main Panel */ /* Main Panel */
.toolbar { .toolbar {
display: flex; display: flex;
align-items: center; align-items: center;
padding: 5px 0; padding: 5px 0;
gap: 5px; gap: 5px;
flex-shrink: 0; flex-shrink: 0;
} }
.spacer { .spacer {
flex: 1; flex: 1;
} }
.log-view { .log-view {
flex: 1; flex: 1;
background: #1a1a1a; background: #1a1a1a;
margin-top: 5px; margin-top: 5px;
overflow-y: auto; overflow-y: auto;
padding: 8px; padding: 8px;
font-family: monospace; font-family: monospace;
font-size: 11px; font-size: 11px;
-webkit-user-select: text; -webkit-user-select: text;
min-height: 0; user-select: text;
} min-height: 0;
}
.log-item { .log-item {
border-left: 4px solid #555; border-left: 4px solid #555;
padding-left: 8px; padding-left: 8px;
margin-bottom: 3px; margin-bottom: 3px;
white-space: pre-wrap; white-space: pre-wrap;
word-break: break-all; word-break: break-all;
} }
.log-item.info { .log-item.info {
border-left-color: #61afef; border-left-color: #61afef;
color: #abb2bf; color: #abb2bf;
} }
.log-item.success { .log-item.success {
border-left-color: #98c379; border-left-color: #98c379;
color: #98c379; color: #98c379;
} }
.log-item.warn { .log-item.warn {
border-left-color: #e5c07b; border-left-color: #e5c07b;
color: #e5c07b; color: #e5c07b;
} }
.log-item.error { .log-item.error {
border-left-color: #e06c75; border-left-color: #e06c75;
color: #e06c75; color: #e06c75;
} }
.log-item.mcp { .log-item.mcp {
border-left-color: #c678dd; border-left-color: #c678dd;
color: #d19a66; color: #d19a66;
background: rgba(198, 120, 221, 0.05); background: rgba(198, 120, 221, 0.05);
} }
.time { .time {
color: #5c6370; color: #5c6370;
margin-right: 8px; margin-right: 8px;
} }
/* Test Panel */ /* Test Panel */
.test-layout { .test-layout {
display: flex; display: flex;
flex: 1; flex: 1;
min-height: 0; min-height: 0;
} }
.left-panel { .left-panel {
width: 250px; width: 250px;
min-width: 150px; min-width: 150px;
max-width: 500px; max-width: 500px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
flex-shrink: 0; flex-shrink: 0;
min-height: 0; min-height: 0;
} }
.resizer { .resizer {
width: 6px; width: 6px;
cursor: col-resize; cursor: col-resize;
background: #1a1a1a; background: #1a1a1a;
flex-shrink: 0; flex-shrink: 0;
} }
.resizer:hover { .resizer:hover {
background: #4CAF50; background: #4caf50;
} }
.right-panel { .right-panel {
flex: 1; flex: 1;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
min-width: 0; min-width: 0;
padding-left: 5px; padding-left: 5px;
} }
.tools-list { .tools-list {
flex: 1; flex: 1;
background: #222; background: #222;
border: 1px solid #444; border: 1px solid #444;
overflow-y: auto; overflow-y: auto;
margin-top: 5px; margin-top: 5px;
} }
.tool-item { .tool-item {
padding: 6px; padding: 6px;
border-bottom: 1px solid #333; border-bottom: 1px solid #333;
cursor: pointer; cursor: pointer;
font-size: 11px; font-size: 11px;
} }
.tool-item:hover { .tool-item:hover {
background: #444; background: #444;
} }
.flex-v { .flex-v {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
flex: 1; flex: 1;
min-height: 0; min-height: 0;
} }
textarea { textarea {
width: 100%; width: 100%;
background: #222; background: #222;
color: #ccc; color: #ccc;
border: 1px solid #444; border: 1px solid #444;
padding: 5px; padding: 5px;
font-family: monospace; font-family: monospace;
resize: none; resize: none;
} }
#toolParams { #toolParams {
height: 120px; height: 120px;
flex-shrink: 0; flex-shrink: 0;
} }
#resultContent { #resultContent {
flex: 1; flex: 1;
} }
.button-group { .button-group {
display: flex; display: flex;
gap: 5px; gap: 5px;
padding: 5px 0; padding: 5px 0;
} }
label { label {
font-size: 11px; font-size: 11px;
color: #888; color: #888;
margin: 4px 0; margin: 4px 0;
} }
.tool-description { .tool-description {
margin-bottom: 10px; margin-bottom: 10px;
} }
.description-box { .description-box {
background: #222; background: #222;
color: #ccc; color: #ccc;
border: 1px solid #444; border: 1px solid #444;
padding: 8px; padding: 8px;
font-size: 11px; font-size: 11px;
line-height: 1.4; line-height: 1.4;
min-height: 60px; min-height: 60px;
max-height: 120px; max-height: 120px;
overflow-y: auto; overflow-y: auto;
border-radius: 2px; border-radius: 2px;
} }
</style> </style>

View File

@@ -39,6 +39,11 @@ Editor.Panel.extend({
*/ */
"mcp-bridge:state-changed"(event, config) { "mcp-bridge:state-changed"(event, config) {
this.updateUI(config.active); this.updateUI(config.active);
// 如果服务器已启动,更新面板显示的端口为实际运行端口
if (config.active && config.port) {
const portInput = this.shadowRoot.querySelector("#portInput");
if (portInput) portInput.value = config.port;
}
}, },
}, },