library: a server run with npx -y reaches the agent as node running the package (#3885)

npx stays running as the server's parent for the server's whole life.
On Windows that is cmd.exe + npx's node + a second cmd.exe beside the
server: measured on xiaomi-gpu with @modelcontextprotocol/server-memory,
4 processes and 143 MB (cmd 8.1, npx node 76.2, cmd 8.2, server 50.8)
for one instance. Codex starts an instance a thread; #3885 had 223 node
processes under codex.exe.

A library server `npx -y <registry package> args` (no other npx flag)
is now installed with npm into ~/.config/magpie/mcp-npm/<hash> in the
background, and the next sync writes it into each agent on this machine
as `node <package bin> args`: node by name for npx by name, or the node
beside an npx given by path. Until the install is done, or when npm
fails (tried again after an hour), the agent keeps npx. An unpinned
spec is installed again after a day, as npx would fetch the newer one;
an install no library server runs any more is removed a day after its
last. The library's own entry, a server's check, Copy config… and WSL
agents keep npx. Taking a server off ends node's run of the program
(launchedBy reads the node line), as before for npx.

Run at this head (rebased on origin/main 1ff54f079; nothing it brought
touches internal/library):
- mote: go test -count=1 -timeout 45m ./internal/library ok (116s);
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/library ok;
  ./internal/proc/... ./internal/testenv/... and the root package ok;
  TestNpx*/TestReadNpx under -race ok.
- xiaomi-gpu (win-run): TestNpx*/TestReadNpx ok.
- Real, on xiaomi-gpu, Node 22 + real npm registry, sandbox HOME: the
  library synced server-memory into a Codex config.toml; the install
  took 12.8s and the second sync wrote command = "node", args = [the
  install's …\server-memory\dist\index.js]. Started from that entry, the
  server answered initialize and tools/list, and its process tree was 1
  process at 56.2 MB, against 4 processes and 143 MB through npx.
- Broken by hand: without the npxDirect call in syncMCP,
  TestNpxServerRunsByNode is red ("the package was never installed").

Not tried: a real Codex or Claude Code session starting the node entry
(the entry has the same command/args shape they already start), and
macOS's process tree (npx's node and sh there too).
Not done (#3885 stays open): Codex starting the same MCP once a thread.
This commit is contained in:
yetone
2026-10-29 01:30:58 +08:00
parent 1ff54f079f
commit 425a613224
5 changed files with 485 additions and 2 deletions
File diff suppressed because one or more lines are too long
+2
View File
@@ -27,6 +27,8 @@ func TestMain(m *testing.M) {
}
// never the machine's own processes (mcp_reap.go)
ending = func([]*Server) {}
// never the registry (mcp_npx.go)
npxInstall = nil
code := testenv.Run(m)
forgetProbes()
if left := leftDownloads(tmp); len(left) > 0 && code == 0 {
+315
View File
@@ -0,0 +1,315 @@
package library
// A server run with `npx -y pkg` is given to an agent as node running the
// package's own program, from a folder magpie installs the package in.
// npx stays running as the server's parent for as long as the server
// does: on Windows a cmd.exe, npx's node (76 MB) and a second cmd.exe
// beside a 51 MB server, ~92 MB of wrapper a server for each instance an
// agent starts; Codex starts one a thread, 200 of them in #3885. Until
// the package is installed, and for any npx line not read here, the
// agent is given npx as the library has it; the library itself, and a
// server's check, keep npx.
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/settings"
)
// npxRun is an `npx -y <spec> args…` line: the package and its arguments.
type npxRun struct {
spec, name string
args []string
}
// npmSpec is a package from the registry, with a version or tag or none:
// npx's other specs (a path, a git or tarball URL, an alias) are left to
// npx.
var npmSpec = regexp.MustCompile(`^((?:@[a-z0-9][a-z0-9._~-]*/)?[a-z0-9][a-z0-9._~-]*)(?:@([A-Za-z0-9._~^<>=*| -]+))?$`)
// readNpx is s's npx line, ok false for anything else: a flag but -y
// before the package (-p, --package, -c, a registry), or no -y, which
// would have npx ask on the server's own stdin.
func readNpx(s *Server) (npxRun, bool) {
if s.Remote() || progName(s.Command) != "npx" {
return npxRun{}, false
}
yes := false
for i, a := range s.Args {
switch {
case a == "-y" || a == "--yes":
yes = true
case strings.HasPrefix(a, "-"):
return npxRun{}, false
default:
m := npmSpec.FindStringSubmatch(a)
if !yes || m == nil {
return npxRun{}, false
}
return npxRun{spec: a, name: m[1], args: s.Args[i+1:]}, true
}
}
return npxRun{}, false
}
// pinned says the spec names an exact version, which never changes: one
// with none, or a tag or range, is installed again after a day, as npx
// would fetch the newer one.
func (r npxRun) pinned() bool {
_, v, ok := strings.Cut(strings.TrimPrefix(r.spec, "@"), "@")
return ok && exactVersion.MatchString(v)
}
var exactVersion = regexp.MustCompile(`^\d+\.\d+\.\d+([-+].*)?$`)
// npxDir is where magpie installs a spec: a folder of its own each.
func npxDir(spec string) string {
h := sha256.Sum256([]byte(spec))
return filepath.Join(settings.Dir(), "mcp-npm", hex.EncodeToString(h[:8]))
}
// nodeBeside is the node to run the package with: node by name for npx
// by name, as the agent finds both on its PATH, or the node in npx's own
// folder; "" when that folder has none.
func nodeBeside(npx string) string {
if !strings.ContainsAny(npx, `/\`) {
return "node"
}
node := filepath.Join(filepath.Dir(npx), "node")
if runtime.GOOS == "windows" {
node += ".exe"
}
if st, err := os.Stat(node); err != nil || st.IsDir() {
return ""
}
return node
}
// npxBin is the program npx would run of the package installed in dir:
// its one bin, or the one named as the package; "" when there is none,
// or it isn't a script node runs.
func npxBin(dir, name string) string {
pkg := filepath.Join(dir, "node_modules", filepath.FromSlash(name))
b, err := os.ReadFile(filepath.Join(pkg, "package.json"))
if err != nil {
return ""
}
var m struct {
Bin json.RawMessage `json:"bin"`
}
if json.Unmarshal(b, &m) != nil {
return ""
}
var rel, one string
var bins map[string]string
switch {
case json.Unmarshal(m.Bin, &one) == nil:
rel = one
case json.Unmarshal(m.Bin, &bins) == nil:
if len(bins) == 1 {
for _, v := range bins {
rel = v
}
} else {
rel = bins[name[strings.LastIndexByte(name, '/')+1:]]
}
}
if rel == "" {
return ""
}
bin := filepath.Join(pkg, filepath.FromSlash(rel))
if rel, err := filepath.Rel(pkg, bin); err != nil || strings.HasPrefix(rel, "..") {
return ""
}
head := make([]byte, 128)
f, err := os.Open(bin)
if err != nil {
return ""
}
n, _ := f.Read(head)
f.Close()
ext := strings.ToLower(filepath.Ext(bin))
if ext != ".js" && ext != ".cjs" && ext != ".mjs" {
line, _, _ := strings.Cut(string(head[:n]), "\n")
if !strings.HasPrefix(line, "#!") || !strings.Contains(line, "node") {
return ""
}
}
return bin
}
// npxDirect is s as node running the package's program, when magpie has
// the package installed; s when it hasn't, with the install started.
func npxDirect(s *Server) *Server {
r, ok := readNpx(s)
if !ok || npxInstall == nil {
return s
}
node := nodeBeside(s.Command)
if node == "" {
return s
}
dir := npxDir(r.spec)
bin := npxBin(dir, r.name)
if bin == "" || !r.pinned() && npxStale(dir) {
npxStart(r, s.Command, dir, bin == "")
}
if bin == "" {
return s
}
c := *s
c.Command = node
c.Args = append([]string{bin}, r.args...)
return &c
}
// npxStale says the install is a day old.
func npxStale(dir string) bool {
st, err := os.Stat(filepath.Join(dir, ".installed"))
return err != nil || time.Since(st.ModTime()) > 24*time.Hour
}
var npxQueue struct {
sync.Mutex
busy map[string]bool
failed map[string]time.Time
}
// npxStart installs the spec in the background, once at a time; new says
// nothing is installed yet, and the agents are synced again once it is.
// A failed install is tried again after an hour.
func npxStart(r npxRun, npx, dir string, new bool) {
npxQueue.Lock()
if npxQueue.busy == nil {
npxQueue.busy, npxQueue.failed = map[string]bool{}, map[string]time.Time{}
}
if npxQueue.busy[dir] || time.Since(npxQueue.failed[dir]) < time.Hour {
npxQueue.Unlock()
return
}
npxQueue.busy[dir] = true
npxQueue.Unlock()
go func() {
err := npxInstall(r.spec, npx, dir)
npxQueue.Lock()
delete(npxQueue.busy, dir)
if err != nil {
npxQueue.failed[dir] = time.Now()
}
npxQueue.Unlock()
if err != nil {
log.Printf("library: installing %s for its MCP server: %v", r.spec, err)
return
}
if new && npxBin(dir, r.name) != "" && npxSynced != nil {
npxSynced()
}
}()
}
// npxInstall installs spec in dir with the npm beside npx; nil in tests,
// which never reach the registry.
var npxInstall = realInstall
func realInstall(spec, npx, dir string) error {
npm := "npm"
if strings.ContainsAny(npx, `/\`) {
npm = filepath.Join(filepath.Dir(npx), "npm")
if runtime.GOOS == "windows" {
npm += ".cmd"
}
} else if _, err := exec.LookPath(npm); err != nil {
if p := proc.FindTool(npm); p != "" {
npm = p
}
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
// a package.json of its own, so npm never takes a folder above for
// the project
if _, err := os.Stat(filepath.Join(dir, "package.json")); err != nil {
if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte("{\"private\":true}\n"), 0o644); err != nil {
return err
}
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
cmd := proc.CommandContext(ctx, npm, "install", "--prefix", dir, "--no-save", "--no-package-lock", "--no-audit", "--no-fund", "--loglevel=error", spec)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
return &npmError{err, strings.TrimSpace(string(out))}
}
return os.WriteFile(filepath.Join(dir, ".installed"), []byte(spec+"\n"), 0o644)
}
type npmError struct {
err error
out string
}
func (e *npmError) Error() string {
if len(e.out) > 400 {
e.out = e.out[len(e.out)-400:]
}
return e.err.Error() + ": " + e.out
}
// npxSynced syncs the agents again, for the servers an install has given
// a program; a var for tests.
var npxSynced func()
func init() {
npxSynced = func() {
if _, err := Sync(); err != nil {
log.Printf("library: syncing after an MCP package install: %v", err)
}
}
}
// npxDirs are the folders of the packages the library's servers run.
func (l *Library) npxDirs() map[string]bool {
dirs := map[string]bool{}
for _, s := range l.MCP {
if r, ok := readNpx(s); ok {
dirs[filepath.Base(npxDir(r.spec))] = true
}
}
return dirs
}
// npxPrune takes out the installs no server of the library's runs, a day
// after the last: a server taken out of the library leaves no package
// behind.
func npxPrune(keep map[string]bool) {
if npxInstall == nil {
return
}
root := filepath.Dir(npxDir(""))
des, _ := os.ReadDir(root)
for _, de := range des {
dir := filepath.Join(root, de.Name())
if !de.IsDir() || keep[de.Name()] || !npxStale(dir) {
continue
}
npxQueue.Lock()
busy := npxQueue.busy[dir]
npxQueue.Unlock()
if !busy {
os.RemoveAll(dir)
}
}
}
+161
View File
@@ -0,0 +1,161 @@
package library
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
)
// The npx lines read as a package and its arguments, and those left to npx.
func TestReadNpx(t *testing.T) {
for _, c := range []struct {
cmd string
args []string
spec string
rest []string
}{
{"npx", []string{"-y", "@playwright/mcp@latest", "--headless"}, "@playwright/mcp@latest", []string{"--headless"}},
{`C:\Program Files\nodejs\npx.cmd`, []string{"--yes", "tavily-mcp@0.2.1"}, "tavily-mcp@0.2.1", []string{}},
{"/opt/homebrew/bin/npx", []string{"-y", "firecrawl-mcp"}, "firecrawl-mcp", []string{}},
{"npx", []string{"firecrawl-mcp"}, "", nil}, // no -y: npx asks
{"npx", []string{"-y", "-p", "a", "b"}, "", nil}, // -p
{"npx", []string{"-y", "github:me/srv"}, "", nil}, // not the registry's
{"npx", []string{"-y", "./srv"}, "", nil}, // a path
{"bunx", []string{"-y", "srv"}, "", nil}, // not npx
{"npx", []string{"-y", "--registry=https://x", "srv"}, "", nil}, // a flag of npm's
{"node", []string{"-y", "srv"}, "", nil}, // node
{"npx", []string{"-y", "mcp-remote", "https://hf.co/mcp"}, "mcp-remote", []string{"https://hf.co/mcp"}},
} {
r, ok := readNpx(&Server{Transport: "stdio", Command: c.cmd, Args: c.args})
if ok != (c.spec != "") || r.spec != c.spec || len(r.args)+len(c.rest) > 0 && !slices.Equal(r.args, c.rest) {
t.Errorf("%s %q: read %q %q %v, want %q %q", c.cmd, c.args, r.spec, r.args, ok, c.spec, c.rest)
}
}
for spec, pinned := range map[string]bool{"a@1.2.3": true, "@s/a@0.1.0-beta.2": true, "a": false, "@s/a": false, "a@latest": false, "a@^1.2.0": false} {
if (npxRun{spec: spec}).pinned() != pinned {
t.Errorf("%s pinned = %v", spec, !pinned)
}
}
}
// An agent is given an npx server as node running the package's program
// from magpie's install of it, with the server's arguments after: no npx
// left between the agent and the server, which held a node and two
// cmd.exe a server on Windows (#3885). Before the install is done the
// agent has npx, as the library does; the install is asked for once.
func TestNpxServerRunsByNode(t *testing.T) {
h := sandbox(t)
cfg := filepath.Join(h, ".codex/config.toml")
installs := make(chan string, 4)
release := make(chan struct{})
npxInstall = func(spec, npx, dir string) error {
installs <- spec
<-release
pkg := filepath.Join(dir, "node_modules", "@acme", "mcp")
if err := os.MkdirAll(filepath.Join(pkg, "dist"), 0o755); err != nil {
return err
}
write(t, filepath.Join(pkg, "package.json"), `{"name":"@acme/mcp","bin":{"acme-mcp":"dist/cli.js"}}`)
write(t, filepath.Join(pkg, "dist", "cli.js"), "#!/usr/bin/env node\n")
return nil
}
synced := make(chan struct{}, 1)
npxSynced = func() { synced <- struct{}{} }
t.Cleanup(func() { npxInstall, npxSynced = nil, nil })
srv := Server{Name: "acme", Transport: "stdio", Command: "npx", Args: []string{"-y", "@acme/mcp@1.0.0", "--port", "0"}, Agents: []string{"codex"}}
ok(t)(SaveServer("", srv))
if e := codexEntry(t, cfg, "acme"); e["command"] != "npx" {
t.Fatalf("before the install, Codex has %v, want npx:\n%s", e["command"], read(t, cfg))
}
select {
case got := <-installs:
if got != "@acme/mcp@1.0.0" {
t.Fatalf("installed %q", got)
}
case <-time.After(30 * time.Second):
close(release)
t.Fatal("the package was never installed")
}
ok(t)(Sync()) // while installing: asked for no second time
close(release)
select {
case <-synced:
case <-time.After(30 * time.Second):
t.Fatal("the install never asked for a sync")
}
if len(installs) > 0 {
t.Fatalf("the package was installed again: %s", <-installs)
}
ok(t)(Sync())
e := codexEntry(t, cfg, "acme")
args, _ := e["args"].([]any)
if e["command"] != "node" || len(args) != 3 || !strings.HasSuffix(filepath.ToSlash(args[0].(string)), "/node_modules/@acme/mcp/dist/cli.js") || args[1] != "--port" || args[2] != "0" {
t.Fatalf("Codex runs %v %v, want node …/@acme/mcp/dist/cli.js --port 0:\n%s", e["command"], args, read(t, cfg))
}
before := read(t, cfg)
ok(t)(Sync())
if read(t, cfg) != before {
t.Fatalf("a sync wrote the entry again:\n%s", read(t, cfg))
}
if l, _ := load(); l.server("acme").Command != "npx" {
t.Fatalf("the library's own server became %s", l.server("acme").Command)
}
// taken off, the processes running the program are the ones ended
var ended []*Server
ending = func(s []*Server) { ended = append(ended, s...) }
t.Cleanup(func() { ending = func([]*Server) {} })
ok(t)(ServerAgents("acme", nil))
if len(ended) != 1 || !launchedBy(ended[0])(`"node" "`+args[0].(string)+`" --port 0`) {
t.Fatalf("ended %v, want node's run of the program", ended)
}
// out of the library, the install goes a day after its last
dir := npxDir("@acme/mcp@1.0.0")
write(t, filepath.Join(dir, ".installed"), "@acme/mcp@1.0.0\n")
ok(t)(Sync())
if _, err := os.Stat(dir); err != nil {
t.Fatalf("the install of a server the library has went: %v", err)
}
ok(t)(RemoveServer("acme"))
ok(t)(Sync())
if _, err := os.Stat(dir); err != nil {
t.Fatalf("an install under a day old went at once: %v", err)
}
old := time.Now().Add(-25 * time.Hour)
os.Chtimes(filepath.Join(dir, ".installed"), old, old)
ok(t)(Sync())
if _, err := os.Stat(dir); err == nil {
t.Fatal("the install of a server taken out of the library stays")
}
}
// A package whose program isn't a script node runs, or with no bin to
// pick, stays with npx.
func TestNpxBinPicks(t *testing.T) {
dir := t.TempDir()
put := func(name, pkgJSON string, files map[string]string) {
pkg := filepath.Join(dir, "node_modules", filepath.FromSlash(name))
os.MkdirAll(pkg, 0o755)
write(t, filepath.Join(pkg, "package.json"), pkgJSON)
for f, b := range files {
os.MkdirAll(filepath.Dir(filepath.Join(pkg, f)), 0o755)
write(t, filepath.Join(pkg, f), b)
}
}
put("one", `{"bin":"cli.mjs"}`, map[string]string{"cli.mjs": "import x from 'y'"})
put("@s/two", `{"bin":{"other":"o.js","two":"bin/two"}}`, map[string]string{"bin/two": "#!/usr/bin/env node\n", "o.js": ""})
put("native", `{"bin":{"native":"bin/native"}}`, map[string]string{"bin/native": "\x7fELF"})
put("many", `{"bin":{"a":"a.js","b":"b.js"}}`, map[string]string{"a.js": "", "b.js": ""})
put("out", `{"bin":"../one/cli.mjs"}`, nil)
for name, want := range map[string]string{"one": "cli.mjs", "@s/two": "bin/two", "native": "", "many": "", "out": "", "none": ""} {
got := npxBin(dir, name)
if want == "" && got != "" || want != "" && !strings.HasSuffix(filepath.ToSlash(got), name+"/"+want) {
t.Errorf("%s: bin %q, want %q", name, got, want)
}
}
}
+6 -1
View File
@@ -154,7 +154,8 @@ func Sync() (*Result, error) {
return nil
}
// the agents are found under the lock, as a change finds them
if err := step(func(l *Library) { all = Targets(); gone = l.held(all) }); err != nil {
var npxDirs map[string]bool
if err := step(func(l *Library) { all = Targets(); gone = l.held(all); npxDirs = l.npxDirs() }); err != nil {
return nil, err
}
for _, f := range syncSteps(all, gone, b, res) {
@@ -171,6 +172,7 @@ func Sync() (*Result, error) {
if len(res.dropped) > 0 {
ending(res.dropped)
}
npxPrune(npxDirs)
return res, nil
}
@@ -245,6 +247,9 @@ func (l *Library) syncMCP(t *Target, b *backups, res *Result) {
continue
}
s, _ = t.MCP.side(s)
if !t.MCP.WSL {
s = npxDirect(s)
}
s = wroteStartup(s, a.Startup[s.Name])
old := entries[s.Name]
if err := t.MCP.foreign(old); err != nil {