library, gui: an MCP server's tools are listed by name and description (nf1qaz2w on Discord)

nf1qaz2w on Discord: "mcp现在好像只能看到有几个工具,看不到具体的工具名和描述等,
能否支持下?" The Library's MCP check kept only len(tools) from tools/list.

What changed:
- internal/library/mcp_check.go: ServerHealth carries ToolList (json
  "toolList"): each tool's name and the first paragraph of its
  description, whitespace collapsed and cut at 500 runes (a tool with only
  a title gets the title); names cut at 128; at most 500 tools kept while
  Tools still counts all. tools/list is now asked through listTools, shared
  by the stdio, streamable HTTP and SSE checks: it follows nextCursor up to
  10 pages, each page with a step budget of its own (the #1467 per-step
  timeout), and a page after the first that is refused ends the list there.
  Before, nextCursor was ignored and only the first page counted.
- internal/gui/assets/library.js/.css: a server whose check listed tools
  shows a chevron on its "N tools" status; a click opens the list under the
  row (name in the code font, description under it, "N more not shown" when
  magpie kept fewer than the server has, and Check again). Clicking the
  count again shuts it. A server with no listed tools keeps the old click,
  which checks it again. The list stays while it is checked again, no
  editor opens, no left-border stripe, no native select. The click guard
  keeps the clicked status in place (a centred row gives up 1px as it
  grows).
- i18n: "Click to see them", "Click to hide them", "{n} more not shown" in
  zh, zh-TW, ja, de.
- docs/subsystems/library.md: the check's tool list and paging.
There is no CLI/TUI output of a server's check, so nothing changed there.

What was run:
- go test ./internal/library: TestCheckKeepsToolNames runs the check on the
  tools/list reply @modelcontextprotocol/server-filesystem really gave
  (captured with npx, testdata/filesystem-tools-list.json, 14 tools, the
  longest description 457 chars); TestCheckToolPages (no description, title
  only, a 1000-char description cut, two pages by nextCursor, the JSON the
  page reads); TestCheckToolPagesEnd (a server that pages forever is asked
  10 times). With the list not kept and paging off, the first two fail:
  "got {State:ok Tools:14 ToolList:[] ...}, want ok with 14 tools, each
  listed" and "...Tools:3 ToolList:[]..., want ok with 4 tools over 2 pages".
- GUI: internal/gui/tests/library-mcp-tools.test.cjs, Chromium and WebKit,
  en/zh/zh-TW/ja/de, at 980 and 420 wide: 20/20 pass; against the old
  library.js it fails. library-*.test.cjs, mcp-signin, search-mcp,
  i18n-keys and click-scroll in both engines: 377/377 pass.
- gofmt -l (nothing), go vet / GOOS=linux / GOOS=windows go vet -tags nogui
  on internal/library and internal/gui, go build for darwin, linux and
  windows (nogui). Full go test -tags nogui ./... under the queue lock:
  every package ok but internal/provider, where TestClaudeSavedAccountDir
  failed "sign-in never finished" (waitDone's 2s bound on a fake claude
  process under full-suite load); alone it passes 5/5. Not touched here.
