Files
magpie/internal/browsermcp/browsermcp.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

122 lines
3.0 KiB
Go

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