mcp router: each caller gets its own Magpie Browser session
The router keeps one backend per Library server for every agent, so all agents behind it shared one `magpie mcp browser`, one browser session and so one tab (packinggoodsllc_07668 on Discord: two agents through a remote router fought over one tab). - serveMCP gives a client that initializes an Mcp-Session-Id (nothing is kept or checked by it). - hubSession names each tools/call's caller: _meta magpie/session from a router in front, else hub-<agent>-<Mcp-Session-Id>. - The router passes it in _meta magpie/session to `magpie mcp browser` and to another magpie's router only (keepsSession); the bridge sends it as that call's X-Magpie-Browser-Session (callerSession). A call naming none goes as the bridge's own session, as before. Run (mote-run): go test ./internal/browsermcp; ./internal/gateway -run 'MCP|Hub'; ./internal/library -run 'TestHubTellsMagpieBrowser|TestKeepsSession|TestHubGivesMagpieImage'. ok. Broken by hand, each red: no meta from the library (library test), no Mcp-Session-Id from serveMCP and ignoring _meta in hubSession (gateway test). Not tried: a real remote router chain between two machines.
This commit is contained in:
@@ -13,6 +13,7 @@ With the Library's switch "MCP router" on (#2679, @minggang123 on X), each agent
|
||||
| Router name | What a router says of itself, for an agent given the same tools by two routers (packinggoodsllc_07668 on Discord: one magpie in China, one in Los Angeles) to pick one. `hubWhere`: the user's words (`settings.RouterNote`, one line, 80 characters at most, `CleanRouterNote`), to every caller; with none, this computer's name (`hostName`) to a caller that isn't `local`, and nothing to one that is (one router at hand; the computer's name stays off its prompts). With a value, `initialize`'s `instructions` end `This router: <name>. …`, `serverInfo.title` is `Magpie MCP hub · <name>`, and each tool's description starts `[<name>] ` (once: a description that starts so already, another magpie's router behind this one, isn't given it again). It is this computer's own (`KeepOwn`): a sync never brings another's. Set in the Library's MCP tab (below) or settings.json; the Settings page's save keeps it (`POST /api/settings`). | `hubWhere` in `hub_mcp.go`; `RouterNote`, `SetRouterNote` in [`settings.go`](../../internal/settings/settings.go); `servers/hub-note` in `gui/library.go`; `View.HubNote`, `View.HubName` in `sync.go` |
|
||||
| Magpie Image's project | Magpie Image saves into the project of the agent that called it, though one server serves every agent. Its tools are `HubTool.Roots`: for such a call the router answers the POST as an event stream (`mcpExchange`) and asks the agent `roots/list` on it, waiting `hubRootsWait` (3s); Claude Code answers with its folder. An agent that answers no roots, or none (Codex answers `[]`), is given the workspaces the call's `_meta` names (Codex's `x-codex-turn-metadata.workspaces`, keyed by the folder of each git repository it works in, absolute paths only), and failing those the folder of the call's `_meta.threadId` in Codex's sessions (`sessions.CodexThreadCwd`, its rollout's cwd), only with consent to read them; with neither (a folder that isn't a repository, no consent), none. A caller that isn't local gets no roots. The call goes on with `_meta` `magpie/roots` (file URIs, never null) and `magpie/client` (the first word of the agent's User-Agent, e.g. `claude-code/2.1.314`). The image server, seeing `magpie/roots`, saves into the first root, or `~/Pictures/Magpie` with none (never its own folder), draws as `<client> magpie-image/1`, and sends no `magpie/toolCalled` report, since the router's row is the call's: its result's `_meta` `magpie/model` (provider/model) names the model it drew with, for that row (`HubModelMeta`). | `hubRoots`, `hubClient`, `WithHubCaller` in `hub_mcp.go`; [`mcp_ask.go`](../../internal/gateway/mcp_ask.go); `imageMeta` in `mcp_hub.go`; `project`, `rootOf` in [`imagemcp.go`](../../internal/imagemcp/imagemcp.go); [`codex_cwd.go`](../../internal/sessions/codex_cwd.go) |
|
||||
| Guard | `serveMCP`, as `/mcp/magpie/tools`: a local request, or one with a gateway key; a browser page's Origin that `corsAllowed` doesn't allow is 403; POST only; a 4 MiB body (`hubBody`). The outer `lanGuard`/`corsGuard` already refuse `Origin: null`, a foreign site and a rebound Host. Each call is held to the calling key's limit (`reserveFor`) before anything runs. | `hubMCP`, `hubMCPRun` in `hub_mcp.go`; `serveMCP` in [`search_mcp.go`](../../internal/gateway/search_mcp.go) |
|
||||
| Each caller's Magpie Browser session | One `magpie mcp browser` backend serves every agent behind the router, so it alone would be one browser session: every agent in one tab (packinggoodsllc_07668 on Discord). serveMCP gives a client that initializes an `Mcp-Session-Id` (`newMCPSession`; magpie keeps nothing by it and refuses nothing for it), and each `tools/call` is given the caller's session (`hubSession`): the `_meta` `magpie/session` a router in front of this one named, else `hub-<agent>-<Mcp-Session-Id>`, else none. The router passes it on in `_meta` `magpie/session` (`HubSessionMeta`) only to `magpie mcp browser` and to another magpie's router (`keepsSession`), and the bridge sends it as the `X-Magpie-Browser-Session` of that call (`callerSession`), so two agents, or two windows of one, work in tabs of their own; a call that names none goes as the bridge's own session, as before. | `hubSession`, `newMCPSession` in `hub_mcp.go` and `search_mcp.go`; `keepsSession` in `mcp_hub.go`; `callerSession` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.go) |
|
||||
| Backends | One `backend` per Library server, shared by every agent (`hubPool`, keyed by the server's name; an edit or a sign-in since makes it a new one and ends the old). A command is started as `CheckServers` starts one (`startServer`: `proc` tree, home as its folder, `${NAME}` env expanded), on its first list or call, and initialized once. A URL (`http`, `sse`) is reached with its headers and the Library's MCP sign-in (`mcpauth`), and a session the server forgot is opened again once. A `notifications/tools/list_changed` from a server makes the next list ask it again. | `backendOf`, `connect`, `dialHub`, `dialStdio`, `dialSSE`, `dialHTTP` in `mcp_hub.go`; `startServer`, `httpSession` in [`mcp_check.go`](../../internal/library/mcp_check.go) |
|
||||
| Lifetime | A server with no call for `hubIdle` (10 minutes) is ended; the tools it listed are kept, so a list doesn't start it again, and the next call does. A command that died is started again on the next call. Turning the switch off, an edit, and the gateway stopping (`StopHub` on drain) end them: stdin closed, then the process tree. The switch can be turned off, or a server edited or unticked, by another magpie (the window while `magpie serve` runs, the CLI), and an agent given each server's own entry again never asks the router, so the serving gateway also prunes every `hubPruneEvery` (5s) while it holds a server: each one the library no longer has as it was started, or every one once the switch is off, is ended (`hubPrune`). A server ticked for no agent is still served at `/mcp/magpie/hub`, so it is kept. | `use`, `done`, `stop`, `hubStopAll`, `hubPrune` in `mcp_hub.go`; `StopHub`, `keepHubPruned` in `hub_mcp.go` |
|
||||
| GUI | Below the server list in the Library's MCP tab: a row with the switch (`.lib-switch`, role=switch) saying what it does; on, a line counting what it serves (`.lib-hubstats`: servers, tools, the agents given it), then a row "Other apps" with the address (`.lib-hubURL`, copied with a click) and Connect…, then a Router name row (`.lib-hubnoterow`) with a field (`.lib-hubname`, no native control) holding `hubNote` and `hubName` as its placeholder, saved on Enter or leaving it through `servers/hub-note` `{note}` (Escape puts the saved words back; an input method's Enter is its own), and under them the agents that keep their own entries, grouped by why (`.lib-hub-why[data-why]`). The address is `mcpAddress`: the public one in a browser, the gateway in the app. Connect… opens a sheet (`connectHub`, `.lib-hubsheet`) of two tabs. Agents: agents → magpie → servers, drawn as icons with magpie's bird in the middle, a line of where things stand, then every agent `mcpAgents` lists (each detected, shown agent that takes MCP servers) in groups (`.lib-hubgrp[data-group]`): `off` (not connected), `on` (connected), `kept` (keeps each server's own entry). Each row (`.lib-hubagent[data-state]`: `on`, `none`, `own`, `taken`, `no-remote`) has a switch that posts `servers/agents-all` `{agents:[id], on}`, as By agent's Turn all on/off does: on gives it every Library server, so `hubFor` gives it the entry; off takes every Library server from it. A kept agent has a word for why and the reason in full behind (i) (`.lib-hubinfo`, `.lib-hubwhy`); an agent that reaches no server over HTTP says so even with none ticked. magpie-image is drawn and counted with the others. Connect all (`.lib-huball`) posts every `none` agent at once. With more than 8 agents a search (`.lib-hubsearch`) narrows every group, and the connected and the kept fold to one row each (`.lib-hubfolded`) until unfolded. The sheet stays open while it changes, and an agent is never handed to the user as a command to run. Other apps: the address (`.lib-hubaddr`), and a row per app (`.lib-hubapp[data-app]`): Cursor (only when it isn't one of the agents), VS Code, Windsurf and any JSON app, each with where its entry goes and a Copy entry (`.lib-hubcopy`) that copies its JSON. In the app, Cursor and VS Code also get Add (`.lib-hubadd`): the page posts `servers/hub-open` `{app}` and the window opens that app's install link (`HubLink`), which the app asks the user to confirm. The page never sends a link; an app with none is an error, and nothing is opened. In a browser there is no Add. With the router on, the server editor has a switch "Through the MCP router" (on for shared; not shown with the router off) saved as `hub`, a direct server's row has a tag (`.lib-tag.lib-direct`), and the line under the switch and the sheet name the direct servers as given directly (`inHub`, `directNames` in client.js; `mcp-hub-direct.test.cjs`). The TUI keeps the policy on edit. | `hubPart`, `hubStats`, `connectHub` in [`client.js`](../../internal/gui/assets/plugins/library/client.js), [`library.css`](../../internal/gui/assets/plugins/library/library.css), [`i18n.js`](../../internal/gui/assets/plugins/library/i18n.js); `HubLink` in `mcp_hub.go`; `servers/hub-open` in `gui/library.go` |
|
||||
|
||||
@@ -125,6 +125,28 @@ func imageFrom(b []byte, wd string) []byte {
|
||||
return out
|
||||
}
|
||||
|
||||
// callerSession is the browser session a message goes on in: the hub's
|
||||
// caller's, which magpie's MCP router names in a call's _meta
|
||||
// (gateway.HubSessionMeta) since it runs this one process for every agent
|
||||
// behind it, else this process's own. Two agents behind the router then
|
||||
// work in tabs of their own, as two given this server directly do.
|
||||
func callerSession(b []byte, own string) string {
|
||||
var m struct {
|
||||
Method string `json:"method"`
|
||||
Params struct {
|
||||
Meta map[string]json.RawMessage `json:"_meta"`
|
||||
} `json:"params"`
|
||||
}
|
||||
var v string
|
||||
if json.Unmarshal(b, &m) != nil || m.Method != "tools/call" || json.Unmarshal(m.Params.Meta[gateway.HubSessionMeta], &v) != nil {
|
||||
return own
|
||||
}
|
||||
if v = strings.TrimSpace(v); v == "" {
|
||||
return own
|
||||
}
|
||||
return "hub:" + v
|
||||
}
|
||||
|
||||
func relay(in io.Reader, s *bridge) error {
|
||||
sc := bufio.NewScanner(in)
|
||||
sc.Buffer(make([]byte, 64<<10), max(s.most, 16<<20))
|
||||
@@ -191,7 +213,7 @@ func (s *bridge) pass(m message, body []byte) {
|
||||
r.Header.Set("Accept", "application/json")
|
||||
r.Header.Set("Authorization", "Bearer "+gateway.Token)
|
||||
if s.session != "" {
|
||||
r.Header.Set(gateway.BrowserSessionHeader, s.session)
|
||||
r.Header.Set(gateway.BrowserSessionHeader, callerSession(body, s.session))
|
||||
}
|
||||
resp, err := s.client.Do(r)
|
||||
if err != nil {
|
||||
|
||||
@@ -218,3 +218,22 @@ func TestImageFromLeavesTheRest(t *testing.T) {
|
||||
t.Fatalf("relative: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Behind magpie's MCP router this one process serves every agent, so a
|
||||
// call that names its caller's session in _meta goes on in that session,
|
||||
// each caller in a tab of its own; every other message, and a call with
|
||||
// no such session, goes in this process's own.
|
||||
func TestBridgeTakesTheRoutersCaller(t *testing.T) {
|
||||
own := "stdio-abc"
|
||||
for _, c := range []struct{ body, want string }{
|
||||
{`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"browser_tabs","_meta":{"magpie/session":"hub-claude-1"}}}`, "hub:hub-claude-1"},
|
||||
{`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"browser_tabs","_meta":{"magpie/session":" "}}}`, own},
|
||||
{`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"browser_tabs"}}`, own},
|
||||
{`{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"magpie/session":"hub-claude-1"}}}`, own},
|
||||
{`not json`, own},
|
||||
} {
|
||||
if got := callerSession([]byte(c.body), own); got != c.want {
|
||||
t.Errorf("%s: %q, want %q", c.body, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"net/http"
|
||||
@@ -53,9 +54,15 @@ type HubTool struct {
|
||||
// said are its, as file URIs (none for an agent on another machine, whose
|
||||
// folders aren't here), and its User-Agent's product, the name the
|
||||
// server's own requests go under.
|
||||
//
|
||||
// Session is which of the hub's callers the call is from (hubSession), for
|
||||
// a server that keeps something per caller: Magpie Browser's tab, which
|
||||
// two agents behind one router would otherwise share, the router running
|
||||
// one `magpie mcp browser` for all of them.
|
||||
type HubCaller struct {
|
||||
Roots []string
|
||||
Client string
|
||||
Roots []string
|
||||
Client string
|
||||
Session string
|
||||
}
|
||||
|
||||
// The _meta keys a call of magpie's image server carries its caller in:
|
||||
@@ -66,6 +73,10 @@ const (
|
||||
HubRootsMeta = "magpie/roots"
|
||||
HubClientMeta = "magpie/client"
|
||||
HubModelMeta = "magpie/model"
|
||||
// HubSessionMeta is the _meta key a call carries its caller's session
|
||||
// in (HubCaller.Session), to Magpie Browser and to another magpie's
|
||||
// router, which passes it on as its own caller's
|
||||
HubSessionMeta = "magpie/session"
|
||||
)
|
||||
|
||||
type hubCallerKey struct{}
|
||||
@@ -221,9 +232,11 @@ func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, m
|
||||
}
|
||||
for _, t := range hubTools(r.Context(), agent) {
|
||||
if t.name == p.Name {
|
||||
c := HubCaller{Session: hubSession(r, agent, p.Meta)}
|
||||
if t.Roots {
|
||||
r = r.WithContext(WithHubCaller(r.Context(), HubCaller{Roots: hubRoots(r, p.Meta), Client: hubClient(r)}))
|
||||
c.Roots, c.Client = hubRoots(r, p.Meta), hubClient(r)
|
||||
}
|
||||
r = r.WithContext(WithHubCaller(r.Context(), c))
|
||||
return s.hubMCPRun(r, agent, t, p.Arguments), nil
|
||||
}
|
||||
}
|
||||
@@ -280,11 +293,35 @@ func (s *Server) hubMCPRun(r *http.Request, agent string, t hubTool, args json.R
|
||||
// (the git repositories it works in, keyed by their folder).
|
||||
type hubCallMeta struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
Turn struct {
|
||||
// Session is the caller's session as another magpie's router passed
|
||||
// it on (HubSessionMeta)
|
||||
Session string `json:"magpie/session"`
|
||||
Turn struct {
|
||||
Workspaces map[string]json.RawMessage `json:"workspaces"`
|
||||
} `json:"x-codex-turn-metadata"`
|
||||
}
|
||||
|
||||
// hubSession is which caller of the hub r is: the session another
|
||||
// magpie's router names, which is its own caller's (that router reaches
|
||||
// this one on one connection for all of them), else the session this
|
||||
// client was given at initialize (serveMCP), else none, and the server
|
||||
// then keeps one thing for every caller, as before clients were told
|
||||
// apart. A caller can name any session, but each is only a tab of the
|
||||
// user's browser, which a caller can pick by its id anyway.
|
||||
func hubSession(r *http.Request, agent string, meta hubCallMeta) string {
|
||||
if v := boundedSession(meta.Session); v != "" {
|
||||
return v
|
||||
}
|
||||
if v := boundedSession(r.Header.Get("Mcp-Session-Id")); v != "" {
|
||||
return "hub-" + agent + "-" + v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// newMCPSession is a session id for a client of one of magpie's MCP
|
||||
// servers.
|
||||
func newMCPSession() string { return "magpie-" + rand.Text() }
|
||||
|
||||
// hubWhere is what the router says of itself to the agent of r, for an
|
||||
// agent given the same tools by two routers (one in China, one in Los
|
||||
// Angeles) to tell them apart: the user's own words (settings'
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -436,3 +437,46 @@ func TestHubMCPSaysWhere(t *testing.T) {
|
||||
t.Fatalf("off: %q", say)
|
||||
}
|
||||
}
|
||||
|
||||
// Each client that initializes is given a session id, and each call the
|
||||
// hub runs is made with its caller's session (HubCaller.Session), so a
|
||||
// server that keeps something per caller (Magpie Browser's tab) keeps it
|
||||
// apart for two agents behind one router: the session another magpie's
|
||||
// router names in _meta, which is its caller's, else the client's own; a
|
||||
// client that sends none is told apart from no one, as before.
|
||||
func TestHubMCPTellsCallersApart(t *testing.T) {
|
||||
fresh(t)
|
||||
var mu sync.Mutex
|
||||
var got []string
|
||||
f := &fakeHub{on: true, tools: map[string][]HubTool{
|
||||
"claude": {{Server: "magpie-browser", Tool: "browser_tabs", Spec: hubSpec("browser_tabs")}},
|
||||
}, call: func(ctx context.Context, server, tool string) (json.RawMessage, error) {
|
||||
mu.Lock()
|
||||
got = append(got, HubCallerOf(ctx).Session)
|
||||
mu.Unlock()
|
||||
return json.RawMessage(`{"content":[{"type":"text","text":"ok"}]}`), nil
|
||||
}}
|
||||
withHub(t, f)
|
||||
h := lanGuard(New().Handler())
|
||||
|
||||
initialize := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}`
|
||||
a := hubPost(h, "claude", here, initialize).Header().Get("Mcp-Session-Id")
|
||||
b := hubPost(h, "claude", here, initialize).Header().Get("Mcp-Session-Id")
|
||||
if a == "" || b == "" || a == b {
|
||||
t.Fatalf("sessions given at initialize: %q, %q", a, b)
|
||||
}
|
||||
if again := hubPost(h, "claude", here, initialize, "Mcp-Session-Id", a).Header().Get("Mcp-Session-Id"); again != "" {
|
||||
t.Errorf("a client with a session was given another: %q", again)
|
||||
}
|
||||
call := toolsCall("magpie-browser__browser_tabs", `{}`)
|
||||
hubPost(h, "claude", here, call, "Mcp-Session-Id", a)
|
||||
hubPost(h, "claude", here, call, "Mcp-Session-Id", b)
|
||||
hubPost(h, "claude", here, `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"magpie-browser__browser_tabs","arguments":{},"_meta":{"magpie/session":"hub-claude-far"}}}`, "Mcp-Session-Id", a)
|
||||
hubPost(h, "claude", here, call)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
want := []string{"hub-claude-" + a, "hub-claude-" + b, "hub-claude-far", ""}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("callers %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +103,14 @@ func serveMCP(w http.ResponseWriter, r *http.Request, what, server string, limit
|
||||
}
|
||||
// one request, by a client that takes an event stream back, may be
|
||||
// answered by one, for the server to ask the client something first
|
||||
// a client that initializes is given a session id, which it sends on
|
||||
// every request after (Streamable HTTP's Mcp-Session-Id): magpie keeps
|
||||
// nothing by it and never refuses a request for it, but tells two
|
||||
// clients of one server apart by it, as Magpie Browser does to give
|
||||
// each its own tab (browserSession, hubSession)
|
||||
if r.Header.Get("Mcp-Session-Id") == "" && slices.ContainsFunc(msgs, func(m mcpMessage) bool { return m.Method == "initialize" }) {
|
||||
w.Header().Set("Mcp-Session-Id", newMCPSession())
|
||||
}
|
||||
x := &mcpExchange{w: w, canStream: !batch && strings.Contains(r.Header.Get("Accept"), "text/event-stream")}
|
||||
r = r.WithContext(context.WithValue(r.Context(), mcpExchangeKey{}, x))
|
||||
var out []any
|
||||
|
||||
@@ -14,9 +14,9 @@ import (
|
||||
// a temp dir of their own: what they leave in it is theirs, and a skill's
|
||||
// download left there fails the run (#2321).
|
||||
func TestMain(m *testing.M) {
|
||||
// started as magpie's own image server (Args mcp image): the fake
|
||||
// server, for the hub to take it for magpie-image
|
||||
if len(os.Args) >= 3 && os.Args[1] == "mcp" && os.Args[2] == "image" {
|
||||
// started as magpie's own image or browser server (Args mcp image,
|
||||
// mcp browser): the fake server, for the hub to take it for that one
|
||||
if len(os.Args) >= 3 && os.Args[1] == "mcp" && (os.Args[2] == "image" || os.Args[2] == "browser") {
|
||||
os.Args = []string{os.Args[0], "-test.run=^TestFakeMCPServer$"}
|
||||
}
|
||||
if os.Getenv(testenv.Marker) != "" {
|
||||
|
||||
@@ -249,12 +249,31 @@ func (theHub) Call(ctx context.Context, agentID, server, tool string, args json.
|
||||
if isSelf(s) {
|
||||
meta = imageMeta(gateway.HubCallerOf(ctx))
|
||||
}
|
||||
if c := gateway.HubCallerOf(ctx); c.Session != "" && keepsSession(s) {
|
||||
if meta == nil {
|
||||
meta = map[string]any{}
|
||||
}
|
||||
meta[gateway.HubSessionMeta] = c.Session
|
||||
}
|
||||
if s.Plugin != "" {
|
||||
return pluginHubCall(ctx, agentID, s, tool, args)
|
||||
}
|
||||
return backendOf(s).call(ctx, tool, args, meta)
|
||||
}
|
||||
|
||||
// keepsSession is whether s is told which of the hub's callers a call is
|
||||
// from: Magpie Browser, which works in a tab of each caller's own (one
|
||||
// process serves every agent behind the hub, so its own session would be
|
||||
// all of theirs), and another magpie's router, which passes it on to its
|
||||
// Magpie Browser. No other server is sent it.
|
||||
func keepsSession(s *Server) bool {
|
||||
if s.Remote() {
|
||||
u, err := url.Parse(s.URL)
|
||||
return err == nil && strings.HasPrefix(u.Path, gateway.HubMCPAll)
|
||||
}
|
||||
return len(s.Args) >= 2 && s.Args[0] == "mcp" && s.Args[1] == "browser"
|
||||
}
|
||||
|
||||
// imageMeta is the _meta a call of magpie's image server is made with:
|
||||
// the calling agent's roots, which it saves into, and its name, which its
|
||||
// requests go under.
|
||||
|
||||
@@ -653,3 +653,65 @@ func TestHubGivesMagpieImage(t *testing.T) {
|
||||
t.Errorf("no roots: called as %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The router runs one Magpie Browser for every agent behind it, so each
|
||||
// call names its caller's session in _meta, for the browser to keep each
|
||||
// caller in a tab of its own; another server is sent no session, and a
|
||||
// call with none (a caller not told apart) is sent none.
|
||||
func TestHubTellsMagpieBrowserItsCaller(t *testing.T) {
|
||||
h := hubSandbox(t)
|
||||
write(t, filepath.Join(h, ".claude.json"), `{"mcpServers": {}}`)
|
||||
br := fakeStdio(t, "ok", nil)
|
||||
br.Name, br.Args, br.Agents = browserServerName, []string{"mcp", "browser"}, []string{"claude"}
|
||||
ok(t)(SaveServer("", *br))
|
||||
other := fakeStdio(t, "ok", nil)
|
||||
other.Agents = []string{"claude"}
|
||||
ok(t)(SaveServer("", *other))
|
||||
ok(t)(SetMCPHub(true))
|
||||
hub := theHub{}
|
||||
ctx := context.Background()
|
||||
|
||||
for _, s := range []string{"hub-claude-one", "hub-claude-two"} {
|
||||
res, err := hub.Call(gateway.WithHubCaller(ctx, gateway.HubCaller{Session: s}), "claude", browserServerName, "a", json.RawMessage(`{}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := hubText(t, res); !strings.Contains(got, `meta={"magpie/session":"`+s+`"}`) {
|
||||
t.Errorf("browser called as %q, want session %s", got, s)
|
||||
}
|
||||
}
|
||||
res, err := hub.Call(gateway.WithHubCaller(ctx, gateway.HubCaller{Session: "hub-claude-one"}), "claude", "fake", "a", json.RawMessage(`{}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := hubText(t, res); strings.Contains(got, "meta=") {
|
||||
t.Errorf("another server was sent the session: %q", got)
|
||||
}
|
||||
res, err = hub.Call(ctx, "claude", browserServerName, "a", json.RawMessage(`{}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := hubText(t, res); strings.Contains(got, "meta=") {
|
||||
t.Errorf("no session: called as %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Another magpie's router is sent the session too, to pass on to its
|
||||
// Magpie Browser; any other URL isn't.
|
||||
func TestKeepsSession(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
s Server
|
||||
want bool
|
||||
}{
|
||||
{Server{Transport: "stdio", Command: "/Applications/Magpie.app/Contents/MacOS/magpie", Args: []string{"mcp", "browser"}}, true},
|
||||
{Server{Transport: "stdio", Command: "magpie", Args: []string{"mcp", "image"}}, false},
|
||||
{Server{Transport: "http", URL: "http://10.0.0.2:3425/mcp/magpie/hub"}, true},
|
||||
{Server{Transport: "http", URL: "http://10.0.0.2:3425/mcp/magpie/hub/claude"}, true},
|
||||
{Server{Transport: "http", URL: "https://mcp.example.com/mcp"}, false},
|
||||
{Server{Transport: "http", URL: "https://example.com/x/mcp/magpie/hub"}, false},
|
||||
} {
|
||||
if got := keepsSession(&c.s); got != c.want {
|
||||
t.Errorf("%+v: %v, want %v", c.s, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user