This commit is contained in:
yetone
2026-10-11 09:24:07 +08:00
parent 1c9747f611
commit 6f4fb883eb
9 changed files with 509 additions and 36 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
| Targets | `Targets` lists the detected agents (`agent.Detected`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi and OmO each by its own rule, and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. An agent a plugin adds (`a.Plugin`) has the places its plugin's `agent.library` names (`pluginTarget`): an instructions file, an MCP file in one of `agentplug.MCPFormats` (each the `mcpFormat` of the agent it is named for, `pluginMCP`) and a skills folder, `~` and `$VAR` expanded as its config is; one that names none is no target. Before, a plugin's agent got models and keys only. | [`targets.go`](../../internal/library/targets.go) |
| Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first, so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) |
| Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). | [`instructions.go`](../../internal/library/instructions.go) |
| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only. Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#615); one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go) |
| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#615); one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go) |
| Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. | [`skills.go`](../../internal/library/skills.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) |
| Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`) go first, marked official: `magpie-quota`, in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills/magpie-quota), lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) |
| Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) |
+12
View File
@@ -1707,6 +1707,9 @@ const I18N = {
"checking…": "检查中…",
"Connecting to it to list its tools": "正在连接并列出它的工具",
"Click to check again": "点击重新检查",
"Click to see them": "点击查看工具",
"Click to hide them": "点击收起",
"{n} more not shown": "另有 {n} 个未显示",
"Sign-in ran out": "登录已失效",
"Sign in again": "重新登录",
"Sign-in required": "需要重新登录",
@@ -5933,6 +5936,9 @@ const I18N = {
"checking…": "檢查中…",
"Connecting to it to list its tools": "正在連線並列出它的工具",
"Click to check again": "點選重新檢查",
"Click to see them": "點選查看工具",
"Click to hide them": "點選收起",
"{n} more not shown": "另有 {n} 個未顯示",
"Sign-in ran out": "登入已失效",
"Sign in again": "重新登入",
"Sign-in required": "需要重新登入",
@@ -10135,6 +10141,9 @@ const I18N = {
"checking…": "確認中…",
"Connecting to it to list its tools": "接続してツールを一覧表示しています",
"Click to check again": "クリックして再確認",
"Click to see them": "クリックしてツールを表示",
"Click to hide them": "クリックして閉じる",
"{n} more not shown": "ほか {n} 個は非表示",
"Sign-in ran out": "サインインの期限切れ",
"Sign in again": "再度サインイン",
"Sign-in required": "サインインが必要です",
@@ -14356,6 +14365,9 @@ const I18N = {
"checking…": "wird geprüft…",
"Connecting to it to list its tools": "Verbindung wird hergestellt, um die Tools aufzulisten",
"Click to check again": "Zum erneuten Prüfen klicken",
"Click to see them": "Klicken, um die Tools zu zeigen",
"Click to hide them": "Klicken zum Ausblenden",
"{n} more not shown": "{n} weitere nicht angezeigt",
"Sign-in ran out": "Anmeldung abgelaufen",
"Sign in again": "Erneut anmelden",
"Sign-in required": "Anmeldung erforderlich",
+12
View File
@@ -471,6 +471,18 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
.lib-health.auth::before { background: var(--amber); }
.lib-health.err { color: var(--red); }
.lib-health.err::before { background: var(--red); }
/* a server that listed its tools: its status opens them, a chevron says so */
.lib-health.has-list::after { content: ""; flex: none; width: 4px; height: 4px; margin: 0 1px 2px 1px; border: solid currentColor; border-width: 0 1.2px 1.2px 0; transform: rotate(45deg); opacity: .7; transition: transform .14s var(--ease); }
.lib-health.has-list[aria-expanded="true"]::after { transform: rotate(-135deg); margin-bottom: -2px; }
.lib-tools { margin-top: 6px; min-width: 0; border: 1px solid var(--line-2); border-radius: 8px; background: var(--card-2); cursor: auto; }
.lib-tools[hidden] { display: none; }
.lib-toollist { list-style: none; margin: 0; padding: 4px 0; max-height: 320px; overflow-y: auto; overscroll-behavior: contain; }
.lib-toollist li { display: flex; flex-direction: column; gap: 1px; padding: 4px 10px; min-width: 0; user-select: text; }
.lib-toolname { font: var(--code-style, normal) 500 11.5px var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); color: var(--fg-2); overflow-wrap: anywhere; }
.lib-tooldesc { font-size: 11.5px; line-height: 1.45; color: var(--muted); overflow-wrap: anywhere; white-space: normal; }
.lib-toolfoot { display: flex; align-items: center; gap: 8px; padding: 4px 6px 4px 10px; border-top: 1px solid var(--line-2); }
.lib-toolfoot .note { font-size: 11px; color: var(--faint); }
.lib-toolfoot button.text { height: 22px; font-size: 11.5px; }
.lib-health.checking::before { animation: lib-health-pulse 1s ease-in-out infinite alternate; }
@keyframes lib-health-pulse { to { opacity: .25; } }
@media (prefers-reduced-motion: reduce) { .lib-health.checking::before { animation: none; } }
+50 -4
View File
@@ -1357,7 +1357,7 @@
who.append(nm, healthEl(s.name));
const sub = el("div", "sub mono", serverLine(s));
sub.title = serverLine(s);
who.append(sub);
who.append(sub, toolsEl(s.name));
row.append(mark(s.icon, s.transport === "stdio" ? GLYPH.cmd : GLYPH.web), who,
agentChips(all, s.agents, chipsChange("servers/agents", s.name, "servers", (x) => serverRow(x, all)), { problems: s.problems, blocked: sseBlocked(s), all: true }));
if (picking) return pickRow(row, s.name);
@@ -1369,20 +1369,58 @@
// Whether a server works, as magpie found by connecting to it: started
// (or reached) and asked for its tools. Its row shows it as a dot and a
// few words, the whole reason in its tooltip; a click checks it again.
// A server that listed its tools shows them instead, by name and what
// each says it does (nf1qaz2w on Discord), with Check again under them.
const health = new Map(); // name → { key: the server as checked, h: what was found, null while checking }
const toolsOpen = new Set(); // the servers whose tools are shown
const healthKey = (s) => JSON.stringify([s.transport, s.command, s.args, s.env, s.url, s.headers, s.signIn]);
const toolList = (name) => { const h = health.get(name)?.h; return h?.state === "ok" ? h.toolList || [] : []; };
function recheck(name) {
const s = lib.servers.find((x) => x.name === name);
if (s && health.get(name)?.h) checkHealth([s], true);
}
function healthEl(name) {
const b = el("button", "lib-health");
b.type = "button";
b.dataset.server = name;
b.onclick = (e) => {
e.stopPropagation(); // the row opens the editor
const s = lib.servers.find((x) => x.name === name);
if (s && health.get(name)?.h) checkHealth([s], true);
if (!toolList(name).length) return recheck(name);
if (toolsOpen.has(name)) toolsOpen.delete(name); else toolsOpen.add(name);
paintHealth(name);
};
paintHealth(b);
return b;
}
// toolsEl is the list a server's status opens: filled by paintHealth
function toolsEl(name) {
const box = el("div", "lib-tools");
box.dataset.server = name;
box.hidden = true;
box.onclick = (e) => e.stopPropagation(); // reading or selecting it opens no editor
paintTools(box);
return box;
}
function paintTools(box) {
const name = box.dataset.server, list = toolList(name);
// while it is checked again the list stays as it was, so nothing under
// the click moves until the answer comes
if (health.get(name) && !health.get(name).h && !box.hidden) return;
box.hidden = !(toolsOpen.has(name) && list.length);
if (box.hidden) return box.replaceChildren();
const ul = el("ul", "lib-toollist");
for (const tl of list) {
const li = el("li", "");
li.append(el("span", "lib-toolname mono", tl.name));
if (tl.description) li.append(el("span", "lib-tooldesc", tl.description));
ul.append(li);
}
const foot = el("div", "lib-toolfoot");
const h = health.get(name).h;
if (h.tools > list.length) foot.append(el("span", "note", t("{n} more not shown", { n: h.tools - list.length })));
foot.append(el("span", "grow"), button(t("Check again"), "", () => recheck(name)));
box.replaceChildren(ul, foot);
}
async function checkHealth(list, fresh) {
if (!list.length) return;
const keys = new Map(list.map((s) => [s.name, healthKey(s)]));
@@ -1434,6 +1472,7 @@
for (const b of boxes) {
const e = health.get(b.dataset.server);
b.hidden = !e;
b.removeAttribute("aria-expanded");
if (!e) continue;
if (!e.h) {
b.className = "lib-health checking";
@@ -1444,8 +1483,15 @@
const [text, tip] = healthWords(e.h, lib.servers.find((s) => s.name === b.dataset.server));
b.className = "lib-health " + (e.h.state === "ok" ? "ok" : e.h.state === "auth" ? "auth" : "err");
b.replaceChildren(el("span", "", text));
b.title = tip + "\n" + t("Click to check again");
if (toolList(b.dataset.server).length) {
const open = toolsOpen.has(b.dataset.server);
b.classList.add("has-list");
b.setAttribute("aria-expanded", String(open));
b.title = tip + "\n" + (open ? t("Click to hide them") : t("Click to see them"));
} else b.title = tip + "\n" + t("Click to check again");
}
const name = typeof x === "string" ? x : x.dataset.server;
for (const box of page.querySelectorAll(`.lib-tools[data-server="${CSS.escape(name)}"]`)) paintTools(box);
}
// magpie's sign-in to a remote server (#615): signed in once here, and
@@ -0,0 +1,177 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// nf1qaz2w on Discord: "mcp现在好像只能看到有几个工具,看不到具体的工具名和描述".
// A server that listed its tools shows them under its row, by name and what
// each says it does, when its "N tools" status is clicked: no editor opens,
// nothing scrolls, the list fits a narrow window, and Check again under it
// checks that server afresh while the list stays put. A server that listed
// no tools still checks again on a click. In every language, both engines.
// No backend: the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/nf";
const LONG = "Read the complete contents of a file from the file system as text. Handles various text encodings and provides detailed error messages if the file cannot be read. Use this tool when you need to examine the contents of a single file.";
const fixture = () => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", skills: `${HOME}/.claude/skills`, mcp: `${HOME}/.claude.json` }],
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [],
servers: [
{ name: "filesystem", transport: "stdio", command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", HOME], agents: ["claude"] },
{ name: "bare", transport: "stdio", command: "bare-mcp", agents: [] },
...Array.from({ length: 6 }, (_, i) => ({ name: "more" + i, transport: "stdio", command: "more-mcp", agents: [] })),
],
});
const tools = [
{ name: "read_text_file", description: LONG },
{ name: "list_allowed_directories" }, // no description
{ name: "a_tool_with_a_very_long_name_that_has_no_spaces_in_it_at_all_anywhere" },
];
const found = (fresh) => ({
// 4 tools, 3 of them listed: one more than magpie keeps
filesystem: fresh ? { state: "ok", tools: 1, toolList: [{ name: "only_one", description: "The one left." }] } : { state: "ok", tools: 4, toolList: tools },
bare: { state: "ok", tools: 0 },
...Object.fromEntries(Array.from({ length: 6 }, (_, i) => ["more" + i, { state: "ok", tools: 0 }])),
});
function server(lang, checks) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang } } });
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/library") return route.fulfill({ json: fixture() });
if (url.pathname === "/api/library/mcp/check") {
const body = req.postDataJSON();
let release;
const held = new Promise((r) => (release = r));
checks.push({ ...body, release });
await held;
const all = found(body.fresh);
const names = body.names?.length ? body.names : Object.keys(all);
return route.fulfill({ json: { servers: Object.fromEntries(names.map((n) => [n, all[n]])) } });
}
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const words = {
en: { four: "4 tools", one: "1 tool", none: "0 tools", tip: "It started and listed its tools", see: "Click to see them", hide: "Click to hide them", again: "Click to check again", check: "Check again", more: "1 more not shown" },
zh: { four: "4 个工具", one: "1 个工具", none: "0 个工具", tip: "已启动并列出了它的工具", see: "点击查看工具", hide: "点击收起", again: "点击重新检查", check: "重新检测", more: "另有 1 个未显示" },
"zh-TW": { four: "4 個工具", one: "1 個工具", none: "0 個工具", tip: "已啟動並列出了它的工具", see: "點選查看工具", hide: "點選收起", again: "點選重新檢查", check: "重新檢測", more: "另有 1 個未顯示" },
ja: { four: "4 個のツール", one: "1 個のツール", none: "0 個のツール", tip: "起動してツールを一覧表示しました", see: "クリックしてツールを表示", hide: "クリックして閉じる", again: "クリックして再確認", check: "再確認", more: "ほか 1 個は非表示" },
de: { four: "4 Tools", one: "1 Tool", none: "0 Tools", tip: "Gestartet, Tools aufgelistet", see: "Klicken, um die Tools zu zeigen", hide: "Klicken zum Ausblenden", again: "Zum erneuten Prüfen klicken", check: "Erneut prüfen", more: "1 weitere nicht angezeigt" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
for (const width of [980, 420]) {
test(`${engine} ${lang} ${width}: an MCP server's tools are listed by name and description`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
const errors = [];
t.after(async () => { await browser.close(); });
const w = words[lang], checks = [];
const ctx = await browser.newContext({ viewport: { width, height: width < 600 ? 820 : 500 } });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("http://magpie.test/**", server(lang, checks));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
await page.locator("#view-library .lib-body:not(.lib-skel) .lib-row").first().waitFor();
const status = (name) => page.locator(`#view-library .lib-health[data-server="${name}"]`);
const list = page.locator('#view-library .lib-tools[data-server="filesystem"]');
const scrollTop = () => page.evaluate(() => document.querySelector("#view-library").scrollTop);
const where = () => status("filesystem").evaluate((b) => b.getBoundingClientRect().top);
for (let i = 0; i < 50 && !checks.length; i++) await page.waitForTimeout(20);
assert.equal(checks.length, 1);
checks[0].release();
await page.waitForFunction(() => !document.querySelector("#view-library .lib-health.checking"));
// the count says it opens the list; the list is shut till then
assert.equal(await status("filesystem").textContent(), w.four);
assert.equal(await status("filesystem").getAttribute("title"), w.tip + "\n" + w.see);
assert.equal(await status("filesystem").getAttribute("aria-expanded"), "false");
assert.equal(await list.isHidden(), true);
// one that listed none still checks again on a click
assert.equal(await status("bare").textContent(), w.none);
assert.equal(await status("bare").getAttribute("title"), w.tip + "\n" + w.again);
assert.equal(await status("bare").getAttribute("aria-expanded"), null);
// scrolled a little first, by the wheel as the reader would
await page.mouse.move(Math.min(490, width / 2), 250);
await page.mouse.wheel(0, 30);
await page.waitForFunction(() => document.querySelector("#view-library").scrollTop > 0);
await page.waitForTimeout(400);
const top = await scrollTop(), pillAt = await where();
// a click shows each tool's name and description, and asks nothing
await status("filesystem").click();
await list.waitFor();
await page.waitForTimeout(100);
// the row grows under it, and what was clicked stays where it was
// (the click guard takes back the pixel a centred row gives up)
assert.equal(await where(), pillAt, "the click moved what was clicked");
assert.ok(Math.abs((await scrollTop()) - top) <= 1, "the click scrolled the page");
assert.equal(await page.evaluate(() => document.querySelector("#modal").classList.contains("lib")), false, "the click opened the editor");
assert.equal(checks.length, 1, "opening the list checked the server again");
assert.equal(await status("filesystem").getAttribute("aria-expanded"), "true");
assert.equal(await status("filesystem").getAttribute("title"), w.tip + "\n" + w.hide);
const items = await list.locator("li").evaluateAll((lis) => lis.map((li) => [li.querySelector(".lib-toolname")?.textContent, li.querySelector(".lib-tooldesc")?.textContent ?? null]));
assert.deepEqual(items, [["read_text_file", LONG], ["list_allowed_directories", null], [tools[2].name, null]]);
assert.equal(await list.locator(".lib-toolfoot .note").textContent(), w.more);
// it fits the window: nothing wider than the page, the long name wraps
const fit = await page.evaluate(() => {
const v = document.querySelector("#view-library"), box = document.querySelector('.lib-tools[data-server="filesystem"]').getBoundingClientRect();
return { over: v.scrollWidth - v.clientWidth, right: box.right, w: innerWidth };
});
assert.ok(fit.over <= 0 && fit.right <= fit.w, "the list is wider than the window: " + JSON.stringify(fit));
// no coloured stripe down its side
const side = await list.evaluate((b) => { const s = getComputedStyle(b); return [s.borderLeftWidth, s.borderLeftColor, s.borderTopWidth, s.borderTopColor]; });
assert.deepEqual(side.slice(0, 2), side.slice(2), "the list has a left border of its own");
// reading it (a click on a description) opens no editor
await list.locator(".lib-tooldesc").first().click();
assert.equal(await page.evaluate(() => document.querySelector("#modal").classList.contains("lib")), false);
// Check again checks that one afresh; the list stays while it does
const at = await scrollTop(), pillThen = await where();
await list.locator(".lib-toolfoot button", { hasText: w.check }).click();
for (let i = 0; i < 50 && checks.length < 2; i++) await page.waitForTimeout(20);
assert.deepEqual({ names: checks[1].names, fresh: checks[1].fresh }, { names: ["filesystem"], fresh: true });
assert.equal(await list.isVisible(), true, "the list went away while checking");
assert.equal(await list.locator("li").count(), 3);
checks[1].release();
await page.waitForFunction((t) => document.querySelector('.lib-health[data-server="filesystem"]').textContent === t, w.one);
assert.deepEqual(await list.locator("li").evaluateAll((lis) => lis.map((li) => li.textContent)), ["only_oneThe one left."]);
assert.equal(await list.locator(".lib-toolfoot .note").count(), 0);
assert.equal(await scrollTop(), at, "Check again scrolled the page");
assert.equal(await where(), pillThen, "Check again moved the row");
// a click on the count shuts it again
await status("filesystem").click();
await list.waitFor({ state: "hidden" });
assert.equal(await status("filesystem").getAttribute("aria-expanded"), "false");
assert.equal(checks.length, 2);
// and the one with none checks again
await status("bare").click();
for (let i = 0; i < 50 && checks.length < 3; i++) await page.waitForTimeout(20);
assert.deepEqual({ names: checks[2].names, fresh: checks[2].fresh }, { names: ["bare"], fresh: true });
checks[2].release();
assert.equal(await page.locator("#view-library select").count(), 0);
assert.deepEqual(errors, []);
await ctx.close();
});
}
}
}
+114 -30
View File
@@ -35,6 +35,10 @@ type ServerHealth struct {
// sign-in or a key) or error (Why says what went wrong)
State string `json:"state"`
Tools int `json:"tools"`
// ToolList is each tool's name and what it says it does, as tools/list
// gave them, for the page to list (nf1qaz2w on Discord); at most
// maxToolList, while Tools counts every one
ToolList []Tool `json:"toolList,omitempty"`
// Why is the kind of error, for the page to put in its own words:
// notfound, start, exited, timeout, http, refused, unreachable,
// protocol, novar (a ${NAME} magpie's environment hasn't: Detail names
@@ -257,22 +261,113 @@ func initializeReq() []byte {
var initializedNote = []byte(`{"jsonrpc":"2.0","method":"notifications/initialized"}`)
// toolsOf is the health the reply to tools/list says: a server with no
// tools may not know the method at all.
func toolsOf(m *rpcMsg) ServerHealth {
// Tool is one tool a server listed: its name, and the first paragraph of
// its description, cut short.
type Tool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
// What of the tools a check keeps: every tool's name up to maxToolList,
// a description up to maxToolDesc runes, and up to maxToolPages pages of
// tools/list, each with a step's budget of its own.
const (
maxToolList = 500
maxToolName = 128
maxToolDesc = 500
maxToolPages = 10
)
// clip is s with its whitespace runs made one space, cut at n runes.
func clip(s string, n int) string {
s = strings.Join(strings.Fields(s), " ")
if r := []rune(s); len(r) > n {
return strings.TrimSpace(string(r[:n])) + "…"
}
return s
}
// toolDesc is the first paragraph of a tool's description: the rest is
// usually how to call it, which the agent reads, not the person.
func toolDesc(d string) string {
d = strings.TrimSpace(strings.ReplaceAll(d, "\r\n", "\n"))
if i := strings.Index(d, "\n\n"); i >= 0 {
d = d[:i]
}
return clip(d, maxToolDesc)
}
// toolsOf is the health one reply to tools/list says, and the cursor of
// the page after it: a server with no tools may not know the method at all.
func toolsOf(m *rpcMsg) (ServerHealth, string) {
if m.Error != nil {
if m.Error.Code == -32601 {
return ServerHealth{State: "ok"}
return ServerHealth{State: "ok"}, ""
}
return failed("protocol", "tools/list: "+m.Error.Message)
return failed("protocol", "tools/list: "+m.Error.Message), ""
}
var r struct {
Tools []json.RawMessage `json:"tools"`
Tools []struct {
Name string `json:"name"`
Title string `json:"title"`
Description string `json:"description"`
} `json:"tools"`
NextCursor string `json:"nextCursor"`
}
if err := json.Unmarshal(m.Result, &r); err != nil {
return failed("protocol", "tools/list: "+err.Error())
return failed("protocol", "tools/list: "+err.Error()), ""
}
return ServerHealth{State: "ok", Tools: len(r.Tools)}
h := ServerHealth{State: "ok", Tools: len(r.Tools)}
for _, t := range r.Tools {
if len(h.ToolList) == maxToolList {
break
}
d := toolDesc(t.Description)
if d == "" {
d = clip(t.Title, maxToolDesc)
}
h.ToolList = append(h.ToolList, Tool{Name: clip(t.Name, maxToolName), Description: d})
}
return h, r.NextCursor
}
// listTools asks for the server's tools, a page at a time while it names
// a next one, up to maxToolPages. ask sends a request and reads the reply
// to its id. A page after the first that is refused ends the list there.
func listTools(ctx context.Context, ask func(id int, req []byte) (*rpcMsg, *ServerHealth)) ServerHealth {
var all ServerHealth
cursor := ""
for page := 0; page < maxToolPages; page++ {
stepTo(ctx, "tools/list")
var params any
if cursor != "" {
params = map[string]any{"cursor": cursor}
}
id := 2 + page
m, bad := ask(id, request(id, "tools/list", params))
if bad != nil {
return *bad
}
h, next := toolsOf(m)
if h.State != "ok" {
if page == 0 {
return h
}
break
}
all.State = "ok"
all.Tools += h.Tools
for _, t := range h.ToolList {
if len(all.ToolList) < maxToolList {
all.ToolList = append(all.ToolList, t)
}
}
if next == "" || next == cursor {
break
}
cursor = next
}
return all
}
// initError is what an error reply to initialize says.
@@ -425,13 +520,10 @@ func checkStdio(ctx context.Context, s *Server) ServerHealth {
return *h
}
_ = send(initializedNote)
stepTo(ctx, "tools/list")
_ = send(request(2, "tools/list", nil))
m, h = await(2)
if h != nil {
return *h
}
return toolsOf(m)
return listTools(ctx, func(id int, req []byte) (*rpcMsg, *ServerHealth) {
_ = send(req)
return await(id)
})
}
func exitHealth(err error, errs *tail) ServerHealth {
@@ -574,12 +666,7 @@ func checkHTTP(ctx context.Context, s *Server) ServerHealth {
} else if ctx.Err() != nil {
return timedOut(ctx)
}
stepTo(ctx, "tools/list")
m, h = call(2, request(2, "tools/list", nil))
if h != nil {
return *h
}
return toolsOf(m)
return listTools(ctx, call)
}
// endSession tells the server the check is done with its session, as a
@@ -784,13 +871,10 @@ func checkSSE(ctx context.Context, s *Server) ServerHealth {
if h := post(initializedNote); h != nil && h.Why == "timeout" {
return *h
}
stepTo(ctx, "tools/list")
if h := post(request(2, "tools/list", nil)); h != nil {
return *h
}
m, h = await(2)
if h != nil {
return *h
}
return toolsOf(m)
return listTools(ctx, func(id int, req []byte) (*rpcMsg, *ServerHealth) {
if h := post(req); h != nil {
return nil, h
}
return await(id)
})
}
+12 -1
View File
@@ -12,6 +12,7 @@ import (
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
@@ -66,6 +67,16 @@ func TestFakeMCPServer(t *testing.T) {
case "notifications/initialized":
os.WriteFile(os.Getenv("MAGPIE_FAKE_MCP_INIT"), []byte("yes"), 0o644)
case "tools/list":
// file: the reply a real server gave, under this request's id
if f := os.Getenv("MAGPIE_FAKE_MCP_TOOLS"); f != "" {
var r map[string]any
b, _ := os.ReadFile(f)
json.Unmarshal(b, &r)
r["id"] = *m.ID
b, _ = json.Marshal(r)
fmt.Println(string(b))
continue
}
fmt.Printf(`{"jsonrpc":"2.0","method":"notifications/message","params":{}}`+"\n"+`{"jsonrpc":"2.0","id":%d,"result":{"tools":[{"name":"a"},{"name":"b"},{"name":"c"}]}}`+"\n", *m.ID)
}
}
@@ -235,7 +246,7 @@ func TestCheckHTTP(t *testing.T) {
defer srv.Close()
h := CheckServer(context.Background(), &Server{Name: "r", Transport: "http", URL: srv.URL})
h.At = 0
if h != c.want {
if !reflect.DeepEqual(h, c.want) {
t.Fatalf("got %+v, want %+v", h, c.want)
}
})
+130
View File
@@ -0,0 +1,130 @@
package library
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"unicode/utf8"
)
// A check keeps each tool's name and what it says it does, for the
// Library page to list (nf1qaz2w on Discord: "只能看到有几个工具,看不到具体
// 的工具名和描述"). The reply is the one @modelcontextprotocol/server-filesystem
// gave to tools/list, byte for byte.
func TestCheckKeepsToolNames(t *testing.T) {
file, err := filepath.Abs("testdata/filesystem-tools-list.json")
if err != nil {
t.Fatal(err)
}
h := CheckServer(context.Background(), fakeStdio(t, "ok", map[string]string{"MAGPIE_FAKE_MCP_TOOLS": file}))
if h.State != "ok" || h.Tools != 14 || len(h.ToolList) != 14 {
t.Fatalf("got %+v, want ok with 14 tools, each listed", h)
}
want := map[int]Tool{
0: {"read_file", "Read the complete contents of a file as text. DEPRECATED: Use read_text_file instead."},
13: {"list_allowed_directories", "Returns the list of directories that this server is allowed to access. Subdirectories within these allowed directories are also accessible. Use this to understand which directories and their nested paths are available before trying to access files."},
}
for i, w := range want {
if h.ToolList[i] != w {
t.Errorf("tool %d: got %+v, want %+v", i, h.ToolList[i], w)
}
}
// the longest, 457 characters, whole
if d := h.ToolList[1].Description; h.ToolList[1].Name != "read_text_file" || utf8.RuneCountInString(d) != 457 || strings.HasSuffix(d, "…") {
t.Errorf("read_text_file: %+v", h.ToolList[1])
}
}
// A tool with no description, one with only a title, one whose description
// runs on, and the pages tools/list is split into (nextCursor) all come
// through, in the JSON the page reads.
func TestCheckToolPages(t *testing.T) {
long := strings.Repeat("word ", 200)
var cursors []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete {
return
}
var m struct {
ID *int `json:"id"`
Method string `json:"method"`
Params struct {
Cursor string `json:"cursor"`
} `json:"params"`
}
json.NewDecoder(r.Body).Decode(&m)
w.Header().Set("Content-Type", "application/json")
switch m.Method {
case "initialize":
fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%d,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{}}}}`, *m.ID)
case "tools/list":
cursors = append(cursors, m.Params.Cursor)
switch m.Params.Cursor {
case "":
fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%d,"result":{"tools":[`+
`{"name":"search","description":"Search the web.\n\nArgs:\n q: the query","inputSchema":{"type":"object"}},`+
`{"name":"ping","inputSchema":{"type":"object"}},`+
`{"name":"fetch","title":"Fetch a page","description":"","inputSchema":{"type":"object"}}],"nextCursor":"p2"}}`, *m.ID)
case "p2":
fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%d,"result":{"tools":[{"name":"long","description":%q,"inputSchema":{"type":"object"}}]}}`, *m.ID, long)
}
default:
w.WriteHeader(202)
}
}))
defer srv.Close()
h := CheckServer(context.Background(), &Server{Name: "r", Transport: "http", URL: srv.URL})
if h.State != "ok" || h.Tools != 4 || len(h.ToolList) != 4 {
t.Fatalf("got %+v, want ok with 4 tools over 2 pages", h)
}
if strings.Join(cursors, ",") != ",p2" {
t.Errorf("cursors asked for: %q", cursors)
}
for i, w := range []Tool{{"search", "Search the web."}, {"ping", ""}, {"fetch", "Fetch a page"}} {
if h.ToolList[i] != w {
t.Errorf("tool %d: got %+v, want %+v", i, h.ToolList[i], w)
}
}
if d := h.ToolList[3].Description; h.ToolList[3].Name != "long" || !strings.HasPrefix(d, "word word") || !strings.HasSuffix(d, "…") || utf8.RuneCountInString(d) > maxToolDesc+1 {
t.Errorf("long: %q (%d runes)", d, utf8.RuneCountInString(d))
}
b, _ := json.Marshal(h)
if !strings.Contains(string(b), `"toolList":[{"name":"search","description":"Search the web."},{"name":"ping"},`) {
t.Errorf("JSON: %s", b)
}
}
// A server that names a next page forever is asked maxToolPages times.
func TestCheckToolPagesEnd(t *testing.T) {
var lists atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var m struct {
ID *int `json:"id"`
Method string `json:"method"`
}
json.NewDecoder(r.Body).Decode(&m)
w.Header().Set("Content-Type", "application/json")
switch m.Method {
case "initialize":
fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%d,"result":{"protocolVersion":"2025-06-18"}}`, *m.ID)
case "tools/list":
n := lists.Add(1)
fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%d,"result":{"tools":[{"name":"t%d"}],"nextCursor":"c%d"}}`, *m.ID, n, n)
default:
io.Copy(io.Discard, r.Body)
w.WriteHeader(202)
}
}))
defer srv.Close()
h := CheckServer(context.Background(), &Server{Name: "r", Transport: "http", URL: srv.URL})
if h.State != "ok" || h.Tools != maxToolPages || int(lists.Load()) != maxToolPages {
t.Fatalf("got %+v after %d pages, want ok with %d", h, lists.Load(), maxToolPages)
}
}
File diff suppressed because one or more lines are too long