mcp router: the hub says what its servers are for, and Pi's first prompt hears it
Asked "can you drive a browser?", Pi said no until nudged. Two causes:
- The hub's initialize instructions were one generic sentence ("The tools
of the MCP servers ticked for this agent…"), so nothing said that
playwright drives a browser or deepwiki answers about GitHub repos.
They now start with one line, "Tools of context7 (…), deepwiki (…),
playwright (Drive a real browser), …", at most 250 characters (names
first, "and N more" past room, abouts shared out short-first), then a
"- name: about" line per server. An about comes from the market entry
the server was added from (by key, then by name), else none.
- Pi 1.4.0 lists a codemode server in its system prompt by its config
description, else its instructions' first line, but writes the first
prompt without waiting for codemode servers. In -p runs the first
prompt had "- mcp__magpie (codemode)" and nothing after it. The hub
entry in Pi's mcp.json now carries that line as its description,
kept in step with the servers ticked; a description on another entry
is the user's and is left alone. Pi only: other formats are unchanged.
Sync runs under the library lock, so the hub's servers are read from the
library already loaded ((*Library).hubServers), not through hubServers().
Run (mote, at origin/main ee7b8b072 + this change):
- go test ./internal/library ./internal/gateway -run 'TestHub|TestPi'
- TestHubMCPNamesItsServers: 10 failures without the change, green with it.
- TestHubPiDescription: red with the description assignment removed by
hand ("the hub entry's description \"\""), green with it.
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet,
the three builds, go test -tags nogui -timeout 45m ./...: all ok (87 packages).
Real use: a sandbox HOME with context7, deepwiki, fetch, playwright and
time ticked for Pi 1.4.0 (deepseek through the sandbox gateway). After
`magpie library sync`, Pi's mcp.json hub entry carries the line. Five
everyday questions, none naming MCP, two runs without the description
and three with it:
- "can you drive a browser": playwright used every time.
- the H1 of usemagpie.ai: fetch + playwright every time.
- "is it OK to call a colleague in San Francisco now": bash `date`
without the description (2 of 2), the time server with it (3 of 3).
- Hono timing middleware docs: context7 in 1 of 2 without, 2 of 3 with.
- how the Next.js App Router client cache works: deepwiki in 1 of 2
without, 1 of 3 with; Pi mostly clones the repo instead. Not fixed here.
Not tried: other agents' first prompts (they get the new instructions
text, not a description), Pi versions other than 1.4.0.
This commit is contained in:
@@ -10,6 +10,7 @@ With the Library's switch "MCP router" on (#2679, @minggang123 on X), each agent
|
||||
| Entry | `syncMCP` gives an agent `hubServerFor(t)`, named `magpie` (`HubEntry`), in place of each server it would have written, and records it in `Applied.MCP` like any server, so turning the switch off takes out only that entry and writes each server's own again. The URL is the gateway as that agent reaches it (`gatewayOf`), so a WSL distro or a LAN computer gets its address, with `Authorization: Bearer <key>` when that address needs a key (`agent.KeyAt`). A LAN key or relay change re-syncs (`LANChanged`). magpie's own image server (`isSelf`) is behind the router too, except for an agent in a WSL distro (its id has `@wsl:`), which keeps its own entry to the magpie in that distro. A server the user keeps direct is not (`Server.Hub` = `direct`, `hub` in library.json; #4382, cuipengcx90): each agent given it keeps its own entry, written as with the router off, beside the router's entry for the rest, and started by that agent: Codex on magpie, which is otherwise given a command server as the gateway's `/mcp/run/<name>` that magpie starts from home ([`mcp_run.go`](../../internal/library/mcp_run.go), #3885), is given a direct one's `command`, `args` and `env` with no `cwd`, so Codex starts it in the thread's folder (codex-mcp's `LocalStdioServerLauncher` falls back to the session's `cwd`; `TestRunDirectServerIsCodexsCommand`); an agent whose every server is direct is given no hub entry. `inHub` is the one test, so the router neither lists nor runs a direct server, at `/mcp/magpie/hub` either, and `hubPrune` ends one it held. The default (`""`; `shared` is saved as `""`) is the router's as before. Switching it (`ServerHub`, or a save) goes through `change`, so each agent is written again at once and the entry it had the other way is taken out (`TestHubDirectServer`). The policy is the server's, so a sync carries it. A per-project or per-session backend behind the router (Option B in #4382, keying `hubPool` by roots) is not built. | `hubFor`, `hubServerFor`, `inHub` in `mcp_hub.go`; `syncMCP` in [`sync.go`](../../internal/library/sync.go); [`mcp_signin.go`](../../internal/library/mcp_signin.go) |
|
||||
| Who keeps their entries | An agent keeps each server's own entry, and `AgentView.Hub` says why: `no-remote` (it reaches no server over HTTP: `mcpFile.supports` refuses the entry, as for Claude Desktop), `taken` (a Library server is itself called magpie), `own` (the agent has an entry called magpie that magpie didn't write; it is left as it is). `on` is an agent given the router's entry. An agent given none of the router's servers has no value. | `hubFor` in `mcp_hub.go`; `AgentView.Hub`, `View.MCPHub`, `View.HubPath` in `sync.go` |
|
||||
| Serve | `tools/list` lists the tools of the servers ticked for that agent (at `/mcp/magpie/hub`, agent `""`: every server in the Library, ticked for any agent or none), but those in `DisabledTools`, as `<server>__<tool>`: each part in `[A-Za-z0-9_-]` (other characters `_`), at most 64 characters (`cutName`), `_2`, `_3` on a name two would share. Each tool's description and `inputSchema` go on as the server listed them (an object schema with no properties when it has none). Every tool is listed in full; what keeps them out of each request is the agent's own tool search (Claude Code's `ENABLE_TOOL_SEARCH`, which magpie turns on, see [agent wiring](agent-wiring.md); Codex's `tool_search` on magpie's catalog). An agent with none sends them all. `tools/call` runs one; an unknown name, or another agent's, is error -32602. `initialize` and `ping` are answered; other methods are -32601. Tools only: no resources or prompts. | `hubMCPCall`, `hubNamed` in [`hub_mcp.go`](../../internal/gateway/hub_mcp.go) |
|
||||
| What it serves | An agent that shows the router as one line, and its tools only once they are searched for, learns from that line alone which servers are behind it (a Pi asked about a GitHub repository cloned it rather than ask the DeepWiki behind the router, told only "The tools of the MCP servers in magpie's Library", 11-01). `initialize`'s `instructions` start with `HubLine`: `Tools of <name> (<what it is for>), …`, every server by name, each one's first clause (`hubClause`) cut at a word to an equal share of 250 characters (`hubLineMax`, Pi's `MAX_SERVER_DESCRIPTION_CHARS`), the short ones whole; names that don't fit are counted (`and N more`). A line follows for each server with all it is for, then the text as before. What a server is for is the market's (`serverAbout`): the featured or registry server it is by `serverKey`, whatever it is named, or the featured one it is named after; nothing for the rest. Pi doesn't wait for a codemode server before writing the first prompt (`waitForDirectServers` waits for direct ones), so its instructions miss that prompt; Pi's own mcp.json (`fmtPiNative`) gets the same line as the hub entry's `description`, which Pi shows before connecting (`serverSummary`). It is magpie's on the hub entry only (`mine`), read back to tell a changed list of servers (`Server.about`, `same`), and any other entry's description is the user's. | `HubLine`, `hubAbout` in `hub_mcp.go`; `theHub.Servers`, `hubAbouts`, `hubServerFor` in `mcp_hub.go`; `serverAbout` in [`market.go`](../../internal/library/market.go) |
|
||||
| Router name | What a router says of itself, for an agent given the same tools by two routers (packinggoodsllc_07668 on Discord: one magpie in China, one in Los Angeles) to pick one. `hubWhere`: the user's words (`settings.RouterNote`, one line, 80 characters at most, `CleanRouterNote`), to every caller; with none, this computer's name (`hostName`) to a caller that isn't `local`, and nothing to one that is (one router at hand; the computer's name stays off its prompts). With a value, `initialize`'s `instructions` end `This router: <name>. …`, `serverInfo.title` is `Magpie MCP hub · <name>`, and each tool's description starts `[<name>] ` (once: a description that starts so already, another magpie's router behind this one, isn't given it again). It is this computer's own (`KeepOwn`): a sync never brings another's. Set in the Library's MCP tab (below) or settings.json; the Settings page's save keeps it (`POST /api/settings`). | `hubWhere` in `hub_mcp.go`; `RouterNote`, `SetRouterNote` in [`settings.go`](../../internal/settings/settings.go); `servers/hub-note` in `gui/library.go`; `View.HubNote`, `View.HubName` in `sync.go` |
|
||||
| Magpie Image's project | Magpie Image saves into the project of the agent that called it, though one server serves every agent. Its tools are `HubTool.Roots`: for such a call the router answers the POST as an event stream (`mcpExchange`) and asks the agent `roots/list` on it, waiting `hubRootsWait` (3s); Claude Code answers with its folder. An agent that answers no roots, or none (Codex answers `[]`), is given the workspaces the call's `_meta` names (Codex's `x-codex-turn-metadata.workspaces`, keyed by the folder of each git repository it works in, absolute paths only), and failing those the folder of the call's `_meta.threadId` in Codex's sessions (`sessions.CodexThreadCwd`, its rollout's cwd), only with consent to read them; with neither (a folder that isn't a repository, no consent), none. A caller that isn't local gets no roots. The call goes on with `_meta` `magpie/roots` (file URIs, never null) and `magpie/client` (the first word of the agent's User-Agent, e.g. `claude-code/2.1.314`). The image server, seeing `magpie/roots`, saves into the first root, or `~/Pictures/Magpie` with none (never its own folder), draws as `<client> magpie-image/1`, and sends no `magpie/toolCalled` report, since the router's row is the call's: its result's `_meta` `magpie/model` (provider/model) names the model it drew with, for that row (`HubModelMeta`). | `hubRoots`, `hubClient`, `WithHubCaller` in `hub_mcp.go`; [`mcp_ask.go`](../../internal/gateway/mcp_ask.go); `imageMeta` in `mcp_hub.go`; `project`, `rootOf` in [`imagemcp.go`](../../internal/imagemcp/imagemcp.go); [`codex_cwd.go`](../../internal/sessions/codex_cwd.go) |
|
||||
| Guard | `serveMCP`, as `/mcp/magpie/tools`: a local request, or one with a gateway key; a browser page's Origin that `corsAllowed` doesn't allow is 403; POST only; a 4 MiB body (`hubBody`). The outer `lanGuard`/`corsGuard` already refuse `Origin: null`, a foreign site and a rebound Host. Each call is held to the calling key's limit (`reserveFor`) before anything runs. | `hubMCP`, `hubMCPRun` in `hub_mcp.go`; `serveMCP` in [`search_mcp.go`](../../internal/gateway/search_mcp.go) |
|
||||
|
||||
@@ -101,6 +101,9 @@ type Hub interface {
|
||||
// in the Library for agent "", HubMCPAll's), but those turned off; a
|
||||
// server that couldn't be reached by ctx's end is left out
|
||||
Tools(ctx context.Context, agent string) []HubTool
|
||||
// Servers are the servers behind agent's tools, by name, each with
|
||||
// what it is for where magpie knows it; it starts none of them
|
||||
Servers(agent string) []HubServer
|
||||
// Call runs one tool of server for agent, and is its result as the
|
||||
// server gave it; an error is why it couldn't be run
|
||||
Call(ctx context.Context, agent, server, tool string, args json.RawMessage) (json.RawMessage, error)
|
||||
@@ -112,6 +115,10 @@ type Hub interface {
|
||||
Prune()
|
||||
}
|
||||
|
||||
// HubServer is a server behind the hub as an agent is told of it: About
|
||||
// is what it is for, "" when magpie doesn't know.
|
||||
type HubServer struct{ Name, About string }
|
||||
|
||||
// MCPHub is set by the library; nil, the hub has no server.
|
||||
var MCPHub Hub
|
||||
|
||||
@@ -171,6 +178,111 @@ func hubTools(ctx context.Context, agent string) []hubTool {
|
||||
return hubNamed(MCPHub.Tools(ctx, agent))
|
||||
}
|
||||
|
||||
// hubLineMax is how much of the instructions' first line an agent is sure
|
||||
// to show its model: Pi shows a server as that line, cut at 250 characters
|
||||
// (extensions/mcp, MAX_SERVER_DESCRIPTION_CHARS), and an agent that lists
|
||||
// the router's tools only once they are searched for knows of the servers
|
||||
// behind it from this line alone (a Pi asked about a GitHub repository
|
||||
// cloned it instead of asking DeepWiki, 11-01).
|
||||
const hubLineMax = 250
|
||||
|
||||
// hubAbout is what the instructions say first: HubLine, then a line for
|
||||
// each server with all it is for. It is "" when there is no server.
|
||||
func hubAbout(ss []HubServer) string {
|
||||
if len(ss) == 0 {
|
||||
return ""
|
||||
}
|
||||
out := HubLine(ss) + "\n"
|
||||
for _, s := range ss {
|
||||
if a := strings.Join(strings.Fields(s.About), " "); a != "" {
|
||||
out += "- " + s.Name + ": " + a + "\n"
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// HubLine is one line naming the servers behind the hub, each with what
|
||||
// it is for cut to fit hubLineMax: "" when there is none.
|
||||
func HubLine(ss []HubServer) string {
|
||||
if len(ss) == 0 {
|
||||
return ""
|
||||
}
|
||||
const head = "Tools of "
|
||||
const room = hubLineMax - len(".")
|
||||
short := make([]string, len(ss))
|
||||
for i, s := range ss {
|
||||
short[i] = hubClause(s.About)
|
||||
}
|
||||
line := func(abouts []string, kept int) string {
|
||||
parts := make([]string, 0, kept+1)
|
||||
for i, s := range ss[:kept] {
|
||||
if abouts[i] != "" {
|
||||
parts = append(parts, s.Name+" ("+abouts[i]+")")
|
||||
} else {
|
||||
parts = append(parts, s.Name)
|
||||
}
|
||||
}
|
||||
if n := len(ss) - kept; n > 0 {
|
||||
parts = append(parts, "and "+strconv.Itoa(n)+" more")
|
||||
}
|
||||
return head + strings.Join(parts, ", ")
|
||||
}
|
||||
// the names first: as many as fit, the rest counted
|
||||
none := make([]string, len(ss))
|
||||
kept := len(ss)
|
||||
for kept > 0 && runeLen(line(none, kept)) > room {
|
||||
kept--
|
||||
}
|
||||
// what's left goes to the abouts, the short ones whole, the rest an
|
||||
// equal share, cut at a word; a share too small to say anything is none
|
||||
abouts := make([]string, len(ss))
|
||||
left := room - runeLen(line(none, kept))
|
||||
order := make([]int, 0, kept)
|
||||
for i := range kept {
|
||||
if short[i] != "" {
|
||||
order = append(order, i)
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(order, func(a, b int) int { return runeLen(short[a]) - runeLen(short[b]) })
|
||||
for j, i := range order {
|
||||
share := left/(len(order)-j) - len(" ()")
|
||||
if share < 12 {
|
||||
continue
|
||||
}
|
||||
abouts[i] = hubCut(short[i], share)
|
||||
left -= runeLen(abouts[i]) + len(" ()")
|
||||
}
|
||||
return line(abouts, kept) + "."
|
||||
}
|
||||
|
||||
// hubClause is the first part of a description: up to its first comma,
|
||||
// colon, semicolon or full stop, on one line.
|
||||
func hubClause(s string) string {
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
if i := strings.IndexAny(s, ",:;"); i > 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
if i := strings.Index(s, ". "); i > 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
return strings.TrimSuffix(s, ".")
|
||||
}
|
||||
|
||||
// hubCut is s in at most n characters, cut at a word with an ellipsis.
|
||||
func hubCut(s string, n int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= n {
|
||||
return s
|
||||
}
|
||||
c := string(r[:n-1])
|
||||
if i := strings.LastIndex(c, " "); i > 0 {
|
||||
c = c[:i]
|
||||
}
|
||||
return strings.TrimRight(c, " ,") + "…"
|
||||
}
|
||||
|
||||
func runeLen(s string) int { return len([]rune(s)) }
|
||||
|
||||
func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, map[string]any) {
|
||||
switch m.Method {
|
||||
case "initialize":
|
||||
@@ -178,6 +290,9 @@ func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, m
|
||||
if agent == "" {
|
||||
say = "The tools of every MCP server in magpie's Library, each named <server>__<tool>. Add servers in magpie's Library → MCP."
|
||||
}
|
||||
if MCPHub != nil {
|
||||
say = hubAbout(MCPHub.Servers(agent)) + say
|
||||
}
|
||||
title := "Magpie MCP hub"
|
||||
if w := hubWhere(r); w != "" {
|
||||
say += " This router: " + w + ". Each of its tools' descriptions starts with [" + w + "]; when another MCP server gives the same tools, choose between them by this."
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
@@ -21,8 +22,10 @@ type fakeHub struct {
|
||||
mu sync.Mutex
|
||||
on bool
|
||||
tools map[string][]HubTool // by agent
|
||||
calls []string
|
||||
call func(ctx context.Context, server, tool string) (json.RawMessage, error)
|
||||
// servers are what Servers says, by agent
|
||||
servers map[string][]HubServer
|
||||
calls []string
|
||||
call func(ctx context.Context, server, tool string) (json.RawMessage, error)
|
||||
}
|
||||
|
||||
func (f *fakeHub) On() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.on }
|
||||
@@ -33,6 +36,12 @@ func (f *fakeHub) Tools(_ context.Context, agent string) []HubTool {
|
||||
return f.tools[agent]
|
||||
}
|
||||
|
||||
func (f *fakeHub) Servers(agent string) []HubServer {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.servers[agent]
|
||||
}
|
||||
|
||||
func (f *fakeHub) Call(ctx context.Context, agent, server, tool string, args json.RawMessage) (json.RawMessage, error) {
|
||||
f.mu.Lock()
|
||||
f.calls = append(f.calls, agent+" "+server+" "+tool+" "+string(args))
|
||||
@@ -348,6 +357,73 @@ func TestHubMCPHeldToKeyLimit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// An agent that shows the router as its instructions' first line (Pi,
|
||||
// cut at 250 characters) learns from that line which servers are behind
|
||||
// it and what each is for: a Pi asked about a GitHub repository cloned
|
||||
// it rather than ask the DeepWiki behind the router, told only "The tools
|
||||
// of the MCP servers in magpie's Library" (11-01). Every server is named
|
||||
// and what it is for cut to fit, then said whole below.
|
||||
func TestHubMCPNamesItsServers(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
||||
five := []HubServer{
|
||||
{Name: "context7", About: "Up-to-date documentation and code examples for any library, straight into the prompt."},
|
||||
{Name: "deepwiki", About: "Ask questions about any public GitHub repository and read its generated wiki."},
|
||||
{Name: "fetch", About: "Fetch a web page and hand it over as Markdown."},
|
||||
{Name: "notes"},
|
||||
{Name: "playwright", About: "Drive a real browser: open pages, click, type and read them through the accessibility tree."},
|
||||
{Name: "time", About: "The current time anywhere, and conversions between time zones."},
|
||||
}
|
||||
var many []HubServer
|
||||
for i := range 40 {
|
||||
many = append(many, HubServer{Name: fmt.Sprintf("server-%02d", i), About: "Does one thing well."})
|
||||
}
|
||||
f := &fakeHub{on: true, servers: map[string][]HubServer{"claude": five}}
|
||||
withHub(t, f)
|
||||
h := lanGuard(New().Handler())
|
||||
|
||||
say, _, _ := whereReply(t, h, here)
|
||||
first, rest, _ := strings.Cut(say, "\n")
|
||||
if n := len([]rune(first)); n > 250 {
|
||||
t.Errorf("the first line is %d characters: %q", n, first)
|
||||
}
|
||||
for _, s := range five {
|
||||
if !strings.Contains(first, s.Name) {
|
||||
t.Errorf("the first line doesn't name %s: %q", s.Name, first)
|
||||
}
|
||||
if s.About != "" && !strings.Contains(rest, "- "+s.Name+": "+s.About+"\n") {
|
||||
t.Errorf("%s isn't said whole: %q", s.Name, rest)
|
||||
}
|
||||
}
|
||||
for _, w := range []string{"documentation", "GitHub repository", "web page", "real browser", "current time"} {
|
||||
if !strings.Contains(first, w) {
|
||||
t.Errorf("the first line doesn't say %q: %q", w, first)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(rest, "each named <server>__<tool>") {
|
||||
t.Errorf("how its tools are named is gone: %q", say)
|
||||
}
|
||||
|
||||
// too many to say each: as many names as fit, the rest counted
|
||||
f.mu.Lock()
|
||||
f.servers["claude"] = many
|
||||
f.mu.Unlock()
|
||||
say, _, _ = whereReply(t, h, here)
|
||||
first, _, _ = strings.Cut(say, "\n")
|
||||
if n := len([]rune(first)); n > 250 || !strings.Contains(first, "server-00") || !strings.Contains(first, " more") {
|
||||
t.Errorf("40 servers: %d characters, %q", n, first)
|
||||
}
|
||||
|
||||
// none: as before
|
||||
f.mu.Lock()
|
||||
f.servers["claude"] = nil
|
||||
f.mu.Unlock()
|
||||
if say, _, _ = whereReply(t, h, here); !strings.HasPrefix(say, "The tools of the MCP servers") {
|
||||
t.Errorf("no server: %q", say)
|
||||
}
|
||||
}
|
||||
|
||||
// whereReply is what an agent is told of the router: initialize's
|
||||
// instructions and title, and each tool's description.
|
||||
func whereReply(t *testing.T, h http.Handler, addr string, hdr ...string) (instructions, title string, descs []string) {
|
||||
|
||||
@@ -871,6 +871,37 @@ func serverIcon(l *Library, s *Server) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// serverAbout is what a server is for, where the market says: the
|
||||
// featured or registry server it is, or the featured one it is named
|
||||
// after; "" for the rest.
|
||||
func serverAbout(s *Server) string {
|
||||
k := serverKey(s)
|
||||
for _, m := range featured {
|
||||
if serverKey(&m.server) == k {
|
||||
return m.Description
|
||||
}
|
||||
}
|
||||
for _, m := range popularServers() {
|
||||
if serverKey(&m.server) == k {
|
||||
return m.Description
|
||||
}
|
||||
}
|
||||
seenServers.Lock()
|
||||
for _, m := range seenServers.m {
|
||||
if serverKey(&m.server) == k {
|
||||
seenServers.Unlock()
|
||||
return m.Description
|
||||
}
|
||||
}
|
||||
seenServers.Unlock()
|
||||
for _, m := range featured {
|
||||
if strings.EqualFold(m.ID, s.Name) {
|
||||
return m.Description
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// skillIcon is its repository owner's avatar, for a skill from GitHub.
|
||||
func skillIcon(s *Skill) string {
|
||||
if s.Source == nil || s.Source.Kind != "github" {
|
||||
|
||||
+19
-4
@@ -67,6 +67,10 @@ type Server struct {
|
||||
// started in, or keeps a session's state (#4382, cuipengcx90).
|
||||
Hub string `json:"hub,omitempty"`
|
||||
|
||||
// about is the hub entry's description, for an agent that shows a
|
||||
// server by one before it has connected (Pi, hubServerFor)
|
||||
about string
|
||||
|
||||
// startupWrote is the startup_timeout_sec magpie last wrote in the
|
||||
// entry being written, 0 for none: one the entry has otherwise is the
|
||||
// user's, and stays (startupTheirs)
|
||||
@@ -168,7 +172,7 @@ func (s *Server) check() error {
|
||||
// have it doesn't matter.
|
||||
func (s *Server) same(o *Server) bool {
|
||||
return s.Transport == o.Transport && s.Command == o.Command && slices.Equal(s.Args, o.Args) &&
|
||||
maps.Equal(s.Env, o.Env) && s.URL == o.URL && maps.Equal(s.Headers, o.Headers)
|
||||
maps.Equal(s.Env, o.Env) && s.URL == o.URL && maps.Equal(s.Headers, o.Headers) && s.about == o.about
|
||||
}
|
||||
|
||||
// ---- each agent's own format ----------------------------------------------
|
||||
@@ -609,6 +613,9 @@ func (f *mcpFile) encode(s *Server) ordered {
|
||||
add("args", list(s.Args))
|
||||
optional("env", s.Env)
|
||||
}
|
||||
if s.about != "" {
|
||||
add("description", s.about)
|
||||
}
|
||||
case fmtHermes, fmtAlma:
|
||||
// Hermes' own `hermes mcp add` writes url/headers or
|
||||
// command/args/env; transport: sse is its only other transport
|
||||
@@ -933,6 +940,10 @@ func (f *mcpFile) decode(name string, m map[string]any) (*Server, bool) {
|
||||
} else {
|
||||
local(str(m, "command"), m["args"], m["env"])
|
||||
}
|
||||
// the hub entry's description is magpie's; any other is the user's
|
||||
if f.Format == fmtPiNative && name == HubEntry {
|
||||
s.about = str(m, "description")
|
||||
}
|
||||
default: // Claude Code, Cursor, Copilot, Crush, ZCode, omp, Grok, Zed
|
||||
t := str(m, "type")
|
||||
if u := str(m, "url"); u != "" {
|
||||
@@ -1227,10 +1238,14 @@ var owned = map[mcpFormat][]string{
|
||||
// one there (refKeys): an env_vars or env_keys the user gave a server
|
||||
// whose library entry has none stays theirs.
|
||||
func (f *mcpFile) mine(s *Server) []string {
|
||||
if extra := f.refKeys(s); len(extra) > 0 {
|
||||
return append(slices.Clone(owned[f.Format]), extra...)
|
||||
own := owned[f.Format]
|
||||
if f.Format == fmtPiNative && s.Name == HubEntry {
|
||||
own = append(slices.Clone(own), "description")
|
||||
}
|
||||
return owned[f.Format]
|
||||
if extra := f.refKeys(s); len(extra) > 0 {
|
||||
return append(slices.Clone(own), extra...)
|
||||
}
|
||||
return own
|
||||
}
|
||||
|
||||
// current is the agent's entry read as the server, for comparing with s:
|
||||
|
||||
@@ -104,12 +104,20 @@ func ServerHub(name string, direct bool) (*Result, error) {
|
||||
// hubServerFor is the entry agent t is given for the hub, at the address
|
||||
// the agent reaches the gateway at, with a key when it reaches it from
|
||||
// another machine (a WSL distro under NAT, a computer on the LAN).
|
||||
func hubServerFor(t *Target) *Server {
|
||||
func (l *Library) hubServerFor(t *Target) *Server {
|
||||
base := strings.TrimRight(gatewayOf(t), "/")
|
||||
s := &Server{Name: HubEntry, Transport: "http", URL: base + gateway.HubMCPPath + url.PathEscape(t.Agent.ID)}
|
||||
if k := agent.KeyAt(base); k != gateway.Token {
|
||||
s.Headers = map[string]string{"Authorization": "Bearer " + k}
|
||||
}
|
||||
// Pi connects to a server it doesn't wait for (the hub's, reached by
|
||||
// codemode) while the first prompt is already written, so only a
|
||||
// description gives that prompt its line of what the hub serves
|
||||
// (extensions/mcp, serverSummary): told the router's instructions
|
||||
// alone, a Pi asked about a repository never saw DeepWiki (11-01)
|
||||
if t.MCP != nil && t.MCP.Format == fmtPiNative {
|
||||
s.about = gateway.HubLine(hubAbouts(l.hubServers(t.Agent.ID)))
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -151,7 +159,7 @@ func (l *Library) hubFor(t *Target, a *Applied, entries map[string]map[string]an
|
||||
if !slices.ContainsFunc(l.MCP, func(s *Server) bool { return slices.Contains(s.Agents, id) && inHub(s, id) }) {
|
||||
return nil, ""
|
||||
}
|
||||
hs := hubServerFor(t)
|
||||
hs := l.hubServerFor(t)
|
||||
if err := t.MCP.supports(hs); err != nil {
|
||||
return nil, hubNoRemote
|
||||
}
|
||||
@@ -187,6 +195,11 @@ func hubServers(agentID string) []*Server {
|
||||
if err != nil || !l.MCPHub {
|
||||
return nil
|
||||
}
|
||||
return l.hubServers(agentID)
|
||||
}
|
||||
|
||||
// hubServers are the servers the hub gives agentID from l, by name.
|
||||
func (l *Library) hubServers(agentID string) []*Server {
|
||||
var out []*Server
|
||||
for _, s := range l.MCP {
|
||||
if (agentID == "" || slices.Contains(s.Agents, agentID)) && inHub(s, agentID) {
|
||||
@@ -197,6 +210,17 @@ func hubServers(agentID string) []*Server {
|
||||
return out
|
||||
}
|
||||
|
||||
func (theHub) Servers(agentID string) []gateway.HubServer { return hubAbouts(hubServers(agentID)) }
|
||||
|
||||
// hubAbouts are ss as an agent is told of them.
|
||||
func hubAbouts(ss []*Server) []gateway.HubServer {
|
||||
out := make([]gateway.HubServer, len(ss))
|
||||
for i, s := range ss {
|
||||
out[i] = gateway.HubServer{Name: s.Name, About: serverAbout(s)}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (theHub) Tools(ctx context.Context, agentID string) []gateway.HubTool {
|
||||
ss := hubServers(agentID)
|
||||
lists := make([][]gateway.HubTool, len(ss))
|
||||
|
||||
@@ -460,7 +460,7 @@ func TestHubEntryFromAnotherMachine(t *testing.T) {
|
||||
hubSandbox(t)
|
||||
const there = "http://172.20.0.1:3425"
|
||||
at := func(gw string) *Server {
|
||||
return hubServerFor(&Target{Agent: &agent.Agent{ID: "claude", Gateway: func() string { return gw }}})
|
||||
return (&Library{}).hubServerFor(&Target{Agent: &agent.Agent{ID: "claude", Gateway: func() string { return gw }}})
|
||||
}
|
||||
if s := at(there); s.URL != there+gateway.HubMCPPath+"claude" || len(s.Headers) != 0 {
|
||||
t.Errorf("nothing shared: %+v", s)
|
||||
@@ -610,6 +610,66 @@ func TestHubDirectServer(t *testing.T) {
|
||||
// agent's roots and name in _meta, an empty list when it has none here,
|
||||
// so it saves into that agent's project. The agent's file has the hub's
|
||||
// entry and not the server's own.
|
||||
// An agent is told what each server behind the hub is for, from the
|
||||
// market: the featured server it is by its address whatever it is named,
|
||||
// the featured one it is named after, and nothing made up for the rest.
|
||||
func TestHubSaysWhatServersAreFor(t *testing.T) {
|
||||
hubSandbox(t)
|
||||
ok(t)(SaveServer("", Server{Name: "wiki", Transport: "http", URL: "https://mcp.deepwiki.com/mcp/", Agents: []string{"pi"}}))
|
||||
c7 := fakeStdio(t, "ok", nil)
|
||||
c7.Name, c7.Agents = "context7", []string{"pi"}
|
||||
ok(t)(SaveServer("", *c7))
|
||||
notes := fakeStdio(t, "ok", nil)
|
||||
notes.Name, notes.Agents = "notes", []string{"pi", "claude"}
|
||||
ok(t)(SaveServer("", *notes))
|
||||
ok(t)(SetMCPHub(true))
|
||||
m, _ := marketServer("deepwiki")
|
||||
c, _ := marketServer("context7")
|
||||
want := []gateway.HubServer{{Name: "context7", About: c.Description}, {Name: "notes"}, {Name: "wiki", About: m.Description}}
|
||||
if got := (theHub{}).Servers("pi"); !slices.Equal(got, want) || m.Description == "" || c.Description == "" {
|
||||
t.Fatalf("pi's servers %q, want %q", got, want)
|
||||
}
|
||||
if got := (theHub{}).Servers("claude"); !slices.Equal(got, []gateway.HubServer{{Name: "notes"}}) {
|
||||
t.Fatalf("claude's servers %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Pi writes its first prompt before it has connected to the hub (it waits
|
||||
// for no codemode server), so the hub entry in its mcp.json says what the
|
||||
// hub serves as its description, the line Pi shows of a server, and the
|
||||
// line follows the servers ticked. Another entry's description is the
|
||||
// user's.
|
||||
func TestHubPiDescription(t *testing.T) {
|
||||
h := hubSandbox(t)
|
||||
setPiVersion(t, "1.4.0")
|
||||
file := filepath.Join(h, ".pi/agent/mcp.json")
|
||||
write(t, file, `{"mcpServers": {"theirs": {"command": "t", "description": "My own."}}}`)
|
||||
ok(t)(SaveServer("", Server{Name: "wiki", Transport: "http", URL: "https://mcp.deepwiki.com/mcp", Agents: []string{"pi"}}))
|
||||
ok(t)(SetMCPHub(true))
|
||||
about := func() string {
|
||||
t.Helper()
|
||||
d, _ := piServers(t, file)[HubEntry]["description"].(string)
|
||||
return d
|
||||
}
|
||||
wiki, _ := marketServer("deepwiki")
|
||||
if d := about(); d != gateway.HubLine([]gateway.HubServer{{Name: "wiki", About: wiki.Description}}) || !strings.Contains(d, "GitHub repository") {
|
||||
t.Fatalf("the hub entry's description %q:\n%s", d, read(t, file))
|
||||
}
|
||||
ok(t)(SaveServer("", Server{Name: "context7", Transport: "http", URL: "https://mcp.context7.com/mcp", Agents: []string{"pi"}}))
|
||||
if d := about(); !strings.Contains(d, "context7 (") || !strings.Contains(d, "wiki (") {
|
||||
t.Fatalf("context7 ticked: %q", d)
|
||||
}
|
||||
// one edited by hand is magpie's again on the next sync
|
||||
write(t, file, strings.Replace(read(t, file), "Tools of", "Tools from", 1))
|
||||
ok(t)(Sync())
|
||||
if d := about(); !strings.HasPrefix(d, "Tools of context7") {
|
||||
t.Fatalf("after a sync: %q", d)
|
||||
}
|
||||
if d, _ := piServers(t, file)["theirs"]["description"].(string); d != "My own." {
|
||||
t.Fatalf("the user's description: %q", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubGivesMagpieImage(t *testing.T) {
|
||||
h := hubSandbox(t)
|
||||
claude := filepath.Join(h, ".claude.json")
|
||||
|
||||
@@ -248,7 +248,7 @@ func (l *Library) syncMCP(t *Target, b *backups, res *Result) {
|
||||
hub = nil
|
||||
if l.MCPHub && slices.Contains(a.MCP, HubEntry) && l.server(HubEntry) == nil &&
|
||||
slices.ContainsFunc(l.MCP, func(s *Server) bool { return slices.Contains(s.Agents, id) && inHub(s, id) }) {
|
||||
hub = hubServerFor(t)
|
||||
hub = l.hubServerFor(t)
|
||||
}
|
||||
}
|
||||
hubbed := func(s *Server) bool { return hub != nil && inHub(s, id) }
|
||||
|
||||
Reference in New Issue
Block a user