From bcf9151591884c052bc86860ea8236ffa153311c Mon Sep 17 00:00:00 2001 From: "Muse (repo queue worker lane D)" Date: Thu, 29 Oct 2026 19:27:50 -0500 Subject: [PATCH 1/2] mcpx: paths.config governs the config chain (two-pass, #1842) Approach C from issue #1842: config.ResolveChainFrom resolves the chain in two passes. Discovery walks the default locations seeded by MCPX_PATHS_CONFIG / --paths-config (global flag captured in main like --config) and reads only paths.config, honouring the null splice; the load pass resolves that list, each file governing the chain farther than itself. A cycle is refused by identity naming the closing path; a paths.config found only in pass 2 is reported via ChainInfo.Divergent and mcpx config --sources (which now shows both passes distinctly), never applied. MCPX_CONFIG bypasses both passes. LoadFrom and the settings file layer both consume the resolved chain. consumed_test allowlist comment and docs (declared-but-unread.md, configuration.md) truthed up. warnPathsConfigFile now warns on entries naming nothing that exists, since file entries mean exactly that file now. --- pkgs/mcpx/cmd/mcpx/main.go | 10 + pkgs/mcpx/docs/configuration.md | 11 + pkgs/mcpx/docs/declared-but-unread.md | 13 +- pkgs/mcpx/internal/cli/root.go | 51 ++- pkgs/mcpx/internal/cli/settings.go | 22 +- pkgs/mcpx/internal/config/chain.go | 438 +++++++++++++++++++ pkgs/mcpx/internal/config/chain_test.go | 204 +++++++++ pkgs/mcpx/internal/config/config.go | 14 +- pkgs/mcpx/internal/settings/consumed_test.go | 5 +- 9 files changed, 739 insertions(+), 29 deletions(-) create mode 100644 pkgs/mcpx/internal/config/chain.go create mode 100644 pkgs/mcpx/internal/config/chain_test.go diff --git a/pkgs/mcpx/cmd/mcpx/main.go b/pkgs/mcpx/cmd/mcpx/main.go index f6a8d08d5c..a9a810d667 100644 --- a/pkgs/mcpx/cmd/mcpx/main.go +++ b/pkgs/mcpx/cmd/mcpx/main.go @@ -12,6 +12,7 @@ import ( "syscall" "github.com/dezren39/mcpx/internal/cli" + "github.com/dezren39/mcpx/internal/config" "github.com/dezren39/mcpx/internal/daemon" ) @@ -93,6 +94,15 @@ func main() { case strings.HasPrefix(args[0], "--config="): app.ConfigPath = strings.TrimPrefix(args[0], "--config=") args = args[1:] + case args[0] == "--paths-config" && len(args) > 1: + // A bootstrap flag like --config: it decides which files + // the settings are read from, so it is captured here, + // before any settings exist (issue #1842). + config.SetPathsConfigSeed(splitList(args[1])) + args = args[2:] + case strings.HasPrefix(args[0], "--paths-config="): + config.SetPathsConfigSeed(splitList(strings.TrimPrefix(args[0], "--paths-config="))) + args = args[1:] case args[0] == "--version" || args[0] == "-v": fmt.Println("mcpx", version) return diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index 72328fb148..dd2b11ac6c 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -53,6 +53,17 @@ Lowest to highest: what it displaced. "Why is this not what my config says" is the most common configuration question there is, and the answer is always in that list. +The search path itself is decided before any of those layers exist, in two +passes. The discovery pass walks the default locations, seeded by +`MCPX_PATHS_CONFIG` / `--paths-config`, and reads only `paths.config`. The +load pass resolves that list and loads everything on it, nearest last: a +file's `paths.config` governs the rest of the chain from that point, a null +entry stands for the locations the default walk provided, and a list with +no null replaces the farther remainder. A `paths.config` found only in the +load pass is reported by `mcpx config --sources`, not applied, and a cycle +is refused naming the path that closed it. `MCPX_CONFIG` bypasses both +passes and loads exactly one file. + Two spellings of one setting at the same level is an error rather than a race: `--log-level` and `--logging-level` together, or two variables that mean the same thing with different values. The environment has no order, so there is diff --git a/pkgs/mcpx/docs/declared-but-unread.md b/pkgs/mcpx/docs/declared-but-unread.md index ab4a339a02..2ddd48fb35 100644 --- a/pkgs/mcpx/docs/declared-but-unread.md +++ b/pkgs/mcpx/docs/declared-but-unread.md @@ -97,10 +97,15 @@ describe a knob nobody wired. ### Left open -`paths.config` is circular by construction (#5): the config search path is what -produces the settings, so the settings cannot decide it. It is declared so that -`mcpx config --schema` names the thing, and `config.SearchPath` reads -`MCPX_PATHS_CONFIG` directly. It is the only entry on the allowlist. +`paths.config` was circular by construction (#5): the config search path is +what produces the settings, so the settings cannot decide it. It is no longer +left open. `config.ResolveChainFrom` resolves the chain in two passes +(issue #1842): a discovery pass over the default locations, seeded by +`MCPX_PATHS_CONFIG` / `--paths-config`, reads only `paths.config`; the load +pass then resolves that list, nearest last. A `paths.config` found in pass 2 +that differs is reported by `mcpx config --sources`, not applied, and a cycle +is refused naming the path that closed it. `MCPX_CONFIG` bypasses both +passes. ### The inverse bug diff --git a/pkgs/mcpx/internal/cli/root.go b/pkgs/mcpx/internal/cli/root.go index 0a04665461..badf3f322a 100644 --- a/pkgs/mcpx/internal/cli/root.go +++ b/pkgs/mcpx/internal/cli/root.go @@ -208,25 +208,24 @@ func (a *App) adoptSettings() { a.warnPathsConfigFile(set) } -// warnPathsConfigFile warns when a paths.config entry names a file. +// warnPathsConfigFile warns when a paths.config entry names nothing +// that exists. // -// 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. +// Entries govern the config chain (issue #1842): a directory is +// searched with the usual spellings, and a file means exactly that +// file. An entry naming neither is the one case that silently does +// nothing, 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() { + if _, err := os.Stat(entry); err != nil { 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) + "mcpx: warning: paths.config entry %q does not exist; "+ + "it contributes nothing to the config chain.\n", + entry) a.warnedPathsConfig = true return } @@ -580,10 +579,18 @@ func (a *App) configSources(cfg *config.Config) error { From string `json:"from"` } out := struct { - Sources []string `json:"sources"` - Servers []row `json:"servers"` - Presets []presetRow `json:"presets,omitempty"` + Sources []string `json:"sources"` + Discovery []string `json:"discovery,omitempty"` + Load []string `json:"load,omitempty"` + Divergent []string `json:"divergent,omitempty"` + Servers []row `json:"servers"` + Presets []presetRow `json:"presets,omitempty"` }{Sources: cfg.Sources} + if cfg.Chain != nil { + out.Discovery = cfg.Chain.Discovery + out.Load = cfg.Chain.Load + out.Divergent = cfg.Chain.Divergent + } // A value a preset supplied is a source too, and the one least likely to // be remembered: it came from a name on the command line, not a file. for _, v := range a.Settings().All() { @@ -611,6 +618,20 @@ func (a *App) configSources(cfg *config.Config) error { } return nil } + if cfg.Chain != nil && !cfg.Chain.Bypass { + fmt.Println("Discovery pass (searched for paths.config), nearest first:") + for _, p := range out.Discovery { + fmt.Println(" " + p) + } + fmt.Println("Load pass (files the chain resolved to), nearest first:") + for _, p := range out.Load { + fmt.Println(" " + p) + } + for _, d := range out.Divergent { + fmt.Println(" ! " + d) + } + fmt.Println() + } fmt.Println("Files, nearest first:") for i, p := range out.Sources { marker := " " diff --git a/pkgs/mcpx/internal/cli/settings.go b/pkgs/mcpx/internal/cli/settings.go index b911c64e41..fe276b6104 100644 --- a/pkgs/mcpx/internal/cli/settings.go +++ b/pkgs/mcpx/internal/cli/settings.go @@ -38,7 +38,11 @@ func (a *App) Settings() *settings.Set { set := settings.NewSet(sch) // Configuration files, furthest first so the nearest ends up highest. - files := configFilesFarthestFirst(a.ConfigPath) + files, ferr := configFilesFarthestFirst(a.ConfigPath) + if ferr != nil { + a.settingsErr = ferr + return + } for i, path := range files { doc, rerr := readJSONFile(path) if rerr != nil { @@ -355,12 +359,18 @@ func ignoredKeysError(ignored []config.IgnoredKey) error { return errors.New(b.String()) } -func configFilesFarthestFirst(explicit string) []string { +func configFilesFarthestFirst(explicit string) ([]string, error) { if explicit != "" { - return []string{explicit} + return []string{explicit}, nil + } + // The settings layer reads the same chain Load merges: the two-pass + // resolution (issue #1842), so a file paths.config adds contributes + // its settings as well as its servers. + search, _, err := config.ResolveChain() + if err != nil { + return nil, err } - search := config.SearchPath() - // SearchPath is nearest-first, because that is the order a lookup wants. + // The chain is nearest-first, because that is the order a lookup wants. // Layering wants the opposite, so that the nearest file is applied last // and therefore wins. out := make([]string, 0, len(search)) @@ -369,7 +379,7 @@ func configFilesFarthestFirst(explicit string) []string { out = append(out, search[i]) } } - return out + return out, nil } func readJSONFile(path string) (map[string]any, error) { diff --git a/pkgs/mcpx/internal/config/chain.go b/pkgs/mcpx/internal/config/chain.go new file mode 100644 index 0000000000..fb002d83e1 --- /dev/null +++ b/pkgs/mcpx/internal/config/chain.go @@ -0,0 +1,438 @@ +package config + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + + "github.com/dezren39/mcpx/internal/settings" +) + +// Two-pass resolution of the config chain (issue #1842, Approach C). +// +// paths.config is declared in the settings registry, but a resolved Set +// cannot decide which files the Set itself is read from — that is the +// circularity that left the setting inert. The chain is therefore resolved +// here, in two passes with the boundary stated rather than implied: +// +// 1. Discovery pass. Walk the default locations (SearchPathFrom), seeded +// by MCPX_PATHS_CONFIG / --paths-config. Read only paths.config from +// whatever is found, honouring the null splice. +// 2. Load pass. Resolve that list and load everything on it, nearest +// last (LoadFrom merges nearest-first, which is the same order seen +// from the other end). +// +// A file's paths.config governs the rest of the chain from that point — +// the locations farther than the file that named them — not the search +// that found the file itself. A list with no null entry replaces the +// farther remainder outright; a null entry stands for that remainder, so +// entries after the null land farther than everything already there. +// +// Rules pinned by the issue: +// - A paths.config found in pass 2 that differs from pass 1 is +// reported (ChainInfo.Divergent), not silently applied. Applying it +// would mean re-running discovery with different roots, which need +// not terminate. +// - A cycle (A adds B, B adds A) is refused by identity, naming the +// path that closed it. +// - MCPX_CONFIG bypasses both passes: "this file, nothing else" has +// to stay expressible. + +// ChainInfo describes one two-pass resolution, so callers (notably +// `mcpx config --sources`) can show the passes distinctly instead of +// presenting one merged list as if it had been searched directly. +type ChainInfo struct { + // Bypass is true when MCPX_CONFIG short-circuited both passes. + Bypass bool + // Discovery lists the pass-1 locations, nearest first: the seed + // expansions followed by the default walk. + Discovery []string + // Load lists the pass-2 locations, nearest first — the chain + // LoadFrom actually merges. + Load []string + // Seeded holds the raw seed entries (environment/flag), if any. + Seeded []string + // Divergent reports paths.config declarations found in pass 2 that + // were not applied: files the load pass added declaring entries of + // their own, and declarations dropped when a nearer list replaced + // the rest of the chain. + Divergent []string +} + +var ( + seedMu sync.Mutex + flagSeed []string +) + +// SetPathsConfigSeed records the --paths-config flag value (a global +// flag, consumed in main alongside --config) as the pass-1 seed, in +// place of MCPX_PATHS_CONFIG. The flag has to be captured before any +// settings exist, for the same reason --config is: it decides which +// files the settings are read from. +func SetPathsConfigSeed(entries []string) { + seedMu.Lock() + defer seedMu.Unlock() + flagSeed = append([]string(nil), entries...) +} + +// pathsConfigSeed returns the pass-1 seed entries: the flag when given, +// otherwise MCPX_PATHS_CONFIG. Both spell the same list a config file +// holds — a JSON array, or entries split on commas and newlines — with +// null entries preserved as splice markers. +func pathsConfigSeed() []string { + seedMu.Lock() + fs := append([]string(nil), flagSeed...) + seedMu.Unlock() + if len(fs) > 0 { + return fs + } + v := strings.TrimSpace(os.Getenv("MCPX_PATHS_CONFIG")) + if v == "" { + return nil + } + if strings.HasPrefix(v, "[") { + var arr []any + if json.Unmarshal([]byte(v), &arr) == nil { + out := make([]string, 0, len(arr)) + for _, e := range arr { + if e == nil { + out = append(out, settings.NullMarker) + continue + } + out = append(out, fmt.Sprint(e)) + } + return out + } + } + fields := strings.FieldsFunc(v, func(r rune) bool { return r == ',' || r == '\n' }) + out := make([]string, 0, len(fields)) + for _, f := range fields { + if f = strings.TrimSpace(f); f != "" { + out = append(out, f) + } + } + return out +} + +// configSpellings are the candidate files one directory level +// contributes to the chain, in the order SearchPathFrom tries them. +func configSpellings(dir string) []string { + return []string{ + filepath.Join(dir, ".config", "mcpx", "config.json"), + filepath.Join(dir, ".mcpx.json"), + filepath.Join(dir, ".mcpx", "config.json"), + filepath.Join(dir, ".mcp.json"), + } +} + +// expandEntry resolves one paths.config entry to candidate chain +// locations. An entry naming an existing file means exactly that file +// (the registry's spelling); anything else is a directory, searched +// with the usual per-level spellings. Relative entries resolve against +// base — the declaring file's directory, or the working directory for +// the seed. +func expandEntry(entry, base string) []string { + p := entry + if !filepath.IsAbs(p) { + p = filepath.Join(base, p) + } + p = filepath.Clean(p) + if st, err := os.Stat(p); err == nil && !st.IsDir() { + return []string{p} + } + return configSpellings(p) +} + +// expandEntries expands a raw entry list, splitting at the null splice +// marker: entries before it land nearer than the inherited remainder, +// entries after it farther. +func expandEntries(entries []string, base string) (before, after []string, hasNull bool) { + dst := &before + for _, e := range entries { + if e == settings.NullMarker { + hasNull = true + dst = &after + continue + } + *dst = append(*dst, expandEntry(e, base)...) + } + return before, after, hasNull +} + +func expandAll(entries []string, base string) []string { + before, after, _ := expandEntries(entries, base) + return append(before, after...) +} + +// readPathsConfig reads only the paths.config key from one file, as raw +// entries with nulls preserved. ok is false when the file is absent or +// declares no paths.config. +func readPathsConfig(path string) (entries []string, ok bool, err error) { + b, rerr := os.ReadFile(path) + if rerr != nil { + if os.IsNotExist(rerr) { + return nil, false, nil + } + return nil, false, rerr + } + var doc struct { + Paths struct { + Config []any `json:"config"` + } `json:"paths"` + Flat []any `json:"paths.config"` + } + if uerr := json.Unmarshal(StripJSONC(b), &doc); uerr != nil { + return nil, false, fmt.Errorf("reading paths.config in %s: %w", path, uerr) + } + raw := doc.Paths.Config + if raw == nil { + raw = doc.Flat + } + if raw == nil { + return nil, false, nil + } + out := make([]string, 0, len(raw)) + for _, e := range raw { + if e == nil { + out = append(out, settings.NullMarker) + continue + } + s, isStr := e.(string) + if !isStr { + return nil, false, fmt.Errorf("reading paths.config in %s: entry %v is not a path string", path, e) + } + out = append(out, s) + } + return out, true, nil +} + +func chainIdentity(p string) string { + abs, err := filepath.Abs(p) + if err != nil { + abs = p + } + if resolved, err := filepath.EvalSymlinks(abs); err == nil { + abs = resolved + } + return filepath.Clean(abs) +} + +// findCycle looks for a cycle in the pass-1 "adds" graph (file -> +// chain files its paths.config expands to). It returns the file whose +// declaration closed the cycle and the cycle itself. +func findCycle(edges map[string][]string, order []string) (string, []string, bool) { + const ( + white = 0 + grey = 1 + black = 2 + ) + colour := map[string]int{} + var stack []string + var visit func(n string) ([]string, bool) + visit = func(n string) ([]string, bool) { + colour[n] = grey + stack = append(stack, n) + for _, m := range edges[n] { + switch colour[m] { + case grey: + i := 0 + for j, s := range stack { + if s == m { + i = j + break + } + } + return append(append([]string{}, stack[i:]...), m), true + case white: + if cyc, found := visit(m); found { + return cyc, true + } + } + } + stack = stack[:len(stack)-1] + colour[n] = black + return nil, false + } + for _, n := range order { + if _, isNode := edges[n]; !isNode { + continue + } + if colour[n] == white { + if cyc, found := visit(n); found { + // The closing declaration belongs to the file whose + // edge led back into the stack: the predecessor of + // the repeated node in the reported cycle. + closing := cyc[len(cyc)-2] + return closing, cyc, true + } + } + } + return "", nil, false +} + +// ResolveChain runs both passes for the process's working directory. +func ResolveChain() ([]string, *ChainInfo, error) { + wd, err := os.Getwd() + if err != nil { + wd = "" + } + return ResolveChainFrom(wd) +} + +// ResolveChainFrom is ResolveChain for a directory other than this +// process's, matching SearchPathFrom. +func ResolveChainFrom(wd string) ([]string, *ChainInfo, error) { + // MCPX_CONFIG wins outright and skips both passes. + if p := os.Getenv("MCPX_CONFIG"); p != "" { + one := []string{p} + return one, &ChainInfo{Bypass: true, Discovery: one, Load: one}, nil + } + + // Pass 1: the seed expands first (nearest), then the default walk. + info := &ChainInfo{Seeded: pathsConfigSeed()} + var chain0 []string + seen0 := map[string]bool{} + add0 := func(p string) { + if id := chainIdentity(p); !seen0[id] { + seen0[id] = true + chain0 = append(chain0, p) + } + } + for _, loc := range expandAll(info.Seeded, wd) { + add0(loc) + } + for _, loc := range SearchPathFrom(wd) { + add0(loc) + } + info.Discovery = chain0 + + inChain0 := map[string]bool{} + for _, p := range chain0 { + inChain0[chainIdentity(p)] = true + } + + // Discovery reads: only paths.config, from files that exist. + declared := map[string][]string{} + for _, f := range chain0 { + entries, ok, err := readPathsConfig(f) + if err != nil { + return nil, nil, err + } + if ok { + declared[f] = entries + } + } + + // A cycle among the discovered files is refused before any chain + // is built from it: A adds B and B adds A has no honest order. + edges := map[string][]string{} + for f, entries := range declared { + for _, loc := range expandAll(entries, filepath.Dir(f)) { + // A file naming its own location is idempotent, not a + // cycle: it is already in the chain at that point. + if chainIdentity(loc) == chainIdentity(f) { + continue + } + if inChain0[chainIdentity(loc)] { + edges[f] = append(edges[f], loc) + } + } + } + if closing, cyc, found := findCycle(edges, chain0); found { + return nil, nil, fmt.Errorf("paths.config cycle refused: %s closes the cycle (%s)", + closing, strings.Join(cyc, " -> ")) + } + + // Build the load chain nearest-first. Each discovered file's list + // governs the chain farther than itself: its locations are + // inserted immediately after it (before the null) and after the + // inherited remainder (after the null), or replace that remainder + // outright when the list has no null. + load := append([]string{}, chain0...) + applied := map[string]bool{} + indexOf := func(p string) int { + id := chainIdentity(p) + for i, q := range load { + if chainIdentity(q) == id { + return i + } + } + return -1 + } + for _, f := range chain0 { + entries, ok := declared[f] + if !ok { + continue + } + idx := indexOf(f) + if idx < 0 { + // A nearer file's list replaced the remainder and this + // file fell out of the chain; its declaration is a + // pass-2 divergence to report below, not to apply. + continue + } + before, after, hasNull := expandEntries(entries, filepath.Dir(f)) + next := make([]string, 0, len(load)+len(before)+len(after)) + next = append(next, load[:idx+1]...) + next = append(next, before...) + if hasNull { + next = append(next, load[idx+1:]...) + next = append(next, after...) + } + // Dedupe by identity, first (nearest) occurrence wins — the + // same rule SearchPathFrom applies to the default walk. + deduped := next[:0] + seen := map[string]bool{} + for _, p := range next { + if id := chainIdentity(p); !seen[id] { + seen[id] = true + deduped = append(deduped, p) + } + } + load = deduped + applied[f] = true + } + info.Load = load + + // Pass 2: re-read the load chain. A declaration that pass 1 did not + // apply — from a file pass 1 added, or one a nearer replacement + // dropped — is reported, never applied. + inLoad := map[string]bool{} + for _, p := range load { + inLoad[chainIdentity(p)] = true + } + for _, f := range load { + if applied[f] { + continue + } + entries, ok, err := readPathsConfig(f) + if err != nil { + return nil, nil, err + } + if !ok { + continue + } + var extra []string + for _, loc := range expandAll(entries, filepath.Dir(f)) { + if !inLoad[chainIdentity(loc)] { + extra = append(extra, loc) + } + } + if len(extra) > 0 { + info.Divergent = append(info.Divergent, fmt.Sprintf( + "%s declares paths.config adding %s — reported, not applied (pass 2)", + f, strings.Join(extra, ", "))) + } + } + for f := range declared { + if !applied[f] && indexOf(f) < 0 { + info.Divergent = append(info.Divergent, fmt.Sprintf( + "%s declares paths.config but a nearer file's list replaced the rest of the chain — reported, not applied (pass 2)", + f)) + } + } + return load, info, nil +} diff --git a/pkgs/mcpx/internal/config/chain_test.go b/pkgs/mcpx/internal/config/chain_test.go new file mode 100644 index 0000000000..63de6b264a --- /dev/null +++ b/pkgs/mcpx/internal/config/chain_test.go @@ -0,0 +1,204 @@ +package config_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/dezren39/mcpx/internal/config" +) + +func writeChainFile(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +// isolateChain points HOME/XDG at a scratch tree and clears the +// bootstrap variables, so the walk and the fallbacks see only the +// fixture. It returns the home directory inside the scratch tree. +func isolateChain(t *testing.T) string { + t.Helper() + root := t.TempDir() + home := filepath.Join(root, "home") + if err := os.MkdirAll(home, 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "xdg")) + t.Setenv("MCPX_CONFIG", "") + t.Setenv("MCPX_PATHS_CONFIG", "") + config.SetPathsConfigSeed(nil) + t.Cleanup(func() { config.SetPathsConfigSeed(nil) }) + return home +} + +func TestPathsConfigExtendsChain(t *testing.T) { + home := isolateChain(t) + proj := filepath.Join(home, "proj") + shared := filepath.Join(home, "shared") + writeChainFile(t, filepath.Join(proj, ".mcpx.json"), + `{"paths":{"config":["../shared", null]}, "mcpServers":{"near":{"command":"x"}}}`) + writeChainFile(t, filepath.Join(shared, ".mcpx.json"), + `{"mcpServers":{"far":{"command":"y"}}}`) + + cfg, err := config.LoadFrom("", proj) + if err != nil { + t.Fatal(err) + } + if _, ok := cfg.MCPServers["far"]; !ok { + t.Fatalf("paths.config extension did not load: sources %v", cfg.Sources) + } + if cfg.Chain == nil { + t.Fatal("load did not record the chain resolution") + } + sharedFile := filepath.Join(shared, ".mcpx.json") + inLoad, inDiscovery := false, false + for _, p := range cfg.Chain.Load { + if p == sharedFile { + inLoad = true + } + } + for _, p := range cfg.Chain.Discovery { + if p == sharedFile { + inDiscovery = true + } + } + if !inLoad { + t.Errorf("added file missing from the load pass: %v", cfg.Chain.Load) + } + if inDiscovery { + t.Errorf("added file should not appear in the discovery pass: %v", cfg.Chain.Discovery) + } + if len(cfg.Chain.Divergent) != 0 { + t.Errorf("unexpected divergence reports: %v", cfg.Chain.Divergent) + } +} + +func TestPathsConfigCycleRefused(t *testing.T) { + isolateChain(t) + root := t.TempDir() + dirA := filepath.Join(root, "a") + dirB := filepath.Join(root, "b") + writeChainFile(t, filepath.Join(dirA, ".mcpx.json"), + `{"paths":{"config":[`+quoteJSON(dirB)+`]}, "mcpServers":{"a":{"command":"x"}}}`) + writeChainFile(t, filepath.Join(dirB, ".mcpx.json"), + `{"paths":{"config":[`+quoteJSON(dirA)+`]}, "mcpServers":{"b":{"command":"y"}}}`) + t.Setenv("MCPX_PATHS_CONFIG", dirA+","+dirB) + + _, _, err := config.ResolveChainFrom(root) + if err == nil { + t.Fatal("a paths.config cycle must be refused") + } + if !strings.Contains(err.Error(), "cycle") { + t.Errorf("error should name the cycle: %v", err) + } + if !strings.Contains(err.Error(), ".mcpx.json") { + t.Errorf("error should name the path that closed the cycle: %v", err) + } +} + +func TestPathsConfigPass2DivergenceReportedNotApplied(t *testing.T) { + home := isolateChain(t) + proj := filepath.Join(home, "proj") + added := filepath.Join(home, "added") + other := filepath.Join(home, "other") + writeChainFile(t, filepath.Join(proj, ".mcpx.json"), + `{"paths":{"config":["../added", null]}, "mcpServers":{"near":{"command":"x"}}}`) + writeChainFile(t, filepath.Join(added, ".mcpx.json"), + `{"paths":{"config":["../other", null]}, "mcpServers":{"added":{"command":"y"}}}`) + writeChainFile(t, filepath.Join(other, ".mcpx.json"), + `{"mcpServers":{"other":{"command":"z"}}}`) + + cfg, err := config.LoadFrom("", proj) + if err != nil { + t.Fatal(err) + } + if _, ok := cfg.MCPServers["added"]; !ok { + t.Fatalf("pass-1 addition did not load: %v", cfg.Sources) + } + if _, ok := cfg.MCPServers["other"]; ok { + t.Errorf("pass-2 paths.config was applied; it must only be reported") + } + if len(cfg.Chain.Divergent) == 0 { + t.Errorf("pass-2 divergence was not reported: %+v", cfg.Chain) + } +} + +func TestMCPXConfigBypassesBothPasses(t *testing.T) { + home := isolateChain(t) + proj := filepath.Join(home, "proj") + single := filepath.Join(home, "single.json") + writeChainFile(t, filepath.Join(proj, ".mcpx.json"), + `{"paths":{"config":["../shared", null]}, "mcpServers":{"near":{"command":"x"}}}`) + writeChainFile(t, filepath.Join(home, "shared", ".mcpx.json"), + `{"mcpServers":{"far":{"command":"y"}}}`) + writeChainFile(t, single, `{"mcpServers":{"only":{"command":"z"}}}`) + t.Setenv("MCPX_CONFIG", single) + + cfg, err := config.LoadFrom("", proj) + if err != nil { + t.Fatal(err) + } + if len(cfg.MCPServers) != 1 { + t.Fatalf("MCPX_CONFIG should load exactly one file, got %v", cfg.Sources) + } + if _, ok := cfg.MCPServers["only"]; !ok { + t.Errorf("the MCPX_CONFIG file did not load: %v", cfg.Sources) + } + if cfg.Chain == nil || !cfg.Chain.Bypass { + t.Errorf("bypass not recorded: %+v", cfg.Chain) + } +} + +func TestPathsConfigEnvSeedExtendsDiscovery(t *testing.T) { + isolateChain(t) + root := t.TempDir() + seedDir := filepath.Join(root, "seeded") + writeChainFile(t, filepath.Join(seedDir, ".mcpx.json"), + `{"mcpServers":{"seeded":{"command":"x"}}}`) + t.Setenv("MCPX_PATHS_CONFIG", seedDir) + + cfg, err := config.LoadFrom("", root) + if err != nil { + t.Fatal(err) + } + if _, ok := cfg.MCPServers["seeded"]; !ok { + t.Errorf("env-seeded directory did not load: %v", cfg.Sources) + } + if cfg.Chain == nil || len(cfg.Chain.Seeded) != 1 { + t.Errorf("seed not recorded: %+v", cfg.Chain) + } +} + +func TestPathsConfigWithoutNullReplacesRemainder(t *testing.T) { + home := isolateChain(t) + proj := filepath.Join(home, "proj") + only := filepath.Join(home, "only") + writeChainFile(t, filepath.Join(home, ".mcpx.json"), + `{"mcpServers":{"homeSrv":{"command":"h"}}}`) + writeChainFile(t, filepath.Join(proj, ".mcpx.json"), + `{"paths":{"config":["../only"]}, "mcpServers":{"near":{"command":"x"}}}`) + writeChainFile(t, filepath.Join(only, ".mcpx.json"), + `{"mcpServers":{"onlySrv":{"command":"y"}}}`) + + cfg, err := config.LoadFrom("", proj) + if err != nil { + t.Fatal(err) + } + if _, ok := cfg.MCPServers["onlySrv"]; !ok { + t.Errorf("replacement directory did not load: %v", cfg.Sources) + } + if _, ok := cfg.MCPServers["homeSrv"]; ok { + t.Errorf("a list without null must replace the farther remainder, but the home file still loaded: %v", cfg.Sources) + } +} + +func quoteJSON(s string) string { + return `"` + strings.ReplaceAll(s, `\`, `\\`) + `"` +} diff --git a/pkgs/mcpx/internal/config/config.go b/pkgs/mcpx/internal/config/config.go index 312af9f076..61c1e49052 100644 --- a/pkgs/mcpx/internal/config/config.go +++ b/pkgs/mcpx/internal/config/config.go @@ -216,6 +216,12 @@ type Config struct { Path string `json:"-"` // Sources lists every file that contributed, nearest first. Sources []string `json:"-"` + // Chain records the two-pass resolution that produced Sources + // (issue #1842): which locations the discovery pass searched, and + // any pass-2 paths.config declarations reported rather than + // applied. Nil for an explicit --config load, which skips the + // chain entirely. + Chain *ChainInfo `json:"-"` // Origin maps a server name to the file that defined the winning entry. Origin map[string]string `json:"-"` // Ignored lists keys on server entries that mcpx does not read, with @@ -796,8 +802,12 @@ func LoadFrom(explicit, wd string) (*Config, error) { return c, nil } - merged := &Config{MCPServers: map[string]*Server{}, Origin: map[string]string{}} - for _, p := range SearchPathFrom(wd) { + chain, chainInfo, cerr := ResolveChainFrom(wd) + if cerr != nil { + return nil, cerr + } + merged := &Config{MCPServers: map[string]*Server{}, Origin: map[string]string{}, Chain: chainInfo} + for _, p := range chain { b, err := os.ReadFile(p) if err != nil { continue diff --git a/pkgs/mcpx/internal/settings/consumed_test.go b/pkgs/mcpx/internal/settings/consumed_test.go index 1da2d3abab..9319d3e56b 100644 --- a/pkgs/mcpx/internal/settings/consumed_test.go +++ b/pkgs/mcpx/internal/settings/consumed_test.go @@ -75,8 +75,9 @@ var unreadAllowed = map[string]string{ // paths.config used to be listed here as circular by construction // (#5): the search path produces the settings, so the settings cannot // decide it. It is read now -- cli.adoptSettings warns when an entry - // names a file instead of a directory (#278) -- so it no longer - // belongs on this list. Deciding the search path itself remains #5's. + // names nothing that exists, and config.ResolveChainFrom consumes + // the file-layer values to govern the chain itself in two passes + // (issue #1842) -- so it no longer belongs on this list. "paths.configFile": "a bootstrap setting: it names the file the settings are " + "read from, so config.SearchPathFrom reads MCPX_CONFIG before any Set " + "exists, and the global --config reaches App.ConfigPath the same way.", From e013229ffdb3c99f2044f8dcd4a223a5d175bb1a Mon Sep 17 00:00:00 2001 From: "Muse (repo queue worker lane D)" Date: Thu, 29 Oct 2026 19:31:12 -0500 Subject: [PATCH 2/2] mcpx: declare MCPX_PATHS_CONFIG as a bootstrap raw read (#1842) TestNoUndeclaredEnvRead caught chain.go reading MCPX_PATHS_CONFIG by name: it seeds the discovery pass before any Set exists, so it belongs on rawReadAllowed with the reason, alongside MCPX_CONFIG. Verified with -count=1 (the guard reads the tree at runtime, so a cached test result can hide this). --- pkgs/mcpx/internal/settings/consumed_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pkgs/mcpx/internal/settings/consumed_test.go b/pkgs/mcpx/internal/settings/consumed_test.go index 9319d3e56b..8b98998be0 100644 --- a/pkgs/mcpx/internal/settings/consumed_test.go +++ b/pkgs/mcpx/internal/settings/consumed_test.go @@ -163,6 +163,9 @@ var rawReadAllowed = map[string]string{ "cli/scripts.go scriptPath).", "MCPX_CONFIG": "paths.configFile names the file the settings are read " + "from, so config.SearchPathFrom cannot ask them.", + "MCPX_PATHS_CONFIG": "paths.config seeds the discovery pass that " + + "decides which files the settings are read from, so " + + "config.ResolveChainFrom cannot ask them either (issue #1842).", } // TestNoUndeclaredEnvRead is the guard facing inward, and the reason #172