browser: Magpie Browser, agents use the user's own browser and its sign-ins

The owner asked for a browser-use MCP of magpie's own, so an agent's
browser keeps working when Claude Code switches accounts, and asked that
it act in the browser the user uses every day: a fresh Playwright
profile is signed in to nothing.

Magpie Browser is an MV3 extension (internal/browserext, ID
dmlhojidlfnkgamkekjhacgkpanbkeko, pinned by its key) that the user loads
once in Chrome, Edge, Arc, Brave or another Chromium browser. It holds a
WebSocket to the gateway's /v1/magpie/browser/extension and carries out
each tool call with chrome.debugger (the DevTools protocol) in the user's
own tabs. The socket is taken only from this computer, with a loopback
Host (no DNS rebinding) and the extension's own Origin; a page or another
extension that connected in its place would be handed every call.

Agents reach it at /mcp/magpie/browser (Streamable HTTP) or through
`magpie mcp browser` (stdio), and the Library's MCP market lists it as
Magpie Browser, opt-in. Like the image server it is magpie's own, but it
is never served to another computer, shared and with a key or not, and
never to a web page, since it acts as the user wherever they are signed
in. 17 tools: navigate (url, back, forward, reload), snapshot (an
accessibility tree with refs, interactive-only on ask), click, type,
press, select, hover, drag, upload, scroll, wait (text, gone, seconds),
dialog, evaluate, text, screenshot (page, full page, element; JPEG or
PNG), console and tabs (list, new, select, close). Each agent session
goes on in its own tab; a link that opens a tab is followed, and a
dialog a click opens is said in the reply.

The Library's sheet for it has Set up the extension…, which writes the
extension to ~/.config/magpie/browser-extension pointed at this gateway
and shows the folder, the three steps to load it, and whether the
browser is connected, polled while the sheet is open.

