library: MCP servers, skills and instructions are kept once in magpie and given to any agent from one place, with a market to find and add them (#29). Each agent reads MCP servers and skills from files of its own and in a format of its own, so one server was set up again in Claude Code, Codex, Gemini CLI, OpenCode, Pi, Goose, Cursor, Copilot CLI and Crush. The Library view keeps each once: a server is added (stdio, http or sse, its env and headers) and switched on per agent with its icon, and magpie writes it into each agent's config in that agent's format, leaving what the agent has of its own as it is; a server or skill an agent already has is shown, to bring into the library. A skill is a folder with a SKILL.md, kept in the library from GitHub (owner/repo, or a link to a folder in one; updated from it later) or linked from a folder on this machine, and linked into each agent's skills folder. The instructions every agent reads (CLAUDE.md, AGENTS.md, GEMINI.md…) can be kept as one too. The market offers checked MCP servers first, then the official MCP Registry's, filled in from what the registry says each needs (keys asked for in a form, never guessed), and skills.sh's most installed skills with what each says it is for; each shows its real icon (the vendor's own, else its GitHub owner's), fetched through magpie only for the icons the market or the library gave out, and an added server or skill keeps its icon in the library. What magpie changes in an agent's files is backed up first

This commit is contained in:
yetone
2026-09-25 14:11:17 +08:00
parent b3705cbb5a
commit dfc2d7fa93
22 changed files with 6141 additions and 8 deletions
+1
View File
@@ -42,6 +42,7 @@ require (
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/tidwall/match v1.1.1 // indirect
+2
View File
@@ -64,6 +64,8 @@ github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+6
View File
@@ -222,8 +222,14 @@ func trimBlank(lines []string) []string {
return lines
}
// Raw is a TOML value written as it is: an array or an inline table the
// caller has already spelled out.
type Raw string
func tomlLiteral(v any) string {
switch x := v.(type) {
case Raw:
return string(x)
case bool:
return strconv.FormatBool(x)
case int:
+1
View File
@@ -188,6 +188,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
providerRoutes(mux, w, gw)
importRoutes(mux)
usageRoutes(mux)
libraryRoutes(mux, w)
updateRoutes(mux, w)
mux.HandleFunc("GET /api/settings", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, settingsState())
+11 -2
View File
@@ -173,7 +173,7 @@ body.window:not(.mac) .brand { display: none; } /* the title bar above already s
background: var(--pill);
}
body.panel .seg { display: none; }
.seg button { position: relative; z-index: 1; height: 24px; padding: 0 12px; border-radius: 6px; font-size: 12.5px; color: var(--muted); transition: color .18s var(--ease), transform .14s var(--ease); }
.seg button { position: relative; z-index: 1; white-space: nowrap; height: 24px; padding: 0 12px; border-radius: 6px; font-size: 12.5px; color: var(--muted); transition: color .18s var(--ease), transform .14s var(--ease); }
.seg button.on { color: var(--fg); }
.seg button:hover:not(.on) { color: var(--fg-2); }
.actions { margin-left: auto; display: flex; gap: 2px; }
@@ -206,7 +206,7 @@ body.panel .seg { display: none; }
and at the narrowest the tabs in the row rather than over it */
.top.tight .brand > span:not(.logo), .top.tight .update span { display: none; }
.top.tight .update { width: 22px; padding: 0; justify-content: center; margin-right: 4px; }
.top.cramped .seg { position: static; transform: none; margin: 0 auto; }
body.window .top.cramped .seg { position: relative; left: auto; top: auto; transform: none; margin: 0 auto; } /* relative still: its thumb sits in it, not over the whole header */
.top.cramped .seg button { padding: 0 8px; }
@keyframes update-in { from { opacity: 0; transform: translateY(-3px) scale(.94); } }
@keyframes spin { to { transform: rotate(360deg); } }
@@ -271,6 +271,15 @@ body.panel .field:hover { box-shadow: inset 0 0 0 1px var(--pill-line), var(--pi
body.panel .field.open { box-shadow: inset 0 0 0 1px var(--accent), var(--pill-shadow); }
/* the tray panel keeps control-sized pills: a solo control spans both columns
and hugs the right — an economy the narrow panel wants */
/* a field that follows the model unless set: a square in a third column */
#agents.extras .fields { width: 379px; grid-template-columns: minmax(0, 1fr) 124px 24px; }
body.panel #agents.extras .fields { width: 301px; grid-template-columns: minmax(0, 1fr) 118px 24px; }
#agents.extras .field.solo { grid-column: 1 / 3; }
body.window #agents.extras .field.solo { grid-column: 1 / 3; }
.field.extra { grid-column: 3; width: 24px; padding: 0; justify-content: center; position: relative; color: var(--faint); }
.field.extra:hover, .field.extra.open { color: var(--fg-2); }
.field.extra.set { color: var(--fg); }
.field.extra.set::after { content: ""; position: absolute; top: 3px; right: 3px; width: 5px; height: 5px; border-radius: 50%; background: var(--accent); }
.field.main, .field.solo { justify-self: end; }
.field.solo { grid-column: 1 / -1; }
/* in the window the chips fill their column, so every chip and chevron lines
+46 -6
View File
@@ -171,9 +171,11 @@ function renderAgents() {
const shownFields = a.fields.filter((f) => !TIERS.includes(f.label));
const tiers = tierMenu(a);
if (tiers) shownFields.push(tiers);
const sorted = shownFields.sort((x, y) => wide(y) - wide(x));
const sorted = shownFields.sort((x, y) => wide(y) - wide(x) || extra(x) - extra(y));
const plain = sorted.filter((f) => !extra(f)).length;
for (const f of sorted) {
const b = el("button", "field " + (sorted.length === 1 ? "solo" : wide(f) ? "main" : "side"));
if (extra(f)) { fields.append(extraField(a, f)); continue; }
const b = el("button", "field " + (plain === 1 ? "solo" : wide(f) ? "main" : "side"));
const opt = optionFor(f, f.value);
b.title = t("{label}: {value}", { label: t(f.label), value: f.value || t("agent default") }) + (opt?.note ? ` · ${opt.note}` : "");
const effort = f.key === "effort" || f.label === "effort" || f.label === "thinking";
@@ -196,6 +198,9 @@ function renderAgents() {
row.append(icon(a.icon), who, fields);
return row;
};
// the extras column is there for every row once any agent has one, so the
// pickers keep lining up down the list
list.classList.toggle("extras", state.agents.some((a) => a.fields.some(extra) || tierMenu(a)));
if (!folded.length) {
for (const a of state.agents) list.append(agentRow(a));
} else {
@@ -272,6 +277,28 @@ const TIERS = ["opus", "sonnet", "haiku", "fable"];
// fields that fall back to the agent's model when unset
const FOLLOWS_MODEL = [...TIERS, "subagents"];
// A field that follows the model unless set — Codex's subagents, Claude
// Code's tiers — is a small square after the pickers rather than a third
// picker, which a row has no room for: it wrapped onto a line of its own.
const extra = (f) => f.key === "tiers" || FOLLOWS_MODEL.includes(f.label);
const EXTRA_GLYPH = {
subagents: "M4.5 2.75v10.5M4.5 9.25c0-2.2 1.6-3.75 3.9-3.75h3.35M9.9 3.6l1.9 1.9-1.9 1.9",
tiers: "M8 2.6 2.75 5.4 8 8.2l5.25-2.8zM2.75 8.1 8 10.9l5.25-2.8M2.75 10.8 8 13.6l5.25-2.8",
};
function extraField(a, f) {
const set = !!(f.value || f.custom);
const b = el("button", "field extra" + (set ? " set" : ""));
b.append(svg(EXTRA_GLYPH[f.label] || EXTRA_GLYPH.tiers, 13, 1.5));
const opt = optionFor(f, f.value);
b.title = f.menu
? t("{label}: {value}", { label: t(f.label), value: f.summary }) + "\n" + f.options.map((o) => `${o.label}: ${o.note}`).join("\n")
: t("{label}: {value}", { label: t(f.label), value: opt?.label || f.value || t("same as model") });
b.setAttribute("aria-label", b.title);
b.dataset.key = f.key;
b.onclick = (ev) => openPicker(a, f, b, ev);
return b;
}
function tierMenu(a) {
const tiers = a.fields.filter((f) => TIERS.includes(f.label));
if (!tiers.length || !tiers.some((f) => f.options.length)) return null;
@@ -346,7 +373,8 @@ async function load() {
try {
state = await api("state");
load.done = true;
applyPrefs(state.settings);
// the library may have drawn itself before the saved language was known
if (applyPrefs(state.settings) && view === "library") window.loadLibrary?.();
tintPanel();
renderAgents();
// an open provider editor is someone typing: coming back to the window
@@ -485,7 +513,7 @@ function openPicker(agent, field, anchor, ev, only) {
}
const q = $("#q");
q.value = "";
q.placeholder = modelPicker ? t("Filter, or type any model id…") : t("Filter {field}…", { field: t(field.label) });
q.placeholder = modelPicker && extra(field) ? t("{field} — filter, or type any model id…", { field: t(field.label) }) : modelPicker ? t("Filter, or type any model id…") : t("Filter {field}…", { field: t(field.label) });
filter();
q.focus();
}
@@ -3367,7 +3395,7 @@ function show(v) {
view = v;
if (mode === "window") { for (const b of $("#nav").querySelectorAll("button")) b.classList.toggle("on", b.dataset.view === v); slide($("#nav"), "nav"); }
$("#prefs").classList.toggle("on", v === "settings");
for (const id of ["agents", "providers", "gateway", "routing", "usage", "settings"]) $("#view-" + id).hidden = v !== id;
for (const id of ["agents", "providers", "gateway", "routing", "usage", "library", "settings"]) $("#view-" + id).hidden = v !== id;
// back to where the reader was in it, and again once it has what it loads
const back = () => backToReader($("#view-" + v));
requestAnimationFrame(back);
@@ -3376,6 +3404,7 @@ function show(v) {
if (v === "providers" || v === "gateway" || v === "routing") loadProviders().then(back, (e) => status(e.message, "err"));
if (v === "usage") loadUsage().then(back, (e) => status(e.message, "err"));
if (v === "settings") loadSettings().then(back, (e) => status(e.message, "err"));
if (v === "library") window.loadLibrary?.()?.then(back);
syncURL();
}
@@ -3449,6 +3478,17 @@ function fitTop() {
}
const topFit = new ResizeObserver(fitTop);
for (const e of [".top", ".brand", ".actions"]) topFit.observe($(e));
// the nav's tabs change size after its thumb was put under one — the header
// tightening, the fonts arriving, another language — so it's put there again
if (mode === "window") new ResizeObserver(() => {
const th = $("#nav > .thumb"), on = $("#nav > .on");
if (!th || !on) return;
th.classList.add("still");
th.style.transform = `translateX(${on.offsetLeft}px)`;
th.style.width = on.offsetWidth + "px";
thumbs.set("nav", { x: on.offsetLeft, w: on.offsetWidth, at: 0 });
requestAnimationFrame(() => th.classList.remove("still"));
}).observe($("#nav"));
document.fonts?.ready.then(fitTop);
document.addEventListener("visibilitychange", () => { if (!document.hidden) { load(); wag(); } });
@@ -3466,6 +3506,6 @@ if (mode === "window" && params.get("import")) {
}).catch(() => {});
}
if (mode === "window" && params.get("view") === "providers" && params.get("edit")) editing = params.get("edit");
if (mode === "window" && ["providers", "gateway", "routing", "usage", "settings"].includes(params.get("view"))) show(params.get("view"));
if (mode === "window" && ["providers", "gateway", "routing", "usage", "library", "settings"].includes(params.get("view"))) show(params.get("view"));
else if (mode === "window") slide($("#nav"), "nav");
load();
+175
View File
@@ -9,6 +9,7 @@ const I18N = {
"Providers": "供应商",
"Gateway": "网关",
"Usage": "用量",
"Library": "资源库",
"Settings": "设置",
"Refresh model lists (models.dev and every vendor)": "刷新模型列表(models.dev 与各供应商)",
"Open as a window": "在窗口中打开",
@@ -77,6 +78,7 @@ const I18N = {
"use as typed": "按输入使用",
"Filter models…": "筛选模型…",
"Filter, or type any model id…": "筛选,或输入任意模型 ID…",
"{field} — filter, or type any model id…": "{field} — 筛选,或输入任意模型 ID…",
"Filter {field}…": "筛选{field}…",
"No matches.": "没有匹配项。",
@@ -625,6 +627,179 @@ const I18N = {
"{h} h {m} min": "{h} 小时 {m} 分钟",
"{n} h": "{n} 小时",
"{n} d": "{n} 天",
// library (#29)
"Show in {fm}": "在 {fm} 中显示",
"the file manager": "文件管理器",
"{agent} has it — click to take it away": "{agent} 已启用 — 点击移除",
"Give it to {agent}": "给 {agent} 启用",
"{agent} reads it through {other} — click to give it its own": "{agent} 通过 {other} 读取它 — 点击给它单独一份",
"{agent}: {error}": "{agent}:{error}",
"(and {n} more)": "(另有 {n} 项)",
"Written to {agent}": "已写入 {agent}",
"Written to {n} agents": "已写入 {n} 个 Agent",
"Saved — the agents already had it": "已保存 — Agent 中已是最新",
"Instructions": "指令",
"MCP servers": "MCP 服务器",
"Skills": "技能",
"Library folder": "资源库文件夹",
"No agents to write to": "没有可写入的 Agent",
"Install Claude Code, Codex, Gemini CLI, OpenCode… and the library can give them the same instructions, MCP servers and skills.": "安装 Claude Code、Codex、Gemini CLI、OpenCode 等之后,资源库就能给它们同一份指令、MCP 服务器和技能。",
"magpie keeps a copy of every file before it writes it.": "magpie 写入任何文件前都会先备份一份。",
"Backups": "备份",
"Write it once: every agent switched on below reads it before each conversation, in its own instructions file.": "写一次就够了:下面开启的每个 Agent 都会在每次对话前,从各自的指令文件里读到它。",
"What every agent should know — how you like code written, the stack you work in, the commands that run your tests…": "每个 Agent 都该知道的事 — 你喜欢的代码风格、使用的技术栈、跑测试的命令……",
"Not saved yet": "尚未保存",
"Discard": "放弃",
"Shared instructions": "共享指令",
"magpie writes its part between two marker lines — the rest of each file stays yours": "magpie 只写两行标记之间的部分 — 文件其余内容仍归你",
"None of your agents reads a user-wide instructions file magpie knows.": "你的 Agent 都没有 magpie 已知的用户级指令文件。",
"{agents} keeps no user-wide instructions file.": "{agents} 没有用户级指令文件。",
"+ its own": "+ 专属",
"{agent} gets something of its own after the shared text": "{agent} 在共享内容之后还有专属内容",
"edited in the file": "文件中已被修改",
"magpie's part of this file was changed there; magpie leaves it until the library's text changes": "文件中 magpie 的部分在别处被改过;在资源库内容变化前 magpie 不会动它",
"1 line of its own": "1 行自有内容",
"{n} lines of its own": "{n} 行自有内容",
"The file has instructions besides magpie's part — they stay, and the agent reads both": "文件里除了 magpie 的部分还有别的指令 — 它们会保留,Agent 两者都会读",
"{agent} reads the shared instructions": "{agent} 读取共享指令",
"Taken out of {agent}'s file": "已从 {agent} 的文件中移除",
"{agent} is on — save to write the new text into its file": "{agent} 已开启 — 保存后写入它的文件",
"{agent} is on — it gets the shared instructions once there are some": "{agent} 已开启 — 有共享指令后就会写入",
"{agent} reads the shared instructions now": "{agent} 现在读取共享指令",
"{agent} reads {file} instead of this file while it has anything in it.": "只要 {file} 有内容,{agent} 就会读它而不是这个文件。",
"OpenCode reads Claude Code's CLAUDE.md when it has no AGENTS.md of its own.": "OpenCode 在没有自己的 AGENTS.md 时会读取 Claude Code 的 CLAUDE.md。",
"Only for {agent}, after the shared text": "仅给 {agent},接在共享内容之后",
"Anything only {agent} should be told": "只需告诉 {agent} 的内容",
"Switch {agent} on for it to read this.": "开启 {agent} 后它才会读到这些。",
"Move its own into the shared text": "把它的内容移入共享指令",
"Moved into the shared instructions — {agent} reads the same as before": "已移入共享指令 — {agent} 读到的内容与之前相同",
"Takes the {n} lines out of the file, adds them to the shared text, and switches {agent} on — so it reads what it read before, and the other agents can too": "从文件中取出这 {n} 行加入共享指令,并开启 {agent} — 它读到的不变,其他 Agent 也能读到",
"Write the library's text again": "重新写入资源库的内容",
"{agent}'s file has the library's text again": "{agent} 的文件已恢复为资源库的内容",
"Replaces what was changed in magpie's part of the file; the file is kept aside first": "覆盖文件中 magpie 部分的改动;会先备份文件",
"{agent} can't reach a server over SSE — only a command or streamable HTTP": "{agent} 不支持 SSE 服务器 — 只支持命令或 Streamable HTTP",
"Add a server once and switch it on for the agents that should have it — magpie writes it into each one's config in the shape that agent reads.": "服务器只需添加一次,再为需要的 Agent 开启 — magpie 会按各 Agent 能读的格式写进它们的配置。",
"+ Add a server": "+ 添加服务器",
"No servers in the library yet": "资源库里还没有服务器",
"Add one, or bring in those your agents already have, below.": "添加一个,或把 Agent 里已有的导入进来(见下方)。",
"Paste a server's JSON from its README, or fill it in.": "粘贴 README 里的服务器 JSON,或手动填写。",
"+ Add server": "+ 添加服务器",
"In your agents": "Agent 中已有",
"not in the library — bring one in to manage it here": "不在资源库中 — 导入后即可在这里管理",
"{agents} has no MCP servers magpie can write.": "{agents} 没有 magpie 可写入的 MCP 配置。",
"Edit {name}": "编辑 {name}",
"differs in {agents}": "{agents} 中不同",
"{agents} has another server by this name; bringing this one in leaves that one as it is": "{agents} 有另一个同名服务器;导入这个不会改动那个",
"Bring in": "导入",
"{name} is in the library now": "{name} 已加入资源库",
"Keeps it in the library: {agents} go on having it, and you can give it to the others": "放进资源库:{agents} 继续拥有它,你也可以把它给其他 Agent",
"+ Add": "+ 添加",
"New MCP server": "新的 MCP 服务器",
"or paste its JSON anywhere here": "或直接在此粘贴它的 JSON",
"e.g. github": "例如 github",
"Letters, digits, - and _ — what the agents call it": "字母、数字、- 和 _ — Agent 用这个名字称呼它",
"Command": "命令",
"Runs as": "运行方式",
"The command and its arguments, as you'd type them": "命令及参数,就像在终端里输入的那样",
"Environment": "环境变量",
"Remove from the library": "从资源库移除",
"{name} is out of the library and the agents it was given to": "{name} 已从资源库及相关 Agent 中移除",
"Filled in from what you pasted": "已根据粘贴内容填写",
"{n} servers in what you pasted": "粘贴内容中有 {n} 个服务器",
"(no name)": "(无名称)",
"in the library": "已在资源库",
"Add 1 server": "添加 1 个服务器",
"Add {n} servers": "添加 {n} 个服务器",
"Added {n} servers": "已添加 {n} 个服务器",
"A skill is a folder with a SKILL.md an agent loads when it's needed. The library keeps each one once and links it into the agents you pick.": "技能是一个带 SKILL.md 的文件夹,Agent 在需要时加载。资源库只保存一份,再链接到你选的 Agent 中。",
"In the library": "资源库中",
"not in the library — bring one in to give it to the others": "不在资源库中 — 导入后可以给其他 Agent",
"{agents} has no skills folder.": "{agents} 没有技能文件夹。",
"owner/repo, a GitHub link, or a folder on this computer": "owner/repo、GitHub 链接,或本机上的文件夹",
"Looking…": "查找中…",
"Find skills": "查找技能",
"No SKILL.md found there": "那里没有找到 SKILL.md",
"No skills there — a skill is a folder with a SKILL.md in it.": "那里没有技能 — 技能是一个含 SKILL.md 的文件夹。",
"1 skill in {src}": "{src} 中有 1 个技能",
"{n} skills in {src}": "{src} 中有 {n} 个技能",
"Select none": "全不选",
"for": "给",
"Installing…": "安装中…",
"1 skill installed": "已安装 1 个技能",
"{n} skills installed": "已安装 {n} 个技能",
"Install 1 skill": "安装 1 个技能",
"Install {n} skills": "安装 {n} 个技能",
"Its folder is gone from the library": "它的文件夹已不在资源库中",
"linked from": "链接自",
"{name} is up to date": "{name} 已是最新",
"Update from GitHub": "从 GitHub 更新",
"Read {name}'s SKILL.md": "查看 {name} 的 SKILL.md",
"Remove {name}?": "移除 {name}?",
"It is taken out of every agent it was given to. The folder it was linked from stays where it is.": "它会从所有已启用的 Agent 中移除。它链接的原文件夹保持不动。",
"It is taken out of every agent it was given to, and its folder is moved to magpie's backups.": "它会从所有已启用的 Agent 中移除,文件夹会移到 magpie 的备份中。",
"{agents} has another skill by this name; bringing this one in leaves that one as it is": "{agents} 有另一个同名技能;导入这个不会改动那个",
"Keeps a link to where it is: {agents} go on having it, and you can give it to the others": "保留指向原位置的链接:{agents} 继续拥有它,你也可以给其他 Agent",
"Moves it into the library and links it back: {agents} go on having it, and you can give it to the others": "移入资源库并链接回去:{agents} 继续拥有它,你也可以给其他 Agent",
"Discover": "发现",
"Search MCP servers — GitHub, Postgres, Figma…": "搜索 MCP 服务器 — GitHub、Postgres、Figma…",
"Search skills on skills.sh — react, pdf, testing…": "在 skills.sh 搜索技能 — react、pdf、testing…",
"1 result": "1 个结果",
"{n} results": "{n} 个结果",
"Featured, and the official MCP Registry": "精选,以及官方 MCP Registry",
"Popular on skills.sh": "skills.sh 热门",
"Nothing matches “{q}”.": "没有与“{q}”匹配的结果。",
"Nothing to show.": "暂无内容。",
"Remote · sign-in": "远程 · 需登录",
"Remote": "远程",
"Local": "本地",
"Added": "已添加",
"In the library as {name}": "已在资源库中,名为 {name}",
"Adding…": "添加中…",
"Needs {what} to add": "添加时需要 {what}",
"Add…": "添加…",
"About {name}": "关于 {name}",
"Homepage": "主页",
"Each agent asks you to sign in, in the browser, the first time it uses it.": "每个 Agent 首次使用时会在浏览器中请你登录。",
"Set as {key}": "设为 {key}",
"Sent as the {key} header": "作为 {key} 请求头发送",
"(optional)": "(可选)",
"Add to the library": "加入资源库",
"{what} is needed": "请填写 {what}",
"Official — from the team that makes it": "官方 — 来自其开发团队",
"{n} installs": "{n} 次安装",
"Official": "官方",
"No description.": "暂无描述。",
"From": "来自",
"Up-to-date documentation and code examples for any library, straight into the prompt.": "任意库的最新文档与代码示例,直接送进提示词。",
"Drive a real browser: open pages, click, type and read them through the accessibility tree.": "驱动真实浏览器:打开页面、点击、输入,并通过无障碍树读取页面。",
"Control and inspect a live Chrome: console, network, performance traces and screenshots.": "控制并检查运行中的 Chrome:控制台、网络、性能追踪和截图。",
"Repositories, issues, pull requests, Actions and code search on GitHub.": "GitHub 上的仓库、Issue、PR、Actions 和代码搜索。",
"Ask questions about any public GitHub repository and read its generated wiki.": "就任意公开 GitHub 仓库提问,并阅读自动生成的 Wiki。",
"Web search and code search built for agents, with clean page contents.": "为 Agent 打造的网页与代码搜索,返回干净的页面内容。",
"Read, write and search files, limited to the folders you allow.": "读、写、搜索文件,仅限你允许的文件夹。",
"Fetch a web page and hand it over as Markdown.": "抓取网页并转成 Markdown。",
"A knowledge graph the agent keeps across conversations.": "Agent 跨对话保留的知识图谱。",
"Think a problem through step by step, revising and branching as it goes.": "一步步想清问题,边想边修正、分支。",
"Read, search and change Git repositories.": "读取、搜索和修改 Git 仓库。",
"The current time anywhere, and conversions between time zones.": "任意地点的当前时间,以及时区换算。",
"Issues, errors and traces from Sentry, and Seer's analysis of them.": "Sentry 中的问题、错误和追踪,以及 Seer 的分析。",
"Find, create and update Linear issues, projects and comments.": "查找、创建和更新 Linear 的 Issue、项目和评论。",
"Search, read and write pages and databases in your Notion workspace.": "搜索、读写 Notion 工作区中的页面和数据库。",
"Jira issues and Confluence pages from Atlassian Cloud.": "Atlassian Cloud 上的 Jira Issue 和 Confluence 页面。",
"Manage Supabase projects: tables, SQL, migrations, logs and edge functions.": "管理 Supabase 项目:数据表、SQL、迁移、日志和 Edge Functions。",
"Customers, payments, subscriptions and Stripe's documentation.": "客户、支付、订阅,以及 Stripe 文档。",
"Projects, deployments and logs on Vercel, and its documentation.": "Vercel 上的项目、部署和日志,以及其文档。",
"Serverless Postgres on Neon: projects, branches and SQL.": "Neon 上的 Serverless Postgres:项目、分支和 SQL。",
"Search Cloudflare's documentation.": "搜索 Cloudflare 文档。",
"Official Microsoft and Azure documentation and code samples.": "微软与 Azure 官方文档和代码示例。",
"Search models, datasets, Spaces and papers on the Hugging Face Hub.": "搜索 Hugging Face Hub 上的模型、数据集、Spaces 和论文。",
"Web, news, image and local search from Brave's independent index.": "基于 Brave 独立索引的网页、新闻、图片和本地搜索。",
"Scrape, crawl and search the web into clean Markdown.": "抓取、爬取和搜索网页,输出干净的 Markdown。",
"Search and extract from the web with Tavily.": "用 Tavily 搜索并提取网页内容。",
"Personal access token": "个人访问令牌",
"Folder": "文件夹",
"The folder it may read and write": "它可以读写的文件夹",
"Optional — raises the rate limit. From context7.com/dashboard": "可选 — 提高速率限制。在 context7.com/dashboard 获取",
},
};
+5
View File
@@ -6,6 +6,7 @@
<title>magpie</title>
<link rel="stylesheet" href="app.css">
<link rel="stylesheet" href="routing.css">
<link rel="stylesheet" href="library.css">
</head>
<body>
<header class="top" style="--wails-draggable:drag">
@@ -19,6 +20,7 @@
<button data-view="gateway" data-t>Gateway</button>
<button data-view="routing" data-t>Routing</button>
<button data-view="usage" data-t>Usage</button>
<button data-view="library" data-t>Library</button>
</nav>
<div class="actions" style="--wails-draggable:no-drag">
<button class="update" id="update" hidden>
@@ -90,6 +92,8 @@
<p class="usage-note" id="usageNote"></p>
</main>
<main class="view" id="view-library" hidden></main>
<main class="view" id="view-settings" hidden>
<div class="row-head"><span class="label" data-t>Preferences</span></div>
<div class="list prefs">
@@ -145,5 +149,6 @@
<script src="i18n.js"></script>
<script src="app.js"></script>
<script src="routing.js"></script>
<script src="library.js"></script>
</body>
</html>
+274
View File
@@ -0,0 +1,274 @@
/* Library: instructions, MCP servers and skills for every agent. */
#view-library { gap: 0; }
/* The tabs stay at the top while the page scrolls under them, on a frosted
strip as wide as the view; a hairline shows once something is beneath. */
.lib-head {
position: sticky; top: 0; z-index: 5;
display: flex; align-items: center; gap: 8px; flex: none;
margin: 0 -12px; padding: 6px 12px 4px;
background: color-mix(in srgb, var(--bg) 92%, transparent);
-webkit-backdrop-filter: saturate(1.6) blur(16px); backdrop-filter: saturate(1.6) blur(16px);
box-shadow: 0 1px 0 transparent; transition: box-shadow .18s var(--ease);
}
/* the window's view is padded 2px at the top: the strip reaches over it */
body.window .lib-head { top: -2px; margin: -2px -16px 0; padding: 8px 16px 4px; }
.lib-head.stuck { box-shadow: 0 1px 0 var(--line-2); }
.lib-tabs .opt { height: 24px; padding: 0 12px; font-size: 12.5px; }
.lib-more { display: inline-flex; align-items: center; gap: 5px; }
.lib-mini { display: inline-grid; place-items: center; color: var(--muted); }
.lib-mini svg { width: 13px; height: 13px; }
.lib-body { display: flex; flex-direction: column; flex: none; animation: content-in .22s var(--ease); }
.lib-intro { margin: 8px 2px 10px; font-size: 12px; line-height: 1.5; color: var(--muted); max-width: 640px; }
.lib-aside { margin: 8px 4px 0; font-size: 11.5px; line-height: 1.5; color: var(--faint); }
.lib-aside.center { text-align: center; margin-top: 14px; }
.lib-foot { margin: auto 0 0; padding: 18px 4px 6px; font-size: 11px; color: var(--faint); flex: none; }
.lib-link { font-size: 11px; color: var(--muted); text-decoration: underline; text-decoration-color: var(--line); text-underline-offset: 2px; }
.lib-link:hover { color: var(--fg); text-decoration-color: currentColor; }
/* the glyph at the front of a row: drawn, in the text colour */
.lib-glyph { flex: none; width: 26px; height: 26px; border-radius: 7px; display: grid; place-items: center; color: var(--fg-2); background: var(--pill); }
.lib-glyph svg { width: 15px; height: 15px; }
.mk-icon.lib-logo { flex: none; width: 26px; height: 26px; border-radius: 7px; }
.lib-editor .ehead .mk-icon.lib-logo { width: 24px; height: 24px; }
/* cards: the shared text, the skill finder */
.lib-card { display: flex; flex-direction: column; }
.lib-cardhead { display: flex; align-items: center; gap: 9px; padding: 9px 12px 0; }
.lib-cardhead b { font-weight: 600; font-size: 13px; }
.lib-cardhead .note { font-size: 11px; color: var(--faint); }
.lib-text {
display: block; width: 100%; box-sizing: border-box; resize: none; border: 0; outline: none; background: none; color: var(--fg);
padding: 10px 14px 14px; font: 12.5px/1.6 var(--code); tab-size: 2; min-height: 150px;
}
.lib-text::placeholder { color: var(--faint); font-family: var(--font); font-size: 12.5px; }
.lib-text.small { min-height: 64px; border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; background: var(--card); transition: border-color .12s, box-shadow .12s; }
.lib-text.small:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
/* unsaved text: a bar that stays in view at the bottom until it's saved */
.lib-savebar {
position: sticky; bottom: 8px; z-index: 3; margin-top: 12px; display: flex; align-items: center; gap: 6px;
padding: 7px 8px 7px 14px; border-radius: 11px; background: var(--pop-bg); box-shadow: var(--shadow);
-webkit-backdrop-filter: blur(14px); backdrop-filter: blur(14px); animation: lib-rise .22s var(--ease);
}
.lib-savebar[hidden] { display: none; }
.lib-savebar .note { font-size: 12px; color: var(--fg-2); display: inline-flex; align-items: center; gap: 7px; }
.lib-savebar .note::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--fg); }
@keyframes lib-rise { from { opacity: 0; transform: translateY(8px); } }
/* rows */
.lib-list .row { min-height: 50px; padding: 7px 10px 7px 12px; gap: 11px; }
.lib-row.click { cursor: default; transition: background .14s var(--ease); }
.lib-row.click:hover { background: var(--card-2); }
.lib-row .who { flex: 1 1 auto; min-width: 0; }
/* a server's or skill's picture sits level with the top of its name */
.lib-row > .lib-logo, .lib-row > .lib-glyph { align-self: flex-start; margin-top: 1px; }
.lib-row .name.mono, .lib-pick .name.mono { font: 500 12.5px var(--code); }
.lib-row .sub { max-width: 100%; }
.lib-row .sub.mono, .lib-pick .sub.mono { font: 11px var(--code); color: var(--muted); }
.lib-row .chev { flex: none; color: var(--faint); transition: transform .2s var(--ease); display: grid; place-items: center; }
.lib-row.open .chev { transform: rotate(90deg); }
.lib-row.open { background: var(--card-2); }
.lib-skill .sub { white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; line-height: 1.4; }
.lib-skill.missing .name { color: var(--muted); text-decoration: line-through; text-decoration-color: var(--faint); }
.lib-skill.missing .sub { color: var(--amber); }
.lib-src { display: flex; align-items: center; gap: 5px; margin-top: 3px; font-size: 11px; color: var(--faint); min-width: 0; }
.lib-srclink { font: 11px var(--code); color: var(--muted); text-decoration: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.lib-srclink:hover { color: var(--fg); text-decoration: underline; text-underline-offset: 2px; }
/* a path: shown in the file manager on a click */
.lib-path { font: 11px var(--code); color: var(--muted); padding: 0; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: left; border-radius: 3px; }
.lib-path:hover { color: var(--fg); text-decoration: underline; text-underline-offset: 2px; }
/* tags beside a name */
.lib-tags { display: flex; gap: 5px; flex: none; flex-wrap: wrap; justify-content: flex-end; }
.lib-tag { flex: none; display: inline-flex; align-items: center; gap: 5px; height: 20px; padding: 0 7px; border-radius: 6px; font-size: 11px; color: var(--fg-2); background: var(--pill); white-space: nowrap; }
.lib-tag.warn { color: var(--amber); background: var(--amber-soft); }
.lib-tag.warn::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: currentColor; }
/* the switch */
.lib-switch { flex: none; position: relative; width: 32px; height: 19px; border-radius: 10px; background: var(--line); transition: background .2s var(--ease); }
.lib-switch i { position: absolute; top: 2px; left: 2px; width: 15px; height: 15px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgba(0, 0, 0, .25); transition: transform .22s var(--ease); }
.lib-switch.on { background: var(--fg); }
.lib-switch.on i { transform: translateX(13px); background: var(--card); }
:root[data-theme="dark"] .lib-switch.on i { background: var(--bg); }
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .lib-switch.on i { background: var(--bg); } }
/* an agent's instructions, opened */
.lib-detail { padding: 4px 14px 14px 50px; background: var(--card-2); display: flex; flex-direction: column; gap: 8px; border-top: 0 !important; animation: content-in .2s var(--ease); }
.lib-lab { font-size: 11.5px; color: var(--muted); }
.lib-detail .lib-aside { margin: 0; }
.lib-acts { display: flex; gap: 6px; flex-wrap: wrap; }
.lib-warn { font-size: 12px; line-height: 1.5; color: var(--fg); background: var(--amber-soft); border-radius: 8px; padding: 8px 10px; }
.lib-warn .lib-path { display: inline; }
/* agents a server or skill is given to: an icon each, lit when it has it */
.lib-agents { display: flex; flex-wrap: wrap; gap: 3px; flex: none; justify-content: flex-end; max-width: 50%; }
.lib-ag {
position: relative; display: inline-flex; align-items: center; gap: 6px; height: 26px; min-width: 26px; padding: 0 5px; border-radius: 7px;
border: 1px solid transparent; font-size: 12px; color: var(--muted); transition: background .14s, border-color .14s, color .14s, transform .14s var(--ease);
}
.lib-ag .ic { width: 15px; height: 15px; filter: grayscale(1); opacity: .35; transition: filter .14s, opacity .14s; }
.lib-ag:hover { background: var(--pill); }
.lib-ag:hover .ic { opacity: .7; }
.lib-ag.on { background: var(--card); border-color: var(--line); color: var(--fg); box-shadow: 0 1px 1px rgba(0, 0, 0, .05); }
.lib-ag.on .ic { filter: none; opacity: 1; }
.lib-ag.via { border: 1px dashed var(--line); }
.lib-ag.via .ic { opacity: .6; }
.lib-ag.warn::after { content: ""; position: absolute; top: -2px; right: -2px; width: 7px; height: 7px; border-radius: 50%; background: var(--amber); box-shadow: 0 0 0 2px var(--card); }
.lib-ag.blocked { opacity: .35; }
.lib-ag.blocked:hover { background: none; }
.lib-ag:active:not(:disabled) { transform: scale(.92); }
.editor .lib-agents { max-width: none; justify-content: flex-start; gap: 5px; }
.editor .lib-ag { padding: 0 9px 0 6px; border-color: var(--line); }
.editor .lib-ag.on { background: var(--accent-soft); border-color: color-mix(in srgb, var(--fg) 30%, transparent); }
.lib-probefoot .lib-agents { max-width: none; justify-content: flex-start; }
/* in a list row they sit stacked like a hand of cards, on one line, and fan
out when the pointer or focus comes to them */
.lib-row > .lib-agents { flex-wrap: nowrap; gap: 0; max-width: none; padding-left: 4px; }
.lib-row > .lib-agents .lib-ag { flex: none; width: 24px; min-width: 0; height: 24px; padding: 0 0 0 4px; justify-content: flex-start; background: var(--card); border-color: var(--line-2); box-shadow: 0 0 0 1.5px var(--card); transition: margin .22s var(--ease), background .14s, border-color .14s, transform .14s var(--ease); }
.lib-row > .lib-agents .lib-ag .ic { width: 14px; height: 14px; }
.lib-row > .lib-agents .lib-ag + .lib-ag { margin-left: -7px; }
.lib-row > .lib-agents .lib-ag.on { border-color: var(--line); box-shadow: 0 0 0 1.5px var(--card), 0 1px 2px rgba(0, 0, 0, .08); }
.lib-row > .lib-agents .lib-ag.via { border-style: dashed; }
.lib-row > .lib-agents:hover .lib-ag + .lib-ag, .lib-row > .lib-agents:focus-within .lib-ag + .lib-ag { margin-left: 3px; }
.lib-row > .lib-agents:hover .lib-ag, .lib-row > .lib-agents:focus-within .lib-ag { box-shadow: none; }
.lib-row > .lib-agents .lib-ag:hover { background: var(--pill); z-index: 1; }
.lib-row.click:hover > .lib-agents .lib-ag { box-shadow: 0 0 0 1.5px var(--card-2); }
.lib-row.click:hover > .lib-agents:hover .lib-ag { box-shadow: none; }
/* agents that have one of their own, not in the library */
.lib-have { display: flex; gap: 4px; flex: none; }
.lib-have .ic { width: 15px; height: 15px; }
/* a skill's actions show on hover */
.lib-rowacts { display: flex; gap: 2px; flex: none; opacity: 0; transition: opacity .14s; }
.lib-row:hover .lib-rowacts, .lib-rowacts:focus-within { opacity: 1; }
.lib-icon { width: 26px; height: 26px; padding: 0; display: inline-grid; place-items: center; }
.lib-icon.busy svg { animation: lib-bob .8s var(--ease) infinite alternate; }
@keyframes lib-bob { to { transform: translateY(-2px); } }
/* the skill finder */
.lib-install { margin-bottom: 4px; }
.lib-find { display: flex; align-items: center; gap: 8px; padding: 8px 8px 8px 12px; }
.lib-find input { flex: 1; min-width: 0; height: 28px; border: 0; outline: none; background: none; font-size: 13px; color: var(--fg); }
.lib-find input::placeholder { color: var(--faint); }
.lib-find .text.busy { color: var(--muted); }
.lib-err { padding: 0 14px 10px 36px; font-size: 12px; color: var(--red); line-height: 1.45; overflow-wrap: anywhere; }
.lib-probe { border-top: 1px solid var(--line-2); padding: 8px 8px 8px; display: flex; flex-direction: column; gap: 6px; animation: content-in .22s var(--ease); }
.lib-probehead { display: flex; align-items: center; gap: 6px; padding: 0 4px; }
.lib-probehead .note { font-size: 11.5px; color: var(--muted); }
.lib-filter { height: 26px; margin: 0 4px; padding: 0 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font-size: 12px; outline: none; }
.lib-filter:focus { border-color: var(--accent); }
.lib-picks { display: flex; flex-direction: column; max-height: 300px; overflow-y: auto; }
.lib-pick { display: flex; align-items: flex-start; gap: 10px; padding: 7px 6px; border-radius: 8px; cursor: default; }
.lib-pick:hover:not(.dim) { background: var(--pill); }
.lib-pick.dim { opacity: .55; }
.lib-pick input { margin: 2px 0 0; accent-color: var(--fg); flex: none; }
.lib-pick .who { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.lib-pick .name { font-size: 13px; font-weight: 500; }
.lib-pick .sub { font-size: 11.5px; color: var(--muted); line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.lib-probefoot { display: flex; align-items: center; gap: 8px; padding: 8px 4px 0; border-top: 1px solid var(--line-2); flex-wrap: wrap; }
.lib-probefoot .note { font-size: 12px; color: var(--muted); }
/* nothing yet */
.lib-empty { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 34px 20px 30px; text-align: center; background: var(--card); border: 1px dashed var(--line); border-radius: 12px; }
.lib-empty b { font-weight: 600; font-size: 13px; }
.lib-empty p { margin: 0 0 8px; font-size: 12px; color: var(--muted); max-width: 380px; line-height: 1.5; }
.lib-none { padding: 14px; font-size: 12px; color: var(--muted); }
.lib-skel .row { height: 50px; }
/* the dialog */
.lib-editor .ehead .lib-glyph { width: 24px; height: 24px; }
.lib-editor .ehead .note { font-size: 11.5px; color: var(--faint); margin-left: auto; }
.lib-editor .lib-slot { display: contents; }
.lib-editor .lib-grid { display: contents; }
.lib-editor input.mono { font-family: var(--code); font-size: 12px; }
.lib-pairs { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; }
.lib-pair { display: flex; gap: 6px; width: 100%; align-items: center; }
.lib-pair input { flex: 1; min-width: 0; font-family: var(--code); font-size: 12px; }
.lib-pair input:first-child { flex: .8; }
.lib-x { width: 24px; height: 24px; padding: 0; display: inline-grid; place-items: center; flex: none; }
.lib-addpair { padding-left: 0; }
.lib-addpair:hover { background: none; }
.lib-editor .lib-picks { grid-column: 1 / -1; max-height: 320px; }
.lib-confirm { grid-column: 1 / -1; margin: 0; font-size: 12.5px; line-height: 1.55; color: var(--fg-2); }
.text.danger-fill { background: var(--red); color: #fff; }
.lib-reader { grid-template-columns: minmax(0, 1fr); }
.lib-md { margin: 0; max-height: min(60vh, 520px); overflow: auto; font: 12px/1.6 var(--code); color: var(--fg-2); white-space: pre-wrap; overflow-wrap: anywhere; background: var(--card-2); border-radius: 8px; padding: 12px 14px; user-select: text; -webkit-user-select: text; }
.lib-reader .bar .lib-path { max-width: 70%; }
.editor .editor-error:empty { display: none; }
@media (max-width: 560px) {
.lib-list .row { flex-wrap: wrap; }
.lib-agents { max-width: 100%; }
}
/* a list's heading: its label, and a quiet line of what it does */
#view-library .row-head { height: auto; min-height: 26px; margin: 18px 0 6px; padding: 0 2px; gap: 12px; }
#view-library .row-head .note { min-width: 0; font-size: 11px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* the market: servers and skills to add, each with its own picture */
.mk { display: flex; flex-direction: column; }
.mk-find { display: flex; align-items: center; gap: 8px; height: 36px; padding: 0 12px; margin-bottom: 10px; border-radius: 10px; background: var(--card); border: 1px solid var(--line); transition: border-color .14s, box-shadow .14s; }
.mk-find:focus-within { border-color: color-mix(in srgb, var(--fg) 35%, transparent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--fg) 7%, transparent); }
.mk-find input { flex: 1; min-width: 0; height: 100%; border: 0; outline: none; background: none; font-size: 13px; color: var(--fg); }
.mk-find input::placeholder { color: var(--faint); }
.mk-find input::-webkit-search-cancel-button { -webkit-appearance: none; }
.mk-spin { flex: none; width: 12px; height: 12px; border-radius: 50%; border: 1.5px solid var(--line); border-top-color: var(--fg-2); opacity: 0; transition: opacity .15s; }
.mk.loading .mk-spin { opacity: 1; animation: mk-spin .7s linear infinite; }
@keyframes mk-spin { to { transform: rotate(360deg); } }
.mk-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(236px, 1fr)); gap: 10px; transition: opacity .2s var(--ease); }
.mk.loading .mk-grid { opacity: .55; }
.mk-card {
position: relative; display: flex; flex-direction: column; gap: 9px; min-width: 0; padding: 12px 12px 10px; border-radius: 12px;
background: var(--card); border: 1px solid var(--line); box-shadow: 0 1px 1px rgba(0, 0, 0, .03);
transition: border-color .16s var(--ease), box-shadow .16s var(--ease), transform .16s var(--ease);
animation: content-in .24s var(--ease) both;
}
.mk-card.click:hover { border-color: color-mix(in srgb, var(--fg) 22%, transparent); box-shadow: 0 6px 18px -8px rgba(0, 0, 0, .18); transform: translateY(-1px); }
.mk-top { display: flex; align-items: center; gap: 10px; min-width: 0; }
.mk-icon {
flex: none; width: 36px; height: 36px; border-radius: 9px; overflow: hidden; display: grid; place-items: center;
background: #fff; box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .07);
}
.mk-icon img { width: 100%; height: 100%; object-fit: cover; display: block; }
.mk-icon.svg img { width: 72%; height: 72%; object-fit: contain; }
.mk-icon.mono { background: var(--pill); box-shadow: none; }
.mk-mono { font-size: 15px; font-weight: 600; color: var(--fg-2); }
.mk-icon.skeleton { box-shadow: none; }
:root[data-theme="dark"] .mk-icon:not(.mono):not(.skeleton) { box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .08); }
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .mk-icon:not(.mono):not(.skeleton) { box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .08); } }
.mk-who { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px; }
.mk-name { display: flex; align-items: center; gap: 5px; min-width: 0; font-size: 13px; font-weight: 600; line-height: 1.2; }
.mk-title { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mk-name.big { font-size: 15px; }
.mk-meta { display: flex; align-items: center; gap: 6px; min-width: 0; font-size: 11px; color: var(--muted); }
.mk-pub { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mk-badge { flex: none; display: inline-flex; align-items: center; gap: 3px; height: 17px; padding: 0 6px; border-radius: 5px; background: var(--pill); color: var(--fg-2); font-size: 10.5px; font-family: var(--code); }
.mk-badge.mk-needs { width: 17px; padding: 0; justify-content: center; }
.mk-official { flex: none; display: inline-grid; place-items: center; width: 13px; height: 13px; border-radius: 50%; background: var(--fg); color: var(--card); }
.mk-desc { margin: 0; min-height: 2.9em; font-size: 12px; line-height: 1.45; color: var(--fg-2); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.mk-desc.wait { background: linear-gradient(90deg, var(--pill) 25%, var(--pill-hover) 45%, var(--pill) 65%); background-size: 240% 100%; animation: skeleton-shift 1.4s ease-in-out infinite; border-radius: 5px; min-height: 0; height: 8px; margin: 6px 20% 10px 0; }
.mk-foot { display: flex; align-items: center; gap: 8px; min-height: 26px; margin-top: auto; }
.mk-id { min-width: 0; font: 11px var(--code); color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mk-installs { display: inline-flex; align-items: center; gap: 3px; font-size: 11px; color: var(--muted); font-variant-numeric: tabular-nums; }
.mk-add { flex: none; height: 26px; }
.mk-add.busy { color: var(--muted); }
.mk-have { flex: none; display: inline-flex; align-items: center; gap: 4px; height: 26px; padding: 0 4px; font-size: 12px; color: var(--muted); }
.mk-card.have .mk-icon { opacity: .9; }
.mk-msg { grid-column: 1 / -1; padding: 22px 12px; text-align: center; font-size: 12px; color: var(--muted); }
.mk-msg.err { padding: 8px 12px; color: var(--amber); background: var(--amber-soft); border-radius: 8px; text-align: left; line-height: 1.45; }
.mk-skel { gap: 12px; min-height: 104px; }
.mk-skel .mk-who { gap: 7px; }
/* a market item up close */
.mk-sheet .mk-sheethead { grid-column: 1 / -1; display: flex; align-items: center; gap: 12px; padding-bottom: 12px; border-bottom: 1px solid var(--line-2); }
.mk-sheet .mk-icon { width: 44px; height: 44px; border-radius: 11px; }
.mk-sheet .mk-about { grid-column: 1 / -1; margin: 0; font-size: 12.5px; line-height: 1.55; color: var(--fg-2); }
.mk-sheet .mk-hint { grid-column: 1 / -1; display: flex; align-items: center; gap: 6px; margin: 0; font-size: 11.5px; color: var(--muted); }
.mk-ext { flex: none; display: inline-flex; align-items: center; gap: 4px; font-size: 12px; color: var(--muted); text-decoration: none; padding: 3px 6px; border-radius: 6px; }
.mk-ext:hover { color: var(--fg); background: var(--pill); }
.mk-sheet .mk-hint .mk-ext { padding: 0; font-family: var(--code); font-size: 11.5px; }
.mk-sheet .mk-hint .mk-ext:hover { background: none; text-decoration: underline; text-underline-offset: 2px; }
.mk-sheet .bar .mk-id { margin-left: 2px; }
File diff suppressed because it is too large Load Diff
+228
View File
@@ -0,0 +1,228 @@
package gui
import (
"encoding/json"
"net/http"
"os"
"path/filepath"
"slices"
"sync"
"github.com/yetone/magpie/internal/library"
)
// The problems of the last change to the library stay on the page until the
// next one, so a reload still says what an agent couldn't be given.
var lastProblems struct {
sync.Mutex
p []library.Problem
}
type libraryJSON struct {
*library.View
Result *library.Result `json:"result,omitempty"`
Home string `json:"home"` // for the page to show paths under it as ~
}
func libraryView(res *library.Result) (libraryJSON, error) {
lastProblems.Lock()
if res != nil {
lastProblems.p = res.Problems
}
p := lastProblems.p
lastProblems.Unlock()
v, err := library.Read(p)
home, _ := os.UserHomeDir()
return libraryJSON{View: v, Result: res, Home: home}, err
}
// marketJSON is a market's list, and why it may be short: a search that
// couldn't reach the registry still shows what magpie has of its own.
type marketJSON struct {
Items any `json:"items"`
Error string `json:"error,omitempty"`
}
func errText(err error) string {
if err == nil {
return ""
}
return err.Error()
}
// revealable is every path the Library page shows: the only ones it may
// ask to be shown in the file manager.
func revealable(v *library.View) []string {
out := []string{v.Dir, v.Backups}
for _, a := range v.Agents {
out = append(out, a.Instructions, a.MCP, a.Skills)
}
for _, s := range v.Skills {
out = append(out, library.SkillPath(s.Name))
if s.Kind == "folder" {
out = append(out, s.Source)
}
}
for _, s := range v.FoundSkills {
out = append(out, s.Link)
}
return out
}
func libraryRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/library", func(rw http.ResponseWriter, r *http.Request) {
v, err := libraryView(nil)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, v)
})
mux.HandleFunc("GET /api/library/skill", func(rw http.ResponseWriter, r *http.Request) {
text, err := library.SkillText(r.URL.Query().Get("name"))
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, map[string]string{"text": text, "path": library.SkillPath(r.URL.Query().Get("name"))})
})
// the market: what it offers for a search, and each skill's description
// once asked for, which skills.sh gives one at a time
mux.HandleFunc("GET /api/library/market/servers", func(rw http.ResponseWriter, r *http.Request) {
list, err := library.MarketServers(r.URL.Query().Get("q"))
writeJSON(rw, marketJSON{Items: list, Error: errText(err)})
})
mux.HandleFunc("GET /api/library/market/skills", func(rw http.ResponseWriter, r *http.Request) {
list, err := library.MarketSkills(r.URL.Query().Get("q"))
writeJSON(rw, marketJSON{Items: list, Error: errText(err)})
})
mux.HandleFunc("POST /api/library/market/about", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ IDs []string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if len(in.IDs) > 60 {
in.IDs = in.IDs[:60]
}
writeJSON(rw, library.SkillsAbout(in.IDs))
})
mux.HandleFunc("GET /api/library/icon", func(rw http.ResponseWriter, r *http.Request) {
b, ct, err := library.Icon(r.URL.Query().Get("u"))
if err != nil {
http.Error(rw, err.Error(), http.StatusNotFound)
return
}
rw.Header().Set("Content-Type", ct)
rw.Header().Set("Cache-Control", "max-age=604800")
rw.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'") // an SVG opened on its own runs nothing
rw.Write(b)
})
mux.HandleFunc("POST /api/library/skills/probe", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Source string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
p, err := library.ProbeSkills(in.Source)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, p)
})
mux.HandleFunc("POST /api/library/reveal", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Path string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Path == "" {
http.Error(rw, "no path", http.StatusBadRequest)
return
}
v, err := library.Read(nil)
if err != nil {
fail(rw, err)
return
}
if !slices.Contains(revealable(v), in.Path) {
http.Error(rw, "not a path the library shows", http.StatusForbidden)
return
}
// a file is shown in its folder; one not written yet, the folder it will be in
p := in.Path
for {
fi, err := os.Stat(p)
if err == nil && fi.IsDir() {
break
}
up := filepath.Dir(p)
if up == p {
break
}
p = up
}
w.OpenFolder(p)
rw.WriteHeader(http.StatusNoContent)
})
// 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 {
Name string
Old string
Agents []string
Source string
Paths []string
Server library.Server
ID string // a market server's, or a market skill's in its repository
Values map[string]string // what a market server needs
library.InstructionsChange
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
var res *library.Result
var err error
switch r.PathValue("what") + "/" + r.PathValue("action") {
case "instructions/save":
res, err = library.SaveInstructions(in.InstructionsChange)
case "instructions/import":
res, err = library.ImportInstructions(in.Name)
case "servers/save":
res, err = library.SaveServer(in.Old, in.Server)
case "servers/agents":
res, err = library.ServerAgents(in.Name, in.Agents)
case "servers/remove":
res, err = library.RemoveServer(in.Name)
case "servers/import":
res, err = library.ImportServer(in.Name)
case "skills/install":
res, err = library.InstallSkills(in.Source, in.Paths, in.Agents)
case "skills/update":
res, err = library.UpdateSkill(in.Name)
case "skills/agents":
res, err = library.SkillAgents(in.Name, in.Agents)
case "skills/remove":
res, err = library.RemoveSkill(in.Name)
case "skills/import":
res, err = library.ImportSkill(in.Name)
case "market/server":
res, err = library.InstallServer(in.ID, in.Values, in.Agents)
case "market/skill":
res, err = library.InstallMarketSkill(in.Source, in.ID, in.Agents)
case "all/sync":
res, err = library.Sync()
default:
http.NotFound(rw, r)
return
}
if err != nil {
fail(rw, err)
return
}
v, err := libraryView(res)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, v)
})
}
+72
View File
@@ -0,0 +1,72 @@
package library
import (
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/yetone/magpie/internal/settings"
)
// keepBackups is how many changes' backups are kept.
const keepBackups = 30
// BackupDir is where a file is copied before magpie first changes it in a
// change: one folder a change, named by when, a folder an agent in it.
func BackupDir() string { return filepath.Join(settings.Dir(), "backups") }
// backups copies each file once, the first time a change is about to
// write it.
type backups struct {
dir string
done map[string]bool
}
func newBackups() *backups {
return &backups{done: map[string]bool{}}
}
// keep copies path aside, as the agent had it, before it is written; a
// file that isn't there has nothing to keep.
func (b *backups) keep(agent, path string) error {
if b.done[path] {
return nil
}
b.done[path] = true
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
if b.dir == "" {
b.dir = filepath.Join(BackupDir(), time.Now().Format("2006-01-02_15-04-05.000"))
}
dst := filepath.Join(b.dir, agent, filepath.Base(path))
if err := os.MkdirAll(filepath.Dir(dst), 0o700); err != nil {
return err
}
return os.WriteFile(dst, data, 0o600)
}
// prune leaves the newest keepBackups.
func pruneBackups() {
es, err := os.ReadDir(BackupDir())
if err != nil {
return
}
var names []string
for _, e := range es {
if e.IsDir() && !strings.HasPrefix(e.Name(), ".") {
names = append(names, e.Name())
}
}
slices.Sort(names)
for len(names) > keepBackups {
os.RemoveAll(filepath.Join(BackupDir(), names[0]))
names = names[1:]
}
}
+294
View File
@@ -0,0 +1,294 @@
package library
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"github.com/yetone/magpie/internal/edit"
)
// The part of an agent's instructions file magpie writes sits between
// these two lines; the rest of the file is the user's.
const (
blockBegin = "<!-- magpie:begin · written by magpie from its Library -->"
blockEnd = "<!-- magpie:end -->"
)
func sharedPath() string { return filepath.Join(Dir(), "instructions.md") }
func extraPath(agent string) string {
return filepath.Join(Dir(), "instructions", agent+".md")
}
func readText(path string) string {
b, _ := os.ReadFile(path)
return strings.TrimSpace(strings.ReplaceAll(string(b), "\r\n", "\n"))
}
func writeText(path, text string) error {
text = strings.TrimSpace(text)
if text == "" {
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
return edit.WriteAtomic(path, []byte(text+"\n"))
}
// wanted is what magpie writes into the agent's file: the shared text and
// the agent's own additions after it; "" for nothing.
func (l *Library) wanted(agent string) string {
if !slices.Contains(l.Instructions.Agents, agent) {
return ""
}
parts := []string{}
for _, s := range []string{readText(sharedPath()), readText(extraPath(agent))} {
if s != "" {
parts = append(parts, s)
}
}
return strings.Join(parts, "\n\n")
}
// split takes a file apart: what is before magpie's part, magpie's part,
// and what is after it. ok is false when magpie has no part in it.
func split(file string) (before, block, after string, ok bool) {
i := strings.Index(file, blockBegin)
if i < 0 {
return file, "", "", false
}
rest := file[i+len(blockBegin):]
j := strings.Index(rest, blockEnd)
if j < 0 {
return file, "", "", false
}
return file[:i], strings.TrimSpace(rest[:j]), rest[j+len(blockEnd):], true
}
// own is the file without magpie's part: the user's own instructions.
func own(file string) string {
before, _, after, _ := split(file)
return strings.TrimSpace(strings.TrimSpace(before) + "\n\n" + strings.TrimSpace(after))
}
// withBlock is the file with magpie's part set to text, or taken out for "".
// A new part goes after what the user has written.
func withBlock(file, text string) string {
file = strings.ReplaceAll(file, "\r\n", "\n")
before, _, after, ok := split(file)
before, after = strings.TrimRight(before, "\n"), strings.TrimLeft(after, "\n")
block := ""
if text != "" {
block = blockBegin + "\n" + text + "\n" + blockEnd
}
if !ok {
before, after = strings.TrimRight(file, "\n"), ""
}
var parts []string
for _, p := range []string{before, block, strings.TrimRight(after, "\n")} {
if strings.TrimSpace(p) != "" {
parts = append(parts, p)
}
}
if len(parts) == 0 {
return ""
}
return strings.Join(parts, "\n\n") + "\n"
}
func hash(s string) string {
h := sha256.Sum256([]byte(s))
return hex.EncodeToString(h[:8])
}
// syncInstructions writes the agent's part as the library has it. A part
// the user edited in the file is left alone until the library's text for
// that agent changes; then it is replaced, the file kept aside first.
func (l *Library) syncInstructions(t *Target, b *backups, res *Result) {
if t.Instructions == "" {
return
}
id := t.Agent.ID
a := l.applied(id)
want := l.wanted(id)
raw, err := edit.Read(t.Instructions)
if err != nil {
res.fail(id, "instructions", err)
return
}
file := string(raw)
_, have, _, ok := split(file)
if want == "" && !ok {
a.Instructions, a.InstrHash = false, ""
return
}
if ok && have == want {
a.Instructions, a.InstrHash = want != "", hash(want)
return
}
if ok && want != "" && a.InstrHash != "" && hash(have) != a.InstrHash && hash(want) == a.InstrHash {
return // edited in the file since, and the library hasn't changed for it
}
next := withBlock(file, want)
if err := b.keep(id, t.Instructions); err != nil {
res.fail(id, "instructions", err)
return
}
if strings.TrimSpace(next) == "" && len(raw) > 0 && own(file) == "" {
err = os.Remove(t.Instructions)
} else if next != "" {
err = edit.WriteAtomic(t.Instructions, []byte(next))
}
if err != nil {
res.fail(id, "instructions", err)
return
}
a.Instructions, a.InstrHash = want != "", hash(want)
res.changed(id)
}
// AgentInstructions is one agent's instructions file as the page shows it.
type AgentInstructions struct {
Agent string `json:"agent"`
Name string `json:"name"`
Icon string `json:"icon"`
Path string `json:"path"`
On bool `json:"on"`
Extra string `json:"extra"` // what this agent gets besides
Own int `json:"own"` // lines of the user's own in the file
Edited bool `json:"edited,omitempty"` // magpie's part was changed in the file
Override string `json:"override,omitempty"` // a file the agent reads instead
}
// InstructionsView is the Instructions page.
type InstructionsView struct {
Shared string `json:"shared"`
Agents []AgentInstructions `json:"agents"`
}
// ReadInstructions is the shared text and each agent's file.
func ReadInstructions() (*InstructionsView, error) {
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return nil, err
}
v := &InstructionsView{Shared: readText(sharedPath()), Agents: []AgentInstructions{}}
for _, t := range Targets() {
if t.Instructions == "" {
continue
}
id := t.Agent.ID
ai := AgentInstructions{Agent: id, Name: t.Agent.Name, Icon: t.Agent.Icon, Path: t.Instructions,
On: slices.Contains(l.Instructions.Agents, id), Extra: readText(extraPath(id))}
file := readText(t.Instructions)
if o := own(file); o != "" {
ai.Own = strings.Count(o, "\n") + 1
}
if _, have, _, ok := split(file); ok && have != l.wanted(id) {
ai.Edited = true
}
if t.Override != "" && readText(t.Override) != "" {
ai.Override = t.Override
}
v.Agents = append(v.Agents, ai)
}
return v, nil
}
// InstructionsChange is what the page saves: the shared text, which agents
// get it, and what each gets besides. A nil field is left as it is.
type InstructionsChange struct {
Shared *string `json:"shared,omitempty"`
Agents []string `json:"agents,omitempty"`
Extra map[string]*string `json:"extra,omitempty"`
// Rewrite writes magpie's part again into these agents' files, over
// edits made there.
Rewrite []string `json:"rewrite,omitempty"`
}
// SaveInstructions saves the change and writes it into the agents.
func SaveInstructions(c InstructionsChange) (*Result, error) {
return change(func(l *Library) error {
if c.Shared != nil {
if err := writeText(sharedPath(), *c.Shared); err != nil {
return err
}
}
if c.Agents != nil {
l.Instructions.Agents = slices.Sorted(slices.Values(c.Agents))
}
for id, x := range c.Extra {
if x == nil {
continue
}
if err := checkName("agent", id); err != nil {
return err
}
if err := writeText(extraPath(id), *x); err != nil {
return err
}
}
for _, id := range c.Rewrite {
l.applied(id).InstrHash = ""
}
return nil
})
}
// ImportInstructions moves the user's own instructions out of an agent's
// file into the library: they are added to the shared text, taken out of
// the file (which is kept aside first), and the agent gets the shared text
// from then on — so what it reads is what it read before.
func ImportInstructions(id string) (*Result, error) {
t := targetByID(id)
if t == nil || t.Instructions == "" {
return nil, fmt.Errorf("%s has no instructions file magpie knows", id)
}
return change(func(l *Library) error {
raw, err := edit.Read(t.Instructions)
if err != nil {
return err
}
file := strings.ReplaceAll(string(raw), "\r\n", "\n")
mine := own(file)
if mine == "" {
return fmt.Errorf("%s has nothing of its own to import", t.Instructions)
}
shared := readText(sharedPath())
if !strings.Contains(shared, mine) {
shared = strings.TrimSpace(shared + "\n\n" + mine)
}
if err := writeText(sharedPath(), shared); err != nil {
return err
}
b := newBackups()
if err := b.keep(id, t.Instructions); err != nil {
return err
}
_, block, _, ok := split(file)
next := ""
if ok {
next = withBlock("", block)
}
if next == "" {
err = os.Remove(t.Instructions)
} else {
err = edit.WriteAtomic(t.Instructions, []byte(next))
}
if err != nil {
return err
}
l.Instructions.Agents = set(l.Instructions.Agents, id, true)
l.applied(id).InstrHash = "" // what's there now isn't what the library says
return nil
})
}
+154
View File
@@ -0,0 +1,154 @@
// Package library keeps what every agent should know, once: the
// instructions each reads before a conversation, the MCP servers it can
// call and the skills it can load. magpie writes them into each agent's own
// files in that agent's own format, and takes back only what it wrote —
// whatever else is in those files stays as it was.
package library
import (
"encoding/json"
"fmt"
"path/filepath"
"regexp"
"slices"
"sort"
"sync"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/settings"
)
// Library is library.json: what magpie keeps, and which agents get it.
type Library struct {
Instructions Instructions `json:"instructions"`
MCP []*Server `json:"mcp"`
Skills []*Skill `json:"skills"`
// Applied is what magpie wrote into each agent, so that what it takes
// away is only ever its own.
Applied map[string]*Applied `json:"applied,omitempty"`
// Icons are the icons of the servers added from the market, by what
// each runs, for the page to show them by
Icons map[string]string `json:"icons,omitempty"`
}
// Instructions are one shared text, and for each agent whether it gets it
// and what it gets besides (kept in files beside library.json).
type Instructions struct {
Agents []string `json:"agents"` // the agents the shared text is written to
}
// Applied is what magpie last wrote into one agent.
type Applied struct {
Instructions bool `json:"instructions,omitempty"`
InstrHash string `json:"instrHash,omitempty"` // of the part last written
MCP []string `json:"mcp,omitempty"`
Skills []string `json:"skills,omitempty"`
}
var mu sync.Mutex // one change at a time, from the page or the CLI's process
// Dir is where the library's own files are: the instructions and the skills.
func Dir() string { return filepath.Join(settings.Dir(), "library") }
func path() string { return filepath.Join(settings.Dir(), "library.json") }
func load() (*Library, error) {
l := &Library{}
b, err := edit.Read(path())
if err != nil {
return nil, err
}
if len(b) > 0 {
if err := json.Unmarshal(b, l); err != nil {
return nil, fmt.Errorf("%s: %w", path(), err)
}
}
if l.Applied == nil {
l.Applied = map[string]*Applied{}
}
return l, nil
}
func (l *Library) save() error {
sort.Slice(l.MCP, func(i, j int) bool { return l.MCP[i].Name < l.MCP[j].Name })
sort.Slice(l.Skills, func(i, j int) bool { return l.Skills[i].Name < l.Skills[j].Name })
for _, a := range l.Applied {
sort.Strings(a.MCP)
sort.Strings(a.Skills)
}
b, err := json.MarshalIndent(l, "", " ")
if err != nil {
return err
}
return edit.WriteAtomic(path(), append(b, '\n'))
}
func (l *Library) applied(agent string) *Applied {
a := l.Applied[agent]
if a == nil {
a = &Applied{}
l.Applied[agent] = a
}
return a
}
func (l *Library) server(name string) *Server {
for _, s := range l.MCP {
if s.Name == name {
return s
}
}
return nil
}
func (l *Library) skill(name string) *Skill {
for _, s := range l.Skills {
if s.Name == name {
return s
}
}
return nil
}
// A name is what a server or a skill is called in every agent's file, and
// a skill's folder: it has to be a bare key in TOML and a plain file name.
var nameRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`)
func checkName(kind, name string) error {
if !nameRe.MatchString(name) {
return fmt.Errorf("%s name %q: use letters, digits, - and _ only", kind, name)
}
return nil
}
// set turns id on or off in a list of agent ids, which stays sorted.
func set(list []string, id string, on bool) []string {
i := slices.Index(list, id)
switch {
case on && i < 0:
list = append(list, id)
sort.Strings(list)
case !on && i >= 0:
list = slices.Delete(list, i, i+1)
}
return list
}
// change runs f on the library under the lock, saves it, and writes what
// changed into the agents.
func change(f func(l *Library) error) (*Result, error) {
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return nil, err
}
if err := f(l); err != nil {
return nil, err
}
if err := l.save(); err != nil {
return nil, err
}
res := l.sync()
return res, l.save()
}
+502
View File
@@ -0,0 +1,502 @@
package library
import (
"archive/tar"
"bytes"
"compress/gzip"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/tidwall/jsonc"
)
// sandbox is a home with every agent magpie can give the library to, and
// nothing on PATH, so only these are found.
func sandbox(t *testing.T) string {
t.Helper()
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("PATH", "")
for _, k := range []string{"CLAUDE_CONFIG_DIR", "CODEX_HOME", "PI_CODING_AGENT_DIR", "COPILOT_HOME", "APPDATA"} {
t.Setenv(k, "")
}
for _, f := range []string{
".claude/settings.json", ".codex/config.toml", ".gemini/settings.json",
".config/opencode/opencode.json", ".pi/agent/settings.json", ".config/goose/config.yaml",
".cursor/cli-config.json", ".copilot/settings.json", ".config/crush/crush.json",
} {
write(t, filepath.Join(h, f), "")
}
return h
}
func write(t *testing.T, p, s string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(s), 0o644); err != nil {
t.Fatal(err)
}
}
func read(t *testing.T, p string) string {
t.Helper()
b, err := os.ReadFile(p)
if err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
return string(b)
}
// ok fails the test on an error or a problem: ok(t)(SaveServer(…)).
func ok(t *testing.T) func(*Result, error) *Result {
return func(r *Result, err error) *Result {
t.Helper()
if err != nil {
t.Fatal(err)
}
if len(r.Problems) > 0 {
t.Fatalf("problems: %+v", r.Problems)
}
return r
}
}
func ids(ts []*Target) []string {
var out []string
for _, t := range ts {
out = append(out, t.Agent.ID)
}
return out
}
func TestTargets(t *testing.T) {
sandbox(t)
got := ids(Targets())
for _, id := range []string{"claude", "codex", "gemini", "opencode", "pi", "goose", "cursor", "copilot", "crush"} {
if !slices.Contains(got, id) {
t.Errorf("%s not a target: %v", id, got)
}
}
}
// Every format writes a server so that reading it back gives it again, and
// taking it out leaves the file as the user had it.
func TestServerEveryFormat(t *testing.T) {
h := sandbox(t)
write(t, filepath.Join(h, ".claude.json"), `{"numStartups": 3, "mcpServers": {"mine": {"command": "x"}}}`)
write(t, filepath.Join(h, ".codex/config.toml"), "model = \"gpt-5\"\n\n[mcp_servers.mine]\ncommand = \"x\"\n\n[profiles.a]\nmodel = \"o3\"\n")
write(t, filepath.Join(h, ".config/goose/config.yaml"), "GOOSE_MODEL: x\nextensions:\n developer:\n enabled: true\n type: builtin\n name: developer\n")
write(t, filepath.Join(h, ".config/opencode/opencode.json"), "{\n // mine\n \"theme\": \"x\"\n}\n")
before := map[string]string{}
for _, tg := range Targets() {
if tg.MCP != nil {
before[tg.Agent.ID] = read(t, tg.MCP.Path)
}
}
all := ids(Targets())
stdio := Server{Name: "fs", Transport: "stdio", Command: "npx", Args: []string{"-y", "@mcp/fs", "/tmp/a b"},
Env: map[string]string{"TOKEN": "t\"q"}, Agents: all}
ok(t)(SaveServer("", stdio))
remote := Server{Name: "web", Transport: "http", URL: "https://example.com/mcp", Headers: map[string]string{"Authorization": "Bearer x"}, Agents: all}
ok(t)(SaveServer("", remote))
for _, tg := range Targets() {
if tg.MCP == nil {
continue
}
got, err := tg.MCP.read()
if err != nil {
t.Fatalf("%s: %v", tg.Agent.ID, err)
}
for _, want := range []Server{stdio, remote} {
s := got[want.Name]
if s == nil || !s.same(&want) {
t.Errorf("%s: %s read back as %+v\n%s", tg.Agent.ID, want.Name, s, read(t, tg.MCP.Path))
}
}
if got["mine"] == nil && strings.Contains(before[tg.Agent.ID], `"mine"`) {
t.Errorf("%s lost the user's server", tg.Agent.ID)
}
}
if s := read(t, filepath.Join(h, ".codex/config.toml")); !strings.HasPrefix(s, "model = \"gpt-5\"") || !strings.Contains(s, "[profiles.a]") {
t.Errorf("codex config lost the user's:\n%s", s)
}
if s := read(t, filepath.Join(h, ".config/opencode/opencode.json")); !strings.Contains(s, "// mine") {
t.Errorf("opencode lost its comment:\n%s", s)
}
ok(t)(RemoveServer("fs"))
ok(t)(RemoveServer("web"))
for _, tg := range Targets() {
if tg.MCP == nil {
continue
}
got, _ := tg.MCP.read()
if got["fs"] != nil || got["web"] != nil {
t.Errorf("%s still has them:\n%s", tg.Agent.ID, read(t, tg.MCP.Path))
}
}
for _, id := range []string{"codex", "goose"} {
tg := targetByID(id)
if a, b := strings.TrimSpace(before[id]), strings.TrimSpace(read(t, tg.MCP.Path)); a != b {
t.Errorf("%s isn't as it was:\n%s\n---\n%s", id, a, b)
}
}
}
func TestServerKeepsUsersKeys(t *testing.T) {
h := sandbox(t)
ok(t)(SaveServer("", Server{Name: "fs", Transport: "stdio", Command: "npx", Agents: []string{"codex", "copilot", "gemini"}}))
cfg := filepath.Join(h, ".codex/config.toml")
write(t, cfg, strings.Replace(read(t, cfg), "command = ", "startup_timeout_sec = 30\ncommand = ", 1))
cp := filepath.Join(h, ".copilot/mcp-config.json")
write(t, cp, strings.Replace(read(t, cp), `"*"`, `"read"`, 1))
gm := filepath.Join(h, ".gemini/settings.json")
var g map[string]any
json.Unmarshal(jsonc.ToJSON([]byte(read(t, gm))), &g)
g["mcpServers"].(map[string]any)["fs"].(map[string]any)["trust"] = true
b, _ := json.Marshal(g)
write(t, gm, string(b))
ok(t)(SaveServer("fs", Server{Name: "fs", Transport: "stdio", Command: "uvx", Agents: []string{"codex", "copilot", "gemini"}}))
if s := read(t, cfg); !strings.Contains(s, "startup_timeout_sec = 30") || !strings.Contains(s, `"uvx"`) {
t.Errorf("codex:\n%s", s)
}
if s := read(t, cp); !strings.Contains(s, `"read"`) || !strings.Contains(s, `"uvx"`) {
t.Errorf("copilot:\n%s", s)
}
if s := read(t, gm); !strings.Contains(s, `"trust":true`) || !strings.Contains(s, `"uvx"`) {
t.Errorf("gemini:\n%s", s)
}
}
func TestServerRenameAndAgents(t *testing.T) {
h := sandbox(t)
ok(t)(SaveServer("", Server{Name: "a", Transport: "stdio", Command: "x", Agents: []string{"claude", "cursor"}}))
ok(t)(SaveServer("a", Server{Name: "b", Transport: "stdio", Command: "x", Agents: []string{"claude", "cursor"}}))
c := read(t, filepath.Join(h, ".claude.json"))
if strings.Contains(c, `"a"`) || !strings.Contains(c, `"b"`) {
t.Errorf("rename:\n%s", c)
}
ok(t)(ServerAgents("b", []string{"claude"}))
if s := read(t, filepath.Join(h, ".cursor/mcp.json")); strings.Contains(s, `"b"`) {
t.Errorf("cursor still has it:\n%s", s)
}
if _, err := SaveServer("", Server{Name: "b", Transport: "stdio", Command: "y"}); err == nil {
t.Error("a second server by the same name")
}
if _, err := SaveServer("", Server{Name: "../x", Transport: "stdio", Command: "y"}); err == nil {
t.Error("a name that isn't one")
}
}
// Codex and Goose can't reach a server over SSE: they're told so, the
// others get it.
func TestServerSSE(t *testing.T) {
sandbox(t)
r, err := SaveServer("", Server{Name: "s", Transport: "sse", URL: "http://localhost:9/sse", Agents: []string{"claude", "codex", "goose"}})
if err != nil {
t.Fatal(err)
}
var who []string
for _, p := range r.Problems {
who = append(who, p.Agent)
}
slices.Sort(who)
if !slices.Equal(who, []string{"codex", "goose"}) {
t.Errorf("problems: %+v", r.Problems)
}
got, _ := targetByID("claude").MCP.read()
if got["s"] == nil || got["s"].Transport != "sse" {
t.Errorf("claude: %+v", got["s"])
}
}
func TestImportServer(t *testing.T) {
h := sandbox(t)
write(t, filepath.Join(h, ".claude.json"), `{"mcpServers": {"gh": {"type": "stdio", "command": "gh-mcp", "args": ["serve"]}}}`)
write(t, filepath.Join(h, ".cursor/mcp.json"), `{"mcpServers": {"gh": {"command": "gh-mcp", "args": ["serve"]}}}`)
write(t, filepath.Join(h, ".gemini/settings.json"), `{"mcpServers": {"gh": {"command": "other"}}}`)
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
if len(v.FoundServers) != 1 || v.FoundServers[0].Server.Name != "gh" {
t.Fatalf("found: %+v", v.FoundServers)
}
f := v.FoundServers[0]
if !slices.Equal(f.Server.Agents, []string{"claude", "cursor"}) || !slices.Equal(f.Others, []string{"gemini"}) {
t.Errorf("found: %+v", f)
}
ok(t)(ImportServer("gh"))
v, _ = Read(nil)
if len(v.FoundServers) != 0 || len(v.Servers) != 1 {
t.Errorf("after: %+v %+v", v.FoundServers, v.Servers)
}
ok(t)(RemoveServer("gh"))
if s := read(t, filepath.Join(h, ".gemini/settings.json")); !strings.Contains(s, "other") {
t.Errorf("gemini's own went:\n%s", s)
}
if s := read(t, filepath.Join(h, ".cursor/mcp.json")); strings.Contains(s, "gh-mcp") {
t.Errorf("cursor kept it:\n%s", s)
}
}
func TestInstructions(t *testing.T) {
h := sandbox(t)
cl := filepath.Join(h, ".claude/CLAUDE.md")
write(t, cl, "# Mine\n\nBe brief.\n")
shared := "Use tabs."
ok(t)(SaveInstructions(InstructionsChange{Shared: &shared, Agents: []string{"claude", "codex"}}))
s := read(t, cl)
if !strings.HasPrefix(s, "# Mine\n\nBe brief.\n\n"+blockBegin+"\nUse tabs.\n"+blockEnd) {
t.Errorf("claude:\n%s", s)
}
cx := filepath.Join(h, ".codex/AGENTS.md")
if s := read(t, cx); s != blockBegin+"\nUse tabs.\n"+blockEnd+"\n" {
t.Errorf("codex:\n%q", s)
}
extra := "Codex only."
ok(t)(SaveInstructions(InstructionsChange{Extra: map[string]*string{"codex": &extra}}))
if s := read(t, cx); !strings.Contains(s, "Use tabs.\n\nCodex only.") {
t.Errorf("codex extra:\n%s", s)
}
// edited in the file: left alone until the library changes
write(t, cl, strings.Replace(read(t, cl), "Use tabs.", "Use spaces.", 1))
ok(t)(Sync())
if !strings.Contains(read(t, cl), "Use spaces.") {
t.Error("an edit in the file was undone")
}
iv, _ := ReadInstructions()
for _, a := range iv.Agents {
if a.Agent == "claude" && (!a.Edited || a.Own != 3) {
t.Errorf("claude: %+v", a)
}
}
ok(t)(SaveInstructions(InstructionsChange{Rewrite: []string{"claude"}}))
if !strings.Contains(read(t, cl), "Use tabs.") {
t.Error("rewrite didn't")
}
// off: magpie's part goes, the user's stays; a file only magpie wrote goes
ok(t)(SaveInstructions(InstructionsChange{Agents: []string{}}))
if s := read(t, cl); s != "# Mine\n\nBe brief.\n" {
t.Errorf("claude after:\n%q", s)
}
if _, err := os.Stat(cx); !os.IsNotExist(err) {
t.Error("codex's AGENTS.md, only magpie's, is still there")
}
if es, _ := os.ReadDir(BackupDir()); len(es) == 0 {
t.Error("nothing was backed up")
}
}
func TestImportInstructions(t *testing.T) {
h := sandbox(t)
gm := filepath.Join(h, ".gemini/GEMINI.md")
write(t, gm, "Always answer in French.\n")
ok(t)(ImportInstructions("gemini"))
iv, _ := ReadInstructions()
if iv.Shared != "Always answer in French." {
t.Errorf("shared: %q", iv.Shared)
}
if s := read(t, gm); s != blockBegin+"\nAlways answer in French.\n"+blockEnd+"\n" {
t.Errorf("gemini:\n%q", s)
}
}
func skill(t *testing.T, dir, name, desc string) {
write(t, filepath.Join(dir, "SKILL.md"), "---\nname: "+name+"\ndescription: "+desc+"\n---\n\n# "+name+"\n")
write(t, filepath.Join(dir, "scripts/run.sh"), "echo hi\n")
}
func TestSkillsFromFolder(t *testing.T) {
h := sandbox(t)
src := filepath.Join(h, "src/skills")
skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs")
skill(t, filepath.Join(src, "nested/xlsx"), "xlsx", "Sheets")
p, err := ProbeSkills(src)
if err != nil {
t.Fatal(err)
}
var paths []string
for _, c := range p.Candidates {
paths = append(paths, c.Path)
}
slices.Sort(paths)
if !slices.Equal(paths, []string{"nested/xlsx", "pdf"}) {
t.Fatalf("candidates: %+v", p.Candidates)
}
ok(t)(InstallSkills(src, []string{"pdf"}, []string{"claude", "codex", "opencode"}))
for _, d := range []string{".claude/skills/pdf", ".codex/skills/pdf", ".config/opencode/skills/pdf"} {
if _, err := os.Stat(filepath.Join(h, d, "SKILL.md")); err != nil {
t.Errorf("%s: %v", d, err)
}
}
// editing the folder is editing the skill
write(t, filepath.Join(src, "pdf/SKILL.md"), "---\nname: pdf\ndescription: Changed\n---\n")
v, _ := Read(nil)
if len(v.Skills) != 1 || v.Skills[0].Description != "Changed" || v.Skills[0].Kind != "folder" {
t.Errorf("skills: %+v", v.Skills)
}
ok(t)(SkillAgents("pdf", []string{"claude"}))
if _, err := os.Lstat(filepath.Join(h, ".codex/skills/pdf")); !os.IsNotExist(err) {
t.Error("codex still has it")
}
ok(t)(RemoveSkill("pdf"))
if _, err := os.Lstat(filepath.Join(h, ".claude/skills/pdf")); !os.IsNotExist(err) {
t.Error("claude still has it")
}
if _, err := os.Stat(filepath.Join(src, "pdf/SKILL.md")); err != nil {
t.Error("the user's folder went with it")
}
}
func TestSkillConflictAndImport(t *testing.T) {
h := sandbox(t)
skill(t, filepath.Join(h, ".claude/skills/notes"), "notes", "Mine")
ext := filepath.Join(h, "elsewhere/lint")
skill(t, ext, "lint", "Linked")
os.MkdirAll(filepath.Join(h, ".codex/skills"), 0o755)
os.Symlink(ext, filepath.Join(h, ".codex/skills/lint"))
os.MkdirAll(filepath.Join(h, ".gemini/skills"), 0o755)
os.Symlink(ext, filepath.Join(h, ".gemini/skills/lint"))
v, _ := Read(nil)
byName := map[string]FoundSkill{}
for _, f := range v.FoundSkills {
byName[f.Name] = f
}
if f := byName["lint"]; !slices.Equal(f.Agents, []string{"codex", "gemini"}) || f.Link == "" {
t.Errorf("lint: %+v", f)
}
ok(t)(ImportSkill("notes"))
ok(t)(ImportSkill("lint"))
if fi, err := os.Lstat(filepath.Join(h, ".claude/skills/notes")); err != nil || fi.Mode()&os.ModeSymlink == 0 {
t.Errorf("notes isn't linked from the library now: %v", err)
}
if _, err := os.Stat(filepath.Join(ext, "SKILL.md")); err != nil {
t.Error("the folder a link pointed to went")
}
for _, d := range []string{".codex/skills/lint", ".gemini/skills/lint"} {
if !ours(filepath.Join(h, d), "lint") {
t.Errorf("%s isn't the library's", d)
}
}
// the user's own by a name the library has: not overwritten
skill(t, filepath.Join(h, ".cursor/skills/notes"), "notes", "Cursor's")
r, err := SkillAgents("notes", []string{"claude", "cursor"})
if err != nil {
t.Fatal(err)
}
if len(r.Problems) != 1 || r.Problems[0].Agent != "cursor" {
t.Errorf("problems: %+v", r.Problems)
}
if !strings.Contains(read(t, filepath.Join(h, ".cursor/skills/notes/SKILL.md")), "Cursor's") {
t.Error("cursor's own was overwritten")
}
}
func tarball(t *testing.T, files map[string]string) []byte {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
tw := tar.NewWriter(gz)
for name, body := range files {
tw.WriteHeader(&tar.Header{Name: "owner-repo-abc123/" + name, Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg})
tw.Write([]byte(body))
}
tw.WriteHeader(&tar.Header{Name: "owner-repo-abc123/../evil", Mode: 0o644, Typeflag: tar.TypeReg})
tw.Close()
gz.Close()
return buf.Bytes()
}
func TestSkillsFromGitHub(t *testing.T) {
h := sandbox(t)
version := "one"
var asked []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asked = append(asked, r.URL.Path)
if strings.Contains(r.URL.Path, "missing") {
http.NotFound(w, r)
return
}
w.Write(tarball(t, map[string]string{
"README.md": "hi",
"skills/pdf/SKILL.md": "---\nname: pdf\ndescription: PDFs " + version + "\n---\n",
"skills/pdf/forms.md": "forms",
"skills/docx/SKILL.md": "---\nname: docx\ndescription: Word\n---\n",
"template/SKILL.md": "---\nname: template\n---\n",
}))
}))
defer srv.Close()
old := tarballURL
tarballURL = func(repo, ref string) string { return srv.URL + "/" + repo + "/" + ref }
defer func() { tarballURL = old }()
if _, err := ProbeSkills("owner/missing"); err == nil || !strings.Contains(err.Error(), "no repository") {
t.Errorf("missing: %v", err)
}
in := "https://github.com/owner/repo/tree/main/skills"
p, err := ProbeSkills(in)
if err != nil {
t.Fatal(err)
}
if len(p.Candidates) != 2 {
t.Fatalf("candidates: %+v", p.Candidates)
}
if asked[len(asked)-1] != "/owner/repo/main" {
t.Errorf("asked %v", asked)
}
ok(t)(InstallSkills(in, []string{"skills/pdf"}, []string{"claude"}))
if s := read(t, filepath.Join(h, ".claude/skills/pdf/forms.md")); s != "forms" {
t.Errorf("forms: %q", s)
}
if _, err := os.Stat(filepath.Join(filepath.Dir(p.root), "evil")); err == nil {
t.Error("the tarball wrote outside its folder")
}
version = "two"
ok(t)(UpdateSkill("pdf"))
v, _ := Read(nil)
if v.Skills[0].Description != "PDFs two" || v.Skills[0].Source != in+"/pdf" {
t.Errorf("after update: %+v", v.Skills[0])
}
if !ours(filepath.Join(h, ".claude/skills/pdf"), "pdf") {
t.Error("claude's link went in the update")
}
if _, err := InstallSkills(in, []string{"skills/pdf"}, nil); err == nil {
t.Error("installed twice")
}
}
func TestGitHubSource(t *testing.T) {
for in, want := range map[string]Source{
"owner/repo": {Kind: "github", Repo: "owner/repo"},
"https://github.com/owner/repo": {Kind: "github", Repo: "owner/repo"},
"github.com/owner/repo.git": {Kind: "github", Repo: "owner/repo"},
"https://github.com/o/r/tree/v1/skills/pdf": {Kind: "github", Repo: "o/r", Ref: "v1", Path: "skills/pdf"},
"https://github.com/o/r/blob/main/skills/pdf/SKILL.md": {Kind: "github", Repo: "o/r", Ref: "main", Path: "skills/pdf"},
} {
got, ok := githubSource(in)
if !ok || got != want {
t.Errorf("%s: %+v %v", in, got, ok)
}
}
for _, in := range []string{"", "not a repo", "https://gitlab.com/o/r", "/abs/path"} {
if _, ok := githubSource(in); ok {
t.Errorf("%q taken for GitHub", in)
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+282
View File
@@ -0,0 +1,282 @@
package library
import (
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
)
func registryEntry(t *testing.T, s string) *registryServer {
t.Helper()
var r registryServer
if err := json.Unmarshal([]byte(s), &r); err != nil {
t.Fatal(err)
}
return &r
}
func TestFromRegistry(t *testing.T) {
// a remote one: its fixed header kept, the one with a secret asked for
m, ok := fromRegistry(registryEntry(t, `{
"name": "io.github.acme/weather-mcp-server", "description": "Weather",
"repository": {"url": "https://github.com/acme/weather"},
"remotes": [
{"type": "sse", "url": "https://acme.dev/sse"},
{"type": "streamable-http", "url": "https://acme.dev/mcp", "headers": [
{"name": "X-Client", "value": "magpie"},
{"name": "Authorization", "value": "Bearer {token}", "isRequired": true, "isSecret": true}
]}
]}`))
if !ok || m.Name != "weather" || m.Title != "weather" || m.Publisher != "acme" || m.Homepage != "https://github.com/acme/weather" ||
m.Icon != gh("acme") || m.Transport != "http" || m.server.URL != "https://acme.dev/mcp" || m.server.Headers["X-Client"] != "magpie" {
t.Fatalf("remote: %+v %v", m, ok)
}
if len(m.Inputs) != 1 || m.Inputs[0].Key != "Authorization" || m.Inputs[0].format != "Bearer {}" || !m.Inputs[0].Secret {
t.Fatalf("remote inputs: %+v", m.Inputs)
}
// a package: npm before pypi, its secret env asked for, a required
// positional argument asked for, one with a value passed as it is
m, ok = fromRegistry(registryEntry(t, `{
"name": "com.example/files", "icons": [{"src": "http://example.com/i.png"}, {"src": "https://example.com/i.png"}],
"packages": [
{"registryType": "pypi", "identifier": "files-py"},
{"registryType": "npm", "identifier": "@example/files", "transport": {"type": "stdio"},
"environmentVariables": [{"name": "FILES_KEY", "isSecret": true, "isRequired": true}, {"name": "OPTIONAL"}],
"packageArguments": [
{"type": "named", "name": "--mode", "value": "ro"},
{"type": "positional", "valueHint": "directory", "isRequired": true}
]}
]}`))
if !ok || m.Runs != "npx" || m.Publisher != "example.com" || m.Icon != "https://example.com/i.png" ||
!slices.Equal(m.server.Args, []string{"-y", "@example/files", "--mode", "ro"}) {
t.Fatalf("npm: %+v %v", m, ok)
}
if len(m.Inputs) != 2 || m.Inputs[0].Key != "FILES_KEY" || m.Inputs[0].Where != "env" || m.Inputs[1].Where != "arg" || m.Inputs[1].Label != "directory" {
t.Fatalf("npm inputs: %+v", m.Inputs)
}
// docker: its env passed through by name, the image last
m, ok = fromRegistry(registryEntry(t, `{"name": "io.github.o/db", "packages": [
{"registryType": "oci", "identifier": "ghcr.io/o/db:1", "environmentVariables": [{"name": "DB_URL", "isRequired": true}]}]}`))
if !ok || m.Icon != gh("o") || !slices.Equal(m.server.Args, []string{"run", "-i", "--rm", "-e", "DB_URL", "ghcr.io/o/db:1"}) {
t.Fatalf("oci: %+v %v", m, ok)
}
// what magpie can't start: a URL with a variable in it, a package over
// another transport, a named argument it would have to make up
for _, s := range []string{
`{"name": "a/b", "remotes": [{"type": "streamable-http", "url": "https://{tenant}.acme.dev/mcp"}]}`,
`{"name": "a/b", "packages": [{"registryType": "npm", "identifier": "x", "transport": {"type": "streamable-http"}}]}`,
`{"name": "a/b", "packages": [{"registryType": "npm", "identifier": "x", "packageArguments": [{"type": "named", "name": "--db", "isRequired": true}]}]}`,
`{"name": "a/b", "packages": [{"registryType": "nuget", "identifier": "x"}]}`,
} {
if m, ok := fromRegistry(registryEntry(t, s)); ok {
t.Errorf("%s taken: %+v", s, m)
}
}
}
func TestShortNameAndKey(t *testing.T) {
for in, want := range map[string]string{
"io.github.upstash/context7-mcp": "context7",
"io.github.x/mcp-server-postgres": "postgres",
"com.example/Weather_MCP": "weather",
"io.github.x/mcp": "mcp",
"io.github.x/" + strings.Repeat("a", 80): strings.Repeat("a", 64),
} {
if got := shortName(in); got != want {
t.Errorf("shortName(%s) = %s, want %s", in, got, want)
}
}
for want, s := range map[string]Server{
"https://acme.dev/mcp": {Transport: "http", URL: "https://ACME.dev/mcp/"},
"npx @scope/pkg": {Command: "npx", Args: []string{"-y", "@scope/pkg@latest", "--flag"}},
"docker ghcr.io/o/db:1": {Command: "docker", Args: []string{"run", "-i", "--rm", "ghcr.io/o/db:1"}},
"uvx mcp-server-fetch": {Command: "uvx", Args: []string{"mcp-server-fetch"}},
"/usr/local/bin/some-server": {Command: "/usr/local/bin/some-server"},
} {
if got := serverKey(&s); got != want {
t.Errorf("serverKey(%+v) = %s, want %s", s, got, want)
}
}
}
func TestMetaDescription(t *testing.T) {
for page, want := range map[string]string{
`<head><meta name="description" content="Turns &amp; checks PDFs &quot;fast&quot;"/></head>`: `Turns & checks PDFs "fast"`,
`<meta name="description" content=" spaced ">`: "spaced",
`<meta property="og:description" content="not this one">`: "",
``: "",
} {
if got := metaDescription([]byte(page)); got != want {
t.Errorf("%s: %q, want %q", page, got, want)
}
}
}
func TestIcons(t *testing.T) {
github := featured[slices.IndexFunc(featured, func(m MarketServer) bool { return m.ID == "github" })]
l := &Library{Icons: map[string]string{"npx @acme/tool": "https://acme.dev/icon.png"}}
for _, c := range []struct {
s Server
want string
}{
{github.server, github.Icon}, // the featured server it is, under any name
{Server{Name: "mine", Transport: "http", URL: strings.ToUpper(github.server.URL)}, github.Icon},
{Server{Name: "tool", Command: "npx", Args: []string{"-y", "@acme/tool"}}, "https://acme.dev/icon.png"}, // the one it was added from
{Server{Name: "GitHub", Command: "node", Args: []string{"gh.js"}}, github.Icon}, // named after one
{Server{Name: "something", Command: "node", Args: []string{"x.js"}}, ""}, // none made up
} {
if got := serverIcon(l, &c.s); got != c.want {
t.Errorf("serverIcon(%+v) = %q, want %q", c.s, got, c.want)
}
}
for _, c := range []struct {
s Skill
want string
}{
{Skill{Source: &Source{Kind: "github", Repo: "mattpocock/skills", Path: "grill-me"}}, gh("mattpocock")},
{Skill{Source: &Source{Kind: "folder", Dir: "/x"}}, ""},
{Skill{}, ""},
} {
if got := skillIcon(&c.s); got != c.want {
t.Errorf("skillIcon(%+v) = %q, want %q", c.s, got, c.want)
}
}
}
func TestOffered(t *testing.T) {
sandbox(t)
for u, want := range map[string]bool{
featured[0].Icon: true,
gh("someone"): true,
"https://github.com/a/b.png?size=96": false, // not an owner's
"http://github.com/someone.png?size=96": false,
"https://evil.example/tracker.png": false,
"https://github.com/someone.png?size=960": false,
} {
if got := offered(u); got != want {
t.Errorf("offered(%s) = %v", u, got)
}
}
}
// skillsSh is skills.sh as the market reads it: its front page with the
// list in its data, and a page for each skill.
func skillsSh(t *testing.T) *int {
t.Helper()
hits := new(int)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*hits++
switch r.URL.Path {
case "/":
list := `[{"source":"o/r","skillId":"pdf","name":"pdf","installs":9},{"source":"not a repo","skillId":"x","name":"x"},{"source":"o/r","skillId":"","name":"y"}]`
js, _ := json.Marshal(`{"initialSkills":` + list + `}`)
w.Write([]byte(`<html><script>self.__next_f.push([1,` + string(js) + `])</script></html>`))
case "/o/r/pdf":
w.Write([]byte(`<meta name="description" content="Reads &amp; fills PDFs">`))
case "/o/r/plain":
w.Write([]byte(`<html>no description</html>`))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
was := skillsShURL
skillsShURL = srv.URL
t.Cleanup(func() { skillsShURL = was })
abouts.Lock()
abouts.m, abouts.loaded = map[string]string{}, false
abouts.Unlock()
return hits
}
func TestSkillsShPages(t *testing.T) {
sandbox(t)
hits := skillsSh(t)
list, err := fetchPopular()
if err != nil || len(list) != 1 || list[0].Source != "o/r" || list[0].SkillID != "pdf" || list[0].Installs != 9 {
t.Fatalf("popular: %+v %v", list, err)
}
got := SkillsAbout([]string{"o/r/pdf", "o/r/plain", "o/r/missing", "../../etc", "o/r"})
if len(got) != 1 || got["o/r/pdf"] != "Reads & fills PDFs" {
t.Fatalf("about: %v", got)
}
// known ones come from what was kept, on disk too
n := *hits
abouts.Lock()
abouts.m, abouts.loaded = map[string]string{}, false
abouts.Unlock()
if got := SkillsAbout([]string{"o/r/pdf"}); got["o/r/pdf"] != "Reads & fills PDFs" || *hits != n {
t.Fatalf("kept: %v, %d fetches", got, *hits-n)
}
}
func TestInstallFromRegistry(t *testing.T) {
sandbox(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("search") != "acme" {
t.Errorf("searched for %q", r.URL.RawQuery)
}
w.Write([]byte(`{"servers": [
{"server": {"name": "io.github.acme/acme-mcp", "title": "Acme", "icons": [{"src": "https://acme.dev/logo.png"}],
"remotes": [{"type": "streamable-http", "url": "https://acme.dev/mcp",
"headers": [{"name": "Authorization", "value": "Bearer {key}", "isRequired": true, "isSecret": true}]}]}},
{"server": {"name": "io.github.acme/old", "remotes": [{"type": "streamable-http", "url": "https://acme.dev/old"}]},
"_meta": {"io.modelcontextprotocol.registry/official": {"status": "deleted"}}}
]}`))
}))
defer srv.Close()
was := registryURL
registryURL = srv.URL
defer func() { registryURL = was }()
list, err := MarketServers("acme")
if err != nil {
t.Fatal(err)
}
i := slices.IndexFunc(list, func(m MarketServer) bool { return m.ID == "io.github.acme/acme-mcp" })
if i < 0 || slices.ContainsFunc(list, func(m MarketServer) bool { return m.ID == "io.github.acme/old" }) {
t.Fatalf("found: %+v", list)
}
if list[i].Have != "" || !offered("https://acme.dev/logo.png") {
t.Fatalf("before: %+v", list[i])
}
if _, err := InstallServer("io.github.acme/acme-mcp", nil, []string{"claude"}); err == nil || !strings.Contains(err.Error(), "Authorization") {
t.Fatalf("installed without its key: %v", err)
}
ok(t)(InstallServer("io.github.acme/acme-mcp", map[string]string{"Authorization": " k-123 "}, []string{"claude"}))
if _, err := InstallServer("io.github.acme/acme-mcp", map[string]string{"Authorization": "k"}, []string{"claude"}); err == nil {
t.Fatal("installed twice")
}
l, err := loadLocked()
if err != nil || len(l.MCP) != 1 {
t.Fatalf("library: %+v %v", l, err)
}
s := l.MCP[0]
if s.Name != "acme" || s.URL != "https://acme.dev/mcp" || s.Headers["Authorization"] != "Bearer k-123" || !slices.Equal(s.Agents, []string{"claude"}) {
t.Fatalf("server: %+v", s)
}
// its icon stays with it, and stays one magpie will fetch, once the
// market has forgotten it
seenServers.Lock()
clear(seenServers.m)
seenServers.Unlock()
if serverIcon(l, s) != "https://acme.dev/logo.png" || !offered("https://acme.dev/logo.png") {
t.Fatalf("icon: %q", serverIcon(l, s))
}
v, err := Read(nil)
if err != nil || len(v.Servers) != 1 || v.Servers[0].Icon != "https://acme.dev/logo.png" {
t.Fatalf("view: %+v %v", v, err)
}
if list, _ := MarketServers("acme"); !slices.ContainsFunc(list, func(m MarketServer) bool { return m.Have == "acme" }) {
t.Fatalf("not marked as added: %+v", list)
}
}
+603
View File
@@ -0,0 +1,603 @@
package library
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"sort"
"strings"
toml "github.com/pelletier/go-toml/v2"
"github.com/tidwall/jsonc"
"gopkg.in/yaml.v3"
"github.com/yetone/magpie/internal/edit"
)
// Server is one MCP server: a command magpie's agents start, or a URL they
// reach.
type Server struct {
Name string `json:"name"`
// Transport is stdio for a command, http (streamable) or sse for a URL.
Transport string `json:"transport"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
URL string `json:"url,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Agents []string `json:"agents"`
}
// Remote reports whether the server is reached by URL.
func (s *Server) Remote() bool { return s.Transport == "http" || s.Transport == "sse" }
func (s *Server) check() error {
if err := checkName("server", s.Name); err != nil {
return err
}
s.Command, s.URL = strings.TrimSpace(s.Command), strings.TrimSpace(s.URL)
switch s.Transport {
case "stdio":
if s.Command == "" {
return fmt.Errorf("%s: a command is needed", s.Name)
}
s.URL, s.Headers = "", nil
case "http", "sse":
if !strings.HasPrefix(s.URL, "http://") && !strings.HasPrefix(s.URL, "https://") {
return fmt.Errorf("%s: the URL has to start with http:// or https://", s.Name)
}
s.Command, s.Args, s.Env = "", nil, nil
default:
return fmt.Errorf("%s: unknown transport %q", s.Name, s.Transport)
}
for k := range s.Env {
if strings.TrimSpace(k) == "" {
delete(s.Env, k)
}
}
for k := range s.Headers {
if strings.TrimSpace(k) == "" {
delete(s.Headers, k)
}
}
return nil
}
// same reports whether two definitions start the same server; which agents
// have it doesn't matter.
func (s *Server) same(o *Server) bool {
return s.Transport == o.Transport && s.Command == o.Command && slices.Equal(s.Args, o.Args) &&
maps.Equal(s.Env, o.Env) && s.URL == o.URL && maps.Equal(s.Headers, o.Headers)
}
// ---- each agent's own format ----------------------------------------------
type mcpFormat int
const (
fmtClaude mcpFormat = iota
fmtCodex
fmtGemini
fmtOpenCode
fmtCursor
fmtCopilot
fmtCrush
fmtGoose
)
// mcpFile is the file an agent keeps its user-wide MCP servers in.
type mcpFile struct {
Path string
Format mcpFormat
}
// key is the object the servers are kept under.
func (f *mcpFile) key() string {
switch f.Format {
case fmtCodex:
return "mcp_servers"
case fmtOpenCode, fmtCrush:
return "mcp"
case fmtGoose:
return "extensions"
}
return "mcpServers"
}
// supports says why the agent can't reach a server, or nil when it can.
func (f *mcpFile) supports(s *Server) error {
if s.Transport == "sse" && (f.Format == fmtCodex || f.Format == fmtGoose) {
return errNoSSE
}
return nil
}
// errNoSSE is what the page says of an agent that can't reach a server
// over SSE (Codex, Goose).
var errNoSSE = errors.New("no-sse")
// ordered is a JSON object that keeps its keys in the order given, so an
// entry reads the way the agent's own would.
type ordered []kv
type kv struct {
k string
v any
}
func (o ordered) MarshalJSON() ([]byte, error) {
var b bytes.Buffer
b.WriteByte('{')
for i, e := range o {
if i > 0 {
b.WriteByte(',')
}
k, _ := json.Marshal(e.k)
v, err := json.Marshal(e.v)
if err != nil {
return nil, err
}
b.Write(k)
b.WriteByte(':')
b.Write(v)
}
b.WriteByte('}')
return b.Bytes(), nil
}
func strs(m map[string]string) map[string]string {
if m == nil {
return map[string]string{}
}
return m
}
func list(a []string) []string {
if a == nil {
return []string{}
}
return a
}
// encode is the server as this agent writes it.
func (f *mcpFile) encode(s *Server) ordered {
var o ordered
add := func(k string, v any) { o = append(o, kv{k, v}) }
optional := func(k string, m map[string]string) {
if len(m) > 0 {
add(k, m)
}
}
switch f.Format {
case fmtClaude, fmtCrush:
add("type", s.Transport)
if s.Remote() {
add("url", s.URL)
optional("headers", s.Headers)
} else {
add("command", s.Command)
add("args", list(s.Args))
add("env", strs(s.Env))
}
case fmtGemini:
switch s.Transport {
case "http":
add("httpUrl", s.URL)
optional("headers", s.Headers)
case "sse":
add("url", s.URL)
optional("headers", s.Headers)
default:
add("command", s.Command)
add("args", list(s.Args))
optional("env", s.Env)
}
case fmtOpenCode:
if s.Remote() {
add("type", "remote")
add("url", s.URL)
optional("headers", s.Headers)
} else {
add("type", "local")
add("command", append([]string{s.Command}, s.Args...))
optional("environment", s.Env)
}
add("enabled", true)
case fmtCursor:
if s.Remote() {
add("url", s.URL)
optional("headers", s.Headers)
} else {
add("command", s.Command)
add("args", list(s.Args))
optional("env", s.Env)
}
case fmtCopilot:
if s.Remote() {
add("type", s.Transport)
add("url", s.URL)
optional("headers", s.Headers)
} else {
add("type", "local")
add("command", s.Command)
add("args", list(s.Args))
optional("env", s.Env)
}
add("tools", []string{"*"})
case fmtGoose:
add("enabled", true)
add("name", s.Name)
switch s.Transport {
case "http":
add("type", "streamable_http")
add("uri", s.URL)
optional("headers", s.Headers)
case "sse":
add("type", "sse")
add("uri", s.URL)
default:
add("type", "stdio")
add("cmd", s.Command)
add("args", list(s.Args))
optional("envs", s.Env)
}
add("timeout", 300)
case fmtCodex:
if s.Remote() {
add("url", s.URL)
optional("http_headers", s.Headers)
} else {
add("command", s.Command)
add("args", list(s.Args))
optional("env", s.Env)
}
}
return o
}
func str(m map[string]any, k string) string { s, _ := m[k].(string); return s }
func strList(v any) []string {
a, _ := v.([]any)
var out []string
for _, x := range a {
out = append(out, fmt.Sprint(x))
}
return out
}
func strMap(v any) map[string]string {
m, _ := v.(map[string]any)
if len(m) == 0 {
return nil
}
out := map[string]string{}
for k, x := range m {
out[k] = fmt.Sprint(x)
}
return out
}
// decode reads one of the agent's entries; false for one magpie can't read
// as a server (a Goose builtin, say).
func (f *mcpFile) decode(name string, m map[string]any) (*Server, bool) {
s := &Server{Name: name}
remote := func(transport, url string, headers any) {
s.Transport, s.URL, s.Headers = transport, url, strMap(headers)
}
local := func(cmd string, args any, env any) {
s.Transport, s.Command, s.Args, s.Env = "stdio", cmd, strList(args), strMap(env)
}
switch f.Format {
case fmtOpenCode:
if str(m, "type") == "remote" {
remote("http", str(m, "url"), m["headers"])
} else if c := strList(m["command"]); len(c) > 0 {
local(c[0], nil, m["environment"])
s.Args = c[1:]
}
case fmtGoose:
switch str(m, "type") {
case "stdio":
local(str(m, "cmd"), m["args"], m["envs"])
case "streamable_http":
remote("http", str(m, "uri"), m["headers"])
case "sse":
remote("sse", str(m, "uri"), m["headers"])
}
case fmtCodex:
if u := str(m, "url"); u != "" {
remote("http", u, m["http_headers"])
} else {
local(str(m, "command"), m["args"], m["env"])
}
case fmtGemini:
if u := str(m, "httpUrl"); u != "" {
remote("http", u, m["headers"])
} else if u := str(m, "url"); u != "" {
t := "sse"
if str(m, "type") == "http" {
t = "http"
}
remote(t, u, m["headers"])
} else {
local(str(m, "command"), m["args"], m["env"])
}
default: // Claude Code, Cursor, Copilot, Crush
t := str(m, "type")
if u := str(m, "url"); u != "" {
if t != "sse" {
t = "http"
}
remote(t, u, m["headers"])
} else {
local(str(m, "command"), m["args"], m["env"])
}
}
if len(s.Args) == 0 {
s.Args = nil
}
if s.Transport == "" || (s.Transport == "stdio" && s.Command == "") || (s.Remote() && s.URL == "") {
return nil, false
}
return s, true
}
// entries is every entry under the servers' key, as the file has it.
func (f *mcpFile) entries() (map[string]map[string]any, error) {
out := map[string]map[string]any{}
raw, err := edit.Read(f.Path)
if err != nil || len(bytes.TrimSpace(raw)) == 0 {
return out, err
}
var doc map[string]any
switch f.Format {
case fmtCodex:
err = toml.Unmarshal(raw, &doc)
case fmtGoose:
err = yaml.Unmarshal(raw, &doc)
default:
err = json.Unmarshal(jsonc.ToJSON(raw), &doc)
}
if err != nil {
return nil, fmt.Errorf("%s: %w", f.Path, err)
}
all, _ := doc[f.key()].(map[string]any)
for name, v := range all {
if m, ok := v.(map[string]any); ok {
out[name] = m
}
}
return out, nil
}
// read is every server in the file, magpie's or not, by name.
func (f *mcpFile) read() (map[string]*Server, error) {
es, err := f.entries()
out := map[string]*Server{}
for name, m := range es {
if s, ok := f.decode(name, m); ok {
out[name] = s
}
}
return out, err
}
// owned are the keys of an entry that say what the server is: magpie
// writes them. An entry's other keys — a timeout, the tools it may call,
// a note — are the user's, and kept when magpie writes the server again.
var owned = map[mcpFormat][]string{
fmtClaude: {"type", "url", "headers", "command", "args", "env"},
fmtCrush: {"type", "url", "headers", "command", "args", "env"},
fmtGemini: {"type", "httpUrl", "url", "headers", "command", "args", "env"},
fmtOpenCode: {"type", "url", "headers", "command", "environment", "enabled"},
fmtCursor: {"type", "url", "headers", "command", "args", "env"},
fmtCopilot: {"type", "url", "headers", "command", "args", "env"},
fmtGoose: {"enabled", "name", "type", "uri", "headers", "cmd", "args", "envs"},
fmtCodex: {"url", "http_headers", "command", "args", "env"},
}
// merged is the entry magpie writes, with what the user added to the old
// one kept; a default magpie gives (Copilot's tools, Goose's timeout)
// yields to the user's.
func (f *mcpFile) merged(s *Server, old map[string]any) ordered {
o := f.encode(s)
mine := owned[f.Format]
for i, e := range o {
if v, ok := old[e.k]; ok && !slices.Contains(mine, e.k) {
o[i].v = v
}
}
keys := slices.Sorted(maps.Keys(old))
for _, k := range keys {
if slices.Contains(mine, k) || slices.ContainsFunc(o, func(e kv) bool { return e.k == k }) {
continue
}
o = append(o, kv{k, old[k]})
}
return o
}
// put writes the server into the file, in place of one by its name.
func (f *mcpFile) put(s *Server, old map[string]any) error {
o := f.merged(s, old)
switch f.Format {
case fmtCodex:
return putCodex(f.Path, s.Name, o)
case fmtGoose:
m := map[string]any{}
for _, e := range o {
m[e.k] = e.v
}
return edit.SetYAML(f.Path, edit.KV{Path: "extensions." + s.Name, Value: m})
}
return edit.SetJSON(f.Path, edit.KV{Path: f.key() + "." + s.Name, Value: o})
}
// del takes the server by that name out of the file.
func (f *mcpFile) del(name string) error {
switch f.Format {
case fmtCodex:
return delCodex(f.Path, name, true)
case fmtGoose:
return edit.DelYAML(f.Path, "extensions."+name)
}
return edit.DelJSON(f.Path, f.key()+"."+name)
}
// ---- Codex's TOML ---------------------------------------------------------
// delCodex takes out the server's table and the tables under it ([…env]),
// or only those under it, which putCodex writes inline instead.
func delCodex(path, name string, self bool) error {
table := "mcp_servers." + name
for _, t := range edit.TOMLTables(path) {
if strings.HasPrefix(t, table+".") {
if err := edit.DelTOMLTable(path, t); err != nil {
return err
}
}
}
if !self {
return nil
}
return edit.DelTOMLTable(path, table)
}
func putCodex(path, name string, o ordered) error {
if err := delCodex(path, name, false); err != nil {
return err
}
var kvs []edit.KV
for _, e := range o {
kvs = append(kvs, edit.KV{Path: tomlKey(e.k), Value: edit.Raw(tomlValue(e.v))})
}
return edit.SetTOMLTable(path, "mcp_servers."+name, kvs...)
}
func tomlString(s string) string {
var b strings.Builder
b.WriteByte('"')
for _, r := range s {
switch r {
case '"':
b.WriteString(`\"`)
case '\\':
b.WriteString(`\\`)
case '\n':
b.WriteString(`\n`)
case '\t':
b.WriteString(`\t`)
case '\r':
b.WriteString(`\r`)
default:
if r < 0x20 || r == 0x7f {
fmt.Fprintf(&b, `\u%04X`, r)
} else {
b.WriteRune(r)
}
}
}
b.WriteByte('"')
return b.String()
}
func tomlKey(k string) string {
if k == "" {
return `""`
}
for _, r := range k {
if !(r == '_' || r == '-' || r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z') {
return tomlString(k)
}
}
return k
}
func tomlValue(v any) string {
switch x := v.(type) {
case string:
return tomlString(x)
case bool, int, int64, float64:
return fmt.Sprint(x)
case []string:
parts := make([]string, len(x))
for i, s := range x {
parts[i] = tomlString(s)
}
return "[" + strings.Join(parts, ", ") + "]"
case []any:
parts := make([]string, len(x))
for i, s := range x {
parts[i] = tomlValue(s)
}
return "[" + strings.Join(parts, ", ") + "]"
case map[string]string:
m := map[string]any{}
for k, s := range x {
m[k] = s
}
return tomlValue(m)
case map[string]any:
keys := slices.Sorted(maps.Keys(x))
parts := make([]string, len(keys))
for i, k := range keys {
parts[i] = tomlKey(k) + " = " + tomlValue(x[k])
}
if len(parts) == 0 {
return "{}"
}
return "{ " + strings.Join(parts, ", ") + " }"
}
return tomlString(fmt.Sprint(v))
}
// ---- found in agents ------------------------------------------------------
// Found is a server an agent has that the library doesn't: the agents
// that have it as it is, and those that have another by that name.
type Found struct {
Server *Server `json:"server"`
Others []string `json:"others,omitempty"`
Icon string `json:"icon,omitempty"`
}
func foundServers(l *Library) []Found {
byName := map[string]*Found{}
var names []string
for _, t := range Targets() {
if t.MCP == nil {
continue
}
have, err := t.MCP.read()
if err != nil {
continue
}
mine := l.applied(t.Agent.ID).MCP
for name, s := range have {
if slices.Contains(mine, name) || l.server(name) != nil || !nameRe.MatchString(name) {
continue
}
f := byName[name]
switch {
case f == nil:
s.Agents = []string{t.Agent.ID}
byName[name] = &Found{Server: s}
names = append(names, name)
case f.Server.same(s):
f.Server.Agents = append(f.Server.Agents, t.Agent.ID)
default:
f.Others = append(f.Others, t.Agent.ID)
}
}
}
sort.Strings(names)
out := []Found{}
for _, n := range names {
out = append(out, *byName[n])
}
return out
}
+781
View File
@@ -0,0 +1,781 @@
package library
import (
"archive/tar"
"compress/gzip"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"sort"
"strings"
"sync"
"time"
"gopkg.in/yaml.v3"
)
// Skill is a folder with a SKILL.md, kept in the library and linked into
// the agents that get it.
type Skill struct {
Name string `json:"name"`
Source *Source `json:"source,omitempty"`
Agents []string `json:"agents"`
}
// Source is where a skill came from: a GitHub repository it can be updated
// from, or a folder on this machine the library links to, so that editing
// the folder is editing the skill.
type Source struct {
Kind string `json:"kind"` // github | folder
Repo string `json:"repo,omitempty"`
Ref string `json:"ref,omitempty"`
Path string `json:"path,omitempty"` // in the repository
Dir string `json:"dir,omitempty"` // the folder, for kind folder
}
func (s *Source) String() string {
if s == nil {
return ""
}
if s.Kind == "folder" {
return s.Dir
}
u := "https://github.com/" + s.Repo
if s.Ref != "" || s.Path != "" {
ref := s.Ref
if ref == "" {
ref = "HEAD"
}
u += "/tree/" + ref
if s.Path != "" {
u += "/" + s.Path
}
}
return u
}
func skillsDir() string { return filepath.Join(Dir(), "skills") }
func skillDir(name string) string { return filepath.Join(skillsDir(), name) }
// meta is what a SKILL.md says of itself in its front matter.
type meta struct {
Name string `yaml:"name" json:"name"`
Description string `yaml:"description" json:"description"`
}
func readMeta(dir string) (meta, bool) {
b, err := os.ReadFile(filepath.Join(dir, "SKILL.md"))
if err != nil {
return meta{}, false
}
return parseMeta(b), true
}
// parseMeta reads a SKILL.md's front matter.
func parseMeta(b []byte) meta {
var m meta
s := strings.ReplaceAll(string(b), "\r\n", "\n")
if rest, ok := strings.CutPrefix(s, "---\n"); ok {
if front, _, ok := strings.Cut(rest, "\n---"); ok {
_ = yaml.Unmarshal([]byte(front), &m)
}
}
m.Name, m.Description = strings.TrimSpace(m.Name), strings.Join(strings.Fields(m.Description), " ")
return m
}
var unsafe = regexp.MustCompile(`[^A-Za-z0-9_-]+`)
// nameFor is the name a skill found at dir goes by: what its SKILL.md
// says, else its folder's, made fit for a file name.
func nameFor(dir string, m meta) string {
n := m.Name
if n == "" {
n = filepath.Base(dir)
}
n = strings.Trim(unsafe.ReplaceAllString(n, "-"), "-_")
if len(n) > 64 {
n = n[:64]
}
return n
}
// ---- linking into agents --------------------------------------------------
// marker is left in a copy magpie makes where it can't link (Windows
// without the right to), to know the copy for its own.
const marker = ".magpie-library"
// ours reports whether the entry at p is magpie's link (or copy) of the
// library's skill by that name.
func ours(p, name string) bool {
fi, err := os.Lstat(p)
if err != nil {
return false
}
if fi.Mode()&fs.ModeSymlink != 0 {
to, err := os.Readlink(p)
return err == nil && filepath.Clean(to) == filepath.Clean(skillDir(name))
}
if fi.IsDir() {
_, err := os.Stat(filepath.Join(p, marker))
return err == nil
}
return false
}
func link(p, name string) error {
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
err := os.Symlink(skillDir(name), p)
if err == nil || runtime.GOOS != "windows" {
return err
}
if err := copyDir(skillDir(name), p); err != nil {
os.RemoveAll(p)
return err
}
return os.WriteFile(filepath.Join(p, marker), []byte("copied from "+skillDir(name)+"\n"), 0o644)
}
func unlink(p string) error {
fi, err := os.Lstat(p)
if err != nil {
return nil
}
if fi.Mode()&fs.ModeSymlink != 0 {
return os.Remove(p)
}
return os.RemoveAll(p)
}
// realDir is where a folder really is, links followed.
func realDir(p string) string {
if r, err := filepath.EvalSymlinks(p); err == nil {
return r
}
return filepath.Clean(p)
}
func (l *Library) syncSkills(t *Target, res *Result, all []*Target) {
if t.Skills == "" {
return
}
id := t.Agent.ID
a := l.applied(id)
// another agent may read the very same folder (one linked to the other):
// what that agent is to have stays
sharers := []string{}
for _, o := range all {
if o != t && o.Skills != "" && realDir(o.Skills) == realDir(t.Skills) {
sharers = append(sharers, o.Agent.ID)
}
}
wanted := func(s *Skill) bool {
if s == nil {
return false
}
return slices.Contains(s.Agents, id) || slices.ContainsFunc(sharers, func(o string) bool { return slices.Contains(s.Agents, o) })
}
var mine []string
for _, name := range a.Skills {
s := l.skill(name)
p := filepath.Join(t.Skills, name)
if wanted(s) || !ours(p, name) {
continue
}
if err := unlink(p); err != nil {
res.fail(id, "skill:"+name, err)
mine = append(mine, name)
continue
}
res.changed(id)
}
for _, s := range l.Skills {
if !slices.Contains(s.Agents, id) {
continue
}
p := filepath.Join(t.Skills, s.Name)
if ours(p, s.Name) {
mine = append(mine, s.Name)
continue
}
if _, err := os.Lstat(p); err == nil {
res.fail(id, "skill:"+s.Name, fmt.Errorf("%s already has a skill of its own called %s", t.Agent.Name, s.Name))
continue
}
if err := link(p, s.Name); err != nil {
res.fail(id, "skill:"+s.Name, err)
continue
}
mine = append(mine, s.Name)
res.changed(id)
}
a.Skills = mine
}
// ---- finding skills to install --------------------------------------------
// Candidate is a skill found where the user pointed: in a repository, or
// in a folder.
type Candidate struct {
Path string `json:"path"` // in the repository or the folder; "" for its root
Name string `json:"name"`
Description string `json:"description"`
Have bool `json:"have"` // the library has a skill by that name
}
// Probe is what was found at a source.
type Probe struct {
Source string `json:"source"`
Kind string `json:"kind"`
Candidates []Candidate `json:"candidates"`
root string // the folder the candidates' paths are in
src Source
}
var probes = struct {
sync.Mutex
m map[string]*probeEntry
}{m: map[string]*probeEntry{}}
type probeEntry struct {
p *Probe
tmp string
at time.Time
}
// githubSource reads a repository out of what the user typed: owner/repo,
// or a github.com URL, to a folder in it.
func githubSource(s string) (Source, bool) {
s = strings.TrimSpace(s)
s = strings.TrimSuffix(s, "/")
if !strings.Contains(s, "://") && strings.HasPrefix(s, "github.com/") {
s = "https://" + s
}
var parts []string
if u, err := url.Parse(s); err == nil && u.Scheme != "" {
if u.Host != "github.com" && u.Host != "www.github.com" {
return Source{}, false
}
parts = strings.Split(strings.Trim(u.Path, "/"), "/")
} else if regexp.MustCompile(`^[\w.-]+/[\w.-]+$`).MatchString(s) {
parts = strings.Split(s, "/")
} else {
return Source{}, false
}
if len(parts) < 2 {
return Source{}, false
}
src := Source{Kind: "github", Repo: parts[0] + "/" + strings.TrimSuffix(parts[1], ".git")}
if len(parts) >= 4 && (parts[2] == "tree" || parts[2] == "blob") {
src.Ref = parts[3]
src.Path = strings.Join(parts[4:], "/")
src.Path = strings.TrimSuffix(strings.TrimSuffix(src.Path, "SKILL.md"), "/")
}
return src, true
}
func expand(p string) string {
if rest, ok := strings.CutPrefix(p, "~"); ok && (rest == "" || rest[0] == '/' || rest[0] == '\\') {
return filepath.Join(home(), rest)
}
return p
}
// tarballURL is where GitHub hands out a repository's files; a variable
// for tests.
var tarballURL = func(repo, ref string) string {
u := "https://api.github.com/repos/" + repo + "/tarball"
if ref != "" {
u += "/" + url.PathEscape(ref)
}
return u
}
// fetch downloads the repository into a new folder and gives it back.
func fetch(src Source) (string, error) {
req, _ := http.NewRequest("GET", tarballURL(src.Repo, src.Ref), nil)
req.Header.Set("User-Agent", "magpie")
req.Header.Set("Accept", "application/vnd.github+json")
c := &http.Client{Timeout: 2 * time.Minute}
resp, err := c.Do(req)
if err != nil {
return "", fmt.Errorf("couldn't reach GitHub: %w", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode == 404:
if src.Ref != "" {
return "", fmt.Errorf("GitHub has no %s at %s (a private repository can't be installed from)", src.Repo, src.Ref)
}
return "", fmt.Errorf("GitHub has no repository %s (a private one can't be installed from)", src.Repo)
case resp.StatusCode == 403 || resp.StatusCode == 429:
return "", fmt.Errorf("GitHub is limiting requests from here; try again in a while")
case resp.StatusCode != 200:
return "", fmt.Errorf("GitHub answered %s", resp.Status)
}
tmp, err := os.MkdirTemp("", "magpie-skill-")
if err != nil {
return "", err
}
if err := untar(resp.Body, tmp); err != nil {
os.RemoveAll(tmp)
return "", err
}
return tmp, nil
}
// untar unpacks a GitHub tarball, whose one top folder is dropped.
func untar(r io.Reader, dst string) error {
gz, err := gzip.NewReader(r)
if err != nil {
return err
}
tr := tar.NewReader(gz)
total := int64(0)
for {
h, err := tr.Next()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
_, rel, _ := strings.Cut(h.Name, "/")
if rel == "" {
continue
}
p := filepath.Join(dst, filepath.FromSlash(rel))
if !strings.HasPrefix(p, dst+string(filepath.Separator)) {
continue // never outside
}
switch h.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(p, 0o755); err != nil {
return err
}
case tar.TypeReg:
if total += h.Size; total > 200<<20 {
return fmt.Errorf("the repository is too big to install skills from (over 200 MB)")
}
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
mode := os.FileMode(0o644)
if h.Mode&0o111 != 0 {
mode = 0o755
}
f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
if err != nil {
return err
}
_, err = io.Copy(f, tr)
f.Close()
if err != nil {
return err
}
}
}
}
// candidates are the skills under root/sub: a folder with a SKILL.md,
// looked for a few folders deep, and not inside another skill.
func candidates(root, sub string) []Candidate {
base := filepath.Join(root, filepath.FromSlash(sub))
var out []Candidate
var walk func(dir string, depth int)
walk = func(dir string, depth int) {
if m, ok := readMeta(dir); ok {
rel, _ := filepath.Rel(root, dir)
if rel == "." {
rel = ""
}
out = append(out, Candidate{Path: filepath.ToSlash(rel), Name: nameFor(dir, m), Description: m.Description})
return
}
if depth == 0 {
return
}
es, _ := os.ReadDir(dir)
for _, e := range es {
n := e.Name()
if strings.HasPrefix(n, ".") || n == "node_modules" {
continue
}
p := filepath.Join(dir, n)
if fi, err := os.Stat(p); err == nil && fi.IsDir() {
walk(p, depth-1)
}
}
}
walk(base, 4)
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// ProbeSkills looks for skills at what the user typed: a GitHub repository
// (or a folder in one), or a folder on this machine.
func ProbeSkills(input string) (*Probe, error) {
input = strings.TrimSpace(input)
if input == "" {
return nil, fmt.Errorf("paste a GitHub link or a folder's path")
}
probes.Lock()
for k, e := range probes.m {
if time.Since(e.at) > 15*time.Minute {
os.RemoveAll(e.tmp)
delete(probes.m, k)
}
}
probes.Unlock()
p := &Probe{Source: input}
if dir := expand(input); filepath.IsAbs(dir) {
fi, err := os.Stat(dir)
if err != nil || !fi.IsDir() {
return nil, fmt.Errorf("%s isn't a folder", input)
}
p.Kind, p.root, p.src = "folder", dir, Source{Kind: "folder", Dir: dir}
p.Candidates = candidates(dir, "")
} else if src, ok := githubSource(input); ok {
tmp, err := fetch(src)
if err != nil {
return nil, err
}
p.Kind, p.root, p.src = "github", tmp, src
if _, err := os.Stat(filepath.Join(tmp, filepath.FromSlash(src.Path))); src.Path != "" && err != nil {
os.RemoveAll(tmp)
return nil, fmt.Errorf("%s has no folder %s", src.Repo, src.Path)
}
p.Candidates = candidates(tmp, src.Path)
probes.Lock()
if old := probes.m[input]; old != nil {
os.RemoveAll(old.tmp)
}
probes.m[input] = &probeEntry{p: p, tmp: tmp, at: time.Now()}
probes.Unlock()
} else {
return nil, fmt.Errorf("that's neither a GitHub repository nor a folder's full path")
}
if p.Candidates == nil {
p.Candidates = []Candidate{}
}
if l, err := load(); err == nil {
for i, c := range p.Candidates {
p.Candidates[i].Have = l.skill(c.Name) != nil
}
}
return p, nil
}
func cachedProbe(input string) (*Probe, error) {
probes.Lock()
e := probes.m[strings.TrimSpace(input)]
probes.Unlock()
if e != nil {
if _, err := os.Stat(e.tmp); err == nil {
return e.p, nil
}
}
return ProbeSkills(input)
}
// InstallSkills adds the skills at those paths of the source to the library
// and gives them to the agents named.
func InstallSkills(input string, paths, agents []string) (*Result, error) {
p, err := cachedProbe(input)
if err != nil {
return nil, err
}
return change(func(l *Library) error {
for _, path := range paths {
i := slices.IndexFunc(p.Candidates, func(c Candidate) bool { return c.Path == path })
if i < 0 {
return fmt.Errorf("no skill at %q", path)
}
c := p.Candidates[i]
if err := checkName("skill", c.Name); err != nil {
return err
}
if l.skill(c.Name) != nil {
return fmt.Errorf("the library already has a skill called %s", c.Name)
}
from := filepath.Join(p.root, filepath.FromSlash(c.Path))
src := p.src
if err := os.MkdirAll(skillsDir(), 0o755); err != nil {
return err
}
if src.Kind == "folder" {
src.Dir = from
if err := os.Symlink(from, skillDir(c.Name)); err != nil {
if err := copyDir(from, skillDir(c.Name)); err != nil {
return err
}
}
} else {
src.Path = c.Path
if err := copyDir(from, skillDir(c.Name)); err != nil {
os.RemoveAll(skillDir(c.Name))
return err
}
}
l.Skills = append(l.Skills, &Skill{Name: c.Name, Source: &src, Agents: slices.Clone(agents)})
}
return nil
})
}
// UpdateSkill fetches a skill from GitHub again, in place: the agents'
// links go on pointing at it.
func UpdateSkill(name string) (*Result, error) {
mu.Lock()
l, err := load()
mu.Unlock()
if err != nil {
return nil, err
}
s := l.skill(name)
if s == nil {
return nil, fmt.Errorf("no skill called %s", name)
}
if s.Source == nil || s.Source.Kind != "github" {
return nil, fmt.Errorf("%s isn't from GitHub; it's kept as it is", name)
}
tmp, err := fetch(*s.Source)
if err != nil {
return nil, err
}
defer os.RemoveAll(tmp)
from := filepath.Join(tmp, filepath.FromSlash(s.Source.Path))
if _, ok := readMeta(from); !ok {
return nil, fmt.Errorf("%s has no SKILL.md at %s any more", s.Source.Repo, s.Source.Path)
}
return change(func(l *Library) error {
next, old := skillDir("."+name+".next"), skillDir("."+name+".old")
os.RemoveAll(next)
os.RemoveAll(old)
if err := copyDir(from, next); err != nil {
os.RemoveAll(next)
return err
}
if err := os.Rename(skillDir(name), old); err != nil {
os.RemoveAll(next)
return err
}
if err := os.Rename(next, skillDir(name)); err != nil {
os.Rename(old, skillDir(name))
return err
}
return os.RemoveAll(old)
})
}
// SkillAgents sets which agents get a skill.
func SkillAgents(name string, agents []string) (*Result, error) {
return change(func(l *Library) error {
s := l.skill(name)
if s == nil {
return fmt.Errorf("no skill called %s", name)
}
s.Agents = slices.Sorted(slices.Values(agents))
return nil
})
}
// RemoveSkill takes a skill out of the library and every agent; its folder
// is kept aside with the backups, never just deleted.
func RemoveSkill(name string) (*Result, error) {
return change(func(l *Library) error {
i := slices.IndexFunc(l.Skills, func(s *Skill) bool { return s.Name == name })
if i < 0 {
return fmt.Errorf("no skill called %s", name)
}
l.Skills = slices.Delete(l.Skills, i, i+1)
p := skillDir(name)
if fi, err := os.Lstat(p); err == nil && fi.Mode()&fs.ModeSymlink != 0 {
return os.Remove(p) // a folder of the user's: only the link goes
}
aside := filepath.Join(BackupDir(), time.Now().Format("2006-01-02_15-04-05.000"), "skills", name)
if err := os.MkdirAll(filepath.Dir(aside), 0o700); err != nil {
return err
}
return move(p, aside)
})
}
// ---- skills the agents have of their own ----------------------------------
// FoundSkill is a skill an agent has that the library doesn't.
type FoundSkill struct {
Name string `json:"name"`
Description string `json:"description"`
Agents []string `json:"agents"` // the agents that have this very folder
Others []string `json:"others,omitempty"` // agents with another by that name
Link string `json:"link,omitempty"` // where it really is, when it's a link
real string
at string // the entry in the first agent's folder
}
func foundSkills(l *Library) []FoundSkill {
var out []*FoundSkill
byName := map[string]*FoundSkill{}
for _, t := range Targets() {
if t.Skills == "" {
continue
}
es, _ := os.ReadDir(t.Skills)
for _, e := range es {
name := e.Name()
p := filepath.Join(t.Skills, name)
if strings.HasPrefix(name, ".") || ours(p, name) || l.skill(name) != nil || !nameRe.MatchString(name) {
continue
}
m, ok := readMeta(p)
if !ok {
continue
}
r := realDir(p)
f := byName[name]
switch {
case f == nil:
f = &FoundSkill{Name: name, Description: m.Description, Agents: []string{t.Agent.ID}, real: r, at: p}
if fi, err := os.Lstat(p); err == nil && fi.Mode()&fs.ModeSymlink != 0 {
f.Link = r
}
byName[name] = f
out = append(out, f)
case f.real == r:
if !slices.Contains(f.Agents, t.Agent.ID) {
f.Agents = append(f.Agents, t.Agent.ID)
}
default:
f.Others = append(f.Others, t.Agent.ID)
}
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
res := []FoundSkill{}
for _, f := range out {
res = append(res, *f)
}
return res
}
// ImportSkill takes a skill the agents have of their own into the library:
// a folder is moved in, a link to a folder elsewhere is linked to from the
// library, and the agents that had it get the library's from then on.
func ImportSkill(name string) (*Result, error) {
return change(func(l *Library) error {
i := slices.IndexFunc(foundSkills(l), func(f FoundSkill) bool { return f.Name == name })
if i < 0 {
return fmt.Errorf("no agent has a skill called %s that the library hasn't", name)
}
f := foundSkills(l)[i]
if err := os.MkdirAll(skillsDir(), 0o755); err != nil {
return err
}
src := &Source{Kind: "folder", Dir: f.real}
if f.Link != "" {
if err := os.Symlink(f.real, skillDir(name)); err != nil {
return err
}
} else {
if err := move(f.real, skillDir(name)); err != nil {
return err
}
src = nil
}
for _, id := range f.Agents { // links to what was moved, or to the folder elsewhere
if t := targetByID(id); t != nil {
p := filepath.Join(t.Skills, name)
if fi, err := os.Lstat(p); err == nil && fi.Mode()&fs.ModeSymlink != 0 {
os.Remove(p)
}
}
}
l.Skills = append(l.Skills, &Skill{Name: name, Source: src, Agents: slices.Clone(f.Agents)})
return nil
})
}
// ---- files ----------------------------------------------------------------
func copyDir(from, to string) error {
return filepath.WalkDir(from, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(from, p)
dst := filepath.Join(to, rel)
if d.IsDir() {
if d.Name() == ".git" && p != from {
return filepath.SkipDir
}
return os.MkdirAll(dst, 0o755)
}
if d.Type()&fs.ModeSymlink != 0 {
if t, err := os.Readlink(p); err == nil {
return os.Symlink(t, dst)
}
return nil
}
if !d.Type().IsRegular() {
return nil
}
in, err := os.Open(p)
if err != nil {
return err
}
defer in.Close()
fi, _ := d.Info()
out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, fi.Mode().Perm())
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
return out.Close()
})
}
// move renames, or copies and removes where a rename can't cross disks.
func move(from, to string) error {
if err := os.Rename(from, to); err == nil {
return nil
} else if errors.Is(err, fs.ErrNotExist) {
return err
}
if err := copyDir(from, to); err != nil {
os.RemoveAll(to)
return err
}
return os.RemoveAll(from)
}
// SkillText is a library skill's SKILL.md, for the page to show.
func SkillText(name string) (string, error) {
if err := checkName("skill", name); err != nil {
return "", err
}
b, err := os.ReadFile(filepath.Join(skillDir(name), "SKILL.md"))
if err != nil {
return "", fmt.Errorf("%s has no SKILL.md in the library", name)
}
return string(b), nil
}
// SkillPath is where a library skill's folder is.
func SkillPath(name string) string { return skillDir(name) }
+296
View File
@@ -0,0 +1,296 @@
package library
import (
"fmt"
"slices"
)
// Result is what a change did to the agents.
type Result struct {
Changed []string `json:"changed"` // agents whose files were written
Problems []Problem `json:"problems"` // what couldn't be written, and why
Backup string `json:"backup,omitempty"`
}
// Problem is one thing that couldn't be given to an agent.
type Problem struct {
Agent string `json:"agent"`
What string `json:"what"` // instructions, mcp:<name>, skill:<name>
Error string `json:"error"`
}
func (r *Result) changed(agent string) {
if !slices.Contains(r.Changed, agent) {
r.Changed = append(r.Changed, agent)
}
}
func (r *Result) fail(agent, what string, err error) {
r.Problems = append(r.Problems, Problem{Agent: agent, What: what, Error: err.Error()})
}
// sync writes the library into every agent on this machine.
func (l *Library) sync() *Result {
res := &Result{Changed: []string{}, Problems: []Problem{}}
b := newBackups()
all := Targets()
for _, t := range all {
l.syncInstructions(t, b, res)
l.syncMCP(t, b, res)
l.syncSkills(t, res, all)
}
res.Backup = b.dir
if b.dir != "" {
pruneBackups()
}
return res
}
// Sync writes the library into the agents again: after an agent is
// installed, or a profile brings another library in.
func Sync() (*Result, error) {
return change(func(*Library) error { return nil })
}
func (l *Library) syncMCP(t *Target, b *backups, res *Result) {
if t.MCP == nil {
return
}
id := t.Agent.ID
a := l.applied(id)
entries, err := t.MCP.entries()
if err != nil {
res.fail(id, "mcp", err)
return
}
write := func(what string, f func() error) bool {
if err := b.keep(id, t.MCP.Path); err != nil {
res.fail(id, what, err)
return false
}
if err := f(); err != nil {
res.fail(id, what, err)
return false
}
res.changed(id)
return true
}
var mine []string
for _, name := range a.MCP {
if s := l.server(name); s != nil && slices.Contains(s.Agents, id) && t.MCP.supports(s) == nil {
continue
}
if _, ok := entries[name]; ok && !write("mcp:"+name, func() error { return t.MCP.del(name) }) {
mine = append(mine, name)
}
}
for _, s := range l.MCP {
if !slices.Contains(s.Agents, id) {
continue
}
if err := t.MCP.supports(s); err != nil {
res.fail(id, "mcp:"+s.Name, err)
continue
}
old := entries[s.Name]
if old != nil {
if cur, ok := t.MCP.decode(s.Name, old); ok && cur.same(s) {
mine = append(mine, s.Name)
continue
}
}
if write("mcp:"+s.Name, func() error { return t.MCP.put(s, old) }) {
mine = append(mine, s.Name)
}
}
a.MCP = mine
}
// ---- the page -------------------------------------------------------------
// AgentView is an agent as the page lists it, with where it keeps each.
type AgentView struct {
ID string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
Instructions string `json:"instructions,omitempty"`
MCP string `json:"mcp,omitempty"`
Skills string `json:"skills,omitempty"`
SkillsAlso []string `json:"skillsAlso,omitempty"`
Note string `json:"note,omitempty"`
NoSSE bool `json:"noSSE,omitempty"`
}
// ServerView is a library server, and what each agent it's on made of it.
type ServerView struct {
*Server
Icon string `json:"icon,omitempty"`
// Problems are the agents it couldn't be given to, and why
Problems map[string]string `json:"problems,omitempty"`
}
// SkillView is a library skill as the page shows it.
type SkillView struct {
Name string `json:"name"`
Description string `json:"description"`
Source string `json:"source,omitempty"`
Kind string `json:"kind"` // github, folder, or "" for one kept in the library
Icon string `json:"icon,omitempty"`
Agents []string `json:"agents"`
Missing bool `json:"missing,omitempty"` // its folder is gone
Problems map[string]string `json:"problems,omitempty"`
}
// View is the Library page.
type View struct {
Agents []AgentView `json:"agents"`
Servers []ServerView `json:"servers"`
FoundServers []Found `json:"foundServers"`
Skills []SkillView `json:"skills"`
FoundSkills []FoundSkill `json:"foundSkills"`
Instructions *InstructionsView `json:"instructions"`
Dir string `json:"dir"`
Backups string `json:"backups"`
}
// Read is the whole page: the library, and what's found in the agents.
// problems are those of the last change, for the page to keep showing.
func Read(problems []Problem) (*View, error) {
iv, err := ReadInstructions()
if err != nil {
return nil, err
}
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return nil, err
}
v := &View{Agents: []AgentView{}, Servers: []ServerView{}, Skills: []SkillView{}, Instructions: iv, Dir: Dir(), Backups: BackupDir()}
targets := Targets()
for _, t := range targets {
av := AgentView{ID: t.Agent.ID, Name: t.Agent.Name, Icon: t.Agent.Icon, Instructions: t.Instructions, Skills: t.Skills,
SkillsAlso: t.SkillsAlso, Note: t.Note}
if t.MCP != nil {
av.MCP = t.MCP.Path
av.NoSSE = t.MCP.supports(&Server{Transport: "sse"}) != nil
}
v.Agents = append(v.Agents, av)
}
of := func(what string) map[string]string {
m := map[string]string{}
for _, p := range problems {
if p.What == what {
m[p.Agent] = p.Error
}
}
if len(m) == 0 {
return nil
}
return m
}
for _, s := range l.MCP {
sv := ServerView{Server: s, Icon: serverIcon(l, s), Problems: of("mcp:" + s.Name)}
for _, t := range targets {
if t.MCP != nil && slices.Contains(s.Agents, t.Agent.ID) {
if err := t.MCP.supports(s); err != nil {
if sv.Problems == nil {
sv.Problems = map[string]string{}
}
sv.Problems[t.Agent.ID] = err.Error()
}
}
}
v.Servers = append(v.Servers, sv)
}
for _, s := range l.Skills {
sv := SkillView{Name: s.Name, Agents: s.Agents, Icon: skillIcon(s), Problems: of("skill:" + s.Name)}
if s.Source != nil {
sv.Source, sv.Kind = s.Source.String(), s.Source.Kind
}
if m, ok := readMeta(skillDir(s.Name)); ok {
sv.Description = m.Description
} else {
sv.Missing = true
}
v.Skills = append(v.Skills, sv)
}
v.FoundServers = foundServers(l)
for i := range v.FoundServers {
v.FoundServers[i].Icon = serverIcon(l, v.FoundServers[i].Server)
}
v.FoundSkills = foundSkills(l)
return v, nil
}
// ---- servers --------------------------------------------------------------
// SaveServer adds a server, or replaces the one called old (renaming it).
func SaveServer(old string, s Server) (*Result, error) {
if err := s.check(); err != nil {
return nil, err
}
return change(func(l *Library) error {
if s.Name != old && l.server(s.Name) != nil {
return fmt.Errorf("the library already has a server called %s", s.Name)
}
if old != "" {
i := slices.IndexFunc(l.MCP, func(x *Server) bool { return x.Name == old })
if i < 0 {
return fmt.Errorf("no server called %s", old)
}
l.MCP = slices.Delete(l.MCP, i, i+1)
}
s.Agents = slices.Sorted(slices.Values(s.Agents))
l.MCP = append(l.MCP, &s)
return nil
})
}
// ServerAgents sets which agents get a server.
func ServerAgents(name string, agents []string) (*Result, error) {
return change(func(l *Library) error {
s := l.server(name)
if s == nil {
return fmt.Errorf("no server called %s", name)
}
s.Agents = slices.Sorted(slices.Values(agents))
return nil
})
}
// RemoveServer takes a server out of the library and out of every agent
// magpie gave it to.
func RemoveServer(name string) (*Result, error) {
return change(func(l *Library) error {
i := slices.IndexFunc(l.MCP, func(x *Server) bool { return x.Name == name })
if i < 0 {
return fmt.Errorf("no server called %s", name)
}
l.MCP = slices.Delete(l.MCP, i, i+1)
return nil
})
}
// ImportServer takes a server the agents have into the library: the agents
// that have it as it is get the library's from then on, the same entry.
func ImportServer(name string) (*Result, error) {
return change(func(l *Library) error {
for _, f := range foundServers(l) {
if f.Server.Name != name {
continue
}
s := f.Server
s.Agents = slices.Sorted(slices.Values(s.Agents))
l.MCP = append(l.MCP, s)
for _, id := range s.Agents {
a := l.applied(id)
if !slices.Contains(a.MCP, name) {
a.MCP = append(a.MCP, name)
}
}
return nil
}
return fmt.Errorf("no agent has a server called %s that the library hasn't", name)
})
}
+137
View File
@@ -0,0 +1,137 @@
package library
import (
"os"
"path/filepath"
"github.com/yetone/magpie/internal/agent"
)
// Target is where one agent keeps each of the three: an empty path is
// something it has no user-wide place for.
type Target struct {
Agent *agent.Agent
// Instructions is the file the agent reads before every conversation;
// Override, when it exists, is read instead of it (Codex's
// AGENTS.override.md), which the page warns of.
Instructions, Override string
MCP *mcpFile
Skills string // the folder the agent finds skills in
// SkillsAlso are agents whose skills this one reads as well, as
// OpenCode reads Claude Code's.
SkillsAlso []string
// Note is what the page says of the agent's instructions file.
Note string
}
func home() string { h, _ := os.UserHomeDir(); return h }
func claudeDir() string {
if d := os.Getenv("CLAUDE_CONFIG_DIR"); d != "" {
return d
}
return filepath.Join(home(), ".claude")
}
// claudeJSON is where Claude Code keeps its user-wide MCP servers: beside
// its folder, or in it when CLAUDE_CONFIG_DIR moves it.
func claudeJSON() string {
if d := os.Getenv("CLAUDE_CONFIG_DIR"); d != "" {
return filepath.Join(d, ".claude.json")
}
return filepath.Join(home(), ".claude.json")
}
func codexDir() string {
if d := os.Getenv("CODEX_HOME"); d != "" {
return d
}
return filepath.Join(home(), ".codex")
}
// targetOf is where a known agent keeps them, or nil for one magpie can't
// give any of them to.
func targetOf(a *agent.Agent) *Target {
h := home()
t := &Target{Agent: a}
switch a.ID {
case "claude":
d := claudeDir()
t.Instructions = filepath.Join(d, "CLAUDE.md")
t.MCP = &mcpFile{Path: claudeJSON(), Format: fmtClaude}
t.Skills = filepath.Join(d, "skills")
case "codex":
d := codexDir()
t.Instructions = filepath.Join(d, "AGENTS.md")
t.Override = filepath.Join(d, "AGENTS.override.md")
t.MCP = &mcpFile{Path: filepath.Join(d, "config.toml"), Format: fmtCodex}
t.Skills = filepath.Join(d, "skills")
case "gemini":
d := filepath.Join(h, ".gemini")
t.Instructions = filepath.Join(d, "GEMINI.md")
t.MCP = &mcpFile{Path: filepath.Join(d, "settings.json"), Format: fmtGemini}
t.Skills = filepath.Join(d, "skills")
case "opencode":
d := filepath.Dir(a.Path)
t.Instructions = filepath.Join(d, "AGENTS.md")
t.Note = "opencode-claude"
t.MCP = &mcpFile{Path: a.Path, Format: fmtOpenCode}
t.Skills = filepath.Join(d, "skills")
t.SkillsAlso = []string{"claude"}
case "pi":
d := os.Getenv("PI_CODING_AGENT_DIR")
if d == "" {
d = filepath.Join(h, ".pi", "agent")
}
t.Instructions = filepath.Join(d, "AGENTS.md")
t.Skills = filepath.Join(d, "skills")
case "omp":
d := filepath.Join(h, ".omp", "agent")
t.Instructions = filepath.Join(d, "AGENTS.md")
t.Skills = filepath.Join(d, "skills")
case "goose":
t.Instructions = filepath.Join(filepath.Dir(a.Path), ".goosehints")
t.MCP = &mcpFile{Path: a.Path, Format: fmtGoose}
case "cursor":
d := filepath.Join(h, ".cursor")
t.MCP = &mcpFile{Path: filepath.Join(d, "mcp.json"), Format: fmtCursor}
t.Skills = filepath.Join(d, "skills")
case "copilot":
d := os.Getenv("COPILOT_HOME")
if d == "" {
d = filepath.Join(h, ".copilot")
}
t.Instructions = filepath.Join(d, "copilot-instructions.md")
t.MCP = &mcpFile{Path: filepath.Join(d, "mcp-config.json"), Format: fmtCopilot}
t.Skills = filepath.Join(d, "skills")
case "crush":
t.Instructions = filepath.Join(filepath.Dir(a.Path), "CRUSH.md")
t.MCP = &mcpFile{Path: a.Path, Format: fmtCrush}
t.Skills = filepath.Join(filepath.Dir(a.Path), "skills")
t.SkillsAlso = []string{"claude"}
default:
return nil
}
return t
}
// Targets are the agents on this machine that magpie can give any of the
// three to, in the order the rest of magpie lists them.
func Targets() []*Target {
var out []*Target
for _, a := range agent.Detected() {
if t := targetOf(a); t != nil {
out = append(out, t)
}
}
return out
}
func targetByID(id string) *Target {
for _, t := range Targets() {
if t.Agent.ID == id {
return t
}
}
return nil
}