+`
+
+// 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, "Two
Page two
")
+ 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)
+ }
+}
diff --git a/internal/gateway/browser_test.go b/internal/gateway/browser_test.go
new file mode 100644
index 000000000..63a30f077
--- /dev/null
+++ b/internal/gateway/browser_test.go
@@ -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)
+ }
+ }
+}
diff --git a/internal/gateway/browser_tools.go b/internal/gateway/browser_tools.go
new file mode 100644
index 000000000..658a2bccb
--- /dev/null
+++ b/internal/gateway/browser_tools.go
@@ -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
+}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index babf5bfc6..7aebd9061 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -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) {
diff --git a/internal/gateway/readonly_test.go b/internal/gateway/readonly_test.go
index feb937fc5..ff35897ed 100644
--- a/internal/gateway/readonly_test.go
+++ b/internal/gateway/readonly_test.go
@@ -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...}", "/",
}
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 384486415..c833e6d10 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -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",
diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js
index 483a69210..aeb7a114d 100644
--- a/internal/gui/assets/plugins/library/client.js
+++ b/internal/gui/assets/plugins/library/client.js
@@ -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;
diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js
index c7cf7dd28..0a3566635 100644
--- a/internal/gui/assets/plugins/library/i18n.js
+++ b/internal/gui/assets/plugins/library/i18n.js
@@ -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…",
diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css
index 0a0f73fb3..b97b6c487 100644
--- a/internal/gui/assets/plugins/library/library.css
+++ b/internal/gui/assets/plugins/library/library.css
@@ -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; }
diff --git a/internal/gui/browser.go b/internal/gui/browser.go
new file mode 100644
index 000000000..e52fca519
--- /dev/null
+++ b/internal/gui/browser.go
@@ -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})
+ })
+}
diff --git a/internal/gui/library.go b/internal/gui/library.go
index 7ae4d6eb2..0e611c734 100644
--- a/internal/gui/library.go
+++ b/internal/gui/library.go
@@ -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 {
diff --git a/internal/gui/tests/library-browser-setup.test.cjs b/internal/gui/tests/library-browser-setup.test.cjs
new file mode 100644
index 000000000..b9780ca3c
--- /dev/null
+++ b/internal/gui/tests/library-browser-setup.test.cjs
@@ -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();
+ });
+ }
+ }
+ });
+}
diff --git a/internal/imagemcp/imagemcp.go b/internal/imagemcp/imagemcp.go
index 2d1166c4a..963debd80 100644
--- a/internal/imagemcp/imagemcp.go
+++ b/internal/imagemcp/imagemcp.go
@@ -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:])
diff --git a/internal/library/market.go b/internal/library/market.go
index d4db89e72..7e0303385 100644
--- a/internal/library/market.go
+++ b/internal/library/market.go
@@ -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" {
diff --git a/internal/library/market_test.go b/internal/library/market_test.go
index bbe223425..ccb1b287f 100644
--- a/internal/library/market_test.go
+++ b/internal/library/market_test.go
@@ -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)
+ }
+}
diff --git a/internal/library/mcp.go b/internal/library/mcp.go
index 81b53b3da..fd030e6f6 100644
--- a/internal/library/mcp.go
+++ b/internal/library/mcp.go
@@ -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
}