Files
magpie/internal/browsermcp/browsermcp_test.go
T
yetone 0e90572274 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.
2026-11-01 02:29:55 +08:00

67 lines
2.1 KiB
Go

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())
}
}