Files
magpie/internal/library/mcp_hub_cards.go
T
yetone d55881730d gateway: a key can be held to some MCP servers and tools
wakaka on Discord (#help, 11-06) asked for gateway keys limited to some
MCP servers and tools, as keys already are to models (#882).

A key's MCP list (caller-keys.json "mcp") holds entries "server" (every
tool of it) or "server/tool"; "-" alone is no MCP server; an empty list
is every server, as before. A key issued under another is held to its
issuer's list too.

Every MCP route checks it:
- magpie's own servers (web search, vision, image, Magpie Browser, plugin
  tools) through serveMCP: initialize/tools/list/tools/call are refused
  or filtered per server and tool, and /v1/magpie/key-limits names "mcp";
- the Library hub ("magpie"): only the backing servers and tools the key
  may use are listed, and a call by name or by fallback is refused;
- /mcp/<name> and /mcp/run/<name>: the server is refused, tools/list is
  filtered in JSON and SSE replies, tools/call refused; a reply the
  filter can't read (an encoded body) is a 502, never passed through.

GUI: "MCP servers" in the key row's menu opens the app's own picker (no
native select) with All, No MCP server, each server and its tools (GET
/api/caller-keys/mcp lists magpie's own servers and the Library's). A
key held to some shows a badge saying which, that opens the same list;
a free key shows nothing more in its row, on hover either. A hover badge
was tried first: it pushed the row past 560px (gateway-caller-keys) and
squeezed the masked key under a drag at 420px (gateway-key-arrange).
CLI: magpie gateway-key mcp <id> github fs/read_file | none | all.
zh, zh-TW, ja, de strings; docs/reference.md and the gateway-routing and
library subsystem pages.

Not covered: a model's own built-in web search (a vendor tool, not MCP).

GET /api/caller-keys/mcp is named in the CLI parity test's notYet (its
list is what `magpie gateway-key mcp` takes; TestEveryRouteHasACommandOrIsNamed
caught it at the rebased head).

