diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 242a87f5c..f773a35c0 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1007,6 +1007,35 @@ const I18N = { "this server already works without signing in, so there is nothing to sign in to: the agents given it can use it as it is. A key it takes goes in Headers; a server that signs in at another address (as Exa's ?login) needs that URL": "这个服务器不登录就已经能用,没有可登录的:分配到它的 agent 直接就能用。它要的密钥填在请求头里;要在另一个地址登录的服务器(如 Exa 的 ?login)需要填那个 URL", "Finish signing in in your browser…": "请在浏览器中完成登录…", "The agents given it use magpie's sign-in": "分配到它的 agent 都用 magpie 的登录", + "1 tool": "1 个工具", + "{n} tools": "{n} 个工具", + "It started and listed its tools": "已启动并列出了它的工具", + "needs sign-in": "需要登录", + "The server asks for a sign-in — open it to sign in once in magpie": "服务器要求登录 — 打开它,在 magpie 里登录一次即可", + "The server asks for a sign-in": "服务器要求登录", + "The server refused magpie (HTTP {code}) — a key in its headers may be missing or wrong": "服务器拒绝了 magpie(HTTP {code})— Headers 里的密钥可能缺失或有误", + "can't start: {cmd} not found": "无法启动:找不到 {cmd}", + "Can't start it: there is no {cmd} on the PATH magpie has": "无法启动:magpie 的 PATH 里没有 {cmd}", + "can't start": "无法启动", + "Can't start it": "无法启动", + "exited ({code})": "已退出({code})", + "exited": "已退出", + "It exited with code {code} before listing its tools": "列出工具前就退出了,退出码 {code}", + "It exited before listing its tools": "列出工具前就退出了", + "no answer": "无响应", + "No answer in 15 seconds": "15 秒内没有响应", + "The server answered {status}": "服务器返回 {status}", + "connection refused": "连接被拒绝", + "Nothing is listening at that address": "该地址上没有服务在监听", + "can't reach": "无法连接", + "Can't reach the server": "无法连接到服务器", + "bad reply": "响应无效", + "It answered, but not as an MCP server does": "有响应,但不是 MCP 服务器的格式", + "couldn't check": "无法检查", + "magpie couldn't check it": "magpie 无法检查它", + "checking…": "检查中…", + "Connecting to it to list its tools": "正在连接并列出它的工具", + "Click to check again": "点击重新检查", "Sign-in ran out": "登录已失效", "Sign in again": "重新登录", "Sign-in required": "需要重新登录", diff --git a/internal/gui/assets/library.css b/internal/gui/assets/library.css index e30c5c538..b35f3d2e3 100644 --- a/internal/gui/assets/library.css +++ b/internal/gui/assets/library.css @@ -399,6 +399,26 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-project { margin-bottom: 8px; } .lib-project.missing .lib-projhead .name { color: var(--muted); } .lib-projhead .lib-tags { max-width: 45%; overflow: hidden; flex-wrap: nowrap; } +/* whether a server works, beside its name: a dot and a few words, the + whole reason in the tooltip; a click checks it again */ +.lib-srvwho { display: grid; grid-template-columns: minmax(0, auto) minmax(0, 1fr); align-items: center; } +.lib-srvwho > .name { min-width: 0; } +.lib-srvwho > .lib-health { justify-self: start; max-width: min(220px, 100%); } +.lib-srvwho > :not(.name):not(.lib-health) { grid-column: 1 / -1; } +.lib-health { display: inline-flex; flex: 0 1 auto; min-width: 0; align-items: center; gap: 5px; max-width: 220px; height: 17px; margin-left: 7px; padding: 0 6px; border-radius: 6px; + font: 400 11px var(--font); color: var(--muted); white-space: nowrap; transition: background .14s var(--ease); } +.lib-health > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.lib-health[hidden] { display: none; } +.lib-health:hover { background: var(--pill); } +.lib-health::before { content: ""; flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--faint); } +.lib-health.ok::before { background: var(--green); } +.lib-health.auth { color: var(--amber); } +.lib-health.auth::before { background: var(--amber); } +.lib-health.err { color: var(--red); } +.lib-health.err::before { background: var(--red); } +.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; } } .lib-tag.lib-dot::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: var(--muted); } .lib-projopts { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding: 8px 12px 8px 49px; border-top: 1px solid var(--line-2); background: var(--card-2); } .lib-projopts .note { font-size: 11px; color: var(--faint); line-height: 1.45; min-width: 0; flex: 1 1 220px; } diff --git a/internal/gui/assets/library.js b/internal/gui/assets/library.js index 73e726896..0054db06d 100644 --- a/internal/gui/assets/library.js +++ b/internal/gui/assets/library.js @@ -1190,6 +1190,10 @@ const after = el("div", "after-list"); after.append(button(t("+ Add server"), "", () => editServer(null))); body.append(after); + // each server is checked once a session, and again only once it + // changed; once the rows are on the page, for them to show it + const unchecked = lib.servers.filter((s) => health.get(s.name)?.key !== healthKey(s)); + queueMicrotask(() => checkHealth(unchecked)); } // an agent's own servers (Codex's node_repl, added each time it starts) // aren't listed: magpie leaves them as they are @@ -1214,7 +1218,9 @@ const nm = el("div", "name mono", s.name); if (s.signIn?.dead) nm.append(tag(t("Sign-in ran out"), "warn", t("Open it to sign in again"))); else if (s.signIn?.signedIn) nm.append(tag(t("Signed in"), "lib-signed", t("The agents given it use magpie's sign-in"))); - who.append(nm); + // its status beside the name, not in it: the name is still the name + who.classList.add("lib-srvwho"); + who.append(nm, healthEl(s.name)); const sub = el("div", "sub mono", serverLine(s)); sub.title = serverLine(s); who.append(sub); @@ -1225,6 +1231,79 @@ return row; } + // 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. + const health = new Map(); // name → { key: the server as checked, h: what was found, null while checking } + const healthKey = (s) => JSON.stringify([s.transport, s.command, s.args, s.env, s.url, s.headers, s.signIn]); + 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); + }; + paintHealth(b); + return b; + } + async function checkHealth(list, fresh) { + if (!list.length) return; + const keys = new Map(list.map((s) => [s.name, healthKey(s)])); + for (const [name, key] of keys) { health.set(name, { key, h: null }); paintHealth(name); } + let got = {}, failed = null; + try { got = (await api("library/mcp/check", { names: [...keys.keys()], fresh: !!fresh })).servers || {}; } catch (e) { failed = e.message; } + for (const [name, key] of keys) { + // a server changed while it was checked has been asked for again + if (health.get(name)?.key !== key) continue; + const h = got[name] || (failed ? { state: "error", why: "request", detail: failed } : null); + if (h) health.set(name, { key, h }); else health.delete(name); + paintHealth(name); + } + } + function healthWords(h, s) { + if (h.state === "ok") return [h.tools === 1 ? t("1 tool") : t("{n} tools", { n: h.tools }), t("It started and listed its tools")]; + if (h.state === "auth") { + const why = h.oauth + ? (s?.transport === "http" ? t("The server asks for a sign-in — open it to sign in once in magpie") : t("The server asks for a sign-in")) + : t("The server refused magpie (HTTP {code}) — a key in its headers may be missing or wrong", { code: h.code || 401 }); + return [t("needs sign-in"), h.detail ? why + "\n" + h.detail : why]; + } + const more = (x) => (h.detail ? x + "\n" + h.detail : x); + switch (h.why) { + case "notfound": return [t("can't start: {cmd} not found", { cmd: h.detail }), t("Can't start it: there is no {cmd} on the PATH magpie has", { cmd: h.detail })]; + case "start": return [t("can't start"), more(t("Can't start it"))]; + case "exited": return [h.code ? t("exited ({code})", { code: h.code }) : t("exited"), more(h.code ? t("It exited with code {code} before listing its tools", { code: h.code }) : t("It exited before listing its tools"))]; + case "timeout": return [t("no answer"), more(t("No answer in 15 seconds"))]; + case "http": return ["HTTP " + h.code, t("The server answered {status}", { status: h.detail })]; + case "refused": return [t("connection refused"), more(t("Nothing is listening at that address"))]; + case "unreachable": return [t("can't reach"), more(t("Can't reach the server"))]; + case "protocol": return [t("bad reply"), more(t("It answered, but not as an MCP server does"))]; + default: return [t("couldn't check"), more(t("magpie couldn't check it"))]; + } + } + // paintHealth fills a row's status in place, by the button or the + // server's name, so a check ending moves nothing on the page + function paintHealth(x) { + const boxes = typeof x === "string" ? page.querySelectorAll(`.lib-health[data-server="${CSS.escape(x)}"]`) : [x]; + for (const b of boxes) { + const e = health.get(b.dataset.server); + b.hidden = !e; + if (!e) continue; + if (!e.h) { + b.className = "lib-health checking"; + b.replaceChildren(el("span", "", t("checking…"))); + b.title = t("Connecting to it to list its tools"); + continue; + } + 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"); + } + } + // magpie's sign-in to a remote server (#615): signed in once here, and // every agent given the server reaches it through magpie, with it let mcpSigning = null; // { name, id, state, error } while one is under way diff --git a/internal/gui/library.go b/internal/gui/library.go index dc0c753b6..d005a5fd4 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -303,6 +303,24 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { } writeJSON(rw, v) }) + // whether the servers work, by connecting to them: those named, or every + // one; a server checked this session as it is now is answered from then + mux.HandleFunc("POST /api/library/mcp/check", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Names []string + Fresh bool + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + m, err := library.CheckServers(r.Context(), in.Names, in.Fresh) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, map[string]any{"servers": m}) + }) // every change answers with the page as it is after it, and what it did mux.HandleFunc("POST /api/library/{what}/{action}", func(rw http.ResponseWriter, r *http.Request) { var in struct { diff --git a/internal/gui/tests/library-mcp-health.test.cjs b/internal/gui/tests/library-mcp-health.test.cjs new file mode 100644 index 000000000..a19ed2a29 --- /dev/null +++ b/internal/gui/tests/library-mcp-health.test.cjs @@ -0,0 +1,167 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Each MCP server's row says whether it works (Discord: lc asked for a +// status per server), as magpie found by connecting to it: a dot and a few +// words beside its name, the whole reason in its tooltip. The servers are +// checked once when the MCP tab opens, not again on coming back to it; a +// click on a row's status checks that one again (fresh), without opening +// the editor or moving the page. In English and Chinese. 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/lc"; +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: "files", transport: "stdio", command: "npx", args: ["files-mcp"], agents: ["claude"] }, + { name: "linear", transport: "http", url: "https://mcp.linear.app/mcp", agents: [], signIn: { signedIn: false } }, + { name: "fetch", transport: "stdio", command: "uvx", args: ["mcp-server-fetch"], agents: [] }, + { name: "github", transport: "stdio", command: "github-mcp", agents: [] }, + { name: "slow", transport: "http", url: "https://slow.example.com/mcp", agents: [], signIn: { signedIn: false } }, + ], +}); +const found = { + files: { state: "ok", tools: 12 }, + linear: { state: "auth", code: 401, oauth: true }, + fetch: { state: "error", why: "notfound", detail: "uvx" }, + github: { state: "error", why: "exited", code: 1, detail: "Error: GITHUB_PERSONAL_ACCESS_TOKEN is not set" }, + slow: { state: "error", why: "timeout" }, +}; + +// checks holds each check asked for; a check's answer waits for release() +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 names = body.names?.length ? body.names : Object.keys(found); + const servers = Object.fromEntries(names.map((n) => [n, body.fresh && n === "files" ? { state: "ok", tools: 13 } : found[n]])); + return route.fulfill({ json: { servers } }); + } + 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: { + checking: "checking…", + files: ["12 tools", "It started and listed its tools"], + linear: ["needs sign-in", "The server asks for a sign-in — open it to sign in once in magpie"], + fetch: ["can't start: uvx not found", "Can't start it: there is no uvx on the PATH magpie has"], + github: ["exited (1)", "It exited with code 1 before listing its tools\nError: GITHUB_PERSONAL_ACCESS_TOKEN is not set"], + slow: ["no answer", "No answer in 15 seconds"], + again: "Click to check again", fresh: "13 tools", skills: "Skills", + }, + zh: { + checking: "检查中…", + files: ["12 个工具", "已启动并列出了它的工具"], + linear: ["需要登录", "服务器要求登录 — 打开它,在 magpie 里登录一次即可"], + fetch: ["无法启动:找不到 uvx", "无法启动:magpie 的 PATH 里没有 uvx"], + github: ["已退出(1)", "列出工具前就退出了,退出码 1\nError: GITHUB_PERSONAL_ACCESS_TOKEN is not set"], + slow: ["无响应", "15 秒内没有响应"], + again: "点击重新检查", fresh: "13 个工具", skills: "技能", + }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": an MCP server's row says whether it works", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + + for (const lang of ["en", "zh"]) { + await t.test(lang, async () => { + const w = words[lang], checks = []; + const ctx = await browser.newContext({ viewport: { width: 980, height: 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-row").first().waitFor(); + const status = (name) => page.locator(`#view-library .lib-health[data-server="${name}"]`); + + // every server asked for at once, each showing it's being checked + for (let i = 0; i < 50 && !checks.length; i++) await page.waitForTimeout(20); + assert.equal(checks.length, 1); + assert.deepEqual([...checks[0].names].sort(), ["fetch", "files", "github", "linear", "slow"]); + assert.equal(checks[0].fresh, false); + for (const n of Object.keys(found)) { + assert.equal(await status(n).textContent(), w.checking); + assert.equal(await status(n).evaluate((b) => b.classList.contains("checking")), true); + } + checks[0].release(); + + // each status in a few words, the whole reason in its tooltip + await page.waitForFunction(() => !document.querySelector("#view-library .lib-health.checking")); + const cls = { files: "ok", linear: "auth", fetch: "err", github: "err", slow: "err" }; + for (const [n, [text, tip]] of Object.entries(w).filter(([k]) => k in found)) { + assert.equal(await status(n).textContent(), text, n); + assert.equal(await status(n).getAttribute("title"), tip + "\n" + w.again, n); + assert.equal(await status(n).evaluate((b, c) => b.classList.contains(c), cls[n]), true, n); + // a dot, not a coloured stripe + assert.equal(await status(n).evaluate((b) => getComputedStyle(b).borderLeftWidth), "0px"); + assert.equal(await status(n).evaluate((b) => getComputedStyle(b, "::before").borderRadius), "50%"); + } + // it stays on the row's name line, one line high + const box = await status("fetch").boundingBox(); + assert.ok(box.height <= 18, "status wraps: " + box.height); + + // back from another tab: not checked again + await page.locator(".lib-tabs button", { hasText: w.skills }).click(); + await page.locator(".lib-tabs button", { hasText: /MCP/ }).click(); + await status("files").waitFor(); + await page.waitForTimeout(150); + assert.equal(checks.length, 1, "the servers were checked again on coming back"); + assert.equal(await status("files").textContent(), w.files[0]); + + // a click checks that server again, opens no editor, moves nothing + // scrolled a little first, by the wheel as the reader would + await page.mouse.move(490, 250); + await page.mouse.wheel(0, 40); + await page.waitForFunction(() => document.querySelector("#view-library").scrollTop > 0); + await page.waitForTimeout(400); + const top = await page.evaluate(() => document.querySelector("#view-library").scrollTop); + await status("files").click(); + assert.equal(await page.evaluate(() => document.querySelector("#view-library").scrollTop), top); + 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: ["files"], fresh: true }); + assert.equal(await status("files").textContent(), w.checking); + assert.equal(await status("linear").textContent(), w.linear[0], "another row was touched"); + checks[1].release(); + await page.waitForFunction((t) => document.querySelector('.lib-health[data-server="files"]').textContent === t, w.fresh); + assert.equal(await page.evaluate(() => document.querySelector("#modal").classList.contains("lib")), false, "the click opened the editor"); + assert.equal(await page.evaluate(() => document.querySelector("#view-library").scrollTop), top); + assert.equal(await page.locator("#view-library select").count(), 0); + await ctx.close(); + }); + } + }); +} diff --git a/internal/library/mcp_check.go b/internal/library/mcp_check.go new file mode 100644 index 000000000..49eecf068 --- /dev/null +++ b/internal/library/mcp_check.go @@ -0,0 +1,717 @@ +package library + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "strings" + "sync" + "syscall" + "time" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/mcpauth" + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/proc" +) + +// The Library page says of each server whether it works, found the only +// way that tells: by connecting to it as an agent would. A command is +// started, asked to initialize and to list its tools, and ended; a URL is +// asked the same over HTTP. Nothing is written anywhere: the check only +// reads the library, and what it found is kept in memory for the session. + +// ServerHealth is what a check of one server found. +type ServerHealth struct { + // State is ok (it answered, with Tools tools), auth (it asks for a + // sign-in or a key) or error (Why says what went wrong) + State string `json:"state"` + Tools int `json:"tools"` + // Why is the kind of error, for the page to put in its own words: + // notfound, start, exited, timeout, http, refused, unreachable, protocol + Why string `json:"why,omitempty"` + Code int `json:"code,omitempty"` // the exit code, or the HTTP status + Detail string `json:"detail,omitempty"` // the last line it wrote to stderr, or the error's text + // OAuth is a refusal that named a sign-in (WWW-Authenticate), which + // magpie can do itself for a streamable HTTP server + OAuth bool `json:"oauth,omitempty"` + At int64 `json:"at"` // when it was checked, unix ms +} + +// checkTimeout is how long a server has to start and list its tools: npx +// fetching a package the first time can take a while. +var checkTimeout = 15 * time.Second + +// checkAtOnce is how many servers are checked together, each a process or +// a few requests. +const checkAtOnce = 4 + +const mcpProtocol = "2025-06-18" + +var checkClient = &http.Client{Transport: checkTransport()} + +func checkTransport() http.RoundTripper { + t := http.DefaultTransport.(*http.Transport).Clone() + t.Proxy = netproxy.Func + return netproxy.Dispatch(t) +} + +// checked is the last check of each server, by name, with what the +// server was then: an edited server, or one signed in to since, is checked +// again. +var checked = struct { + sync.Mutex + m map[string]checkedServer +}{m: map[string]checkedServer{}} + +type checkedServer struct { + key string + h ServerHealth +} + +func healthKey(s *Server) string { + c := *s + c.Name, c.Agents = "", nil + b, _ := json.Marshal(c) + st := mcpauth.StatusOf(s.Name, s.URL) + return fmt.Sprintf("%s|%v|%v|%d", b, st.SignedIn, st.Dead, st.At) +} + +// CheckServers checks the library's servers called names (every one when +// there are none). One checked already this session, as it is now, isn't +// started again unless fresh. +func CheckServers(ctx context.Context, names []string, fresh bool) (map[string]ServerHealth, error) { + mu.Lock() + l, err := load() + mu.Unlock() + if err != nil { + return nil, err + } + var list []*Server + if len(names) == 0 { + list = l.MCP + } else { + for _, n := range names { + if s := l.server(n); s != nil { + list = append(list, s) + } + } + } + out := map[string]ServerHealth{} + var outMu sync.Mutex + var wg sync.WaitGroup + slots := make(chan struct{}, checkAtOnce) + for _, s := range list { + key := healthKey(s) + checked.Lock() + c, ok := checked.m[s.Name] + checked.Unlock() + if ok && c.key == key && !fresh { + outMu.Lock() + out[s.Name] = c.h + outMu.Unlock() + continue + } + wg.Add(1) + go func(s *Server) { + defer wg.Done() + slots <- struct{}{} + defer func() { <-slots }() + h := CheckServer(ctx, s) + if ctx.Err() == nil { // a check cut short by the page going away isn't one + checked.Lock() + checked.m[s.Name] = checkedServer{key, h} + checked.Unlock() + } + outMu.Lock() + out[s.Name] = h + outMu.Unlock() + }(s) + } + wg.Wait() + return out, nil +} + +// CheckServer connects to one server and asks it for its tools. +func CheckServer(ctx context.Context, s *Server) ServerHealth { + ctx, cancel := context.WithTimeout(ctx, checkTimeout) + defer cancel() + var h ServerHealth + switch s.Transport { + case "stdio": + h = checkStdio(ctx, s) + case "sse": + h = checkSSE(ctx, s) + default: + h = checkHTTP(ctx, s) + } + h.At = time.Now().UnixMilli() + return h +} + +func failed(why, detail string) ServerHealth { + return ServerHealth{State: "error", Why: why, Detail: detail} +} + +// timedOut is a server that didn't answer in checkTimeout; the page says +// how long that is. +func timedOut() ServerHealth { return failed("timeout", "") } + +// rpcMsg is a JSON-RPC message from the server: a reply has an id. +type rpcMsg struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Result json.RawMessage `json:"result"` + Error *struct { + Code int `json:"code"` + Message string `json:"message"` + } `json:"error"` +} + +func (m *rpcMsg) is(id int) bool { return string(bytes.TrimSpace(m.ID)) == fmt.Sprint(id) } + +func request(id int, method string, params any) []byte { + m := map[string]any{"jsonrpc": "2.0", "id": id, "method": method} + if params != nil { + m["params"] = params + } + b, _ := json.Marshal(m) + return b +} + +func initializeReq() []byte { + return request(1, "initialize", map[string]any{ + "protocolVersion": mcpProtocol, + "capabilities": map[string]any{}, + "clientInfo": map[string]any{"name": "magpie", "version": gateway.Version}, + }) +} + +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 { + if m.Error != nil { + if m.Error.Code == -32601 { + return ServerHealth{State: "ok"} + } + return failed("protocol", "tools/list: "+m.Error.Message) + } + var r struct { + Tools []json.RawMessage `json:"tools"` + } + if err := json.Unmarshal(m.Result, &r); err != nil { + return failed("protocol", "tools/list: "+err.Error()) + } + return ServerHealth{State: "ok", Tools: len(r.Tools)} +} + +// initError is what an error reply to initialize says. +func initError(m *rpcMsg) *ServerHealth { + if m.Error == nil { + return nil + } + h := failed("protocol", "initialize: "+m.Error.Message) + return &h +} + +// ---- a command --------------------------------------------------------------- + +// tail keeps the end of what a server writes to stderr: its last line is +// usually why it stopped. +type tail struct { + mu sync.Mutex + buf []byte +} + +func (t *tail) Write(p []byte) (int, error) { + t.mu.Lock() + defer t.mu.Unlock() + t.buf = append(t.buf, p...) + if len(t.buf) > 8192 { + t.buf = t.buf[len(t.buf)-8192:] + } + return len(p), nil +} + +func (t *tail) last() string { + t.mu.Lock() + defer t.mu.Unlock() + lines := strings.Split(strings.TrimSpace(string(t.buf)), "\n") + l := strings.TrimSpace(lines[len(lines)-1]) + if len(l) > 300 { + l = l[:300] + "…" + } + return l +} + +func checkStdio(ctx context.Context, s *Server) ServerHealth { + // started as the agents start it: in the environment magpie has, with + // the server's own variables over it + cmd := proc.Command(s.Command, s.Args...) + cmd.Env = os.Environ() + for k, v := range s.Env { + cmd.Env = append(cmd.Env, k+"="+v) + } + stdin, err := cmd.StdinPipe() + if err != nil { + return failed("start", err.Error()) + } + stdout, err := cmd.StdoutPipe() + if err != nil { + return failed("start", err.Error()) + } + errs := &tail{} + cmd.Stderr = errs + tree, err := proc.StartTree(cmd) + if err != nil { + if errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist) { + return failed("notfound", s.Command) + } + return failed("start", err.Error()) + } + var exitErr error + exited := make(chan struct{}) + go func() { exitErr = tree.Wait(); close(exited) }() + // the server ends with the check, and whatever it started with it + defer func() { + stdin.Close() + tree.Kill() + select { + case <-exited: + case <-time.After(3 * time.Second): + } + }() + + msgs := make(chan *rpcMsg, 16) + go func() { + defer close(msgs) + sc := bufio.NewScanner(stdout) + sc.Buffer(make([]byte, 64*1024), 16<<20) + for sc.Scan() { + var m rpcMsg + // a line that isn't JSON-RPC is a server logging to the wrong + // stream; agents pass over it too + if json.Unmarshal(sc.Bytes(), &m) != nil { + continue + } + select { + case msgs <- &m: + case <-ctx.Done(): + return + } + } + }() + send := func(b []byte) error { + _, err := stdin.Write(append(b, '\n')) + return err + } + // a reply, or why there is none: the process ended or time ran out. A + // process that ended may still have lines to read, the reply among + // them, so its output is read to the end first. + out, gone, ended := msgs, exited, false + await := func(id int) (*rpcMsg, *ServerHealth) { + for { + select { + case m, ok := <-out: + if !ok { + out = nil + if ended { + h := exitHealth(exitErr, errs) + return nil, &h + } + continue + } + if m.is(id) { + return m, nil + } + case <-gone: + gone, ended = nil, true + if out == nil { + h := exitHealth(exitErr, errs) + return nil, &h + } + case <-ctx.Done(): + h := timedOut() + h.Detail = errs.last() + return nil, &h + } + } + } + if err := send(initializeReq()); err != nil { + if _, h := await(1); h != nil { + return *h + } + return failed("start", err.Error()) + } + m, h := await(1) + if h != nil { + return *h + } + if h := initError(m); h != nil { + return *h + } + _ = send(initializedNote) + _ = send(request(2, "tools/list", nil)) + m, h = await(2) + if h != nil { + return *h + } + return toolsOf(m) +} + +func exitHealth(err error, errs *tail) ServerHealth { + h := failed("exited", errs.last()) + var ee *exec.ExitError + if errors.As(err, &ee) { + h.Code = ee.ExitCode() + } + return h +} + +// ---- a URL ------------------------------------------------------------------- + +// remoteHeaders are the server's own headers, with magpie's token when it +// is signed in to it: the agents reach it with that too. +func remoteHeaders(ctx context.Context, s *Server) (http.Header, *ServerHealth) { + h := http.Header{} + for k, v := range s.Headers { + h.Set(k, v) + } + if s.Transport == "http" && mcpauth.SignedIn(s.Name, s.URL) { + tok, err := mcpauth.Token(ctx, s.Name) + if err != nil { + return nil, &ServerHealth{State: "auth", OAuth: true, Detail: err.Error()} + } + h.Set("Authorization", "Bearer "+tok) + } + return h, nil +} + +// netHealth puts a failed request in the page's words. +func netHealth(ctx context.Context, err error) ServerHealth { + if ctx.Err() != nil || errors.Is(err, context.DeadlineExceeded) { + return timedOut() + } + if errors.Is(err, syscall.ECONNREFUSED) { + return failed("refused", err.Error()) + } + var ue *url.Error + if errors.As(err, &ue) { + err = ue.Err + } + var dns *net.DNSError + if errors.As(err, &dns) { + return failed("unreachable", "can't find "+dns.Name) + } + return failed("unreachable", err.Error()) +} + +// refused is the health of a 401 or 403: the server wants a sign-in, or a +// key it wasn't given. +func refused(res *http.Response) ServerHealth { + return ServerHealth{State: "auth", Code: res.StatusCode, OAuth: res.Header.Get("WWW-Authenticate") != ""} +} + +func statusHealth(res *http.Response) ServerHealth { + h := failed("http", res.Status) + h.Code = res.StatusCode + return h +} + +func checkHTTP(ctx context.Context, s *Server) ServerHealth { + hdr, bad := remoteHeaders(ctx, s) + if bad != nil { + return *bad + } + session, version := "", mcpProtocol + post := func(body []byte) (*http.Response, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.URL, bytes.NewReader(body)) + if err != nil { + return nil, err + } + for k, v := range hdr { + req.Header[k] = v + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + if session != "" { + req.Header.Set("Mcp-Session-Id", session) + req.Header.Set("MCP-Protocol-Version", version) + } + return checkClient.Do(req) + } + // call posts a request and reads its reply, as JSON or from an event + // stream + call := func(id int, body []byte) (*rpcMsg, *ServerHealth) { + res, err := post(body) + if err != nil { + h := netHealth(ctx, err) + return nil, &h + } + defer res.Body.Close() + if res.StatusCode == 401 || res.StatusCode == 403 { + h := refused(res) + return nil, &h + } + if res.StatusCode/100 != 2 { + h := statusHealth(res) + return nil, &h + } + if sid := res.Header.Get("Mcp-Session-Id"); sid != "" { + session = sid + } + m, err := replyOf(res, id) + if err != nil { + if ctx.Err() != nil { + h := timedOut() + return nil, &h + } + h := failed("protocol", err.Error()) + return nil, &h + } + return m, nil + } + m, h := call(1, initializeReq()) + if h != nil { + return *h + } + if h := initError(m); h != nil { + return *h + } + var init struct { + ProtocolVersion string `json:"protocolVersion"` + } + if json.Unmarshal(m.Result, &init) == nil && init.ProtocolVersion != "" { + version = init.ProtocolVersion + } + if session != "" { + defer endSession(s.URL, hdr, session) + } + if res, err := post(initializedNote); err == nil { + io.Copy(io.Discard, io.LimitReader(res.Body, 1<<16)) + res.Body.Close() + } + m, h = call(2, request(2, "tools/list", nil)) + if h != nil { + return *h + } + return toolsOf(m) +} + +// endSession tells the server the check is done with its session, as a +// client leaving should; one that doesn't take it is no matter. +func endSession(u string, hdr http.Header, session string) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodDelete, u, nil) + if err != nil { + return + } + for k, v := range hdr { + req.Header[k] = v + } + req.Header.Set("Mcp-Session-Id", session) + if res, err := checkClient.Do(req); err == nil { + res.Body.Close() + } +} + +// replyOf is the reply to id in a response: its JSON body, or the event +// stream's message that carries it. +func replyOf(res *http.Response, id int) (*rpcMsg, error) { + ct := res.Header.Get("Content-Type") + if strings.HasPrefix(ct, "text/event-stream") { + done := make(chan struct{}) + defer close(done) + for e := range sseEvents(res.Body, done) { + if e.name != "" && e.name != "message" { + continue + } + var m rpcMsg + if json.Unmarshal([]byte(e.data), &m) == nil && m.is(id) { + return &m, nil + } + } + return nil, errors.New("the event stream ended without a reply") + } + b, err := io.ReadAll(io.LimitReader(res.Body, 16<<20)) + if err != nil { + return nil, err + } + var m rpcMsg + if err := json.Unmarshal(b, &m); err != nil { + return nil, fmt.Errorf("not an MCP reply (%s): %s", ct, snippet(b)) + } + return &m, nil +} + +func snippet(b []byte) string { + s := strings.Join(strings.Fields(string(b)), " ") + if len(s) > 120 { + s = s[:120] + "…" + } + return s +} + +type sseEvent struct{ name, data string } + +// sseEvents reads an event stream's events until it ends. +// done ends the reading once the events are no longer wanted. +func sseEvents(r io.Reader, done <-chan struct{}) <-chan sseEvent { + out := make(chan sseEvent) + go func() { + defer close(out) + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 64*1024), 16<<20) + var e sseEvent + var data []string + for sc.Scan() { + l := strings.TrimSuffix(sc.Text(), "\r") + switch { + case l == "": + if len(data) > 0 { + e.data = strings.Join(data, "\n") + select { + case out <- e: + case <-done: + return + } + } + e, data = sseEvent{}, nil + case strings.HasPrefix(l, "event:"): + e.name = strings.TrimSpace(l[6:]) + case strings.HasPrefix(l, "data:"): + data = append(data, strings.TrimPrefix(l[5:], " ")) + } + } + }() + return out +} + +// checkSSE checks a server on the older SSE transport: its stream names +// where to post, and the replies come back on the stream. +func checkSSE(ctx context.Context, s *Server) ServerHealth { + hdr, bad := remoteHeaders(ctx, s) + if bad != nil { + return *bad + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil) + if err != nil { + return failed("unreachable", err.Error()) + } + for k, v := range hdr { + req.Header[k] = v + } + req.Header.Set("Accept", "text/event-stream") + res, err := checkClient.Do(req) + if err != nil { + return netHealth(ctx, err) + } + defer res.Body.Close() + if res.StatusCode == 401 || res.StatusCode == 403 { + return refused(res) + } + if res.StatusCode/100 != 2 { + return statusHealth(res) + } + events := sseEvents(res.Body, ctx.Done()) + next := func() (sseEvent, *ServerHealth) { + select { + case e, ok := <-events: + if !ok { + h := timedOut() + if ctx.Err() == nil { + h = failed("protocol", "the event stream ended") + } + return e, &h + } + return e, nil + case <-ctx.Done(): + h := timedOut() + return sseEvent{}, &h + } + } + var endpoint *url.URL + for endpoint == nil { + e, h := next() + if h != nil { + return *h + } + if e.name == "endpoint" { + base, _ := url.Parse(s.URL) + endpoint, err = base.Parse(strings.TrimSpace(e.data)) + if err != nil { + return failed("protocol", "endpoint: "+err.Error()) + } + } + } + post := func(body []byte) *ServerHealth { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(body)) + if err != nil { + h := failed("protocol", err.Error()) + return &h + } + for k, v := range hdr { + req.Header[k] = v + } + req.Header.Set("Content-Type", "application/json") + res, err := checkClient.Do(req) + if err != nil { + h := netHealth(ctx, err) + return &h + } + io.Copy(io.Discard, io.LimitReader(res.Body, 1<<16)) + res.Body.Close() + if res.StatusCode == 401 || res.StatusCode == 403 { + h := refused(res) + return &h + } + if res.StatusCode/100 != 2 { + h := statusHealth(res) + return &h + } + return nil + } + await := func(id int) (*rpcMsg, *ServerHealth) { + for { + e, h := next() + if h != nil { + return nil, h + } + var m rpcMsg + if json.Unmarshal([]byte(e.data), &m) == nil && m.is(id) { + return &m, nil + } + } + } + if h := post(initializeReq()); h != nil { + return *h + } + m, h := await(1) + if h != nil { + return *h + } + if h := initError(m); h != nil { + return *h + } + _ = post(initializedNote) + if h := post(request(2, "tools/list", nil)); h != nil { + return *h + } + m, h = await(2) + if h != nil { + return *h + } + return toolsOf(m) +} diff --git a/internal/library/mcp_check_test.go b/internal/library/mcp_check_test.go new file mode 100644 index 000000000..3250b80bb --- /dev/null +++ b/internal/library/mcp_check_test.go @@ -0,0 +1,378 @@ +package library + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +// The fake stdio server is this test binary, started again with +// MAGPIE_FAKE_MCP saying how it behaves. +const fakeMode = "MAGPIE_FAKE_MCP" + +func TestFakeMCPServer(t *testing.T) { + mode := os.Getenv(fakeMode) + if mode == "" { + t.Skip("run by the checker's tests") + } + if f := os.Getenv("MAGPIE_FAKE_MCP_LOG"); f != "" { + l, _ := os.OpenFile(f, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + fmt.Fprintf(l, "%d\n", os.Getpid()) + l.Close() + } + switch mode { + case "sleep": + time.Sleep(time.Minute) + os.Exit(0) + case "exit": + fmt.Fprintln(os.Stderr, "starting…") + fmt.Fprintln(os.Stderr, "Error: GITHUB_TOKEN is not set") + os.Exit(3) + case "hang": + // a child of its own, which the check has to end too + self, _ := os.Executable() + c := exec.Command(self, "-test.run=^TestFakeMCPServer$") + c.Env = append(os.Environ(), fakeMode+"=sleep") + c.Start() + time.Sleep(time.Minute) + os.Exit(0) + } + // ok: a log line on stdout first, as some servers write + fmt.Println("server starting on stdio") + sc := bufio.NewScanner(os.Stdin) + for sc.Scan() { + var m struct { + ID *int `json:"id"` + Method string `json:"method"` + } + json.Unmarshal(sc.Bytes(), &m) + switch m.Method { + case "initialize": + fmt.Printf(`{"jsonrpc":"2.0","id":%d,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{}},"serverInfo":{"name":"fake","version":"1"}}}`+"\n", *m.ID) + case "notifications/initialized": + os.WriteFile(os.Getenv("MAGPIE_FAKE_MCP_INIT"), []byte("yes"), 0o644) + case "tools/list": + 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) + } + } + os.Exit(0) +} + +func fakeStdio(t *testing.T, mode string, env map[string]string) *Server { + t.Helper() + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + e := map[string]string{fakeMode: mode} + for k, v := range env { + e[k] = v + } + return &Server{Name: "fake", Transport: "stdio", Command: self, Args: []string{"-test.run=^TestFakeMCPServer$"}, Env: e} +} + +func short(t *testing.T, d time.Duration) { + was := checkTimeout + checkTimeout = d + t.Cleanup(func() { checkTimeout = was }) +} + +func TestCheckStdio(t *testing.T) { + t.Run("ok", func(t *testing.T) { + initFile := filepath.Join(t.TempDir(), "init") + h := CheckServer(context.Background(), fakeStdio(t, "ok", map[string]string{"MAGPIE_FAKE_MCP_INIT": initFile})) + if h.State != "ok" || h.Tools != 3 { + t.Fatalf("got %+v, want ok with 3 tools", h) + } + if b, _ := os.ReadFile(initFile); string(b) != "yes" { + t.Error("notifications/initialized wasn't sent before tools/list") + } + }) + t.Run("exited", func(t *testing.T) { + h := CheckServer(context.Background(), fakeStdio(t, "exit", nil)) + if h.State != "error" || h.Why != "exited" || h.Code != 3 || h.Detail != "Error: GITHUB_TOKEN is not set" { + t.Fatalf("got %+v, want exited 3 with the last stderr line", h) + } + }) + t.Run("not found", func(t *testing.T) { + h := CheckServer(context.Background(), &Server{Name: "x", Transport: "stdio", Command: "magpie-no-such-mcp-server"}) + if h.State != "error" || h.Why != "notfound" || h.Detail != "magpie-no-such-mcp-server" { + t.Fatalf("got %+v, want notfound", h) + } + }) + t.Run("timeout ends the tree", func(t *testing.T) { + short(t, 1500*time.Millisecond) + pids := filepath.Join(t.TempDir(), "pids") + start := time.Now() + h := CheckServer(context.Background(), fakeStdio(t, "hang", map[string]string{"MAGPIE_FAKE_MCP_LOG": pids})) + if h.State != "error" || h.Why != "timeout" { + t.Fatalf("got %+v, want timeout", h) + } + if d := time.Since(start); d > 6*time.Second { + t.Errorf("took %s", d) + } + if runtime.GOOS == "windows" { + return + } + b, _ := os.ReadFile(pids) + list := strings.Fields(string(b)) + if len(list) != 2 { + t.Fatalf("pids %q: the server and its child should both have started", list) + } + for _, p := range list { + pid, _ := strconv.Atoi(p) + // the child may stay a zombie a moment, reaped by init + gone := false + for i := 0; i < 50 && !gone; i++ { + out, _ := exec.Command("ps", "-o", "stat=", "-p", p).Output() + s := strings.TrimSpace(string(out)) + gone = s == "" || strings.HasPrefix(s, "Z") + if !gone { + time.Sleep(100 * time.Millisecond) + } + } + if !gone { + if p, err := os.FindProcess(pid); err == nil { + p.Kill() + } + t.Errorf("process %d still runs after the check", pid) + } + } + }) +} + +// mcpHandler is a streamable HTTP server: a session from initialize, +// which tools/list has to carry. +func mcpHandler(t *testing.T, sse bool, seen *http.Header) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + w.WriteHeader(204) + return + } + var m struct { + ID *int `json:"id"` + Method string `json:"method"` + } + json.NewDecoder(r.Body).Decode(&m) + reply := "" + switch m.Method { + case "initialize": + if !strings.Contains(r.Header.Get("Accept"), "text/event-stream") || !strings.Contains(r.Header.Get("Accept"), "application/json") { + t.Errorf("Accept %q", r.Header.Get("Accept")) + } + w.Header().Set("Mcp-Session-Id", "s-1") + reply = fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"result":{"protocolVersion":"2025-03-26","capabilities":{}}}`, *m.ID) + case "notifications/initialized": + w.WriteHeader(202) + return + case "tools/list": + if r.Header.Get("Mcp-Session-Id") != "s-1" { + http.Error(w, "no session", 400) + return + } + *seen = r.Header.Clone() + reply = fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"result":{"tools":[{"name":"a"},{"name":"b"}]}}`, *m.ID) + } + if sse { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprintf(w, "event: message\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}\n\nevent: message\ndata: %s\n\n", reply) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, reply) + } +} + +func TestCheckHTTP(t *testing.T) { + for _, sse := range []bool{false, true} { + t.Run(fmt.Sprintf("ok sse=%v", sse), func(t *testing.T) { + var seen http.Header + srv := httptest.NewServer(mcpHandler(t, sse, &seen)) + defer srv.Close() + h := CheckServer(context.Background(), &Server{Name: "r", Transport: "http", URL: srv.URL, Headers: map[string]string{"Authorization": "Bearer k"}}) + if h.State != "ok" || h.Tools != 2 { + t.Fatalf("got %+v, want ok with 2 tools", h) + } + if seen.Get("Authorization") != "Bearer k" || seen.Get("MCP-Protocol-Version") != "2025-03-26" { + t.Errorf("tools/list headers %v", seen) + } + }) + } + cases := []struct { + name string + handler http.HandlerFunc + want ServerHealth + }{ + {"oauth", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="x"`) + w.WriteHeader(401) + }, ServerHealth{State: "auth", Code: 401, OAuth: true}}, + {"key", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(403) }, ServerHealth{State: "auth", Code: 403}}, + {"404", func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }, ServerHealth{State: "error", Why: "http", Code: 404, Detail: "404 Not Found"}}, + {"broken json", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + io.WriteString(w, "hello") + }, ServerHealth{State: "error", Why: "protocol", Detail: "not an MCP reply (text/html): hello"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + srv := httptest.NewServer(c.handler) + defer srv.Close() + h := CheckServer(context.Background(), &Server{Name: "r", Transport: "http", URL: srv.URL}) + h.At = 0 + if h != c.want { + t.Fatalf("got %+v, want %+v", h, c.want) + } + }) + } + t.Run("timeout", func(t *testing.T) { + short(t, time.Second) + // the body read first: the server notices the client gone only then + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + <-r.Context().Done() + })) + defer srv.Close() + h := CheckServer(context.Background(), &Server{Name: "r", Transport: "http", URL: srv.URL}) + if h.State != "error" || h.Why != "timeout" { + t.Fatalf("got %+v, want timeout", h) + } + }) + t.Run("refused", func(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + ln.Close() + h := CheckServer(context.Background(), &Server{Name: "r", Transport: "http", URL: "http://" + addr + "/mcp"}) + if h.State != "error" || h.Why != "refused" { + t.Fatalf("got %+v, want refused", h) + } + }) +} + +// The older SSE transport: the stream names where to post, and the replies +// come on the stream. +func TestCheckSSE(t *testing.T) { + var mu sync.Mutex + streams := map[string]chan string{} + mux := http.NewServeMux() + mux.HandleFunc("GET /sse", func(w http.ResponseWriter, r *http.Request) { + ch := make(chan string, 8) + mu.Lock() + streams["1"] = ch + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "event: endpoint\ndata: /messages?session=1\n\n") + w.(http.Flusher).Flush() + for { + select { + case s := <-ch: + fmt.Fprintf(w, "event: message\ndata: %s\n\n", s) + w.(http.Flusher).Flush() + case <-r.Context().Done(): + return + } + } + }) + mux.HandleFunc("POST /messages", func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + ch := streams[r.URL.Query().Get("session")] + mu.Unlock() + var m struct { + ID *int `json:"id"` + Method string `json:"method"` + } + json.NewDecoder(r.Body).Decode(&m) + switch m.Method { + case "initialize": + ch <- fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"result":{"protocolVersion":"2024-11-05"}}`, *m.ID) + case "tools/list": + ch <- fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"result":{"tools":[{"name":"only"}]}}`, *m.ID) + } + w.WriteHeader(202) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + h := CheckServer(context.Background(), &Server{Name: "s", Transport: "sse", URL: srv.URL + "/sse"}) + if h.State != "ok" || h.Tools != 1 { + t.Fatalf("got %+v, want ok with 1 tool", h) + } +} + +// A server is started once a session; again when asked fresh, or when it +// was changed meanwhile. Nothing is written to the agents. +func TestCheckServersOnce(t *testing.T) { + sandbox(t) + checked.Lock() + checked.m = map[string]checkedServer{} + checked.Unlock() + pids := filepath.Join(t.TempDir(), "pids") + s := fakeStdio(t, "ok", map[string]string{"MAGPIE_FAKE_MCP_LOG": pids}) + s.Agents = []string{} + if _, err := SaveServer("", *s); err != nil { + t.Fatal(err) + } + if _, err := SaveServer("", Server{Name: "gone", Transport: "stdio", Command: "magpie-no-such-mcp-server", Agents: []string{}}); err != nil { + t.Fatal(err) + } + starts := func() int { + b, _ := os.ReadFile(pids) + return len(strings.Fields(string(b))) + } + m, err := CheckServers(context.Background(), nil, false) + if err != nil { + t.Fatal(err) + } + if m["fake"].State != "ok" || m["fake"].Tools != 3 || m["gone"].Why != "notfound" || starts() != 1 { + t.Fatalf("first check %+v, %d starts", m, starts()) + } + m, _ = CheckServers(context.Background(), []string{"fake"}, false) + if len(m) != 1 || m["fake"].Tools != 3 || starts() != 1 { + t.Fatalf("second check %+v started it again: %d starts", m, starts()) + } + CheckServers(context.Background(), []string{"fake"}, true) + if starts() != 2 { + t.Fatalf("fresh check: %d starts, want 2", starts()) + } + s.Env["EXTRA"] = "1" + if _, err := SaveServer("fake", *s); err != nil { + t.Fatal(err) + } + before := snapshot(t, os.Getenv("HOME")) + CheckServers(context.Background(), nil, false) + if starts() != 3 { + t.Fatalf("changed server: %d starts, want 3", starts()) + } + if after := snapshot(t, os.Getenv("HOME")); after != before { + t.Errorf("the check wrote files:\n%s\n---\n%s", before, after) + } +} + +// snapshot is every file under dir with its size and time. +func snapshot(t *testing.T, dir string) string { + var b strings.Builder + filepath.Walk(dir, func(p string, fi os.FileInfo, err error) error { + if err != nil || fi.IsDir() { + return nil + } + fmt.Fprintf(&b, "%s %d %d\n", p, fi.Size(), fi.ModTime().UnixNano()) + return nil + }) + return b.String() +}