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.
This commit is contained in:
ninon
2026-11-02 18:55:23 +08:00
committed by GitHub
parent 0793242b6b
commit 75a1937e23
4 changed files with 57 additions and 6 deletions
+53 -3
View File
@@ -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 })
},
+1 -1
View File
@@ -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;
+2 -1
View File
@@ -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();
+1 -1
View File
@@ -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": [