Run on mote (mote-run), at the pushed head:
- go test ./internal/access ./internal/cli ./internal/gui
  ./internal/library ./internal/gateway at a9c40186d (this change on
  2ce44dc28): ok except internal/gui's TestMainWindowCorners/macOS_26_SDK
  (#3949, the same message on macOS 27). After the rebase onto a9667daad
  (no file in common): TestCoreScriptBudget, TestCallerKey*,
  TestEveryRoute*, TestGatewayKey*, TestKeyMCP*, internal/access and
  go vet ./internal/... at d36f89224's tree: ok.
- gateway-caller-keys chromium en reads wider than 560px 4 of 6 runs
  alone on this branch and 4 of 6 on origin/main a9667daad: #3797,
  recorded there.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: clean; darwin, linux (nogui) and windows builds ok; gofmt -l
  clean.
- GUI: gateway-key-mcp.test.cjs in chromium and webkit, widths 1100 and
  420, en/zh/zh-TW/ja/de: 20/20. Every gateway-key*, gateway-keys* and
  i18n* file in both engines: ok except gateway-key-models en (red on
  origin/main ecc26a339 too, #4081/#5233) and i18n-keys "a plugin's words
  are its own" (red on main, #5332).
- The whole GUI suite (both engines, every language) with the hover
  badge: 91 reds in 25 files. Rerun alone on this branch and on
  origin/main 54dc257f1: only gateway-caller-keys (560px sideways),
  gateway-key-readonly, models-fold and models-select-all-api were red
  on the branch alone; the badge moved into the row menu for the first
  two. After it, every gateway-key*, gateway-caller-keys, gateway-card,
  gateway-connect-keys, api-key-theme and i18n* file passes in both
  engines, except i18n-keys "a plugin's words are its own" (red on main,
  #5332, none of the three strings are this change's) and 1 of 20
  models-select-all-api "the click scrolled" (#4389; models-fold is
  #4071). The rest are red on origin/main too and each has an issue:
  account-weight #4644, codex-auto-reset #2360, header-centre #3479,
  images-codex-one #4618, key-replace #4126, menu-input-scroll #3402,
  mobile-web #3952, model-chip-steady #4388, model-copy-id #4621,
  models-works-only #4391, nav-timeout #4787, omarchy #4624,
  page-width-steady #5013, phone-connect-menu #4706/#4707,
  plugin-move-unserved #4392.

Broken by hand, each went red: the serveMCP server gate, call check and
list filter, the own-server list filter and key-limits "mcp"
(TestKeyMCPOwnServer); hubTools, hubServersOf, the hubToolNamed
fallback and hubMCPRun (TestKeyMCPHub); /mcp/run (TestKeyMCPRun); the
/mcp/<name> guard and filter (TestKeyMCPProxy); the GUI's "No MCP
server" being exclusive (gateway-key-mcp).
gateway-key-readonly chromium 420 ja was red with the hover badge (the
sibling run, the whole suite and its rerun; green on origin/main) and
passes with the badge in the row menu.

Not tried: a real Library server through a live gateway, the hub with a
real agent, and running on Windows or Linux (vet and build only).

Reported-by: wakaka
2026-11-07 03:21:57 +08:00

213 lines
6.0 KiB
Go

package library
// What the router tells an agent of each server behind it
// (packinggoodsllc_07668 on Discord runs magpies that only share MCP
// servers, and an agent given several routers knew each by its name
// alone): the server's own title and first words, and its tools with the
// first clause of each description, as it last listed them. They are kept
// in a file of their own, so a router started again describes its servers
// before it has run any of them; they are what the servers said, not
// magpie's words, and no model writes them.
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/settings"
)
// hubCard is what the router last learnt of one server, for the server as
// it was then (Key: an edit or a sign-in since is another server to it).
type hubCard struct {
Key string `json:"key"`
Title string `json:"title,omitempty"`
Says string `json:"says,omitempty"`
Tools []Tool `json:"tools"`
}
// What a card keeps: a title and the server's own words cut short, at most
// maxCardTools tools, each description cut at maxCardDesc runes (the
// instructions take its first clause).
const (
maxCardTitle = 80
maxCardSays = 300
maxCardTools = 200
maxCardDesc = 200
)
// serverSays is what a server said of itself in initialize's result.
type serverSays struct{ Title, Says string }
// saysOf is what result says of its server: its title, and its description
// (serverInfo.description) or else its instructions' first line.
func saysOf(result json.RawMessage) serverSays {
var r struct {
Instructions string `json:"instructions"`
ServerInfo struct {
Title string `json:"title"`
Description string `json:"description"`
} `json:"serverInfo"`
}
if json.Unmarshal(result, &r) != nil {
return serverSays{}
}
says := r.ServerInfo.Description
if strings.TrimSpace(says) == "" {
for l := range strings.SplitSeq(r.Instructions, "\n") {
if strings.TrimSpace(l) != "" {
says = l
break
}
}
}
return serverSays{Title: clip(r.ServerInfo.Title, maxCardTitle), Says: clip(says, maxCardSays)}
}
func cardsPath() string { return filepath.Join(settings.Dir(), "mcp-hub-servers.json") }
// cards are the hub's cards by server name, read from path once.
var cards struct {
sync.Mutex
m map[string]hubCard
path string
}
// cardKey is s as the hub runs it, short.
func cardKey(s *Server) string {
h := sha256.Sum256([]byte(hubKey(s)))
return hex.EncodeToString(h[:8])
}
// loadCards reads the file when cards haven't been. A file that can't be
// read or parsed is no cards: each is what a server lists, which the next
// list writes again. Held under cards.
func loadCards() {
p := cardsPath()
if cards.m != nil && cards.path == p {
return
}
cards.m, cards.path = map[string]hubCard{}, p
if b, err := os.ReadFile(p); err == nil {
json.Unmarshal(b, &cards.m)
if cards.m == nil {
cards.m = map[string]hubCard{}
}
}
}
// cardOf is s's card, nil when there is none for s as it is now.
func cardOf(s *Server) *hubCard {
cards.Lock()
defer cards.Unlock()
loadCards()
c, ok := cards.m[s.Name]
if !ok || c.Key != cardKey(s) {
return nil
}
return &c
}
// noteCard keeps what s listed (ts) and said of itself, written to the
// file only when it changed; the cards of servers the library no longer
// has go with it.
func noteCard(s *Server, says serverSays, ts []map[string]json.RawMessage) {
c := hubCard{Key: cardKey(s), Title: says.Title, Says: says.Says, Tools: []Tool{}}
for _, t := range ts {
var name, desc string
if json.Unmarshal(t["name"], &name) != nil || name == "" {
continue
}
json.Unmarshal(t["description"], &desc)
c.Tools = append(c.Tools, Tool{Name: clip(name, maxToolName), Description: clip(desc, maxCardDesc)})
if len(c.Tools) == maxCardTools {
break
}
}
// the library first: cards is taken under mu elsewhere (a sync)
mu.Lock()
l, err := load()
mu.Unlock()
cards.Lock()
defer cards.Unlock()
loadCards()
if old, ok := cards.m[s.Name]; ok && old.Key == c.Key && old.Title == c.Title && old.Says == c.Says && slices.Equal(old.Tools, c.Tools) {
return
}
cards.m[s.Name] = c
if err == nil {
for n := range cards.m {
if l.server(n) == nil {
delete(cards.m, n)
}
}
}
writeCards(cards.m)
}
// writeCards writes m through a temporary file, so a reader never sees
// half of it.
func writeCards(m map[string]hubCard) {
b, err := json.MarshalIndent(m, "", " ")
if err != nil {
return
}
p := cardsPath()
if os.MkdirAll(filepath.Dir(p), 0o755) != nil {
return
}
tmp := p + ".tmp"
if os.WriteFile(tmp, b, 0o600) != nil {
os.Remove(tmp)
return
}
if os.Rename(tmp, p) != nil {
os.Remove(tmp)
}
}
// hubServerOf is s as an agent is told of it: what the market says it is
// for, else what it says of itself; its title; and its tools but those
// turned off, as it last listed them.
func hubServerOf(s *Server) gateway.HubServer {
out := gateway.HubServer{Name: s.Name, About: serverAbout(s), Bridge: s.Bridge != "", HereOnly: hereOnly(s), Program: s.Plugin != "" || !s.Remote(), Keyed: keepsSession(s) && !s.Remote()}
c := cardOf(s)
if c == nil {
return out
}
out.Known = true
if out.About == "" {
out.About = c.Says
}
out.Title = c.Title
for _, t := range c.Tools {
if !slices.Contains(s.DisabledTools, t.Name) {
out.Tools = append(out.Tools, gateway.HubToolNote{Name: t.Name, About: t.Description})
}
}
return out
}
// KeyMCPServers are every MCP server in the library, by name, with its
// tools but those turned off as it last listed them (none when it never
// has), for the picker of the servers and tools a gateway key may use
// (wakaka on Discord): the hub, /mcp/<name> and /mcp/run/<name> reach
// each, whether or not the hub gives it.
func KeyMCPServers() []gateway.HubServer {
mu.Lock()
l, err := load()
var ss []*Server
if err == nil {
ss = slices.Clone(l.MCP)
}
mu.Unlock()
slices.SortStableFunc(ss, func(a, b *Server) int { return strings.Compare(a.Name, b.Name) })
return hubAbouts(ss)
}