Files
magpie/internal/library/bridge_mcp.go
T
yetone 4c8e1cfdfc providers: a Remote magpie's MCP servers go to the Library only when switched on, and follow its rename
treeman_26897 (Discord) on v0.1.3127's bridge MCP auto-discovery:

- Renamed (name and id), a Remote magpie's auto-added MCP server went:
  adoptBridges keyed it on the provider id, and after provider.Rename
  that id is gone, so the server was taken out as the provider's. Now
  RemoteHub carries the provider's Was, and adoptBridges moves the
  server's bridge, bridgesOn and bridgesOffered from an id it had to
  the id it has (one that another provider has now stays that one's).
  The server keeps its name.
- The add dialog had only the address and key. A new Remote magpie's
  editor has a Name and an ID under the key; blank, they are the
  preset's as before (provider.Add numbers them when taken), and the
  ID follows the name until one is typed.
- Adding its MCP servers is opt-in: a switch, "Add its MCP servers to
  the Library", in the add dialog (off) and in a saved one's editor.
  It lives in library.json (bridgesOn); /api/providers says it as
  libraryMCP and the save takes it (library.SetRemoteMCP). On asks the
  remote at once (provider.AskRemoteHub) when no model list is fetched
  on that save; off takes its server out. Only one switched on is
  asked (bridgeWanted). A server auto-added before this (no bridgesOn)
  is kept, and its switch shows on. A server removed in the Library
  turns its switch off; the provider gone takes its switch with it.

Run (mote, at this tree):
- go test ./internal/library ./internal/provider ./internal/gui:
  library ok; provider ok but TestRenewLoginsKeepsClaudeReading
  (#5481, red the same at the base); gui ok but TestMainWindowCorners
  (#3949). The first gui run had TestCoreScriptBudget red (app.js
  over by ~1.2KB); the new code was made compact and seven editor
  comment blocks cut to one line each. Rebased on 09812e66b the core
  was 68 bytes over again, so three more comments near the editor
  (decidesModel, modelAPIs, pickedOf) were cut: app.js is 161 bytes
  smaller than at its base, and the budget (not raised) passes there:
  go test -run 'TestCoreScriptBudget|Provider' ./internal/gui ok.
- go vet ./..., GOOS=windows go vet ./..., GOOS=linux go vet -tags
  nogui ./...: ok; gofmt -l clean.
- node --test remote-magpie (chromium + webkit, en + zh), i18n-keys,
  i18n-en-no-cjk, gui-de, gui-ja, gui-zh-tw, preset-name,
  name-suffix-remote, remote-self, provider-unmasked, key-row-chips-fit,
  ctx-head-narrow, routing-remote-windows, usage-remote-cards,
  old-webkit: all
  green except reds that are red the same at the base 1ccad582d and
  filed: remote-magpie's "asks for the other magpie's address" fails
  at its decision-model chips before reaching anything this changes
  (#5013, #4398), and i18n-keys' "a plugin's words are its own"
  (#5332, #5426, #5482). With that one chips assertion bypassed in a
  local copy, remote-magpie's new assertions are 12 of 12 green.
  name-suffix-remote went red in Chromium (zh, zh-TW, de) beside 10
  other files, its scrollends.js import failing (#5147); alone it is
  10 of 10 green. The switch's label in the editor is the existing
  "MCP servers".

Broken by hand:
- the Was mapping off: TestRemoteMagpieMCPFollowsRename red ("renamed
  home, read before a sync: switch map[]").
- bridgeWanted/adoptBridge not asking bridgesOn: TestRemoteMagpieMCPIsOptIn
  red ("switched off, asked").
- the new editor's switch defaulting on: remote-magpie red ("off when
  added") in both engines.

Not tried: a real rename against a real second magpie (the library
tests fake RemoteHubs; the provider test renames a real providers.json
in a sandbox and checks Was reaches RemoteHubs). The CLI (provider
add/set remote-magpie) and the TUI have no switch: from there a new
Remote magpie gets no MCP server until it is switched on in the GUI.

Reported-by: treeman_26897 (Discord)
2026-11-06 15:41:43 +08:00

320 lines
9.9 KiB
Go

package library
// A Remote magpie's MCP router is a server in the Library of its own
// (treeman_26897 on Discord: with another magpie as a provider, its MCP
// servers took adding that magpie again under Library → MCP). Once the
// other magpie, its models listed, says its router has a server to give
// (provider/remote_hub.go), the library adds a server named for the
// provider, at that magpie's gateway.HubMCPAll with the provider's key.
// It is then a server as any other: switched on per agent, its tools
// turned off one by one, behind the MCP hub as <name>__<tool>, or written
// into an agent as its own entry with the hub off.
//
// - It is the user's call (treeman_26897 again): a Remote magpie's
// editor has a switch for it, off when one is added, and only one
// switched on (BridgesOn) is asked. Switched off, its server is taken
// out; a server added before the switch was there stays, the switch
// shown on. One taken out in the Library turns the switch off.
// - It is offered once each time it is switched on (BridgesOffered).
// One the user switched off for an agent stays off.
// - It follows the provider's rename: a server, an offer and a switch
// under an id the provider had (its Was) are under its id now.
// - A server the user has at that magpie's router already (its host and
// the router's path) is the one: none is added beside it.
// - It goes with the provider: once providers.json no longer has it, the
// server is taken out. A provider turned off keeps its server. A
// providers.json that can't be read takes nothing out. The provider's
// address and key, changed, change the server's.
// - Edited to another address or key, it is the user's own from then on.
// - It is kept to this computer (Local): the key is this computer's.
// - Added with the hub on, it is on for the agents given the hub's entry;
// with the hub off, on for none until the user switches it on.
// - Two magpies that have each other as Remote magpies don't ask each
// other round: a router asks another's with gateway.RouterHeader, and
// a request with it isn't given a server of this kind
// (gateway.FromRouter).
import (
"log"
"net/url"
"slices"
"strconv"
"strings"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
// remoteHubs are provider's, a test's fake in its place.
var remoteHubs = provider.RemoteHubs
func init() {
provider.RemoteHubAsk = bridgeWanted
provider.RemoteHubFound = func(id string) {
if changed, err := adoptBridge(id); err != nil {
log.Printf("library: giving a Remote magpie's MCP router a server: %v", err)
} else if changed {
if _, err := Sync(); err != nil {
log.Printf("library: syncing after a Remote magpie's MCP router: %v", err)
}
}
}
}
// bridgeURL is the address of the router of the magpie at root.
func bridgeURL(root string) string { return strings.TrimRight(root, "/") + gateway.HubMCPAll }
// bridgeHeaders are the headers its router is asked with.
func bridgeHeaders(key string) map[string]string {
return map[string]string{"Authorization": "Bearer " + key}
}
// routerAt is whether u is a magpie's router at host (scheme and host).
func routerAt(u, host string) bool {
p, err := url.Parse(u)
return err == nil && strings.EqualFold(p.Scheme+"://"+p.Host, host) && strings.HasPrefix(p.Path, gateway.HubMCPAll)
}
// originOf is u's scheme and host.
func originOf(u string) string {
p, err := url.Parse(u)
if err != nil {
return ""
}
return p.Scheme + "://" + p.Host
}
// bridgeWanted is whether the Remote magpie id would be given a server,
// were it to say it serves its router: switched on and not offered one
// yet.
func bridgeWanted(id string) bool {
mu.Lock()
l, err := load()
mu.Unlock()
return err == nil && slices.Contains(l.BridgesOn, id) && !slices.Contains(l.BridgesOffered, id)
}
// RemoteMCPOn are the Remote magpies (provider ids) whose editor's switch
// is on: switched on, or with a server of their router in the library
// (one added before the switch was there too). Nil when the library
// can't be read.
func RemoteMCPOn() map[string]bool {
mu.Lock()
l, err := load()
mu.Unlock()
if err != nil {
return nil
}
l.adoptBridges() // a rename not yet written down: read as it will be
on := map[string]bool{}
for _, id := range l.BridgesOn {
on[id] = true
}
for _, s := range l.MCP {
if s.Bridge != "" {
on[s.Bridge] = true
}
}
return on
}
// SetRemoteMCP turns the switch of the Remote magpie id on or off. On, it
// is asked again at its next model list (provider.AskRemoteHub asks at
// once); off, its server is taken out of the library and the agents.
func SetRemoteMCP(id string, on bool) (*Result, error) {
return change(func(l *Library) error {
l.adoptBridges()
if on {
if !slices.Contains(l.BridgesOn, id) {
l.BridgesOn = append(l.BridgesOn, id)
}
l.BridgesOffered = slices.DeleteFunc(l.BridgesOffered, func(x string) bool { return x == id })
return nil
}
l.BridgesOn = slices.DeleteFunc(l.BridgesOn, func(x string) bool { return x == id })
for _, s := range slices.Clone(l.MCP) {
if s.Bridge == id {
if err := removeServer(l, s.Name); err != nil {
return err
}
}
}
return nil
})
}
// adoptBridge gives the router of the Remote magpie id a server, it having
// said it serves one, saving the library when it changed. It doesn't
// sync.
func adoptBridge(id string) (bool, error) {
hs, err := remoteHubs()
if err != nil {
return false, err
}
i := slices.IndexFunc(hs, func(h provider.RemoteHub) bool { return h.ID == id })
if i < 0 {
return false, nil // not a provider (yet): one being tried in the editor
}
h := hs[i]
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return false, err
}
l.adoptBridges()
if slices.Contains(l.BridgesOffered, id) || !slices.Contains(l.BridgesOn, id) {
return false, nil
}
l.BridgesOffered = append(l.BridgesOffered, id)
host := originOf(bridgeURL(h.Root))
if !slices.ContainsFunc(l.MCP, func(s *Server) bool { return s.Bridge == id || (s.Remote() && routerAt(s.URL, host)) }) {
l.MCP = append(l.MCP, &Server{Name: l.bridgeName(h), Transport: "http", URL: bridgeURL(h.Root),
Headers: bridgeHeaders(h.Key), Bridge: id, Local: true, Agents: l.hubAgents()})
}
return true, l.save()
}
// adoptBridges brings the library's Remote magpie servers in line with the
// providers: what is under an id a provider had is under its id now; one
// whose provider is gone is taken out, and its offer and switch with it;
// the others' address and key are the provider's now. It asks no magpie;
// true when it changed the library.
func (l *Library) adoptBridges() bool {
if len(l.BridgesOffered) == 0 && len(l.BridgesOn) == 0 && !slices.ContainsFunc(l.MCP, func(s *Server) bool { return s.Bridge != "" }) {
return false
}
hs, err := remoteHubs()
if err != nil {
return false // unknown: nothing taken out
}
by := map[string]provider.RemoteHub{}
for _, h := range hs {
by[h.ID] = h
}
// renamed (treeman_26897: its name and id changed, the server went):
// an id no provider has now that one had is that one's
now := map[string]string{}
for _, h := range hs {
for _, w := range h.Was {
if _, taken := by[w]; !taken && w != "" {
now[w] = h.ID
}
}
}
changed := false
renamed := func(ids []string) []string {
var out []string
for _, id := range ids {
if to, ok := now[id]; ok {
id, changed = to, true
}
if !slices.Contains(out, id) {
out = append(out, id)
}
}
return out
}
l.BridgesOffered, l.BridgesOn = renamed(l.BridgesOffered), renamed(l.BridgesOn)
for _, s := range l.MCP {
if to, ok := now[s.Bridge]; ok && s.Bridge != "" {
s.Bridge, changed = to, true
}
}
gone := func(id string) bool { _, ok := by[id]; return !ok }
for _, ids := range []*[]string{&l.BridgesOffered, &l.BridgesOn} {
if n := len(*ids); n > 0 {
*ids = slices.DeleteFunc(*ids, gone)
changed = changed || len(*ids) != n
}
if len(*ids) == 0 {
*ids = nil
}
}
if n := len(l.MCP); n > 0 {
l.MCP = slices.DeleteFunc(l.MCP, func(s *Server) bool { _, ok := by[s.Bridge]; return s.Bridge != "" && !ok })
changed = changed || len(l.MCP) != n
}
for _, s := range l.MCP {
h, ok := by[s.Bridge]
if s.Bridge == "" || !ok {
continue
}
if u := bridgeURL(h.Root); s.URL != u {
s.URL, changed = u, true
}
if want := bridgeHeaders(h.Key); !sameHeaders(s.Headers, want) {
s.Headers, changed = want, true
}
}
return changed
}
// sameHeaders is whether a and b are the same headers.
func sameHeaders(a, b map[string]string) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
if b[k] != v {
return false
}
}
return true
}
// bridgeName is a name no server has, from the provider's name (its id
// when the name gives none): never the hub's own entry's.
func (l *Library) bridgeName(h provider.RemoteHub) string {
base := slug(h.Name)
if base == "" {
base = slug(h.ID)
}
if base == "" {
base = "remote-magpie"
}
if base == HubEntry {
base = "magpie-remote"
}
name := base
for i := 2; l.server(name) != nil; i++ {
name = base + "-" + strconv.Itoa(i)
}
return name
}
// slug is s in a server name's characters, lower case, at most 56 of them.
func slug(s string) string {
var b strings.Builder
dash := false
for _, r := range strings.ToLower(s) {
switch {
case r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_':
if dash && b.Len() > 0 {
b.WriteByte('-')
}
dash = false
b.WriteRune(r)
default:
dash = true
}
if b.Len() >= 56 {
break
}
}
return strings.Trim(b.String(), "-_")
}
// keptBridge is s, edited from old, still the Remote magpie's server: its
// address and key as they were. Edited to others, it is the user's own,
// and on this computer still, the key being this computer's.
func keptBridge(old *Server, s *Server) {
if old.Bridge == "" || s.Bridge != "" {
return
}
s.Local = true
if s.URL == old.URL && sameHeaders(s.Headers, old.Headers) {
s.Bridge = old.Bridge
}
}