Run:
- TestBrowserToolsInARealBrowser: the extension magpie writes, loaded in
  a real Chrome for Testing 141 (Playwright's chromium-1234, headless=new)
  with --load-extension, connects, and all 17 tools act in a real tab of
  a fixture site. Green on mote (macOS 27), on xiaomi-gpu (Windows 11,
  win-run) and in magpie-desktop (Ubuntu 24.04, wsl-run). Under a test
  HOME Chrome needs --use-mock-keychain / --password-store=basic, or the
  extension's storage waits on a keychain and it never connects.
- go test ./internal/gateway -run 'Browser|ReadOnly|Image', ./internal/
  browserext, ./internal/browsermcp, ./internal/library, ./internal/gui
  -run 'Library|Browser', ./internal/cli on mote.
- GUI: library-browser-setup.test.cjs (new) in Chromium and WebKit, en,
  zh, zh-TW, ja, de, at 1100 and 420 wide: 22/22. With i18n-keys and
  every library*.test.cjs: 915 pass, 1 fail, i18n-keys' "Unmarked",
  red on main since 5787d758a (#4524, fixed in the next commit).
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
  go vet ./... on mote.
- Again at this commit, rebased on 2e9df9b1b: gofmt -l, the vet trio,
  ./internal/gui -run 'Budget|Size', ./internal/proc (exec guard),
  ./internal/usage, ./internal/browserext, ./internal/browsermcp, and
  i18n-keys (0 fail with the next commit). The full go test ./... runs
  in magpie-desktop (Linux) as this is pushed; mote had another
  session's suite running.

Broken by hand, each red, then restored:
- browser_click's dispatch in background.js turned into a no-op: the
  E2E test is red at "clicked Ada".
- the extension socket's Origin check, its loopback-Host check and
  local(): TestBrowserExtensionOnlyFromItsOrigin red for each.
- browserMCP's local()/fromBrowser() guard: TestBrowserMCPGuarded red.
- a tool dropped from background.js: TestBrowserToolsAreTheExtensions red.
- the sheet's steps left shown once connected: the GUI test is red.

Not tried: loading it by hand (Load unpacked) in the owner's own daily
Chrome or Edge and driving a site they are signed in to; Arc, Brave and
Edge themselves (only Chrome for Testing); Firefox and Safari, which
have no chrome.debugger and are not supported. Chrome shows its "is
debugging this browser" bar while a tab is being driven; that is
Chrome's and cannot be hidden.
This commit is contained in:
yetone
2026-11-01 02:29:55 +08:00
parent 2e9df9b1be
commit 0e90572274
34 changed files with 2907 additions and 8 deletions
+77
View File
@@ -0,0 +1,77 @@
// Package browserext is Magpie Browser, the browser extension through which
// the agents magpie serves use the user's own browser: their tabs, signed
// in to the sites they use (gateway/browser.go relays the calls). magpie
// writes it to a folder of its own, pointed at its gateway, for the user to
// load in chrome://extensions.
package browserext
import (
"bytes"
"embed"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
)
// ID is the extension's ID in every Chromium browser, fixed by the public
// key in its manifest; the gateway takes a connection from this origin
// only.
const ID = "dmlhojidlfnkgamkekjhacgkpanbkeko"
// Origin is what the extension's requests carry as Origin.
const Origin = "chrome-extension://" + ID
//go:embed ext
var files embed.FS
// Version is the extension's version, from its manifest.
func Version() string {
b, _ := files.ReadFile("ext/manifest.json")
_, v, ok := bytes.Cut(b, []byte(`"version": "`))
if !ok {
return ""
}
v, _, _ = bytes.Cut(v, []byte(`"`))
return string(v)
}
// File is one of the extension's files as magpie has it.
func File(name string) ([]byte, error) { return files.ReadFile("ext/" + name) }
// Write puts the extension in dir, pointed at the gateway at gatewayURL
// (http://127.0.0.1:3425), replacing what an older magpie wrote there.
// A file is written only when it changed, so a browser that has the folder
// loaded sees no change it has to reload for.
func Write(dir, gatewayURL string) error {
ws := "ws" + strings.TrimPrefix(strings.TrimRight(gatewayURL, "/"), "http")
if !strings.HasPrefix(ws, "ws://") && !strings.HasPrefix(ws, "wss://") {
return fmt.Errorf("the gateway's address %q isn't http", gatewayURL)
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
return fs.WalkDir(files, "ext", func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
b, err := files.ReadFile(p)
if err != nil {
return err
}
name := strings.TrimPrefix(p, "ext/")
if name == "config.js" {
b = fmt.Appendf(nil, "// The gateway this extension talks to, written by magpie.\nexport const GATEWAY = %q;\n", ws)
}
to := filepath.Join(dir, filepath.FromSlash(name))
if old, err := os.ReadFile(to); err == nil && bytes.Equal(old, b) {
return nil
}
tmp := to + ".tmp"
if err := os.WriteFile(tmp, b, 0o644); err != nil {
return err
}
return os.Rename(tmp, to)
})
}
+49
View File
@@ -0,0 +1,49 @@
package browserext
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// The extension is written pointed at the gateway it is set up from, and
// written again only where it changed.
func TestWritePointsAtTheGateway(t *testing.T) {
dir := filepath.Join(t.TempDir(), "ext")
if err := Write(dir, "http://127.0.0.1:3425"); err != nil {
t.Fatal(err)
}
cfg, _ := os.ReadFile(filepath.Join(dir, "config.js"))
if !strings.Contains(string(cfg), `export const GATEWAY = "ws://127.0.0.1:3425";`) {
t.Fatalf("config.js: %s", cfg)
}
var man struct {
Version, Key string
Background struct {
ServiceWorker string `json:"service_worker"`
}
}
b, _ := os.ReadFile(filepath.Join(dir, "manifest.json"))
if err := json.Unmarshal(b, &man); err != nil || man.Version != Version() || man.Key == "" || man.Background.ServiceWorker != "background.js" {
t.Fatalf("manifest: %v %+v", err, man)
}
old := time.Now().Add(-time.Hour)
bg := filepath.Join(dir, "background.js")
os.Chtimes(bg, old, old)
if err := Write(dir, "http://127.0.0.1:4000/"); err != nil {
t.Fatal(err)
}
cfg, _ = os.ReadFile(filepath.Join(dir, "config.js"))
if !strings.Contains(string(cfg), `"ws://127.0.0.1:4000"`) {
t.Fatalf("another port: %s", cfg)
}
if fi, _ := os.Stat(bg); !fi.ModTime().Equal(old) {
t.Fatal("background.js was written again unchanged")
}
if Write(dir, "ftp://x") == nil {
t.Fatal("took an address that isn't http")
}
}
+686
View File
@@ -0,0 +1,686 @@
// Magpie Browser: magpie's gateway hands this extension the browser tool
// calls of the agents it serves (magpie mcp browser), and it carries them
// out in this browser's own tabs, signed in to whatever the user is.
import { GATEWAY } from "./config.js";
import { attach, forget, send, settle, sleep, state, waitLoad } from "./cdp.js";
import { find, take } from "./snapshot.js";
import { press as keyPress, typeSlowly } from "./keys.js";
const VERSION = chrome.runtime.getManifest().version;
const ACT_SNAPSHOT_MAX = 30000;
// ---- the gateway connection --------------------------------------------
let ws = null;
let retry = 1000;
let connecting = false;
async function gatewayURL() {
try {
const { gateway } = await chrome.storage.local.get("gateway");
if (gateway) return gateway;
} catch {}
return GATEWAY;
}
async function connect() {
if (connecting || (ws && ws.readyState <= 1)) return;
connecting = true;
const base = await gatewayURL();
let s;
try {
s = new WebSocket(base.replace(/\/$/, "") + "/v1/magpie/browser/extension");
} catch (e) {
connecting = false;
setStatus({ connected: false, gateway: base, error: String(e.message || e) });
return later();
}
ws = s;
s.onopen = () => {
connecting = false;
retry = 1000;
s.send(JSON.stringify({ type: "hello", version: VERSION, agent: navigator.userAgent }));
setStatus({ connected: true, gateway: base });
};
s.onmessage = (ev) => {
let m;
try { m = JSON.parse(ev.data); } catch { return; }
if (m.type === "ping") return s.send(JSON.stringify({ type: "pong" }));
if (!m.id || !m.tool) return;
run(m).then((result) => {
if (s.readyState === 1) s.send(JSON.stringify({ id: m.id, result }));
});
};
s.onclose = () => {
connecting = false;
if (ws === s) ws = null;
setStatus({ connected: false, gateway: base });
later();
};
s.onerror = () => {};
}
let timer = 0;
function later() {
clearTimeout(timer);
timer = setTimeout(connect, retry);
retry = Math.min(retry * 2, 15000);
}
function setStatus(s) {
chrome.storage.session.set({ status: { ...s, at: Date.now() } }).catch(() => {});
chrome.action.setBadgeText({ text: s.connected ? "" : "off" }).catch(() => {});
chrome.action.setBadgeBackgroundColor({ color: "#8a8a8a" }).catch(() => {});
}
// a message every 20s keeps the service worker alive while connected;
// the alarm brings it back to reconnect when Chrome stopped it
setInterval(() => { if (ws && ws.readyState === 1) ws.send(JSON.stringify({ type: "ping" })); }, 20000);
chrome.alarms.create("magpie-reconnect", { periodInMinutes: 0.5 });
chrome.alarms.onAlarm.addListener(() => connect());
chrome.runtime.onStartup.addListener(() => connect());
chrome.runtime.onInstalled.addListener(() => connect());
chrome.storage.onChanged.addListener((c, area) => {
if (area === "local" && c.gateway) {
retry = 1000;
if (ws) ws.close();
else connect();
}
});
chrome.runtime.onMessage.addListener((m, _s, reply) => {
if (m && m.type === "reconnect") {
retry = 1000;
if (ws) ws.close();
connect();
reply({ ok: true });
}
});
connect();
// ---- sessions: each agent's tab ------------------------------------------
const sessions = new Map(); // session → tabId
let loaded = false;
async function loadSessions() {
if (loaded) return;
loaded = true;
try {
const { sessions: s } = await chrome.storage.session.get("sessions");
for (const [k, v] of Object.entries(s || {})) sessions.set(k, v);
} catch {}
}
function saveSessions() {
chrome.storage.session.set({ sessions: Object.fromEntries(sessions) }).catch(() => {});
}
chrome.tabs.onRemoved.addListener((tabId) => {
forget(tabId);
for (const [k, v] of sessions) if (v === tabId) sessions.delete(k);
saveSessions();
});
function tabArg(v) {
if (v === undefined || v === null || v === "") return null;
const m = /^t?(\d+)$/i.exec(String(v).trim());
if (!m) throw new Error(`"${v}" isn't a tab: tabs look like t123, from browser_tabs`);
return Number(m[1]);
}
// the tab a call works in: the one it names, else the session's, else the
// tab the user is looking at
async function tabFor(session, args) {
await loadSessions();
const named = tabArg(args.tab);
if (named !== null) {
await chrome.tabs.get(named).catch(() => { throw new Error(`there is no tab t${named} now: call browser_tabs for the open ones`); });
sessions.set(session, named);
saveSessions();
return named;
}
const had = sessions.get(session);
if (had !== undefined) {
const ok = await chrome.tabs.get(had).then(() => true, () => false);
if (ok) return had;
}
const [active] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
if (!active) throw new Error("no browser window is open: open one, or call browser_tabs with action new");
sessions.set(session, active.id);
saveSessions();
return active.id;
}
// the tab group agents' tabs are opened in, one per window
async function group(tabId, windowId) {
try {
const [g] = await chrome.tabGroups.query({ windowId, title: "Magpie" });
if (g) return await chrome.tabs.group({ tabIds: [tabId], groupId: g.id });
const id = await chrome.tabs.group({ tabIds: [tabId], createProperties: { windowId } });
await chrome.tabGroups.update(id, { title: "Magpie", color: "grey" });
} catch {}
}
// ---- running a call ------------------------------------------------------
const text = (s) => ({ type: "text", text: s });
const fail = (s) => ({ content: [text(s)], isError: true });
async function run(m) {
try {
const tool = TOOLS[m.tool];
if (!tool) return fail(`magpie's browser extension has no tool ${m.tool}: update it (magpie writes it again on start; reload it in chrome://extensions)`);
return await tool(m.session || "default", m.args || {});
} catch (e) {
return fail(String((e && e.message) || e));
}
}
async function ready(session, args) {
const tabId = await tabFor(session, args);
const t = state(tabId);
if (t.stoppedByUser) {
t.stoppedByUser = false;
throw new Error("the user stopped Magpie Browser in this tab (Cancel on Chrome's bar): ask them before going on. The next call attaches to it again.");
}
await attach(tabId);
await send(tabId, "Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => {});
return t;
}
async function head(t) {
const tab = await chrome.tabs.get(t.tabId).catch(() => null);
return tab ? `Tab t${t.tabId}: ${tab.title || "(untitled)"} — ${tab.url}` : `Tab t${t.tabId}`;
}
async function page(t, max = ACT_SNAPSHOT_MAX, opts = {}) {
const s = await take(t, { maxChars: max, ...opts });
return `${await head(t)}\n${s.count} refs\n\n${s.text || "(the page shows nothing)"}`;
}
function notices(t) {
const out = [];
if (t.answered) {
out.push(`A ${t.answered.type} dialog ("${t.answered.message}") was ${t.answered.accept ? "accepted" : "dismissed"} as asked.`);
t.answered = null;
}
if (t.dialog) out.push(`A ${t.dialog.type} dialog is open: "${t.dialog.message}". Answer it with browser_dialog before anything else.`);
return out;
}
// act runs an action, waits for the page to settle and answers with what
// happened and the page after it. A dialog the action opens stops the
// page; it is reported rather than waited on.
async function act(t, what, fn) {
if (t.dialog) return fail(notices(t).join("\n"));
const before = new Set((await chrome.tabs.query({})).map((x) => x.id));
let opened = null;
const onCreated = (tab) => { if (!before.has(tab.id) && (tab.openerTabId === t.tabId || !opened)) opened = tab; };
chrome.tabs.onCreated.addListener(onCreated);
let said;
try {
const p = fn();
p.catch(() => {});
said = await Promise.race([
p,
(async () => { while (!t.dialog) await sleep(100); return ""; })(),
]);
} finally {
setTimeout(() => chrome.tabs.onCreated.removeListener(onCreated), 1500);
}
if (!t.dialog) await settle(t);
const out = [];
if (said) out.push(said);
else out.push(what);
out.push(...notices(t));
if (t.dialog) return { content: [text(out.join("\n"))] };
if (opened && opened.openerTabId === t.tabId) {
// a link that opens a new tab: the agent goes on in it
const s = [...sessions].find(([, v]) => v === t.tabId);
if (s) { sessions.set(s[0], opened.id); saveSessions(); }
const nt = state(opened.id);
await attach(opened.id);
await waitLoad(nt, 15000);
await settle(nt);
out.push(`It opened a new tab, t${opened.id}; calls now go to it (browser_tabs select to go back).`);
out.push("", await page(nt));
return { content: [text(out.join("\n"))] };
}
out.push("", await page(t));
return { content: [text(out.join("\n"))] };
}
// point is where to click an element: the middle of its first box that
// isn't covered by something else, scrolled into view
async function point(t, el) {
await send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: el.backend }).catch(() => {});
let quads;
try {
quads = (await send(t.tabId, "DOM.getContentQuads", { backendNodeId: el.backend })).quads;
} catch {
quads = [];
}
if (!quads.length) throw new Error(`${el.ref} (${el.role} "${el.name}") has no box on the page (hidden or collapsed): open what holds it first, or take a snapshot`);
const q = quads[0];
const xs = [q[0], q[2], q[4], q[6]], ys = [q[1], q[3], q[5], q[7]];
const x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys);
const tries = [[0.5, 0.5], [0.3, 0.5], [0.7, 0.5], [0.5, 0.3], [0.5, 0.7], [0.2, 0.2], [0.8, 0.8]];
let cover = "";
for (const [fx, fy] of tries) {
const x = x0 + (x1 - x0) * fx, y = y0 + (y1 - y0) * fy;
const r = await send(t.tabId, "Runtime.callFunctionOn", {
objectId: el.objectId,
functionDeclaration: `function(x, y) {
if (this.ownerDocument.defaultView !== window.top) return "";
const e = document.elementFromPoint(x, y);
if (!e) return "outside";
if (e === this || this.contains(e) || (e.shadowRoot && e.contains(this))) return "";
let r = e; while (r && r.shadowRoot && r !== this) { const d = r.shadowRoot.elementFromPoint(x, y); if (!d || d === r) break; r = d; if (r === this || this.contains(r)) return ""; }
if (this.contains && e.contains(this) && getComputedStyle(e).pointerEvents !== "none" && e.tagName === "LABEL") return "";
const s = (e.innerText || e.getAttribute("aria-label") || "").trim().replace(/\\s+/g, " ").slice(0, 60);
return "<" + e.tagName.toLowerCase() + (e.id ? "#" + e.id : "") + (e.className && typeof e.className === "string" ? "." + e.className.trim().split(/\\s+/).slice(0, 2).join(".") : "") + ">" + (s ? " \\"" + s + "\\"" : "");
}`,
arguments: [{ value: x }, { value: y }],
returnByValue: true,
}).catch(() => ({ result: { value: "" } }));
const v = r.result.value;
if (!v) return { x, y };
if (v !== "outside") cover = v;
}
if (cover) throw new Error(`${el.ref} (${el.role} "${el.name}") is covered by ${cover}: close or move what covers it (a dialog, a cookie banner, a menu) and try again`);
throw new Error(`${el.ref} (${el.role} "${el.name}") is outside the window: scroll to it (browser_scroll) and try again`);
}
const BUTTONS = { left: "left", right: "right", middle: "middle" };
const MODS = { Alt: 1, Control: 2, Ctrl: 2, Meta: 4, Command: 4, Cmd: 4, Shift: 8 };
async function mouse(t, x, y, opts = {}) {
const button = BUTTONS[opts.button] || "left";
const modifiers = (opts.modifiers || []).reduce((a, m) => a | (MODS[m] || 0), 0);
const count = opts.double ? 2 : 1;
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x, y, modifiers });
await sleep(30 + Math.random() * 40);
for (let i = 1; i <= count; i++) {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x, y, button, clickCount: i, modifiers, buttons: 1 });
await sleep(40 + Math.random() * 50);
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button, clickCount: i, modifiers });
}
}
async function call(t, el, fn, args = []) {
const r = await send(t.tabId, "Runtime.callFunctionOn", {
objectId: el.objectId, functionDeclaration: fn, arguments: args.map((value) => ({ value })),
returnByValue: true, awaitPromise: true,
});
if (r.exceptionDetails) throw new Error((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || r.exceptionDetails.text);
return r.result.value;
}
function need(args, ...names) {
for (const n of names) {
if (args[n] === undefined || args[n] === null || args[n] === "") throw new Error(`${n} is needed`);
}
}
function withScheme(u) {
u = String(u).trim();
if (/^[a-z][a-z0-9+.-]*:/i.test(u)) return u;
if (/^(localhost|127\.|\[::1\])/i.test(u)) return "http://" + u;
return "https://" + u;
}
const TOOLS = {
async browser_tabs(session, args) {
await loadSessions();
const action = args.action || "list";
if (action === "new") {
const [w] = await chrome.windows.getAll({ windowTypes: ["normal"] }).then((ws) => ws.filter((x) => x.focused).concat(ws));
const tab = await chrome.tabs.create({ url: args.url ? withScheme(args.url) : "about:blank", active: args.background ? false : true, ...(w ? { windowId: w.id } : {}) });
await group(tab.id, tab.windowId);
sessions.set(session, tab.id);
saveSessions();
const t = state(tab.id);
await attach(tab.id);
if (args.url) { await waitLoad(t); await settle(t); }
return { content: [text(`Opened t${tab.id}; calls now go to it.\n\n` + (args.url ? await page(t) : await head(t)))] };
}
if (action === "select") {
need(args, "tab");
const t = await ready(session, { tab: args.tab });
return { content: [text(`Calls now go to t${t.tabId}.\n\n` + await page(t))] };
}
if (action === "close") {
const id = args.tab ? tabArg(args.tab) : sessions.get(session);
if (id === undefined || id === null) throw new Error("tab is needed");
await chrome.tabs.remove(id);
return { content: [text(`Closed t${id}.`)] };
}
const all = await chrome.tabs.query({});
const mine = sessions.get(session);
const lines = all.map((x) => `${x.id === mine ? "*" : x.active ? "+" : " "} t${x.id} ${x.title ? JSON.stringify(x.title.slice(0, 100)) : ""} ${x.url ? x.url.slice(0, 200) : ""}`);
return { content: [text(`${all.length} tabs (* is the one calls go to, + a window's shown tab):\n` + lines.join("\n"))] };
},
async browser_navigate(session, args) {
const t = await ready(session, args);
const go = args.go || (["back", "forward", "reload"].includes(args.url) ? args.url : "");
let said;
if (go === "reload") {
await send(t.tabId, "Page.reload", {});
said = "Reloaded.";
} else if (go === "back" || go === "forward") {
const h = await send(t.tabId, "Page.getNavigationHistory");
const e = h.entries[h.currentIndex + (go === "back" ? -1 : 1)];
if (!e) throw new Error(`there is no page to go ${go} to`);
await send(t.tabId, "Page.navigateToHistoryEntry", { entryId: e.id });
said = `Went ${go} to ${e.url}.`;
} else {
need(args, "url");
const url = withScheme(args.url);
t.loading = true;
const r = await send(t.tabId, "Page.navigate", { url });
if (r.errorText) { t.loading = false; throw new Error(`${url} didn't load: ${r.errorText}`); }
said = `Opened ${url}.`;
}
const loaded = await waitLoad(t);
await settle(t);
if (!loaded) said += " (It is still loading after 30s.)";
return { content: [text([said, ...notices(t), "", await page(t)].join("\n"))] };
},
async browser_snapshot(session, args) {
const t = await ready(session, args);
if (t.dialog) return fail(notices(t).join("\n"));
const s = await take(t, { interactive: !!args.interactive, ref: args.ref, maxChars: Math.min(Number(args.maxChars) || 60000, 200000) });
return { content: [text(`${await head(t)}\n${s.count} refs, ${s.interactive} to act on\n\n${s.text || "(the page shows nothing)"}`)] };
},
async browser_click(session, args) {
need(args, "ref");
const t = await ready(session, args);
const el = await find(t, args.ref);
return act(t, `Clicked ${el.ref} (${el.role} "${el.name}").`, async () => {
const p = await point(t, el);
await mouse(t, p.x, p.y, args);
});
},
async browser_hover(session, args) {
need(args, "ref");
const t = await ready(session, args);
const el = await find(t, args.ref);
return act(t, `Hovering over ${el.ref}.`, async () => {
const p = await point(t, el);
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y });
});
},
async browser_type(session, args) {
need(args, "ref");
if (typeof args.text !== "string") throw new Error("text is needed");
const t = await ready(session, args);
const el = await find(t, args.ref);
return act(t, `Typed into ${el.ref}${args.submit ? " and pressed Enter" : ""}.`, async () => {
const p = await point(t, el).catch(() => null);
if (p) await mouse(t, p.x, p.y);
const ok = await call(t, el, `function(clear) {
const e = this;
const edit = (x) => x && (x.isContentEditable || /^(INPUT|TEXTAREA)$/.test(x.tagName));
let to = edit(e) ? e : (e.querySelector && e.querySelector('input,textarea,[contenteditable=""],[contenteditable="true"]')) || e;
if (document.activeElement !== to && !(to.contains && to.contains(document.activeElement))) to.focus();
const a = document.activeElement;
if (!edit(a) && !(a && a.isContentEditable)) return false;
if (/^(INPUT|TEXTAREA)$/.test(a.tagName)) {
if (clear) a.select(); else { try { const n = a.value.length; a.setSelectionRange(n, n); } catch {} }
} else {
const s = getSelection(), r = document.createRange();
r.selectNodeContents(a);
if (!clear) r.collapse(false);
s.removeAllRanges(); s.addRange(r);
}
return true;
}`, [args.clear !== false]);
if (!ok) throw new Error(`${el.ref} (${el.role} "${el.name}") doesn't take text: click the field itself`);
if (args.clear !== false) await keyPress(t, "Delete");
if (args.slowly) await typeSlowly(t, args.text);
else if (args.text) await send(t.tabId, "Input.insertText", { text: args.text });
if (args.submit) await keyPress(t, "Enter");
});
},
async browser_press(session, args) {
need(args, "key");
const t = await ready(session, args);
let el = null;
if (args.ref) el = await find(t, args.ref);
return act(t, `Pressed ${args.key}.`, async () => {
if (el) await call(t, el, "function(){ this.focus() }");
await keyPress(t, args.key);
});
},
async browser_select(session, args) {
need(args, "ref");
const values = Array.isArray(args.values) ? args.values.map(String) : args.value !== undefined ? [String(args.value)] : [];
if (!values.length) throw new Error("values is needed");
const t = await ready(session, args);
const el = await find(t, args.ref);
return act(t, `Chose ${values.map((v) => JSON.stringify(v)).join(", ")} in ${el.ref}.`, async () => {
const why = await call(t, el, `function(values) {
const s = this.tagName === "SELECT" ? this : this.querySelector && this.querySelector("select");
if (!s) return "is not a native list: click it, then click the option in the snapshot";
const opts = [...s.options], picked = [];
for (const v of values) {
const l = v.trim().toLowerCase();
const o = opts.find((o) => o.value === v) || opts.find((o) => o.label.trim().toLowerCase() === l) || opts.find((o) => o.label.toLowerCase().includes(l));
if (!o) return "has no option " + JSON.stringify(v) + "; it has: " + opts.map((o) => o.label.trim()).slice(0, 60).join(", ");
picked.push(o);
}
if (!s.multiple && picked.length > 1) return "takes one value";
for (const o of opts) o.selected = picked.includes(o);
s.dispatchEvent(new Event("input", { bubbles: true }));
s.dispatchEvent(new Event("change", { bubbles: true }));
return "";
}`, [values]);
if (why) throw new Error(`${el.ref} (${el.role} "${el.name}") ${why}`);
});
},
async browser_scroll(session, args) {
const t = await ready(session, args);
const m = await send(t.tabId, "Page.getLayoutMetrics");
const vw = m.cssVisualViewport || m.layoutViewport;
let x = vw.clientWidth / 2, y = vw.clientHeight / 2;
if (args.ref) {
const el = await find(t, args.ref);
if (!args.direction) {
return act(t, `Scrolled ${el.ref} into view.`, () => send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: el.backend }));
}
const q = (await send(t.tabId, "DOM.getContentQuads", { backendNodeId: el.backend }).catch(() => ({ quads: [] }))).quads[0];
if (q) { x = (q[0] + q[4]) / 2; y = (q[1] + q[5]) / 2; }
}
const dir = args.direction || "down";
const amount = Number(args.amount) || Math.round((dir === "left" || dir === "right" ? vw.clientWidth : vw.clientHeight) * 0.8);
const dx = dir === "left" ? -amount : dir === "right" ? amount : 0;
const dy = dir === "up" ? -amount : dir === "down" ? amount : 0;
return act(t, `Scrolled ${dir} ${amount}px.`, async () => {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX: dx, deltaY: dy });
await sleep(250);
const r = await send(t.tabId, "Runtime.evaluate", { expression: "[scrollX, scrollY, document.documentElement.scrollHeight, innerHeight]", returnByValue: true });
const [sx, sy, h, ih] = r.result.value;
return `Scrolled ${dir} ${amount}px; the page is at ${Math.round(sy)} of ${Math.max(0, h - ih)}px down${sx ? `, ${Math.round(sx)}px across` : ""}.`;
});
},
async browser_drag(session, args) {
need(args, "from", "to");
const t = await ready(session, args);
const a = await find(t, args.from);
const b = await find(t, args.to);
return act(t, `Dragged ${a.ref} onto ${b.ref}.`, async () => {
const p = await point(t, a);
const q = await point(t, b);
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y });
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x: p.x, y: p.y, button: "left", clickCount: 1, buttons: 1 });
try {
for (let i = 1; i <= 12; i++) {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x + ((q.x - p.x) * i) / 12, y: p.y + ((q.y - p.y) * i) / 12, button: "left", buttons: 1 });
await sleep(25);
}
} finally {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x: q.x, y: q.y, button: "left", clickCount: 1 });
}
});
},
async browser_upload(session, args) {
need(args, "ref");
const files = Array.isArray(args.paths) ? args.paths.map(String) : [];
if (!files.length) throw new Error("paths is needed: the files' full paths on this computer");
const t = await ready(session, args);
const el = await find(t, args.ref);
return act(t, `Chose ${files.length} file${files.length > 1 ? "s" : ""} in ${el.ref}.`, async () => {
const isInput = await call(t, el, 'function(){ return this.tagName === "INPUT" && this.type === "file" }');
const set = (backendNodeId) => send(t.tabId, "DOM.setFileInputFiles", { files, backendNodeId }).catch((e) => {
const m = String(e.message || e);
if (/not allowed|permission|denied/i.test(m)) throw new Error("Chrome didn't let Magpie Browser choose files: turn on \"Allow access to file URLs\" for Magpie Browser in chrome://extensions");
throw e;
});
if (isInput) return void (await set(el.backend));
// a button that opens the file picker: the picker is caught and
// answered with the files
await send(t.tabId, "Page.setInterceptFileChooserDialog", { enabled: true });
try {
const opened = new Promise((resolve, reject) => {
t.chooser = resolve;
setTimeout(() => reject(new Error(`clicking ${el.ref} opened no file picker: use the file field's ref`)), 5000);
});
const p = await point(t, el);
await mouse(t, p.x, p.y);
const c = await opened;
await set(c.backendNodeId);
} finally {
t.chooser = null;
await send(t.tabId, "Page.setInterceptFileChooserDialog", { enabled: false }).catch(() => {});
}
});
},
async browser_wait(session, args) {
const t = await ready(session, args);
const bound = Math.min(Number(args.timeout) || 10, 60) * 1000;
if (args.seconds) {
await sleep(Math.min(Number(args.seconds), 60) * 1000);
return { content: [text([`Waited ${args.seconds}s.`, ...notices(t), "", await page(t)].join("\n"))] };
}
if (!args.text && !args.textGone && !args.url) throw new Error("text, textGone, url or seconds is needed");
const end = Date.now() + bound;
for (;;) {
if (t.dialog) return fail(notices(t).join("\n"));
const r = await send(t.tabId, "Runtime.evaluate", { expression: "[location.href, document.body ? document.body.innerText : '']", returnByValue: true }).catch(() => null);
if (r && r.result && r.result.value) {
const [href, body] = r.result.value;
const ok = (!args.text || body.includes(args.text)) && (!args.textGone || !body.includes(args.textGone)) && (!args.url || href.includes(args.url));
if (ok) break;
}
if (Date.now() > end) throw new Error(`waited ${bound / 1000}s and the page still ${args.text ? `doesn't show "${args.text}"` : args.textGone ? `shows "${args.textGone}"` : `isn't at ${args.url}`}`);
await sleep(250);
}
await settle(t);
return { content: [text(["Done waiting.", "", await page(t)].join("\n"))] };
},
async browser_screenshot(session, args) {
const t = await ready(session, args);
if (t.dialog) return fail(notices(t).join("\n"));
const params = { format: args.png ? "png" : "jpeg", ...(args.png ? {} : { quality: 80 }) };
if (args.ref) {
const el = await find(t, args.ref);
await send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: el.backend }).catch(() => {});
const { model } = await send(t.tabId, "DOM.getBoxModel", { backendNodeId: el.backend });
const b = model.border;
const xs = [b[0], b[2], b[4], b[6]], ys = [b[1], b[3], b[5], b[7]];
const lm = await send(t.tabId, "Page.getLayoutMetrics");
const vv = lm.cssVisualViewport;
params.clip = { x: Math.min(...xs) + vv.pageX, y: Math.min(...ys) + vv.pageY, width: Math.max(1, Math.max(...xs) - Math.min(...xs)), height: Math.max(1, Math.max(...ys) - Math.min(...ys)), scale: 1 };
params.captureBeyondViewport = true;
} else if (args.fullPage) {
const lm = await send(t.tabId, "Page.getLayoutMetrics");
const c = lm.cssContentSize || lm.contentSize;
params.clip = { x: 0, y: 0, width: c.width, height: Math.min(c.height, 12000), scale: 1 };
params.captureBeyondViewport = true;
}
const shot = () => send(t.tabId, "Page.captureScreenshot", params);
let r = await Promise.race([shot(), sleep(8000).then(() => null)]);
if (!r) {
// a tab in the background isn't drawn: show it, then take it
await chrome.tabs.update(t.tabId, { active: true });
await sleep(300);
r = await shot();
}
return { content: [{ type: "image", data: r.data, mimeType: args.png ? "image/png" : "image/jpeg" }, text(await head(t))] };
},
async browser_evaluate(session, args) {
need(args, "script");
const t = await ready(session, args);
if (t.dialog) return fail(notices(t).join("\n"));
const src = String(args.script).trim();
const fn = /^(async\s+)?(function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/.test(src);
let r;
if (args.ref) {
const el = await find(t, args.ref);
r = await send(t.tabId, "Runtime.callFunctionOn", {
objectId: el.objectId, returnByValue: true, awaitPromise: true,
functionDeclaration: fn ? `function() { return (${src})(this); }` : `function() { return (${src}); }`,
});
} else {
r = await send(t.tabId, "Runtime.evaluate", { expression: fn ? `(${src})()` : src, returnByValue: true, awaitPromise: true, userGesture: true });
}
if (r.exceptionDetails) {
const d = r.exceptionDetails;
throw new Error("the script threw: " + ((d.exception && d.exception.description) || d.text));
}
let out = r.result.value === undefined ? (r.result.description || r.result.type) : JSON.stringify(r.result.value, null, 1);
if (out && out.length > 20000) out = out.slice(0, 20000) + "\n… (cut at 20000 characters)";
return { content: [text([out === undefined ? "undefined" : out, ...notices(t)].join("\n"))] };
},
async browser_text(session, args) {
const t = await ready(session, args);
if (t.dialog) return fail(notices(t).join("\n"));
const max = Math.min(Number(args.maxChars) || 40000, 200000);
const r = await send(t.tabId, "Runtime.evaluate", { expression: "document.body ? document.body.innerText : ''", returnByValue: true });
let s = String(r.result.value || "").replace(/\n{3,}/g, "\n\n").trim();
if (s.length > max) s = s.slice(0, max) + `\n… (cut at ${max} characters of ${s.length})`;
return { content: [text(`${await head(t)}\n\n${s || "(the page has no text)"}`)] };
},
async browser_console(session, args) {
const t = await ready(session, args);
const levels = args.level === "errors" ? ["error", "assert"] : args.level === "network" ? ["network"] : null;
let logs = t.logs.filter((l) => !levels || levels.includes(l.level));
const n = Math.min(Number(args.limit) || 50, 300);
logs = logs.slice(-n);
if (!logs.length) return { content: [text("Nothing logged since Magpie Browser started watching this tab.")] };
return { content: [text(logs.map((l) => `[${new Date(l.at).toISOString().slice(11, 19)}] ${l.level}: ${l.text}`).join("\n"))] };
},
async browser_dialog(session, args) {
const tabId = await tabFor(session, args);
const t = state(tabId);
await attach(tabId);
const accept = args.accept !== false;
if (t.dialog) {
const d = t.dialog;
await send(tabId, "Page.handleJavaScriptDialog", { accept, ...(args.promptText !== undefined ? { promptText: String(args.promptText) } : {}) });
t.dialog = null;
await settle(t);
return { content: [text(`${accept ? "Accepted" : "Dismissed"} the ${d.type} dialog ("${d.message}").\n\n` + await page(t))] };
}
t.answer = { accept, promptText: args.promptText !== undefined ? String(args.promptText) : undefined };
return { content: [text(`No dialog is open. The next one in t${tabId} will be ${accept ? "accepted" : "dismissed"}.`)] };
},
};
+197
View File
@@ -0,0 +1,197 @@
// The DevTools protocol over chrome.debugger, one attachment per tab. A
// tab stays attached while an agent works in it and is let go after a
// quiet spell, so Chrome's "is debugging this browser" bar is up only
// while it is used.
const IDLE_MS = 2 * 60 * 1000;
const LOG_KEPT = 300;
// tabId → what is known of the page while attached
const tabs = new Map();
export function state(tabId) {
let t = tabs.get(tabId);
if (!t) {
t = {
tabId, attached: false, attaching: null, idle: 0,
refs: new Map(), keys: new Map(), next: 1, doc: "",
logs: [], dialog: null, answer: null, chooser: null,
inflight: new Map(), lastNet: 0, loading: false,
stoppedByUser: false,
};
tabs.set(tabId, t);
}
return t;
}
export function forget(tabId) {
const t = tabs.get(tabId);
if (t) clearTimeout(t.idle);
tabs.delete(tabId);
}
export async function attach(tabId) {
const t = state(tabId);
clearTimeout(t.idle);
t.idle = setTimeout(() => detach(tabId), IDLE_MS);
if (t.attached) return t;
if (!t.attaching) {
t.attaching = (async () => {
try {
await chrome.debugger.attach({ tabId }, "1.3");
} catch (e) {
const m = String(e && e.message || e);
if (!/already attached/i.test(m)) throw new Error(why(m));
}
t.attached = true;
t.stoppedByUser = false;
await Promise.all([
send(tabId, "Page.enable"),
send(tabId, "Runtime.enable"),
send(tabId, "Network.enable"),
send(tabId, "DOM.enable"),
send(tabId, "Accessibility.enable"),
]);
await send(tabId, "Page.setInterceptFileChooserDialog", { enabled: false }).catch(() => {});
})().finally(() => { t.attaching = null; });
}
await t.attaching;
return t;
}
function why(m) {
if (/chrome:\/\/|chrome-extension:\/\/|Cannot access|Cannot attach/i.test(m)) {
return "Chrome doesn't let an extension control this page (a chrome:// page, the Web Store or another extension's page): open a web page in the tab first";
}
if (/Another debugger is already attached/i.test(m)) {
return "DevTools or another debugger is attached to this tab: close DevTools in it, or use another tab";
}
return m;
}
export async function detach(tabId) {
const t = tabs.get(tabId);
if (!t || !t.attached) return;
t.attached = false;
try { await chrome.debugger.detach({ tabId }); } catch {}
}
export function send(tabId, method, params = {}) {
return chrome.debugger.sendCommand({ tabId }, method, params).catch((e) => {
const m = String(e && e.message || e);
if (/Debugger is not attached|No tab with given id|detached/i.test(m)) {
const t = tabs.get(tabId);
if (t) t.attached = false;
}
throw new Error(m.replace(/^\{"code":-?\d+,"message":"(.*)"\}$/, "$1"));
});
}
// requests that never end on their own: a page with one open is still
// quiet
const STREAMING = new Set(["EventSource", "WebSocket", "Ping", "CSPViolationReport", "Preflight"]);
chrome.debugger.onEvent.addListener((src, method, p) => {
const t = tabs.get(src.tabId);
if (!t) return;
switch (method) {
case "Network.requestWillBeSent":
if (!STREAMING.has(p.type) && !/^data:|^blob:/.test(p.request.url)) t.inflight.set(p.requestId, Date.now());
t.lastNet = Date.now();
break;
case "Network.loadingFinished":
case "Network.loadingFailed":
t.inflight.delete(p.requestId);
t.lastNet = Date.now();
if (method === "Network.loadingFailed" && !p.canceled && p.type === "Document") log(t, "network", `failed: ${p.errorText}`);
break;
case "Network.responseReceived":
if (p.response.status >= 400) log(t, "network", `${p.response.status} ${p.type} ${p.response.url.slice(0, 300)}`);
// a streamed answer (server-sent events, a long poll) isn't waited for
if (/text\/event-stream/i.test(p.response.mimeType || "")) t.inflight.delete(p.requestId);
break;
case "Page.frameStartedLoading":
if (!p.frameId || p.frameId === t.mainFrame) t.loading = true;
break;
case "Page.loadEventFired":
t.loading = false;
break;
case "Page.frameNavigated":
if (!p.frame.parentId) {
t.mainFrame = p.frame.id;
t.inflight.clear();
}
break;
case "Runtime.consoleAPICalled": {
const text = (p.args || []).map((a) => a.value !== undefined ? String(a.value) : (a.description || a.type)).join(" ");
log(t, p.type === "warning" ? "warn" : p.type, text);
break;
}
case "Runtime.exceptionThrown": {
const d = p.exceptionDetails || {};
log(t, "error", (d.exception && d.exception.description) || d.text || "exception");
break;
}
case "Page.javascriptDialogOpening":
if (t.answer) {
const a = t.answer;
t.answer = null;
send(src.tabId, "Page.handleJavaScriptDialog", { accept: a.accept, promptText: a.promptText }).catch(() => {});
t.answered = { type: p.type, message: p.message, accept: a.accept };
} else {
t.dialog = { type: p.type, message: p.message, defaultPrompt: p.defaultPrompt };
}
break;
case "Page.javascriptDialogClosed":
t.dialog = null;
break;
case "Page.fileChooserOpened":
if (t.chooser) t.chooser(p);
break;
}
});
chrome.debugger.onDetach.addListener((src, reason) => {
const t = tabs.get(src.tabId);
if (!t) return;
t.attached = false;
// the user pressed Cancel on Chrome's bar: they want it stopped
if (reason === "canceled_by_user") t.stoppedByUser = true;
});
function log(t, level, text) {
t.logs.push({ at: Date.now(), level, text: String(text).slice(0, 2000) });
if (t.logs.length > LOG_KEPT) t.logs.splice(0, t.logs.length - LOG_KEPT);
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export { sleep };
// settle waits for the page to go quiet after an action: no load under
// way and no request open for a short spell, or until the bound.
export async function settle(t, bound = 2500, quiet = 400) {
const end = Date.now() + bound;
await sleep(60);
while (Date.now() < end) {
const now = Date.now();
for (const [id, at] of t.inflight) if (now - at > 10000) t.inflight.delete(id); // a long poll
if (!t.loading && t.inflight.size === 0 && now - t.lastNet >= quiet) return;
await sleep(80);
}
}
// waitLoad waits for the main frame to finish loading after a navigation.
export async function waitLoad(t, bound = 30000) {
const end = Date.now() + bound;
await sleep(100);
while (Date.now() < end) {
if (!t.loading) {
try {
const r = await send(t.tabId, "Runtime.evaluate", { expression: "document.readyState", returnByValue: true });
if (r.result.value === "complete" || r.result.value === "interactive") return true;
} catch {}
}
await sleep(150);
}
return false;
}
+3
View File
@@ -0,0 +1,3 @@
// The gateway this extension talks to. magpie writes this file when it
// writes the extension, with the address its gateway listens on.
export const GATEWAY = "ws://127.0.0.1:3425";
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 663 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

+111
View File
@@ -0,0 +1,111 @@
// Keys as Input.dispatchKeyEvent wants them. A press is a name ("Enter",
// "a", "ArrowDown") or a chord ("Control+a", "Meta+Shift+K").
import { send, sleep } from "./cdp.js";
const KEYS = {
Enter: { code: "Enter", keyCode: 13, text: "\r" },
Tab: { code: "Tab", keyCode: 9 },
Backspace: { code: "Backspace", keyCode: 8 },
Delete: { code: "Delete", keyCode: 46 },
Escape: { code: "Escape", keyCode: 27 },
Space: { key: " ", code: "Space", keyCode: 32, text: " " },
" ": { code: "Space", keyCode: 32, text: " " },
ArrowUp: { code: "ArrowUp", keyCode: 38 },
ArrowDown: { code: "ArrowDown", keyCode: 40 },
ArrowLeft: { code: "ArrowLeft", keyCode: 37 },
ArrowRight: { code: "ArrowRight", keyCode: 39 },
Home: { code: "Home", keyCode: 36 },
End: { code: "End", keyCode: 35 },
PageUp: { code: "PageUp", keyCode: 33 },
PageDown: { code: "PageDown", keyCode: 34 },
Insert: { code: "Insert", keyCode: 45 },
Shift: { code: "ShiftLeft", keyCode: 16 },
Control: { code: "ControlLeft", keyCode: 17 },
Alt: { code: "AltLeft", keyCode: 18 },
Meta: { code: "MetaLeft", keyCode: 91 },
};
for (let i = 1; i <= 12; i++) KEYS["F" + i] = { code: "F" + i, keyCode: 111 + i };
const ALIASES = {
return: "Enter", esc: "Escape", del: "Delete", up: "ArrowUp", down: "ArrowDown",
left: "ArrowLeft", right: "ArrowRight", space: "Space", ctrl: "Control",
control: "Control", cmd: "Meta", command: "Meta", meta: "Meta", option: "Alt",
alt: "Alt", shift: "Shift", pageup: "PageUp", pagedown: "PageDown",
backspace: "Backspace", tab: "Tab", enter: "Enter", escape: "Escape",
delete: "Delete", home: "Home", end: "End",
};
const MODS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
// what a chord with Control or Meta does on a Mac, where the page never
// sees the key turn into an edit
const MAC_COMMANDS = { a: "selectAll", c: "copy", x: "cut", v: "paste", z: "undo" };
function name(k) {
if (KEYS[k]) return k;
const a = ALIASES[k.toLowerCase()];
if (a) return a;
if (/^f\d{1,2}$/i.test(k)) return k.toUpperCase();
return k;
}
function describe(k, shift) {
const n = name(k);
if (KEYS[n]) return { key: KEYS[n].key || n, ...KEYS[n] };
if (n.length !== 1) throw new Error(`"${k}" isn't a key this knows: use a name like Enter, Tab, Escape, ArrowDown, PageDown, F5, or one character`);
const ch = shift ? n.toUpperCase() : n;
const up = n.toUpperCase();
let code = "";
if (/[a-z]/i.test(n)) code = "Key" + up;
else if (/[0-9]/.test(n)) code = "Digit" + n;
return { key: ch, code, keyCode: /[a-z0-9]/i.test(n) ? up.charCodeAt(0) : 0, text: ch };
}
const mac = /Mac/i.test(navigator.platform || navigator.userAgent);
// press presses one key or chord in the focused element.
export async function press(t, combo) {
const parts = String(combo).split("+").map((s) => s.trim());
if (parts.some((p) => p === "")) {
// "Control++" or a bare "+"
const i = parts.lastIndexOf("");
parts.splice(i - (i > 0 ? 1 : 0), 2, "+");
}
const keyName = parts.pop();
const mods = parts.map(name);
for (const m of mods) if (!(m in MODS)) throw new Error(`"${m}" isn't a modifier: use Control, Alt, Shift or Meta`);
let modifiers = mods.reduce((a, m) => a | MODS[m], 0);
const k = describe(keyName, !!(modifiers & 8));
const commands = [];
if (mac && (modifiers & 4) && MAC_COMMANDS[k.key.toLowerCase()]) commands.push(MAC_COMMANDS[k.key.toLowerCase()]);
let held = 0;
for (const m of mods) {
held |= MODS[m];
await send(t.tabId, "Input.dispatchKeyEvent", { type: "rawKeyDown", modifiers: held, key: m, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].keyCode });
}
// a chord with Control, Alt or Meta types no text
const typed = k.text && !(modifiers & 7);
await send(t.tabId, "Input.dispatchKeyEvent", {
type: typed ? "keyDown" : "rawKeyDown", modifiers, key: k.key, code: k.code,
windowsVirtualKeyCode: k.keyCode, nativeVirtualKeyCode: k.keyCode,
...(typed ? { text: k.text, unmodifiedText: k.text } : {}),
...(commands.length ? { commands } : {}),
});
await sleep(20);
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", modifiers, key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode });
for (const m of mods.reverse()) {
held &= ~MODS[m];
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", modifiers: held, key: m, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].keyCode });
}
}
// typeSlowly types text a key at a time, for a field that listens to
// each key (an autocomplete, a field that formats as you type).
export async function typeSlowly(t, text) {
for (const ch of String(text)) {
if (ch === "\n") { await press(t, "Enter"); continue; }
const k = /^[a-z0-9]$/i.test(ch) ? describe(ch.toLowerCase(), ch !== ch.toLowerCase()) : { key: ch, code: "", keyCode: 0, text: ch };
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyDown", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, text: k.text, unmodifiedText: k.text, modifiers: /[A-Z]/.test(ch) ? 8 : 0 });
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode });
await sleep(30 + Math.random() * 50);
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"manifest_version": 3,
"name": "Magpie Browser",
"version": "0.1.0",
"description": "Lets the agents you run through Magpie use this browser: your tabs, signed in to the sites you use.",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwjVk++2N/+l0PX53QSgXvBmDiyIOFXPDRTSo6l7HfM633QbDes2FXjS09l6hY33gsVX9eXE9O+94jQD2SVKSBn8V/EsL3f7mbNfkBqsZ4hYF3ogYxHUjJD6wjKHMFZQi54ArMZBI/psMUBbIjVTeuU9EGwnxoYU5umC8UHvEwkb4ZO0lprP3PGbHDjxrNi5fdFI8azVjyX0zlYlSw2wv0bCAZdkWuRoZWWgKdQwpdtRHrDQMnulWXT5DmNLYDpHgCreDrVaVLXzIAblSLOkZFo/T5xBiicmEbkWPbb8d3iE0OQStm1HYLdp4LLeKnnU6B7Kj/woOFt1uGIwoMqPzswIDAQAB",
"minimum_chrome_version": "116",
"permissions": ["debugger", "tabs", "tabGroups", "storage", "alarms"],
"background": { "service_worker": "background.js", "type": "module" },
"action": { "default_title": "Magpie Browser", "default_popup": "popup.html" },
"icons": { "16": "icon-16.png", "32": "icon-32.png", "48": "icon-48.png", "128": "icon-128.png" }
}
+37
View File
@@ -0,0 +1,37 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
:root { color-scheme: light dark; --fg: #1d1d1f; --mute: #6e6e73; --line: #d2d2d7; --bg: #fff; --ok: #34c759; --off: #8e8e93; }
@media (prefers-color-scheme: dark) { :root { --fg: #f5f5f7; --mute: #98989d; --line: #3a3a3c; --bg: #1c1c1e; } }
body { margin: 0; width: 280px; font: 13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; color: var(--fg); background: var(--bg); }
main { padding: 14px; }
h1 { font-size: 13px; font-weight: 600; margin: 0 0 10px; display: flex; align-items: center; gap: 8px; }
h1 img { width: 18px; height: 18px; }
.state { display: flex; align-items: center; gap: 8px; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--off); flex: none; }
.dot.on { background: var(--ok); }
p { margin: 8px 0 0; color: var(--mute); font-size: 12px; }
details { margin-top: 12px; border-top: 1px solid var(--line); padding-top: 10px; }
summary { cursor: default; color: var(--mute); font-size: 12px; }
label { display: block; margin-top: 8px; font-size: 12px; color: var(--mute); }
input { box-sizing: border-box; width: 100%; margin-top: 4px; padding: 5px 7px; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: var(--fg); font: inherit; }
button { margin-top: 8px; padding: 4px 10px; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: var(--fg); font: inherit; }
</style>
</head>
<body>
<main>
<h1><img src="icon-32.png" alt="">Magpie Browser</h1>
<div class="state"><span class="dot" id="dot"></span><span id="state">…</span></div>
<p id="hint"></p>
<details>
<summary>Gateway</summary>
<label for="gw">Magpie's address</label>
<input id="gw" spellcheck="false">
<button id="save">Save and reconnect</button>
</details>
</main>
<script type="module" src="popup.js"></script>
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
import { GATEWAY } from "./config.js";
const zh = /^zh/i.test(navigator.language);
const say = zh
? { on: "已连接 Magpie", off: "未连接 Magpie", onHint: "通过 Magpie 运行的智能体可以使用这个浏览器里的标签页。它们打开的标签页放在 “Magpie” 分组里。", offHint: "请确认 Magpie 正在运行。扩展会自动重连。" }
: { on: "Connected to Magpie", off: "Not connected to Magpie", onHint: "Agents you run through Magpie can use this browser's tabs. Tabs they open go in the \"Magpie\" group.", offHint: "Check that Magpie is running. The extension reconnects by itself." };
async function show() {
const { status } = await chrome.storage.session.get("status");
const on = !!(status && status.connected);
document.getElementById("dot").classList.toggle("on", on);
document.getElementById("state").textContent = on ? say.on : say.off;
document.getElementById("hint").textContent = on ? say.onHint : say.offHint;
}
const gw = document.getElementById("gw");
chrome.storage.local.get("gateway").then(({ gateway }) => { gw.value = gateway || GATEWAY; });
document.getElementById("save").addEventListener("click", async () => {
const v = gw.value.trim();
if (!v || v === GATEWAY) await chrome.storage.local.remove("gateway");
else await chrome.storage.local.set({ gateway: v.replace(/^http/, "ws") });
chrome.runtime.sendMessage({ type: "reconnect" }).catch(() => {});
});
chrome.storage.onChanged.addListener((c, area) => { if (area === "session" && c.status) show(); });
show();
+266
View File
@@ -0,0 +1,266 @@
// A page as the model reads it: its accessibility tree as indented text,
// each element it can act on given a ref (e3) that stays the element's
// from one snapshot to the next, for as long as the page keeps it.
import { send } from "./cdp.js";
const INTERACTIVE = new Set([
"button", "link", "textbox", "searchbox", "checkbox", "radio", "combobox",
"listbox", "option", "menuitem", "menuitemcheckbox", "menuitemradio", "tab",
"switch", "slider", "spinbutton", "treeitem", "textarea", "ComboBox",
"PopUpButton", "MenuListPopup", "DisclosureTriangle", "columnheader",
]);
// wrappers that say nothing of their own: their children are shown in
// their place
const TRANSPARENT = new Set([
"generic", "none", "presentation", "GenericContainer", "Section", "LayoutTable",
"LayoutTableRow", "LayoutTableCell", "Div", "Span", "Pre", "Abbr", "Ruby",
"LabelText", "group", "Canvas", "superscript", "subscript", "emphasis", "strong",
"paragraph", "Paragraph", "time", "mark", "code",
]);
const SKIP = new Set(["InlineTextBox", "LineBreak", "ListMarker"]);
const NAMED_MAX = 200;
const TEXT_MAX = 500;
const STATES = ["checked", "selected", "expanded", "pressed", "disabled", "required", "invalid", "focused", "readonly"];
// elements a page made clickable with a listener of its own (a div with a
// pointer cursor) that the accessibility tree calls generic
const CLICKABLE = `(() => {
const inter = 'a,button,input,select,textarea,summary,label,[role],[contenteditable=""],[contenteditable="true"]';
const out = [];
const all = document.querySelectorAll('body *');
for (let i = 0; i < all.length && out.length < 300; i++) {
const el = all[i];
if (el.closest(inter)) continue;
const cs = getComputedStyle(el);
if (cs.cursor !== 'pointer' && !el.hasAttribute('onclick')) continue;
const p = el.parentElement;
if (p && p !== document.body && getComputedStyle(p).cursor === 'pointer') continue;
const r = el.getBoundingClientRect();
if (r.width < 4 || r.height < 4 || cs.visibility === 'hidden') continue;
out.push(el);
}
return out;
})()`;
async function clickables(tabId) {
const ids = new Set();
try {
const r = await send(tabId, "Runtime.evaluate", { expression: CLICKABLE, objectGroup: "magpie-snap" });
if (!r.result || !r.result.objectId) return ids;
const props = await send(tabId, "Runtime.getProperties", { objectId: r.result.objectId, ownProperties: true });
await Promise.all(props.result.filter((p) => /^\d+$/.test(p.name) && p.value && p.value.objectId).map(async (p) => {
try {
const d = await send(tabId, "DOM.describeNode", { objectId: p.value.objectId });
ids.add(d.node.backendNodeId);
} catch {}
}));
} catch {} finally {
send(tabId, "Runtime.releaseObjectGroup", { objectGroup: "magpie-snap" }).catch(() => {});
}
return ids;
}
// frames of the page's own process, read beside the main one; a frame
// from another site runs in a process of its own, which this tab's
// debugger doesn't reach
async function frames(tabId) {
const out = new Map(); // owner element's backendNodeId → nodes
let tree;
try { tree = (await send(tabId, "Page.getFrameTree")).frameTree; } catch { return out; }
const kids = [];
(function walk(f) { for (const c of f.childFrames || []) { kids.push(c.frame); walk(c); } })(tree);
await Promise.all(kids.slice(0, 20).map(async (f) => {
try {
const owner = await send(tabId, "DOM.getFrameOwner", { frameId: f.id });
const { nodes } = await send(tabId, "Accessibility.getFullAXTree", { frameId: f.id });
out.set(owner.backendNodeId, nodes);
} catch {
try {
const owner = await send(tabId, "DOM.getFrameOwner", { frameId: f.id });
out.set(owner.backendNodeId, null);
} catch {}
}
}));
return out;
}
const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
const val = (v) => (v && v.value !== undefined && v.value !== null ? String(v.value) : "");
const q = (s) => JSON.stringify(s);
// take reads the page and gives each actionable element its ref.
export async function take(t, opts = {}) {
const tabId = t.tabId;
const [{ nodes }, clickable, inner, info] = await Promise.all([
send(tabId, "Accessibility.getFullAXTree"),
clickables(tabId),
frames(tabId),
send(tabId, "Runtime.evaluate", { expression: "[location.href, document.title]", returnByValue: true }).then((r) => r.result.value).catch(() => ["", ""]),
]);
const [url, title] = info;
// a new document starts its refs over; the same one keeps them
const doc = url.split("#")[0];
if (doc !== t.doc) {
t.doc = doc;
t.keys = new Map();
t.next = 1;
}
const refs = new Map();
const seen = new Map(); // role|name → how many so far, for the nth
const lines = [];
let interactive = 0;
const index = (list) => {
const m = new Map();
for (const n of list) m.set(n.nodeId, n);
return m;
};
const refFor = (role, name, backend) => {
const k = role + "|" + name;
const nth = seen.get(k) || 0;
seen.set(k, nth + 1);
const key = k + "|" + nth;
let ref = t.keys.get(key);
if (!ref || refs.has(ref)) {
ref = "e" + t.next++;
t.keys.set(key, ref);
}
refs.set(ref, { backend, role, name, key });
return ref;
};
// text a node's subtree reads as, for an element that has no name
const textOf = (byId, n, depth = 0) => {
if (!n || depth > 12) return "";
const r = val(n.role);
if (r === "StaticText") return val(n.name);
let s = "";
for (const c of n.childIds || []) {
const x = textOf(byId, byId.get(c), depth + 1);
if (x) s += (s ? " " : "") + x;
if (s.length > NAMED_MAX) break;
}
return s;
};
const walk = (byId, n, depth, named) => {
if (!n || depth > 60) return;
const role = val(n.role);
const children = () => { for (const c of n.childIds || []) walk(byId, byId.get(c), depth, named); };
if (SKIP.has(role)) return;
if (n.ignored) {
for (const c of n.childIds || []) walk(byId, byId.get(c), depth, named);
return;
}
const name = clip(val(n.name).replace(/\s+/g, " ").trim(), NAMED_MAX);
if (role === "StaticText") {
const text = name;
if (!text || (named && named.includes(text))) return;
if (!opts.interactive) lines.push(" ".repeat(depth) + "- text: " + clip(text, TEXT_MAX));
return;
}
if (role === "RootWebArea" || role === "WebArea") {
for (const c of n.childIds || []) walk(byId, byId.get(c), depth, named);
return;
}
const backend = n.backendDOMNodeId;
const isClick = backend && clickable.has(backend);
const props = {};
for (const p of n.properties || []) props[p.name] = p.value && p.value.value;
const acts = INTERACTIVE.has(role) || isClick || (props.focusable && props.editable);
if (TRANSPARENT.has(role) && !name && !acts) {
// an iframe's document is read under its element
if (backend && inner.has(backend)) return frame(backend, depth);
return children();
}
if (role === "Iframe" || role === "iframe") {
lines.push(" ".repeat(depth) + "- iframe" + (name ? " " + q(name) : ""));
if (backend && inner.has(backend)) frame(backend, depth + 1);
return;
}
let shown = isClick && TRANSPARENT.has(role) ? "clickable" : role;
let label = name;
if (isClick && !label) label = clip(textOf(byId, n).replace(/\s+/g, " ").trim(), NAMED_MAX);
let line = "- " + shown + (label ? " " + q(label) : "");
const states = [];
for (const s of STATES) {
const v = props[s];
if (v === true || v === "true" || (s === "checked" && v === "mixed")) states.push(s === "checked" && v === "mixed" ? "checked=mixed" : s);
}
if (props.level && role === "heading") states.unshift("level=" + props.level);
if (states.length) line += " [" + states.join(", ") + "]";
if (acts && backend && !props.disabled) {
line += " [ref=" + refFor(shown, label, backend) + "]";
interactive++;
} else if ((role === "image" || role === "img") && backend) {
line += " [ref=" + refFor(role, label, backend) + "]";
}
const v = val(n.value);
if (v && v !== name) line += ": " + q(clip(v.replace(/\s+/g, " "), TEXT_MAX));
if (!opts.interactive || line.includes("[ref=") || role === "heading") lines.push(" ".repeat(depth) + line);
const under = label ? (named ? named + "\n" + label : label) : named;
for (const c of n.childIds || []) walk(byId, byId.get(c), opts.interactive ? depth : depth + 1, under);
};
const frame = (backend, depth) => {
const list = inner.get(backend);
if (!list) {
lines.push(" ".repeat(depth) + "- (a frame from another site: not readable here; use a screenshot, or open its address in a tab)");
return;
}
const byId = index(list);
walk(byId, list.find((n) => !n.parentId) || list[0], depth, "");
};
const byId = index(nodes);
let root = nodes.find((n) => !n.parentId) || nodes[0];
if (opts.ref) {
const r = t.refs.get(opts.ref);
const n = r && nodes.find((x) => x.backendDOMNodeId === r.backend);
if (!n) throw new Error(`ref ${opts.ref} isn't on the page now: take a snapshot without ref`);
root = n;
}
walk(byId, root, 0, "");
// the old refs stay good for elements still on the page that this
// snapshot didn't show (a scoped one)
if (opts.ref) for (const [k, v] of refs) t.refs.set(k, v);
else t.refs = refs;
const max = opts.maxChars || 40000;
let body = lines.join("\n");
let cut = "";
if (body.length > max) {
const at = body.lastIndexOf("\n", max);
body = body.slice(0, at > 0 ? at : max);
cut = `\n… (cut at ${max} characters of ${lines.join("\n").length}: pass interactive: true for only what can be acted on, or ref to read one part)`;
}
return { url, title, text: body + cut, count: refs.size, interactive };
}
// find is the element a ref names: its node if still there, else the one
// element the page now has with the same role and name, else an error
// that says what the page has.
export async function find(t, ref) {
const m = /^(?:ref=)?(e\d+)$/i.exec(String(ref || "").trim());
if (!m) throw new Error(`"${ref}" isn't a ref: refs look like e12, from the latest snapshot`);
ref = m[1].toLowerCase();
const r = t.refs.get(ref);
if (!r) throw new Error(`ref ${ref} isn't in the latest snapshot of this tab: take a snapshot and use a ref from it`);
try {
const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: r.backend, objectGroup: "magpie-act" });
const c = await send(t.tabId, "Runtime.callFunctionOn", { objectId: o.object.objectId, functionDeclaration: "function(){return this.isConnected}", returnByValue: true });
if (c.result.value) return { ...r, ref, objectId: o.object.objectId };
} catch {}
// the page drew it again: the same role and name, if only one has it
await take(t, { maxChars: 1 });
const same = [...t.refs].filter(([, v]) => v.role === r.role && v.name === r.name);
if (same.length === 1) {
const [nref, v] = same[0];
const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: v.backend, objectGroup: "magpie-act" });
return { ...v, ref: nref, objectId: o.object.objectId };
}
if (same.length > 1) throw new Error(`${ref} (${r.role} "${r.name}") was redrawn and ${same.length} elements now match it: take a snapshot and pick one`);
throw new Error(`${ref} (${r.role} "${r.name}") is no longer on the page: take a snapshot`);
}
+121
View File
@@ -0,0 +1,121 @@
// Package browsermcp is `magpie mcp browser`: the browser MCP server
// (gateway.BrowserMCPPath) over stdio, for an agent that starts its MCP
// servers as commands. Each message is passed to the running gateway and
// its answer back; the process is one agent session, which goes on in the
// tab it was working in.
package browsermcp
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/gateway"
)
// Run serves stdin and stdout until stdin ends.
func Run(args []string) error {
if len(args) > 0 {
return fmt.Errorf("magpie mcp browser takes no arguments")
}
base := strings.TrimRight(os.Getenv("MAGPIE_GATEWAY"), "/")
if base == "" {
base = gateway.URL()
}
return serve(os.Stdin, os.Stdout, base)
}
func session() string {
b := make([]byte, 8)
rand.Read(b)
return "stdio-" + hex.EncodeToString(b)
}
type message struct {
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
}
func serve(in io.Reader, out io.Writer, base string) error {
s := &bridge{base: base, session: session(), client: &http.Client{Timeout: 2 * time.Minute}, out: out}
sc := bufio.NewScanner(in)
sc.Buffer(make([]byte, 64<<10), 16<<20)
var wg sync.WaitGroup
for sc.Scan() {
line := bytes.TrimSpace(sc.Bytes())
if len(line) == 0 {
continue
}
var m message
if json.Unmarshal(line, &m) != nil {
continue
}
body := append([]byte(nil), line...)
wg.Add(1)
// calls run side by side, as an agent may send the next before the
// last is answered (a ping during a long wait)
go func() {
defer wg.Done()
s.pass(m, body)
}()
}
wg.Wait()
return sc.Err()
}
type bridge struct {
base, session string
client *http.Client
mu sync.Mutex
out io.Writer
}
func (s *bridge) write(b []byte) {
s.mu.Lock()
defer s.mu.Unlock()
s.out.Write(append(bytes.TrimSpace(b), '\n'))
}
func (s *bridge) fail(id json.RawMessage, msg string) {
if len(id) == 0 {
return
}
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "error": map[string]any{"code": -32603, "message": msg}})
s.write(b)
}
func (s *bridge) pass(m message, body []byte) {
r, err := http.NewRequest(http.MethodPost, s.base+gateway.BrowserMCPPath, bytes.NewReader(body))
if err != nil {
s.fail(m.ID, err.Error())
return
}
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Accept", "application/json")
r.Header.Set("Authorization", "Bearer "+gateway.Token)
r.Header.Set(gateway.BrowserSessionHeader, s.session)
resp, err := s.client.Do(r)
if err != nil {
s.fail(m.ID, "magpie isn't running, so Magpie Browser can't be reached: start magpie ("+err.Error()+")")
return
}
defer resp.Body.Close()
b, _ := io.ReadAll(io.LimitReader(resp.Body, 128<<20))
if len(m.ID) == 0 || resp.StatusCode == http.StatusAccepted {
return
}
if resp.StatusCode != http.StatusOK {
s.fail(m.ID, fmt.Sprintf("magpie answered %d: %s", resp.StatusCode, strings.TrimSpace(string(b))))
return
}
s.write(b)
}
+66
View File
@@ -0,0 +1,66 @@
package browsermcp
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/gateway"
)
// Each line goes to the gateway's browser server with this process's
// session, and its answer comes back a line; a notification is answered
// nothing, and a gateway that can't be reached is said so, by id.
func TestBridgePassesLinesWithItsSession(t *testing.T) {
var mu sync.Mutex
var sessions []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != gateway.BrowserMCPPath || r.Header.Get("Authorization") != "Bearer "+gateway.Token {
http.Error(w, "wrong", 400)
return
}
mu.Lock()
sessions = append(sessions, r.Header.Get(gateway.BrowserSessionHeader))
mu.Unlock()
b, _ := io.ReadAll(r.Body)
var m struct {
ID json.RawMessage
Method string
}
json.Unmarshal(b, &m)
if len(m.ID) == 0 {
w.WriteHeader(http.StatusAccepted)
return
}
json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": map[string]any{"method": m.Method}})
}))
defer srv.Close()
in := strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize"}` + "\n" +
`{"jsonrpc":"2.0","method":"notifications/initialized"}` + "\n\n" +
`{"jsonrpc":"2.0","id":"b","method":"tools/list"}` + "\n")
var out bytes.Buffer
if err := serve(in, &out, srv.URL); err != nil {
t.Fatal(err)
}
lines := strings.Split(strings.TrimSpace(out.String()), "\n")
if len(lines) != 2 || !strings.Contains(out.String(), `"method":"initialize"`) || !strings.Contains(out.String(), `"id":"b"`) {
t.Fatalf("out: %q", out.String())
}
if len(sessions) != 3 || sessions[0] == "" || sessions[0] != sessions[1] || sessions[1] != sessions[2] {
t.Fatalf("sessions: %q", sessions)
}
out.Reset()
srv.Close()
if err := serve(strings.NewReader(`{"jsonrpc":"2.0","id":7,"method":"tools/list"}`+"\n"), &out, srv.URL); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), `"id":7`) || !strings.Contains(out.String(), "magpie isn't running") {
t.Fatalf("gateway gone: %q", out.String())
}
}
+4
View File
@@ -15,6 +15,7 @@ import (
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/browsermcp"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/claudebridge"
"github.com/yetone/magpie/internal/claudetui"
@@ -330,6 +331,9 @@ func run(args []string) error {
if len(args) > 0 {
switch args[0] {
case "mcp":
if len(args) > 1 && args[1] == "browser" {
return browsermcp.Run(args[2:])
}
return imagemcp.Run(args[1:])
case "claude-mcp-helper": // internal: stdio MCP subprocess spawned by Claude Code
return claudebridge.RunMCP(args[1:])
+284
View File
@@ -0,0 +1,284 @@
package gateway
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"strconv"
"sync"
"time"
"github.com/coder/websocket"
"github.com/yetone/magpie/internal/browserext"
)
// Magpie Browser: the agents magpie serves use the user's own browser,
// its tabs signed in to whatever the user is, through the Magpie Browser
// extension (internal/browserext). Not a browser of magpie's own: a fresh
// profile is signed in to nothing, and an agent's own browser tool stops
// working when its account changes.
//
// The extension holds a WebSocket to BrowserExtensionPath, taken only from
// its own origin on this computer. An agent calls the tools at
// BrowserMCPPath (Streamable HTTP, or `magpie mcp browser` over stdio),
// and each call is handed to the extension, which carries it out with the
// DevTools protocol in the tab and answers with MCP content. Only this
// computer's agents may: unlike the other servers of magpie's own, it is
// never served to another machine, shared or not, since it acts as the
// user wherever they are signed in.
// BrowserMCPPath is where the browser MCP server is served.
const BrowserMCPPath = "/mcp/magpie/browser"
// BrowserExtensionPath is where the extension connects.
const BrowserExtensionPath = "/v1/magpie/browser/extension"
// BrowserStatusPath tells whether the extension is connected.
const BrowserStatusPath = "/v1/magpie/browser"
// BrowserSessionHeader names the agent session a call is from, so each
// one goes on in the tab it was working in; `magpie mcp browser` sends one
// a process.
const BrowserSessionHeader = "X-Magpie-Browser-Session"
// browserCallWait is how long a call waits for the extension: a
// browser_wait waits up to 60s, a load 30s, and each acts then waits for the
// page to settle.
const browserCallWait = 100 * time.Second
// browserRelay is the extensions connected, the last one first served.
type browserRelay struct {
mu sync.Mutex
conns []*browserConn
pending map[string]chan json.RawMessage
next uint64
}
type browserConn struct {
c *websocket.Conn
version string
agent string
since time.Time
wmu sync.Mutex
}
func (c *browserConn) send(ctx context.Context, v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
c.wmu.Lock()
defer c.wmu.Unlock()
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
return c.c.Write(ctx, websocket.MessageText, b)
}
func (b *browserRelay) current() *browserConn {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.conns) == 0 {
return nil
}
return b.conns[len(b.conns)-1]
}
func (b *browserRelay) add(c *browserConn) {
b.mu.Lock()
b.conns = append(b.conns, c)
b.mu.Unlock()
}
func (b *browserRelay) remove(c *browserConn) {
b.mu.Lock()
for i, x := range b.conns {
if x == c {
b.conns = append(b.conns[:i], b.conns[i+1:]...)
break
}
}
b.mu.Unlock()
}
func (b *browserRelay) answered(id string, result json.RawMessage) {
b.mu.Lock()
ch := b.pending[id]
delete(b.pending, id)
b.mu.Unlock()
if ch != nil {
ch <- result
}
}
// call hands a tool call to the extension and waits for its MCP result.
func (b *browserRelay) call(ctx context.Context, session, tool string, args json.RawMessage) (json.RawMessage, error) {
c := b.current()
if c == nil {
return nil, errBrowserAway
}
b.mu.Lock()
if b.pending == nil {
b.pending = map[string]chan json.RawMessage{}
}
b.next++
id := strconv.FormatUint(b.next, 10)
ch := make(chan json.RawMessage, 1)
b.pending[id] = ch
b.mu.Unlock()
defer func() {
b.mu.Lock()
delete(b.pending, id)
b.mu.Unlock()
}()
if len(args) == 0 || string(args) == "null" {
args = json.RawMessage("{}")
}
if err := c.send(ctx, map[string]any{"id": id, "session": session, "tool": tool, "args": args}); err != nil {
return nil, errors.New("couldn't reach Magpie Browser: " + err.Error())
}
t := time.NewTimer(browserCallWait)
defer t.Stop()
select {
case r := <-ch:
return r, nil
case <-t.C:
return nil, errors.New("Magpie Browser didn't answer in " + browserCallWait.String() + ": the page may be stuck; take a snapshot or a screenshot to see where it is")
case <-ctx.Done():
return nil, ctx.Err()
}
}
var errBrowserAway = errors.New("Magpie Browser isn't connected, so there is no browser to use. Ask the user to set it up: magpie's Library → Magpie Browser → Set up, which loads the extension in Chrome, Edge or another Chromium browser. Once installed it connects by itself whenever that browser and magpie are both running.")
// browserExtension takes the extension's WebSocket.
func (s *Server) browserExtension(w http.ResponseWriter, r *http.Request) {
if !local(r) || !loopbackHost(r.Host) || r.Header.Get("Origin") != browserext.Origin {
http.Error(w, "only the Magpie Browser extension, on this computer, connects here", http.StatusForbidden)
return
}
ws, err := websocket.Accept(w, r, &websocket.AcceptOptions{OriginPatterns: []string{"chrome-extension://" + browserext.ID}})
if err != nil {
log.Printf("browser extension socket: %v", err)
return
}
ws.SetReadLimit(64 << 20) // a full-page screenshot
c := &browserConn{c: ws, since: time.Now()}
ctx := r.Context()
defer ws.CloseNow()
added := false
defer func() {
if added {
s.browser.remove(c)
log.Printf("Magpie Browser disconnected")
}
}()
for {
_, data, err := ws.Read(ctx)
if err != nil {
return
}
var m struct {
Type string `json:"type"`
ID string `json:"id"`
Result json.RawMessage `json:"result"`
Version string `json:"version"`
Agent string `json:"agent"`
}
if json.Unmarshal(data, &m) != nil {
continue
}
switch {
case m.Type == "hello":
c.version, c.agent = m.Version, m.Agent
if !added {
s.browser.add(c)
added = true
log.Printf("Magpie Browser %s connected", m.Version)
}
case m.Type == "ping":
c.send(ctx, map[string]string{"type": "pong"})
case m.ID != "":
s.browser.answered(m.ID, m.Result)
}
}
}
// browserStatus says whether the extension is connected, for the GUI.
func (s *Server) browserStatus(w http.ResponseWriter, r *http.Request) {
if !local(r) || fromBrowser(r) {
http.Error(w, "Magpie Browser's state is told to this computer's magpie only", http.StatusForbidden)
return
}
out := map[string]any{"connected": false, "version": browserext.Version()}
if c := s.browser.current(); c != nil {
out["connected"] = true
out["extension"] = c.version
out["browser"] = c.agent
out["since"] = c.since
}
writeJSON(w, http.StatusOK, out)
}
func (s *Server) browserMCP(w http.ResponseWriter, r *http.Request) {
// never another machine's, a gateway key or not: the tools act as the
// user wherever their browser is signed in; and no web page's, whatever
// Settings lists
if !local(r) || fromBrowser(r) {
http.Error(w, "magpie's browser MCP server answers agents on this computer only", http.StatusForbidden)
return
}
serveMCP(w, r, "magpie's browser", "magpie-browser", 1<<20, s.browserMCPCall)
}
func (s *Server) browserMCPCall(r *http.Request, m mcpMessage) (any, map[string]any) {
switch m.Method {
case "initialize":
return map[string]any{
"protocolVersion": mcpVersion(m),
"capabilities": map[string]any{"tools": map[string]any{}},
"serverInfo": map[string]any{"name": "magpie-browser", "title": "Magpie Browser", "version": Version},
"instructions": browserInstructions,
}, nil
case "ping":
return map[string]any{}, nil
case "tools/list":
return map[string]any{"tools": browserTools()}, nil
case "tools/call":
var p struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if err := json.Unmarshal(m.Params, &p); err != nil {
return nil, map[string]any{"code": -32602, "message": "invalid params: " + err.Error()}
}
if !browserToolNamed(p.Name) {
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name}
}
out, err := s.browser.call(r.Context(), browserSession(r), p.Name, p.Arguments)
if err != nil {
return toolResult(err.Error(), true), nil
}
var result map[string]any
if json.Unmarshal(out, &result) != nil || result["content"] == nil {
return toolResult("Magpie Browser answered with something that isn't a tool result: update it (magpie's Library → Magpie Browser)", true), nil
}
return result, nil
}
return nil, map[string]any{"code": -32601, "message": "method not found: " + m.Method}
}
// browserSession is which agent session a call is from: the header the
// stdio server sends, else the MCP session, else the agent.
func browserSession(r *http.Request) string {
for _, h := range []string{BrowserSessionHeader, "Mcp-Session-Id"} {
if v := boundedSession(r.Header.Get(h)); v != "" {
return v
}
}
if a := callerOf(r).agent; a != "" {
return "agent:" + a
}
return "default"
}
+223
View File
@@ -0,0 +1,223 @@
package gateway
import (
"bytes"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/browserext"
)
// The fixture page the real browser works in, served from this test.
const browserFixture = `<!doctype html>
<title>Fixture</title>
<h1>Magpie fixture</h1>
<input aria-label="Name" id="name">
<button onclick="out.textContent = 'clicked ' + document.getElementById('name').value">Go</button>
<select aria-label="Colour" onchange="out.textContent = 'colour ' + this.value"><option value="r">Red</option><option value="g">Green</option></select>
<button onmouseover="out.textContent = 'hovered'">Hover me</button>
<input type="file" aria-label="Upload" onchange="out.textContent = 'file ' + this.files[0].name">
<button id="src">Drag me</button> <button id="dst">Drop here</button>
<button onclick="alert('hello')">Alert</button>
<button onclick="out.textContent = confirm('sure?') ? 'confirmed' : 'declined'">Confirm</button>
<button onclick="console.error('boom from the page')">Log</button>
<button onclick="setTimeout(() => out.textContent = 'later', 400)">Later</button>
<a href="/two" target="_blank">Open two</a>
<div id="out" role="status"></div>
<div style="height: 4000px"></div>
<p>Bottom of the page</p>
<script>
const out = document.getElementById('out');
let down = null;
document.addEventListener('mousedown', (e) => { down = e.target.id; });
document.addEventListener('mouseup', (e) => { if (down === 'src' && e.target.id === 'dst') out.textContent = 'dropped'; down = null; });
</script>`
// Magpie Browser in a real Chromium: the extension magpie writes, loaded
// as a user loads it, connects to the gateway, and every tool an agent
// calls is carried out in a real tab. Set MAGPIE_BROWSER_CHROME to a
// Chromium that takes --load-extension (Chrome for Testing, as Playwright
// has it) to run it.
func TestBrowserToolsInARealBrowser(t *testing.T) {
chrome := os.Getenv("MAGPIE_BROWSER_CHROME")
if chrome == "" {
t.Skip("MAGPIE_BROWSER_CHROME names no Chromium")
}
fresh(t)
s := New()
srv := httptest.NewServer(lanGuard(s.Handler()))
t.Cleanup(srv.Close)
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if r.URL.Path == "/two" {
io.WriteString(w, "<!doctype html><title>Two</title><h1>Page two</h1>")
return
}
io.WriteString(w, browserFixture)
}))
t.Cleanup(site.Close)
ext := t.TempDir()
if err := browserext.Write(ext, srv.URL); err != nil {
t.Fatal(err)
}
profile := t.TempDir()
cmd := exec.Command(chrome, "--headless=new", "--user-data-dir="+profile,
"--disable-extensions-except="+ext, "--load-extension="+ext,
"--no-first-run", "--no-default-browser-check", "--disable-gpu", "--remote-debugging-port=0",
// with the test's own HOME there is no keychain (macOS) or keyring
// (Linux), and Chrome waits on it before the extension's storage
// answers
"--use-mock-keychain", "--password-store=basic", "about:blank")
var logs bytes.Buffer
cmd.Stdout, cmd.Stderr = &logs, &logs
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
defer cmd.Wait()
defer cmd.Process.Kill()
if t.Failed() {
t.Logf("chromium said:\n%s", logs.String())
// what it runs: is the extension's worker among them
if port, err := os.ReadFile(filepath.Join(profile, "DevToolsActivePort")); err == nil {
if resp, err := http.Get("http://127.0.0.1:" + strings.SplitN(string(port), "\n", 2)[0] + "/json/list"); err == nil {
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Logf("its targets: %s", b)
}
}
}
})
for deadline := time.Now().Add(60 * time.Second); s.browser.current() == nil; {
if time.Now().After(deadline) {
t.Fatal("the extension never connected")
}
time.Sleep(50 * time.Millisecond)
}
call := func(tool string, args map[string]any) imageReply {
t.Helper()
req, _ := http.NewRequest(http.MethodPost, srv.URL+BrowserMCPPath, strings.NewReader(imageToolCall(tool, args)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
req.Header.Set(BrowserSessionHeader, "e2e")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
var m imageReply
if resp.StatusCode != 200 || json.Unmarshal(b, &m) != nil || m.Error != nil || len(m.Result.Content) == 0 {
t.Fatalf("%s: %d %s", tool, resp.StatusCode, b)
}
return m
}
// ok calls a tool that should work and answers with its text
ok := func(tool string, args map[string]any, want ...string) string {
t.Helper()
m := call(tool, args)
var said []string
for _, c := range m.Result.Content {
said = append(said, c.Text)
}
out := strings.Join(said, "\n")
if m.Result.IsError {
t.Fatalf("%s %v failed: %s", tool, args, out)
}
for _, w := range want {
if !strings.Contains(out, w) {
t.Fatalf("%s %v doesn't say %q:\n%s", tool, args, w, out)
}
}
return out
}
ref := func(page, role, name string) string {
t.Helper()
m := regexp.MustCompile(`- ` + role + ` "` + regexp.QuoteMeta(name) + `"(?: \[[a-z=, ]+\])? \[ref=(e\d+)\]`).FindStringSubmatch(page)
if m == nil {
t.Fatalf("no %s %q with a ref in:\n%s", role, name, page)
}
return m[1]
}
shows := func(want string) {
t.Helper()
ok("browser_evaluate", map[string]any{"script": "() => document.getElementById('out').textContent"}, want)
}
page := ok("browser_tabs", map[string]any{"action": "new", "url": site.URL}, "Opened t", "Tab t", "Fixture", "Magpie fixture")
ok("browser_tabs", nil, "* t", site.URL)
page = ok("browser_snapshot", nil, `heading "Magpie fixture"`)
ok("browser_snapshot", map[string]any{"interactive": true}, `button "Go"`)
ok("browser_type", map[string]any{"ref": ref(page, "textbox", "Name"), "text": "Ada"}, "Typed into")
ok("browser_click", map[string]any{"ref": ref(page, "button", "Go")}, "Clicked", "clicked Ada")
ok("browser_press", map[string]any{"key": "Backspace", "ref": ref(page, "textbox", "Name")}, "Pressed Backspace")
ok("browser_click", map[string]any{"ref": ref(page, "button", "Go")}, "clicked Ad")
ok("browser_type", map[string]any{"ref": ref(page, "textbox", "Name"), "text": "Bo", "slowly": true, "clear": false})
ok("browser_click", map[string]any{"ref": ref(page, "button", "Go")}, "clicked AdBo")
ok("browser_select", map[string]any{"ref": ref(page, "combobox", "Colour"), "values": []string{"Green"}}, `Chose "Green"`)
shows("colour g")
ok("browser_hover", map[string]any{"ref": ref(page, "button", "Hover me")}, "Hovering")
shows("hovered")
ok("browser_drag", map[string]any{"from": ref(page, "button", "Drag me"), "to": ref(page, "button", "Drop here")}, "Dragged")
shows("dropped")
file := filepath.Join(t.TempDir(), "notes.txt")
os.WriteFile(file, []byte("hi"), 0o600)
ok("browser_upload", map[string]any{"ref": ref(page, `\w+`, "Upload"), "paths": []string{file}}, "Chose 1 file")
shows("file notes.txt")
ok("browser_click", map[string]any{"ref": ref(page, "button", "Later")})
ok("browser_wait", map[string]any{"text": "later"}, "Done waiting")
ok("browser_wait", map[string]any{"seconds": 0.2}, "Waited")
ok("browser_click", map[string]any{"ref": ref(page, "button", "Alert")}, `alert dialog is open: "hello"`)
ok("browser_dialog", nil, `Accepted the alert dialog ("hello")`)
ok("browser_dialog", map[string]any{"accept": false}, "next one", "dismissed")
ok("browser_click", map[string]any{"ref": ref(page, "button", "Confirm")}, "was dismissed as asked")
shows("declined")
ok("browser_click", map[string]any{"ref": ref(page, "button", "Log")})
ok("browser_console", map[string]any{"level": "errors"}, "boom from the page")
ok("browser_scroll", map[string]any{"direction": "down", "amount": 600}, "Scrolled down 600px")
ok("browser_evaluate", map[string]any{"script": "window.scrollY"}, "600")
ok("browser_text", nil, "Magpie fixture", "Bottom of the page")
shot := call("browser_screenshot", nil)
if shot.Result.IsError || shot.Result.Content[0].Type != "image" || shot.Result.Content[0].MimeType != "image/jpeg" {
t.Fatalf("screenshot: %+v", shot.Result)
}
if b, err := base64.StdEncoding.DecodeString(shot.Result.Content[0].Data); err != nil || !bytes.HasPrefix(b, []byte{0xff, 0xd8}) {
t.Fatalf("the screenshot isn't a JPEG: %v", err)
}
png := call("browser_screenshot", map[string]any{"ref": ref(page, "button", "Go"), "png": true})
if b, _ := base64.StdEncoding.DecodeString(png.Result.Content[0].Data); png.Result.IsError || !bytes.HasPrefix(b, []byte("\x89PNG")) {
t.Fatalf("an element's screenshot isn't a PNG: %+v", png.Result.Content[len(png.Result.Content)-1])
}
ok("browser_navigate", map[string]any{"url": site.URL + "/two"}, "Opened", "Page two")
ok("browser_navigate", map[string]any{"go": "back"}, "Went back", "Magpie fixture")
page = ok("browser_navigate", map[string]any{"go": "reload"}, "Reloaded", "Magpie fixture")
// a link that opens a tab: the session goes on in it
two := ok("browser_click", map[string]any{"ref": ref(page, "link", "Open two")}, "opened a new tab", "Page two")
id := regexp.MustCompile(`new tab, (t\d+)`).FindStringSubmatch(two)[1]
ok("browser_tabs", map[string]any{"action": "close", "tab": id}, "Closed "+id)
if m := call("browser_snapshot", map[string]any{"tab": id}); !m.Result.IsError {
t.Fatalf("a closed tab still answers: %+v", m.Result)
}
}
+236
View File
@@ -0,0 +1,236 @@
package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/yetone/magpie/internal/browserext"
)
func browserPost(h http.Handler, addr, body string, hdr ...string) *httptest.ResponseRecorder {
r := httptest.NewRequest(http.MethodPost, BrowserMCPPath, strings.NewReader(body))
r.RemoteAddr = addr
r.Host = "127.0.0.1:3425"
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Accept", "application/json, text/event-stream")
for i := 0; i+1 < len(hdr); i += 2 {
r.Header.Set(hdr[i], hdr[i+1])
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
// fakeExtension connects to the gateway at base as Magpie Browser does,
// and answers each call with answer.
func fakeExtension(t *testing.T, base string, answer func(id, session, tool string, args map[string]any) any) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
c, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(base, "http")+BrowserExtensionPath,
&websocket.DialOptions{HTTPHeader: http.Header{"Origin": {browserext.Origin}}})
if err != nil {
cancel()
t.Fatal(err)
}
done := make(chan struct{})
t.Cleanup(func() { cancel(); c.CloseNow(); <-done })
if err := c.Write(ctx, websocket.MessageText, []byte(`{"type":"hello","version":"0.1.0","agent":"Chrome/140"}`)); err != nil {
t.Fatal(err)
}
go func() {
defer close(done)
for {
_, b, err := c.Read(ctx)
if err != nil {
return
}
var m struct {
ID, Session, Tool string
Args map[string]any
}
if json.Unmarshal(b, &m) != nil || m.ID == "" {
continue
}
out, _ := json.Marshal(map[string]any{"id": m.ID, "result": answer(m.ID, m.Session, m.Tool, m.Args)})
c.Write(ctx, websocket.MessageText, out)
}
}()
}
// browserConnected waits until the gateway has the extension, as it adds
// it on its hello.
func browserConnected(t *testing.T, s *Server) {
t.Helper()
for deadline := time.Now().Add(10 * time.Second); s.browser.current() == nil; {
if time.Now().After(deadline) {
t.Fatal("the extension never connected")
}
time.Sleep(5 * time.Millisecond)
}
}
// An agent's call goes to the extension with its session, and the
// extension's MCP content comes back as the tool's result.
func TestBrowserMCPRelaysToTheExtension(t *testing.T) {
fresh(t)
s := New()
srv := httptest.NewServer(lanGuard(s.Handler()))
t.Cleanup(srv.Close)
type got struct {
session, tool string
args map[string]any
}
calls := make(chan got, 4)
fakeExtension(t, srv.URL, func(_, session, tool string, args map[string]any) any {
calls <- got{session, tool, args}
return map[string]any{"content": []any{map[string]any{"type": "text", "text": "Page: Example"}}}
})
browserConnected(t, s)
body := imageToolCall("browser_navigate", map[string]any{"url": "example.com"})
req, _ := http.NewRequest(http.MethodPost, srv.URL+BrowserMCPPath, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
req.Header.Set(BrowserSessionHeader, "s1")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
var m imageReply
if resp.StatusCode != 200 || json.Unmarshal(b, &m) != nil || m.Result.IsError || len(m.Result.Content) != 1 || m.Result.Content[0].Text != "Page: Example" {
t.Fatalf("%d %s", resp.StatusCode, b)
}
c := <-calls
if c.session != "s1" || c.tool != "browser_navigate" || c.args["url"] != "example.com" {
t.Fatalf("the extension was handed %+v", c)
}
st, err := http.Get(srv.URL + BrowserStatusPath)
if err != nil {
t.Fatal(err)
}
var status struct {
Connected bool
Extension, Browser string
}
json.NewDecoder(st.Body).Decode(&status)
st.Body.Close()
if !status.Connected || status.Extension != "0.1.0" || status.Browser != "Chrome/140" {
t.Fatalf("status: %+v", status)
}
}
// With no extension connected, the tools are still listed, and a call says
// how to set it up instead of waiting.
func TestBrowserMCPSaysWhenNoBrowser(t *testing.T) {
fresh(t)
h := lanGuard(New().Handler())
w := browserPost(h, "127.0.0.1:5000", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
var list struct {
Result struct{ Tools []struct{ Name string } }
}
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &list) != nil || len(list.Result.Tools) != len(browserTools()) {
t.Fatalf("tools/list: %d %s", w.Code, w.Body.String())
}
m := readImageReply(t, browserPost(h, "127.0.0.1:5000", imageToolCall("browser_snapshot", nil)))
if !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "Magpie Browser isn't connected") {
t.Fatalf("no browser: %+v", m)
}
w = browserPost(h, "127.0.0.1:5000", imageToolCall("browser_format_disk", nil))
if !strings.Contains(w.Body.String(), "unknown tool") {
t.Fatalf("an unknown tool: %s", w.Body.String())
}
}
// The tools act as the user wherever their browser is signed in: never
// for another computer, shared and with its key or not, and never for a
// web page on this one.
func TestBrowserMCPGuarded(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
h := lanGuard(New().Handler())
list := `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`
const there = "192.0.2.7:4000"
if w := browserPost(h, there, list); w.Code/100 == 2 {
t.Fatalf("not shared: %d %s", w.Code, w.Body.String())
}
_, secrets := newCaller(t, "Laptop")
if w := browserPost(h, there, list, "Authorization", "Bearer "+secrets[0]); w.Code != http.StatusForbidden {
t.Fatalf("shared, with a key: %d %s", w.Code, w.Body.String())
}
if w := browserPost(h, "127.0.0.1:5000", list, "Origin", "http://localhost:5173"); w.Code != http.StatusForbidden {
t.Fatalf("a page on this computer: %d %s", w.Code, w.Body.String())
}
for _, addr := range []string{there, "127.0.0.1:5000"} {
r := httptest.NewRequest(http.MethodGet, BrowserStatusPath, nil)
r.RemoteAddr = addr
r.Host = "127.0.0.1:3425"
r.Header.Set("Authorization", "Bearer "+secrets[0])
if addr != there {
r.Header.Set("Origin", "http://localhost:5173")
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Fatalf("status from %s: %d %s", addr, w.Code, w.Body.String())
}
}
}
// Only the extension itself, on this computer, may be the browser: a page
// that connects in its place would be handed every call, and could answer
// them.
func TestBrowserExtensionOnlyFromItsOrigin(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
h := lanGuard(New().Handler())
newCaller(t, "Laptop")
for _, c := range []struct{ addr, host, origin string }{
{"127.0.0.1:5000", "127.0.0.1:3425", "chrome-extension://abcdefghijklmnopabcdefghijklmnop"},
{"127.0.0.1:5000", "127.0.0.1:3425", "http://localhost:5173"},
{"127.0.0.1:5000", "127.0.0.1:3425", "null"},
{"127.0.0.1:5000", "127.0.0.1:3425", ""},
{"127.0.0.1:5000", "rebound.example:3425", browserext.Origin}, // DNS rebinding
{"192.0.2.7:4000", "192.0.2.1:3425", browserext.Origin}, // another computer
} {
r := httptest.NewRequest(http.MethodGet, BrowserExtensionPath, nil)
r.RemoteAddr, r.Host = c.addr, c.host
r.Header.Set("Connection", "Upgrade")
r.Header.Set("Upgrade", "websocket")
r.Header.Set("Sec-WebSocket-Version", "13")
r.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
if c.origin != "" {
r.Header.Set("Origin", c.origin)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Fatalf("%+v: %d %s", c, w.Code, w.Body.String())
}
}
}
// browser_* tool names the gateway lists are the ones the extension
// carries out.
func TestBrowserToolsAreTheExtensions(t *testing.T) {
src, err := browserext.File("background.js")
if err != nil {
t.Fatal(err)
}
for _, tl := range browserTools() {
name := tl.(map[string]any)["name"].(string)
if !strings.Contains(string(src), " async "+name+"(session, args) {") {
t.Errorf("%s isn't in background.js's TOOLS", name)
}
}
}
+133
View File
@@ -0,0 +1,133 @@
package gateway
// The browser MCP server's tools, carried out by the extension
// (internal/browserext/ext/background.js), whose argument names these
// schemas give.
const browserInstructions = `These tools use the user's own browser (Chrome, Edge or another Chromium browser with Magpie Browser installed): its real tabs, signed in to the sites the user is signed in to. Use it when a task needs the user's sessions or a real browser.
How to work:
- Start with browser_tabs or browser_snapshot. Calls go to the tab the user is looking at until you open or select another; tabs you open go in the "Magpie" tab group.
- browser_snapshot shows the page as an accessibility tree. Elements you can act on carry a ref (e12); pass it to browser_click, browser_type and the rest. Refs stay the element's while the page keeps it. Every action answers with the page after it, so you rarely need another snapshot.
- Prefer refs to browser_evaluate. Use browser_screenshot when the layout or an image matters.
- This is the user's browser: don't close tabs you didn't open, don't change their settings, and ask before sending, buying, posting or deleting anything on their behalf. When a site wants a sign-in, a captcha or a 2FA code, ask the user to do it in the tab, then go on.`
func browserTabArg() map[string]any {
return map[string]any{"type": "string", "description": "The tab to act in (t123, from browser_tabs). Without it: the tab this session works in, or the user's current tab."}
}
func browserRefArg(what string) map[string]any {
return map[string]any{"type": "string", "description": what + " (a ref from the latest snapshot, like e12)"}
}
func browserTool(name, title, desc string, readOnly bool, props map[string]any, required ...string) map[string]any {
props["tab"] = browserTabArg()
schema := map[string]any{"type": "object", "properties": props}
if len(required) > 0 {
schema["required"] = required
}
return map[string]any{
"name": name, "title": title, "description": desc, "inputSchema": schema,
"annotations": map[string]any{"readOnlyHint": readOnly, "openWorldHint": true},
}
}
func browserTools() []any {
str := func(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
boolean := func(desc string) map[string]any { return map[string]any{"type": "boolean", "description": desc} }
num := func(desc string) map[string]any { return map[string]any{"type": "number", "description": desc} }
enum := func(desc string, vals ...string) map[string]any {
return map[string]any{"type": "string", "enum": vals, "description": desc}
}
strs := func(desc string) map[string]any {
return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": desc}
}
return []any{
browserTool("browser_tabs", "Tabs", "List the browser's tabs, open a new one (in the Magpie tab group), switch the tab calls go to, or close one.", false, map[string]any{
"action": enum("list (default), new, select or close", "list", "new", "select", "close"),
"url": str("For new: the page to open in it."),
"background": boolean("For new: open it without bringing it to the front."),
}),
browserTool("browser_navigate", "Navigate", "Open a URL in the tab, or go back, forward or reload. Answers with the page once it has loaded.", false, map[string]any{
"url": str("The address to open (https:// is added when it has no scheme)."),
"go": enum("Instead of url: back, forward or reload.", "back", "forward", "reload"),
}),
browserTool("browser_snapshot", "Snapshot", "Read the page as an accessibility tree, each element you can act on with a ref.", true, map[string]any{
"interactive": boolean("Only the elements you can act on, and headings: a much shorter read of a long page."),
"ref": browserRefArg("Read only this part of the page"),
"maxChars": num("The most characters to return (default 60000)."),
}),
browserTool("browser_click", "Click", "Click an element, as the user would with the mouse.", false, map[string]any{
"ref": browserRefArg("The element"),
"double": boolean("Double-click."),
"button": enum("left (default), right or middle", "left", "right", "middle"),
"modifiers": map[string]any{"type": "array", "items": map[string]any{"type": "string", "enum": []string{"Alt", "Control", "Meta", "Shift"}}, "description": "Keys held while clicking."},
}, "ref"),
browserTool("browser_type", "Type", "Type text into a field or an editable element.", false, map[string]any{
"ref": browserRefArg("The field"),
"text": str("What to type."),
"clear": boolean("Replace what the field holds (default true); false adds to it."),
"submit": boolean("Press Enter after."),
"slowly": boolean("Type a key at a time, for a field that reacts to each key (an autocomplete)."),
}, "ref", "text"),
browserTool("browser_press", "Press key", "Press a key or a chord: Enter, Escape, Tab, ArrowDown, PageDown, Backspace, Control+a, Meta+Shift+k.", false, map[string]any{
"key": str("The key or chord."),
"ref": browserRefArg("Focus this element first"),
}, "key"),
browserTool("browser_hover", "Hover", "Move the mouse over an element, to open a menu or a tooltip.", false, map[string]any{
"ref": browserRefArg("The element"),
}, "ref"),
browserTool("browser_select", "Select option", "Choose options in a native select list, by value or label.", false, map[string]any{
"ref": browserRefArg("The list"),
"values": strs("The options to choose."),
}, "ref", "values"),
browserTool("browser_scroll", "Scroll", "Scroll the page or an element, or bring an element into view (ref with no direction).", false, map[string]any{
"direction": enum("down (default), up, left or right", "down", "up", "left", "right"),
"amount": num("Pixels; default most of the window."),
"ref": browserRefArg("Scroll inside this element, or into view without a direction"),
}),
browserTool("browser_drag", "Drag", "Drag one element onto another.", false, map[string]any{
"from": browserRefArg("What to drag"),
"to": browserRefArg("Where to drop it"),
}, "from", "to"),
browserTool("browser_upload", "Upload files", "Choose files in a file field, or in the picker a button opens.", false, map[string]any{
"ref": browserRefArg("The file field or the button that opens the picker"),
"paths": strs("The files' full paths on this computer."),
}, "ref", "paths"),
browserTool("browser_wait", "Wait", "Wait for text to show or go, for the address to change, or a number of seconds.", true, map[string]any{
"text": str("Wait until the page shows this text."),
"textGone": str("Wait until the page no longer shows this text."),
"url": str("Wait until the address contains this."),
"seconds": num("Just wait this long (at most 60)."),
"timeout": num("Give up after this many seconds (default 10, at most 60)."),
}),
browserTool("browser_screenshot", "Screenshot", "Take a screenshot of the window, the whole page or one element.", true, map[string]any{
"ref": browserRefArg("Only this element"),
"fullPage": boolean("The whole page, not only what the window shows."),
"png": boolean("PNG instead of JPEG."),
}),
browserTool("browser_evaluate", "Run script", "Run JavaScript in the page and return its JSON result. A function is called (with the element when ref is given); an expression is evaluated.", false, map[string]any{
"script": str("An expression, or a function like () => document.title or (el) => el.value."),
"ref": browserRefArg("The element the function is called with"),
}, "script"),
browserTool("browser_text", "Page text", "Read the page's visible text, without the tree.", true, map[string]any{
"maxChars": num("The most characters to return (default 40000)."),
}),
browserTool("browser_console", "Console", "Read the tab's console messages, script errors and failed requests since magpie started watching it.", true, map[string]any{
"level": enum("all (default), errors or network", "all", "errors", "network"),
"limit": num("The most recent messages to return (default 50)."),
}),
browserTool("browser_dialog", "Dialog", "Answer the page's alert, confirm or prompt dialog; with none open, answer the next one.", false, map[string]any{
"accept": boolean("Accept (default true) or dismiss."),
"promptText": str("For a prompt: the text to answer with."),
}),
}
}
func browserToolNamed(name string) bool {
for _, t := range browserTools() {
if t.(map[string]any)["name"] == name {
return true
}
}
return false
}
+7 -2
View File
@@ -439,7 +439,9 @@ type Server struct {
refusedThinking map[string]bool
subscription *subscriptionBridge
// imageStore is the image MCP server's jobs and images (image_mcp.go)
imageStore imageMCPStore
imageStore imageMCPStore
// browser is the Magpie Browser extensions connected (browser.go)
browser browserRelay
debug bool
trace trace // what routing did with each request, for the Gateway view
titlePrompts titlePrompts
@@ -885,6 +887,9 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc(SearchMCPPath, s.searchMCP)
mux.HandleFunc(VisionMCPPath, s.visionMCP)
mux.HandleFunc(ImageMCPPath, s.imageMCP)
mux.HandleFunc(BrowserMCPPath, s.browserMCP)
mux.HandleFunc("GET "+BrowserExtensionPath, s.browserExtension)
mux.HandleFunc("GET "+BrowserStatusPath, s.browserStatus)
mux.HandleFunc(ImageMCPFiles+"{name}", s.imageMCPFile)
mux.HandleFunc(ToolsMCPPath, s.toolsMCP)
mux.HandleFunc(ToolsMCPOne+"{plugin}", s.toolsMCPOne)
@@ -924,7 +929,7 @@ var catalogSize stamped[struct{}, int]
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return len(provider.Catalog()) }), "window": Window,
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, ImageMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
// which process serves, for another magpie on this computer to name it
// on its Routing page (#2606); not told to another machine
if local(r) {
+2 -1
View File
@@ -44,7 +44,8 @@ var readOnlyRefused = []string{
"GET /v1/videos/{id}/content", "GET /videos/{id}/content",
// MCP servers, plugins' and Codex's backends, Gemini, everything else
"POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}",
SearchMCPPath, VisionMCPPath, ImageMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}",
SearchMCPPath, VisionMCPPath, ImageMCPPath, ImageMCPFiles + "{name}",
BrowserMCPPath, "GET " + BrowserExtensionPath, "GET " + BrowserStatusPath, ToolsMCPPath, ToolsMCPOne + "{plugin}",
HubMCPPath + "{agent}", HubMCPAll, CodexPath + "/", "GET " + CodexCatalogPath,
"GET /v1beta/models", "POST /v1beta/models/{call...}", "/",
}
+4
View File
@@ -989,6 +989,7 @@ const I18N = {
"ChatGPT's image backend picks the model itself, whichever is named, so one GPT Image is listed": "ChatGPT 的生图后端自己决定用哪个模型,不管请求里写的是哪个,所以只列一个 GPT Image",
"ChatGPT picks the model": "ChatGPT 自己决定模型",
"Generate and edit images with the image model set in Magpie (Settings → Images), and make short videos with a video model set up in Magpie (Grok Imagine, Seedance), saved in the project.": "用 Magpie 设置的生图模型(设置 → 图像)生成和编辑图片,并可用 Magpie 里配置的视频模型(Grok Imagine、Seedance)生成短视频,保存在项目目录。",
"Use your own browser: your tabs, signed in to the sites you use. Open pages, click, type, upload, read and take screenshots, through the Magpie Browser extension.": "使用你自己的浏览器:你的标签页,登录着你常用的网站。通过 Magpie Browser 扩展打开网页、点击、输入、上传、读取和截图。",
"Observability": "可观测性",
"OTLP export": "OTLP 导出",
"Collector connection": "采集服务连接",
@@ -5275,6 +5276,7 @@ const I18N = {
"ChatGPT's image backend picks the model itself, whichever is named, so one GPT Image is listed": "ChatGPT 的生圖後端自己決定用哪個模型,不管請求裡寫的是哪個,所以只列一個 GPT Image",
"ChatGPT picks the model": "ChatGPT 自己決定模型",
"Generate and edit images with the image model set in Magpie (Settings → Images), and make short videos with a video model set up in Magpie (Grok Imagine, Seedance), saved in the project.": "用 Magpie 設定的生圖模型(設定 → 影像)生成和編輯圖片,並可用 Magpie 裡設定的影片模型(Grok Imagine、Seedance)生成短影片,儲存在專案目錄。",
"Use your own browser: your tabs, signed in to the sites you use. Open pages, click, type, upload, read and take screenshots, through the Magpie Browser extension.": "使用你自己的瀏覽器:你的分頁,登入著你常用的網站。透過 Magpie Browser 擴充功能開啟網頁、點擊、輸入、上傳、讀取和截圖。",
"Observability": "可觀測性",
"OTLP export": "OTLP 匯出",
"Collector connection": "採集服務連線",
@@ -9532,6 +9534,7 @@ const I18N = {
"ChatGPT's image backend picks the model itself, whichever is named, so one GPT Image is listed": "ChatGPT の画像生成バックエンドは、どのモデル名を指定してもモデルを自分で選ぶため、GPT Image は 1 つだけ表示されます",
"ChatGPT picks the model": "モデルは ChatGPT が選択",
"Generate and edit images with the image model set in Magpie (Settings → Images), and make short videos with a video model set up in Magpie (Grok Imagine, Seedance), saved in the project.": "Magpie で設定した画像モデル(設定 → 画像)で画像を生成・編集し、Magpie で設定した動画モデル(Grok Imagine、Seedance)で短い動画を作成します。プロジェクトに保存されます。",
"Use your own browser: your tabs, signed in to the sites you use. Open pages, click, type, upload, read and take screenshots, through the Magpie Browser extension.": "いつものブラウザを使います:あなたのタブで、普段のサイトにサインインしたまま。Magpie Browser 拡張機能を通じて、ページを開き、クリック、入力、アップロード、読み取り、スクリーンショットを行います。",
"Observability": "オブザーバビリティ",
"OTLP export": "OTLP エクスポート",
"Collector connection": "コレクターへの接続",
@@ -13804,6 +13807,7 @@ const I18N = {
"ChatGPT's image backend picks the model itself, whichever is named, so one GPT Image is listed": "Das Bild-Backend von ChatGPT wählt das Modell selbst, egal welches genannt wird, daher ist nur ein GPT Image aufgeführt",
"ChatGPT picks the model": "ChatGPT wählt das Modell",
"Generate and edit images with the image model set in Magpie (Settings → Images), and make short videos with a video model set up in Magpie (Grok Imagine, Seedance), saved in the project.": "Bilder mit dem in Magpie festgelegten Bildmodell (Einstellungen → Bilder) erzeugen und bearbeiten sowie kurze Videos mit einem in Magpie eingerichteten Videomodell (Grok Imagine, Seedance) erstellen, gespeichert im Projekt.",
"Use your own browser: your tabs, signed in to the sites you use. Open pages, click, type, upload, read and take screenshots, through the Magpie Browser extension.": "Deinen eigenen Browser nutzen: deine Tabs, angemeldet bei den Seiten, die du nutzt. Seiten öffnen, klicken, tippen, hochladen, lesen und Screenshots machen – über die Erweiterung Magpie Browser.",
"Observability": "Observability",
"OTLP export": "OTLP-Export",
"Collector connection": "Collector-Verbindung",
+44 -1
View File
@@ -5892,7 +5892,10 @@ magpie.plugin("library", (ctx) => {
ed.append(head);
if (x.description) ed.append(el("p", "mk-about", about(x)));
if (x.signIn) ed.append(el("p", "mk-hint", t("Each agent asks you to sign in, in the browser, the first time it uses it.")));
if (x.optIn) ed.append(el("p", "mk-hint", t("Pick the agents that may generate images: each image costs what the model set in Settings → Images charges.")));
if (x.name === "magpie-browser") {
ed.append(el("p", "mk-hint", t("Pick the agents that may use your browser: they act in your tabs, signed in as you are.")));
ed.append(browserSetup());
} else if (x.optIn) ed.append(el("p", "mk-hint", t("Pick the agents that may generate images: each image costs what the model set in Settings → Images charges.")));
const firsts = [];
for (const i of x.inputs || []) {
const f = field2("", i.placeholder || (i.where === "env" ? i.key : ""), (v) => { values[i.key] = v.trim(); });
@@ -5931,6 +5934,46 @@ magpie.plugin("library", (ctx) => {
if (firsts.length) requestAnimationFrame(() => firsts[0].focus());
}
// Magpie Browser's extension: whether it is connected, and setting it up
// in the user's own browser, where their sign-ins are
function browserSetup() {
const box = el("div", "mk-browser");
const state = el("div", "mk-browser-state");
const steps = el("ol", "mk-browser-steps");
const go = button(t("Set up the extension…"), "action", async () => {
go.disabled = true;
try {
draw(await api("library/browser/setup", {}));
steps.hidden = false;
} catch (e) { status(e.message, "err"); }
go.disabled = false;
});
const draw = (b) => {
state.replaceChildren();
const dot = el("span", "mk-browser-dot" + (b.connected ? " on" : ""));
state.append(dot, el("span", "", b.connected
? t("Connected to your browser") + (b.extension ? " · " + b.extension : "")
: b.written ? t("Not connected: load the folder below in your browser, and keep that browser open") : t("Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser")));
go.textContent = b.written ? t("Show the extension folder") : t("Set up the extension…");
steps.replaceChildren(
el("li", "", t("Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.")),
el("li", "", t("Turn on Developer mode.")),
el("li", "", t("Click Load unpacked and choose {dir}.", { dir: tilde(b.dir) })),
);
if (b.connected) steps.hidden = true;
else if (b.written) steps.hidden = false;
};
steps.hidden = true;
box.append(state, steps, go);
const poll = async () => {
if (!box.isConnected) return;
try { draw(await api("library/browser")); } catch {}
setTimeout(poll, 3000);
};
requestAnimationFrame(poll);
return box;
}
function extLink(href, text) {
const a = el("a", "mk-ext");
a.href = href;
@@ -130,6 +130,15 @@ magpie.strings({
"Copies updated": "副本已更新",
"It will be removed from the library and the agents it was given to.": "这将从资源库及使用它的 Agent 中移除它。",
"Pick the agents that may generate images: each image costs what the model set in Settings → Images charges.": "选择可以生图的 Agent:每张图按 设置 → 图像 里所选模型的价格计费。",
"Pick the agents that may use your browser: they act in your tabs, signed in as you are.": "选择可以使用你浏览器的 Agent:它们会在你的标签页里,以你的登录身份操作。",
"Set up the extension…": "安装扩展…",
"Show the extension folder": "打开扩展文件夹",
"Connected to your browser": "已连接到你的浏览器",
"Not connected: load the folder below in your browser, and keep that browser open": "未连接:在浏览器里加载下面的文件夹,并保持该浏览器打开",
"Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser": "未安装:在 Chrome、Edge、Arc、Brave 或其他 Chromium 浏览器里安装扩展",
"Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.": "在你日常使用的浏览器里打开 chrome://extensions(Edge 为 edge://extensions)。",
"Turn on Developer mode.": "打开「开发者模式」。",
"Click Load unpacked and choose {dir}.": "点击「加载已解压的扩展程序」,选择 {dir}。",
"For a server that asks you to sign in (OAuth): magpie signs in once, and every agent given it uses that sign-in": "用于需要登录(OAuth)的服务器:在 magpie 登录一次,分配到它的 agent 共用此登录",
"Opening the sign-in…": "正在打开登录…",
"Finish signing in in your browser…": "请在浏览器中完成登录…",
@@ -869,6 +878,15 @@ magpie.strings({
"Copies updated": "副本已更新",
"It will be removed from the library and the agents it was given to.": "這將從資源庫及使用它的 Agent 中移除它。",
"Pick the agents that may generate images: each image costs what the model set in Settings → Images charges.": "選擇可以生圖的 Agent:每張圖按 設定 → 影像 裡所選模型的價格計費。",
"Pick the agents that may use your browser: they act in your tabs, signed in as you are.": "選擇可以使用你瀏覽器的 Agent:它們會在你的分頁裡,以你的登入身分操作。",
"Set up the extension…": "安裝擴充功能…",
"Show the extension folder": "打開擴充功能資料夾",
"Connected to your browser": "已連線到你的瀏覽器",
"Not connected: load the folder below in your browser, and keep that browser open": "未連線:在瀏覽器裡載入下面的資料夾,並保持該瀏覽器開啟",
"Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser": "未安裝:在 Chrome、Edge、Arc、Brave 或其他 Chromium 瀏覽器裡安裝擴充功能",
"Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.": "在你日常使用的瀏覽器裡打開 chrome://extensions(Edge 為 edge://extensions)。",
"Turn on Developer mode.": "開啟「開發人員模式」。",
"Click Load unpacked and choose {dir}.": "點擊「載入未封裝項目」,選擇 {dir}。",
"For a server that asks you to sign in (OAuth): magpie signs in once, and every agent given it uses that sign-in": "用於需要登入(OAuth)的伺服器:在 magpie 登入一次,分配到它的 agent 共用此登入",
"Opening the sign-in…": "正在開啟登入…",
"Finish signing in in your browser…": "請在瀏覽器中完成登入…",
@@ -1603,6 +1621,15 @@ magpie.strings({
"The copy in {agents} differs from the library's skill. Click to copy it again.": "{agents} のコピーがライブラリのスキルと異なります。クリックしてコピーし直します。",
"Copies updated": "コピーを更新しました",
"Pick the agents that may generate images: each image costs what the model set in Settings → Images charges.": "画像を生成できるエージェントを選んでください:画像 1 枚ごとに、設定 → 画像 で選んだモデルの料金がかかります。",
"Pick the agents that may use your browser: they act in your tabs, signed in as you are.": "ブラウザを使えるエージェントを選んでください:あなたのタブで、あなたのサインインのまま操作します。",
"Set up the extension…": "拡張機能を設定…",
"Show the extension folder": "拡張機能のフォルダを表示",
"Connected to your browser": "ブラウザに接続しました",
"Not connected: load the folder below in your browser, and keep that browser open": "未接続:下のフォルダをブラウザで読み込み、そのブラウザを開いたままにしてください",
"Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser": "未設定:Chrome、Edge、Arc、Brave などの Chromium ブラウザに拡張機能を設定してください",
"Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.": "普段使っているブラウザで chrome://extensions(Edge では edge://extensions)を開きます。",
"Turn on Developer mode.": "デベロッパー モードをオンにします。",
"Click Load unpacked and choose {dir}.": "「パッケージ化されていない拡張機能を読み込む」をクリックし、{dir} を選びます。",
"For a server that asks you to sign in (OAuth): magpie signs in once, and every agent given it uses that sign-in": "サインインを求めるサーバー(OAuth)向け:magpie で一度サインインすれば、割り当てられたすべてのエージェントがそのサインインを使います",
"Opening the sign-in…": "サインインを開いています…",
"Finish signing in in your browser…": "ブラウザでサインインを完了してください…",
@@ -2340,6 +2367,15 @@ magpie.strings({
"The copy in {agents} differs from the library's skill. Click to copy it again.": "Die Kopie in {agents} weicht vom Skill der Bibliothek ab. Klicken, um sie neu zu kopieren.",
"Copies updated": "Kopien aktualisiert",
"Pick the agents that may generate images: each image costs what the model set in Settings → Images charges.": "Agenten wählen, die Bilder erzeugen dürfen: jedes Bild kostet, was das unter Einstellungen → Bilder festgelegte Modell berechnet.",
"Pick the agents that may use your browser: they act in your tabs, signed in as you are.": "Agenten wählen, die deinen Browser nutzen dürfen: Sie handeln in deinen Tabs, so angemeldet wie du.",
"Set up the extension…": "Erweiterung einrichten…",
"Show the extension folder": "Ordner der Erweiterung zeigen",
"Connected to your browser": "Mit deinem Browser verbunden",
"Not connected: load the folder below in your browser, and keep that browser open": "Nicht verbunden: Lade den Ordner unten in deinem Browser und lass diesen Browser offen",
"Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser": "Nicht eingerichtet: Richte die Erweiterung in Chrome, Edge, Arc, Brave oder einem anderen Chromium-Browser ein",
"Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.": "Öffne chrome://extensions (in Edge edge://extensions) in dem Browser, den du täglich nutzt.",
"Turn on Developer mode.": "Schalte den Entwicklermodus ein.",
"Click Load unpacked and choose {dir}.": "Klicke auf „Entpackte Erweiterung laden“ und wähle {dir}.",
"For a server that asks you to sign in (OAuth): magpie signs in once, and every agent given it uses that sign-in": "Für einen Server, der eine Anmeldung verlangt (OAuth): magpie meldet sich einmal an, und jeder Agent, dem er zugewiesen ist, nutzt diese Anmeldung",
"Opening the sign-in…": "Anmeldung wird geöffnet…",
"Finish signing in in your browser…": "Schließen Sie die Anmeldung im Browser ab…",
@@ -758,3 +758,8 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
.lib-ag.always::before { background: var(--card); box-shadow: 0 0 0 1px var(--line); }
.lib-ag.always::after { background: var(--fg-2); -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M5 7V5.5a3 3 0 0 1 6 0V7h.3a1 1 0 0 1 1 1v4.7a1 1 0 0 1-1 1H4.7a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1zm1.6 0h2.8V5.5a1.4 1.4 0 0 0-2.8 0z'/%3E%3C/svg%3E") center / 7px no-repeat; mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M5 7V5.5a3 3 0 0 1 6 0V7h.3a1 1 0 0 1 1 1v4.7a1 1 0 0 1-1 1H4.7a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1zm1.6 0h2.8V5.5a1.4 1.4 0 0 0-2.8 0z'/%3E%3C/svg%3E") center / 7px no-repeat; }
.lib-foldall[hidden] { display: none; }
.mk-sheet .mk-browser { grid-column: 1 / -1; display: grid; gap: 8px; justify-items: start; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; }
.mk-sheet .mk-browser-state { display: flex; align-items: center; gap: 8px; font-size: 12.5px; }
.mk-sheet .mk-browser-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--muted); flex: none; }
.mk-sheet .mk-browser-dot.on { background: var(--green); }
.mk-sheet .mk-browser-steps { margin: 0; padding-left: 18px; font-size: 12px; color: var(--muted); display: grid; gap: 2px; }
+83
View File
@@ -0,0 +1,83 @@
package gui
import (
"context"
"encoding/json"
"net/http"
"os"
"path/filepath"
"time"
"github.com/yetone/magpie/internal/browserext"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/settings"
)
// Magpie Browser's extension, as the Library page sets it up: written to a
// folder of magpie's, which the user loads in their own browser
// (chrome://extensions → Load unpacked), and connected or not as the
// gateway says.
func browserExtDir() string { return filepath.Join(settings.Dir(), "browser-extension") }
type browserJSON struct {
Dir string `json:"dir"`
Written bool `json:"written"`
Version string `json:"version"`
Connected bool `json:"connected"`
Extension string `json:"extension,omitempty"` // the connected one's version
Browser string `json:"browser,omitempty"`
}
func browserState(ctx context.Context) browserJSON {
out := browserJSON{Dir: browserExtDir(), Version: browserext.Version()}
if _, err := os.Stat(filepath.Join(out.Dir, "manifest.json")); err == nil {
out.Written = true
// kept as this magpie has it, and pointed at its gateway: the browser
// reads the folder again when it starts
browserext.Write(out.Dir, gateway.URL())
}
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, gateway.URL()+gateway.BrowserStatusPath, nil)
if err != nil {
return out
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return out
}
defer resp.Body.Close()
var st struct {
Connected bool `json:"connected"`
Extension string `json:"extension"`
Browser string `json:"browser"`
}
if resp.StatusCode == http.StatusOK && json.NewDecoder(resp.Body).Decode(&st) == nil {
out.Connected, out.Extension, out.Browser = st.Connected, st.Extension, st.Browser
}
return out
}
func browserRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/library/browser", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, browserState(r.Context()))
})
// Set up: the extension written, and its folder shown for Load unpacked
mux.HandleFunc("POST /api/library/browser/setup", func(rw http.ResponseWriter, r *http.Request) {
dir := browserExtDir()
if err := browserext.Write(dir, gateway.URL()); err != nil {
fail(rw, err)
return
}
st := browserState(r.Context())
var reveal string
if err := w.OpenFolder(dir); err != nil {
reveal = err.Error()
}
writeJSON(rw, struct {
browserJSON
RevealError string `json:"revealError,omitempty"`
}{st, reveal})
})
}
+1
View File
@@ -140,6 +140,7 @@ func revealable(v *library.View) []string {
}
func libraryRoutes(mux *http.ServeMux, w Windows) {
browserRoutes(mux, w)
mux.HandleFunc("GET /api/library", func(rw http.ResponseWriter, r *http.Request) {
v, err := libraryRead(nil, r.URL.Query().Get("glance") == "1")
if err != nil {
@@ -0,0 +1,145 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Magpie Browser's sheet in the Library's Discover: the agents it gives the
// browser act in the user's own tabs, so the sheet says so, and sets up the
// extension it needs in the browser the user is signed in to. Not set up,
// it offers Set up the extension…, which writes the folder and shows it,
// and the steps to load it there (chrome://extensions → Load unpacked);
// once the browser connects, the sheet says it is connected without being
// opened again. Every language, Chromium and WebKit, at 1100 and 420 wide,
// nothing running off to the side; no backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { strings } = require("./strings.cjs");
const assets = path.resolve(__dirname, "../assets");
const { I18N } = strings();
const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
const tr = (lang, s, vars = {}) => Object.entries(vars).reduce((o, [k, v]) => o.replace(`{${k}}`, v), lang === "en" ? s : I18N[lang]?.[s] ?? s);
const HOME = "/Users/tester";
const DIR = `${HOME}/.config/magpie/browser-extension`;
const ABOUT = "Use your own browser: your tabs, signed in to the sites you use. Open pages, click, type, upload, read and take screenshots, through the Magpie Browser extension.";
function fixture(lang) {
const st = { written: false, connected: false, setups: 0 };
const browser = () => ({ dir: DIR, written: st.written, version: "0.1.0", connected: st.connected, ...(st.connected ? { extension: "0.1.0", browser: "Chrome/141" } : {}) });
const route = async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/library") {
return json({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", mcp: `${HOME}/.claude.json`, skills: `${HOME}/.claude/skills` }],
instructions: { agents: [], sets: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], skills: [], problems: [],
});
}
if (url.pathname === "/api/library/market/servers") {
return json({ items: [
{ id: "magpie-browser", name: "magpie-browser", title: "Magpie Browser", publisher: "Magpie", description: ABOUT, transport: "stdio", runs: "magpie", featured: true, optIn: true, have: "" },
{ id: "fetch", name: "fetch", title: "Fetch", description: "Read the web.", transport: "stdio", runs: "uvx", featured: true, have: "" },
] });
}
if (url.pathname === "/api/library/market/skills") return json({ items: [] });
if (url.pathname === "/api/library/browser") return json(browser());
if (url.pathname === "/api/library/browser/setup" && req.method() === "POST") {
st.setups++;
st.written = true;
return json(browser());
}
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
const body = await fs.readFile(file).catch(() => null);
await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }));
};
return { route, st };
}
const wide = (page) => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": Magpie Browser's sheet sets up the extension in the user's browser", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const shots = [];
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
for (const [name, buf] of shots) await fs.writeFile(path.join(process.env.ARTIFACT_DIR, `${engine}-library-browser-setup-${name}.png`), buf);
}
await browser.close();
});
for (const lang of LANGS) {
const w = (s, vars) => tr(lang, s, vars);
for (const width of [1100, 420]) {
await t.test(`${lang} at ${width}px: set up, then connected`, async () => {
const f = fixture(lang);
const context = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", f.route);
await page.addInitScript(() => { localStorage.setItem("magpie.libTab", "mcp"); });
await page.goto("http://magpie.test/?view=library");
await page.locator('#view-library .mk[data-market="mcp"] .mk-card[data-id="magpie-browser"]').click();
const sheet = page.locator("#modal .mk-sheet");
await sheet.waitFor();
assert.equal((await sheet.locator(".mk-name.big").textContent()).trim(), "Magpie Browser");
assert.equal(await sheet.locator(".mk-about").textContent(), w(ABOUT));
const hints = await sheet.locator(".mk-hint").allTextContents();
assert(hints.includes(w("Pick the agents that may use your browser: they act in your tabs, signed in as you are.")), hints.join(" | "));
// not the image server's word about what each image costs
assert(!hints.some((h) => h.includes(w("Pick the agents that may generate images: each image costs what the model set in Settings → Images charges."))));
const box = sheet.locator(".mk-browser");
const state = box.locator(".mk-browser-state");
const go = box.locator("button");
await page.waitForFunction((s) => document.querySelector("#modal .mk-browser-state")?.textContent === s,
w("Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser"));
assert.equal((await go.textContent()).trim(), w("Set up the extension…"));
assert.equal(await box.locator(".mk-browser-steps").isVisible(), false);
assert.equal(await state.locator(".mk-browser-dot.on").count(), 0);
assert.equal(await wide(page), 0);
shots.push([`${lang}-${width}-new`, await sheet.screenshot()]);
await go.click();
await page.waitForFunction((s) => document.querySelector("#modal .mk-browser-state")?.textContent === s,
w("Not connected: load the folder below in your browser, and keep that browser open"));
assert.equal(f.st.setups, 1);
assert.equal((await go.textContent()).trim(), w("Show the extension folder"));
assert.deepEqual(await box.locator(".mk-browser-steps li").allTextContents(), [
w("Open chrome://extensions (edge://extensions in Edge) in the browser you use every day."),
w("Turn on Developer mode."),
w("Click Load unpacked and choose {dir}.", { dir: "~/.config/magpie/browser-extension" }),
]);
assert.equal(await box.locator(".mk-browser-steps").isVisible(), true);
// nothing in the sheet runs off its side, the folder's path included
assert.equal(await wide(page), 0);
assert.equal(await sheet.evaluate((e) => e.scrollWidth - e.clientWidth), 0);
shots.push([`${lang}-${width}-written`, await sheet.screenshot()]);
// the extension loaded: the sheet says so on its next look
f.st.connected = true;
await page.waitForFunction((s) => document.querySelector("#modal .mk-browser-state")?.textContent === s,
w("Connected to your browser") + " · 0.1.0", { timeout: 10000 });
assert.equal(await state.locator(".mk-browser-dot.on").count(), 1);
assert.equal(await box.locator(".mk-browser-steps").isVisible(), false);
assert.equal(await wide(page), 0);
shots.push([`${lang}-${width}-connected`, await sheet.screenshot()]);
assert.deepEqual(errors, []);
await context.close();
});
}
}
});
}
+1 -1
View File
@@ -231,7 +231,7 @@ func callLongest() time.Duration {
// Run serves MCP on stdin/stdout until stdin closes.
func Run(args []string) error {
if len(args) > 0 && args[0] != "image" {
return fmt.Errorf("unknown MCP server %q (there is: image)", args[0])
return fmt.Errorf("unknown MCP server %q (there are: image, browser)", args[0])
}
if len(args) > 1 {
w, err := options(args[1:])
+17 -2
View File
@@ -92,6 +92,7 @@ func secretEnv(key, label, where string) Input {
// package is published, its endpoint answers.
var featured = []MarketServer{
selfServer(),
browserServer(),
remoteServer("context7", "Context7", "Upstash", gh("upstash"), "https://mcp.context7.com/mcp",
"Up-to-date documentation and code examples for any library, straight into the prompt.", false,
Input{Key: "CONTEXT7_API_KEY", Where: "header", Label: "API key", Description: "Optional — raises the rate limit. From context7.com/dashboard", Secret: true, format: "{}"}),
@@ -175,6 +176,20 @@ func selfServer() MarketServer {
return m
}
// browserServerName is the name Magpie Browser's server is written under.
const browserServerName = "magpie-browser"
// browserServer is Magpie Browser: the agent uses the user's own browser,
// its tabs signed in to the sites they use, through the extension magpie
// sets up (gateway/browser.go). It acts as the user wherever they are
// signed in, so it is given only to the agents picked for it.
func browserServer() MarketServer {
m := localServer(browserServerName, "Magpie Browser", "Magpie", "https://usemagpie.ai/favicon.png", "https://usemagpie.ai",
"Use your own browser: your tabs, signed in to the sites you use. Open pages, click, type, upload, read and take screenshots, through the Magpie Browser extension.", magpieCommand, []string{"mcp", "browser"})
m.OptIn = true
return m
}
// selfCommand is the server's command and env for this magpie: its binary
// by full path, and the gateway's address when it isn't the default one.
func selfCommand(s *Server) {
@@ -285,8 +300,8 @@ func serverKey(s *Server) string {
if s.Remote() {
return strings.TrimSuffix(strings.ToLower(s.URL), "/")
}
if len(s.Args) == 2 && s.Args[0] == "mcp" && s.Args[1] == "image" {
return "magpie mcp image" // magpie's own, wherever its binary is
if len(s.Args) == 2 && s.Args[0] == "mcp" && (s.Args[1] == "image" || s.Args[1] == "browser") {
return "magpie mcp " + s.Args[1] // magpie's own, wherever its binary is
}
for _, a := range s.Args {
if a == "" || strings.HasPrefix(a, "-") || a == "run" {
+26
View File
@@ -370,3 +370,29 @@ func TestMarketSkillHadByName(t *testing.T) {
}
}
}
// Magpie Browser is magpie's own too, `magpie mcp browser`, given only to
// the agents picked for it: it acts as the user wherever they're signed in.
func TestMagpieBrowserIsOptIn(t *testing.T) {
sandbox(t)
ok(t)(InstallServer(browserServerName, nil, nil))
list, err := MarketServers("")
if err != nil {
t.Fatal(err)
}
i := slices.IndexFunc(list, func(m MarketServer) bool { return m.ID == browserServerName })
if i < 0 || !list[i].OptIn || list[i].Have != browserServerName {
t.Fatalf("market: %+v", list)
}
l, err := load()
if err != nil {
t.Fatal(err)
}
s := l.server(browserServerName)
if s == nil || len(s.Agents) != 0 || !filepath.IsAbs(s.Command) || strings.Join(s.Args, " ") != "mcp browser" {
t.Fatalf("added as %+v", s)
}
if v, ok := valueOf((&mcpFile{Format: fmtCodex}).encode(s), "tool_timeout_sec"); !ok || v != 120 {
t.Fatalf("Codex's entry: tool_timeout_sec = %v %v", v, ok)
}
}
+6 -1
View File
@@ -371,11 +371,16 @@ func (o ordered) MarshalYAML() (any, error) {
}
// selfTimeout is the seconds an agent waits for a tool of s: what
// magpie-image's video tool needs, else def.
// magpie-image's video tool needs, at least two minutes for
// magpie-browser's, else def.
func selfTimeout(s *Server, def int) int {
if s.Name == selfServerName && s.Command != "" {
return int(imagemcp.ToolTimeout().Seconds())
}
if s.Name == browserServerName && s.Command != "" {
// a browser_wait waits up to a minute, and the page settles after
return max(def, 120)
}
return def
}