library: a Remote magpie's MCP router is a Library server of its own
With another magpie as a provider (preset remote-magpie), its router's
MCP servers took adding that same magpie again under Library -> MCP.
Now the gateway's info (GET /v1) says "mcp_hub": true to a caller it
serves MCP to while its router is on with a server that isn't itself
another magpie's router. A fetch of a Remote magpie's models asks that
info with the provider's key, only while the library would still give
it a server, and the library then adds one: named for the provider,
http at <root>/mcp/magpie/hub with Authorization: Bearer <key>, kept to
this computer (local), on for the agents given the hub's entry.
- Offered once (bridgesOffered in library.json): removed or switched
off by the user, it stays so until the provider is removed and added
again.
- A server the user already has at that magpie's router (same origin,
the router's path) is the one; none is added beside it.
- The provider removed takes its server out (adoptBridges, at Sync and
the View read); providers.json unreadable takes nothing out; the
provider's address or key changed changes the server's; edited to
another address or key it becomes the user's own (keptBridge).
- No loop: every dial to a URL under /mcp/magpie/hub carries
X-Magpie-Router, and a request with it is given no such server,
neither listed (library Tools, gateway hubServersOf) nor run (Call,
hubToolNamed). A server carried in by sync is never a bridge.
- No GUI change: it is a server row as any other.
Run (mote, at base 1c45645b5):
- gofmt -l clean; go vet ./internal/{gateway,library,provider} on
darwin, GOOS=windows, and GOOS=linux -tags nogui: ok.
- go test ./internal/gateway -run 'TestHubLeavesRemoteRouterToARouter|
TestInfoSaysMCPHub|TestHubMCP'; ./internal/provider -run
'TestRemoteHubNoted|TestRemoteSelf'; ./internal/library -run
'TestRemoteMagpieRouter|TestCarriedServerIsNoBridge|TestPluginTools|
TestHub': ok.
- Real two-magpie run on mote: a built binary, two sandbox HOMEs /
XDG_CONFIG_HOMEs, B on 3512 with a python stub provider and a stub
HTTP MCP server behind its router, A on 3513 with B as a Remote
magpie. After `magpie sync` on A, A's library.json had home-magpie
(http://127.0.0.1:3512/mcp/magpie/hub, Bearer key, bridge home) and
bridgesOffered [home]; A's /mcp/magpie/hub listed
home-magpie__stubmcp__echo and tools/call returned the stub's echo;
A asked with X-Magpie-Router listed nothing (loop guard); B asked
with it still listed its own stubmcp__echo.
Broken by hand, each red: the Tools filter, the Call filter, the router
header in remoteHeaders, the same-origin dedup, offered-once, the
unreadable-providers keep, the key refresh, keptBridge, putServers'
carried reset, hubServerOf's Bridge, the gateway's hubServersOf, the
gateway's header -> ctx, info's non-bridge check, fetch's hook, the
older-magpie check and the this-magpie check.
Not tried / not handled:
- The real run was over loopback; a LAN remote's key check is covered
only by the existing TestHubMCPRemoteEntryNeedsKey path.
- The provider's own extra headers (a proxy's) aren't carried to the
server; a remote with several keys is asked with p.Key.
- A remote whose router is turned off later keeps its server (it lists
no tools).
- A server the user added by hand at another magpie's router now sends
X-Magpie-Router too, so that router leaves out its own Remote
magpies' servers for it.
- Windows and Linux test runs (vet only).
Reported-by: treeman_26897
This commit is contained in:
@@ -19,6 +19,7 @@ With the Library's switch "MCP router" on (#2679, @minggang123 on X), each agent
|
||||
| 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. 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` |
|
||||
| A Remote magpie's router | With another magpie as a provider (preset `remote-magpie`), its router's servers took adding that magpie again under Library → MCP (treeman_26897 on Discord). The gateway's info (`GET /v1`) says `"mcp_hub": true` to a caller it serves MCP to (`local` or `sharedWith`) while the switch is on with a server that isn't another magpie's router (`hubServes`). A fetch of a Remote magpie's models (`fetch` → `noteRemoteHub`, not one found to be this magpie) asks that info with the provider's key, only while the library would give it a server (`RemoteHubAsk`: its id isn't in `bridgesOffered`), and `RemoteHubFound` then adds one server: named for the provider (`bridgeName`), `http` at `<root>/mcp/magpie/hub` with `Authorization: Bearer <key>`, `bridge` = the provider's id, `local`, on for the agents given the hub's entry. Offered once: a user who removes it or switches it off keeps it so until the provider is removed and added again. A server the user has at that magpie's router already (same origin, the router's path) is the one, and none is added. The provider gone takes the server out (`adoptBridges`, at Sync and the View read); providers.json unreadable 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 (`keptBridge`). No loop: every dial to a URL under `/mcp/magpie/hub` carries `X-Magpie-Router` (`remoteHeaders`), and a request with it (`gateway.FromRouter`) is given no `bridge` server, neither listed (`Tools`, `hubServersOf`) nor run (`Call`, `hubToolNamed`). | [`bridge_mcp.go`](../../internal/library/bridge_mcp.go); [`remote_hub.go`](../../internal/provider/remote_hub.go); `RouterHeader`, `hubServes` in [`hub_mcp.go`](../../internal/gateway/hub_mcp.go) |
|
||||
|
||||
The CLI's `magpie library mcp router on|off` (`hub`, its name before, still works) calls `SetMCPHub`, and `magpie library mcp router <name> 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)).
|
||||
|
||||
@@ -42,15 +43,17 @@ The gateway can't import the library (the library imports the gateway), so the g
|
||||
- Every process the router starts is in a `proc` tree magpie ends when the switch goes off, the server is edited, it has been idle, or the gateway stops. A test ends them in cleanup (`hubSandbox`).
|
||||
- A gateway key holder on the LAN reaches the Library's command servers through the router while it is on, as they reach plugin tools. They run with the user's rights on this computer.
|
||||
- A tools plugin's server (`plugin` set, [Plugin tools](plugin-tools.md)) is behind the router as any server is, but its tools are listed and run in this process through the plugin host, not over its URL, and they aren't cached: the host has them.
|
||||
- A Remote magpie's server is offered once and asked for only then; a remote whose router is turned off later keeps its server (its tools list empty). The provider's own extra headers (a proxy's) aren't carried to it, and a remote with several keys is asked with its first (`p.Key`). A server the user added at another magpie's router also sends `X-Magpie-Router`, so that router leaves out its own Remote magpies' servers for it.
|
||||
- The tools a server listed are cached until it says they changed, it is edited, or the switch is turned off. A server that changes its tools without saying so shows them after one of those.
|
||||
|
||||
## Verification
|
||||
|
||||
```sh
|
||||
go test -tags nogui ./internal/gui -run 'TestHubOpen|TestHubNote|TestHubAllTools'
|
||||
go test -tags nogui ./internal/library -run 'TestHub|TestRunDirect|TestFakeMCPServer|TestCheck|TestPluginTools'
|
||||
go test -tags nogui ./internal/library -run 'TestHub|TestRunDirect|TestFakeMCPServer|TestCheck|TestPluginTools|TestRemoteMagpieRouter|TestCarriedServerIsNoBridge'
|
||||
go test -tags nogui ./internal/settings -run TestRouterNote
|
||||
go test -tags nogui ./internal/gateway -run 'HubMCP|OwnMCPRejects' -timeout 45m
|
||||
go test -tags nogui ./internal/gateway -run 'HubMCP|OwnMCPRejects|TestHubLeavesRemoteRouterToARouter|TestInfoSaysMCPHub' -timeout 45m
|
||||
go test -tags nogui ./internal/provider -run 'TestRemoteHubNoted|TestRemoteSelf'
|
||||
go test -tags nogui ./internal/cli -run TestLibraryMCPHub
|
||||
node --test internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/mcp-hub-direct.test.cjs internal/gui/tests/library-mcp-router-note.test.cjs internal/gui/tests/library-mcp-router-tools.test.cjs
|
||||
```
|
||||
|
||||
@@ -1089,6 +1089,12 @@ func (s *Server) info(w http.ResponseWriter, r *http.Request) {
|
||||
if local(r) {
|
||||
out["pid"], out["serves"] = os.Getpid(), Serves
|
||||
}
|
||||
// its MCP router has a server to give, for another magpie that has
|
||||
// this one as a Remote magpie to give it a server of its own
|
||||
// (provider/remote_hub.go); told to whoever the router answers
|
||||
if (local(r) || sharedWith(r)) && hubServes() {
|
||||
out["mcp_hub"] = true
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// bridgeHub is fakeHub whose Tools, as the library's, leaves out a
|
||||
// Remote magpie's router for a request of another magpie's router, and
|
||||
// says which requests were.
|
||||
type bridgeHub struct {
|
||||
*fakeHub
|
||||
fromRouter []bool
|
||||
}
|
||||
|
||||
func (b *bridgeHub) Tools(ctx context.Context, agent string) []HubTool {
|
||||
b.mu.Lock()
|
||||
b.fromRouter = append(b.fromRouter, FromRouter(ctx))
|
||||
b.mu.Unlock()
|
||||
ts := b.fakeHub.Tools(ctx, agent)
|
||||
if FromRouter(ctx) {
|
||||
ts = slices.DeleteFunc(slices.Clone(ts), func(t HubTool) bool { return t.Server == "home" })
|
||||
}
|
||||
return ts
|
||||
}
|
||||
|
||||
// A request of another magpie's router (RouterHeader) is one to the
|
||||
// library (FromRouter), and isn't given a server that is a Remote
|
||||
// magpie's router: neither listed, nor run when named. Two magpies that
|
||||
// have each other as Remote magpies don't ask each other round. Without
|
||||
// the header, it is given as any server.
|
||||
func TestHubLeavesRemoteRouterToARouter(t *testing.T) {
|
||||
fresh(t)
|
||||
f := &bridgeHub{fakeHub: &fakeHub{on: true,
|
||||
tools: map[string][]HubTool{"": {
|
||||
{Server: "fs", Tool: "read", Spec: hubSpec("read")},
|
||||
{Server: "home", Tool: "search", Spec: hubSpec("search")},
|
||||
}},
|
||||
servers: map[string][]HubServer{"": {{Name: "fs", Known: true}, {Name: "home", Known: true, Bridge: true}}},
|
||||
}}
|
||||
old := MCPHub
|
||||
MCPHub = f
|
||||
t.Cleanup(func() { MCPHub = old })
|
||||
h := lanGuard(New().Handler())
|
||||
list := `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`
|
||||
names := func(m mcpReply) []string {
|
||||
var out []string
|
||||
for _, x := range m.Result.Tools {
|
||||
out = append(out, x.Name)
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
|
||||
if got := names(readMCP(t, hubPostAt(h, HubMCPAll, here, list))); !slices.Equal(got, []string{"fs__read", "home__search"}) {
|
||||
t.Fatalf("an agent's tools %v, want fs's and home's", got)
|
||||
}
|
||||
if got := names(readMCP(t, hubPostAt(h, HubMCPAll, here, list, RouterHeader, "1"))); !slices.Equal(got, []string{"fs__read"}) {
|
||||
t.Fatalf("a router's tools %v, want fs's alone", got)
|
||||
}
|
||||
if !slices.Equal(f.fromRouter, []bool{false, true}) {
|
||||
t.Errorf("the library was told %v of the two requests, want false then true", f.fromRouter)
|
||||
}
|
||||
// named, home's tool isn't run for a router (hubToolNamed asks
|
||||
// Servers), and is for an agent
|
||||
call := `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"home__search","arguments":{"q":"x"}}}`
|
||||
if m := readMCP(t, hubPostAt(h, HubMCPAll, here, call, RouterHeader, "1")); m.Error == nil {
|
||||
t.Fatalf("home's tool ran for a router: %+v", m.Result)
|
||||
}
|
||||
if ran := f.ran(); len(ran) != 0 {
|
||||
t.Fatalf("ran %v for a router", ran)
|
||||
}
|
||||
if m := readMCP(t, hubPostAt(h, HubMCPAll, here, call)); m.Error != nil || m.Result.IsError {
|
||||
t.Fatalf("home's tool for an agent: %+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// The gateway's info says its router has a server to give ("mcp_hub")
|
||||
// while the hub is on with a server that isn't a Remote magpie's router,
|
||||
// for another magpie that has this one as a provider to give it a server.
|
||||
func TestInfoSaysMCPHub(t *testing.T) {
|
||||
fresh(t)
|
||||
f := &fakeHub{on: true, servers: map[string][]HubServer{"": {{Name: "home", Bridge: true}}}}
|
||||
withHub(t, f)
|
||||
h := lanGuard(New().Handler())
|
||||
says := func() bool {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(http.MethodGet, "/v1", nil)
|
||||
r.RemoteAddr, r.Host = here, "127.0.0.1:3425"
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
var info struct {
|
||||
Name string `json:"name"`
|
||||
MCPHub bool `json:"mcp_hub"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &info); err != nil || info.Name != "magpie" {
|
||||
t.Fatalf("info %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
return info.MCPHub
|
||||
}
|
||||
if says() {
|
||||
t.Error("mcp_hub with only a Remote magpie's router behind it")
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.servers[""] = append(f.servers[""], HubServer{Name: "fs"})
|
||||
f.mu.Unlock()
|
||||
if !says() {
|
||||
t.Error("no mcp_hub with fs behind the hub")
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.on = false
|
||||
f.mu.Unlock()
|
||||
if says() {
|
||||
t.Error("mcp_hub with the hub off")
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,46 @@ type HubServer struct {
|
||||
// the server as it is now
|
||||
Tools []HubToolNote
|
||||
Known bool
|
||||
// Bridge: the server is another magpie's router, which the library
|
||||
// gave a server of its own for being a Remote magpie
|
||||
// (library/bridge_mcp.go). A request from another magpie's router
|
||||
// (RouterHeader) isn't given it, so two magpies that have each other
|
||||
// never ask each other round.
|
||||
Bridge bool
|
||||
}
|
||||
|
||||
// RouterHeader marks a request of magpie's own router to another magpie's
|
||||
// (FromRouter).
|
||||
const RouterHeader = "X-Magpie-Router"
|
||||
|
||||
type fromRouterKey struct{}
|
||||
|
||||
// WithRouter is ctx a request of another magpie's router.
|
||||
func WithRouter(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, fromRouterKey{}, true)
|
||||
}
|
||||
|
||||
// FromRouter is whether ctx is a request of another magpie's router: the
|
||||
// servers behind this one that are a Remote magpie's router (HubServer's
|
||||
// Bridge) aren't listed or run for it.
|
||||
func FromRouter(ctx context.Context) bool {
|
||||
on, _ := ctx.Value(fromRouterKey{}).(bool)
|
||||
return on
|
||||
}
|
||||
|
||||
// hubServersOf are the servers behind agent's tools, as the request of
|
||||
// ctx is given them.
|
||||
func hubServersOf(ctx context.Context, agent string) []HubServer {
|
||||
ss := MCPHub.Servers(agent)
|
||||
if FromRouter(ctx) {
|
||||
ss = slices.DeleteFunc(ss, func(s HubServer) bool { return s.Bridge })
|
||||
}
|
||||
return ss
|
||||
}
|
||||
|
||||
// hubServes is whether the hub gives another magpie's router a server.
|
||||
func hubServes() bool {
|
||||
return MCPHub != nil && MCPHub.On() && slices.ContainsFunc(MCPHub.Servers(""), func(s HubServer) bool { return !s.Bridge })
|
||||
}
|
||||
|
||||
// HubToolNote is one tool of a server behind the hub, as the instructions
|
||||
@@ -153,6 +193,9 @@ const errHubOff = "magpie's MCP hub is off, so it runs no server's tools: turn i
|
||||
|
||||
func (s *Server) hubMCP(w http.ResponseWriter, r *http.Request) {
|
||||
agent := r.PathValue("agent")
|
||||
if r.Header.Get(RouterHeader) != "" {
|
||||
r = r.WithContext(WithRouter(r.Context()))
|
||||
}
|
||||
serveMCP(w, r, "magpie's MCP hub", "magpie", hubBody, func(r *http.Request, m mcpMessage) (any, map[string]any) {
|
||||
return s.hubMCPCall(r, agent, m)
|
||||
})
|
||||
@@ -438,14 +481,14 @@ var hubDescribeWait = 5 * time.Second
|
||||
// hubServersFor are the servers behind agent's tools, as the instructions
|
||||
// describe them, their tools listed first when magpie hasn't yet.
|
||||
func hubServersFor(ctx context.Context, agent string) []HubServer {
|
||||
ss := MCPHub.Servers(agent)
|
||||
ss := hubServersOf(ctx, agent)
|
||||
if !MCPHub.On() || !slices.ContainsFunc(ss, func(s HubServer) bool { return !s.Known }) {
|
||||
return ss
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, hubDescribeWait)
|
||||
wait, cancel := context.WithTimeout(ctx, hubDescribeWait)
|
||||
defer cancel()
|
||||
MCPHub.Tools(ctx, agent)
|
||||
return MCPHub.Servers(agent)
|
||||
MCPHub.Tools(wait, agent)
|
||||
return hubServersOf(ctx, agent)
|
||||
}
|
||||
|
||||
func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, map[string]any) {
|
||||
@@ -484,7 +527,7 @@ func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, m
|
||||
where := hubWhere(r)
|
||||
if hubOnDemand(agent, len(ts)) {
|
||||
// hubTools ran, so each server's tools are as just listed
|
||||
return map[string]any{"tools": hubOnDemandSpecs(where, MCPHub.Servers(agent))}, nil
|
||||
return map[string]any{"tools": hubOnDemandSpecs(where, hubServersOf(r.Context(), agent))}, nil
|
||||
}
|
||||
list := make([]any, 0, len(ts))
|
||||
for _, t := range ts {
|
||||
@@ -513,7 +556,7 @@ func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, m
|
||||
case hubCallTool:
|
||||
return s.hubCallByName(r, agent, ts, p.Arguments, p.Meta), nil
|
||||
}
|
||||
if t, ok := hubToolNamed(ts, agent, p.Name); ok {
|
||||
if t, ok := hubToolNamed(r.Context(), ts, agent, p.Name); ok {
|
||||
return s.hubCall(r, agent, t, p.Arguments, p.Meta), nil
|
||||
}
|
||||
if agent == "" {
|
||||
@@ -531,14 +574,14 @@ func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, m
|
||||
// browser_tabs became the browser tool's tabs action, and it still takes
|
||||
// the old name (7e201ce20). A server whose list failed just now is asked
|
||||
// the same way, and either says why it can't run the tool.
|
||||
func hubToolNamed(ts []hubTool, agent, name string) (hubTool, bool) {
|
||||
func hubToolNamed(ctx context.Context, ts []hubTool, agent, name string) (hubTool, bool) {
|
||||
for _, t := range ts {
|
||||
if t.name == name {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
var found []hubTool
|
||||
for _, sv := range MCPHub.Servers(agent) {
|
||||
for _, sv := range hubServersOf(ctx, agent) {
|
||||
tool, ok := strings.CutPrefix(name, unsafeToolChars.ReplaceAllString(sv.Name, "-")+hubSep)
|
||||
if !ok || tool == "" {
|
||||
continue
|
||||
|
||||
@@ -2,6 +2,7 @@ package gateway
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
@@ -295,8 +296,8 @@ func hubCallArgs(args json.RawMessage) (name string, inner json.RawMessage, err
|
||||
// hubCallNamed is the tool call_tool names: as tools/call finds it
|
||||
// (hubToolNamed), else the one tool of that name on its server, in any
|
||||
// case.
|
||||
func hubCallNamed(ts []hubTool, agent, name string) (hubTool, bool) {
|
||||
if t, ok := hubToolNamed(ts, agent, name); ok {
|
||||
func hubCallNamed(ctx context.Context, ts []hubTool, agent, name string) (hubTool, bool) {
|
||||
if t, ok := hubToolNamed(ctx, ts, agent, name); ok {
|
||||
return t, true
|
||||
}
|
||||
var found []hubTool
|
||||
@@ -321,7 +322,7 @@ func (s *Server) hubCallByName(r *http.Request, agent string, ts []hubTool, args
|
||||
if name == "" {
|
||||
return toolResult(hubCallTool+" needs the name of the tool to run; "+hubFindTool+" gives the tools' names.", true)
|
||||
}
|
||||
t, ok := hubCallNamed(ts, agent, name)
|
||||
t, ok := hubCallNamed(r.Context(), ts, agent, name)
|
||||
if !ok {
|
||||
why := "No tool is called " + name + "."
|
||||
if ms := hubMatches(ts, name); len(ms) > 0 {
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
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 offered once (BridgesOffered): a user who removes the server
|
||||
// doesn't get it back until the provider is removed and added again.
|
||||
// One the user switched off for an agent stays off.
|
||||
// - 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: it wasn't offered one yet.
|
||||
func bridgeWanted(id string) bool {
|
||||
mu.Lock()
|
||||
l, err := load()
|
||||
mu.Unlock()
|
||||
return err == nil && !slices.Contains(l.BridgesOffered, id)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
if slices.Contains(l.BridgesOffered, 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: one whose provider is gone is taken out, and its offer 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 && !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
|
||||
}
|
||||
changed := false
|
||||
if n := len(l.BridgesOffered); n > 0 {
|
||||
l.BridgesOffered = slices.DeleteFunc(l.BridgesOffered, func(id string) bool { _, ok := by[id]; return !ok })
|
||||
changed = len(l.BridgesOffered) != n
|
||||
if len(l.BridgesOffered) == 0 {
|
||||
l.BridgesOffered = 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// fakeRemotes has the Remote magpies in providers.json be hs, or
|
||||
// providers.json unreadable with err.
|
||||
type fakeRemotes struct {
|
||||
hs []provider.RemoteHub
|
||||
err error
|
||||
}
|
||||
|
||||
func fakeRemoteHubs(t *testing.T, hs ...provider.RemoteHub) *fakeRemotes {
|
||||
t.Helper()
|
||||
f := &fakeRemotes{hs: hs}
|
||||
old := remoteHubs
|
||||
t.Cleanup(func() { remoteHubs = old })
|
||||
remoteHubs = func() ([]provider.RemoteHub, error) { return slices.Clone(f.hs), f.err }
|
||||
return f
|
||||
}
|
||||
|
||||
func loaded(t *testing.T) *Library {
|
||||
t.Helper()
|
||||
l, err := load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// A Remote magpie that says it serves its MCP router (treeman_26897 on
|
||||
// Discord) is a Library server of its own: named for the provider, at its
|
||||
// router with its key, kept to this computer, on for the agents given the
|
||||
// hub's entry, its tools in their hub. It is asked as a router asks
|
||||
// another's, and isn't given to another magpie's router. The provider's
|
||||
// key changed, the server's is; edited in the Library's editor as it was,
|
||||
// it stays the provider's; edited to another address, the user's own.
|
||||
func TestRemoteMagpieRouterIsAServer(t *testing.T) {
|
||||
hubSandbox(t)
|
||||
var seen http.Header
|
||||
srv := httptest.NewServer(mcpHandler(t, false, &seen))
|
||||
t.Cleanup(srv.Close)
|
||||
f := fakeRemoteHubs(t, provider.RemoteHub{ID: "home", Name: "Home magpie", Root: srv.URL + "/", Key: "k1"})
|
||||
fake := fakeStdio(t, "ok", nil)
|
||||
fake.Agents = []string{"claude"}
|
||||
ok(t)(SaveServer("", *fake))
|
||||
ok(t)(SetMCPHub(true))
|
||||
|
||||
if !provider.RemoteHubAsk("home") {
|
||||
t.Fatal("a Remote magpie not offered yet isn't asked")
|
||||
}
|
||||
provider.RemoteHubFound("home")
|
||||
l := loaded(t)
|
||||
s := l.server("home-magpie")
|
||||
if s == nil {
|
||||
t.Fatalf("no server for the Remote magpie: %+v", l.MCP)
|
||||
}
|
||||
if s.Bridge != "home" || !s.Local || s.Transport != "http" || s.URL != srv.URL+gateway.HubMCPAll ||
|
||||
s.Headers["Authorization"] != "Bearer k1" || !slices.Equal(s.Agents, []string{"claude"}) {
|
||||
t.Fatalf("the Remote magpie's server: %+v", s)
|
||||
}
|
||||
if provider.RemoteHubAsk("home") {
|
||||
t.Error("a Remote magpie offered once is asked again")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
hub := theHub{}
|
||||
if got := hubNames(hub.Tools(ctx, "claude")); !slices.Contains(got, "home-magpie/a") {
|
||||
t.Fatalf("claude's hub tools %v, want home-magpie's", got)
|
||||
}
|
||||
if seen.Get(gateway.RouterHeader) == "" || seen.Get("Authorization") != "Bearer k1" {
|
||||
t.Errorf("the router asked with %v, want its key and %s", seen, gateway.RouterHeader)
|
||||
}
|
||||
if ss := hub.Servers("claude"); !slices.ContainsFunc(ss, func(s gateway.HubServer) bool { return s.Name == "home-magpie" && s.Bridge }) {
|
||||
t.Errorf("the gateway isn't told home-magpie is a Remote magpie's router: %+v", ss)
|
||||
}
|
||||
// another magpie's router isn't given it
|
||||
rctx := gateway.WithRouter(ctx)
|
||||
if got := hubNames(hub.Tools(rctx, "claude")); slices.Contains(got, "home-magpie/a") || !slices.Contains(got, "fake/a") {
|
||||
t.Fatalf("a router's tools %v, want fake's alone", got)
|
||||
}
|
||||
if _, err := hub.Call(rctx, "claude", "home-magpie", "a", json.RawMessage(`{}`)); err == nil {
|
||||
t.Error("home-magpie's tool ran for a router")
|
||||
}
|
||||
if res, err := hub.Call(ctx, "claude", "home-magpie", "a", json.RawMessage(`{}`)); err != nil || !strings.HasPrefix(hubText(t, res), "remote ") {
|
||||
t.Fatalf("home-magpie's a: %s %v", res, err)
|
||||
}
|
||||
|
||||
// the provider's key changed
|
||||
f.hs[0].Key = "k2"
|
||||
ok(t)(Sync())
|
||||
if s := loaded(t).server("home-magpie"); s.Headers["Authorization"] != "Bearer k2" {
|
||||
t.Fatalf("the key changed, the server's headers: %v", s.Headers)
|
||||
}
|
||||
// edited as it was, by an editor that sends neither Bridge nor Local
|
||||
ed := *loaded(t).server("home-magpie")
|
||||
ed.Bridge, ed.Local, ed.Agents = "", false, []string{"claude", "codex"}
|
||||
ok(t)(SaveServer("home-magpie", ed))
|
||||
if s := loaded(t).server("home-magpie"); s.Bridge != "home" || !s.Local {
|
||||
t.Fatalf("edited as it was, no longer the Remote magpie's: %+v", s)
|
||||
}
|
||||
// edited to another address: the user's own, not changed again
|
||||
ed.URL = srv.URL + "/mine"
|
||||
ok(t)(SaveServer("home-magpie", ed))
|
||||
f.hs[0].Key = "k3"
|
||||
ok(t)(Sync())
|
||||
if s := loaded(t).server("home-magpie"); s.Bridge != "" || !s.Local || s.URL != srv.URL+"/mine" || s.Headers["Authorization"] != "Bearer k2" {
|
||||
t.Fatalf("edited to another address: %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
// The server is offered once: removed by the user, it isn't added again
|
||||
// until the provider is removed and added again; switched off for an
|
||||
// agent, it stays off. One the user has at that magpie's router already
|
||||
// is the one. The provider removed takes its server with it; one turned
|
||||
// off keeps it (RemoteHubs still lists it); providers.json unreadable
|
||||
// takes nothing out. A name a server has already, or the hub's own entry's,
|
||||
// isn't given it.
|
||||
func TestRemoteMagpieRouterOfferedOnce(t *testing.T) {
|
||||
hubSandbox(t)
|
||||
home := provider.RemoteHub{ID: "home", Name: "Home", Root: "http://192.168.1.9:3425", Key: "k"}
|
||||
f := fakeRemoteHubs(t, home)
|
||||
has := func(name string) bool { t.Helper(); return loaded(t).server(name) != nil }
|
||||
|
||||
// the user's own at that magpie's router: none beside it
|
||||
ok(t)(SaveServer("", Server{Name: "office", Transport: "http", URL: "http://192.168.1.9:3425" + gateway.HubMCPPath + "claude"}))
|
||||
provider.RemoteHubFound("home")
|
||||
if l := loaded(t); len(l.MCP) != 1 || !slices.Contains(l.BridgesOffered, "home") {
|
||||
t.Fatalf("beside the user's own: %+v, offered %v", l.MCP, l.BridgesOffered)
|
||||
}
|
||||
ok(t)(RemoveServer("office"))
|
||||
provider.RemoteHubFound("home")
|
||||
if has("home") {
|
||||
t.Fatal("offered once already, added after the user's own was removed")
|
||||
}
|
||||
|
||||
// the provider removed and added again: offered again
|
||||
f.hs = nil
|
||||
ok(t)(Sync())
|
||||
if slices.Contains(loaded(t).BridgesOffered, "home") {
|
||||
t.Fatal("the provider removed, still offered")
|
||||
}
|
||||
f.hs = []provider.RemoteHub{home}
|
||||
provider.RemoteHubFound("home")
|
||||
if !has("home") {
|
||||
t.Fatal("the provider added again, no server")
|
||||
}
|
||||
if a := loaded(t).server("home").Agents; len(a) != 0 {
|
||||
t.Errorf("with the hub off, on for %v, want none", a)
|
||||
}
|
||||
// switched on, then off, for claude: off it stays
|
||||
ok(t)(ServerAgents("home", []string{"claude"}))
|
||||
ok(t)(ServerAgents("home", nil))
|
||||
ok(t)(Sync())
|
||||
provider.RemoteHubFound("home")
|
||||
if a := loaded(t).server("home").Agents; len(a) != 0 {
|
||||
t.Errorf("switched off, on for %v", a)
|
||||
}
|
||||
// removed by the user: not back
|
||||
ok(t)(RemoveServer("home"))
|
||||
ok(t)(Sync())
|
||||
provider.RemoteHubFound("home")
|
||||
if has("home") {
|
||||
t.Fatal("a server the user removed came back")
|
||||
}
|
||||
|
||||
// providers.json unreadable takes nothing out
|
||||
f.hs = nil
|
||||
ok(t)(Sync())
|
||||
f.hs = []provider.RemoteHub{home}
|
||||
provider.RemoteHubFound("home")
|
||||
f.err = errors.New("unreadable")
|
||||
f.hs = nil
|
||||
ok(t)(Sync())
|
||||
if !has("home") || !slices.Contains(loaded(t).BridgesOffered, "home") {
|
||||
t.Fatal("providers.json unreadable took the server out")
|
||||
}
|
||||
f.err = nil
|
||||
ok(t)(Sync())
|
||||
if has("home") {
|
||||
t.Fatal("the provider removed kept its server")
|
||||
}
|
||||
|
||||
// a provider being tried in the editor, not saved: nothing
|
||||
provider.RemoteHubFound("nope")
|
||||
if l := loaded(t); len(l.MCP) != 0 || len(l.BridgesOffered) != 0 {
|
||||
t.Fatalf("a provider not saved: %+v, offered %v", l.MCP, l.BridgesOffered)
|
||||
}
|
||||
|
||||
// names: the hub's own entry's isn't given, nor one a server has
|
||||
ok(t)(SaveServer("", Server{Name: "magpie-remote", Transport: "http", URL: "https://example.com/mcp"}))
|
||||
f.hs = []provider.RemoteHub{{ID: "m", Name: "magpie", Root: "http://10.0.0.2:3425", Key: "k"}, {ID: "x", Name: "!!", Root: "http://10.0.0.3:3425", Key: "k"}}
|
||||
provider.RemoteHubFound("m")
|
||||
provider.RemoteHubFound("x")
|
||||
l := loaded(t)
|
||||
if s := l.server("magpie-remote-2"); s == nil || s.Bridge != "m" {
|
||||
t.Errorf("a Remote magpie called magpie: %+v", l.MCP)
|
||||
}
|
||||
if s := l.server("x"); s == nil || s.Bridge != "x" {
|
||||
t.Errorf("a Remote magpie whose name gives no name: %+v", l.MCP)
|
||||
}
|
||||
}
|
||||
|
||||
// A server carried in from another computer is never that computer's
|
||||
// Remote magpie's here.
|
||||
func TestCarriedServerIsNoBridge(t *testing.T) {
|
||||
l := &Library{}
|
||||
l.putServers([]*Server{{Name: "home", Transport: "http", URL: "http://10.0.0.2:3425" + gateway.HubMCPAll, Bridge: "home"}})
|
||||
if l.MCP[0].Bridge != "" {
|
||||
t.Fatalf("carried in as a Remote magpie's: %+v", l.MCP[0])
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,10 @@ type Library struct {
|
||||
// PluginsOffered are the plugins (plugin.Name) given a server of their
|
||||
// tools, for one the user removed not to come back (plugin_tools.go)
|
||||
PluginsOffered []string `json:"pluginsOffered,omitempty"`
|
||||
// BridgesOffered are the Remote magpies (provider ids) whose MCP
|
||||
// router was given a server, for one the user removed not to come
|
||||
// back (bridge_mcp.go)
|
||||
BridgesOffered []string `json:"bridgesOffered,omitempty"`
|
||||
// SeenSkills are, by repository and ref ("owner/repo@ref"), the
|
||||
// folders of skills there the page has offered: picked or not at
|
||||
// install, or set aside after a check. A check offers only the others
|
||||
|
||||
@@ -62,6 +62,9 @@ type Server struct {
|
||||
// gateway serves them at its URL, and the hub calls the plugin itself
|
||||
// (plugin_tools.go)
|
||||
Plugin string `json:"plugin,omitempty"`
|
||||
// Bridge is the Remote magpie (its provider id) whose MCP router the
|
||||
// server is, given a server of its own (bridge_mcp.go)
|
||||
Bridge string `json:"bridge,omitempty"`
|
||||
// Hub is how the MCP hub (Library.MCPHub) gives the server: "" shares
|
||||
// it through the hub's one entry, as every server was before;
|
||||
// HubDirect keeps it the agents' own entry, written as with the hub
|
||||
|
||||
@@ -814,6 +814,11 @@ func remoteHeaders(ctx context.Context, s *Server) (http.Header, *ServerHealth)
|
||||
for k, v := range headers {
|
||||
h.Set(k, v)
|
||||
}
|
||||
// another magpie's router is told the call is a router's, for it not
|
||||
// to ask this one's back (bridge_mcp.go)
|
||||
if u, err := url.Parse(s.URL); err == nil && strings.HasPrefix(u.Path, gateway.HubMCPAll) {
|
||||
h.Set(gateway.RouterHeader, "1")
|
||||
}
|
||||
if s.Transport == "http" && mcpauth.SignedIn(s.Name, s.URL) {
|
||||
tok, err := mcpauth.Token(ctx, s.Name)
|
||||
if err != nil {
|
||||
|
||||
@@ -223,6 +223,10 @@ func hubAbouts(ss []*Server) []gateway.HubServer {
|
||||
|
||||
func (theHub) Tools(ctx context.Context, agentID string) []gateway.HubTool {
|
||||
ss := hubServers(agentID)
|
||||
if gateway.FromRouter(ctx) {
|
||||
// another magpie's router: not given a Remote magpie's back
|
||||
ss = slices.DeleteFunc(ss, func(s *Server) bool { return s.Bridge != "" })
|
||||
}
|
||||
lists := make([][]gateway.HubTool, len(ss))
|
||||
var wg sync.WaitGroup
|
||||
for i, s := range ss {
|
||||
@@ -270,6 +274,9 @@ func (theHub) Call(ctx context.Context, agentID, server, tool string, args json.
|
||||
return nil, fmt.Errorf("it isn't switched on for %s in magpie's Library", agentID)
|
||||
}
|
||||
s := ss[i]
|
||||
if s.Bridge != "" && gateway.FromRouter(ctx) {
|
||||
return nil, errors.New("it is another magpie's router, which isn't run for a magpie's router")
|
||||
}
|
||||
if slices.Contains(s.DisabledTools, tool) {
|
||||
return nil, errors.New("the tool is turned off in magpie's Library")
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ func writeCards(m map[string]hubCard) {
|
||||
// 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)}
|
||||
out := gateway.HubServer{Name: s.Name, About: serverAbout(s), Bridge: s.Bridge != ""}
|
||||
c := cardOf(s)
|
||||
if c == nil {
|
||||
return out
|
||||
|
||||
@@ -51,6 +51,7 @@ func (l *Library) putServers(in []*Server) {
|
||||
for _, s := range in {
|
||||
c := *s
|
||||
c.Local = false // only this computer says what is its own
|
||||
c.Bridge = "" // and which of its providers a server is
|
||||
c.Agents = slices.Sorted(slices.Values(orNone(s.Agents)))
|
||||
if own[c.Name] {
|
||||
l.Away = append(l.Away, &c)
|
||||
|
||||
@@ -75,7 +75,8 @@ func adoptPluginTools() (bool, error) {
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !l.adoptPlugins() {
|
||||
// and each Remote magpie's router's (bridge_mcp.go)
|
||||
if plugins, bridges := l.adoptPlugins(), l.adoptBridges(); !plugins && !bridges {
|
||||
return false, nil
|
||||
}
|
||||
return true, l.save()
|
||||
|
||||
@@ -567,9 +567,10 @@ func readView(problems []Problem, glance bool) (*View, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// a plugin's tools, a server of their own (plugin_tools.go): saved,
|
||||
// and given to the agents by a sync of their own
|
||||
if l.adoptPlugins() {
|
||||
// a plugin's tools, a server of their own (plugin_tools.go), and a
|
||||
// Remote magpie's router (bridge_mcp.go): saved, and given to the
|
||||
// agents by a sync of their own
|
||||
if plugins, bridges := l.adoptPlugins(), l.adoptBridges(); plugins || bridges {
|
||||
if err := l.save(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -775,6 +776,9 @@ func SaveServer(old string, s Server) (*Result, error) {
|
||||
if p := l.MCP[i].Plugin; p != "" && s.Plugin == "" {
|
||||
s.Plugin, s.Local = p, true
|
||||
}
|
||||
// a Remote magpie's router stays its own while it is at the
|
||||
// provider's address and key (bridge_mcp.go)
|
||||
keptBridge(l.MCP[i], &s)
|
||||
l.MCP = slices.Delete(l.MCP, i, i+1)
|
||||
if old != s.Name {
|
||||
l.renameProjectServers(old, s.Name)
|
||||
|
||||
@@ -424,11 +424,15 @@ func relistPicks(q *Provider, now map[string]bool) bool {
|
||||
}
|
||||
|
||||
// fetch is Fetch without the picks looked after. A Remote magpie's list
|
||||
// also tells whether it is this magpie (noteSelf).
|
||||
// also tells whether it is this magpie (noteSelf), and that magpie is
|
||||
// asked whether it serves its MCP router (noteRemoteHub).
|
||||
func (p Provider) fetch(ctx context.Context) ([]catalog.Model, error) {
|
||||
ms, err := p.fetchList(ctx)
|
||||
if err == nil {
|
||||
noteSelf(p, ms)
|
||||
if len(ms) > 0 {
|
||||
noteRemoteHub(ctx, p)
|
||||
}
|
||||
}
|
||||
return ms, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A Remote magpie's MCP router (treeman_26897 on Discord): the other
|
||||
// magpie serves the MCP servers in its Library at its hub
|
||||
// (gateway.HubMCPAll), and the Library here gives that address a server
|
||||
// of its own (library/bridge_mcp.go), the user not adding the same
|
||||
// magpie a second time. Its info (GET /v1) says "mcp_hub" when it has a
|
||||
// server there to give, which a magpie from before this doesn't; the
|
||||
// list of its models, fetched, asks it once the library would give it a
|
||||
// server.
|
||||
|
||||
// RemoteHubAsk, set by the library, is whether it would give the router of
|
||||
// the Remote magpie id a server; RemoteHubFound is called once that magpie
|
||||
// says it serves one. Nil, nothing is asked.
|
||||
var (
|
||||
RemoteHubAsk func(id string) bool
|
||||
RemoteHubFound func(id string)
|
||||
)
|
||||
|
||||
// RemoteHubWait is how long a Remote magpie's info is waited for.
|
||||
var RemoteHubWait = 5 * time.Second
|
||||
|
||||
// RemoteHub is a Remote magpie as its router's server is made: its
|
||||
// address (the gateway's root) and its key.
|
||||
type RemoteHub struct {
|
||||
ID, Name, Root, Key string
|
||||
}
|
||||
|
||||
// RemoteHubs are the Remote magpies in providers.json, turned off or not,
|
||||
// but one found to be this magpie, and one without an address or a key.
|
||||
// An error is providers.json unreadable: which there are is unknown.
|
||||
func RemoteHubs() ([]RemoteHub, error) {
|
||||
f, err := read()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
own, _ := ownOf(f)
|
||||
var out []RemoteHub
|
||||
for _, p := range own {
|
||||
if !p.IsRemoteMagpie() || p.SelfAnswered() || p.Key == "" || p.Anthropic == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, RemoteHub{ID: p.ID, Name: p.Name, Root: strings.TrimRight(p.Anthropic, "/"), Key: p.Key})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// noteRemoteHub asks the Remote magpie p, its models just listed, whether
|
||||
// it serves its router, once the library would give it a server.
|
||||
func noteRemoteHub(ctx context.Context, p Provider) {
|
||||
ask, found := RemoteHubAsk, RemoteHubFound
|
||||
if !p.IsRemoteMagpie() || p.SelfAnswered() || p.Key == "" || p.Anthropic == "" || ask == nil || found == nil || !ask(p.ID) {
|
||||
return
|
||||
}
|
||||
b, err := remoteBody(ctx, p, "GET", "/v1", RemoteHubWait)
|
||||
if err != nil {
|
||||
return // unknown: asked again at the next list
|
||||
}
|
||||
var info struct {
|
||||
Name string `json:"name"`
|
||||
MCPHub bool `json:"mcp_hub"`
|
||||
}
|
||||
if json.Unmarshal(b, &info) == nil && info.Name == "magpie" && info.MCPHub {
|
||||
found(p.ID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
)
|
||||
|
||||
// A Remote magpie whose models are listed is asked, with its key, whether
|
||||
// its router has a server to give, while the library would give it one
|
||||
// (RemoteHubAsk); one that says so is noted (RemoteHubFound). One that
|
||||
// doesn't say, a magpie from before it, isn't; nor one the library
|
||||
// doesn't ask about, nor one found to be this magpie. RemoteHubs lists the
|
||||
// Remote magpies with their address and key, and fails while
|
||||
// providers.json can't be read.
|
||||
func TestRemoteHubNoted(t *testing.T) {
|
||||
isolate(t)
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
|
||||
var mu sync.Mutex
|
||||
info, lister := `{"name":"magpie","mcp_hub":true}`, "another"
|
||||
var asked []string // the info's requests, by key
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == "/v1" {
|
||||
asked = append(asked, r.Header.Get("Authorization"))
|
||||
io.WriteString(w, info)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, `{"object":"list","data":[{"id":"own/m1","object":"model","magpie_via":["`+lister+`"]}]}`)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
id, err := Add(Provider{ID: "rem", Name: "Rem", Preset: RemoteMagpiePreset, Key: "k1", Chat: strings.TrimPrefix(srv.URL, "http://")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := true
|
||||
var found []string
|
||||
oldA, oldF := RemoteHubAsk, RemoteHubFound
|
||||
t.Cleanup(func() { RemoteHubAsk, RemoteHubFound = oldA, oldF })
|
||||
RemoteHubAsk = func(string) bool { return want }
|
||||
RemoteHubFound = func(id string) { found = append(found, id) }
|
||||
fetch := func() {
|
||||
t.Helper()
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.Fetch(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
reset := func() { mu.Lock(); asked = nil; mu.Unlock(); found = nil }
|
||||
|
||||
fetch()
|
||||
if !slices.Equal(found, []string{"rem"}) || !slices.Equal(asked, []string{"Bearer k1"}) {
|
||||
t.Fatalf("found %v, asked %v; want rem, with its key", found, asked)
|
||||
}
|
||||
hs, err := RemoteHubs()
|
||||
if err != nil || len(hs) != 1 || hs[0] != (RemoteHub{ID: "rem", Name: "Rem", Root: srv.URL, Key: "k1"}) {
|
||||
t.Fatalf("RemoteHubs: %+v %v", hs, err)
|
||||
}
|
||||
|
||||
reset()
|
||||
want = false
|
||||
fetch()
|
||||
if len(found) != 0 || len(asked) != 0 {
|
||||
t.Errorf("not wanted: found %v, asked %v", found, asked)
|
||||
}
|
||||
|
||||
reset()
|
||||
want = true
|
||||
mu.Lock()
|
||||
info = `{"name":"magpie","version":"v0.1.1"}`
|
||||
mu.Unlock()
|
||||
fetch()
|
||||
if len(found) != 0 || len(asked) != 1 {
|
||||
t.Errorf("a magpie from before: found %v, asked %v", found, asked)
|
||||
}
|
||||
|
||||
// this magpie itself
|
||||
reset()
|
||||
mu.Lock()
|
||||
info, lister = `{"name":"magpie","mcp_hub":true}`, catalog.Self()
|
||||
mu.Unlock()
|
||||
fetch()
|
||||
if len(found) != 0 || len(asked) != 0 {
|
||||
t.Errorf("this magpie: found %v, asked %v", found, asked)
|
||||
}
|
||||
if hs, err := RemoteHubs(); err != nil || len(hs) != 0 {
|
||||
t.Errorf("RemoteHubs with this magpie: %+v %v", hs, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user