The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
mcpconnect: fix three disconnect/replace edge cases
Claude3ffb6bfc5836
diff --git a/cli/beacon/internal/mcpconnect/cli_url_test.go b/cli/beacon/internal/mcpconnect/cli_url_test.goindex a1dce574..b58b1db9 100644--- a/cli/beacon/internal/mcpconnect/cli_url_test.go+++ b/cli/beacon/internal/mcpconnect/cli_url_test.go@@ -226,3 +226,36 @@ func TestCheckURLFailures(t *testing.T) {}}}++// Regression: when replacing through the CLI, a failed `mcp add` must put back the entry the+// preceding `mcp remove` took out.+func TestClaudeCLIFailedAddRestoresTheEntryItRemoved(t *testing.T) {+ home := isolate(t)+ opts, fake := claudeOptions(t, home)+ opts.Force = true+ original := `{"numStartups": 3, "mcpServers": {"beacon-managed": {"type": "http", "url": "https://elsewhere.example", "headers": {"X-Team": "a"}}}}`+ writeFile(t, fake.path, original)+ run := fake.run+ opts.Run = func(ctx context.Context, name string, args ...string) ([]byte, error) {+ if len(args) > 1 && args[1] == "add" {+ return []byte("boom"), errors.New("exit status 1")+ }+ return run(ctx, name, args...)+ }+ plan, _ := Plan(opts, []Target{mustTarget(t, "claude")})+ applied, _ := Apply(context.Background(), opts, plan)+ if applied[0].Err == nil {+ t.Fatal("a failed add was reported as success")+ }+ st, err := inspect(mustTarget(t, "claude"), fake.path)+ if err != nil || !st.exists || st.url != "https://elsewhere.example" {+ t.Fatalf("the removed entry was not put back: %+v %v\n%s", st.entry, err, readFile(t, fake.path))+ }+ if headers, _ := st.entry["headers"].(map[string]any); headers["X-Team"] != "a" {+ t.Fatalf("the restored entry lost fields: %+v", st.entry)+ }+ got, _ := decodeJSONC(readFile(t, fake.path))+ if got["numStartups"] == nil {+ t.Fatal("restoring the entry dropped other state")+ }+}diff --git a/cli/beacon/internal/mcpconnect/engine.go b/cli/beacon/internal/mcpconnect/engine.goindex 113bd208..c875e184 100644--- a/cli/beacon/internal/mcpconnect/engine.go+++ b/cli/beacon/internal/mcpconnect/engine.go@@ -358,6 +358,10 @@ func applyOne(ctx context.Context, opts Options, m *manifest, it Item) (Record,if recorded && it.Action == ActionUpdate {rec.CreatedParents = max(rec.CreatedParents, prev.CreatedParents)rec.CreatedInputs = rec.CreatedInputs || (prev.CreatedInputs && opts.TokenEnv != "")+ // This backup still holds Beacon's previous entry, so it is not a state disconnect+ // may restore: that would put the old entry back and forget it. Keep the backup for+ // the person, but leave no baseline, so disconnect splices the entry out instead.+ rec.BeforeSHA256 = ""}}if err := cf.write(updated); err != nil {@@ -454,6 +458,14 @@ func verifyDisconnect(t Target, before, after string, rec Record) error {return err}deletePath(b, t.container, ServerName, rec.CreatedParents)+ if t.format == formatTOML {+ // [mcp_servers] exists in TOML only through its subtables, so once Beacon's table is+ // stripped a document with no other server has no mcp_servers key at all. An explicit+ // empty [mcp_servers] header survives the strip. Either way an empty table and a missing+ // one are the same configuration.+ dropEmptyTable(b, t.container[0])+ dropEmptyTable(a, t.container[0])+ }if t.vscodeInputs && rec.Auth == AuthTokenEnv {dropBeaconInputs(b)if list, ok := b["inputs"].([]any); ok && len(list) == 0 && rec.CreatedInputs {@@ -466,6 +478,12 @@ func verifyDisconnect(t Target, before, after string, rec Record) error {return nil}+func dropEmptyTable(doc map[string]any, key string) {+ if m, ok := doc[key].(map[string]any); ok && len(m) == 0 {+ delete(doc, key)+ }+}+func parseBoth(t Target, before, after string) (map[string]any, map[string]any, error) {parse := decodeJSONCif t.format == formatTOML {@@ -551,29 +569,73 @@ func applyCLI(ctx context.Context, opts Options, it Item, st state, rec Record)return Record{}, fmt.Errorf("could not back up %s: %w", it.Path, err)}rec.Backup = backup+ // Replacing through the CLI is remove-then-add. Keep the removed entry's exact text so a+ // failed add can put it back rather than leave the harness with no server at all.+ var removed stringif st.exists {+ removed, _ = rawMember(st.file.text, it.Target.container, ServerName)if out, err := opts.run(ctx, it.cliPath, "mcp", "remove", ServerName, "--scope", "user"); err != nil {return Record{}, fmt.Errorf("`%s mcp remove` failed: %v: %s", it.Target.cli, err, strings.TrimSpace(string(out)))}}+ fail := func(err error) (Record, error) {+ if removed != "" {+ if restoreErr := restoreMember(it.Target, it.Path, removed); restoreErr != nil {+ return Record{}, fmt.Errorf("%w; putting back the previous %s entry also failed (%v); it is in the backup %s", err, ServerName, restoreErr, backup)+ }+ return Record{}, fmt.Errorf("%w; the previous %s entry was put back", err, ServerName)+ }+ return Record{}, err+ }args := []string{"mcp", "add", "--transport", "http", "--scope", "user", ServerName, opts.URL}if opts.TokenEnv != "" {args = append(args, "--header", "Authorization: Bearer ${"+opts.TokenEnv+"}")}if out, err := opts.run(ctx, it.cliPath, args...); err != nil {- return Record{}, fmt.Errorf("`%s mcp add` failed: %v: %s", it.Target.cli, err, strings.TrimSpace(string(out)))+ return fail(fmt.Errorf("`%s mcp add` failed: %v: %s", it.Target.cli, err, strings.TrimSpace(string(out))))}after, err := inspect(it.Target, it.Path)if err != nil {- return Record{}, err+ return fail(err)}want := normalizeJSON(it.Target.entry(opts.URL, opts.TokenEnv))if !after.exists || !reflect.DeepEqual(normalizeJSON(after.entry), want) {- return Record{}, fmt.Errorf("`%s mcp add` ran, but %s does not hold the expected %s entry", it.Target.cli, it.Path, ServerName)+ return fail(fmt.Errorf("`%s mcp add` ran, but %s does not hold the expected %s entry", it.Target.cli, it.Path, ServerName))}return rec, nil}+// restoreMember puts an entry's original JSON text back under the server name, when the name is+// free, with the same parse-back check as every other write.+func restoreMember(t Target, path, raw string) error {+ st, err := inspect(t, path)+ if err != nil {+ return err+ }+ if st.exists {+ return fmt.Errorf("%s already holds a %s entry", path, ServerName)+ }+ updated, _, err := insertJSONMember(st.file.text, t.container, ServerName, rawJSON(raw))+ if err != nil {+ return err+ }+ b, a, err := parseBoth(t, st.file.text, updated)+ if err != nil {+ return err+ }+ var value any+ decoder := json.NewDecoder(strings.NewReader(raw))+ decoder.UseNumber()+ if err := decoder.Decode(&value); err != nil {+ return err+ }+ setPath(b, t.container, ServerName, value)+ if !reflect.DeepEqual(normalizeValue(b), normalizeValue(a)) {+ return errors.New("the restore would have changed more than the entry")+ }+ return st.file.write(updated)+}+// Disconnect removes the entries Beacon wrote for the targets, and nothing else.func Disconnect(ctx context.Context, opts Options, targets []Target) ([]Item, error) {m, err := loadManifest(opts.Home)diff --git a/cli/beacon/internal/mcpconnect/harness_test.go b/cli/beacon/internal/mcpconnect/harness_test.goindex 29ff564f..20ad1c31 100644--- a/cli/beacon/internal/mcpconnect/harness_test.go+++ b/cli/beacon/internal/mcpconnect/harness_test.go@@ -960,3 +960,57 @@ func TestNextStepsNameTheServerOrTheVariable(t *testing.T) {}}}++// Regression: a Codex config whose only MCP server is Beacon's has no [mcp_servers] table left+// once Beacon's is stripped, which the disconnect check must accept.+func TestCodexDisconnectAfterEditWhenBeaconsIsTheOnlyServer(t *testing.T) {+ home := isolate(t)+ target := mustTarget(t, "codex")+ path := targetPath(t, target, home)+ writeFile(t, path, "model = \"o3\"\n")+ connect(t, fileOptions(home), target)+ writeFile(t, path, "# edited later\n"+readFile(t, path))+ if got := disconnect(t, fileOptions(home), target); got.Action != ActionRemove {+ t.Fatalf("action = %s (%s)", got.Action, got.Detail)+ }+ if got := readFile(t, path); got != "# edited later\nmodel = \"o3\"\n" {+ t.Fatalf("got %q", got)+ }+}++// Regression: an update made after the user edited the file must not leave a backup that holds+// Beacon's previous entry as the thing disconnect restores.+func TestDisconnectAfterUpdateOnAnEditedFileRemovesTheEntry(t *testing.T) {+ for _, name := range []string{"cursor", "codex"} {+ t.Run(name, func(t *testing.T) {+ home := isolate(t)+ target := mustTarget(t, name)+ path := targetPath(t, target, home)+ original := harnessFixtures[fixtureIndex(name)].existing+ writeFile(t, path, original)+ connect(t, fileOptions(home), target)+ edit := strings.Replace(readFile(t, path), original[:1], original[:1]+userEdit(target), 1)+ writeFile(t, path, edit)+ tokenOpts := fileOptions(home)+ tokenOpts.TokenEnv = "BEACON_MCP_TOKEN"+ if got := connect(t, tokenOpts, target); got.Action != ActionUpdate {+ t.Fatalf("action = %s", got.Action)+ }+ disconnect(t, fileOptions(home), target)+ want := strings.Replace(original, original[:1], original[:1]+userEdit(target), 1)+ if got := readFile(t, path); got != want {+ t.Fatalf("got:\n%s\nwant:\n%s", got, want)+ }+ })+ }+}++func fixtureIndex(name string) int {+ target, _ := Lookup(name)+ for i, fx := range harnessFixtures {+ if fx.name == target.Name {+ return i+ }+ }+ panic(name)+}diff --git a/cli/beacon/internal/mcpconnect/jsonedit.go b/cli/beacon/internal/mcpconnect/jsonedit.goindex a94bd892..5bcb610f 100644--- a/cli/beacon/internal/mcpconnect/jsonedit.go+++ b/cli/beacon/internal/mcpconnect/jsonedit.go@@ -16,6 +16,9 @@ type field struct {Value any}+// rawJSON is a value inserted exactly as written, such as an entry's original text.+type rawJSON string+// jsonStyle is the formatting an edit copies from the document it goes into.type jsonStyle struct {unit string // one level of indentation@@ -65,6 +68,8 @@ func jsonString(value string) string {// indentation, or on one line when the surrounding object is written on one line.func renderJSON(value any, style jsonStyle, depth int, compact bool, sep string) string {switch v := value.(type) {+ case rawJSON:+ return string(v)case ordered:if len(v) == 0 {return "{}"@@ -279,6 +284,25 @@ func insertJSONMember(text string, path []string, key string, value any) (updatereturn insertItem(text, parent, items, rendered, style), len(missing), nil}+// rawMember returns the original text of path.key's value, as JSON with comments stripped.+func rawMember(text string, path []string, key string) (string, bool) {+ root, err := parseJSONC(text)+ if err != nil || root == nil || root.kind != jsonObject {+ return "", false+ }+ chain, err := lookupObject(root, path)+ if err != nil || len(chain) != len(path)+1 {+ return "", false+ }+ _, value := chain[len(chain)-1].member(key)+ if value == nil {+ return "", false+ }+ var buf bytes.Buffer+ writeStandardJSON(&buf, text, value)+ return buf.String(), true+}+// removeJSONMember returns text without path.key. prune is how many of the innermost path objects// Beacon created; each of those is removed too when the removal leaves it empty.func removeJSONMember(text string, path []string, key string, prune int) (string, error) {