page-chat 0.1.7: magpie's own MCP servers that are on are used beside the Library's (ferock on Discord)
ferock on Discord: with "使用 magpie 的全部 MCP 服务器" on, a chat got only the servers in library.json, never magpie's own web search, image recognition or image generation. ownMcp (lib/gateway.mjs) asks the gateway's GET /v1/magpie/mcp (magpie v0.1.2397) for the ones on now and mounts each at the gateway's address with the gateway key. readMcp adds them after the Library's, which every route takes its MCP list from: the page's list (libraryView), a chat's tools, a tool call and the connection check; a Library server of the same name (an installed magpie-image) is used in its place. One turned off in magpie's Settings is left out of the next chat. An older magpie (404), a gateway that doesn't answer, or a bad reply lists none, as before. lib/mcp.mjs loadServers (library.json only) is unchanged; the page calls listTools/callTool with server objects, never by name. Run (mote): bun test chat.test.mjs, 29 pass; the new test is red on the old lib (Expected 2 more tools, Received 0), checked by hand. bun scripts/check.mjs ok. magpie's side was run against its real binary (magpie commit cac655c14's body). Not tried: the page in magpie's window against a real magpie with the switch on (the test drives the page's service with a fake gateway).
This commit is contained in:
@@ -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). 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.
|
||||
- **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. magpie's own MCP servers (web search, image recognition, image generation, plugin tools) are in the list beside the library's while they are on in magpie (asked of the gateway's `/v1/magpie/mcp`, magpie v0.1.2397 and later; an older magpie lists none); one turned off in magpie's Settings is left out, and a library server of the same name, such as an installed `magpie-image`, is used in its place.
|
||||
- **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 `` 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.
|
||||
@@ -42,7 +42,7 @@ A plugin page runs in a sandboxed frame with no network (`connect-src 'none'`).
|
||||
|
||||
- From magpie's config folder (`$XDG_CONFIG_HOME/magpie` or `~/.config/magpie`): `caller-keys.json` (the first gateway key, sent as `Authorization: Bearer` to the gateway, so the chat's usage is counted on that key), `providers.json` and `routing.json` (icons), `settings.json` (fonts, and the gateway `port` when the build writes one there), `library.json` and `library/` (MCP servers, instructions, skills).
|
||||
- To magpie's gateway: `MAGPIE_CHAT_GATEWAY` if set, else `MAGPIE_ADDR`, else the `port` from magpie's `settings.json` (the portable build writes its real port there, e.g. `18086`), else `http://127.0.0.1:3425`. The key goes there, so set `MAGPIE_CHAT_GATEWAY` only to a gateway you trust.
|
||||
- To your MCP servers: what the model asks their tools, with the headers you configured for them. A stdio server's command is run as you configured it.
|
||||
- To your MCP servers: what the model asks their tools, with the headers you configured for them. A stdio server's command is run as you configured it. magpie's own MCP servers are on the gateway, and get the gateway key.
|
||||
|
||||
### Who can use the service
|
||||
|
||||
|
||||
@@ -20,11 +20,31 @@ delete process.env.MAGPIE_GATEWAY_KEY
|
||||
delete process.env.MAGPIE_ADDR
|
||||
|
||||
const seen = []
|
||||
// magpie's own MCP servers the fake gateway lists on /v1/magpie/mcp; null
|
||||
// answers 404, as a magpie from before the list does
|
||||
let ownList = null
|
||||
const ownAuth = []
|
||||
const gateway = Bun.serve({
|
||||
port: 0,
|
||||
hostname: "127.0.0.1",
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url)
|
||||
if (url.pathname === "/v1/magpie/mcp") {
|
||||
return ownList ? Response.json({ servers: ownList }) : new Response("no", { status: 404 })
|
||||
}
|
||||
if (url.pathname.startsWith("/mcp/magpie/")) {
|
||||
// one of magpie's own servers: its tool is named for its path
|
||||
ownAuth.push(req.headers.get("authorization"))
|
||||
const msg = await req.json()
|
||||
if (msg.id === undefined) return new Response(null, { status: 202 })
|
||||
const tool = "own_" + url.pathname.slice("/mcp/magpie/".length).replace(/\W/g, "_")
|
||||
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 })
|
||||
}
|
||||
if (url.pathname === "/v1/models") return Response.json({ data: [{ id: "fake/model", owned_by: "fake" }] })
|
||||
if (url.pathname === "/v1/chat/completions") {
|
||||
seen.push({ auth: req.headers.get("authorization"), body: await req.json() })
|
||||
@@ -461,3 +481,66 @@ test("the chat UI asks for tools when mcpAll is on with nothing ticked, and flus
|
||||
expect(html).toMatch(/id="mcpAll"[^>]*role="switch"/)
|
||||
expect(html).not.toContain("<select")
|
||||
})
|
||||
|
||||
// ---------- 0.1.7: magpie's own MCP servers beside the Library's ----------
|
||||
|
||||
test("with mcpAll on, a chat gets magpie's own MCP servers that are on, beside the Library's", async () => {
|
||||
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"), img = fakeMcp("search_library_image")
|
||||
writeFileSync(join(cfg, "library.json"), JSON.stringify({
|
||||
mcp: [
|
||||
{ name: "a", transport: "http", url: `http://127.0.0.1:${a.port}/mcp`, agents: [] },
|
||||
// installed from the Library under the same name as magpie's own: the Library's is used
|
||||
{ name: "magpie-image", transport: "http", url: `http://127.0.0.1:${img.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 {
|
||||
await raw("POST", "/api/settings", h, { mcp: [], mcpAll: true })
|
||||
// a magpie without the list: the Library's alone, as before
|
||||
ownList = null
|
||||
expect(await toolNames()).toEqual(["a_search_alpha", "magpie-image_search_library_image"])
|
||||
// web search and image recognition on, image generation listed too
|
||||
ownList = [
|
||||
{ name: "magpie-web-search", title: "Magpie Web Search", path: "/mcp/magpie/web-search" },
|
||||
{ name: "magpie-vision", title: "Magpie Image Recognition", path: "/mcp/magpie/vision" },
|
||||
{ name: "magpie-image", title: "Magpie Image", path: "/mcp/magpie/image" },
|
||||
]
|
||||
ownAuth.length = 0
|
||||
expect(await toolNames()).toEqual([
|
||||
"a_search_alpha",
|
||||
"magpie-image_search_library_image",
|
||||
"magpie-vision_own_vision",
|
||||
"magpie-web-search_own_web_search",
|
||||
])
|
||||
// they are asked with the same key as the gateway
|
||||
expect(ownAuth.length).toBeGreaterThan(0)
|
||||
expect(ownAuth.every((x) => x === "Bearer mk-test-key")).toBe(true)
|
||||
// the page's list and "check connection" show them too
|
||||
const lib = JSON.parse((await raw("GET", "/api/library", h)).body)
|
||||
expect(lib.mcp.map((m) => m.name)).toEqual(["a", "magpie-image", "magpie-web-search", "magpie-vision"])
|
||||
const check = JSON.parse((await raw("GET", "/api/mcp/tools", h)).body)
|
||||
expect(check.servers.map((s) => s.name).sort()).toEqual(["a", "magpie-image", "magpie-vision", "magpie-web-search"])
|
||||
// image recognition turned off in magpie: gone from the next chat
|
||||
ownList = ownList.filter((m) => m.name !== "magpie-vision")
|
||||
expect(await toolNames()).toEqual(["a_search_alpha", "magpie-image_search_library_image", "magpie-web-search_own_web_search"])
|
||||
// ticked by itself, with the switch off, one of magpie's own is used alone
|
||||
await raw("POST", "/api/settings", h, { mcp: ["magpie-web-search"], mcpAll: false })
|
||||
expect(await toolNames()).toEqual(["magpie-web-search_own_web_search"])
|
||||
} finally {
|
||||
ownList = null
|
||||
await raw("POST", "/api/settings", h, { mcp: [], mcpAll: false })
|
||||
rmSync(join(cfg, "library.json"), { force: true })
|
||||
a.stop(true); img.stop(true)
|
||||
await own.close()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -120,6 +120,32 @@ function headers(extra = {}) {
|
||||
return h;
|
||||
}
|
||||
|
||||
// magpie 自己的 MCP 服务器(网页搜索、识图、生图、插件工具)不在 library.json 里:
|
||||
// 网关的 /v1/magpie/mcp 列出现在开着的那几个(在 magpie 设置里关掉的不列)。
|
||||
// 老版本 magpie 没有这个接口(404)、网关连不上、答得不对,都当没有,不挡对话。
|
||||
export async function ownMcp(opts = {}) {
|
||||
try {
|
||||
const base = await resolveGateway(opts);
|
||||
const res = await fetch(base + "/v1/magpie/mcp", { headers: headers(), signal: AbortSignal.timeout(2500) });
|
||||
if (!res.ok) return [];
|
||||
const body = await res.json();
|
||||
const list = Array.isArray(body?.servers) ? body.servers : [];
|
||||
const auth = headers().authorization;
|
||||
return list
|
||||
.filter((s) => s && typeof s.name === "string" && s.name && typeof s.path === "string" && s.path.startsWith("/"))
|
||||
.map((s) => ({
|
||||
name: s.name,
|
||||
transport: "http",
|
||||
url: base + s.path,
|
||||
headers: auth ? { authorization: auth } : undefined,
|
||||
detail: base + s.path,
|
||||
builtin: true,
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// 归一化成界面要用的形状:名字、思考档位、上下文、能不能看图
|
||||
export function normalizeModel(m) {
|
||||
const id = String(m.id || "");
|
||||
|
||||
@@ -5,6 +5,7 @@ import { readFile, readdir, stat } from "node:fs/promises";
|
||||
import { existsSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { ownMcp } from "./gateway.mjs";
|
||||
|
||||
export function configDir() {
|
||||
const xdg = process.env.XDG_CONFIG_HOME;
|
||||
@@ -75,11 +76,11 @@ export async function readSkills(dir = configDir()) {
|
||||
return out.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
export async function readMcp(dir = configDir()) {
|
||||
export async function readMcp(dir = configDir(), opts = {}) {
|
||||
// magpie 的 MCP 列表在配置目录的 library.json(library/ 里放的是指令和技能的正文)
|
||||
const lib = await readJson(join(dir, "library.json"), {});
|
||||
const [lib, own] = await Promise.all([readJson(join(dir, "library.json"), {}), ownMcp(opts)]);
|
||||
const list = Array.isArray(lib.mcp) ? lib.mcp : [];
|
||||
return list.map((m) => ({
|
||||
const mine = list.map((m) => ({
|
||||
name: m.name || m.url || m.command || "mcp",
|
||||
transport: m.transport === "stdio" ? "stdio" : "http",
|
||||
url: m.url,
|
||||
@@ -89,11 +90,14 @@ export async function readMcp(dir = configDir()) {
|
||||
env: m.env && typeof m.env === "object" ? m.env : undefined,
|
||||
detail: m.url || [m.command, ...(m.args || [])].join(" "),
|
||||
}));
|
||||
// 再加上 magpie 自己开着的那几个;Library 里装了同名的(比如 magpie-image)就用 Library 的
|
||||
const names = new Set(mine.map((m) => m.name));
|
||||
return [...mine, ...own.filter((m) => !names.has(m.name))];
|
||||
}
|
||||
|
||||
// 给前端的精简视图(不带正文,免得 bootstrap 太重)
|
||||
export async function libraryView(dir = configDir()) {
|
||||
const [instructions, skills, mcp] = await Promise.all([readInstructions(dir), readSkills(dir), readMcp(dir)]);
|
||||
export async function libraryView(dir = configDir(), opts = {}) {
|
||||
const [instructions, skills, mcp] = await Promise.all([readInstructions(dir), readSkills(dir), readMcp(dir, opts)]);
|
||||
return {
|
||||
instructions: instructions.map(({ id, name, size }) => ({ id, name, size })),
|
||||
skills: skills.map(({ name, description }) => ({ name, description })),
|
||||
|
||||
@@ -344,7 +344,7 @@ function toGatewayContent(m) {
|
||||
return parts;
|
||||
}
|
||||
|
||||
// 这轮要用的 MCP 服务器:开了「全部」就是 Library 里的每一个(每次现读,
|
||||
// 这轮要用的 MCP 服务器:开了「全部」就是 Library 里的每一个加上 magpie 自己开着的(每次现读,
|
||||
// 后来在 magpie 里加的也在内),否则只用勾选的那些
|
||||
export function pickServers(servers, settings) {
|
||||
if (settings?.mcpAll === true) return servers.slice();
|
||||
@@ -379,7 +379,7 @@ async function runChat({ res, body, settings, store, options }, controllers) {
|
||||
let tools = [];
|
||||
let toolNote = "";
|
||||
if (wantTools) {
|
||||
const servers = await readMcp();
|
||||
const servers = await readMcp(undefined, options);
|
||||
const picked = pickServers(servers, settings);
|
||||
const all = [];
|
||||
for (const s of picked) {
|
||||
@@ -518,7 +518,7 @@ async function runChat({ res, body, settings, store, options }, controllers) {
|
||||
if (!tool) {
|
||||
result = "没有这个工具:" + c.name; isError = true;
|
||||
} else {
|
||||
const server = (await readMcp()).find((s) => s.name === tool.server);
|
||||
const server = (await readMcp(undefined, options)).find((s) => s.name === tool.server);
|
||||
try {
|
||||
const out = await callTool(server, tool.rawName, args);
|
||||
result = out.text; isError = Boolean(out.isError);
|
||||
@@ -614,7 +614,7 @@ export async function startServer({ configDir: dirArg, options = {} } = {}) {
|
||||
gateway,
|
||||
settings,
|
||||
models: list,
|
||||
library: await libraryView(dir),
|
||||
library: await libraryView(dir, options),
|
||||
error: gatewayError,
|
||||
});
|
||||
}
|
||||
@@ -679,10 +679,10 @@ export async function startServer({ configDir: dirArg, options = {} } = {}) {
|
||||
const patch = await readBody(req);
|
||||
return send(res, 200, await store.saveSettings(patch));
|
||||
}
|
||||
if (path === "/api/library" && req.method === "GET") return send(res, 200, await libraryView(dir));
|
||||
if (path === "/api/library" && req.method === "GET") return send(res, 200, await libraryView(dir, options));
|
||||
if (path === "/api/mcp/tools" && req.method === "GET") {
|
||||
const settings = await store.settings();
|
||||
const servers = pickServers(await readMcp(dir), settings);
|
||||
const servers = pickServers(await readMcp(dir, options), settings);
|
||||
const out = [];
|
||||
for (const s of servers) {
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-chat",
|
||||
"version": "0.1.6",
|
||||
"version": "0.1.7",
|
||||
"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": [
|
||||
|
||||
Reference in New Issue
Block a user