From 75a1937e23a4335fd23299e319391a6963a04408 Mon Sep 17 00:00:00 2001 From: ninon <284425649+ninondev@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:55:23 -0800 Subject: [PATCH] chat: rank MCP tools using the typed question (#631) chat: an attached EPUB's text no longer decides which MCP tools are picked (#623) The page sends the typed text as userText beside the message that has the book in it, and the server ranks MCP tools on userText when it is there, on content otherwise. The gateway still gets the whole book; userText is never sent to it. page-chat 0.1.10. By ninondev (#631). Run at cb07bd6 on mote (bun 1.4.2, temp HOME): packages/chat bun test 35 pass, 1 skip, 0 fail; scripts/check.mjs chat ok. Broken by hand: origin/main's server.mjs, then origin/main's app.js, each alone: the new test goes red (34 pass, 1 fail). Not tried: the real page in magpie's window with a real EPUB and MCP server. --- packages/chat/chat.test.mjs | 56 ++++++++++++++++++++++++++++++++++-- packages/chat/chat/app.js | 2 +- packages/chat/lib/server.mjs | 3 +- packages/chat/package.json | 2 +- 4 files changed, 57 insertions(+), 6 deletions(-) diff --git a/packages/chat/chat.test.mjs b/packages/chat/chat.test.mjs index 9c9a681..53aabe2 100644 --- a/packages/chat/chat.test.mjs +++ b/packages/chat/chat.test.mjs @@ -224,6 +224,56 @@ test("switching chats discards a book that is still being read", async () => { expect(page.pending()).toBe(0) }) +test("MCP tools follow the typed question while the gateway still receives the EPUB", async () => { + const names = [...Array.from({ length: 12 }, (_, i) => "github_lookup_" + i), + ...Array.from({ length: 3 }, (_, i) => "weather_forecast_" + i), "list_items"] + const mcp = fakeMcp("catalog", names.map(name => ({ name, inputSchema: { type: "object", properties: {} } }))) + const h = { ...json, "x-magpie-chat-token": token } + writeFileSync(join(cfg, "library.json"), JSON.stringify({ + mcp: [{ name: "catalog", transport: "http", url: `http://127.0.0.1:${mcp.port}/mcp`, agents: [] }], + })) + const page = chatPage() + const chapters = "github ".repeat(1000) + "The last page." + const file = { name: "github.epub", kind: "file", data: "data:;base64,Ym9vaw==" } + page.MagpieEpub.read = async () => ({ text: chapters }) + const weather = names.filter(name => name.startsWith("weather")).map(name => "catalog_" + name) + const send = async history => { + const before = seen.length + await page.streamChat({ ...chatBody, messages: history }, () => {}) + expect(seen.length).toBe(before + 1) + const body = seen.at(-1).body + expect(JSON.stringify(body.messages).split("The last page.")).toHaveLength(2) + expect(body.messages.find(message => message.role === "user").content).toContain(chapters) + expect(body.messages.every(message => !("userText" in message))).toBe(true) + return (body.tools || []).map(tool => tool.function.name) + } + try { + await raw("POST", "/api/settings", h, { mcp: ["catalog"], mcpAll: false }) + const first = { role: "user", content: "weather", files: [file] } + expect(await send([first])).toEqual(weather) + expect(await send([{ ...first, content: "" }])).toEqual(["catalog_list_items"]) + expect(await send([{ ...first, content: "【电子书:例子】weather【电子书结束】" }])).toEqual(weather) + for (const files of [[], [file]]) { + expect(await send([first, { role: "assistant", content: "hello" }, + { role: "user", content: "weather", files }])).toEqual(weather) + } + expect(await send([first, { role: "assistant", content: "hello" }, + { role: "user", content: "github" }])).toEqual( + names.filter(name => name.startsWith("github")).map(name => "catalog_" + name)) + const before = seen.length + const response = await raw("POST", "/api/chat", h, { + ...chatBody, messages: [{ role: "user", content: "weather" }], + }) + expect(response.status).toBe(200) + expect(seen.length).toBe(before + 1) + expect(seen.at(-1).body.tools.map(tool => tool.function.name)).toEqual(weather) + } finally { + await raw("POST", "/api/settings", h, { mcp: [], mcpAll: false }) + rmSync(join(cfg, "library.json"), { force: true }) + mcp.stop(true) + } +}) + test("conversations save and list with the token", async () => { const h = { ...json, origin: "null", "x-magpie-chat-token": token } const saved = JSON.parse((await raw("POST", "/api/conversations", h, { title: "t", messages: [{ role: "user", content: "x" }] })).body) @@ -461,8 +511,8 @@ test("finish() renders a reply that arrived in one chunk", () => { // ---------- 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) { +// a Streamable-HTTP MCP server on a free port +function fakeMcp(tool, tools) { return Bun.serve({ port: 0, hostname: "127.0.0.1", @@ -472,7 +522,7 @@ function fakeMcp(tool) { 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: {} } }] } + ? { tools: tools || [{ name: tool, description: "search " + tool, inputSchema: { type: "object", properties: {} } }] } : {} return Response.json({ jsonrpc: "2.0", id: msg.id, result }) }, diff --git a/packages/chat/chat/app.js b/packages/chat/chat/app.js index 1827982..8ae4e23 100644 --- a/packages/chat/chat/app.js +++ b/packages/chat/chat/app.js @@ -2187,7 +2187,7 @@ async function requestMessages(history, warn) { } if (String(m.content || "").trim()) parts.push(m.content); if (parts.length || otherFiles.some(function (f) { return f.kind === "image"; })) { - messages.push({ role: m.role, content: parts.join("\n\n"), files: otherFiles }); + messages.push({ role: m.role, content: parts.join("\n\n"), userText: String(m.content ?? ""), files: otherFiles }); } } return messages; diff --git a/packages/chat/lib/server.mjs b/packages/chat/lib/server.mjs index 78e42f3..00c3adf 100644 --- a/packages/chat/lib/server.mjs +++ b/packages/chat/lib/server.mjs @@ -390,7 +390,8 @@ async function runChat({ res, body, settings, store, options }, controllers) { sse(res, "tool", { phase: "error", name: s.name, result: "无法连接 " + s.name + ":" + (err?.message || err) }); } } - const q = String(history[history.length - 1]?.content || "").toLowerCase(); + const last = history[history.length - 1]; + const q = String(typeof last?.userText === "string" ? last.userText : last?.content || "").toLowerCase(); const words = q.split(/[^a-z0-9\u4e00-\u9fff]+/).filter((w) => w.length >= 3); const scored = all.map((t) => { const hay = (t.name + " " + (t.description || "")).toLowerCase(); diff --git a/packages/chat/package.json b/packages/chat/package.json index 5e2d89c..4a06745 100644 --- a/packages/chat/package.json +++ b/packages/chat/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/page-chat", - "version": "0.1.9", + "version": "0.1.10", "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": [