From 39de03001d399ed878bf074d67f4bcb581e56624 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 12:25:16 +0800 Subject: [PATCH] page-chat 0.1.6: one switch uses every MCP server in magpie's Library (Magiczerowxy/magpie-chat#4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ferocknew asked for a way to give new chats every MCP server without ticking each one. The MCP list in the settings sidebar now starts with a switch, "使用 magpie 的全部 MCP 服务器". On, a chat uses every server in library.json, read again on each chat, so a server added to magpie later is in too; the rows show checked and disabled. Off (the default, and what a 0.1.5 settings.json reads as), ticking works as before, and the ticks set before turning it on come back. The whole path: the setting is mcpAll in the service's settings (cleanSettings keeps it, default false). runChat wants tools when mcpAll is on even with nothing ticked, and pickServers() picks every Library server; "检查连接" (/api/mcp/tools) checks the same set. The page sends useTools when mcpAll is on. The service picks servers from the saved settings, while the page saves them 320ms after a change, so send() now saves pending settings before /api/chat; a switch flipped just before sending (or a server just ticked) counts. Run (mote, bun 1.4.2, HOME a temp dir): bun test chat.test.mjs, 28 pass; bun scripts/check.mjs chat ok. Three new tests: a chat against two fake Streamable-HTTP MCP servers gets only the ticked one with the switch off, both with it on and nothing ticked, a third added to library.json after turning it on, and /api/mcp/tools lists all three; a 0.1.5 settings.json reads as off; the page's wantsTools and the save-before-send. Broken by hand: pickServers ignoring mcpAll fails the first two tests; cleanSettings dropping mcpAll fails the same two; useTools back to "mcp ticked" fails the third. Real page, Playwright 1.62.0, 1200 and 760 wide: switch off by default with the old tick, on makes every row checked and disabled, flipping it and pressing Enter saves settings before /api/chat with useTools true, still on after reload, off brings back the old tick, rows clickable. Chromium on mote, 18 of 18; WebKit on Linux (WSL magpie-desktop), 18 of 18, since WebKit on mote didn't launch within 180s (other sessions' WebKit processes were running there). Not tried: a real magpie window with real MCP servers and a real model call (the gateway in the browser run was absent; tool lists came from fakes); stdio servers under the switch (same pick, only http was run); macOS WebKit; languages other than Chinese (the page has no i18n). --- packages/chat/README.md | 2 +- packages/chat/chat.test.mjs | 100 ++++++++++++++++++++++++++++++++++ packages/chat/chat/app.js | 40 +++++++++++--- packages/chat/chat/index.html | 4 ++ packages/chat/chat/style.css | 5 ++ packages/chat/lib/server.mjs | 16 +++++- packages/chat/package.json | 2 +- 7 files changed, 157 insertions(+), 12 deletions(-) diff --git a/packages/chat/README.md b/packages/chat/README.md index 2fe95c6..814c6d8 100644 --- a/packages/chat/README.md +++ b/packages/chat/README.md @@ -19,7 +19,7 @@ It then has a tab, **Chat** (对话, 對話, チャット), under Plugins in the ## What it does - **magpie's models.** The list comes from the gateway's `/v1/models`. Models with reasoning levels get an effort picker. Each model shows its brand icon (OpenAI, Claude, Gemini, DeepSeek, Qwen, Kimi, GLM, MiniMax and more) in the picker and next to its name in the transcript. The icons come from [@lobehub/icons](https://github.com/lobehub/lobe-icons) (MIT); see `chat/icons/models/NOTICE`. -- **magpie's library.** Tick instructions and skills from `~/.config/magpie/library/` (folded into the system prompt), and MCP servers from `library.json` (their tools run as real `tool_calls`, at most 8 rounds, Streamable HTTP and stdio). +- **magpie's library.** Tick instructions and skills from `~/.config/magpie/library/` (folded into the system prompt), and MCP servers from `library.json` (their tools run as real `tool_calls`, at most 8 rounds, Streamable HTTP and stdio). The switch "使用 magpie 的全部 MCP 服务器" at the top of the MCP list uses every server in the library instead, one added to magpie later too; it is off by default, and turning it off brings back the servers you ticked. - **Images and files.** Pick, drop or paste them. Images go to the model as `image_url`. Replies can carry base64 data-URI images, which render inline and open full size on click. Remote `![alt](https://…)` images are shown as a link instead of being loaded — fetching them automatically would let a reply make the page request an arbitrary URL. - **Streaming.** Reasoning unfolds while it arrives, then collapses. While the answer streams, the page follows it down unless you scroll up yourself; scroll back to the bottom and it resumes. - **Model status.** Every reply ends with a line saying what the model is doing: `Magpie正在觅食ing… · 2s` with a running timer while it generates, green `Magpie找到了食物! · 2s` when done, red `Magpie没有找到食物` on failure. The elapsed time is kept with the conversation. diff --git a/packages/chat/chat.test.mjs b/packages/chat/chat.test.mjs index 763588f..3d7f094 100644 --- a/packages/chat/chat.test.mjs +++ b/packages/chat/chat.test.mjs @@ -55,6 +55,9 @@ afterAll(async () => { // node:http, so the test sets Host and Origin exactly as a hostile page would function raw(method, path, headers = {}, body) { + return rawOn(port, method, path, headers, body) +} +function rawOn(port, method, path, headers = {}, body) { return new Promise((resolve, reject) => { const req = request({ host: "127.0.0.1", port, method, path, headers: { host: `127.0.0.1:${port}`, ...headers } }, (res) => { let data = "" @@ -361,3 +364,100 @@ test("finish() renders a reply that arrived in one chunk", () => { // 不能只判 .md-stable:整段一次到达时那个结构根本不存在 expect(app).toMatch(/else if \(refs\.body && refs\.msg\.content\) renderMarkdown\(refs\.body, refs\.msg\.content\)/) }) + +// ---------- 0.1.6: one switch for every MCP server in magpie's Library ---------- + +// a Streamable-HTTP MCP server on a free port that lists one tool +function fakeMcp(tool) { + return Bun.serve({ + port: 0, + hostname: "127.0.0.1", + async fetch(req) { + const msg = await req.json() + if (msg.id === undefined) return new Response(null, { status: 202 }) + const result = msg.method === "initialize" + ? { protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: tool, version: "1" } } + : msg.method === "tools/list" + ? { tools: [{ name: tool, description: "search " + tool, inputSchema: { type: "object", properties: {} } }] } + : {} + return Response.json({ jsonrpc: "2.0", id: msg.id, result }) + }, + }) +} + +test("with mcpAll on, a chat gets every Library server's tools, one added later too, and none ticked", async () => { + // a service of its own: the last one started owns the Host allow list, and + // an earlier test started another + const { startServer } = await import("./lib/server.mjs") + const own = await startServer({ configDir: cfg, options: { port: 0 } }) + const raw = (...args) => rawOn(own.port, ...args) + const h = { ...json, origin: "null", "x-magpie-chat-token": token } + const a = fakeMcp("search_alpha"), b = fakeMcp("search_beta"), c = fakeMcp("search_gamma") + const lib = (list) => writeFileSync(join(cfg, "library.json"), JSON.stringify({ + mcp: list.map(([name, srv]) => ({ name, transport: "http", url: `http://127.0.0.1:${srv.port}/mcp`, agents: [] })), + })) + const toolNames = async () => { + const before = seen.length + const res = await raw("POST", "/api/chat", h, { ...chatBody, messages: [{ role: "user", content: "search something" }] }) + expect(res.status).toBe(200) + expect(seen.length).toBe(before + 1) + return (seen.at(-1).body.tools || []).map((t) => t.function.name).sort() + } + try { + lib([["a", a], ["b", b]]) + // off and nothing ticked: no tools, as before + await raw("POST", "/api/settings", h, { mcp: [], mcpAll: false }) + expect(await toolNames()).toEqual([]) + // off with one ticked: only that one + await raw("POST", "/api/settings", h, { mcp: ["a"] }) + expect(await toolNames()).toEqual(["a_search_alpha"]) + // on: every server, whatever is ticked; the setting is kept + const saved = JSON.parse((await raw("POST", "/api/settings", h, { mcp: [], mcpAll: true })).body) + expect(saved.mcpAll).toBe(true) + expect(JSON.parse((await raw("GET", "/api/settings", h)).body).mcpAll).toBe(true) + expect(await toolNames()).toEqual(["a_search_alpha", "b_search_beta"]) + // a server added to magpie's Library afterwards is in the next chat + lib([["a", a], ["b", b], ["c", c]]) + expect(await toolNames()).toEqual(["a_search_alpha", "b_search_beta", "c_search_gamma"]) + // and "check connection" checks the same servers + const check = JSON.parse((await raw("GET", "/api/mcp/tools", h)).body) + expect(check.servers.map((s) => s.name).sort()).toEqual(["a", "b", "c"]) + } finally { + await raw("POST", "/api/settings", h, { mcp: [], mcpAll: false }) + rmSync(join(cfg, "library.json"), { force: true }) + a.stop(true); b.stop(true); c.stop(true) + await own.close() + } +}) + +test("mcpAll defaults to off, so an existing user's settings keep ticking", async () => { + const { pickServers } = await import("./lib/server.mjs") + const servers = [{ name: "a" }, { name: "b" }] + expect(pickServers(servers, { mcp: ["b"] }).map((s) => s.name)).toEqual(["b"]) + expect(pickServers(servers, { mcp: ["b"], mcpAll: true }).map((s) => s.name)).toEqual(["a", "b"]) + const { createStore } = await import("./lib/server.mjs") + const fresh = mkdtempSync(join(tmp, "fresh-")) + expect((await createStore(fresh).settings()).mcpAll).toBe(false) + // a settings.json written by 0.1.5 has no mcpAll + writeFileSync(join(createStore(fresh).dir, "settings.json"), JSON.stringify({ mcp: ["b"] })) + const old = await createStore(fresh).settings() + expect(old.mcpAll).toBe(false) + expect(old.mcp).toEqual(["b"]) +}) + +test("the chat UI asks for tools when mcpAll is on with nothing ticked, and flushes settings before it sends", () => { + const app = readFileSync(join(dir, "chat", "app.js"), "utf8") + const start = app.indexOf("function wantsTools") + expect(start).toBeGreaterThan(0) + const end = app.indexOf("\n}\n", start) + 3 + const wantsTools = new Function(app.slice(start, end) + "\nreturn wantsTools")() + expect(wantsTools({ mcp: [], mcpAll: true })).toBe(true) + expect(wantsTools({ mcp: ["a"], mcpAll: false })).toBe(true) + expect(wantsTools({ mcp: [], mcpAll: false })).toBe(false) + expect(app).toContain("useTools: wantsTools(state.settings)") + // the server picks servers from the saved settings, so a switch flipped just before sending is saved first + expect(app).toMatch(/var saved = saveTimer \? flushSettings\(\) : Promise\.resolve\(\);\s*saved\.then\(function \(\) \{ return streamChat\(/) + const html = readFileSync(join(dir, "chat", "index.html"), "utf8") + expect(html).toMatch(/id="mcpAll"[^>]*role="switch"/) + expect(html).not.toContain(" 0 || (s.skills || []).length > 0 || (s.mcp || []).length > 0 + || s.mcpAll === true || Number(s.temperature) !== 0.7 || Number(s.maxTokens) > 0 || s.showReasoning === false; @@ -1243,12 +1245,20 @@ function renderSettings() { renderSetList("#skillList", state.library.skills || [], "skills", function (item) { return { key: item.name, name: item.name, extra: "" }; }); + var all = state.settings.mcpAll === true; + $("#mcpAll").setAttribute("aria-checked", all ? "true" : "false"); renderSetList("#mcpList", state.library.mcp || [], "mcp", function (item) { return { key: item.name, name: item.name, extra: item.transport || "" }; - }); + }, all); } -function renderSetList(sel, items, field, pick) { +/* 这一轮要不要带工具:开了「全部」,或者勾了至少一个服务器 */ +function wantsTools(settings) { + return settings.mcpAll === true || (settings.mcp || []).length > 0; +} + +// allOn:列表由上面的总开关接管,每一项都显示为勾上、点不动 +function renderSetList(sel, items, field, pick, allOn) { var box = $(sel); while (box.firstChild) box.removeChild(box.firstChild); if (!items.length) { @@ -1258,14 +1268,20 @@ function renderSetList(sel, items, field, pick) { var selected = state.settings[field] || []; items.forEach(function (item) { var info = pick(item); - var on = selected.indexOf(info.key) >= 0; + var on = allOn === true || selected.indexOf(info.key) >= 0; var tick = el("span", { class: "tick" + (on ? " on" : ""), text: "\u2713" }); var row = el("button", { class: "set-item", type: "button", role: "checkbox", "aria-checked": on ? "true" : "false", title: info.name }, tick, el("span", { class: "set-name", text: info.name }), info.extra ? el("span", { class: "set-extra", text: info.extra }) : null ); - row.addEventListener("click", function () { toggleItem(field, info.key); }); + if (allOn === true) { + row.disabled = true; + row.setAttribute("aria-disabled", "true"); + row.title = info.name + "(已用全部 MCP 服务器)"; + } else { + row.addEventListener("click", function () { toggleItem(field, info.key); }); + } box.appendChild(row); }); } @@ -2188,13 +2204,15 @@ function send() { system: state.settings.systemEnabled === false ? "" : (state.settings.system || ""), temperature: Number(state.settings.temperature), maxTokens: Number(state.settings.maxTokens) || 0, - useTools: (state.settings.mcp || []).length > 0, + useTools: wantsTools(state.settings), clientId: state.clientId }; var started = Date.now(); forageBegin(refs); // 开始计时:从按下发送到这一轮结束,显示在这条回复的底部 - streamChat(payload, function (evt) { handleEvent(evt, refs); }, state.abort.signal) + // 服务端按存下来的设置挑 MCP 服务器:刚拨的开关还在 320ms 的防抖里没存,先存了再发 + var saved = saveTimer ? flushSettings() : Promise.resolve(); + saved.then(function () { return streamChat(payload, function (evt) { handleEvent(evt, refs); }, state.abort.signal); }) .then(function () { if (!asstMsg.ms) asstMsg.ms = Date.now() - started; finish(refs); @@ -2574,6 +2592,14 @@ function bindUI() { patchSettings({ systemEnabled: on }); }); + $("#mcpAll").addEventListener("click", function (e) { + var on = e.currentTarget.getAttribute("aria-checked") !== "true"; + patchSettings({ mcpAll: on }); + renderSettings(); + $("#toolsStatus").textContent = ""; + $("#toolsStatus").className = "set-tools-status"; + }); + $("#showReasoning").addEventListener("click", function (e) { var on = e.currentTarget.getAttribute("aria-checked") !== "true"; e.currentTarget.setAttribute("aria-checked", on ? "true" : "false"); diff --git a/packages/chat/chat/index.html b/packages/chat/chat/index.html index 663a1d5..a1d01f6 100644 --- a/packages/chat/chat/index.html +++ b/packages/chat/chat/index.html @@ -109,6 +109,10 @@
MCP 服务器
+
+ 使用 magpie 的全部 MCP 服务器 + +
diff --git a/packages/chat/chat/style.css b/packages/chat/chat/style.css index 4fc6334..4684822 100644 --- a/packages/chat/chat/style.css +++ b/packages/chat/chat/style.css @@ -542,6 +542,9 @@ input, textarea { font: inherit; color: inherit; } } .set-item:hover { background: var(--pill); } +.set-item:disabled { cursor: default; } +.set-item:disabled:hover { background: none; } +.set-item:disabled .tick.on { opacity: .55; } .set-item .set-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .set-item .set-extra { margin-left: auto; flex: none; font-size: 11px; color: var(--faint); } @@ -592,6 +595,8 @@ input, textarea { font: inherit; color: inherit; } .set-row + .set-row { border-top: 1px solid var(--line-2); } .set-label { flex: 0 0 auto; min-width: 78px; color: var(--fg-2); } +.set-row-all { margin-bottom: 2px; } +.set-row-all .set-label { flex: 1 1 auto; min-width: 0; } .range { flex: 1 1 auto; min-width: 0; height: 16px; accent-color: var(--accent); } .set-val { flex: none; min-width: 30px; text-align: right; font-size: 11.5px; color: var(--muted); font-variant-numeric: tabular-nums; } diff --git a/packages/chat/lib/server.mjs b/packages/chat/lib/server.mjs index 75e80f6..cb20a07 100644 --- a/packages/chat/lib/server.mjs +++ b/packages/chat/lib/server.mjs @@ -73,6 +73,7 @@ async function fontCss() { const DEFAULTS = { model: "", effort: "", system: "", instructions: [], skills: [], mcp: [], + mcpAll: false, // 用 magpie Library 里的全部 MCP 服务器(以后新加的也算),不看 mcp 里勾的 temperature: 0.7, maxTokens: 0, showReasoning: true, pinned: [], // 置顶的对话 id,按置顶顺序排在列表最前 sidebar: true, // 左侧栏是否展开 @@ -93,6 +94,7 @@ function cleanSettings(raw) { instructions: Array.isArray(s.instructions) ? s.instructions.map(String) : [], skills: Array.isArray(s.skills) ? s.skills.map(String) : [], mcp: Array.isArray(s.mcp) ? s.mcp.map(String) : [], + mcpAll: s.mcpAll === true, temperature: Number.isFinite(Number(s.temperature)) ? Number(s.temperature) : 0.7, maxTokens: Number.isFinite(Number(s.maxTokens)) ? Number(s.maxTokens) : 0, showReasoning: s.showReasoning !== false, @@ -342,6 +344,14 @@ function toGatewayContent(m) { return parts; } +// 这轮要用的 MCP 服务器:开了「全部」就是 Library 里的每一个(每次现读, +// 后来在 magpie 里加的也在内),否则只用勾选的那些 +export function pickServers(servers, settings) { + if (settings?.mcpAll === true) return servers.slice(); + const names = settings?.mcp || []; + return servers.filter((s) => names.includes(s.name)); +} + // 一轮对话:可多次工具调用;把每条增量转成 SSE 发回浏览器 async function runChat({ res, body, settings, store, options }, controllers) { const clientId = String(body.clientId || ""); @@ -354,7 +364,7 @@ async function runChat({ res, body, settings, store, options }, controllers) { const effort = String(body.effort ?? settings.effort ?? ""); const temperature = Number.isFinite(Number(body.temperature)) ? Number(body.temperature) : settings.temperature; const maxTokens = Number.isFinite(Number(body.maxTokens)) ? Number(body.maxTokens) : settings.maxTokens; - const wantTools = body.useTools !== false && (settings.mcp || []).length > 0; + const wantTools = body.useTools !== false && (settings.mcpAll === true || (settings.mcp || []).length > 0); const history = Array.isArray(body.messages) ? body.messages.filter((m) => m && (m.role === "user" || m.role === "assistant")) : []; // 只挂了图片/文件、没写文字的消息也算有内容 @@ -370,7 +380,7 @@ async function runChat({ res, body, settings, store, options }, controllers) { let toolNote = ""; if (wantTools) { const servers = await readMcp(); - const picked = servers.filter((s) => (settings.mcp || []).includes(s.name)); + const picked = pickServers(servers, settings); const all = []; for (const s of picked) { try { @@ -672,7 +682,7 @@ export async function startServer({ configDir: dirArg, options = {} } = {}) { if (path === "/api/library" && req.method === "GET") return send(res, 200, await libraryView(dir)); if (path === "/api/mcp/tools" && req.method === "GET") { const settings = await store.settings(); - const servers = (await readMcp(dir)).filter((s) => settings.mcp.includes(s.name)); + const servers = pickServers(await readMcp(dir), settings); const out = []; for (const s of servers) { try { diff --git a/packages/chat/package.json b/packages/chat/package.json index 37a9b16..417cf97 100644 --- a/packages/chat/package.json +++ b/packages/chat/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/page-chat", - "version": "0.1.5", + "version": "0.1.6", "description": "在 magpie 窗口里加一个「对话」页面:用 magpie 自己的模型、MCP 服务器、指令和技能聊天,支持图片与 LaTeX。A chat page inside magpie's window: talk with magpie's own models, MCP servers, instructions and skills, with images and LaTeX.", "author": "Magic_zero (https://github.com/Magiczerowxy)", "files": [