diff --git a/internal/library/library.go b/internal/library/library.go index 54ab2ea03..c3edf29cb 100644 --- a/internal/library/library.go +++ b/internal/library/library.go @@ -249,8 +249,17 @@ func set(list []string, id string, on bool) []string { } // change runs f on the library under the lock, saves it, and writes what -// changed into the agents. +// changed into the agents. The processes of a server taken out are ended +// after, with the lock let go (mcp_reap.go). func change(f func(l *Library) error) (*Result, error) { + res, err := changeLocked(f) + if res != nil && len(res.dropped) > 0 { + ending(res.dropped) + } + return res, err +} + +func changeLocked(f func(l *Library) error) (*Result, error) { mu.Lock() defer mu.Unlock() l, err := load() diff --git a/internal/library/main_test.go b/internal/library/main_test.go index 68b79049c..200df431f 100644 --- a/internal/library/main_test.go +++ b/internal/library/main_test.go @@ -25,6 +25,8 @@ func TestMain(m *testing.M) { for _, k := range []string{"TMPDIR", "TMP", "TEMP"} { // TMP, TEMP: Windows' os.Setenv(k, tmp) } + // never the machine's own processes (mcp_reap.go) + ending = func([]*Server) {} code := testenv.Run(m) forgetProbes() if left := leftDownloads(tmp); len(left) > 0 && code == 0 { diff --git a/internal/library/mcp_reap.go b/internal/library/mcp_reap.go new file mode 100644 index 000000000..fa3741ea4 --- /dev/null +++ b/internal/library/mcp_reap.go @@ -0,0 +1,121 @@ +package library + +import ( + "context" + "log" + "slices" + "strings" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// A server taken out of an agent's config keeps running in an agent that +// doesn't read its config again until it restarts: Codex, the Codex app +// and Claude Code. With every server turned off in the Library, one user's +// agents went on holding 17.75 GB of node processes for them, one set more +// for each Codex session (#3885). So the processes of a stdio server taken +// out are ended, once no agent's config names that command any more. + +// ending ends the processes of the servers a change took out, before the +// change returns, as magpie library mcp exits after it; tests keep it from +// ending anything on the machine running them. +var ending = endDropped + +func endDropped(dropped []*Server) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + for _, s := range unused(dropped, Targets()) { + n, err := proc.EndTrees(ctx, launchedBy(s)) + if err != nil { + log.Printf("library: ending %s's processes: %v", s.Name, err) + } else if n > 0 { + log.Printf("library: ended %d process trees of %s, taken out of every agent", n, s.Name) + } + } +} + +// unused are the dropped stdio servers no agent's config runs any more, by +// command and arguments: one the user has under another name, or another +// agent still has, keeps running. +func unused(dropped []*Server, all []*Target) []*Server { + held := map[string]bool{} + for _, t := range all { + if t.MCP == nil { + continue + } + have, _ := t.MCP.read() + for _, s := range have { + held[launchKey(s)] = true + } + } + var out []*Server + for _, s := range dropped { + k := launchKey(s) + if k != "" && !held[k] && !slices.ContainsFunc(out, func(o *Server) bool { return launchKey(o) == k }) { + out = append(out, s) + } + } + return out +} + +// launchKey is a stdio server's command and arguments as launchedBy reads +// them; "" for a server with no command, or one too plain to tell its +// processes by (an interpreter with nothing after it). +func launchKey(s *Server) string { + if s == nil || s.Command == "" || s.URL != "" { + return "" + } + name := progName(s.Command) + args := words(strings.Join(s.Args, " ")) + if len(args) == 0 && interpreters[name] { + return "" + } + return name + "\x00" + strings.Join(args, "\x00") +} + +var interpreters = map[string]bool{ + "node": true, "npx": true, "npm": true, "pnpm": true, "bunx": true, "bun": true, "deno": true, + "uv": true, "uvx": true, "python": true, "python3": true, "py": true, "pipx": true, + "docker": true, "podman": true, "sh": true, "bash": true, "zsh": true, "cmd": true, + "powershell": true, "pwsh": true, "java": true, "go": true, "ruby": true, +} + +// launchedBy picks a command line that runs s: its arguments last, with +// its command's program before them. It reads npx -y x run as +// `cmd /d /s /c "npx -y x"` and as `node …\npx-cli.js -y x` alike, the +// wrapper and the node it starts for Codex on Windows. +func launchedBy(s *Server) func(string) bool { + key := launchKey(s) + name := progName(s.Command) + args := words(strings.Join(s.Args, " ")) + return func(line string) bool { + if key == "" { + return false + } + w := words(line) + if len(w) <= len(args) || !slices.EqualFunc(w[len(w)-len(args):], args, strings.EqualFold) { + return false + } + before := w[:len(w)-len(args)] + if len(args) == 0 { + return progName(before[len(before)-1]) == name + } + return slices.ContainsFunc(before, func(x string) bool { return progName(x) == name }) + } +} + +// words is a command line split at spaces, its quotes dropped. +func words(line string) []string { + return strings.Fields(strings.ReplaceAll(line, `"`, " ")) +} + +// progName is a program's name, lowercased, with no folder, extension or +// -cli: npx for C:\Program Files\nodejs\node_modules\npm\bin\npx-cli.js. +func progName(p string) string { + p = strings.ToLower(p[strings.LastIndexAny(p, `/\`)+1:]) + for _, ext := range []string{".exe", ".cmd", ".bat", ".ps1", ".js", ".cjs", ".mjs"} { + p = strings.TrimSuffix(p, ext) + } + return strings.TrimSuffix(p, "-cli") +} diff --git a/internal/library/mcp_reap_test.go b/internal/library/mcp_reap_test.go new file mode 100644 index 000000000..ebfd16c28 --- /dev/null +++ b/internal/library/mcp_reap_test.go @@ -0,0 +1,93 @@ +package library + +import ( + "path/filepath" + "slices" + "testing" +) + +// A server turned off goes from the agents that run it only once no agent's +// config runs that command: another agent's entry, or the user's own under +// another name, keeps it (#3885). +func TestDroppedServerEndedOnceNoAgentRunsIt(t *testing.T) { + h := sandbox(t) + write(t, filepath.Join(h, ".codex", "config.toml"), "") + write(t, filepath.Join(h, ".config", "opencode", "opencode.json"), "{}") + var dropped []*Server + was := ending + ending = func(d []*Server) { dropped = append(dropped, d...) } + t.Cleanup(func() { ending = was }) + names := func(ss []*Server) []string { + var out []string + for _, s := range ss { + out = append(out, s.Name+": "+s.Command+" "+filepath.Join(s.Args...)) + } + return out + } + + ok(t)(SaveServer("", Server{Name: "tavily", Transport: "stdio", Command: "npx", Args: []string{"-y", "tavily-mcp"}, Agents: []string{"codex", "opencode"}})) + if len(dropped) != 0 { + t.Fatalf("dropped on adding: %v", names(dropped)) + } + ok(t)(ServerAgents("tavily", []string{"opencode"})) + if got := names(dropped); !slices.Equal(got, []string{"tavily: npx " + filepath.Join("-y", "tavily-mcp")}) { + t.Fatalf("dropped from codex: %v", got) + } + if got := unused(dropped, Targets()); len(got) != 0 { + t.Errorf("OpenCode runs it still, but it is ended: %v", names(got)) + } + + // the user's own entry in Claude Code, by another name, runs the same + write(t, filepath.Join(h, ".claude.json"), `{"mcpServers": {"web": {"command": "npx", "args": ["-y", "tavily-mcp"]}}}`) + dropped = nil + ok(t)(ServerAgents("tavily", nil)) + if len(dropped) != 1 { + t.Fatalf("dropped from opencode: %v", names(dropped)) + } + if got := unused(dropped, Targets()); len(got) != 0 { + t.Errorf("Claude Code's own entry runs it, but it is ended: %v", names(got)) + } + write(t, filepath.Join(h, ".claude.json"), `{}`) + if got := unused(dropped, Targets()); len(got) != 1 { + t.Errorf("no agent runs it, but it isn't ended: %v", names(got)) + } + + // taken out of the library while on an agent + ok(t)(ServerAgents("tavily", []string{"codex"})) + dropped = nil + ok(t)(RemoveServer("tavily")) + if got := unused(dropped, Targets()); len(got) != 1 { + t.Errorf("removed: %v, ended %v", names(dropped), names(got)) + } +} + +// launchedBy reads the processes a server's command line starts, from the +// lines of #3885's Windows machine and their macOS and Linux forms. +func TestLaunchedBy(t *testing.T) { + tavily := launchedBy(&Server{Command: "npx", Args: []string{"-y", "tavily-mcp"}}) + for line, want := range map[string]bool{ + `C:\WINDOWS\system32\cmd.exe /d /s /c "npx -y tavily-mcp"`: true, + `"C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npx-cli.js" -y tavily-mcp`: true, + `node /usr/local/lib/node_modules/npm/bin/npx-cli.js -y tavily-mcp`: true, + `npm exec tavily-mcp`: false, // what npx runs is under the npx it is ended with + `node C:\Users\u\AppData\Local\npm-cache\_npx\1\node_modules\tavily-mcp\build\index.js`: false, + `cmd.exe /d /s /c "npx -y tavily-mcp-two"`: false, + `bunx -y tavily-mcp`: false, + `npx -y other tavily-mcp`: false, + `tavily-mcp`: false, + } { + if got := tavily(line); got != want { + t.Errorf("%s: %v, want %v", line, got, want) + } + } + bin := launchedBy(&Server{Command: `C:\tools\firecrawl-mcp.cmd`}) + if !bin(`C:\WINDOWS\system32\cmd.exe /d /s /c "C:\tools\firecrawl-mcp.cmd"`) || bin(`firecrawl-mcp-x`) { + t.Error("a server with no arguments is told by its program") + } + // an interpreter with nothing after it is anything it runs + for _, s := range []*Server{{Command: "node"}, {Command: "npx"}, {URL: "https://x", Command: "npx", Args: []string{"x"}}, {}} { + if launchKey(s) != "" || launchedBy(s)(`node index.js`) || launchedBy(s)(`node`) { + t.Errorf("%+v picks", s) + } + } +} diff --git a/internal/library/sync.go b/internal/library/sync.go index 26dbf66e7..26dc98333 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -37,6 +37,9 @@ type Result struct { Installed []string `json:"installed,omitempty"` Had []string `json:"had,omitempty"` Skipped []Problem `json:"skipped,omitempty"` + // dropped are the servers taken out of an agent's config, as it had + // them, whose processes go once no agent runs them (mcp_reap.go) + dropped []*Server } // Problem is one thing that couldn't be given to an agent. @@ -165,6 +168,9 @@ func Sync() (*Result, error) { pruneBackups() mu.Unlock() } + if len(res.dropped) > 0 { + ending(res.dropped) + } return res, nil } @@ -206,10 +212,16 @@ func (l *Library) syncMCP(t *Target, b *backups, res *Result) { if s := l.server(name); s != nil && slices.Contains(s.Agents, id) && t.MCP.supports(s) == nil { continue } - if _, ok := entries[name]; (ok || t.MCP.holds(name)) && !write("mcp:"+name, func() error { return t.MCP.del(name) }) { + e, ok := entries[name] + if !ok && !t.MCP.holds(name) { + continue + } + if !write("mcp:"+name, func() error { return t.MCP.del(name) }) { mine = append(mine, name) toolsOff[name] = a.ToolsOff[name] startup[name] = a.Startup[name] + } else if had, ok := t.MCP.decode(name, e); ok && e != nil { + res.dropped = append(res.dropped, had) } } base := gatewayOf(t) diff --git a/internal/proc/family.go b/internal/proc/family.go new file mode 100644 index 000000000..0b7e1001e --- /dev/null +++ b/internal/proc/family.go @@ -0,0 +1,108 @@ +package proc + +import ( + "context" + "os" + "strconv" + "strings" +) + +// A Kin is a running process with its parent's id, as a listing of every +// process saw it. +type Kin struct { + PID, PPID int + Args string +} + +// EndTrees ends the processes match picks from every process this user +// can see, each with all it started, and says how many match picked. A +// process under one already picked goes with that one; magpie and what it +// runs under are never picked. It is how a turned-off MCP server's +// processes go when the agent that started them keeps running (#3885). +func EndTrees(ctx context.Context, match func(args string) bool) (int, error) { + ps, err := family(ctx) + if err != nil { + return 0, err + } + picked := picks(ps, match, os.Getpid()) + for _, pid := range picked { + endFamily(pid, under(ps, pid)) + } + return len(picked), nil +} + +// parseFamily reads lines of "pid ppid command line", as ps prints them. +func parseFamily(out string) []Kin { + var ps []Kin + for _, line := range strings.Split(out, "\n") { + id, rest, _ := strings.Cut(strings.TrimSpace(line), " ") + parent, args, _ := strings.Cut(strings.TrimSpace(rest), " ") + pid, err1 := strconv.Atoi(id) + ppid, err2 := strconv.Atoi(parent) + if err1 != nil || err2 != nil || pid <= 0 { + continue + } + ps = append(ps, Kin{PID: pid, PPID: ppid, Args: strings.TrimSpace(args)}) + } + return ps +} + +// picks are the processes match picks, but those under another picked one +// and self with what it runs under. +func picks(ps []Kin, match func(string) bool, self int) []int { + parent := map[int]int{} + for _, p := range ps { + if p.PID != p.PPID { + parent[p.PID] = p.PPID + } + } + mine := map[int]bool{} + for p, n := self, 0; p > 0 && n < len(ps)+1; p, n = parent[p], n+1 { + mine[p] = true + } + hit := map[int]bool{} + for _, p := range ps { + if !mine[p.PID] && p.Args != "" && match(p.Args) { + hit[p.PID] = true + } + } + var out []int + for _, p := range ps { + if !hit[p.PID] { + continue + } + top := true + for q, n := parent[p.PID], 0; q > 0 && n < len(ps); q, n = parent[q], n+1 { + if hit[q] { + top = false + break + } + } + if top { + out = append(out, p.PID) + } + } + return out +} + +// under are the processes started under pid, at any depth, nearest first. +func under(ps []Kin, pid int) []int { + kids := map[int][]int{} + for _, p := range ps { + if p.PID != p.PPID { + kids[p.PPID] = append(kids[p.PPID], p.PID) + } + } + var out []int + seen := map[int]bool{pid: true} + for queue := []int{pid}; len(queue) > 0; queue = queue[1:] { + for _, k := range kids[queue[0]] { + if !seen[k] { + seen[k] = true + out = append(out, k) + queue = append(queue, k) + } + } + } + return out +} diff --git a/internal/proc/family_test.go b/internal/proc/family_test.go new file mode 100644 index 000000000..d211d940c --- /dev/null +++ b/internal/proc/family_test.go @@ -0,0 +1,116 @@ +package proc + +import ( + "context" + "fmt" + "os" + "slices" + "strings" + "testing" + "time" +) + +func TestParseFamily(t *testing.T) { + got := parseFamily(" 101 1 /usr/bin/node /x/npx-cli.js -y tavily-mcp\n 7 0\nnope\n 102 101 node index.js\n") + want := []Kin{{101, 1, "/usr/bin/node /x/npx-cli.js -y tavily-mcp"}, {7, 0, ""}, {102, 101, "node index.js"}} + if !slices.Equal(got, want) { + t.Fatalf("%+v", got) + } +} + +// A process under one picked goes with it, and magpie and what it runs +// under are never picked, whatever their command lines say. +func TestPicks(t *testing.T) { + ps := []Kin{ + {1, 0, "init x"}, // under magpie + {10, 1, "codex x"}, // the agent + {11, 10, "cmd /c npx x"}, // the wrapper: picked + {12, 11, "npx-cli x"}, // under it: ends with it + {13, 12, "node index.js"}, + {20, 1, "npx-cli x"}, // its wrapper gone: picked + {30, 1, "shell x"}, // runs magpie + {31, 30, "magpie x"}, + {40, 40, "loop x"}, // its own parent + } + match := func(a string) bool { return strings.HasSuffix(a, " x") } + if got := picks(ps, match, 31); !slices.Equal(got, []int{10, 20, 40}) { + t.Errorf("picks: %v", got) + } + if got := under(ps, 10); !slices.Equal(got, []int{11, 12, 13}) { + t.Errorf("under: %v", got) + } +} + +// A helper for TestEndTreesEndsWhatItStarted: the parent starts a child, +// and both wait. +func TestFamilyHelper(t *testing.T) { + switch os.Getenv("MAGPIE_FAMILY_HELPER") { + case "parent": + cmd := Command(os.Args[0], "-test.run=^TestFamilyHelper$") + cmd.Env = append(os.Environ(), "MAGPIE_FAMILY_HELPER=child") + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + time.Sleep(60 * time.Second) + _ = cmd.Process.Kill() + case "child": + time.Sleep(60 * time.Second) + } +} + +// EndTrees ends the process its match picks, and what that process +// started, whose own command line names nothing it picks: npx's server +// under npx (#3885). +func TestEndTreesEndsWhatItStarted(t *testing.T) { + mark := fmt.Sprintf("family-%d-%d", os.Getpid(), time.Now().UnixNano()) + cmd := Command(os.Args[0], "-test.run=^TestFamilyHelper$", mark) + cmd.Env = append(os.Environ(), "MAGPIE_FAMILY_HELPER=parent") + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + go func() { _ = cmd.Wait(); close(done) }() + child := 0 + t.Cleanup(func() { + _ = cmd.Process.Kill() + if child > 0 { + _ = kill(child) + } + <-done + }) + alive := func(pid int) bool { + ps, err := family(context.Background()) + if err != nil { + t.Fatal(err) + } + for _, p := range ps { + if p.PID == pid && !strings.Contains(p.Args, "") { + return true + } + if pid == 0 && p.PPID == cmd.Process.Pid { + child = p.PID + return true + } + } + return false + } + for end := time.Now().Add(20 * time.Second); !alive(0); time.Sleep(50 * time.Millisecond) { + if time.Now().After(end) { + t.Fatal("the helper's child never started") + } + } + n, err := EndTrees(context.Background(), func(args string) bool { return strings.HasSuffix(args, " "+mark) }) + if err != nil || n != 1 { + t.Fatalf("EndTrees = %d, %v; want 1", n, err) + } + select { + case <-done: + case <-time.After(20 * time.Second): + t.Fatal("the picked process runs 20s after EndTrees") + } + for end := time.Now().Add(20 * time.Second); alive(child); time.Sleep(50 * time.Millisecond) { + if time.Now().After(end) { + t.Fatal("the process it started runs 20s after EndTrees") + } + } +} diff --git a/internal/proc/list_other.go b/internal/proc/list_other.go index 9544110e4..3d1382539 100644 --- a/internal/proc/list_other.go +++ b/internal/proc/list_other.go @@ -13,3 +13,21 @@ func list(ctx context.Context, _ string) ([]Process, error) { } return parseList(string(out)), nil } + +// family is ps with each process's parent too. +func family(ctx context.Context) ([]Kin, error) { + out, err := CommandContext(ctx, "ps", "-A", "-o", "pid=", "-o", "ppid=", "-o", "args=").Output() + if err != nil { + return nil, err + } + return parseFamily(string(out)), nil +} + +// endFamily ends pid, then what it started as the listing saw it: npx +// leaves the server it ran when it ends. +func endFamily(pid int, kids []int) { + _ = end(pid) + for _, k := range kids { + _ = end(k) + } +} diff --git a/internal/proc/list_windows.go b/internal/proc/list_windows.go index 553e9d62e..ea61404d3 100644 --- a/internal/proc/list_windows.go +++ b/internal/proc/list_windows.go @@ -61,3 +61,31 @@ func commandLine(pid uint32) string { } return strings.TrimSpace((*windows.NTUnicodeString)(unsafe.Pointer(&buf[0])).String()) } + +// family walks a Toolhelp snapshot of every process, with its parent's +// id and its command line. +func family(ctx context.Context) ([]Kin, error) { + snap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0) + if err != nil { + return nil, err + } + defer windows.CloseHandle(snap) + var ps []Kin + e := windows.ProcessEntry32{Size: uint32(unsafe.Sizeof(windows.ProcessEntry32{}))} + for err = windows.Process32First(snap, &e); err == nil; err = windows.Process32Next(snap, &e) { + if err := ctx.Err(); err != nil { + return nil, err + } + if e.ProcessID != 0 { + ps = append(ps, Kin{PID: int(e.ProcessID), PPID: int(e.ParentProcessID), Args: commandLine(e.ProcessID)}) + } + } + if err != windows.ERROR_NO_MORE_FILES { + return nil, err + } + return ps, nil +} + +// endFamily is endTree, which tells what pid started from a later process +// given an old parent's id by its start. +func endFamily(pid int, _ []int) { _ = endTree(pid) }