diff --git a/docs/reference.md b/docs/reference.md index cfef2d1d6..618ffb1e0 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3204,8 +3204,10 @@ key. See [Connecting anything else](#connecting-anything-else) for the protocol-specific base URLs. Keep `3425` behind a firewall or VPN and do not expose it publicly without gateway-key authentication. -Such a page is in **gateway mode**: it shows Providers, Gateway, Routing, -Usage, Sessions, Plugins and Settings, with no Agents or Library tab. +Such a page is in **gateway mode**: it shows Sessions, Library, Providers, +Routing, Gateway, Usage, Masking, Plugins and Settings, with no Agents tab. +The Library has its MCP servers alone, with the MCP router: other +computers' apps connect at the router's address with a gateway key. Sessions lists only the sessions of other computers' agents that came through this gateway, never this machine's agents' session files ([gateway sessions](subsystems/gateway-sessions.md)). Settings leaves out what is written into this machine's agents (provider in diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 05089e0db..618448996 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -15,7 +15,7 @@ three. | Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil), and `watchGateway` looks at it again every 15 s (`gatewayWatch`). A magpie of another version there (`otherServes` in `gateway_older.go`) is told the page as `gatewayOther` in `/api/state` and said over the Agents list (`gatewaySkewLine` in `plugins/gateway/client.js`), in the panel and the window: pi got 404 for a model the newer app had written it while an older copy of the app kept the gateway, and only the Gateway page said so (matrix0487 on Discord). An older released copy of the app (`serves` app or tray, with a pid) is this app's own predecessor: once its `/v1/magpie/concurrency` says nothing is in flight (`gateway.ServedBusy`; unknown is never idle) the app quits it as the Gateway page's button does (`quitMagpieOnPort`, a magpie only) and serves the gateway, so no stream is cut; at most three times a run (`replaceMost`), and a quit that fails is left to the button. Any other (magpie serve or the service, `magpie web`, a TUI, a newer magpie, a build of its own) is left running, with what to do; a dev build of this magpie says nothing. A request that starts between the idle read and the quit gets the older app's short drain. See `TestAppReplacesItsOlderGatewayOnceIdle`, `TestGatewaySkewOfAnotherIsSaidNotQuit` and `gateway-skew.test.cjs`. `magpie serve` (the service's, launchd's `com.yetone.magpie.serve` or systemd's) does the same beside a magpie serving or another program holding the port: before it moves or starts anything (`startUp`), it waits, looking every 15 s, and serves once the port is free (`awaitGatewayFree` in [`serve_wait.go`](../../internal/cli/serve_wait.go); `--web` excepted, which shows the other one). Before, it ran the start-up moves, the plugin host and every account's model fetch, failed to bind, exited 1 and was started again by the service, 6,035 times in two days with a 279MB serve.log and requests 504 behind it (#4938, `TestServeWaitsForTheGatewayBeforeStartingUp`). `stopServing` drains requests in flight. A restart to update can hand the listening socket to the new version instead (see [A restart to update hands the gateway over](#a-restart-to-update-hands-the-gateway-over)). | [`backend.go`](../../internal/gui/backend.go), [`gateway_older.go`](../../internal/gui/gateway_older.go) | | API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set`, `/api/agents/{action}/{id}` and `/api/agents/restart/{id}` (a desktop app's Restart, after the row's confirm). `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) | | Settings from the terminal | `POST /api/settings` saves through `settingsapi.Apply` (`internal/settingsapi`, outside the GUI so the `nogui` build has it): the carry of keys a page leaves out (`Merge`), the vision, image and searcher checks, `settings.Save`'s own checks, and `catalog.Touched`. `magpie settings list\|get\|set\|reset` (#4745) builds the same body with `settingsapi.Body` (the whole file with one key changed, so a key the save keeps when it isn't sent is set even to off) and calls the same `Apply`; a refused value writes nothing. `settingsapi.Keys` names what the save writes; `TestKeysAreWhatTheSaveWrites` fails when a field of `settings.Settings` is saved without it, `TestSettingsCLISetsWhatTheWindowSaves` when a key the page's `savePrefs` sends isn't one, and `TestEveryRouteHasACommandOrIsNamed` when an `/api` route has neither a command nor a reason in `notYet` (`internal/cli/settings_parity_test.go`). The running app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update check) run only from the window's save; a change from the terminal is read from the file. | [`internal/settingsapi/settingsapi.go`](../../internal/settingsapi/settingsapi.go), [`settings_cli.go`](../../internal/cli/settings_cli.go) | -| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Added to a phone's home screen the page opens as an app of its own, with no browser bars (ninja_s6114 on Discord): `index.html` names `manifest.json` (display standalone), an apple-touch-icon and the iOS meta tags, the status bar keeps its own ground (`default`), and its theme colours match only `(display-mode: standalone)`, so a browser's tab and the app's windows take none. `webGuard` serves those three files (`webAppFiles`: the manifest, `icons/apple-touch-icon.png`, `icons/icon-512.png`) without the key, to GET and HEAD at those exact paths alone, as a home screen may ask without the cookie; see `TestWebAppAddsToHomeScreen` and `web-app-standalone.test.cjs`. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304; never an event stream, which gzip would hold back until its buffer fills); the app's own windows read the page in-process and get it uncompressed. The page's port answers the gateway's client routes too (`onePort`, `gateway.ClientPath`: `/v1/…`, `/v1beta/…`, `/mcp/…`, the Codex backend path and the routes without `/v1`; never `/api/*` or `/_magpie/*`, never a path that isn't clean), so one reverse-proxy location serves the page and the agents (zgcwkj on Discord). They skip the page's key and gzip and go to the gateway's own guards, always as a request from another machine (`gateway.FromPagePort`, the `X-Magpie-Page-Port` mark: `local` is false for it, from loopback too and under `MAGPIE_TRUST_PROXY`, so magpie must be shared and the request carry an enabled gateway key), since a raw TCP forward or a proxy that adds no forwarding header reaches this port from loopback looking like an agent here (reported privately by Coffemon); agents here use the gateway's own port. `Server.Front` (lanGuard over Handler) serves them in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host, the forwarding headers and the mark, adds X-Forwarded-For for a peer that isn't loopback, and the peer's loopback address as X-Forwarded-For when none came, so a gateway of an older magpie that doesn't know the mark still asks for a key. `lanGuard` moves the mark into the request's context and takes the header off, so it never goes upstream. The page itself calls no client route. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere`, `TestWebOnePortAgentsHereUseTheGatewayPort`, `TestPagePortMarkIsNeverLocal` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) | +| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Added to a phone's home screen the page opens as an app of its own, with no browser bars (ninja_s6114 on Discord): `index.html` names `manifest.json` (display standalone), an apple-touch-icon and the iOS meta tags, the status bar keeps its own ground (`default`), and its theme colours match only `(display-mode: standalone)`, so a browser's tab and the app's windows take none. `webGuard` serves those three files (`webAppFiles`: the manifest, `icons/apple-touch-icon.png`, `icons/icon-512.png`) without the key, to GET and HEAD at those exact paths alone, as a home screen may ask without the cookie; see `TestWebAppAddsToHomeScreen` and `web-app-standalone.test.cjs`. Gateway mode shows every page but Agents on a machine that is only a gateway (`GATEWAY_HIDES`); the Library has its MCP servers and the MCP router alone, for other computers' apps to reach with a gateway key (treeman_26897 on Discord, `gateway-mode.test.cjs`, `library-mcp-agentless.test.cjs`). `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304; never an event stream, which gzip would hold back until its buffer fills); the app's own windows read the page in-process and get it uncompressed. The page's port answers the gateway's client routes too (`onePort`, `gateway.ClientPath`: `/v1/…`, `/v1beta/…`, `/mcp/…`, the Codex backend path and the routes without `/v1`; never `/api/*` or `/_magpie/*`, never a path that isn't clean), so one reverse-proxy location serves the page and the agents (zgcwkj on Discord). They skip the page's key and gzip and go to the gateway's own guards, always as a request from another machine (`gateway.FromPagePort`, the `X-Magpie-Page-Port` mark: `local` is false for it, from loopback too and under `MAGPIE_TRUST_PROXY`, so magpie must be shared and the request carry an enabled gateway key), since a raw TCP forward or a proxy that adds no forwarding header reaches this port from loopback looking like an agent here (reported privately by Coffemon); agents here use the gateway's own port. `Server.Front` (lanGuard over Handler) serves them in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host, the forwarding headers and the mark, adds X-Forwarded-For for a peer that isn't loopback, and the peer's loopback address as X-Forwarded-For when none came, so a gateway of an older magpie that doesn't know the mark still asks for a key. `lanGuard` moves the mark into the request's context and takes the header off, so it never goes upstream. The page itself calls no client route. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere`, `TestWebOnePortAgentsHereUseTheGatewayPort`, `TestPagePortMarkIsNeverLocal` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) | | The app's page in a browser | Settings › Network and sharing › Browser access (`renderWebPage` in `plugins/gateway/settings.js`, drawn with the Web pages rows) has the app serve its own page to a browser while it runs, so a tunnel (Cloudflare Tunnel, SSH) or a computer on the network can reach it without `magpie web` kept running in a terminal (jiakun_zhao on X). Off, This computer (`127.0.0.1`, which a tunnel's service points at) or Local network (every address; a "Not encrypted" row without `--tls-cert`). It is `magpie web`'s page and guard, not a second kind: `startAppPage` (from `Run`, after `startBackend`) serves `webServed` over a `Handler` of its own, whose `Windows` is `appWebHost` (a browser tab for `isWeb`, but not `ownWeb`, so the app's windows aren't taken for `magpie web`'s: `webPage` and gateway mode stay the app's; quitting quits the app, and a restart to update from it brings back the windows the app has up, `restartFrom`). The key is always asked for: no mode serves without it. It lives with the mode and port in `web-page.json` beside settings.json (0600, never in settings.json, so sync and backup don't carry it), is made the first time the page is turned on, kept across restarts (a browser's cookie stays good), and replaced by New key, which turns away every browser signed in with the old one (the guard is swapped atomically, `appPage.cur`). A file that can't be read, or names no known mode, is off and says why; Settings rewrites it only given a whole choice. A port another program holds (`magpie web`; the magpie before a restart to update) is said and tried again every 4 s (`appPageRetry`); the port must be 1024 up and not the gateway's. `GET/POST /api/web-page` are on the app's own windows' API only, never a browser's, so a browser on the page can neither read the key it came in without nor turn the page off under itself. `magpie web` on the port the app serves prints the app's link and opens it rather than starting a second (`gui.AppPage`, `samePort`). Sessions are warmed once a process however many `Handler`s there are (`warmOnce`). See `TestAppPageServesOnlyWithItsKey`, `TestAppPageWaitsForABusyPort`, `TestAppPageUnreadFileServesNothing`, `TestAppPageTurnsDownBadChoices`, `TestAppPageBrowserIsATab` and `browser-access.test.cjs`. | [`apppage.go`](../../internal/gui/apppage.go), [`web_cli.go`](../../internal/cli/web_cli.go) | | The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins//` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; a client whose User-Agent names only an HTTP library, a runtime or an API SDK (`usage.IsLibrary`: curl, Bun, python-httpx, Go-http-client, OpenAI/Python), or nothing (`other`), is no agent and goes on one card, `scripts`, named Scripts with its libraries listed, read from each route's kept agent so older history folds too, while the Usage page's Agents list keeps each by its own name (theforeveriris on X, `context_scripts_test.go`, `context-scripts.test.cjs`); clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory, else the request archive's copy masked the same way, with a 404 saying why there is none (`archive`: off, missing, cut, unread; `context_archive.go`), and its Reply the reply from `/api/context/reply` (`openCtxText`, in `ctxtext.js`, `context-text.test.cjs`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) | | Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar, or drawn at once from boot.js's `sideGateway`; on a page other machines open, `magpie web`, it is `MAGPIE_PUBLIC_URL` while they are let in, as the Gateway page's address and About's Gateway URL are, noahhrreion on Discord; a port applied in Settings redraws it), and the header a breadcrumb (`renderCrumb`). A page whose head holds only its tools (Library, Plugins, Settings) has them in the title bar after the breadcrumb, `tools` setting the room between it and the window's own buttons. When they don't fit there the tools show their icons alone (`tools-tight`; each keeps its name as `aria-label` and in its tooltip), then the breadcrumb drops its leading parts, and last the page's name is cut at its end, so no tool lies over the title (#2625, `title-bar-tools.test.cjs`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. The open page's own row is marked the same way, by one shape (`.nav-top-hl`, the rows' own ground given up to it, hovered or pressed too) that `navTopGo` moves to the row picked on a damped spring, as iOS moves a selection (`NAV_SPRING`, SwiftUI's response 0.42s and damping 0.84; `navTopStep` steps it each frame): it sets off as the row is pressed and comes back if the press leaves the row or the page isn't left, turns with the speed it has when the press changes its mind, and follows its row while the list above it folds, landing where the row ends up. It is put in place, not sent, when the window opens on a page or the rows move under it at rest (a `ResizeObserver`), is away while Settings is open (it has its own selection at the foot), comes back fading in on its row, jumps under reduced motion, and isn't drawn in the header's tabs, which have their `.thumb`. `#nav` is `position: relative` in the sidebar for it, so `.seg`'s centring `left` and `top` are reset. See `sidebar-glide.test.cjs`. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) | diff --git a/docs/subsystems/mcp-router.md b/docs/subsystems/mcp-router.md index fcdd37845..c370e7c0e 100644 --- a/docs/subsystems/mcp-router.md +++ b/docs/subsystems/mcp-router.md @@ -18,7 +18,7 @@ With the Library's switch "MCP router" on (#2679, @minggang123 on X), each agent | 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--`, 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), then a Tools on demand row (`.lib-hubtoolsrow`) whose switch is on while `hubAllTools` is false and posts `servers/hub-tools` `{on}` (on: every tool whole), 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` | +| 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), then a Tools on demand row (`.lib-hubtoolsrow`) whose switch is on while `hubAllTools` is false and posts `servers/hub-tools` `{on}` (on: every tool whole), 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. With no agent to write to, or in gateway mode (where no agent is shown), the Library is its MCP tab alone (`agentless` in client.js): the servers without agent chips, found servers or projects, the router's switch even before the first server, its lines saying any app connects at the address, the status saying the router is on or off, the servers it serves checked once it is on, and Connect… on Other apps alone. A server for remote clients is set up this way on a headless magpie (treeman_26897 on Discord); the remote client still needs a gateway key, through the same `serveMCP` guard (`TestHubMCPRemoteEntryNeedsKey`, `library-mcp-agentless.test.cjs`). | `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` | The CLI's `magpie library mcp router on|off` (`hub`, its name before, still works) calls `SetMCPHub`, and `magpie library mcp router shared|direct` calls `ServerHub`. `magpie library` lists the agents given magpie's entry and those that keep their own, with why (`libraryStatus` in [`library_cli.go`](../../internal/cli/library_cli.go)). diff --git a/internal/gateway/hub_mcp_test.go b/internal/gateway/hub_mcp_test.go index 71f953afe..8c7b61210 100644 --- a/internal/gateway/hub_mcp_test.go +++ b/internal/gateway/hub_mcp_test.go @@ -597,3 +597,79 @@ func TestHubMCPTellsCallersApart(t *testing.T) { t.Fatalf("callers %q, want %q", got, want) } } + +// The router's one address is what a headless magpie gives remote MCP +// clients (treeman_26897 on Discord: a server with no agents, the router +// turned on for other computers' apps). From another computer it takes a +// gateway key, as /v1 does, and nothing without one gets a tool run: +// not while magpie isn't shared, not with no Origin, a null one, another +// scheme's or a foreign site's, not under a rebound Host, and not through +// a proxy on this computer. +func TestHubMCPRemoteEntryNeedsKey(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + t.Setenv("MAGPIE_PUBLIC_URL", "") + t.Setenv("MAGPIE_TRUST_PROXY", "") + f := &fakeHub{on: true, tools: map[string][]HubTool{"": {{Server: "notes", Tool: "find", Spec: hubSpec("find")}}}} + withHub(t, f) + h := lanGuard(New().Handler()) + call := toolsCall("notes__find", `{"q":"x"}`) + const there = "192.0.2.7:4000" + refused := func(what string, w *httptest.ResponseRecorder, want ...int) { + t.Helper() + for _, c := range want { + if w.Code == c { + return + } + } + t.Errorf("%s: %d %s, want %v", what, w.Code, w.Body, want) + } + refused("not shared", hubPostAt(h, HubMCPAll, there, call), http.StatusForbidden) + refused("not shared, a tools/list", hubPostAt(h, HubMCPAll, there, toolsList), http.StatusForbidden) + _, secrets := newCaller(t, "Remote client") // shares magpie + refused("no key, no Origin", hubPostAt(h, HubMCPAll, there, call), http.StatusUnauthorized) + refused("no key, a tools/list", hubPostAt(h, HubMCPAll, there, toolsList), http.StatusUnauthorized) + refused("a wrong key", hubPostAt(h, HubMCPAll, there, call, "Authorization", "Bearer sk-magpie-wrong"), http.StatusUnauthorized) + for _, origin := range []string{"null", "chrome-extension://abcdefghijklmnop", "file://", "moz-extension://1234", "https://evil.example", "http://192.0.2.7:3425"} { + hdr := []string{"Origin", origin, "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "cors"} + refused("no key, Origin "+origin+" from there", hubPostAt(h, HubMCPAll, there, call, hdr...), http.StatusUnauthorized, http.StatusForbidden) + refused("Origin "+origin+" from here", hubPostAt(h, HubMCPAll, here, call, hdr...), http.StatusForbidden) + } + // a page whose own name was rebound to this computer: same-origin, so + // its Origin is the Host or (as a browser's own marks show) none at all. + // With none of a browser's marks it is an agent here calling by a name + // of its own, which lanGuard lets by, as /v1 + for _, addr := range []string{here, there} { + for _, marks := range [][]string{ + {"Origin", "http://rebind.attacker.example:3425", "Sec-Fetch-Site", "same-origin", "Sec-Fetch-Mode", "cors"}, + {"Sec-Fetch-Site", "same-origin", "Sec-Fetch-Mode", "cors"}, + {"User-Agent", "Mozilla/5.0 (Macintosh) AppleWebKit/605.1.15 Safari/605.1.15"}, + } { + r := httptest.NewRequest(http.MethodPost, HubMCPAll, strings.NewReader(call)) + r.RemoteAddr, r.Host = addr, "rebind.attacker.example:3425" + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Accept", "application/json, text/event-stream") + for i := 0; i+1 < len(marks); i += 2 { + r.Header.Set(marks[i], marks[i+1]) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, r) + refused(fmt.Sprintf("a rebound Host from %s %v", addr, marks), rec, http.StatusUnauthorized, http.StatusForbidden) + } + } + // a proxy or tunnel on this computer passing another's request on + refused("through a proxy here, no key", hubPostAt(h, HubMCPAll, here, call, "X-Forwarded-For", "203.0.113.9"), http.StatusUnauthorized, http.StatusForbidden) + refused("through a tunnel here, no key", hubPostAt(h, HubMCPAll, here, call, "Cf-Connecting-IP", "203.0.113.9"), http.StatusUnauthorized, http.StatusForbidden) + if got := f.ran(); len(got) != 0 { + t.Fatalf("ran for a request turned away: %q", got) + } + // with its key: the tool runs, from there and through the proxy + m := readMCP(t, hubPostAt(h, HubMCPAll, there, call, "Authorization", "Bearer "+secrets[0])) + if m.Result.IsError || m.Result.Content[0].Text != "ran notes find" { + t.Fatalf("with its key: %+v", m) + } + m = readMCP(t, hubPostAt(h, HubMCPAll, here, call, "X-Forwarded-For", "203.0.113.9", "Authorization", "Bearer "+secrets[0])) + if m.Result.IsError || len(f.ran()) != 2 { + t.Fatalf("through a proxy, with its key: %+v, ran %q", m, f.ran()) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index d45bf17b5..8cd1f88b8 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -39,10 +39,10 @@ const remotePage = web && !/^(localhost|127(\.\d+){3}|\[::1\]|::1)$/i.test(locat // layout.js applies the mode and platform before the header can paint. // Gateway mode (gatewaymode.go): magpie web on a server that is only the // gateway for other computers' agents leaves out this computer's agents' -// pages — Agents, Sessions, Library — and their settings; Settings › -// General turns it off, and they are back. +// pages — Agents, the Library but its MCP tab — and their settings; +// Settings › General turns it off, and they are back. let gatewayMode = web && !!window.bootPrefs?.gateway; -const GATEWAY_HIDES = ["agents", "library"]; +const GATEWAY_HIDES = ["agents"]; // Plugins › Built-in (builtins.go, Lxxyx): the window's parts switched off, // by id. data-feature="" leaves by a style while off; its tab leaves the // nav (navHides), a link opens Agents (show), Settings skips its rows. @@ -20133,7 +20133,7 @@ function renderGatewayMode(s) { flag: t("Now on: magpie web was started with --gateway"), "no-agents": t("Now on: no agents on this computer"), }[s.gatewayWhy] || t("Now off: agents found on this computer"); - $("#gatewayModeSub").textContent = [t("Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions"), now].filter(Boolean).join(" · "); + $("#gatewayModeSub").textContent = [t("Only what a gateway for other computers needs: no Agents page, nor this computer's agents' settings or sessions"), now].filter(Boolean).join(" · "); } // renderLangPick: Settings' language, one menu button showing the language diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index f11d7dc3c..6b0568bd1 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1011,7 +1011,7 @@ const I18N = { "{name} doesn't ask to read {what}": "{name} 没有声明读取 {what}", "No such call: {what}": "没有这个调用:{what}", "The page hit an error": "页面出错了", - "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions": "只显示给其他电脑当网关所需的内容:不显示 Agent 和资源库,也不显示本机 Agent 的设置和会话", + "Only what a gateway for other computers needs: no Agents page, nor this computer's agents' settings or sessions": "只显示给其他电脑当网关所需的内容:不显示 Agent 页面,也不显示本机 Agent 的设置和会话", "Now on: magpie web was started with --gateway": "当前开启:magpie web 以 --gateway 启动", "Now on: no agents on this computer": "当前开启:本机没有 Agent", "Now off: agents found on this computer": "当前关闭:本机找到了 Agent", @@ -4013,8 +4013,6 @@ const I18N = { "still sent": "仍发给模型", "Put RTK on PATH": "加到 PATH", "Update RTK": "需更新 RTK", - "No agents to write to": "没有可写入的 Agent", - "Install Claude Code, Codex, Gemini CLI, OpenCode… and the library can give them the same instructions, MCP servers and skills.": "安装 Claude Code、Codex、Gemini CLI、OpenCode 等之后,资源库就能给它们同一份指令、MCP 服务器和技能。", "magpie keeps a copy of every file before it writes it.": "magpie 写入任何文件前都会先备份一份。", "Backups": "备份", "Not saved yet": "尚未保存", @@ -5651,7 +5649,7 @@ const I18N = { "{name} doesn't ask to read {what}": "{name} 沒有宣告讀取 {what}", "No such call: {what}": "沒有這個呼叫:{what}", "The page hit an error": "頁面出錯了", - "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions": "只顯示給其他電腦當閘道所需的內容:不顯示 Agent 和資源庫,也不顯示本機 Agent 的設定和會話", + "Only what a gateway for other computers needs: no Agents page, nor this computer's agents' settings or sessions": "只顯示給其他電腦當閘道所需的內容:不顯示 Agent 頁面,也不顯示本機 Agent 的設定和會話", "Now on: magpie web was started with --gateway": "目前開啟:magpie web 以 --gateway 啟動", "Now on: no agents on this computer": "目前開啟:本機沒有 Agent", "Now off: agents found on this computer": "目前關閉:本機找到了 Agent", @@ -8621,8 +8619,6 @@ const I18N = { "still sent": "仍發給模型", "Put RTK on PATH": "加到 PATH", "Update RTK": "需更新 RTK", - "No agents to write to": "沒有可寫入的 Agent", - "Install Claude Code, Codex, Gemini CLI, OpenCode… and the library can give them the same instructions, MCP servers and skills.": "安裝 Claude Code、Codex、Gemini CLI、OpenCode 等之後,資源庫就能給它們同一份指令、MCP 伺服器和技能。", "magpie keeps a copy of every file before it writes it.": "magpie 寫入任何檔案前都會先備份一份。", "Backups": "備份", "Not saved yet": "尚未儲存", @@ -10262,7 +10258,7 @@ const I18N = { "{name} doesn't ask to read {what}": "{name} は {what} の読み取りを宣言していません", "No such call: {what}": "そのような呼び出しはありません:{what}", "The page hit an error": "ページでエラーが起きました", - "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions": "他のコンピューターのゲートウェイに必要なものだけ:エージェント、ライブラリ、このコンピューターのエージェントの設定とセッションは表示しません", + "Only what a gateway for other computers needs: no Agents page, nor this computer's agents' settings or sessions": "他のコンピューターのゲートウェイに必要なものだけ:エージェントのページ、このコンピューターのエージェントの設定とセッションは表示しません", "Now on: magpie web was started with --gateway": "現在オン:magpie web が --gateway で起動されています", "Now on: no agents on this computer": "現在オン:このコンピューターにエージェントがありません", "Now off: agents found on this computer": "現在オフ:このコンピューターにエージェントがあります", @@ -13245,8 +13241,6 @@ const I18N = { "still sent": "送信済み", "Put RTK on PATH": "PATH に追加", "Update RTK": "RTK の更新が必要", - "No agents to write to": "書き込み先のエージェントがありません", - "Install Claude Code, Codex, Gemini CLI, OpenCode… and the library can give them the same instructions, MCP servers and skills.": "Claude Code、Codex、Gemini CLI、OpenCode… をインストールすると、ライブラリが同じ指示、MCP サーバー、スキルを渡せます。", "magpie keeps a copy of every file before it writes it.": "magpie はファイルに書き込む前に必ずコピーを保存します。", "Backups": "バックアップ", "Not saved yet": "未保存", @@ -14888,7 +14882,7 @@ const I18N = { "{name} doesn't ask to read {what}": "{name} fragt nicht danach, {what} zu lesen", "No such call: {what}": "Kein solcher Aufruf: {what}", "The page hit an error": "Die Seite hat einen Fehler", - "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions": "Nur, was ein Gateway für andere Computer braucht: keine Agenten oder Bibliothek, keine Einstellungen oder Sitzungen der Agenten auf diesem Computer", + "Only what a gateway for other computers needs: no Agents page, nor this computer's agents' settings or sessions": "Nur, was ein Gateway für andere Computer braucht: keine Agenten-Seite, keine Einstellungen oder Sitzungen der Agenten auf diesem Computer", "Now on: magpie web was started with --gateway": "Jetzt an: magpie web wurde mit --gateway gestartet", "Now on: no agents on this computer": "Jetzt an: keine Agenten auf diesem Computer", "Now off: agents found on this computer": "Jetzt aus: Agenten auf diesem Computer gefunden", @@ -17884,8 +17878,6 @@ const I18N = { "still sent": "noch gesendet", "Put RTK on PATH": "RTK in den PATH aufnehmen", "Update RTK": "RTK aktualisieren", - "No agents to write to": "Keine Agenten zum Schreiben", - "Install Claude Code, Codex, Gemini CLI, OpenCode… and the library can give them the same instructions, MCP servers and skills.": "Installieren Sie Claude Code, Codex, Gemini CLI, OpenCode…, und die Bibliothek kann ihnen dieselben Anweisungen, MCP-Server und Skills geben.", "magpie keeps a copy of every file before it writes it.": "magpie sichert jede Datei, bevor es sie schreibt.", "Backups": "Backups", "Not saved yet": "Noch nicht gespeichert", diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 508de14ad..21f96441a 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -69,7 +69,15 @@ magpie.plugin("library", (ctx) => { // places magpie never saw (unseen) only on the rows that name it, like // a gone one, its chip greyed out: opening its files would start WSL // (#3896, cybercaius on Discord). - const shownAgents = () => lib.agents.filter((a) => !a.gone && !a.unseen && !isHidden(a)); + // In gateway mode (gatewaymode.go) none is shown: the page is the + // MCP servers the router gives other computers' apps. + const shownAgents = () => gatewayPage() ? [] : lib.agents.filter((a) => !a.gone && !a.unseen && !isHidden(a)); + // With no agent to write to, none on this computer or gateway mode, the + // library is its MCP servers alone, served to any app through the router + // (treeman_26897 on Discord: magpie on a server, an MCP entry point for + // remote clients, had no way to turn the router on). + const gatewayPage = () => typeof gatewayMode !== "undefined" && !!gatewayMode; + const agentless = () => !!lib && (gatewayPage() || !lib.agents.length); const withGone = (all, on) => [...all, ...lib.agents.filter((a) => (a.gone || a.unseen && !isHidden(a)) && (on || []).includes(a.id) && !all.some((x) => x.id === a.id))]; const mcpAgents = () => shownAgents().filter((a) => a.mcp) .map((a) => a.mcpVia ? { ...a, aside: t("{agent} reads MCP servers through the {ext} extension", { agent: a.name, ext: a.mcpVia }) } : a); @@ -816,7 +824,7 @@ magpie.plugin("library", (ctx) => { function libHead(counts) { const head = el("div", "lib-head"); const n = (k) => (counts?.[k] ? " · " + counts[k] : ""); - const tabs = segs([ + const tabs = segs(agentless() ? [["mcp", t("MCP servers") + n("mcp")]] : [ ["instructions", t("Instructions")], ["mcp", t("MCP servers") + n("mcp")], ["skills", t("Skills") + n("skills")], @@ -873,13 +881,12 @@ magpie.plugin("library", (ctx) => { const caret = focus ? [document.activeElement.selectionStart, document.activeElement.selectionEnd] : null; page.replaceChildren(); fits = []; + // the MCP servers alone with no agent to write to; the tab the reader + // last picked is kept for when there is one + if (agentless()) tab = "mcp"; const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length }); page.append(head); head.classList.toggle("stuck", top > 0); - if (!lib.agents.length) { - page.append(empty(t("No agents to write to"), t("Install Claude Code, Codex, Gemini CLI, OpenCode… and the library can give them the same instructions, MCP servers and skills."))); - return; - } // what changed in a tab is drawn in place: only another tab (or the // first one after the skeleton) fades in const problems = problemsCard(); @@ -1640,12 +1647,17 @@ magpie.plugin("library", (ctx) => { const reaches = (s) => (a) => !a || (!(remote(s) && a.noRemote) && !(s.transport === "sse" && a.noSSE) && !(envRefs(s) && a.noEnvRefs)); function renderServers(body) { - body.append(intro(t("Add a server once and switch it on for the agents that should have it — magpie writes it into each one's config in the shape that agent reads."))); + body.append(intro(agentless() + ? t("Add the servers other apps should reach, and turn on the MCP router: they connect at its address, from another computer with a gateway key.") + : t("Add a server once and switch it on for the agents that should have it — magpie writes it into each one's config in the shape that agent reads."))); const all = mcpAgents(); pickingFor("servers", lib.servers); if (!lib.servers.length) { const add = button(t("+ Add a server"), "action", () => editServer(null)); - body.append(empty(t("No servers in the library yet"), lib.foundServers.length ? t("Add one, or bring in those your agents already have, below.") : t("Paste a server's JSON from its README, or fill it in."), add)); + body.append(empty(t("No servers in the library yet"), lib.foundServers.length && !agentless() ? t("Add one, or bring in those your agents already have, below.") : t("Paste a server's JSON from its README, or fill it in."), add)); + // with no agent, the router is what the page is for: there to turn + // on before the first server + if (agentless()) body.append(...hubPart()); } else { const list = el("div", "list lib-list"); // in the order the reader picked (#481), A→Z till then @@ -1678,12 +1690,13 @@ magpie.plugin("library", (ctx) => { // checked only when the reader clicks its status (#1597, xiaozhu1337), // and again once it changed after that: a sign-in since isn't left // beside "needs sign-in" (新v学员 on Discord) - const unchecked = lib.servers.filter((s) => (inUse(s) || health.has(s.name)) && health.get(s.name)?.key !== healthKey(s)); + // With no agent, the router is what starts them, so on it checks them too + const unchecked = lib.servers.filter((s) => (inUse(s) || (agentless() && lib.mcpHub && inHub(s)) || health.has(s.name)) && health.get(s.name)?.key !== healthKey(s)); queueMicrotask(() => checkHealth(unchecked)); } // an agent's own servers (Codex's node_repl, added each time it starts) // aren't listed: magpie leaves them as they are - const found = lib.foundServers.filter((f) => !f.own); + const found = agentless() ? [] : lib.foundServers.filter((f) => !f.own); if (found.length) { const rh = el("div", "row-head"); rh.append(el("span", "label", t("In your agents")), el("span", "grow"), el("span", "note", t("not in the library — bring one in to manage it here"))); @@ -1692,10 +1705,10 @@ magpie.plugin("library", (ctx) => { for (const f of found) list.append(foundServerRow(f)); body.append(list); } - if (lib.servers.length || lib.projects.length) renderProjects(body, "mcp"); + if (!agentless() && (lib.servers.length || lib.projects.length)) renderProjects(body, "mcp"); const skip = shownAgents().filter((a) => !a.mcp); if (skip.length) body.append(el("p", "lib-aside", t("{agents} has no MCP servers magpie can write.", { agents: skip.map((a) => a.name).join(", ") }))); - body.append(...asleepAsides()); + if (!gatewayPage()) body.append(...asleepAsides()); // WorkBuddy connects a server only once it is trusted there, again // after its command or address changes (#1266) for (const wb of shownAgents().filter((a) => (a.id === "workbuddy" || a.id === "workbuddy-ai") && a.mcp)) { @@ -1716,12 +1729,16 @@ magpie.plugin("library", (ctx) => { const row = el("div", "row lib-row lib-hub"); const who = el("div", "who"); who.append(el("div", "name", t("MCP router"))); - who.append(el("div", "sub wraps", lib.mcpHub + who.append(el("div", "sub wraps", agentless() + ? (lib.mcpHub ? t("Any app connects at the address below for every server in the library, as server__tool.") : t("Serve every server in the library at one address, for any app to connect to.")) + : lib.mcpHub ? t("Each agent is given one server, magpie, in place of these. magpie runs each server once for all of them and hands each call to it, as server__tool. Restart an agent for it to read the change.") : t("Serve every server through magpie: each agent is given one server, magpie, in place of these, and any other app connects at one address."))); if (lib.mcpHub) who.append(el("div", "sub lib-hubstats", hubStats())); row.append(hubMark(), who, toggle(!!lib.mcpHub, t("MCP router"), (on) => - change("servers/hub", { on }, on + change("servers/hub", { on }, agentless() + ? (on ? t("The MCP router is on: apps can connect at its address") : t("The MCP router is off")) + : on ? t("The agents are given magpie's one MCP server — restart them to use it") : t("The agents are given each server's own entry again — restart them to use it")))); list.append(row); @@ -1841,7 +1858,7 @@ magpie.plugin("library", (ctx) => { const given = hubAgents().filter((a) => a.hub === "on").map((a) => a.name); if (given.length) parts.push(t("in {agents}", { agents: given.length > 3 ? t("{first} and {n} more", { first: given.slice(0, 2).join(", "), n: given.length - 2 }) : given.join(", ") })); // the owner, counting two servers and seeing one: where the other went - const direct = directNames(); + const direct = agentless() ? "" : directNames(); if (direct) parts.push(t("{name} is given to each agent directly", { name: direct })); return parts.join(" · "); } @@ -2123,7 +2140,8 @@ magpie.plugin("library", (ctx) => { sub.title = serverLine(s); who.append(noteSub(s.note, sub, serverLine(s)), toolsEl(s.name)); row.append(mark(s.icon, s.transport === "stdio" ? GLYPH.cmd : GLYPH.web), who, ...removeAct(() => confirmRemoveServer(s)), - agentChips(withGone(all, s.agents), s.agents, chipsChange("servers/agents", s.name, "servers", (x) => serverRow(x, all)), { problems: s.problems, blocked: sseBlocked(s), all: true })); + // no agent to give it to: other apps reach it through the router + ...(agentless() ? [] : [agentChips(withGone(all, s.agents), s.agents, chipsChange("servers/agents", s.name, "servers", (x) => serverRow(x, all)), { problems: s.problems, blocked: sseBlocked(s), all: true })])); if (picking) return pickRow(row, s.name); // a line of its own under the row, not in the name's column (tao0194) if (s.name === "magpie-browser" && !s.agents?.length) row.append(browserAsk(row)); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index cb871cef3..5cc07f185 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -2,6 +2,11 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "The MCP router is on: apps can connect at its address": "MCP 路由已打开:应用可以连接它的地址", + "The MCP router is off": "MCP 路由已关闭", + "Any app connects at the address below for every server in the library, as server__tool.": "任何应用连接下面的地址,即可使用资源库里的全部服务器,工具名为 server__tool。", + "Serve every server in the library at one address, for any app to connect to.": "在一个地址上提供资源库里的全部服务器,供任何应用连接。", + "Add the servers other apps should reach, and turn on the MCP router: they connect at its address, from another computer with a gateway key.": "添加其他应用要用的服务器,再打开 MCP 路由:它们连接路由地址,从其他电脑连接时需要网关密钥。", "Tools on demand": "按需加载工具", "An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.": "给一个 Agent 的工具超过 10 个时,改为给它两个工具:一个查找工具,一个运行工具,这样工具定义不会出现在每次请求里。Claude Code、Claude Desktop、Codex 和 Pi 会自己查找工具,仍会拿到全部工具。", "Agents are given the router's tools on demand — restart them to use it": "Agent 现在按需拿到路由的工具 — 重启它们后生效", @@ -784,6 +789,11 @@ magpie.strings({ "{agents} can be changed once it runs.": "{agents} 要等它运行后才能修改。", }, "zh-TW": { + "The MCP router is on: apps can connect at its address": "MCP 路由已開啟:應用程式可以連線到它的位址", + "The MCP router is off": "MCP 路由已關閉", + "Any app connects at the address below for every server in the library, as server__tool.": "任何應用程式連線下面的位址,即可使用資源庫裡的全部伺服器,工具名稱為 server__tool。", + "Serve every server in the library at one address, for any app to connect to.": "在一個位址上提供資源庫裡的全部伺服器,供任何應用程式連線。", + "Add the servers other apps should reach, and turn on the MCP router: they connect at its address, from another computer with a gateway key.": "新增其他應用程式要用的伺服器,再開啟 MCP 路由:它們連線路由位址,從其他電腦連線時需要閘道金鑰。", "Tools on demand": "按需載入工具", "An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.": "給一個 Agent 的工具超過 10 個時,改為給它兩個工具:一個尋找工具,一個執行工具,這樣工具定義不會出現在每次請求裡。Claude Code、Claude Desktop、Codex 和 Pi 會自己尋找工具,仍會拿到全部工具。", "Agents are given the router's tools on demand — restart them to use it": "Agent 現在按需取得路由的工具 — 重新啟動它們後生效", @@ -1566,6 +1576,11 @@ magpie.strings({ "{agents} can be changed once it runs.": "{agents} 要等它執行後才能修改。", }, ja: { + "The MCP router is on: apps can connect at its address": "MCP ルーターをオンにしました:アプリはそのアドレスに接続できます", + "The MCP router is off": "MCP ルーターをオフにしました", + "Any app connects at the address below for every server in the library, as server__tool.": "どのアプリも下のアドレスに接続すると、ライブラリのすべてのサーバーを server__tool として使えます。", + "Serve every server in the library at one address, for any app to connect to.": "ライブラリのすべてのサーバーを一つのアドレスで提供し、どのアプリからも接続できるようにします。", + "Add the servers other apps should reach, and turn on the MCP router: they connect at its address, from another computer with a gateway key.": "他のアプリが使うサーバーを追加し、MCP ルーターをオンにします:アプリはルーターのアドレスに接続し、他のコンピューターからはゲートウェイキーが必要です。", "Tools on demand": "ツールをオンデマンドで渡す", "An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.": "エージェントに渡すツールが 10 個を超えると、代わりにツールを探すものと実行するものの 2 つを渡し、ツールの定義が毎回のリクエストに入らないようにします。Claude Code、Claude Desktop、Codex、Pi は自分でツールを探すので、すべてのツールが渡されます。", "Agents are given the router's tools on demand — restart them to use it": "エージェントにルーターのツールをオンデマンドで渡します — 反映するにはエージェントを再起動してください", @@ -2348,6 +2363,11 @@ magpie.strings({ "{agents} can be changed once it runs.": "{agents} は起動後に変更できます。", }, de: { + "The MCP router is on: apps can connect at its address": "Der MCP-Router ist an: Apps verbinden sich mit seiner Adresse", + "The MCP router is off": "Der MCP-Router ist aus", + "Any app connects at the address below for every server in the library, as server__tool.": "Jede App verbindet sich mit der Adresse unten und erreicht jeden Server der Bibliothek, als server__tool.", + "Serve every server in the library at one address, for any app to connect to.": "Stellt jeden Server der Bibliothek unter einer Adresse bereit, mit der sich jede App verbinden kann.", + "Add the servers other apps should reach, and turn on the MCP router: they connect at its address, from another computer with a gateway key.": "Fügen Sie die Server hinzu, die andere Apps erreichen sollen, und schalten Sie den MCP-Router ein: Sie verbinden sich mit seiner Adresse, von einem anderen Computer mit einem Gateway-Schlüssel.", "Tools on demand": "Tools bei Bedarf", "An agent given more than 10 tools gets two in their place, one that finds a tool and one that runs it, so their definitions stay out of every request. Claude Code, Claude Desktop, Codex and Pi find tools themselves and are given every one.": "Ein Agent, der mehr als 10 Tools bekäme, bekommt stattdessen zwei: eines findet ein Tool, das andere führt es aus, damit ihre Definitionen nicht in jeder Anfrage stehen. Claude Code, Claude Desktop, Codex und Pi suchen Tools selbst und bekommen alle.", "Agents are given the router's tools on demand — restart them to use it": "Agents bekommen die Tools des Routers bei Bedarf — starte sie neu, damit sie es nutzen", diff --git a/internal/gui/gatewaymode.go b/internal/gui/gatewaymode.go index 77c34fae6..1c27edecd 100644 --- a/internal/gui/gatewaymode.go +++ b/internal/gui/gatewaymode.go @@ -16,8 +16,9 @@ import ( // Gateway mode (Player on Discord): `magpie web` on a server that is only // the gateway for other machines' agents shows what such a gateway needs — -// Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings — and leaves out -// what is this machine's agents' (Agents, Library, the settings +// Providers, Gateway, Routing, Usage, Sessions, Plugins, Settings and the +// Library's MCP servers with the router (treeman_26897) — and leaves out +// what is this machine's agents' (Agents, the Library's other tabs, the settings // written into agents' files) and its desktop's (the tray, the Dock, open // at login, notifications). It is the browser page's alone: the app's // windows show everything whatever it says. diff --git a/internal/gui/tests/gateway-mode.test.cjs b/internal/gui/tests/gateway-mode.test.cjs index 71bba5442..d207ee883 100644 --- a/internal/gui/tests/gateway-mode.test.cjs +++ b/internal/gui/tests/gateway-mode.test.cjs @@ -1,7 +1,7 @@ // Run with Node's test runner and Playwright on the module path; see README.md. // Gateway mode (Player on Discord): magpie web on a server that is only // the gateway for other computers' agents. boot.js says so and the page -// opens on Providers with no Agents or Library tab, an address +// opens on Providers with no Agents tab, an address // kept for one of them opening Providers; Settings leaves out what is // written into this computer's agents' files (provider in model names; // the Codex and Claude Code settings live on the Agents page, which is @@ -82,9 +82,10 @@ const L = { en: { mode: "Gateway mode", noAgents: "Now on: no agents on this computer", off: "Now off: agents found on this computer" }, zh: { mode: "网关模式", noAgents: "当前开启:本机没有 Agent", off: "当前关闭:本机找到了 Agent" }, }; -const HIDDEN = ["agents", "library"]; +// the Library stays, its MCP servers alone, for the router (treeman_26897) +const HIDDEN = ["agents"]; // in the order the pages are grouped in (work, models, insights, extend) -const KEPT = ["sessions", "providers", "routing", "gateway", "usage", "masking", "plugins"]; +const KEPT = ["sessions", "library", "providers", "routing", "gateway", "usage", "masking", "plugins"]; // the tabs shown, the page shown const tabs = (page) => page.evaluate(() => [...document.querySelectorAll("#nav button[data-view]")].filter((b) => !b.hidden && b.offsetParent).map((b) => b.dataset.view)); diff --git a/internal/gui/tests/last-page.test.cjs b/internal/gui/tests/last-page.test.cjs index ea60597a5..4757357fe 100644 --- a/internal/gui/tests/last-page.test.cjs +++ b/internal/gui/tests/last-page.test.cjs @@ -5,7 +5,7 @@ // again (no ?view=) and reloaded is on Routing, its tab picked, nothing // scrolled. A page asked for (?view=, the tray's links) wins over the one // kept, Agents too. A page kept that isn't one, or one gateway mode leaves -// out (Agents, Library), gives way to the first page (Providers there). +// out (Agents), gives way to the first page (Providers there). // Chromium and WebKit, 1100 (sidebar) and 420 (header's tabs) wide. No // backend: the API is faked. const assert = require("node:assert/strict"); @@ -100,7 +100,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(errors, [], where); await context.close(); - // magpie web in gateway mode: Agents and Library aren't there + // magpie web in gateway mode: Agents isn't there (the Library is, for + // its MCP router) const gw = await browser.newContext({ viewport: { width, height: 640 }, reducedMotion: "reduce" }); const gp = await gw.newPage(); gp.setDefaultTimeout(5000); @@ -109,7 +110,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", gp.on("pageerror", (e) => gerr.push(e.message)); await gp.route("**/*", server({ web: true, gateway: true })); await open(gp, BASE, "providers", `${where} gateway: first open`); - for (const v of ["agents", "library"]) { + for (const v of ["agents"]) { await keep(gp, v); await open(gp, BASE, "providers", `${where} gateway: ${v} kept`); } diff --git a/internal/gui/tests/library-mcp-agentless.test.cjs b/internal/gui/tests/library-mcp-agentless.test.cjs new file mode 100644 index 000000000..31ab7dca0 --- /dev/null +++ b/internal/gui/tests/library-mcp-agentless.test.cjs @@ -0,0 +1,181 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// treeman_26897 on Discord: magpie run as an MCP entry point for remote +// clients has no agents, and the MCP router could only be turned on with +// one to write to: the Library said "No agents to write to", and in +// gateway mode (magpie web on such a server) it wasn't there at all. +// With no agent, or in gateway mode, the Library is its MCP tab alone: the +// servers with no agent chips, nothing from agents' own configs, and the +// router's switch, there before the first server too. Its lines say any +// app connects at the address; a click posts servers/hub on, says the +// router is on, counts what it serves and shows the address, and Connect… +// has Other apps alone, with the gateway key a remote app needs. In every +// language, both engines, the app with no agents at 1100px and a browser +// in gateway mode at 420px: no sideways scroll, no native select. +// 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 HOME = "/srv/mg"; +const fixture = (st) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + mcpHub: st.on, hubPath: "/mcp/magpie/hub/", + // in gateway mode this computer's agents are there, and not shown + agents: st.gateway ? [{ id: "claude", name: "Claude Code", icon: "claudecode-color", skills: `${HOME}/.claude/skills`, mcp: `${HOME}/.claude.json`, ...(st.on ? { hub: "on" } : {}) }] : [], + instructions: { agents: [], sets: [] }, foundSkills: [], skills: [], problems: [], + foundServers: st.gateway ? [{ name: "agent-own", transport: "stdio", command: "npx", args: ["agent-own"], agents: ["claude"] }] : [], + projects: st.gateway ? [{ path: `${HOME}/code/app`, servers: { notes: ["claude"] } }] : [], + servers: st.none ? [] : [{ name: "notes", transport: "stdio", command: "uvx", args: ["notes-mcp"], agents: st.gateway ? ["claude"] : [] }], +}); + +let I18N; +function tr(lang, key, vars = {}) { + let s = key; + if (lang !== "en") { + assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`); + s = I18N[lang][key]; + } + return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m)); +} + +function server(lang, st) { + return 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:"${lang}",theme:"light",web:${st.web}${st.gateway ? ",gateway: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", gateway: "http://127.0.0.1:3425", publicURL: "https://mcp.example.net" } }); + if (url.pathname === "/api/library") return json(fixture(st)); + if (url.pathname === "/api/library/servers/hub") { + const body = req.postDataJSON(); + st.sent.push(body); + st.on = body.on; + return json({ ...fixture(st), result: { changed: [] } }); + } + if (url.pathname === "/api/library/mcp/check") { + const names = req.postDataJSON().names; + st.checked.push(...names); + return json({ servers: Object.fromEntries(names.map((n) => [n, { state: "ok", tools: 2 }])) }); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + 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({}); + if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const sideways = (page) => page.evaluate(() => { + const over = []; + const w = document.documentElement.clientWidth; + if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth); + for (const e of document.querySelectorAll("#view-library .lib-hub, #view-library .lib-hub .lib-switch, #view-library .lib-server, #view-library .lib-hubat, #view-library .lib-hubat .lib-hubconnect, .lib-hubsheet, .lib-hubsheet .lib-hubapp, .lib-hubsheet .lib-hubaddr, .lib-hubsheet .bar button")) { + const r = e.getBoundingClientRect(); + if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right)); + } + return over; +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the MCP router with no agent", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + I18N = strings().I18N; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + + for (const width of [1100, 420]) for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + await t.test(`${lang} ${width}px`, async () => { + const w = (key, vars) => tr(lang, key, vars); + // the app with no agents; a browser in gateway mode, its agent not shown + const web = width < 800; + const st = { on: false, sent: [], checked: [], web, gateway: web, none: false }; + const where = web ? "gateway mode" : "no agents"; + const url = (web ? "https://mcp.example.net" : "http://127.0.0.1:3425") + "/mcp/magpie/hub"; + const errors = []; + const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + // the Skills tab last left: there is only MCP now + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, st)); + await page.goto("http://magpie.test/"); + // the Library is a page in gateway mode too + const nav = page.locator('button[data-view="library"]'); + assert.ok(await nav.isVisible(), `${where}: no Library tab`); + await nav.click(); + const v = page.locator("#view-library"); + const hub = v.locator(".lib-hub"); + await hub.waitFor(); + + // the MCP tab alone, and nothing of agents + assert.deepEqual((await v.locator(".lib-tabs .opt").allTextContents()).map((x) => x.trim().replace(/ · \d+$/, "")), [w("MCP servers")], `${where}: the tabs`); + assert.equal((await v.locator(".lib-intro").first().textContent()).trim(), w("Add the servers other apps should reach, and turn on the MCP router: they connect at its address, from another computer with a gateway key."), where); + assert.equal(await v.locator(".lib-server").count(), 1, where); + assert.equal(await v.locator(".lib-ag, .lib-agents").count(), 0, `${where}: agent chips`); + const text = await v.textContent(); + for (const gone of [w("In your agents"), w("In projects"), "Claude Code", "agent-own"]) assert.ok(!text.includes(gone), `${where}: ${gone} is shown`); + assert.equal(await page.locator("select").count(), 0); + + // off: what it would do + assert.equal((await hub.locator(".name").textContent()).trim(), w("MCP router")); + assert.equal((await hub.locator(".sub.wraps").textContent()).trim(), w("Serve every server in the library at one address, for any app to connect to.")); + const sw = hub.locator(".lib-switch"); + assert.equal(await sw.getAttribute("aria-checked"), "false"); + assert.equal(await v.locator(".lib-hubat").count(), 0); + assert.deepEqual(await sideways(page), [], `${where}: sideways scroll, off`); + + // on: the router is on, what it serves, and its address + await sw.click(); + await page.waitForFunction((x) => document.querySelector("#status")?.textContent === x, w("The MCP router is on: apps can connect at its address")); + assert.deepEqual(st.sent, [{ on: true }]); + await page.waitForFunction(() => document.querySelector("#view-library .lib-hub .lib-switch")?.getAttribute("aria-checked") === "true"); + assert.equal((await v.locator(".lib-hub .sub.wraps").textContent()).trim(), w("Any app connects at the address below for every server in the library, as server__tool.")); + await page.waitForFunction((x) => document.querySelector("#view-library .lib-hubstats")?.textContent === x, [w("1 server"), w("{n} tools", { n: 2 })].join(" · ")); + assert.ok(st.checked.includes("notes"), `${where}: the router's server isn't checked`); + assert.equal((await v.locator(".lib-hubURL").textContent()).trim(), url); + assert.deepEqual(await sideways(page), [], `${where}: sideways scroll, on`); + + // Connect…: other apps alone, with the gateway key + await v.locator(".lib-hubconnect").click(); + const sheet = page.locator(".lib-hubsheet"); + await sheet.waitFor(); + assert.equal(await sheet.locator(".ebody > .segs").count(), 0, `${where}: the sheet has tabs`); + assert.equal(await sheet.locator(".lib-hubagent").count(), 0); + assert.equal((await sheet.locator(".lib-hubaddr code").textContent()).trim(), url); + assert.ok(await sheet.locator(".lib-hubapp").count() >= 3); + assert.equal((await sheet.locator(".lib-hubcap").textContent()).trim(), w("From another computer, use the address magpie is reached at there, with a gateway key: Authorization: Bearer .")); + assert.deepEqual(await sideways(page), [], `${where}: sideways scroll, sheet`); + await sheet.locator(".bar button.primary").click(); + await sheet.waitFor({ state: "hidden" }); + + // off again + await v.locator(".lib-hub .lib-switch").click(); + await page.waitForFunction((x) => document.querySelector("#status")?.textContent === x, w("The MCP router is off")); + assert.deepEqual(st.sent, [{ on: true }, { on: false }]); + + // no server yet: the switch is there to turn on first + st.none = true; + await page.reload(); + await page.locator('button[data-view="library"]').click(); + await v.locator(".lib-hub").waitFor(); + assert.equal(await v.locator(".lib-server").count(), 0); + assert.ok((await v.textContent()).includes(w("Paste a server's JSON from its README, or fill it in.")), where); + assert.equal(await v.locator(".lib-hub .lib-switch").getAttribute("aria-checked"), "false"); + assert.deepEqual(await sideways(page), [], `${where}: sideways scroll, no server`); + + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/site/public/docs/docker.html b/site/public/docs/docker.html index 6754453fc..befff8ce4 100644 --- a/site/public/docs/docker.html +++ b/site/public/docs/docker.html @@ -129,7 +129,7 @@ docker logs magpie

The browser UI

Open the link from the log. The key in it is traded for a cookie and taken out of the address; a page opened without it is turned away (401). With MAGPIE_WEB_KEY set (16 or more letters, digits or - . _ ~; openssl rand -hex 16 makes one) the key stays the same across restarts and the browser stays signed in for 400 days. Without it, every start makes a new key and the cookie lasts the browser session.

-

The page is in gateway mode: Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings, with no Agents or Library, since there are no agents in the container. Sessions lists only the sessions of agents on other computers that came through this gateway, never this machine’s agents’ files. Settings → General → Gateway mode turns it off.

+

The page is in gateway mode: Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings, with no Agents, since there are no agents in the container. Library has its MCP servers alone, with the MCP router: other computers’ apps connect at the router’s address with a gateway key. Sessions lists only the sessions of agents on other computers that came through this gateway, never this machine’s agents’ files. Settings → General → Gateway mode turns it off.

On a NAS or a server you reach over SSH, open the page through a tunnel rather than publishing 3430: ssh -L 3430:127.0.0.1:3430 you@nas, then the log’s link on your own computer.

Anyone with the link can change magpie and see its keys. Keep 3430 on loopback or a VPN. Across the network, serve it over HTTPS: give magpie a certificate with MAGPIE_TLS_CERT and MAGPIE_TLS_KEY, or put it behind a reverse proxy with TLS, such as Caddy.