diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 31c93ea64..3f5237d64 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -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/` (#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/` (#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) | diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 6c54eb1a1..2ecf6746b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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", diff --git a/internal/gui/assets/library.css b/internal/gui/assets/library.css index 55c641e67..f0ff99d73 100644 --- a/internal/gui/assets/library.css +++ b/internal/gui/assets/library.css @@ -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; } } diff --git a/internal/gui/assets/library.js b/internal/gui/assets/library.js index f64d36527..ae2c0da94 100644 --- a/internal/gui/assets/library.js +++ b/internal/gui/assets/library.js @@ -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 diff --git a/internal/gui/tests/library-mcp-tools.test.cjs b/internal/gui/tests/library-mcp-tools.test.cjs new file mode 100644 index 000000000..a744a1840 --- /dev/null +++ b/internal/gui/tests/library-mcp-tools.test.cjs @@ -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(); + }); + } + } +} diff --git a/internal/library/mcp_check.go b/internal/library/mcp_check.go index edd99f772..2754a8dee 100644 --- a/internal/library/mcp_check.go +++ b/internal/library/mcp_check.go @@ -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) + }) } diff --git a/internal/library/mcp_check_test.go b/internal/library/mcp_check_test.go index 13d055144..b66032453 100644 --- a/internal/library/mcp_check_test.go +++ b/internal/library/mcp_check_test.go @@ -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) } }) diff --git a/internal/library/mcp_tools_test.go b/internal/library/mcp_tools_test.go new file mode 100644 index 000000000..a4d250cc5 --- /dev/null +++ b/internal/library/mcp_tools_test.go @@ -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) + } +} diff --git a/internal/library/testdata/filesystem-tools-list.json b/internal/library/testdata/filesystem-tools-list.json new file mode 100644 index 000000000..6749951da --- /dev/null +++ b/internal/library/testdata/filesystem-tools-list.json @@ -0,0 +1 @@ +{"result":{"tools":[{"name":"read_file","title":"Read File (Deprecated)","description":"Read the complete contents of a file as text. DEPRECATED: Use read_text_file instead.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"},"tail":{"description":"If provided, returns only the last N lines of the file","type":"number"},"head":{"description":"If provided, returns only the first N lines of the file","type":"number"}},"required":["path"]},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"read_text_file","title":"Read Text File","description":"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. Use the 'head' parameter to read only the first N lines of a file, or the 'tail' parameter to read only the last N lines of a file. Operates on the file as text regardless of extension. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"},"tail":{"description":"If provided, returns only the last N lines of the file","type":"number"},"head":{"description":"If provided, returns only the first N lines of the file","type":"number"}},"required":["path"]},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"read_media_file","title":"Read Media File","description":"Read a file and return it as a base64-encoded content block with its MIME type. Image and audio files are returned as image/audio content; any other file type is returned as an embedded resource. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"}},"required":["path"]},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"type":{"type":"string","enum":["image","audio"]},"data":{"type":"string"},"mimeType":{"type":"string"}},"required":["type","data","mimeType"],"additionalProperties":false},{"type":"object","properties":{"type":{"type":"string","const":"resource"},"resource":{"type":"object","properties":{"uri":{"type":"string"},"mimeType":{"type":"string"},"blob":{"type":"string"}},"required":["uri","blob"],"additionalProperties":false}},"required":["type","resource"],"additionalProperties":false}]}}},"required":["content"],"additionalProperties":false}},{"name":"read_multiple_files","title":"Read Multiple Files","description":"Read the contents of multiple files simultaneously. This is more efficient than reading files one by one when you need to analyze or compare multiple files. Each file's content is returned with its path as a reference. Failed reads for individual files won't stop the entire operation. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"paths":{"minItems":1,"type":"array","items":{"type":"string"},"description":"Array of file paths to read. Each path must be a string pointing to a valid file within allowed directories."}},"required":["paths"]},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"write_file","title":"Write File","description":"Create a new file or completely overwrite an existing file with new content. Use with caution as it will overwrite existing files without warning. Handles text content with proper encoding. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path","content"]},"annotations":{"readOnlyHint":false,"idempotentHint":true,"destructiveHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"edit_file","title":"Edit File","description":"Make line-based edits to a text file. Each edit replaces exact line sequences with new content. Returns a git-style diff showing the changes made. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"},"edits":{"type":"array","items":{"type":"object","properties":{"oldText":{"type":"string","description":"Text to search for - must match exactly"},"newText":{"type":"string","description":"Text to replace with"}},"required":["oldText","newText"]}},"dryRun":{"default":false,"description":"Preview changes using git-style diff format","type":"boolean"}},"required":["path","edits"]},"annotations":{"readOnlyHint":false,"idempotentHint":false,"destructiveHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"create_directory","title":"Create Directory","description":"Create a new directory or ensure a directory exists. Can create multiple nested directories in one operation. If the directory already exists, this operation will succeed silently. Perfect for setting up directory structures for projects or ensuring required paths exist. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"}},"required":["path"]},"annotations":{"readOnlyHint":false,"idempotentHint":true,"destructiveHint":false,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"list_directory","title":"List Directory","description":"Get a detailed listing of all files and directories in a specified path. Results clearly distinguish between files and directories with [FILE] and [DIR] prefixes. This tool is essential for understanding directory structure and finding specific files within a directory. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"}},"required":["path"]},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"list_directory_with_sizes","title":"List Directory with Sizes","description":"Get a detailed listing of all files and directories in a specified path, including sizes. Results clearly distinguish between files and directories with [FILE] and [DIR] prefixes. This tool is useful for understanding directory structure and finding specific files within a directory. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"},"sortBy":{"default":"name","description":"Sort entries by name or size","type":"string","enum":["name","size"]}},"required":["path"]},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"directory_tree","title":"Directory Tree","description":"Get a recursive tree view of files and directories as a JSON structure. Each entry includes 'name', 'type' (file/directory), and 'children' for directories. Files have no children array, while directories always have a children array (which may be empty). The output is formatted with 2-space indentation for readability. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"},"excludePatterns":{"default":[],"type":"array","items":{"type":"string"}}},"required":["path"]},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"move_file","title":"Move File","description":"Move or rename files and directories. Can move files between directories and rename them in a single operation. If the destination exists, the operation will fail. Works across different directories and can be used for simple renaming within the same directory. Both source and destination must be within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"source":{"type":"string"},"destination":{"type":"string"}},"required":["source","destination"]},"annotations":{"readOnlyHint":false,"idempotentHint":false,"destructiveHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"search_files","title":"Search Files","description":"Recursively search for files and directories matching a pattern. The patterns should be glob-style patterns that match paths relative to the working directory. Use pattern like '*.ext' to match files in current directory, and '**/*.ext' to match files in all subdirectories. Returns full paths to all matching items. Great for finding files when you don't know their exact location. Only searches within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"},"pattern":{"type":"string"},"excludePatterns":{"default":[],"type":"array","items":{"type":"string"}}},"required":["path","pattern"]},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"get_file_info","title":"Get File Info","description":"Retrieve detailed metadata about a file or directory. Returns comprehensive information including size, creation time, last modified time, permissions, and type. This tool is perfect for understanding file characteristics without reading the actual content. Only works within allowed directories.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"path":{"type":"string"}},"required":["path"]},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}},{"name":"list_allowed_directories","title":"List Allowed Directories","description":"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.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{}},"annotations":{"readOnlyHint":true,"openWorldHint":false},"execution":{"taskSupport":"forbidden"},"outputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"content":{"type":"string"}},"required":["content"],"additionalProperties":false}}]},"jsonrpc":"2.0","id":2}