diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 07e3240df..bf1645ea4 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -16,7 +16,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | Targets | `Targets` lists the detected agents (`agent.Detected`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi and OmO each by its own rule, and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. | [`targets.go`](../../internal/library/targets.go) | | Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first, so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) | | Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). | [`instructions.go`](../../internal/library/instructions.go) | -| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only. Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#615). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go) | +| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only. Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#615); one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go) | | Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. | [`skills.go`](../../internal/library/skills.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) | | Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`) go first, marked official: `magpie-quota`, in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills/magpie-quota), lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) | | Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) | diff --git a/internal/access/access.go b/internal/access/access.go index 89e8d0524..2bea1cffb 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -442,9 +442,22 @@ func migrateLegacyLANKey() error { return settings.Save(s) } +// LANChanged is called after sharing is turned on or off, or its key made +// anew: what was given the key goes on with the one there is now (the +// library's MCP servers relayed to an agent in a WSL distro under NAT). +var LANChanged = func() {} + // ConfigureLAN starts sharing with a named key. Rotation preserves the key's // identity, name and enabled state. func ConfigureLAN(on, rotate bool) error { + if err := configureLAN(on, rotate); err != nil { + return err + } + LANChanged() + return nil +} + +func configureLAN(on, rotate bool) error { mu.Lock() defer mu.Unlock() if err := migrateLegacyLANKey(); err != nil { diff --git a/internal/agent/gatewaykey.go b/internal/agent/gatewaykey.go index ad0d59eab..b03542dc9 100644 --- a/internal/agent/gatewaykey.go +++ b/internal/agent/gatewaykey.go @@ -20,6 +20,10 @@ func keyAt(gw string) string { return gateway.Token } +// KeyAt is keyAt, for what else magpie gives an agent that reaches the +// gateway at gw (the library's MCP servers relayed through it). +func KeyAt(gw string) string { return keyAt(gw) } + // gwKey is keyAt for the agent at p. func (p place) gwKey() string { return keyAt(p.gw()) } diff --git a/internal/gateway/mcp_test.go b/internal/gateway/mcp_test.go index 77932cfb1..3225fc3dd 100644 --- a/internal/gateway/mcp_test.go +++ b/internal/gateway/mcp_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/mcpauth" "github.com/yetone/magpie/internal/mcpauth/mcpauthtest" ) @@ -132,6 +133,48 @@ func TestMCPProxyStaysHere(t *testing.T) { } } +// A WSL agent under NAT, at Windows' address, is lent the sign-in with the +// key the gateway is shared with as its Authorization (library's through), +// which the server never sees: it gets magpie's token. Without the key the +// call is a 401, which an MCP client takes for the server asking it to +// sign in. +func TestMCPProxyFromWSLWithLANKey(t *testing.T) { + fresh(t) + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + key := access.LANSecret() + f := mcpauthtest.New(t) + f.SignIn(t, "neon") + h := lanGuard(New().Handler()) + call := func(auth string) *httptest.ResponseRecorder { + r := httptest.NewRequest("POST", "/mcp/neon", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize"}`)) + r.RemoteAddr = "172.20.0.5:40000" + r.Host = "172.20.0.1:3425" + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Accept", "application/json, text/event-stream") + if auth != "" { + r.Header.Set("Authorization", auth) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + if w := call(""); w.Code != http.StatusUnauthorized || len(f.Calls) != 0 { + t.Fatalf("without the key: %d, calls %v", w.Code, f.Calls) + } + w := call("Bearer " + key) + token, _ := mcpauth.Token(t.Context(), "neon") + if w.Code != 200 || f.Seen.Get("Authorization") != "Bearer "+token { + t.Fatalf("with the LAN key: %d %s, the server got Authorization %q", w.Code, w.Body, f.Seen.Get("Authorization")) + } + for k, v := range f.Seen { + if strings.Contains(strings.Join(v, " "), key) { + t.Fatalf("the server got the LAN key in %s", k) + } + } +} + // A web page can't borrow magpie's sign-ins through the browser: a request // with an Origin, or one to a hostname of the page's own pointed at // 127.0.0.1, is refused before it reaches the server. diff --git a/internal/library/mcp_signin.go b/internal/library/mcp_signin.go index f778d728f..f115e4394 100644 --- a/internal/library/mcp_signin.go +++ b/internal/library/mcp_signin.go @@ -5,8 +5,11 @@ import ( "errors" "fmt" "net/url" + "slices" "strings" + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/mcpauth" ) @@ -19,6 +22,25 @@ import ( func init() { mcpauth.Changed = func(string) { _, _ = Sync() } + // an agent beyond loopback is given a relayed server with the LAN key + // (through), which is the one there is no longer + access.LANChanged = func() { + if relaysAny() { + _, _ = Sync() + } + } +} + +// relaysAny says whether any of the library's servers is given through the +// gateway: one magpie is signed in to. +func relaysAny() bool { + mu.Lock() + l, err := load() + mu.Unlock() + if err != nil { + return false + } + return slices.ContainsFunc(l.MCP, func(s *Server) bool { return s.Transport == "http" && mcpauth.SignedIn(s.Name, s.URL) }) } // through is the server as an agent that reaches the gateway at base is @@ -41,6 +63,16 @@ func through(s *Server, base string) *Server { } c.Headers[k] = v } + if k := agent.KeyAt(base); k != gateway.Token { + // from another machine (a WSL distro under NAT) the gateway refuses + // a call without an enabled key, with a 401 the agent would take + // for the server asking it to sign in; the relay drops this + // Authorization for magpie's token + if c.Headers == nil { + c.Headers = map[string]string{} + } + c.Headers["Authorization"] = "Bearer " + k + } return &c } diff --git a/internal/library/mcp_signin_wsl_test.go b/internal/library/mcp_signin_wsl_test.go new file mode 100644 index 000000000..1885c666f --- /dev/null +++ b/internal/library/mcp_signin_wsl_test.go @@ -0,0 +1,74 @@ +package library + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/mcpauth/mcpauthtest" +) + +// A WSL agent under NAT reaches the gateway at Windows' address, where a +// request without an enabled gateway key is refused with a 401, which an +// MCP client takes for the server asking it to sign in. A server magpie +// signed in to is given to it at /mcp/ with the key the gateway is +// shared with, as its models are; this machine's agent stays keyless, and +// so does the WSL one while nothing is shared. +func TestSignedInServerCarriesKeyBeyondLoopback(t *testing.T) { + sandbox(t) + root := t.TempDir() + write(t, filepath.Join(root, "home", "me", ".claude", "settings.json"), "{}\n") + t.Cleanup(agent.FakeWSL(map[string]string{ + "Ubuntu": "home:/home/me\ndir:.claude\nroute:default via 172.20.0.1 dev eth0\nnet:nat\n", + }, map[string]string{"Ubuntu": root})) + const wsl = "claude@wsl:Ubuntu" + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + key := access.LANSecret() + if key == "" { + t.Fatal("no LAN key") + } + f := mcpauthtest.New(t) + ok(t)(SaveServer("", Server{Name: "neon", Transport: "http", URL: f.URL, Headers: map[string]string{"X-Team": "acme"}, Agents: []string{"claude", wsl}})) + f.SignIn(t, "neon") + given := func(id string) *Server { + t.Helper() + tg := targetByID(id) + if tg == nil { + t.Fatalf("%s isn't a target: %v", id, ids(Targets())) + } + got, err := tg.MCP.read() + if err != nil { + t.Fatal(err) + } + return got["neon"] + } + s := given(wsl) + if s == nil || !strings.HasPrefix(s.URL, "http://172.20.0.1:") || !strings.HasSuffix(s.URL, "/mcp/neon") { + t.Fatalf("%s: %+v", wsl, s) + } + if s.Headers["Authorization"] != "Bearer "+key || s.Headers["X-Team"] != "acme" { + t.Fatalf("%s under NAT is given headers %v, want the LAN key as its Authorization", wsl, s.Headers) + } + if h := given("claude"); h == nil || h.Headers["Authorization"] != "" || h.Headers["X-Team"] != "acme" { + t.Fatalf("this machine's claude: %+v", h) + } + + // a new key, and sharing turned off, reach the entry without a visit + // to the Library + if err := access.ConfigureLAN(true, true); err != nil { + t.Fatal(err) + } + if fresh := access.LANSecret(); fresh == key || given(wsl).Headers["Authorization"] != "Bearer "+fresh { + t.Fatalf("after a new key %s is given %v", wsl, given(wsl).Headers) + } + if err := access.ConfigureLAN(false, false); err != nil { + t.Fatal(err) + } + if s := given(wsl); s == nil || s.Headers["Authorization"] != "" { + t.Fatalf("nothing shared, yet %s is given %+v", wsl, s) + } +}