Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pkgs/mcpx/docs/parity.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ that reaches none says why: those are decisions, not gaps.
| `completion` | – | Text about the binary, produced by the binary. |
| `config` | – | Reads the configuration files on the caller's search path; `settings` is the running daemon's view. |
| `daemon` | – | Starts a daemon, which a daemon's own API cannot do. |
| `daemons` | – | Reads every daemon's info file on this machine; one daemon cannot see the others. |
| `daemons` | – | Reads every daemon's info file on this machine; one daemon cannot see the others. Daemons with their own state directory mirror their record into the default one, and records whose process is gone are pruned. |
| `dashboard` | `dashboard` | |
| `diagnose` | `diagnose` | |
| `doctor` | – | Checks this machine: binaries on PATH, permissions, configuration files. |
Expand Down
47 changes: 41 additions & 6 deletions pkgs/mcpx/internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ type App struct {
machineOutput bool
// inlineStop shuts down an in-process daemon when the command ends.
inlineStop func()
// warnedPathsConfig records that the paths.config file-entry warning
// has been shown, so adoptSettings does not repeat it per command.
warnedPathsConfig bool
// connected records that the ladder has been walked for this command.
connected bool
// ladder is how the connection was made, for doctor and --json output.
Expand Down Expand Up @@ -1531,17 +1534,48 @@ func (a *App) CmdStop(ctx context.Context, args []string) error {
return nil
}

// daemonListing pairs a daemon record with the state directory it was
// found in, so the caller can build a client for exactly that daemon.
type daemonListing struct {
paths daemon.Paths
info daemon.Info
}

// allDaemons returns every daemon record on this machine: the caller's
// state directory plus the default one, where daemons with a state
// directory of their own mirror their records (#278). Stale records --
// the process is gone, so nothing is listening -- are pruned from disk
// and left out. Records are deduped by socket, since a mirrored record
// and its primary describe the same daemon.
func (a *App) allDaemons() []daemonListing {
var out []daemonListing
seen := map[string]bool{}
for _, dir := range daemon.DaemonSearchDirs(a.Paths.State) {
p := daemon.Paths{State: dir}
p.PruneStale()
for _, info := range p.ListDaemons() {
if seen[info.Socket] {
continue
}
seen[info.Socket] = true
out = append(out, daemonListing{paths: p, info: info})
}
}
return out
}

// stopAll shuts down every daemon recorded in the state directory. Each
// config gets its own daemon, so this is the way to clear them all after
// working across many repos.
func (a *App) stopAll(ctx context.Context) error {
infos := a.Paths.ListDaemons()
if len(infos) == 0 {
listings := a.allDaemons()
if len(listings) == 0 {
fmt.Println("no daemons running")
return nil
}
stopped := 0
for _, info := range infos {
for _, listing := range listings {
info := listing.info
p := a.Paths
p.Socket = info.Socket
c := NewClient(p, info.ConfigPath)
Expand Down Expand Up @@ -1591,16 +1625,17 @@ func waitUntilStarted(ctx context.Context, c *Client) error {

// CmdDaemons lists every daemon this user has running.
func (a *App) CmdDaemons(ctx context.Context, args []string) error {
infos := a.Paths.ListDaemons()
listings := a.allDaemons()
type row struct {
PID int `json:"pid"`
Config string `json:"config"`
Running bool `json:"running"`
Started string `json:"startedAt"`
}
var rows []row
for _, info := range infos {
p := a.Paths
for _, listing := range listings {
info := listing.info
p := listing.paths
p.Socket = info.Socket
c := NewClient(p, info.ConfigPath)
rows = append(rows, row{
Expand Down
6 changes: 4 additions & 2 deletions pkgs/mcpx/internal/cli/manual.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func handCommands() []Command {
Local: "Manages embedded agent skills.",
Usage: "[list|install] [--agent <name>] [--to <dir>]",
Summary: "list or install embedded mcpx agent skills",
Detail: "Lists available agent skills embedded with mcpx or installs them into the target agent configuration.",
Detail: "Lists available agent skills embedded with mcpx or installs them into the target agent configuration.",
},
{
Name: "recipes", Group: "running",
Expand Down Expand Up @@ -237,7 +237,9 @@ func handCommands() []Command {
},
{
Name: "daemons", Group: "daemon",
Local: "Reads every daemon's info file on this machine; one daemon cannot see the others.",
Local: "Reads every daemon's info file on this machine; one daemon cannot see the others. " +
"Daemons with their own state directory mirror their record into the default one, " +
"and records whose process is gone are pruned.",
Summary: "list every mcpx daemon on this machine",
},
{
Expand Down
26 changes: 26 additions & 0 deletions pkgs/mcpx/internal/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,32 @@ func (a *App) adoptSettings() {
} else if dir := set.String("paths.cache"); dir != "" {
a.Paths = daemon.PathsAt(a.Paths.State, dir)
}
a.warnPathsConfigFile(set)
}

// warnPathsConfigFile warns when a paths.config entry names a file.
//
// The entries are directories that are searched for configuration files,
// so pointing one at a file -- a natural reading of --paths-config -- is
// silently ignored and the default configuration loads instead (#278).
// Naming the file directly is what MCPX_CONFIG and --config are for, so
// say so rather than leaving the user to debug a configuration that was
// never read.
func (a *App) warnPathsConfigFile(set *settings.Set) {
if a.warnedPathsConfig {
return
}
for _, entry := range set.List("paths.config") {
if st, err := os.Stat(entry); err == nil && !st.IsDir() {
fmt.Fprintf(os.Stderr,
"mcpx: warning: paths.config entry %q is a file; entries are "+
"directories searched for config files, so it is ignored. "+
"To use that file directly, pass --config %s or set MCPX_CONFIG.\n",
entry, entry)
a.warnedPathsConfig = true
return
}
}
}

// adoptSpec installs the MCP revision policy (spec.precedence, spec.first,
Expand Down
120 changes: 119 additions & 1 deletion pkgs/mcpx/internal/daemon/paths.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
)

// Paths resolves the on-disk locations mcpx uses.
Expand Down Expand Up @@ -225,6 +227,104 @@ func ContentFingerprint(paths []string) string {
return hex.EncodeToString(h.Sum(nil))[:12]
}

// DefaultStateDir is the state directory a daemon uses when nobody asked
// for another one: XDG_STATE_HOME/mcpx, or ~/.local/state/mcpx. It ignores
// MCPX_STATE_DIR and paths.state on purpose -- it is the one location every
// invocation can compute, which is what makes it usable as the place custom
// state directories mirror their daemon records into (#278).
func DefaultStateDir() string {
home, _ := os.UserHomeDir()
return firstNonEmpty(
envJoin("XDG_STATE_HOME", "mcpx"),
filepath.Join(home, ".local", "state", "mcpx"),
)
}

// DaemonSearchDirs is where `mcpx daemons` looks for daemon records: the
// caller's own state directory, plus the default one. A daemon started
// with its own state directory mirrors its record into the default
// directory (see WriteInfo), so the second entry is what makes the listing
// cover the whole machine rather than only the caller's directory.
func DaemonSearchDirs(primary string) []string {
out := []string{primary}
if d := DefaultStateDir(); d != "" && d != primary {
out = append(out, d)
}
return out
}

// ProcessAlive reports whether pid names a process that still exists.
// Signal 0 probes without delivering anything; EPERM means the process is
// there but owned by somebody else, which is still alive.
func ProcessAlive(pid int) bool {
if pid <= 0 {
return false
}
proc, err := os.FindProcess(pid)
if err != nil {
return false
}
err = proc.Signal(syscall.Signal(0))
return err == nil || errors.Is(err, syscall.EPERM)
}

// PruneStale removes this state directory's daemon records whose process
// is gone, and returns what it removed. A daemon that exits cleanly
// removes its own record; one that is killed or crashes cannot, and
// without pruning its record is listed forever (#278). Records with no
// PID recorded are kept: there is nothing to check them against.
func (p Paths) PruneStale() []Info {
entries, err := os.ReadDir(p.State)
if err != nil {
return nil
}
var out []Info
for _, e := range entries {
name := e.Name()
if !strings.HasPrefix(name, "daemon") || !strings.HasSuffix(name, ".json") {
continue
}
path := filepath.Join(p.State, name)
b, err := os.ReadFile(path)
if err != nil {
continue
}
var i Info
if json.Unmarshal(b, &i) != nil || i.PID == 0 || ProcessAlive(i.PID) {
continue
}
if err := os.Remove(path); err == nil {
out = append(out, i)
}
}
return out
}

// mirrorInfoPath is where a daemon in a custom state directory also
// publishes its record: the default state directory, under a name keyed
// by its own directory so two custom directories cannot collide and a
// custom record cannot shadow the default directory's own daemon for the
// same configuration. Empty when this directory is the default one.
func (p Paths) mirrorInfoPath() string {
def := DefaultStateDir()
if def == "" || p.State == "" || p.State == def || p.Info == "" {
return ""
}
sum := sha256.Sum256([]byte(p.State))
return filepath.Join(def, "daemon-x"+hex.EncodeToString(sum[:])[:12]+"-"+filepath.Base(p.Info))
}

// RemoveInfo removes the daemon record, including its mirror in the
// default state directory when there is one.
func (p Paths) RemoveInfo() {
if p.Info != "" {
_ = os.Remove(p.Info)
}
if m := p.mirrorInfoPath(); m != "" {
_ = os.Remove(m)
}
}

// ListDaemons returns the info records of every daemon in this state dir.
func (p Paths) ListDaemons() []Info {
entries, err := os.ReadDir(p.State)
Expand Down Expand Up @@ -281,6 +381,13 @@ type Info struct {
}

// WriteInfo publishes the daemon record atomically.
//
// A daemon in a custom state directory also mirrors the record into the
// default state directory (#278): `mcpx daemons` promises every daemon on
// the machine, and a listing that only reads the caller's own directory
// can never see it. The mirror is best-effort -- the primary record is
// authoritative, and a daemon must not fail to start because a listing
// convenience could not be written.
func (p Paths) WriteInfo(i Info) error {
b, err := json.MarshalIndent(i, "", " ")
if err != nil {
Expand All @@ -290,7 +397,18 @@ func (p Paths) WriteInfo(i Info) error {
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
return os.Rename(tmp, p.Info)
if err := os.Rename(tmp, p.Info); err != nil {
return err
}
if m := p.mirrorInfoPath(); m != "" {
if err := os.MkdirAll(filepath.Dir(m), 0o700); err == nil {
mtmp := m + ".tmp"
if os.WriteFile(mtmp, b, 0o600) == nil {
_ = os.Rename(mtmp, m)
}
}
}
return nil
}

// ReadInfo loads the daemon record, if any.
Expand Down
Loading
Loading