Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

mcpconnect: register Beacon Managed MCP in harness configs

Claudeb3ac9965c4bd
diff --git a/cli/beacon/internal/mcpconnect/cli_url_test.go b/cli/beacon/internal/mcpconnect/cli_url_test.go
new file mode 100644
index 00000000..a1dce574
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/cli_url_test.go
@@ -0,0 +1,228 @@
+package mcpconnect
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+// fakeClaude stands in for `claude mcp add/remove --scope user`, editing ~/.claude.json the way
+// the real CLI does, and records every invocation.
+type fakeClaude struct {
+ t *testing.T
+ path string
+ calls [][]string
+ // broken makes `mcp add` succeed without writing anything.
+ broken bool
+}
+
+func (f *fakeClaude) run(_ context.Context, name string, args ...string) ([]byte, error) {
+ f.calls = append(f.calls, append([]string{name}, args...))
+ if name != "/opt/bin/claude" {
+ return nil, fmt.Errorf("unexpected binary %s", name)
+ }
+ doc := map[string]any{}
+ if data, err := os.ReadFile(f.path); err == nil {
+ _ = json.Unmarshal(data, &doc)
+ }
+ servers, _ := doc["mcpServers"].(map[string]any)
+ if servers == nil {
+ servers = map[string]any{}
+ }
+ switch {
+ case len(args) >= 3 && args[0] == "mcp" && args[1] == "add":
+ if f.broken {
+ return []byte("Added"), nil
+ }
+ entry := map[string]any{"type": "http", "url": args[7]}
+ if len(args) == 10 && args[8] == "--header" {
+ name, value, _ := strings.Cut(args[9], ": ")
+ entry["headers"] = map[string]any{name: value}
+ }
+ servers[args[6]] = entry
+ case len(args) >= 3 && args[0] == "mcp" && args[1] == "remove":
+ delete(servers, args[2])
+ default:
+ return nil, fmt.Errorf("unexpected args %v", args)
+ }
+ doc["mcpServers"] = servers
+ data, _ := json.MarshalIndent(doc, "", " ")
+ return nil, os.WriteFile(f.path, data, 0o600)
+}
+
+func claudeOptions(t *testing.T, home string) (Options, *fakeClaude) {
+ opts := fileOptions(home)
+ fake := &fakeClaude{t: t, path: filepath.Join(home, ".claude.json")}
+ opts.LookPath = func(name string) (string, error) {
+ if name == "claude" {
+ return "/opt/bin/claude", nil
+ }
+ return "", errors.New("not found")
+ }
+ opts.Run = fake.run
+ return opts, fake
+}
+
+func TestClaudeUsesItsOwnCLIWhenOnPath(t *testing.T) {
+ home := isolate(t)
+ opts, fake := claudeOptions(t, home)
+ opts.TokenEnv = "BEACON_MCP_TOKEN"
+ writeFile(t, fake.path, `{"numStartups": 3}`)
+ target := mustTarget(t, "claude")
+ item := connect(t, opts, target)
+ if item.Method != "claude CLI" {
+ t.Fatalf("method = %q", item.Method)
+ }
+ want := [][]string{{"/opt/bin/claude", "mcp", "add", "--transport", "http", "--scope", "user", ServerName, testURL, "--header", "Authorization: Bearer ${BEACON_MCP_TOKEN}"}}
+ if !reflect.DeepEqual(fake.calls, want) {
+ t.Fatalf("calls = %q\nwant %q", fake.calls, want)
+ }
+ if backups, _ := filepath.Glob(fake.path + ".beacon.*.bak"); len(backups) != 1 {
+ t.Fatalf("the CLI path did not back up ~/.claude.json first: %v", backups)
+ }
+ disconnect(t, opts, target)
+ if last := fake.calls[len(fake.calls)-1]; !reflect.DeepEqual(last, []string{"/opt/bin/claude", "mcp", "remove", ServerName, "--scope", "user"}) {
+ t.Fatalf("disconnect ran %q", last)
+ }
+ if strings.Contains(readFile(t, fake.path), ServerName) {
+ t.Fatal("the entry is still there")
+ }
+}
+
+func TestClaudeCLIThatDoesNotWriteTheEntryIsAnError(t *testing.T) {
+ home := isolate(t)
+ opts, fake := claudeOptions(t, home)
+ fake.broken = true
+ plan, _ := Plan(opts, []Target{mustTarget(t, "claude")})
+ applied, _ := Apply(context.Background(), opts, plan)
+ if applied[0].Err == nil || !strings.Contains(applied[0].Err.Error(), "does not hold") {
+ t.Fatalf("err = %v", applied[0].Err)
+ }
+ if _, err := os.Stat(manifestPath(home)); !os.IsNotExist(err) {
+ t.Fatal("a failed connect was recorded as Beacon's")
+ }
+}
+
+func TestClaudeCLIForceReplacesThroughRemoveThenAdd(t *testing.T) {
+ home := isolate(t)
+ opts, fake := claudeOptions(t, home)
+ opts.Force = true
+ writeFile(t, fake.path, `{"mcpServers": {"beacon-managed": {"type": "http", "url": "https://elsewhere.example"}}}`)
+ connect(t, opts, mustTarget(t, "claude"))
+ if len(fake.calls) != 2 || fake.calls[0][2] != "remove" || fake.calls[1][2] != "add" {
+ t.Fatalf("calls = %q", fake.calls)
+ }
+}
+
+func TestDisconnectFallsBackToTheFileWhenTheCLIIsGone(t *testing.T) {
+ home := isolate(t)
+ opts, fake := claudeOptions(t, home)
+ writeFile(t, fake.path, `{"numStartups": 3}`)
+ connect(t, opts, mustTarget(t, "claude"))
+ disconnect(t, fileOptions(home), mustTarget(t, "claude"))
+ got, _ := decodeJSONC(readFile(t, fake.path))
+ if servers, _ := got["mcpServers"].(map[string]any); servers[ServerName] != nil {
+ t.Fatal("the entry survived disconnect without the CLI")
+ }
+ if got["numStartups"] == nil {
+ t.Fatal("disconnect removed unrelated state")
+ }
+}
+
+func TestResolveURL(t *testing.T) {
+ cases := []struct {
+ flag, ingest, want string
+ derived bool
+ err error
+ }{
+ {"https://mcp.example.test/", "https://api.example.test", "https://mcp.example.test", false, nil},
+ {"", "https://api.example.test/", "https://api.example.test/mcp", true, nil},
+ {"", "", "", false, ErrNoURL},
+ }
+ for _, tc := range cases {
+ got, derived, err := ResolveURL(tc.flag, tc.ingest)
+ if got != tc.want || derived != tc.derived || !errors.Is(err, tc.err) {
+ t.Errorf("ResolveURL(%q, %q) = %q, %v, %v", tc.flag, tc.ingest, got, derived, err)
+ }
+ }
+}
+
+// metadataServer serves RFC 9728 metadata naming resource, and counts requests.
+func metadataServer(t *testing.T, resource func(base string) string) (*httptest.Server, *int32) {
+ var hits int32
+ var srv *httptest.Server
+ srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&hits, 1)
+ if r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" {
+ t.Errorf("the URL check sent credentials")
+ }
+ if r.URL.Path != "/.well-known/oauth-protected-resource" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{"resource": resource(srv.URL), "authorization_servers": []string{srv.URL}})
+ }))
+ t.Cleanup(srv.Close)
+ return srv, &hits
+}
+
+func TestCheckURLAcceptsTheAdvertisedResource(t *testing.T) {
+ srv, hits := metadataServer(t, func(base string) string { return base + "/mcp" })
+ got, err := CheckURL(context.Background(), srv.Client(), srv.URL+"/mcp", false)
+ if err != nil || got != srv.URL+"/mcp" {
+ t.Fatalf("got %q, %v", got, err)
+ }
+ if *hits != 1 {
+ t.Fatalf("the check made %d requests, want 1", *hits)
+ }
+}
+
+func TestCheckURLRejectsAnExplicitURLTheServerDoesNotName(t *testing.T) {
+ srv, _ := metadataServer(t, func(base string) string { return base + "/mcp" })
+ _, err := CheckURL(context.Background(), srv.Client(), srv.URL+"/other", false)
+ if err == nil || !strings.Contains(err.Error(), "--url "+srv.URL+"/mcp") {
+ t.Fatalf("err = %v", err)
+ }
+}
+
+func TestCheckURLAdoptsTheCanonicalURLForADerivedOne(t *testing.T) {
+ // The backend serves MCP on its own host and names it; the ingest host's metadata names it too.
+ canonical, _ := metadataServer(t, func(base string) string { return base })
+ ingest, _ := metadataServer(t, func(string) string { return canonical.URL })
+ got, err := CheckURL(context.Background(), http.DefaultClient, ingest.URL+"/mcp", true)
+ if err != nil || got != canonical.URL {
+ t.Fatalf("got %q, %v; want %q", got, err, canonical.URL)
+ }
+}
+
+func TestCheckURLFailures(t *testing.T) {
+ redirect := httptest.NewServer(http.RedirectHandler("https://example.invalid/", http.StatusFound))
+ t.Cleanup(redirect.Close)
+ notJSON := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "<html>") }))
+ t.Cleanup(notJSON.Close)
+ noResource := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"x": 1}`) }))
+ t.Cleanup(noResource.Close)
+ insecure, _ := metadataServer(t, func(string) string { return "http://mcp.example.test" })
+ for name, url := range map[string]string{
+ "plain http to a remote host": "http://mcp.example.test/mcp",
+ "not a url": "https://",
+ "redirect is not followed": redirect.URL + "/mcp",
+ "not JSON": notJSON.URL + "/mcp",
+ "no resource": noResource.URL + "/mcp",
+ "insecure resource": insecure.URL + "/mcp",
+ } {
+ if _, err := CheckURL(context.Background(), http.DefaultClient, url, true); err == nil {
+ t.Errorf("%s: %s passed the check", name, url)
+ }
+ }
+}
diff --git a/cli/beacon/internal/mcpconnect/engine.go b/cli/beacon/internal/mcpconnect/engine.go
new file mode 100644
index 00000000..113bd208
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/engine.go
@@ -0,0 +1,813 @@
+package mcpconnect
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "reflect"
+ "strings"
+ "time"
+)
+
+// Action is what connect will do, or did, for one target.
+type Action string
+
+const (
+ ActionAdd Action = "add" // no entry yet; Beacon adds one
+ ActionUpdate Action = "update" // Beacon's own entry, with a different URL or auth mode
+ ActionPresent Action = "present" // already configured as asked; nothing to do
+ ActionConflict Action = "conflict" // an entry Beacon did not write, or with another URL; left alone
+ ActionReplace Action = "replace" // a conflict that --force overwrites
+ ActionManual Action = "manual" // Beacon writes nothing; steps are printed
+ ActionSkip Action = "skip" // cannot be handled; Detail says why
+ ActionRemove Action = "remove" // disconnect: Beacon's entry is removed
+ ActionAbsent Action = "absent" // disconnect: nothing of Beacon's is there
+)
+
+// Options configures a plan.
+type Options struct {
+ Home string
+ URL string
+ TokenEnv string // empty for OAuth
+ Force bool
+
+ // LookPath finds a harness CLI (claude); nil means exec.LookPath.
+ LookPath func(string) (string, error)
+ // Run runs a harness CLI and returns its combined output; nil runs it for real.
+ Run func(ctx context.Context, name string, args ...string) ([]byte, error)
+ Now func() time.Time
+}
+
+func (o Options) auth() AuthMode {
+ if o.TokenEnv != "" {
+ return AuthTokenEnv
+ }
+ return AuthOAuth
+}
+
+func (o Options) now() time.Time {
+ if o.Now != nil {
+ return o.Now()
+ }
+ return time.Now()
+}
+
+func (o Options) lookPath(name string) (string, error) {
+ if o.LookPath != nil {
+ return o.LookPath(name)
+ }
+ return exec.LookPath(name)
+}
+
+func (o Options) run(ctx context.Context, name string, args ...string) ([]byte, error) {
+ if o.Run != nil {
+ return o.Run(ctx, name, args...)
+ }
+ ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
+ defer cancel()
+ return exec.CommandContext(ctx, name, args...).CombinedOutput()
+}
+
+// Item is one row of a plan, and after Apply, of its result.
+type Item struct {
+ Target Target
+ Path string
+ Action Action
+ Auth AuthMode
+ Method string // "file" or "<cli> CLI"
+ Detail string
+ // ExistingURL is the URL of an entry already there.
+ ExistingURL string
+ // Err is set when applying this item failed; other items still ran.
+ Err error
+
+ cliPath string
+}
+
+// NextStep is the follow-up the person runs after connect.
+func (it Item) NextStep(opts Options) string {
+ if it.Action == ActionManual {
+ return it.Target.ManualSteps(opts.URL)
+ }
+ return it.Target.NextStep(it.Auth, opts.TokenEnv)
+}
+
+// Writes reports whether applying the item changes a file.
+func (it Item) Writes() bool {
+ return it.Action == ActionAdd || it.Action == ActionUpdate || it.Action == ActionReplace
+}
+
+// state is what a config currently holds for the server name.
+type state struct {
+ file configFile
+ exists bool // the entry exists
+ entry map[string]any // its decoded value
+ url string
+ inputOK bool // VS Code: the input Beacon's token mode needs is absent or already Beacon's
+ inputHas bool // VS Code: an input with Beacon's id exists
+}
+
+func inspect(t Target, path string) (state, error) {
+ var st state
+ cf, err := readConfig(path)
+ if err != nil {
+ return st, err
+ }
+ st.file = cf
+ st.inputOK = true
+ switch t.format {
+ case formatTOML:
+ parsed, err := parseTOML(cf.text)
+ if err != nil {
+ return st, fmt.Errorf("%s is not valid TOML (%v)", path, err)
+ }
+ if raw, ok := parsed[t.container[0]]; ok {
+ if _, isTable := raw.(map[string]any); !isTable {
+ return st, fmt.Errorf("%s: %q is not a table", path, t.container[0])
+ }
+ }
+ st.entry, st.exists = tomlTableEntry(parsed, t.container[0], ServerName)
+ default:
+ parsed, err := decodeJSONC(cf.text)
+ if err != nil {
+ return st, fmt.Errorf("%s is not valid JSON (%v)", path, err)
+ }
+ root, _ := parseJSONC(cf.text)
+ if root != nil {
+ chain, err := lookupObject(root, t.container)
+ if err != nil {
+ return st, fmt.Errorf("%s: %v", path, err)
+ }
+ if len(chain) == len(t.container)+1 && chain[len(chain)-1].memberCount(ServerName) > 1 {
+ return st, fmt.Errorf("%s: %q appears more than once", path, ServerName)
+ }
+ }
+ container := dig(parsed, t.container)
+ if raw, ok := container[ServerName]; ok {
+ st.exists = true
+ st.entry, _ = raw.(map[string]any)
+ if st.entry == nil {
+ st.entry = map[string]any{}
+ }
+ }
+ if t.vscodeInputs {
+ for _, input := range inputList(parsed) {
+ if id, _ := input["id"].(string); id == vscodeInputID {
+ st.inputHas = true
+ st.inputOK = reflect.DeepEqual(input, normalizeJSON(vscodeInput()))
+ }
+ }
+ }
+ }
+ if st.exists {
+ st.url, _ = st.entry["url"].(string)
+ }
+ return st, nil
+}
+
+func dig(doc map[string]any, path []string) map[string]any {
+ cur := doc
+ for _, seg := range path {
+ next, ok := cur[seg].(map[string]any)
+ if !ok {
+ return map[string]any{}
+ }
+ cur = next
+ }
+ return cur
+}
+
+func inputList(doc map[string]any) []map[string]any {
+ raw, _ := doc["inputs"].([]any)
+ var out []map[string]any
+ for _, r := range raw {
+ if m, ok := r.(map[string]any); ok {
+ out = append(out, m)
+ }
+ }
+ return out
+}
+
+func vscodeInput() ordered {
+ return ordered{
+ {"type", "promptString"},
+ {"id", vscodeInputID},
+ {"description", "Beacon Managed MCP token (" + TokenPage + ")"},
+ {"password", true},
+ }
+}
+
+// normalizeJSON turns an ordered value into what decodeJSONC produces for it.
+func normalizeJSON(v any) any {
+ text := renderJSON(v, jsonStyle{unit: " ", eol: "\n"}, 0, true, ":")
+ decoder := json.NewDecoder(strings.NewReader(text))
+ decoder.UseNumber()
+ var out any
+ _ = decoder.Decode(&out)
+ return out
+}
+
+func sameURL(a, b string) bool {
+ return strings.TrimRight(strings.TrimSpace(a), "/") == strings.TrimRight(strings.TrimSpace(b), "/")
+}
+
+// Plan works out what connect would do for each target without writing anything.
+func Plan(opts Options, targets []Target) ([]Item, error) {
+ m, err := loadManifest(opts.Home)
+ if err != nil {
+ return nil, err
+ }
+ var items []Item
+ for _, t := range targets {
+ items = append(items, planOne(opts, m, t))
+ }
+ return items, nil
+}
+
+func planOne(opts Options, m *manifest, t Target) Item {
+ it := Item{Target: t, Auth: opts.auth(), Method: "file"}
+ if !t.Automatic {
+ it.Action, it.Auth, it.Method = ActionManual, AuthManual, ""
+ it.Detail = "no confirmed MCP OAuth support; Beacon writes nothing"
+ return it
+ }
+ path, err := t.path(opts.Home)
+ if err != nil {
+ it.Action, it.Detail = ActionSkip, err.Error()
+ return it
+ }
+ it.Path = path
+ if t.cli != "" {
+ if cliPath, err := opts.lookPath(t.cli); err == nil {
+ it.cliPath, it.Method = cliPath, t.cli+" CLI"
+ }
+ }
+ st, err := inspect(t, path)
+ if err != nil {
+ it.Action, it.Detail = ActionSkip, err.Error()
+ return it
+ }
+ it.ExistingURL = st.url
+ rec, recorded := m.find(t.Name, path)
+ ours := recorded && st.exists && sameURL(st.url, rec.URL)
+ want := normalizeJSON(t.entry(opts.URL, opts.TokenEnv))
+ same := st.exists && reflect.DeepEqual(normalizeJSON(st.entry), want)
+ if opts.TokenEnv != "" && t.vscodeInputs && !st.inputOK && !(recorded && rec.Auth == AuthTokenEnv) {
+ if opts.Force {
+ it.Action, it.Detail = ActionReplace, "an input named "+vscodeInputID+" exists; --force replaces it"
+ } else {
+ it.Action, it.Detail = ActionConflict, "an input named "+vscodeInputID+" exists that Beacon did not write; pass --force to replace it"
+ }
+ return it
+ }
+ switch {
+ case !st.exists:
+ it.Action = ActionAdd
+ case ours && same && (!t.vscodeInputs || opts.TokenEnv == "" || st.inputHas):
+ it.Action, it.Detail = ActionPresent, "already configured by Beacon"
+ case ours:
+ it.Action, it.Detail = ActionUpdate, "Beacon's entry is updated to the requested URL and auth mode"
+ case same:
+ it.Action, it.Detail = ActionPresent, "already configured outside Beacon; left as is"
+ case opts.Force:
+ it.Action, it.Detail = ActionReplace, conflictDetail(st, opts.URL)+"; --force replaces it"
+ default:
+ it.Action, it.Detail = ActionConflict, conflictDetail(st, opts.URL)+"; left alone (pass --force to replace it)"
+ }
+ return it
+}
+
+func conflictDetail(st state, url string) string {
+ if st.url != "" && !sameURL(st.url, url) {
+ return fmt.Sprintf("an entry named %s points at %s", ServerName, st.url)
+ }
+ return fmt.Sprintf("an entry named %s exists that Beacon did not write", ServerName)
+}
+
+// Apply carries out the writing items of a plan. Each target is independent: one that fails is
+// reported in its Err and the rest still run. The manifest is saved after every write, so a later
+// failure never loses the record of an earlier success.
+func Apply(ctx context.Context, opts Options, items []Item) ([]Item, error) {
+ m, err := loadManifest(opts.Home)
+ if err != nil {
+ return nil, err
+ }
+ out := make([]Item, len(items))
+ for i, it := range items {
+ out[i] = it
+ if !it.Writes() {
+ continue
+ }
+ rec, err := applyOne(ctx, opts, m, it)
+ if err != nil {
+ out[i].Err = err
+ continue
+ }
+ m.put(rec)
+ if err := m.save(opts.Home); err != nil {
+ out[i].Err = fmt.Errorf("the entry was written, but the record of it could not be saved (%w); `beacon mcp disconnect` will not remove it", err)
+ }
+ }
+ return out, nil
+}
+
+func applyOne(ctx context.Context, opts Options, m *manifest, it Item) (Record, error) {
+ t := it.Target
+ st, err := inspect(t, it.Path)
+ if err != nil {
+ return Record{}, err
+ }
+ rec := Record{
+ Harness: t.Name, Path: it.Path, ServerName: ServerName, URL: opts.URL,
+ Auth: opts.auth(), TokenEnv: opts.TokenEnv, Method: "file", WrittenAt: opts.now().UTC(),
+ }
+ prev, recorded := m.find(t.Name, it.Path)
+ if it.cliPath != "" {
+ return applyCLI(ctx, opts, it, st, rec)
+ }
+ cf := st.file
+ updated, created, createdInputs, err := editForConnect(t, cf.text, st, opts)
+ if err != nil {
+ return Record{}, fmt.Errorf("could not edit %s: %w", it.Path, err)
+ }
+ if err := verifyConnect(t, cf.text, updated, opts); err != nil {
+ return Record{}, fmt.Errorf("%s: %w; the file was left unchanged", it.Path, err)
+ }
+ // Keep the baseline of Beacon's first write while the file holds nothing but Beacon's
+ // changes, so disconnect can still restore it byte for byte.
+ if recorded && it.Action == ActionUpdate && digest(cf.text) == prev.AfterSHA256 {
+ rec.CreatedFile, rec.CreatedParents, rec.CreatedInputs = prev.CreatedFile, prev.CreatedParents, prev.CreatedInputs
+ rec.Backup, rec.BeforeSHA256 = prev.Backup, prev.BeforeSHA256
+ if opts.TokenEnv == "" {
+ rec.CreatedInputs = false
+ }
+ if createdInputs {
+ rec.CreatedInputs = true
+ }
+ } else {
+ backup, err := cf.backup(opts.now())
+ if err != nil {
+ return Record{}, fmt.Errorf("could not back up %s: %w", it.Path, err)
+ }
+ rec.Backup, rec.BeforeSHA256 = backup, digest(cf.text)
+ rec.CreatedFile = !cf.exists
+ rec.CreatedParents, rec.CreatedInputs = created, createdInputs
+ if recorded && it.Action == ActionUpdate {
+ rec.CreatedParents = max(rec.CreatedParents, prev.CreatedParents)
+ rec.CreatedInputs = rec.CreatedInputs || (prev.CreatedInputs && opts.TokenEnv != "")
+ }
+ }
+ if err := cf.write(updated); err != nil {
+ return Record{}, fmt.Errorf("could not write %s: %w", it.Path, err)
+ }
+ rec.AfterSHA256 = digest(updated)
+ return rec, nil
+}
+
+// editForConnect returns the config text with Beacon's entry in place.
+func editForConnect(t Target, text string, st state, opts Options) (updated string, created int, createdInputs bool, err error) {
+ entry := t.entry(opts.URL, opts.TokenEnv)
+ if t.format == formatTOML {
+ eol := tomlLineEnding(text)
+ stripped := text
+ if st.exists {
+ var found bool
+ stripped, found = stripTOMLTable(text, t.container[0], ServerName)
+ if !found {
+ return "", 0, false, errors.New("the existing " + ServerName + " entry is not a [" + t.container[0] + "." + ServerName + "] table, so Beacon cannot replace it; remove it by hand")
+ }
+ stripped = endTOMLWithNewline(stripped, eol)
+ }
+ return appendTOMLBlock(stripped, tomlBlock(t.container[0], ServerName, entry, eol), eol), 0, false, nil
+ }
+ updated = text
+ if strings.TrimSpace(updated) == "" && len(t.skeleton) > 0 {
+ updated = renderJSONDocument(t.skeleton, detectJSONStyle(text))
+ }
+ if st.exists {
+ if updated, err = removeJSONMember(updated, t.container, ServerName, 0); err != nil {
+ return "", 0, false, err
+ }
+ }
+ if updated, created, err = insertJSONMember(updated, t.container, ServerName, entry); err != nil {
+ return "", 0, false, err
+ }
+ if t.vscodeInputs {
+ if st.inputHas {
+ if updated, err = removeJSONElements(updated, nil, "inputs", isBeaconInput, false); err != nil {
+ return "", 0, false, err
+ }
+ }
+ if opts.TokenEnv != "" {
+ if updated, createdInputs, err = appendJSONElement(updated, nil, "inputs", vscodeInput()); err != nil {
+ return "", 0, false, err
+ }
+ }
+ }
+ return updated, created, createdInputs, nil
+}
+
+func isBeaconInput(v any) bool {
+ m, ok := v.(map[string]any)
+ if !ok {
+ return false
+ }
+ id, _ := m["id"].(string)
+ return id == vscodeInputID
+}
+
+// verifyConnect parses the proposed text and checks that it is the original with exactly Beacon's
+// entry set: every other key, at every depth, deeply equal. It is the safety net under the text
+// splicing, the same check the Kimi Code installer runs before it replaces config.toml.
+func verifyConnect(t Target, before, after string, opts Options) error {
+ b, a, err := parseBoth(t, before, after)
+ if err != nil {
+ return err
+ }
+ if strings.TrimSpace(before) == "" && len(t.skeleton) > 0 {
+ for _, f := range t.skeleton {
+ b[f.Key] = normalizeJSON(f.Value)
+ }
+ }
+ setPath(b, t.container, ServerName, normalizeJSON(t.entry(opts.URL, opts.TokenEnv)))
+ if t.vscodeInputs {
+ dropBeaconInputs(b)
+ if opts.TokenEnv != "" {
+ list, _ := b["inputs"].([]any)
+ b["inputs"] = append(list, normalizeJSON(vscodeInput()))
+ }
+ }
+ if !reflect.DeepEqual(normalizeValue(b), normalizeValue(a)) {
+ return errors.New("Beacon's edit would have changed more than its own " + ServerName + " entry")
+ }
+ return nil
+}
+
+// verifyDisconnect checks that after is before without Beacon's entry (and, when Beacon created
+// them, the containers the entry leaves empty).
+func verifyDisconnect(t Target, before, after string, rec Record) error {
+ b, a, err := parseBoth(t, before, after)
+ if err != nil {
+ return err
+ }
+ deletePath(b, t.container, ServerName, rec.CreatedParents)
+ if t.vscodeInputs && rec.Auth == AuthTokenEnv {
+ dropBeaconInputs(b)
+ if list, ok := b["inputs"].([]any); ok && len(list) == 0 && rec.CreatedInputs {
+ delete(b, "inputs")
+ }
+ }
+ if !reflect.DeepEqual(normalizeValue(b), normalizeValue(a)) {
+ return errors.New("Beacon's edit would have changed more than its own " + ServerName + " entry")
+ }
+ return nil
+}
+
+func parseBoth(t Target, before, after string) (map[string]any, map[string]any, error) {
+ parse := decodeJSONC
+ if t.format == formatTOML {
+ parse = parseTOML
+ }
+ b, err := parse(before)
+ if err != nil {
+ return nil, nil, err
+ }
+ a, err := parse(after)
+ if err != nil {
+ return nil, nil, fmt.Errorf("Beacon's edit would not parse (%v)", err)
+ }
+ return b, a, nil
+}
+
+// normalizeValue makes TOML and JSON decodings comparable (go-toml decodes integers as int64).
+func normalizeValue(v any) any {
+ data, err := json.Marshal(v)
+ if err != nil {
+ return v
+ }
+ decoder := json.NewDecoder(strings.NewReader(string(data)))
+ decoder.UseNumber()
+ var out any
+ _ = decoder.Decode(&out)
+ return out
+}
+
+func setPath(doc map[string]any, path []string, key string, value any) {
+ cur := doc
+ for _, seg := range path {
+ next, ok := cur[seg].(map[string]any)
+ if !ok {
+ next = map[string]any{}
+ cur[seg] = next
+ }
+ cur = next
+ }
+ cur[key] = value
+}
+
+func deletePath(doc map[string]any, path []string, key string, prune int) {
+ chain := []map[string]any{doc}
+ cur := doc
+ for _, seg := range path {
+ next, ok := cur[seg].(map[string]any)
+ if !ok {
+ return
+ }
+ chain = append(chain, next)
+ cur = next
+ }
+ delete(cur, key)
+ for level := len(path); level > 0 && len(path)-level < prune; level-- {
+ if len(chain[level]) != 0 {
+ return
+ }
+ delete(chain[level-1], path[level-1])
+ }
+}
+
+func dropBeaconInputs(doc map[string]any) {
+ list, ok := doc["inputs"].([]any)
+ if !ok {
+ return
+ }
+ kept := []any{}
+ for _, v := range list {
+ if !isBeaconInput(v) {
+ kept = append(kept, v)
+ }
+ }
+ doc["inputs"] = kept
+}
+
+// applyCLI registers the server through the harness's own CLI (Claude Code), which also owns the
+// locking of a file its running sessions rewrite. The file is backed up first and read back after.
+func applyCLI(ctx context.Context, opts Options, it Item, st state, rec Record) (Record, error) {
+ rec.Method = it.Target.cli + "-cli"
+ backup, err := st.file.backup(opts.now())
+ if err != nil {
+ return Record{}, fmt.Errorf("could not back up %s: %w", it.Path, err)
+ }
+ rec.Backup = backup
+ if st.exists {
+ 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)))
+ }
+ }
+ 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)))
+ }
+ after, err := inspect(it.Target, it.Path)
+ if err != nil {
+ return Record{}, 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 rec, nil
+}
+
+// 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)
+ if err != nil {
+ return nil, err
+ }
+ var items []Item
+ for _, t := range targets {
+ if !t.Automatic {
+ continue
+ }
+ path, err := t.path(opts.Home)
+ if err != nil {
+ continue
+ }
+ it := Item{Target: t, Path: path}
+ // Records are matched by harness and file. A harness whose config moved (CODEX_HOME,
+ // CLAUDE_CONFIG_DIR) is still cleaned up at the path Beacon wrote.
+ recs := recordsFor(m, t.Name)
+ if len(recs) == 0 {
+ it.Action, it.Detail = ActionAbsent, "nothing written by Beacon"
+ items = append(items, it)
+ continue
+ }
+ for _, rec := range recs {
+ it := Item{Target: t, Path: rec.Path, Auth: rec.Auth, Method: rec.Method}
+ action, detail, err := disconnectOne(ctx, opts, t, rec)
+ it.Action, it.Detail, it.Err = action, detail, err
+ if err == nil {
+ m.drop(rec.Harness, rec.Path)
+ if saveErr := m.save(opts.Home); saveErr != nil {
+ it.Err = saveErr
+ }
+ }
+ items = append(items, it)
+ }
+ }
+ return items, nil
+}
+
+func recordsFor(m *manifest, harness string) []Record {
+ var out []Record
+ for _, r := range m.Records {
+ if r.Harness == harness {
+ out = append(out, r)
+ }
+ }
+ return out
+}
+
+func disconnectOne(ctx context.Context, opts Options, t Target, rec Record) (Action, string, error) {
+ st, err := inspect(t, rec.Path)
+ if err != nil {
+ return ActionSkip, "", err
+ }
+ if !st.exists {
+ return ActionAbsent, "the entry is already gone", nil
+ }
+ if !sameURL(st.url, rec.URL) {
+ return ActionAbsent, fmt.Sprintf("the %s entry now points at %s, not the URL Beacon wrote; left alone", ServerName, st.url), nil
+ }
+ if rec.Method == "claude-cli" {
+ cliPath, err := opts.lookPath("claude")
+ if err == nil {
+ if out, err := opts.run(ctx, cliPath, "mcp", "remove", ServerName, "--scope", "user"); err != nil {
+ return ActionSkip, "", fmt.Errorf("`claude mcp remove` failed: %v: %s", err, strings.TrimSpace(string(out)))
+ }
+ after, err := inspect(t, rec.Path)
+ if err != nil {
+ return ActionSkip, "", err
+ }
+ if after.exists {
+ return ActionSkip, "", fmt.Errorf("`claude mcp remove` ran, but %s still holds %s", rec.Path, ServerName)
+ }
+ return ActionRemove, "removed with `claude mcp remove`", nil
+ }
+ // Without the CLI, fall through to editing the file directly.
+ }
+ cf := st.file
+ // Nothing has touched the file since Beacon wrote it: put back the exact bytes.
+ if rec.AfterSHA256 != "" && digest(cf.text) == rec.AfterSHA256 {
+ if rec.CreatedFile {
+ if err := cf.remove(); err != nil {
+ return ActionSkip, "", err
+ }
+ return ActionRemove, "removed the file Beacon created", nil
+ }
+ if rec.Backup == "" && rec.BeforeSHA256 == digest("") {
+ if err := cf.write(""); err != nil {
+ return ActionSkip, "", err
+ }
+ return ActionRemove, "restored the file as it was before connect", nil
+ }
+ if rec.Backup != "" {
+ if data, err := os.ReadFile(rec.Backup); err == nil && digest(string(data)) == rec.BeforeSHA256 {
+ if err := cf.write(string(data)); err != nil {
+ return ActionSkip, "", err
+ }
+ return ActionRemove, "restored the file as it was before connect", nil
+ }
+ }
+ }
+ updated, err := editForDisconnect(t, cf.text, rec)
+ if err != nil {
+ return ActionSkip, "", fmt.Errorf("could not edit %s: %w", rec.Path, err)
+ }
+ if err := verifyDisconnect(t, cf.text, updated, rec); err != nil {
+ return ActionSkip, "", fmt.Errorf("%s: %w; the file was left unchanged", rec.Path, err)
+ }
+ if rec.CreatedFile && onlySkeleton(t, updated) {
+ if err := cf.remove(); err != nil {
+ return ActionSkip, "", err
+ }
+ return ActionRemove, "removed the file Beacon created", nil
+ }
+ if _, err := cf.backup(opts.now()); err != nil {
+ return ActionSkip, "", fmt.Errorf("could not back up %s: %w", rec.Path, err)
+ }
+ if err := cf.write(updated); err != nil {
+ return ActionSkip, "", err
+ }
+ return ActionRemove, "removed Beacon's entry", nil
+}
+
+func editForDisconnect(t Target, text string, rec Record) (string, error) {
+ if t.format == formatTOML {
+ stripped, found := stripTOMLTable(text, t.container[0], ServerName)
+ if !found {
+ return "", errors.New("the " + ServerName + " entry is not a [" + t.container[0] + "." + ServerName + "] table; remove it by hand")
+ }
+ return endTOMLWithNewline(stripped, tomlLineEnding(text)), nil
+ }
+ updated, err := removeJSONMember(text, t.container, ServerName, rec.CreatedParents)
+ if err != nil {
+ return "", err
+ }
+ if t.vscodeInputs && rec.Auth == AuthTokenEnv {
+ if updated, err = removeJSONElements(updated, nil, "inputs", isBeaconInput, rec.CreatedInputs); err != nil {
+ return "", err
+ }
+ }
+ return updated, nil
+}
+
+// onlySkeleton reports whether a config Beacon created holds nothing but what Beacon put there.
+func onlySkeleton(t Target, text string) bool {
+ parse := decodeJSONC
+ if t.format == formatTOML {
+ parse = parseTOML
+ }
+ doc, err := parse(text)
+ if err != nil {
+ return false
+ }
+ for _, f := range t.skeleton {
+ if reflect.DeepEqual(doc[f.Key], normalizeJSON(f.Value)) {
+ delete(doc, f.Key)
+ }
+ }
+ for _, key := range t.container[:1] {
+ if m, ok := doc[key].(map[string]any); ok && len(m) == 0 {
+ delete(doc, key)
+ }
+ }
+ return len(doc) == 0
+}
+
+// Status describes what a harness has configured for the server name.
+type Status struct {
+ Target Target
+ Path string
+ Configured bool
+ URL string
+ Auth AuthMode
+ ByBeacon bool
+ Detail string
+}
+
+// Inspect reports the current state of each target without changing anything.
+func Inspect(opts Options, targets []Target) ([]Status, error) {
+ m, err := loadManifest(opts.Home)
+ if err != nil {
+ return nil, err
+ }
+ var out []Status
+ for _, t := range targets {
+ s := Status{Target: t}
+ if !t.Automatic {
+ s.Auth, s.Detail = AuthManual, "configured by hand; Beacon does not read this runtime's MCP config"
+ out = append(out, s)
+ continue
+ }
+ path, err := t.path(opts.Home)
+ if err != nil {
+ s.Detail = err.Error()
+ out = append(out, s)
+ continue
+ }
+ s.Path = path
+ st, err := inspect(t, path)
+ if err != nil {
+ s.Detail = err.Error()
+ out = append(out, s)
+ continue
+ }
+ if st.exists {
+ s.Configured, s.URL = true, st.url
+ s.Auth = entryAuth(st.entry)
+ rec, ok := m.find(t.Name, path)
+ s.ByBeacon = ok && sameURL(rec.URL, st.url)
+ }
+ out = append(out, s)
+ }
+ return out, nil
+}
+
+// entryAuth infers the auth mode of an entry from its shape. A header value is inspected only
+// for a variable reference and is never returned or printed.
+func entryAuth(entry map[string]any) AuthMode {
+ if _, ok := entry["bearer_token_env_var"]; ok {
+ return AuthTokenEnv
+ }
+ for _, key := range []string{"headers", "http_headers"} {
+ headers, ok := entry[key].(map[string]any)
+ if !ok || len(headers) == 0 {
+ continue
+ }
+ for _, v := range headers {
+ s, _ := v.(string)
+ if strings.Contains(s, "${") || strings.Contains(s, "{env:") {
+ return AuthTokenEnv
+ }
+ }
+ return AuthToken
+ }
+ return AuthOAuth
+}
diff --git a/cli/beacon/internal/mcpconnect/files.go b/cli/beacon/internal/mcpconnect/files.go
new file mode 100644
index 00000000..79f05253
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/files.go
@@ -0,0 +1,114 @@
+package mcpconnect
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+)
+
+// configFile is a harness config as read from disk.
+type configFile struct {
+ path string // the path Beacon reports and records
+ real string // the file actually written, after following symlinks
+ text string
+ exists bool
+ mode os.FileMode
+}
+
+// readConfig reads a harness config. A symlinked config (a dotfiles manager's, say) is read and
+// later written through the link, so the link survives and the file it points at is the one that
+// changes.
+func readConfig(path string) (configFile, error) {
+ cf := configFile{path: path, real: path, mode: 0o600}
+ if resolved, err := filepath.EvalSymlinks(path); err == nil {
+ cf.real = resolved
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return cf, err
+ }
+ info, err := os.Stat(cf.real)
+ if errors.Is(err, os.ErrNotExist) {
+ return cf, nil
+ }
+ if err != nil {
+ return cf, err
+ }
+ if info.IsDir() {
+ return cf, fmt.Errorf("%s is a directory", path)
+ }
+ data, err := os.ReadFile(cf.real)
+ if err != nil {
+ return cf, err
+ }
+ cf.text, cf.exists, cf.mode = string(data), true, info.Mode().Perm()
+ return cf, nil
+}
+
+// write replaces the config atomically: a temporary file in the same directory, given the
+// existing file's mode, renamed over it. A reader never sees half a config. A file Beacon creates
+// is 0600, because several of these configs are where users keep API keys.
+func (cf configFile) write(text string) error {
+ dir := filepath.Dir(cf.real)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return err
+ }
+ tmp, err := os.CreateTemp(dir, "."+filepath.Base(cf.real)+".beacon-*")
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ defer os.Remove(tmpName)
+ if _, err := tmp.WriteString(text); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Sync(); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ if err := os.Chmod(tmpName, cf.mode); err != nil {
+ return err
+ }
+ return os.Rename(tmpName, cf.real)
+}
+
+// remove deletes a config file Beacon created.
+func (cf configFile) remove() error {
+ err := os.Remove(cf.real)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ return err
+}
+
+// backup copies the current contents next to the file, following the naming the endpoint
+// installers already use (<file>.beacon.<UTC timestamp>.bak, 0600). An empty or missing file has
+// nothing to keep and gets no backup.
+func (cf configFile) backup(now time.Time) (string, error) {
+ if !cf.exists || cf.text == "" {
+ return "", nil
+ }
+ base := fmt.Sprintf("%s.beacon.%s", cf.real, now.UTC().Format("20060102T150405Z"))
+ path := base + ".bak"
+ for i := 1; ; i++ {
+ if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) {
+ break
+ }
+ path = fmt.Sprintf("%s.%d.bak", base, i)
+ }
+ if err := os.WriteFile(path, []byte(cf.text), 0o600); err != nil {
+ return "", err
+ }
+ return path, nil
+}
+
+func digest(text string) string {
+ sum := sha256.Sum256([]byte(text))
+ return hex.EncodeToString(sum[:])
+}
diff --git a/cli/beacon/internal/mcpconnect/harness_test.go b/cli/beacon/internal/mcpconnect/harness_test.go
new file mode 100644
index 00000000..c71af122
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/harness_test.go
@@ -0,0 +1,956 @@
+package mcpconnect
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+const testURL = "https://mcp.example.test"
+
+// harnessFixture is one automatic target's test data: an existing config full of things Beacon
+// must not touch, and the exact bytes connect must produce from it.
+type harnessFixture struct {
+ name string
+ // existing is a realistic config with unrelated servers, comments where the format allows
+ // them, and the harness's own formatting.
+ existing string
+ // wantExisting is existing after `connect` in OAuth mode.
+ wantExisting string
+ // wantNew is a config connect creates from nothing, in OAuth mode.
+ wantNew string
+ // wantToken is a config connect creates from nothing with --token-env BEACON_MCP_TOKEN.
+ wantToken string
+ // conflict is a config with a beacon-managed entry pointing somewhere else.
+ conflict string
+}
+
+var harnessFixtures = []harnessFixture{
+ {
+ name: "claude_code",
+ existing: `{
+ "numStartups": 12,
+ "mcpServers": {
+ "beacon": {
+ "type": "stdio",
+ "command": "beacon",
+ "args": [
+ "mcp",
+ "serve"
+ ]
+ }
+ },
+ "projects": {
+ "/work/repo": {
+ "allowedTools": []
+ }
+ }
+}
+`,
+ wantExisting: `{
+ "numStartups": 12,
+ "mcpServers": {
+ "beacon": {
+ "type": "stdio",
+ "command": "beacon",
+ "args": [
+ "mcp",
+ "serve"
+ ]
+ },
+ "beacon-managed": {
+ "type": "http",
+ "url": "https://mcp.example.test"
+ }
+ },
+ "projects": {
+ "/work/repo": {
+ "allowedTools": []
+ }
+ }
+}
+`,
+ wantNew: `{
+ "mcpServers": {
+ "beacon-managed": {
+ "type": "http",
+ "url": "https://mcp.example.test"
+ }
+ }
+}
+`,
+ wantToken: `{
+ "mcpServers": {
+ "beacon-managed": {
+ "type": "http",
+ "url": "https://mcp.example.test",
+ "headers": {
+ "Authorization": "Bearer ${BEACON_MCP_TOKEN}"
+ }
+ }
+ }
+}
+`,
+ conflict: `{"mcpServers": {"beacon-managed": {"type": "http", "url": "https://elsewhere.example"}}}`,
+ },
+ {
+ name: "codex_cli",
+ existing: `# Codex settings
+model = "gpt-5-codex"
+approval_policy = "on-request" # ask first
+
+[mcp_servers.docs]
+command = "docs-mcp"
+args = ["--stdio"]
+
+[profiles.work]
+model = "o3"
+`,
+ wantExisting: `# Codex settings
+model = "gpt-5-codex"
+approval_policy = "on-request" # ask first
+
+[mcp_servers.docs]
+command = "docs-mcp"
+args = ["--stdio"]
+
+[profiles.work]
+model = "o3"
+
+[mcp_servers.beacon-managed]
+url = "https://mcp.example.test"
+`,
+ wantNew: `[mcp_servers.beacon-managed]
+url = "https://mcp.example.test"
+`,
+ wantToken: `[mcp_servers.beacon-managed]
+url = "https://mcp.example.test"
+bearer_token_env_var = "BEACON_MCP_TOKEN"
+`,
+ conflict: "[mcp_servers.beacon-managed]\nurl = \"https://elsewhere.example\"\n",
+ },
+ {
+ name: "cursor",
+ existing: `{
+ "mcpServers": {
+ "github": {
+ "url": "https://api.githubcopilot.com/mcp/",
+ "headers": {
+ "Authorization": "Bearer ${env:GITHUB_TOKEN}"
+ }
+ }
+ }
+}
+`,
+ wantExisting: `{
+ "mcpServers": {
+ "github": {
+ "url": "https://api.githubcopilot.com/mcp/",
+ "headers": {
+ "Authorization": "Bearer ${env:GITHUB_TOKEN}"
+ }
+ },
+ "beacon-managed": {
+ "url": "https://mcp.example.test"
+ }
+ }
+}
+`,
+ wantNew: `{
+ "mcpServers": {
+ "beacon-managed": {
+ "url": "https://mcp.example.test"
+ }
+ }
+}
+`,
+ wantToken: `{
+ "mcpServers": {
+ "beacon-managed": {
+ "url": "https://mcp.example.test",
+ "headers": {
+ "Authorization": "Bearer ${env:BEACON_MCP_TOKEN}"
+ }
+ }
+ }
+}
+`,
+ conflict: `{"mcpServers":{"beacon-managed":{"url":"https://elsewhere.example"}}}`,
+ },
+ {
+ name: "vscode",
+ existing: `{
+ // Servers for the whole profile.
+ "servers": {
+ "memory": {
+ "type": "stdio",
+ "command": "npx",
+ "args": ["-y", "@modelcontextprotocol/server-memory"], // pinned later
+ },
+ },
+ "inputs": [],
+}
+`,
+ wantExisting: `{
+ // Servers for the whole profile.
+ "servers": {
+ "memory": {
+ "type": "stdio",
+ "command": "npx",
+ "args": ["-y", "@modelcontextprotocol/server-memory"], // pinned later
+ },
+ "beacon-managed": {
+ "type": "http",
+ "url": "https://mcp.example.test"
+ },
+ },
+ "inputs": [],
+}
+`,
+ wantNew: `{
+ "servers": {
+ "beacon-managed": {
+ "type": "http",
+ "url": "https://mcp.example.test"
+ }
+ }
+}
+`,
+ wantToken: `{
+ "servers": {
+ "beacon-managed": {
+ "type": "http",
+ "url": "https://mcp.example.test",
+ "headers": {
+ "Authorization": "Bearer ${input:beacon-managed-token}"
+ }
+ }
+ },
+ "inputs": [
+ {
+ "type": "promptString",
+ "id": "beacon-managed-token",
+ "description": "Beacon Managed MCP token (beacon.sh → Dashboard → MCP Access)",
+ "password": true
+ }
+ ]
+}
+`,
+ conflict: `{"servers": {"beacon-managed": {"type": "http", "url": "https://elsewhere.example"}}}`,
+ },
+ {
+ name: "gemini_cli",
+ existing: `{
+ "security": {
+ "auth": {
+ "selectedType": "oauth-personal"
+ }
+ },
+ "ui": {
+ "theme": "GitHub"
+ }
+}
+`,
+ wantExisting: `{
+ "security": {
+ "auth": {
+ "selectedType": "oauth-personal"
+ }
+ },
+ "ui": {
+ "theme": "GitHub"
+ },
+ "mcpServers": {
+ "beacon-managed": {
+ "url": "https://mcp.example.test",
+ "type": "http"
+ }
+ }
+}
+`,
+ wantNew: `{
+ "mcpServers": {
+ "beacon-managed": {
+ "url": "https://mcp.example.test",
+ "type": "http"
+ }
+ }
+}
+`,
+ wantToken: `{
+ "mcpServers": {
+ "beacon-managed": {
+ "url": "https://mcp.example.test",
+ "type": "http",
+ "headers": {
+ "Authorization": "Bearer ${BEACON_MCP_TOKEN}"
+ }
+ }
+ }
+}
+`,
+ conflict: `{"mcpServers": {"beacon-managed": {"httpUrl": "https://elsewhere.example", "url": "https://elsewhere.example"}}}`,
+ },
+ {
+ name: "opencode",
+ existing: `{
+ "$schema": "https://opencode.ai/config.json",
+ // Plugins and servers.
+ "plugin": ["./plugins/beacon.ts"],
+ "mcp": {
+ "context7": {
+ "type": "remote",
+ "url": "https://mcp.context7.com/mcp",
+ "enabled": true,
+ },
+ },
+}
+`,
+ wantExisting: `{
+ "$schema": "https://opencode.ai/config.json",
+ // Plugins and servers.
+ "plugin": ["./plugins/beacon.ts"],
+ "mcp": {
+ "context7": {
+ "type": "remote",
+ "url": "https://mcp.context7.com/mcp",
+ "enabled": true,
+ },
+ "beacon-managed": {
+ "type": "remote",
+ "url": "https://mcp.example.test",
+ "enabled": true
+ },
+ },
+}
+`,
+ wantNew: `{
+ "$schema": "https://opencode.ai/config.json",
+ "mcp": {
+ "beacon-managed": {
+ "type": "remote",
+ "url": "https://mcp.example.test",
+ "enabled": true
+ }
+ }
+}
+`,
+ wantToken: `{
+ "$schema": "https://opencode.ai/config.json",
+ "mcp": {
+ "beacon-managed": {
+ "type": "remote",
+ "url": "https://mcp.example.test",
+ "enabled": true,
+ "oauth": false,
+ "headers": {
+ "Authorization": "Bearer {env:BEACON_MCP_TOKEN}"
+ }
+ }
+ }
+}
+`,
+ conflict: `{"mcp": {"beacon-managed": {"type": "remote", "url": "https://elsewhere.example"}}}`,
+ },
+}
+
+// isolate points every harness path at a fresh home and returns it.
+func isolate(t *testing.T) string {
+ t.Helper()
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ t.Setenv("XDG_CONFIG_HOME", "")
+ t.Setenv("CLAUDE_CONFIG_DIR", "")
+ t.Setenv("CODEX_HOME", "")
+ return home
+}
+
+func fileOptions(home string) Options {
+ return Options{
+ Home: home, URL: testURL,
+ // The file writers are under test here; the Claude CLI path has its own tests.
+ LookPath: func(string) (string, error) { return "", errors.New("not on PATH") },
+ Run: func(context.Context, string, ...string) ([]byte, error) {
+ return nil, errors.New("no CLI may run in file-writer tests")
+ },
+ Now: func() time.Time { return time.Date(2026, 9, 28, 12, 0, 0, 0, time.UTC) },
+ }
+}
+
+func mustTarget(t *testing.T, name string) Target {
+ t.Helper()
+ target, ok := Lookup(name)
+ if !ok {
+ t.Fatalf("no target %q", name)
+ }
+ return target
+}
+
+func targetPath(t *testing.T, target Target, home string) string {
+ t.Helper()
+ path, err := target.ConfigPath(home)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
+
+func writeFile(t *testing.T, path, text string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func readFile(t *testing.T, path string) string {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(data)
+}
+
+func connect(t *testing.T, opts Options, target Target) Item {
+ t.Helper()
+ plan, err := Plan(opts, []Target{target})
+ if err != nil {
+ t.Fatal(err)
+ }
+ applied, err := Apply(context.Background(), opts, plan)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if applied[0].Err != nil {
+ t.Fatalf("apply %s: %v", target.Name, applied[0].Err)
+ }
+ return applied[0]
+}
+
+func disconnect(t *testing.T, opts Options, target Target) Item {
+ t.Helper()
+ items, err := Disconnect(context.Background(), opts, []Target{target})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 1 {
+ t.Fatalf("disconnect returned %d items", len(items))
+ }
+ if items[0].Err != nil {
+ t.Fatalf("disconnect %s: %v", target.Name, items[0].Err)
+ }
+ return items[0]
+}
+
+func TestHarnessConnectWritesExactlyTheExpectedConfig(t *testing.T) {
+ for _, fx := range harnessFixtures {
+ t.Run(fx.name, func(t *testing.T) {
+ target := mustTarget(t, fx.name)
+
+ t.Run("missing file is created, and removed again", func(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ path := targetPath(t, target, home)
+ if got := connect(t, opts, target); got.Action != ActionAdd {
+ t.Fatalf("action = %s, want add", got.Action)
+ }
+ if got := readFile(t, path); got != fx.wantNew {
+ t.Fatalf("new config:\n%s\nwant:\n%s", got, fx.wantNew)
+ }
+ if testenv.HasPOSIXFileModes() {
+ info, _ := os.Stat(path)
+ if info.Mode().Perm() != 0o600 {
+ t.Errorf("a config Beacon creates is %v, want 0600", info.Mode().Perm())
+ }
+ }
+ if got := disconnect(t, opts, target); got.Action != ActionRemove {
+ t.Fatalf("disconnect action = %s (%s)", got.Action, got.Detail)
+ }
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("disconnect left the file connect created: %v", err)
+ }
+ })
+
+ t.Run("existing file keeps everything else, byte for byte", func(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ path := targetPath(t, target, home)
+ writeFile(t, path, fx.existing)
+ connect(t, opts, target)
+ if got := readFile(t, path); got != fx.wantExisting {
+ t.Fatalf("connected config:\n%s\nwant:\n%s", got, fx.wantExisting)
+ }
+ if testenv.HasPOSIXFileModes() {
+ info, _ := os.Stat(path)
+ if info.Mode().Perm() != 0o644 {
+ t.Errorf("connect changed the file's mode to %v", info.Mode().Perm())
+ }
+ }
+ backups, _ := filepath.Glob(path + ".beacon.*.bak")
+ if len(backups) != 1 || readFile(t, backups[0]) != fx.existing {
+ t.Fatalf("expected one backup holding the original, got %v", backups)
+ }
+ disconnect(t, opts, target)
+ if got := readFile(t, path); got != fx.existing {
+ t.Fatalf("disconnect did not restore the original:\n%s", got)
+ }
+ })
+
+ t.Run("disconnect after the user edited the file removes only Beacon's entry", func(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ path := targetPath(t, target, home)
+ writeFile(t, path, fx.existing)
+ connect(t, opts, target)
+ // An unrelated edit the user makes afterwards, so the backup is stale and the
+ // entry has to be spliced out.
+ edited := strings.Replace(readFile(t, path), fx.existing[:1], fx.existing[:1]+userEdit(target), 1)
+ writeFile(t, path, edited)
+ disconnect(t, opts, target)
+ want := strings.Replace(fx.existing, fx.existing[:1], fx.existing[:1]+userEdit(target), 1)
+ if got := readFile(t, path); got != want {
+ t.Fatalf("got:\n%s\nwant:\n%s", got, want)
+ }
+ })
+
+ t.Run("re-running connect changes nothing", func(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ path := targetPath(t, target, home)
+ writeFile(t, path, fx.existing)
+ connect(t, opts, target)
+ first := readFile(t, path)
+ manifestBefore := readFile(t, manifestPath(home))
+ plan, err := Plan(opts, []Target{target})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plan[0].Action != ActionPresent {
+ t.Fatalf("second plan = %s, want present", plan[0].Action)
+ }
+ if _, err := Apply(context.Background(), opts, plan); err != nil {
+ t.Fatal(err)
+ }
+ if readFile(t, path) != first || readFile(t, manifestPath(home)) != manifestBefore {
+ t.Fatal("a no-op connect rewrote the config or the manifest")
+ }
+ if backups, _ := filepath.Glob(path + ".beacon.*.bak"); len(backups) != 1 {
+ t.Fatalf("a no-op connect made another backup: %v", backups)
+ }
+ })
+
+ t.Run("token-env references the variable and never a value", func(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ opts.TokenEnv = "BEACON_MCP_TOKEN"
+ t.Setenv("BEACON_MCP_TOKEN", "bcn_mcp_must_never_be_written")
+ path := targetPath(t, target, home)
+ connect(t, opts, target)
+ got := readFile(t, path)
+ if got != fx.wantToken {
+ t.Fatalf("token config:\n%s\nwant:\n%s", got, fx.wantToken)
+ }
+ if strings.Contains(got, "bcn_mcp_") {
+ t.Fatal("the token value was written")
+ }
+ disconnect(t, opts, target)
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatal("disconnect left the token-mode file connect created")
+ }
+ })
+
+ t.Run("switching auth mode updates Beacon's own entry", func(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ path := targetPath(t, target, home)
+ writeFile(t, path, fx.existing)
+ connect(t, opts, target)
+ tokenOpts := opts
+ tokenOpts.TokenEnv = "BEACON_MCP_TOKEN"
+ if got := connect(t, tokenOpts, target); got.Action != ActionUpdate {
+ t.Fatalf("action = %s, want update", got.Action)
+ }
+ back := connect(t, opts, target)
+ if back.Action != ActionUpdate {
+ t.Fatalf("action = %s, want update", back.Action)
+ }
+ if got := readFile(t, path); got != fx.wantExisting {
+ t.Fatalf("switching back did not restore the OAuth entry:\n%s", got)
+ }
+ disconnect(t, opts, target)
+ if got := readFile(t, path); got != fx.existing {
+ t.Fatalf("disconnect after updates did not restore the original:\n%s", got)
+ }
+ })
+
+ t.Run("a conflicting entry is left alone without --force", func(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ path := targetPath(t, target, home)
+ writeFile(t, path, fx.conflict)
+ plan, err := Plan(opts, []Target{target})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plan[0].Action != ActionConflict || plan[0].ExistingURL != "https://elsewhere.example" {
+ t.Fatalf("plan = %s (%q)", plan[0].Action, plan[0].ExistingURL)
+ }
+ if _, err := Apply(context.Background(), opts, plan); err != nil {
+ t.Fatal(err)
+ }
+ if readFile(t, path) != fx.conflict {
+ t.Fatal("a conflict was overwritten without --force")
+ }
+ if got := disconnect(t, opts, target); got.Action != ActionAbsent || readFile(t, path) != fx.conflict {
+ t.Fatal("disconnect touched an entry Beacon did not write")
+ }
+
+ opts.Force = true
+ if got := connect(t, opts, target); got.Action != ActionReplace {
+ t.Fatalf("forced action = %s", got.Action)
+ }
+ st, _ := inspect(target, path)
+ if !sameURL(st.url, testURL) {
+ t.Fatalf("--force did not replace the entry; url = %s", st.url)
+ }
+ disconnect(t, fileOptions(home), target)
+ if got := readFile(t, path); got != fx.conflict {
+ t.Fatalf("disconnect after --force should restore the pre-connect file:\n%s", got)
+ }
+ })
+
+ t.Run("an identical entry Beacon did not write is left as is", func(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ path := targetPath(t, target, home)
+ writeFile(t, path, fx.wantNew)
+ plan, err := Plan(opts, []Target{target})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plan[0].Action != ActionPresent {
+ t.Fatalf("plan = %s", plan[0].Action)
+ }
+ if got := disconnect(t, opts, target); got.Action != ActionAbsent {
+ t.Fatalf("disconnect action = %s", got.Action)
+ }
+ if readFile(t, path) != fx.wantNew {
+ t.Fatal("disconnect removed an entry the user wrote")
+ }
+ })
+ })
+ }
+}
+
+// userEdit is a harmless edit placed right after the first byte of a fixture.
+func userEdit(target Target) string {
+ if target.format == formatTOML {
+ return " user edit\n#"
+ }
+ return "\n \"userEdit\": true,"
+}
+
+func TestUnparseableConfigsAreSkippedAndLeftAlone(t *testing.T) {
+ for _, name := range []string{"claude_code", "codex_cli", "cursor", "vscode", "gemini_cli", "opencode"} {
+ t.Run(name, func(t *testing.T) {
+ home := isolate(t)
+ target := mustTarget(t, name)
+ path := targetPath(t, target, home)
+ broken := "{ this is [ not valid\n"
+ writeFile(t, path, broken)
+ plan, err := Plan(fileOptions(home), []Target{target})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plan[0].Action != ActionSkip || plan[0].Detail == "" {
+ t.Fatalf("plan = %s (%s)", plan[0].Action, plan[0].Detail)
+ }
+ if _, err := Apply(context.Background(), fileOptions(home), plan); err != nil {
+ t.Fatal(err)
+ }
+ if readFile(t, path) != broken {
+ t.Fatal("an unparseable config was rewritten")
+ }
+ })
+ }
+}
+
+func TestCodexInlineTableIsNotRewritten(t *testing.T) {
+ home := isolate(t)
+ target := mustTarget(t, "codex")
+ path := targetPath(t, target, home)
+ inline := "mcp_servers = { beacon-managed = { url = \"https://elsewhere.example\" } }\n"
+ writeFile(t, path, inline)
+ opts := fileOptions(home)
+ opts.Force = true
+ plan, err := Plan(opts, []Target{target})
+ if err != nil {
+ t.Fatal(err)
+ }
+ applied, _ := Apply(context.Background(), opts, plan)
+ if applied[0].Err == nil {
+ t.Fatal("an inline table Beacon cannot splice was reported as replaced")
+ }
+ if readFile(t, path) != inline {
+ t.Fatal("the inline table was rewritten")
+ }
+}
+
+func TestCodexHonorsCodexHome(t *testing.T) {
+ home := isolate(t)
+ codexHome := filepath.Join(home, "elsewhere")
+ t.Setenv("CODEX_HOME", codexHome)
+ connect(t, fileOptions(home), mustTarget(t, "codex"))
+ if !strings.Contains(readFile(t, filepath.Join(codexHome, "config.toml")), "[mcp_servers.beacon-managed]") {
+ t.Fatal("CODEX_HOME was not honored")
+ }
+}
+
+func TestClaudeHonorsClaudeConfigDir(t *testing.T) {
+ home := isolate(t)
+ dir := filepath.Join(home, "claude-config")
+ t.Setenv("CLAUDE_CONFIG_DIR", dir)
+ connect(t, fileOptions(home), mustTarget(t, "claude"))
+ if !strings.Contains(readFile(t, filepath.Join(dir, ".claude.json")), ServerName) {
+ t.Fatal("CLAUDE_CONFIG_DIR was not honored")
+ }
+}
+
+func TestOpenCodePrefersAnExistingConfigFile(t *testing.T) {
+ home := isolate(t)
+ dir := filepath.Join(home, ".config", "opencode")
+ writeFile(t, filepath.Join(dir, "opencode.json"), "{\n \"$schema\": \"https://opencode.ai/config.json\"\n}\n")
+ target := mustTarget(t, "opencode")
+ if got := targetPath(t, target, home); got != filepath.Join(dir, "opencode.json") {
+ t.Fatalf("path = %s, want the existing opencode.json", got)
+ }
+ writeFile(t, filepath.Join(dir, "opencode.jsonc"), "{}\n")
+ if got := targetPath(t, target, home); got != filepath.Join(dir, "opencode.jsonc") {
+ t.Fatalf("path = %s, want opencode.jsonc when both exist", got)
+ }
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "xdg"))
+ if got := targetPath(t, target, home); got != filepath.Join(home, "xdg", "opencode", "opencode.jsonc") {
+ t.Fatalf("XDG_CONFIG_HOME was not honored: %s", got)
+ }
+}
+
+func TestSymlinkedConfigIsWrittenThroughTheLink(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("symlinks need privileges on Windows")
+ }
+ home := isolate(t)
+ target := mustTarget(t, "cursor")
+ path := targetPath(t, target, home)
+ real := filepath.Join(home, "dotfiles", "mcp.json")
+ writeFile(t, real, "{}\n")
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(real, path); err != nil {
+ t.Fatal(err)
+ }
+ connect(t, fileOptions(home), target)
+ if info, err := os.Lstat(path); err != nil || info.Mode()&os.ModeSymlink == 0 {
+ t.Fatal("connect replaced the symlink with a file")
+ }
+ if !strings.Contains(readFile(t, real), ServerName) {
+ t.Fatal("the link target was not updated")
+ }
+ disconnect(t, fileOptions(home), target)
+ if readFile(t, real) != "{}\n" {
+ t.Fatalf("disconnect did not restore the link target: %q", readFile(t, real))
+ }
+}
+
+func TestBlankExistingFileIsRestoredBlank(t *testing.T) {
+ home := isolate(t)
+ target := mustTarget(t, "gemini")
+ path := targetPath(t, target, home)
+ writeFile(t, path, "")
+ connect(t, fileOptions(home), target)
+ disconnect(t, fileOptions(home), target)
+ if got := readFile(t, path); got != "" {
+ t.Fatalf("got %q, want the original blank file", got)
+ }
+}
+
+func TestVSCodeInputConflictNeedsForce(t *testing.T) {
+ home := isolate(t)
+ target := mustTarget(t, "vscode")
+ path := targetPath(t, target, home)
+ doc := `{"servers": {}, "inputs": [{"type": "promptString", "id": "beacon-managed-token", "description": "mine"}]}`
+ writeFile(t, path, doc)
+ opts := fileOptions(home)
+ opts.TokenEnv = "BEACON_MCP_TOKEN"
+ plan, _ := Plan(opts, []Target{target})
+ if plan[0].Action != ActionConflict {
+ t.Fatalf("plan = %s", plan[0].Action)
+ }
+ // OAuth mode does not use the input, so it is not a conflict there.
+ plan, _ = Plan(fileOptions(home), []Target{target})
+ if plan[0].Action != ActionAdd {
+ t.Fatalf("oauth plan = %s", plan[0].Action)
+ }
+}
+
+func TestManifestIsPrivateAndHoldsNoSecret(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ opts.TokenEnv = "BEACON_MCP_TOKEN"
+ t.Setenv("BEACON_MCP_TOKEN", "bcn_mcp_secret_value")
+ connect(t, opts, mustTarget(t, "codex"))
+ data := readFile(t, manifestPath(home))
+ if strings.Contains(data, "bcn_mcp_secret_value") {
+ t.Fatal("the manifest holds a token value")
+ }
+ if !strings.Contains(data, `"token_env": "BEACON_MCP_TOKEN"`) {
+ t.Fatalf("manifest does not record the variable name:\n%s", data)
+ }
+ if testenv.HasPOSIXFileModes() {
+ info, _ := os.Stat(manifestPath(home))
+ dir, _ := os.Stat(filepath.Dir(manifestPath(home)))
+ if info.Mode().Perm() != 0o600 || dir.Mode().Perm() != 0o700 {
+ t.Fatalf("manifest %v in %v, want 0600 in 0700", info.Mode().Perm(), dir.Mode().Perm())
+ }
+ }
+ disconnect(t, opts, mustTarget(t, "codex"))
+ if _, err := os.Stat(manifestPath(home)); !os.IsNotExist(err) {
+ t.Fatal("an empty manifest was left behind")
+ }
+}
+
+func TestDisconnectLeavesAnEntryWhoseURLTheUserChanged(t *testing.T) {
+ home := isolate(t)
+ target := mustTarget(t, "cursor")
+ path := targetPath(t, target, home)
+ connect(t, fileOptions(home), target)
+ changed := strings.Replace(readFile(t, path), testURL, "https://theirs.example", 1)
+ writeFile(t, path, changed)
+ if got := disconnect(t, fileOptions(home), target); got.Action != ActionAbsent {
+ t.Fatalf("action = %s", got.Action)
+ }
+ if readFile(t, path) != changed {
+ t.Fatal("disconnect removed an entry that no longer points at Beacon's URL")
+ }
+}
+
+func TestLookupAcceptsEndpointTargetSpellings(t *testing.T) {
+ for spelling, want := range map[string]string{
+ "claude": "claude_code", "Claude_Code": "claude_code", "codex": "codex_cli", "codex-cli": "codex_cli",
+ "gemini": "gemini_cli", "vs-code": "vscode", "opencode": "opencode", "cursor": "cursor",
+ "copilot": "copilot_cli", "droid": "factory", "windsurf": "devin-desktop",
+ } {
+ got, ok := Lookup(spelling)
+ if !ok || got.Name != want {
+ t.Errorf("Lookup(%q) = %q, %v; want %q", spelling, got.Name, ok, want)
+ }
+ }
+ if _, ok := Lookup("nonsense"); ok {
+ t.Error("an unknown harness was accepted")
+ }
+}
+
+func TestManualTargetsNeverWriteAndNeverPrintAToken(t *testing.T) {
+ home := isolate(t)
+ for _, target := range Targets() {
+ if target.Automatic {
+ continue
+ }
+ plan, err := Plan(fileOptions(home), []Target{target})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plan[0].Action != ActionManual || plan[0].Writes() {
+ t.Fatalf("%s: manual target planned %s", target.Name, plan[0].Action)
+ }
+ steps := plan[0].NextStep(fileOptions(home))
+ if !strings.Contains(steps, testURL) || !strings.Contains(steps, "<token>") || !strings.Contains(steps, TokenPage) {
+ t.Errorf("%s: steps lack the URL, the placeholder or the token page:\n%s", target.Name, steps)
+ }
+ }
+ entries, _ := os.ReadDir(home)
+ if len(entries) != 0 {
+ t.Fatalf("manual targets wrote into the home directory: %v", entries)
+ }
+}
+
+func TestCreatedFileIsKeptWhenTheUserAddedToIt(t *testing.T) {
+ home := isolate(t)
+ target := mustTarget(t, "opencode")
+ path := targetPath(t, target, home)
+ connect(t, fileOptions(home), target)
+ withTheirs, _, err := insertJSONMember(readFile(t, path), []string{"mcp"}, "theirs", ordered{{"type", "remote"}, {"url", "https://t"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeFile(t, path, withTheirs)
+ disconnect(t, fileOptions(home), target)
+ got, err := decodeJSONC(readFile(t, path))
+ if err != nil {
+ t.Fatal(err)
+ }
+ servers, _ := got["mcp"].(map[string]any)
+ if servers["theirs"] == nil || servers[ServerName] != nil {
+ t.Fatalf("got %v", got)
+ }
+
+ // A created file whose only change since connect is formatting is still Beacon's to delete.
+ home = isolate(t)
+ path = targetPath(t, target, home)
+ connect(t, fileOptions(home), target)
+ writeFile(t, path, readFile(t, path)+"\n")
+ disconnect(t, fileOptions(home), target)
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatal("a created file holding only Beacon's skeleton was left behind")
+ }
+}
+
+func TestInspectReportsModeAndOwnershipWithoutValues(t *testing.T) {
+ home := isolate(t)
+ opts := fileOptions(home)
+ opts.TokenEnv = "BEACON_MCP_TOKEN"
+ connect(t, opts, mustTarget(t, "codex"))
+ cursor := mustTarget(t, "cursor")
+ writeFile(t, targetPath(t, cursor, home), `{"mcpServers": {"beacon-managed": {"url": "https://mcp.example.test", "headers": {"Authorization": "Bearer bcn_mcp_literal"}}}}`)
+ statuses, err := Inspect(fileOptions(home), []Target{mustTarget(t, "codex"), cursor, mustTarget(t, "gemini"), mustTarget(t, "copilot")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ type row struct {
+ configured, byBeacon bool
+ auth AuthMode
+ }
+ want := []row{{true, true, AuthTokenEnv}, {true, false, AuthToken}, {false, false, ""}, {false, false, AuthManual}}
+ for i, s := range statuses {
+ if got := (row{s.Configured, s.ByBeacon, s.Auth}); got != want[i] {
+ t.Errorf("%s: %+v, want %+v", s.Target.Name, got, want[i])
+ }
+ if strings.Contains(s.Detail+s.URL, "bcn_mcp_") {
+ t.Errorf("%s: status exposes a header value", s.Target.Name)
+ }
+ }
+}
+
+func TestNextStepsNameTheServerOrTheVariable(t *testing.T) {
+ for _, target := range Targets() {
+ if !target.Automatic {
+ continue
+ }
+ if step := target.NextStep(AuthOAuth, ""); step == "" {
+ t.Errorf("%s has no OAuth next step", target.Name)
+ }
+ if step := target.NextStep(AuthTokenEnv, "MY_TOKEN_VAR"); !strings.Contains(step, "MY_TOKEN_VAR") && !strings.Contains(step, "secret storage") {
+ t.Errorf("%s token step does not name the variable: %q", target.Name, step)
+ }
+ }
+}
diff --git a/cli/beacon/internal/mcpconnect/jsonc.go b/cli/beacon/internal/mcpconnect/jsonc.go
new file mode 100644
index 00000000..b3dcecec
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/jsonc.go
@@ -0,0 +1,328 @@
+package mcpconnect
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "strings"
+)
+
+// The harness configs Beacon edits are JSON files the user also edits by hand, and two of them
+// (OpenCode's opencode.jsonc, VS Code's mcp.json) are JSONC: comments and trailing commas are
+// legal. Decoding one into a map and encoding it back would drop every comment, reorder keys and
+// reindent the file, so Beacon never does that. This file is a small parser that keeps the byte
+// span of every value, so an edit can splice text in or out at an exact offset and leave every
+// other byte where it was. verifyJSONEdit then parses the result and checks that the edit changed
+// only the one entry Beacon owns.
+
+type jsonKind byte
+
+const (
+ jsonObject jsonKind = 'o'
+ jsonArray jsonKind = 'a'
+ jsonScalar jsonKind = 's'
+)
+
+type jsonNode struct {
+ kind jsonKind
+ start int // offset of the first byte of the value
+ end int // offset one past the last byte of the value
+ depth int // nesting depth; the document's root value is 0
+
+ members []jsonMember // objects
+ elems []*jsonNode // arrays
+}
+
+type jsonMember struct {
+ key string
+ keyStart int
+ value *jsonNode
+}
+
+func (n *jsonNode) member(key string) (int, *jsonNode) {
+ if n == nil || n.kind != jsonObject {
+ return -1, nil
+ }
+ for i, m := range n.members {
+ if m.key == key {
+ return i, m.value
+ }
+ }
+ return -1, nil
+}
+
+func (n *jsonNode) memberCount(key string) int {
+ count := 0
+ if n == nil {
+ return 0
+ }
+ for _, m := range n.members {
+ if m.key == key {
+ count++
+ }
+ }
+ return count
+}
+
+type jsonParser struct {
+ text string
+ pos int
+}
+
+// parseJSONC parses a JSON or JSONC document. An empty or whitespace-only document has no root.
+func parseJSONC(text string) (*jsonNode, error) {
+ p := &jsonParser{text: text}
+ if err := p.skip(); err != nil {
+ return nil, err
+ }
+ if p.pos == len(text) {
+ return nil, nil
+ }
+ root, err := p.value(0)
+ if err != nil {
+ return nil, err
+ }
+ if err := p.skip(); err != nil {
+ return nil, err
+ }
+ if p.pos != len(text) {
+ return nil, p.errorf("unexpected content after the document")
+ }
+ return root, nil
+}
+
+func (p *jsonParser) errorf(format string, args ...any) error {
+ line := strings.Count(p.text[:min(p.pos, len(p.text))], "\n") + 1
+ return fmt.Errorf("line %d: %s", line, fmt.Sprintf(format, args...))
+}
+
+// skip moves past whitespace and comments.
+func (p *jsonParser) skip() error {
+ for p.pos < len(p.text) {
+ switch c := p.text[p.pos]; {
+ case c == ' ' || c == '\t' || c == '\n' || c == '\r':
+ p.pos++
+ case c == '/' && p.pos+1 < len(p.text) && p.text[p.pos+1] == '/':
+ end := strings.IndexByte(p.text[p.pos:], '\n')
+ if end < 0 {
+ p.pos = len(p.text)
+ } else {
+ p.pos += end
+ }
+ case c == '/' && p.pos+1 < len(p.text) && p.text[p.pos+1] == '*':
+ end := strings.Index(p.text[p.pos+2:], "*/")
+ if end < 0 {
+ return p.errorf("unterminated comment")
+ }
+ p.pos += end + 4
+ default:
+ return nil
+ }
+ }
+ return nil
+}
+
+func (p *jsonParser) value(depth int) (*jsonNode, error) {
+ if p.pos >= len(p.text) {
+ return nil, p.errorf("unexpected end of document")
+ }
+ if depth > 200 {
+ return nil, p.errorf("document is nested too deeply")
+ }
+ switch p.text[p.pos] {
+ case '{':
+ return p.object(depth)
+ case '[':
+ return p.array(depth)
+ case '"':
+ start := p.pos
+ if _, err := p.str(); err != nil {
+ return nil, err
+ }
+ return &jsonNode{kind: jsonScalar, start: start, end: p.pos, depth: depth}, nil
+ default:
+ start := p.pos
+ for p.pos < len(p.text) && !strings.ContainsRune(",}] \t\r\n/", rune(p.text[p.pos])) {
+ p.pos++
+ }
+ if p.pos == start {
+ return nil, p.errorf("unexpected %q", p.text[p.pos])
+ }
+ literal := p.text[start:p.pos]
+ if !json.Valid([]byte(literal)) {
+ return nil, p.errorf("invalid value %q", literal)
+ }
+ return &jsonNode{kind: jsonScalar, start: start, end: p.pos, depth: depth}, nil
+ }
+}
+
+// str scans a string starting at the opening quote and returns its decoded value.
+func (p *jsonParser) str() (string, error) {
+ start := p.pos
+ p.pos++
+ for p.pos < len(p.text) {
+ switch p.text[p.pos] {
+ case '\\':
+ p.pos += 2
+ case '"':
+ p.pos++
+ var decoded string
+ if err := json.Unmarshal([]byte(p.text[start:p.pos]), &decoded); err != nil {
+ return "", p.errorf("invalid string: %v", err)
+ }
+ return decoded, nil
+ case '\n':
+ return "", p.errorf("unterminated string")
+ default:
+ p.pos++
+ }
+ }
+ return "", p.errorf("unterminated string")
+}
+
+func (p *jsonParser) object(depth int) (*jsonNode, error) {
+ node := &jsonNode{kind: jsonObject, start: p.pos, depth: depth}
+ p.pos++
+ for {
+ if err := p.skip(); err != nil {
+ return nil, err
+ }
+ if p.pos >= len(p.text) {
+ return nil, p.errorf("unterminated object")
+ }
+ if p.text[p.pos] == '}' {
+ p.pos++
+ node.end = p.pos
+ return node, nil
+ }
+ if len(node.members) > 0 {
+ if p.text[p.pos] != ',' {
+ return nil, p.errorf("expected , or } in object")
+ }
+ p.pos++
+ if err := p.skip(); err != nil {
+ return nil, err
+ }
+ if p.pos < len(p.text) && p.text[p.pos] == '}' { // trailing comma
+ p.pos++
+ node.end = p.pos
+ return node, nil
+ }
+ }
+ if p.pos >= len(p.text) || p.text[p.pos] != '"' {
+ return nil, p.errorf("expected a quoted key")
+ }
+ keyStart := p.pos
+ key, err := p.str()
+ if err != nil {
+ return nil, err
+ }
+ if err := p.skip(); err != nil {
+ return nil, err
+ }
+ if p.pos >= len(p.text) || p.text[p.pos] != ':' {
+ return nil, p.errorf("expected : after key %q", key)
+ }
+ p.pos++
+ if err := p.skip(); err != nil {
+ return nil, err
+ }
+ value, err := p.value(depth + 1)
+ if err != nil {
+ return nil, err
+ }
+ node.members = append(node.members, jsonMember{key: key, keyStart: keyStart, value: value})
+ }
+}
+
+func (p *jsonParser) array(depth int) (*jsonNode, error) {
+ node := &jsonNode{kind: jsonArray, start: p.pos, depth: depth}
+ p.pos++
+ for {
+ if err := p.skip(); err != nil {
+ return nil, err
+ }
+ if p.pos >= len(p.text) {
+ return nil, p.errorf("unterminated array")
+ }
+ if p.text[p.pos] == ']' {
+ p.pos++
+ node.end = p.pos
+ return node, nil
+ }
+ if len(node.elems) > 0 {
+ if p.text[p.pos] != ',' {
+ return nil, p.errorf("expected , or ] in array")
+ }
+ p.pos++
+ if err := p.skip(); err != nil {
+ return nil, err
+ }
+ if p.pos < len(p.text) && p.text[p.pos] == ']' {
+ p.pos++
+ node.end = p.pos
+ return node, nil
+ }
+ }
+ value, err := p.value(depth + 1)
+ if err != nil {
+ return nil, err
+ }
+ node.elems = append(node.elems, value)
+ }
+}
+
+// decodeJSONC parses a JSON or JSONC document into plain Go values, the way the harness reads it.
+// Numbers stay json.Number so a comparison never loses precision. An empty document is an empty
+// object, which is how every harness Beacon edits treats a blank config file.
+func decodeJSONC(text string) (map[string]any, error) {
+ root, err := parseJSONC(text)
+ if err != nil {
+ return nil, err
+ }
+ if root == nil {
+ return map[string]any{}, nil
+ }
+ if root.kind != jsonObject {
+ return nil, fmt.Errorf("the document is not a JSON object")
+ }
+ var buf bytes.Buffer
+ writeStandardJSON(&buf, text, root)
+ decoder := json.NewDecoder(&buf)
+ decoder.UseNumber()
+ var out map[string]any
+ if err := decoder.Decode(&out); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// writeStandardJSON re-emits a parsed node as strict JSON: the same values, without comments or
+// trailing commas.
+func writeStandardJSON(buf *bytes.Buffer, text string, n *jsonNode) {
+ switch n.kind {
+ case jsonObject:
+ buf.WriteByte('{')
+ for i, m := range n.members {
+ if i > 0 {
+ buf.WriteByte(',')
+ }
+ key, _ := json.Marshal(m.key)
+ buf.Write(key)
+ buf.WriteByte(':')
+ writeStandardJSON(buf, text, m.value)
+ }
+ buf.WriteByte('}')
+ case jsonArray:
+ buf.WriteByte('[')
+ for i, e := range n.elems {
+ if i > 0 {
+ buf.WriteByte(',')
+ }
+ writeStandardJSON(buf, text, e)
+ }
+ buf.WriteByte(']')
+ default:
+ buf.WriteString(text[n.start:n.end])
+ }
+}
diff --git a/cli/beacon/internal/mcpconnect/jsonc_test.go b/cli/beacon/internal/mcpconnect/jsonc_test.go
new file mode 100644
index 00000000..f600acaf
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/jsonc_test.go
@@ -0,0 +1,268 @@
+package mcpconnect
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestDecodeJSONCMatchesStrictJSONWithoutComments(t *testing.T) {
+ doc := `{
+ // a line comment with "quotes" and {braces}
+ "url": "https://host//not-a-comment/*nor-this*/",
+ /* a block
+ comment */ "n": 1.50,
+ "escaped": "say \"hi\" \\ // still a string",
+ "list": [1, 2, 3,],
+ "nested": {"a": true,},
+}`
+ got, err := decodeJSONC(doc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want, err := decodeJSONC(`{"url":"https://host//not-a-comment/*nor-this*/","n":1.50,"escaped":"say \"hi\" \\ // still a string","list":[1,2,3],"nested":{"a":true}}`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("got %#v\nwant %#v", got, want)
+ }
+}
+
+func TestParseJSONCRejectsMalformedDocuments(t *testing.T) {
+ for _, doc := range []string{
+ `{"a": }`,
+ `{"a": 1 "b": 2}`,
+ `{"a": 1`,
+ `{"a": "unterminated}`,
+ `{/* unterminated comment "a": 1}`,
+ `{"a": nope}`,
+ `{a: 1}`,
+ `{"a": 1} trailing`,
+ `{,}`,
+ } {
+ if _, err := decodeJSONC(doc); err == nil {
+ t.Errorf("decodeJSONC(%q) accepted a malformed document", doc)
+ }
+ }
+}
+
+func TestDecodeJSONCTreatsBlankAsEmptyObjectAndRejectsNonObjects(t *testing.T) {
+ for _, doc := range []string{"", " \n", "// only a comment\n"} {
+ got, err := decodeJSONC(doc)
+ if err != nil || len(got) != 0 {
+ t.Errorf("decodeJSONC(%q) = %v, %v; want an empty object", doc, got, err)
+ }
+ }
+ if _, err := decodeJSONC(`[1, 2]`); err == nil {
+ t.Error("a top-level array was accepted as a config object")
+ }
+}
+
+var beaconEntry = ordered{{"url", "https://mcp.example.test"}, {"type", "http"}}
+
+// Every insertion must be undone exactly by the matching removal, whatever the formatting of the
+// document it went into. This is what makes connect → disconnect leave a file as it found it even
+// when the file changed in between (so the backup cannot simply be restored).
+func TestInsertThenRemoveJSONMemberIsTheIdentity(t *testing.T) {
+ docs := map[string]string{
+ "empty object": "{}",
+ "empty object newline": "{}\n",
+ "two-space": "{\n \"theme\": \"dark\"\n}\n",
+ "four-space": "{\n \"theme\": \"dark\",\n \"mcpServers\": {\n \"other\": {\"url\": \"https://o\"}\n }\n}\n",
+ "tabs": "{\n\t\"mcpServers\": {\n\t\t\"other\": {\n\t\t\t\"command\": \"x\"\n\t\t}\n\t}\n}\n",
+ "crlf": "{\r\n \"mcpServers\": {\r\n \"other\": {}\r\n }\r\n}\r\n",
+ "compact": `{"mcpServers":{"other":{"url":"https://o"}}}`,
+ "compact spaced": `{"mcpServers": {"other": {"url": "https://o"}, "more": {}}}`,
+ "empty container": "{\n \"mcpServers\": {}\n}\n",
+ "comment-only container": "{\n \"mcpServers\": {\n // add servers here\n }\n}\n",
+ "trailing comma": "{\n \"mcpServers\": {\n \"other\": {},\n },\n}\n",
+ "trailing comment": "{\n \"a\": 1 // why\n}\n",
+ "comment before close": "{\n \"mcpServers\": {\n \"other\": {}\n // end\n }\n}\n",
+ "no final newline": "{\n \"a\": 1\n}",
+ "unicode and escapes": "{\n \"名前\": \"\\u00e9\\n\",\n \"mcpServers\": {\"x\": {}}\n}\n",
+ "container not last": "{\n \"mcpServers\": {\n \"other\": {}\n },\n \"after\": [1, 2]\n}\n",
+ "deeply nested elsewhere": "{\n \"a\": {\"b\": {\"c\": [{\"d\": {}}]}}\n}\n",
+ }
+ for name, doc := range docs {
+ t.Run(name, func(t *testing.T) {
+ inserted, created, err := insertJSONMember(doc, []string{"mcpServers"}, ServerName, beaconEntry)
+ if err != nil {
+ t.Fatal(err)
+ }
+ before, _ := decodeJSONC(doc)
+ after, err := decodeJSONC(inserted)
+ if err != nil {
+ t.Fatalf("insertion produced invalid JSONC: %v\n%s", err, inserted)
+ }
+ setPath(before, []string{"mcpServers"}, ServerName, normalizeJSON(beaconEntry))
+ if !reflect.DeepEqual(normalizeValue(before), normalizeValue(after)) {
+ t.Fatalf("insertion changed more than the entry:\n%s", inserted)
+ }
+ removed, err := removeJSONMember(inserted, []string{"mcpServers"}, ServerName, created)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if removed != doc {
+ t.Fatalf("remove did not undo insert\n doc: %q\n ins: %q\n got: %q", doc, inserted, removed)
+ }
+ })
+ }
+}
+
+func TestInsertJSONMemberCopiesTheDocumentsFormatting(t *testing.T) {
+ cases := []struct{ name, doc, want string }{
+ {
+ "four-space indentation",
+ "{\n \"mcpServers\": {\n \"other\": {}\n }\n}\n",
+ "{\n \"mcpServers\": {\n \"other\": {},\n \"beacon-managed\": {\n \"url\": \"https://mcp.example.test\",\n \"type\": \"http\"\n }\n }\n}\n",
+ },
+ {
+ "single-line document stays on one line",
+ `{"mcpServers":{"other":{}}}`,
+ `{"mcpServers":{"other":{},"beacon-managed":{"url":"https://mcp.example.test","type":"http"}}}`,
+ },
+ {
+ "CRLF line endings",
+ "{\r\n \"a\": 1\r\n}\r\n",
+ "{\r\n \"a\": 1,\r\n \"mcpServers\": {\r\n \"beacon-managed\": {\r\n \"url\": \"https://mcp.example.test\",\r\n \"type\": \"http\"\r\n }\r\n }\r\n}\r\n",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, _, err := insertJSONMember(tc.doc, []string{"mcpServers"}, ServerName, beaconEntry)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != tc.want {
+ t.Fatalf("got\n%q\nwant\n%q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestJSONEditRefusesShapesItCannotEditSafely(t *testing.T) {
+ cases := map[string]string{
+ "duplicate container": `{"mcpServers": {}, "mcpServers": {}}`,
+ "container not object": `{"mcpServers": []}`,
+ "container is a string": `{"mcpServers": "none"}`,
+ "root is an array": `[]`,
+ }
+ for name, doc := range cases {
+ if _, _, err := insertJSONMember(doc, []string{"mcpServers"}, ServerName, beaconEntry); err == nil {
+ t.Errorf("%s: insert accepted %q", name, doc)
+ }
+ }
+ if _, _, err := insertJSONMember(`{"mcpServers": {"beacon-managed": {}}}`, []string{"mcpServers"}, ServerName, beaconEntry); err == nil {
+ t.Error("insert over an existing entry was accepted")
+ }
+ if _, err := removeJSONMember(`{"mcpServers": {"beacon-managed": {}, "beacon-managed": {}}}`, []string{"mcpServers"}, ServerName, 0); err == nil {
+ t.Error("removal of a duplicated key was accepted")
+ }
+}
+
+func TestRemoveJSONMemberHandlesEntriesItDidNotPosition(t *testing.T) {
+ cases := []struct{ name, doc, want string }{
+ {"first of several", `{"s": {"beacon-managed": {}, "b": 1}}`, `{"s": {"b": 1}}`},
+ {"middle", `{"s": {"a": 1, "beacon-managed": {}, "b": 1}}`, `{"s": {"a": 1, "b": 1}}`},
+ {"only, with trailing comma", "{\"s\": {\"beacon-managed\": {},}}", `{"s": {}}`},
+ {"absent", `{"s": {"a": 1}}`, `{"s": {"a": 1}}`},
+ {"no container", `{"a": 1}`, `{"a": 1}`},
+ }
+ for _, tc := range cases {
+ got, err := removeJSONMember(tc.doc, []string{"s"}, ServerName, 0)
+ if err != nil {
+ t.Fatalf("%s: %v", tc.name, err)
+ }
+ if got != tc.want {
+ t.Errorf("%s: got %q want %q", tc.name, got, tc.want)
+ }
+ }
+}
+
+func TestPruneRemovesOnlyContainersLeftEmpty(t *testing.T) {
+ doc := "{\n \"a\": 1\n}\n"
+ inserted, created, err := insertJSONMember(doc, []string{"mcp", "servers"}, ServerName, beaconEntry)
+ if err != nil || created != 2 {
+ t.Fatalf("created=%d err=%v", created, err)
+ }
+ // Someone else adds a server next to Beacon's: the container is no longer Beacon's to remove.
+ shared, _, err := insertJSONMember(inserted, []string{"mcp", "servers"}, "theirs", ordered{{"url", "https://t"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := removeJSONMember(shared, []string{"mcp", "servers"}, ServerName, created)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(got, `"theirs"`) || strings.Contains(got, ServerName) {
+ t.Fatalf("prune removed a container that still held another server:\n%s", got)
+ }
+}
+
+func TestArrayAppendAndRemoveAreInverse(t *testing.T) {
+ for _, doc := range []string{
+ "{\n \"servers\": {}\n}\n",
+ "{\n \"inputs\": []\n}\n",
+ "{\n \"inputs\": [\n {\"id\": \"other\"}\n ]\n}\n",
+ "{\"inputs\":[{\"id\":\"other\"}]}",
+ } {
+ appended, created, err := appendJSONElement(doc, nil, "inputs", vscodeInput())
+ if err != nil {
+ t.Fatal(err)
+ }
+ back, err := removeJSONElements(appended, nil, "inputs", isBeaconInput, created)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if back != doc {
+ t.Errorf("array round trip\n doc: %q\n app: %q\n got: %q", doc, appended, back)
+ }
+ }
+}
+
+// The verifier is the backstop under the text splicing: it must reject any edit that changes
+// something other than Beacon's own entry, whatever the splice got wrong.
+func TestVerifierRejectsEditsBeyondBeaconsEntry(t *testing.T) {
+ opts := Options{URL: testURL}
+ json := mustTarget(t, "cursor")
+ before := `{"theme": "dark", "mcpServers": {"other": {"url": "https://o"}}}`
+ good := `{"theme": "dark", "mcpServers": {"other": {"url": "https://o"}, "beacon-managed": {"url": "https://mcp.example.test"}}}`
+ if err := verifyConnect(json, before, good, opts); err != nil {
+ t.Fatalf("a correct edit was rejected: %v", err)
+ }
+ for name, bad := range map[string]string{
+ "changed another key": `{"theme": "light", "mcpServers": {"other": {"url": "https://o"}, "beacon-managed": {"url": "https://mcp.example.test"}}}`,
+ "dropped another entry": `{"theme": "dark", "mcpServers": {"beacon-managed": {"url": "https://mcp.example.test"}}}`,
+ "wrong entry": `{"theme": "dark", "mcpServers": {"other": {"url": "https://o"}, "beacon-managed": {"url": "https://evil"}}}`,
+ "added a key": `{"theme": "dark", "x": 1, "mcpServers": {"other": {"url": "https://o"}, "beacon-managed": {"url": "https://mcp.example.test"}}}`,
+ "does not parse": `{"theme": "dark",`,
+ } {
+ if err := verifyConnect(json, before, bad, opts); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+ toml := mustTarget(t, "codex")
+ tBefore := "model = \"o3\"\n"
+ if err := verifyConnect(toml, tBefore, "model = \"o3\"\n\n[mcp_servers.beacon-managed]\nurl = \"https://mcp.example.test\"\n", opts); err != nil {
+ t.Fatalf("a correct TOML edit was rejected: %v", err)
+ }
+ if err := verifyConnect(toml, tBefore, "model = \"o4\"\n\n[mcp_servers.beacon-managed]\nurl = \"https://mcp.example.test\"\n", opts); err == nil {
+ t.Error("a TOML edit that changed the model was accepted")
+ }
+ if err := verifyDisconnect(toml, "a = 1\n[mcp_servers.beacon-managed]\nurl = \"x\"\n", "", Record{}); err == nil {
+ t.Error("a disconnect that dropped an unrelated key was accepted")
+ }
+}
+
+func TestStripTOMLTableHandlesQuotingAndSubtables(t *testing.T) {
+ doc := "a = 1\n\n[mcp_servers.\"beacon-managed\"]\nurl = \"x\"\n\n[mcp_servers.beacon-managed.env]\nK = \"v\"\n\n[mcp_servers.beacon-managed-other]\nurl = \"y\"\n"
+ got, found := stripTOMLTable(doc, "mcp_servers", ServerName)
+ if !found {
+ t.Fatal("not found")
+ }
+ want := "a = 1\n\n[mcp_servers.beacon-managed-other]\nurl = \"y\"\n"
+ if got != want {
+ t.Fatalf("got %q want %q", got, want)
+ }
+}
diff --git a/cli/beacon/internal/mcpconnect/jsonedit.go b/cli/beacon/internal/mcpconnect/jsonedit.go
new file mode 100644
index 00000000..a94bd892
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/jsonedit.go
@@ -0,0 +1,394 @@
+package mcpconnect
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "strings"
+)
+
+// ordered is a JSON object whose keys are written in the order given, so the entry Beacon adds
+// reads the way the harness's own `mcp add` writes it.
+type ordered []field
+
+type field struct {
+ Key string
+ Value any
+}
+
+// jsonStyle is the formatting an edit copies from the document it goes into.
+type jsonStyle struct {
+ unit string // one level of indentation
+ eol string
+}
+
+func detectJSONStyle(text string) jsonStyle {
+ style := jsonStyle{unit: " ", eol: "\n"}
+ if strings.Contains(text, "\r\n") {
+ style.eol = "\r\n"
+ }
+ // The shallowest indented key is a member of the root object, so its indentation is one
+ // level. Deeper keys are multiples of it.
+ best := ""
+ for _, line := range strings.Split(text, "\n") {
+ trimmed := strings.TrimLeft(line, " \t")
+ if !strings.HasPrefix(trimmed, `"`) {
+ continue
+ }
+ lead := line[:len(line)-len(trimmed)]
+ if lead == "" {
+ continue
+ }
+ if best == "" || len(lead) < len(best) {
+ best = lead
+ }
+ }
+ if best != "" {
+ style.unit = best
+ }
+ return style
+}
+
+func (s jsonStyle) indent(depth int) string {
+ return strings.Repeat(s.unit, depth)
+}
+
+func jsonString(value string) string {
+ var buf bytes.Buffer
+ encoder := json.NewEncoder(&buf)
+ encoder.SetEscapeHTML(false)
+ _ = encoder.Encode(value)
+ return strings.TrimRight(buf.String(), "\n")
+}
+
+// renderJSON writes value as it would appear at depth: multi-line with the document's
+// 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 ordered:
+ if len(v) == 0 {
+ return "{}"
+ }
+ parts := make([]string, len(v))
+ for i, f := range v {
+ parts[i] = jsonString(f.Key) + sep + renderJSON(f.Value, style, depth+1, compact, sep)
+ }
+ if compact {
+ return "{" + strings.Join(parts, ",") + "}"
+ }
+ inner := style.eol + style.indent(depth+1)
+ return "{" + inner + strings.Join(parts, ","+inner) + style.eol + style.indent(depth) + "}"
+ case []any:
+ if len(v) == 0 {
+ return "[]"
+ }
+ parts := make([]string, len(v))
+ for i, e := range v {
+ parts[i] = renderJSON(e, style, depth+1, compact, sep)
+ }
+ if compact {
+ return "[" + strings.Join(parts, ",") + "]"
+ }
+ inner := style.eol + style.indent(depth+1)
+ return "[" + inner + strings.Join(parts, ","+inner) + style.eol + style.indent(depth) + "]"
+ case string:
+ return jsonString(v)
+ case bool:
+ if v {
+ return "true"
+ }
+ return "false"
+ default:
+ encoded, _ := json.Marshal(v)
+ return string(encoded)
+ }
+}
+
+// renderJSONDocument writes a new document holding only value.
+func renderJSONDocument(value ordered, style jsonStyle) string {
+ return renderJSON(value, style, 0, false, ": ") + style.eol
+}
+
+// nest wraps value in one object per path segment: nest([a b], v) is {"a": {"b": v}}.
+func nest(path []string, value any) any {
+ for i := len(path) - 1; i >= 0; i-- {
+ value = ordered{{Key: path[i], Value: value}}
+ }
+ return value
+}
+
+// span is one member of an object or element of an array: [start, end) runs from the first byte
+// of the key (or element) to the last byte of the value.
+type span struct{ start, end int }
+
+func memberSpans(n *jsonNode) []span {
+ out := make([]span, len(n.members))
+ for i, m := range n.members {
+ out[i] = span{m.keyStart, m.value.end}
+ }
+ return out
+}
+
+func elemSpans(n *jsonNode) []span {
+ out := make([]span, len(n.elems))
+ for i, e := range n.elems {
+ out[i] = span{e.start, e.end}
+ }
+ return out
+}
+
+// isCompact reports whether a non-empty container is written on a single line.
+func isCompact(text string, n *jsonNode, items []span) bool {
+ return len(items) > 0 && !strings.Contains(text[n.start:n.end], "\n")
+}
+
+// keySeparator is the text a document puts between a key and its value (": " or ":").
+func keySeparator(text string, n *jsonNode) string {
+ for _, m := range n.members {
+ between := text[m.keyStart+len(jsonString(m.key)) : m.value.start]
+ if strings.TrimSpace(between) == ":" {
+ if strings.HasPrefix(strings.TrimLeft(between, " \t"), ":") && strings.HasSuffix(between, ":") {
+ return ":"
+ }
+ return ": "
+ }
+ }
+ return ": "
+}
+
+// itemSeparator is the text a single-line container puts between items ("," or ", ").
+func itemSeparator(text string, items []span) string {
+ if len(items) < 2 {
+ return ","
+ }
+ between := text[items[0].end:items[1].start]
+ if strings.TrimSpace(between) == "," && strings.HasSuffix(between, " ") {
+ return ", "
+ }
+ return ","
+}
+
+// insertItem appends rendered as the last item of container n.
+//
+// The new text goes directly after the last existing value, so removeItem, which deletes from the
+// end of the previous value to the end of the removed one, takes out exactly what this put in.
+// A trailing comma, a comment after the last item, and everything else in the file stay put.
+func insertItem(text string, n *jsonNode, items []span, rendered string, style jsonStyle) string {
+ if len(items) > 0 {
+ at := items[len(items)-1].end
+ if isCompact(text, n, items) {
+ return text[:at] + itemSeparator(text, items) + rendered + text[at:]
+ }
+ return text[:at] + "," + style.eol + style.indent(n.depth+1) + rendered + text[at:]
+ }
+ open := n.start + 1
+ inner := text[open : n.end-1]
+ if strings.TrimSpace(inner) == "" {
+ return text[:open] + style.eol + style.indent(n.depth+1) + rendered + style.eol + style.indent(n.depth) + text[n.end-1:]
+ }
+ // The container holds only comments. Keep them after the new item.
+ return text[:open] + style.eol + style.indent(n.depth+1) + rendered + text[open:]
+}
+
+// removeItem deletes item i of container n, with the separator that belongs to it.
+func removeItem(text string, n *jsonNode, items []span, i int) string {
+ var from, to int
+ switch {
+ case i > 0:
+ from, to = items[i-1].end, items[i].end
+ case len(items) > 1:
+ from, to = items[0].start, items[1].start
+ default:
+ from, to = n.start+1, items[0].end
+ // A trailing comma after the only item has to go with it.
+ p := &jsonParser{text: text, pos: to}
+ if p.skip() == nil && p.pos < n.end-1 && text[p.pos] == ',' {
+ to = p.pos + 1
+ }
+ // When nothing but whitespace is left, close the container up to {} or [], which is
+ // what insertItem expanded it from.
+ if strings.TrimSpace(text[to:n.end-1]) == "" {
+ to = n.end - 1
+ }
+ }
+ return text[:from] + text[to:]
+}
+
+// jsonPathError reports a config shape Beacon will not edit around.
+type jsonPathError struct{ msg string }
+
+func (e *jsonPathError) Error() string { return e.msg }
+
+// lookupObject walks path from the root, returning the object at the end of it, how far the walk
+// got, and the containing object at each step. A path segment that is not an object, or a key that
+// appears twice (which harnesses resolve differently), is an error.
+func lookupObject(root *jsonNode, path []string) (chain []*jsonNode, err error) {
+ node := root
+ chain = []*jsonNode{root}
+ for _, seg := range path {
+ if node.memberCount(seg) > 1 {
+ return chain, &jsonPathError{fmt.Sprintf("%q appears more than once", seg)}
+ }
+ _, child := node.member(seg)
+ if child == nil {
+ return chain, nil
+ }
+ if child.kind != jsonObject {
+ return chain, &jsonPathError{fmt.Sprintf("%q is not a JSON object", seg)}
+ }
+ node = child
+ chain = append(chain, node)
+ }
+ return chain, nil
+}
+
+// insertJSONMember returns text with path.key set to value. key must not already exist. Objects
+// missing from path are created; created reports how many were, so a later removal can take them
+// out again once they are empty.
+func insertJSONMember(text string, path []string, key string, value any) (updated string, created int, err error) {
+ root, err := parseJSONC(text)
+ if err != nil {
+ return "", 0, err
+ }
+ style := detectJSONStyle(text)
+ if root == nil {
+ doc := nest(path, ordered{{Key: key, Value: value}}).(ordered)
+ // Keep a blank file's surrounding whitespace out of it; a blank file becomes the document.
+ return renderJSONDocument(doc, style), len(path), nil
+ }
+ if root.kind != jsonObject {
+ return "", 0, &jsonPathError{"the document is not a JSON object"}
+ }
+ chain, err := lookupObject(root, path)
+ if err != nil {
+ return "", 0, err
+ }
+ parent := chain[len(chain)-1]
+ missing := path[len(chain)-1:]
+ insertKey, insertValue := key, value
+ if len(missing) > 0 {
+ insertKey = missing[0]
+ insertValue = nest(missing[1:], ordered{{Key: key, Value: value}})
+ } else if parent.memberCount(key) > 0 {
+ return "", 0, &jsonPathError{fmt.Sprintf("%q already exists", key)}
+ }
+ items := memberSpans(parent)
+ compact := isCompact(text, parent, items)
+ sep := keySeparator(text, parent)
+ rendered := jsonString(insertKey) + sep + renderJSON(insertValue, style, parent.depth+1, compact, sep)
+ return insertItem(text, parent, items, rendered, style), len(missing), nil
+}
+
+// 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) {
+ root, err := parseJSONC(text)
+ if err != nil {
+ return "", err
+ }
+ if root == nil || root.kind != jsonObject {
+ return text, nil
+ }
+ chain, err := lookupObject(root, path)
+ if err != nil {
+ return "", err
+ }
+ if len(chain) != len(path)+1 {
+ return text, nil
+ }
+ target := chain[len(chain)-1]
+ if target.memberCount(key) > 1 {
+ return "", &jsonPathError{fmt.Sprintf("%q appears more than once", key)}
+ }
+ index, _ := target.member(key)
+ if index < 0 {
+ return text, nil
+ }
+ // Climb while the object being emptied is one Beacon created and holds nothing else.
+ level := len(path)
+ for level > 0 && len(path)-level < prune && len(target.members) == 1 {
+ level--
+ target = chain[level]
+ index, _ = target.member(path[level])
+ }
+ return removeItem(text, target, memberSpans(target), index), nil
+}
+
+// appendJSONElement returns text with value appended to the array at path.key, creating the
+// array when it is missing. created reports whether it was.
+func appendJSONElement(text string, path []string, key string, value any) (string, bool, error) {
+ root, err := parseJSONC(text)
+ if err != nil {
+ return "", false, err
+ }
+ if root == nil {
+ updated, _, err := insertJSONMember(text, path, key, []any{value})
+ return updated, true, err
+ }
+ chain, err := lookupObject(root, path)
+ if err != nil {
+ return "", false, err
+ }
+ if len(chain) != len(path)+1 || chain[len(chain)-1].memberCount(key) == 0 {
+ updated, _, err := insertJSONMember(text, path, key, []any{value})
+ return updated, true, err
+ }
+ parent := chain[len(chain)-1]
+ if parent.memberCount(key) > 1 {
+ return "", false, &jsonPathError{fmt.Sprintf("%q appears more than once", key)}
+ }
+ _, arr := parent.member(key)
+ if arr.kind != jsonArray {
+ return "", false, &jsonPathError{fmt.Sprintf("%q is not a JSON array", key)}
+ }
+ style := detectJSONStyle(text)
+ items := elemSpans(arr)
+ compact := isCompact(text, arr, items)
+ rendered := renderJSON(value, style, arr.depth+1, compact, keySeparator(text, parent))
+ return insertItem(text, arr, items, rendered, style), false, nil
+}
+
+// removeJSONElements returns text without the elements of the array at path.key that match. With
+// prune set, an array left empty is removed as well.
+func removeJSONElements(text string, path []string, key string, match func(any) bool, prune bool) (string, error) {
+ for {
+ root, err := parseJSONC(text)
+ if err != nil {
+ return "", err
+ }
+ if root == nil {
+ return text, nil
+ }
+ chain, err := lookupObject(root, path)
+ if err != nil {
+ return "", err
+ }
+ if len(chain) != len(path)+1 {
+ return text, nil
+ }
+ parent := chain[len(chain)-1]
+ index, arr := parent.member(key)
+ if arr == nil || arr.kind != jsonArray {
+ return text, nil
+ }
+ found := -1
+ for i, e := range arr.elems {
+ var buf bytes.Buffer
+ writeStandardJSON(&buf, text, e)
+ var decoded any
+ decoder := json.NewDecoder(&buf)
+ decoder.UseNumber()
+ if decoder.Decode(&decoded) == nil && match(decoded) {
+ found = i
+ break
+ }
+ }
+ if found < 0 {
+ return text, nil
+ }
+ if prune && len(arr.elems) == 1 {
+ return removeItem(text, parent, memberSpans(parent), index), nil
+ }
+ text = removeItem(text, arr, elemSpans(arr), found)
+ }
+}
diff --git a/cli/beacon/internal/mcpconnect/manifest.go b/cli/beacon/internal/mcpconnect/manifest.go
new file mode 100644
index 00000000..f59e84c9
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/manifest.go
@@ -0,0 +1,128 @@
+package mcpconnect
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "time"
+)
+
+// The manifest is how `disconnect` knows which entries are Beacon's. A comment in the config
+// would not do: several of these files are rewritten by their own runtime (Claude Code rewrites
+// ~/.claude.json constantly, and `codex mcp` re-serializes config.toml), which drops comments --
+// the lesson the Kimi Code installer learned. An entry is Beacon's when the manifest has a record
+// for that harness and file, and the entry there still points at the recorded URL.
+//
+// The manifest holds no secret. It records a URL, an environment variable's name, file paths and
+// hashes; a token value is never written anywhere by this package.
+
+// ManifestPath is the file under ~/.beacon that records what `beacon mcp connect` wrote.
+const ManifestPath = ".beacon/mcp/connections.json"
+
+const manifestSchemaVersion = 1
+
+// Record is one entry Beacon wrote into one harness config.
+type Record struct {
+ Harness string `json:"harness"`
+ Path string `json:"path"`
+ ServerName string `json:"server_name"`
+ URL string `json:"url"`
+ Auth AuthMode `json:"auth"`
+ TokenEnv string `json:"token_env,omitempty"`
+ Method string `json:"method"`
+ // CreatedFile is set when the config did not exist before connect, so disconnect can remove a
+ // file that holds nothing else.
+ CreatedFile bool `json:"created_file,omitempty"`
+ // CreatedParents counts the enclosing objects (such as "mcpServers") connect had to create.
+ CreatedParents int `json:"created_parents,omitempty"`
+ // CreatedInputs is set when connect created VS Code's "inputs" array.
+ CreatedInputs bool `json:"created_inputs,omitempty"`
+ // Backup, BeforeSHA256 and AfterSHA256 let disconnect restore the exact original bytes when
+ // the file has not changed since connect wrote it.
+ Backup string `json:"backup,omitempty"`
+ BeforeSHA256 string `json:"before_sha256,omitempty"`
+ AfterSHA256 string `json:"after_sha256,omitempty"`
+ WrittenAt time.Time `json:"written_at"`
+}
+
+type manifest struct {
+ SchemaVersion int `json:"schema_version"`
+ Records []Record `json:"records"`
+}
+
+func manifestPath(home string) string {
+ return filepath.Join(home, ManifestPath)
+}
+
+func loadManifest(home string) (*manifest, error) {
+ data, err := os.ReadFile(manifestPath(home))
+ if errors.Is(err, os.ErrNotExist) {
+ return &manifest{SchemaVersion: manifestSchemaVersion}, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ var m manifest
+ if err := json.Unmarshal(data, &m); err != nil {
+ return nil, fmt.Errorf("%s is not valid JSON: %w", manifestPath(home), err)
+ }
+ if m.SchemaVersion != manifestSchemaVersion {
+ return nil, fmt.Errorf("%s has schema version %d; this Beacon understands %d", manifestPath(home), m.SchemaVersion, manifestSchemaVersion)
+ }
+ return &m, nil
+}
+
+func (m *manifest) find(harness, path string) (Record, bool) {
+ for _, r := range m.Records {
+ if r.Harness == harness && r.Path == path {
+ return r, true
+ }
+ }
+ return Record{}, false
+}
+
+func (m *manifest) put(rec Record) {
+ m.drop(rec.Harness, rec.Path)
+ m.Records = append(m.Records, rec)
+ sort.Slice(m.Records, func(i, j int) bool {
+ if m.Records[i].Harness != m.Records[j].Harness {
+ return m.Records[i].Harness < m.Records[j].Harness
+ }
+ return m.Records[i].Path < m.Records[j].Path
+ })
+}
+
+func (m *manifest) drop(harness, path string) {
+ kept := m.Records[:0]
+ for _, r := range m.Records {
+ if r.Harness != harness || r.Path != path {
+ kept = append(kept, r)
+ }
+ }
+ m.Records = kept
+}
+
+// save writes the manifest 0600 in a 0700 directory, like the rest of ~/.beacon. An empty
+// manifest is removed rather than left behind.
+func (m *manifest) save(home string) error {
+ path := manifestPath(home)
+ if len(m.Records) == 0 {
+ err := os.Remove(path)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ return err
+ }
+ data, err := json.MarshalIndent(m, "", " ")
+ if err != nil {
+ return err
+ }
+ cf := configFile{path: path, real: path, mode: 0o600}
+ return cf.write(string(data) + "\n")
+}
diff --git a/cli/beacon/internal/mcpconnect/targets.go b/cli/beacon/internal/mcpconnect/targets.go
new file mode 100644
index 00000000..f66e5f0a
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/targets.go
@@ -0,0 +1,334 @@
+package mcpconnect
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
+)
+
+// ServerName is the name Beacon registers the Beacon Managed MCP server under in every harness.
+// The local stdio server `beacon mcp serve` is "beacon"; the two names differ so neither entry
+// overwrites the other.
+const ServerName = "beacon-managed"
+
+// TokenPage is where a person creates a personal Beacon Managed MCP token.
+const TokenPage = "beacon.sh → Dashboard → MCP Access"
+
+// vscodeInputID names the VS Code input variable that holds a token in token mode.
+const vscodeInputID = "beacon-managed-token"
+
+// AuthMode is how a harness authenticates to Beacon Managed MCP.
+type AuthMode string
+
+const (
+ // AuthOAuth writes only the URL. The harness finds the authorization server from the MCP
+ // server's 401 challenge, registers itself, and signs the user in in a browser. Beacon
+ // writes no secret.
+ AuthOAuth AuthMode = "oauth"
+ // AuthTokenEnv writes a reference to an environment variable (or, for VS Code, a prompted
+ // input) that holds a personal MCP token. The token value is never written.
+ AuthTokenEnv AuthMode = "token-env"
+ // AuthToken is an entry that carries a header written outside Beacon, which may hold a
+ // token value. Beacon reports the mode and never reads the value out.
+ AuthToken AuthMode = "token"
+ // AuthManual means Beacon writes nothing and prints the steps instead.
+ AuthManual AuthMode = "manual"
+)
+
+type configFormat int
+
+const (
+ formatJSON configFormat = iota
+ formatTOML
+)
+
+// Target is one harness Beacon can register the server in, or print the steps for.
+type Target struct {
+ // Name is the harness's canonical discovery name (internal/endpoint/harness).
+ Name string
+ DisplayName string
+ // Aliases are the extra spellings --harness accepts, after normalization.
+ Aliases []string
+
+ // Automatic targets have a config Beacon writes. The rest are manual.
+ Automatic bool
+
+ format configFormat
+ path func(home string) (string, error)
+ container []string // path to the object holding servers, e.g. ["mcpServers"]
+ entry func(url, tokenEnv string) ordered
+ // skeleton is the content of a config Beacon creates, besides the server entry.
+ skeleton ordered
+ // cli names a CLI whose own `mcp add`/`mcp remove` Beacon prefers when it is on PATH.
+ cli string
+ // vscodeInputs is set for VS Code, whose token mode uses a prompted input.
+ vscodeInputs bool
+
+ oauthNext string
+ tokenNext string // may contain %s for the variable name
+
+ // manual renders the steps for a manual target.
+ manual func(url string) string
+}
+
+// Targets is the catalog: every harness Beacon knows how to connect, automatic first.
+func Targets() []Target {
+ return []Target{
+ {
+ Name: "claude_code", DisplayName: "Claude Code", Aliases: []string{"claude", "claude-code"},
+ Automatic: true, format: formatJSON, path: claudeConfigPath, container: []string{"mcpServers"},
+ cli: "claude",
+ entry: func(url, tokenEnv string) ordered {
+ e := ordered{{"type", "http"}, {"url", url}}
+ if tokenEnv != "" {
+ e = append(e, field{"headers", ordered{{"Authorization", "Bearer ${" + tokenEnv + "}"}}})
+ }
+ return e
+ },
+ oauthNext: "In Claude Code, run /mcp, choose " + ServerName + ", and sign in.",
+ tokenNext: "Set %s in the environment Claude Code starts from.",
+ },
+ {
+ Name: "codex_cli", DisplayName: "Codex CLI", Aliases: []string{"codex", "codex-cli"},
+ Automatic: true, format: formatTOML, path: codexConfigPath, container: []string{"mcp_servers"},
+ entry: func(url, tokenEnv string) ordered {
+ e := ordered{{"url", url}}
+ if tokenEnv != "" {
+ e = append(e, field{"bearer_token_env_var", tokenEnv})
+ }
+ return e
+ },
+ oauthNext: "Run `codex mcp login " + ServerName + "`.",
+ tokenNext: "Set %s in the environment Codex starts from.",
+ },
+ {
+ Name: "cursor", DisplayName: "Cursor", Aliases: []string{"cursor"},
+ Automatic: true, format: formatJSON, path: homePath(".cursor", "mcp.json"), container: []string{"mcpServers"},
+ entry: func(url, tokenEnv string) ordered {
+ e := ordered{{"url", url}}
+ if tokenEnv != "" {
+ e = append(e, field{"headers", ordered{{"Authorization", "Bearer ${env:" + tokenEnv + "}"}}})
+ }
+ return e
+ },
+ oauthNext: "In Cursor Settings → MCP, find " + ServerName + " (marked \"Needs login\") and sign in.",
+ tokenNext: "Set %s in the environment Cursor starts from.",
+ },
+ {
+ Name: "vscode", DisplayName: "VS Code", Aliases: []string{"vscode", "vs-code", "code"},
+ Automatic: true, format: formatJSON, path: vscodeMCPPath, container: []string{"servers"},
+ vscodeInputs: true,
+ entry: func(url, tokenEnv string) ordered {
+ e := ordered{{"type", "http"}, {"url", url}}
+ if tokenEnv != "" {
+ e = append(e, field{"headers", ordered{{"Authorization", "Bearer ${input:" + vscodeInputID + "}"}}})
+ }
+ return e
+ },
+ oauthNext: "In VS Code, run \"MCP: List Servers\", start " + ServerName + ", and sign in.",
+ tokenNext: "VS Code asks for the token the first time " + ServerName + " starts and keeps it in its secret storage; it does not read %s.",
+ },
+ {
+ Name: "gemini_cli", DisplayName: "Gemini CLI", Aliases: []string{"gemini", "gemini-cli"},
+ Automatic: true, format: formatJSON, path: homePath(".gemini", "settings.json"), container: []string{"mcpServers"},
+ entry: func(url, tokenEnv string) ordered {
+ e := ordered{{"url", url}, {"type", "http"}}
+ if tokenEnv != "" {
+ e = append(e, field{"headers", ordered{{"Authorization", "Bearer ${" + tokenEnv + "}"}}})
+ }
+ return e
+ },
+ oauthNext: "In Gemini CLI, run /mcp auth " + ServerName + ". Gemini CLI loads MCP servers only in trusted folders.",
+ tokenNext: "Set %s in the environment Gemini CLI starts from. Gemini CLI loads MCP servers only in trusted folders.",
+ },
+ {
+ Name: "opencode", DisplayName: "OpenCode", Aliases: []string{"opencode", "open-code"},
+ Automatic: true, format: formatJSON, path: opencodeConfigPath, container: []string{"mcp"},
+ skeleton: ordered{{"$schema", "https://opencode.ai/config.json"}},
+ entry: func(url, tokenEnv string) ordered {
+ e := ordered{{"type", "remote"}, {"url", url}, {"enabled", true}}
+ if tokenEnv != "" {
+ e = append(e, field{"oauth", false}, field{"headers", ordered{{"Authorization", "Bearer {env:" + tokenEnv + "}"}}})
+ }
+ return e
+ },
+ oauthNext: "Run `opencode mcp auth " + ServerName + "`.",
+ tokenNext: "Set %s in the environment OpenCode starts from.",
+ },
+
+ // Manual targets: no MCP OAuth support Beacon has confirmed, so Beacon writes nothing
+ // and prints the steps. The snippets follow each runtime's documentation.
+ {
+ Name: "copilot_cli", DisplayName: "GitHub Copilot CLI", Aliases: []string{"copilot", "copilot-cli", "github-copilot-cli"},
+ manual: func(url string) string {
+ return "copilot mcp add --transport http " + ServerName + " " + url + " --header \"Authorization: Bearer <token>\""
+ },
+ },
+ {
+ Name: "cline", DisplayName: "Cline", Aliases: []string{"cline"},
+ manual: func(url string) string {
+ return "In Cline → MCP Servers → Configure, add to cline_mcp_settings.json:\n" +
+ jsonSnippet("mcpServers", ordered{{"type", "streamableHttp"}, {"url", url}, {"headers", bearerPlaceholder()}})
+ },
+ },
+ {
+ Name: "kiro", DisplayName: "Kiro", Aliases: []string{"kiro", "kiro-ide", "kiro-cli"},
+ manual: func(url string) string {
+ return "Add to ~/.kiro/settings/mcp.json:\n" +
+ jsonSnippet("mcpServers", ordered{{"url", url}, {"headers", bearerPlaceholder()}})
+ },
+ },
+ {
+ Name: "devin-desktop", DisplayName: "Devin Desktop", Aliases: []string{"devin-desktop", "windsurf"},
+ manual: func(url string) string {
+ return "Add to ~/.codeium/windsurf/mcp_config.json:\n" +
+ jsonSnippet("mcpServers", ordered{{"serverUrl", url}, {"headers", bearerPlaceholder()}})
+ },
+ },
+ {
+ Name: "qwen_code", DisplayName: "Qwen Code", Aliases: []string{"qwen", "qwen-code"},
+ manual: func(url string) string {
+ return "Add to ~/.qwen/settings.json:\n" +
+ jsonSnippet("mcpServers", ordered{{"httpUrl", url}, {"headers", bearerPlaceholder()}})
+ },
+ },
+ {
+ Name: "factory", DisplayName: "Factory Droid", Aliases: []string{"factory", "droid"},
+ manual: func(url string) string {
+ return "droid mcp add " + ServerName + " " + url + " --type http --header \"Authorization: Bearer <token>\""
+ },
+ },
+ {
+ Name: "hermes", DisplayName: "Hermes Agent", Aliases: []string{"hermes", "hermes-agent"},
+ manual: func(url string) string {
+ return "Add to ~/.hermes/config.yaml:\n" +
+ "mcp_servers:\n " + ServerName + ":\n url: " + url + "\n headers:\n Authorization: \"Bearer <token>\""
+ },
+ },
+ {
+ Name: "kimi_code", DisplayName: "Kimi Code", Aliases: []string{"kimi", "kimi-code"},
+ manual: func(url string) string {
+ return "kimi mcp add --transport http " + ServerName + " " + url + " --header \"Authorization: Bearer <token>\""
+ },
+ },
+ {
+ Name: "antigravity_cli", DisplayName: "Antigravity CLI", Aliases: []string{"antigravity", "antigravity-cli"},
+ manual: func(url string) string {
+ return "Add to ~/.gemini/antigravity/mcp_config.json:\n" +
+ jsonSnippet("mcpServers", ordered{{"serverUrl", url}, {"headers", bearerPlaceholder()}})
+ },
+ },
+ }
+}
+
+func bearerPlaceholder() ordered {
+ return ordered{{"Authorization", "Bearer <token>"}}
+}
+
+func jsonSnippet(container string, entry ordered) string {
+ doc := ordered{{container, ordered{{ServerName, entry}}}}
+ return strings.TrimRight(renderJSONDocument(doc, jsonStyle{unit: " ", eol: "\n"}), "\n")
+}
+
+// NormalizeKey folds a harness spelling the way `beacon endpoint` target names are folded.
+func NormalizeKey(name string) string {
+ return strings.ReplaceAll(strings.ToLower(strings.TrimSpace(name)), "_", "-")
+}
+
+// Lookup finds a target by its canonical name or an alias.
+func Lookup(name string) (Target, bool) {
+ key := NormalizeKey(name)
+ if key == "" {
+ return Target{}, false
+ }
+ for _, t := range Targets() {
+ if NormalizeKey(t.Name) == key {
+ return t, true
+ }
+ for _, alias := range t.Aliases {
+ if NormalizeKey(alias) == key {
+ return t, true
+ }
+ }
+ }
+ return Target{}, false
+}
+
+// ConfigPath is the file an automatic target's entry lives in.
+func (t Target) ConfigPath(home string) (string, error) {
+ if !t.Automatic {
+ return "", errors.New("manual target has no config Beacon writes")
+ }
+ return t.path(home)
+}
+
+func homePath(parts ...string) func(string) (string, error) {
+ return func(home string) (string, error) {
+ return filepath.Join(append([]string{home}, parts...)...), nil
+ }
+}
+
+// claudeConfigPath is the file `claude mcp add --scope user` writes: ~/.claude.json, or
+// .claude.json inside CLAUDE_CONFIG_DIR when that is set.
+func claudeConfigPath(home string) (string, error) {
+ if dir := strings.TrimSpace(os.Getenv("CLAUDE_CONFIG_DIR")); dir != "" {
+ return filepath.Join(dir, ".claude.json"), nil
+ }
+ return filepath.Join(home, ".claude.json"), nil
+}
+
+// codexConfigPath honors CODEX_HOME, as Codex does.
+func codexConfigPath(home string) (string, error) {
+ if dir := strings.TrimSpace(os.Getenv("CODEX_HOME")); dir != "" {
+ return filepath.Join(dir, "config.toml"), nil
+ }
+ return filepath.Join(home, ".codex", "config.toml"), nil
+}
+
+// vscodeMCPPath is the user-profile mcp.json, next to the settings.json VS Code discovery uses.
+func vscodeMCPPath(string) (string, error) {
+ settings, err := harness.VSCodeUserSettingsPath()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(filepath.Dir(settings), "mcp.json"), nil
+}
+
+// opencodeConfigPath picks the global config OpenCode's own `opencode mcp add` writes to: an
+// existing opencode.jsonc, else an existing opencode.json, else a new opencode.jsonc.
+func opencodeConfigPath(home string) (string, error) {
+ base := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME"))
+ if base == "" {
+ base = filepath.Join(home, ".config")
+ }
+ dir := filepath.Join(base, "opencode")
+ for _, name := range []string{"opencode.jsonc", "opencode.json"} {
+ if info, err := os.Stat(filepath.Join(dir, name)); err == nil && !info.IsDir() {
+ return filepath.Join(dir, name), nil
+ }
+ }
+ return filepath.Join(dir, "opencode.jsonc"), nil
+}
+
+// NextStep is what the person does after connect for an automatic target.
+func (t Target) NextStep(auth AuthMode, tokenEnv string) string {
+ if auth == AuthTokenEnv {
+ if strings.Contains(t.tokenNext, "%s") {
+ return fmt.Sprintf(t.tokenNext, tokenEnv)
+ }
+ return t.tokenNext
+ }
+ return t.oauthNext
+}
+
+// ManualSteps is what the person does by hand for a manual target.
+func (t Target) ManualSteps(url string) string {
+ if t.manual == nil {
+ return ""
+ }
+ return "Create a token at " + TokenPage + ", then:\n" + t.manual(url)
+}
diff --git a/cli/beacon/internal/mcpconnect/tomledit.go b/cli/beacon/internal/mcpconnect/tomledit.go
new file mode 100644
index 00000000..4c02568b
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/tomledit.go
@@ -0,0 +1,127 @@
+package mcpconnect
+
+import (
+ "fmt"
+ "regexp"
+ "runtime"
+ "strings"
+
+ "github.com/pelletier/go-toml/v2"
+)
+
+// Codex CLI keeps MCP servers in ~/.codex/config.toml as [mcp_servers.<name>] tables. The file
+// also holds the user's model, profile and sandbox settings, so Beacon edits it the way the Kimi
+// Code installer edits config.toml: it appends or removes its own table as lines of text, never
+// re-serializes the document, and parses the result to prove nothing else changed.
+
+func parseTOML(text string) (map[string]any, error) {
+ parsed := map[string]any{}
+ if strings.TrimSpace(text) == "" {
+ return parsed, nil
+ }
+ if err := toml.Unmarshal([]byte(text), &parsed); err != nil {
+ return nil, err
+ }
+ return parsed, nil
+}
+
+// tomlString renders a TOML basic string, double-quoted as Codex's own `codex mcp add` writes it.
+// JSON's string escapes (\" \\ \n \t \uXXXX, and nothing else) are all valid in a TOML basic
+// string, and the parse-back check in verifyConnect confirms the result.
+func tomlString(value string) string {
+ return jsonString(value)
+}
+
+// tomlLineEnding is the line ending the document already uses.
+func tomlLineEnding(text string) string {
+ if strings.Contains(text, "\r\n") {
+ return "\r\n"
+ }
+ if strings.Contains(text, "\n") || runtime.GOOS != "windows" {
+ return "\n"
+ }
+ return "\r\n"
+}
+
+// tomlBlock renders [mcp_servers.<name>] with fields in the order given.
+func tomlBlock(table string, name string, fields []field, eol string) string {
+ var b strings.Builder
+ b.WriteString("[" + table + "." + tomlKey(name) + "]" + eol)
+ for _, f := range fields {
+ b.WriteString(f.Key + " = " + tomlString(fmt.Sprint(f.Value)) + eol)
+ }
+ return b.String()
+}
+
+var bareTOMLKey = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
+
+func tomlKey(name string) string {
+ if bareTOMLKey.MatchString(name) {
+ return name
+ }
+ return tomlString(name)
+}
+
+// tomlHeaderFor matches the header of table.name and of its subtables (for example
+// [mcp_servers.beacon-managed.env]), in any of TOML's quoting styles.
+func tomlHeaderFor(table, name string) *regexp.Regexp {
+ key := `(?:` + regexp.QuoteMeta(name) + `|"` + regexp.QuoteMeta(name) + `"|'` + regexp.QuoteMeta(name) + `')`
+ return regexp.MustCompile(`^\s*\[\s*` + regexp.QuoteMeta(table) + `\s*\.\s*` + key + `\s*(?:\.[^\]]*)?\]\s*(?:#.*)?$`)
+}
+
+var tomlAnyHeader = regexp.MustCompile(`^\s*\[`)
+
+// stripTOMLTable removes every [table.name] block (and its subtables) from text. A block runs
+// from its header to the next header, so its own trailing blank lines go with it; a block at the
+// end of the document also takes the blank lines above it, which is what appendTOMLBlock added.
+// It reports whether any block was found.
+func stripTOMLTable(text, table, name string) (string, bool) {
+ header := tomlHeaderFor(table, name)
+ lines := strings.SplitAfter(text, "\n")
+ var out []string
+ found, skipping := false, false
+ for _, line := range lines {
+ bare := strings.TrimRight(line, "\r\n")
+ if tomlAnyHeader.MatchString(bare) {
+ skipping = header.MatchString(bare)
+ found = found || skipping
+ }
+ if !skipping {
+ out = append(out, line)
+ }
+ }
+ if skipping {
+ for len(out) > 0 && strings.TrimSpace(out[len(out)-1]) == "" {
+ out = out[:len(out)-1]
+ }
+ }
+ return strings.Join(out, ""), found
+}
+
+// appendTOMLBlock adds block at the end of the document, one blank line after existing content.
+func appendTOMLBlock(text, block, eol string) string {
+ trimmed := strings.TrimRight(text, " \t\r\n")
+ if trimmed == "" {
+ return block
+ }
+ return trimmed + eol + eol + block
+}
+
+// endTOMLWithNewline gives a non-empty document exactly one trailing line ending, so a document
+// whose last table was Beacon's does not lose its final newline when the table is removed.
+func endTOMLWithNewline(text, eol string) string {
+ trimmed := strings.TrimRight(text, " \t\r\n")
+ if trimmed == "" {
+ return ""
+ }
+ return trimmed + eol
+}
+
+func tomlTableEntry(parsed map[string]any, table, name string) (map[string]any, bool) {
+ servers, ok := parsed[table].(map[string]any)
+ if !ok {
+ return nil, false
+ }
+ entry, ok := servers[name].(map[string]any)
+ return entry, ok
+}
diff --git a/cli/beacon/internal/mcpconnect/urlcheck.go b/cli/beacon/internal/mcpconnect/urlcheck.go
new file mode 100644
index 00000000..5dcce653
--- /dev/null
+++ b/cli/beacon/internal/mcpconnect/urlcheck.go
@@ -0,0 +1,119 @@
+package mcpconnect
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"
+)
+
+// ErrNoURL means neither --url nor a Beacon Managed connection gives an MCP URL.
+var ErrNoURL = errors.New("no Beacon Managed MCP URL: run `beacon endpoint connect` to connect this endpoint to Beacon Managed, or pass --url")
+
+// ResolveURL picks the MCP URL: the --url flag, else the ingest URL `beacon endpoint connect`
+// recorded plus /mcp, which is where the Beacon Managed backend serves MCP by default. derived
+// reports the second case; CheckURL then accepts the canonical URL the server names for itself.
+func ResolveURL(flag, ingestURL string) (resolved string, derived bool, err error) {
+ if v := strings.TrimSpace(flag); v != "" {
+ return strings.TrimRight(v, "/"), false, nil
+ }
+ if v := strings.TrimSpace(ingestURL); v != "" {
+ return strings.TrimRight(v, "/") + "/mcp", true, nil
+ }
+ return "", false, ErrNoURL
+}
+
+// protectedResource is the part of RFC 9728 resource metadata Beacon reads.
+type protectedResource struct {
+ Resource string `json:"resource"`
+ AuthorizationServers []string `json:"authorization_servers"`
+}
+
+// resourceMetadataURL is <origin>/.well-known/oauth-protected-resource, the document the server
+// names in its 401 challenge.
+func resourceMetadataURL(mcpURL string) (string, error) {
+ u, err := url.Parse(mcpURL)
+ if err != nil || u.Host == "" {
+ return "", fmt.Errorf("%q is not a URL", mcpURL)
+ }
+ return u.Scheme + "://" + u.Host + "/.well-known/oauth-protected-resource", nil
+}
+
+// CheckURL confirms that mcpURL is a Beacon Managed MCP server before anything is written: its
+// origin must serve resource metadata whose "resource" is mcpURL. This is `beacon mcp connect`'s
+// only network request (two when a derived URL is replaced by the canonical one), and nothing is
+// sent with it -- no token, no cookie.
+//
+// A derived URL (the ingest URL plus /mcp) may be answered with a different canonical URL: the
+// backend can serve MCP on its own host, and names that host as the resource. The canonical URL is
+// then checked the same way and used instead. An explicit --url must match exactly, so a typo is
+// reported rather than silently corrected.
+func CheckURL(ctx context.Context, client *http.Client, mcpURL string, derived bool) (string, error) {
+ resource, err := fetchResource(ctx, client, mcpURL)
+ if err != nil {
+ return "", err
+ }
+ if sameURL(resource, mcpURL) {
+ return mcpURL, nil
+ }
+ if !derived {
+ return "", fmt.Errorf("%s is not the MCP URL this server advertises; it names %s. Pass --url %s", mcpURL, resource, resource)
+ }
+ canonical := strings.TrimRight(resource, "/")
+ again, err := fetchResource(ctx, client, canonical)
+ if err != nil {
+ return "", fmt.Errorf("the server at %s names %s as its MCP URL, but checking that failed: %w", mcpURL, canonical, err)
+ }
+ if !sameURL(again, canonical) {
+ return "", fmt.Errorf("the server at %s names %s as its MCP URL, and that names %s; pass --url explicitly", mcpURL, canonical, again)
+ }
+ return canonical, nil
+}
+
+func fetchResource(ctx context.Context, client *http.Client, mcpURL string) (string, error) {
+ if !asymptote.IsSecureURL(mcpURL) {
+ return "", fmt.Errorf("%s must use https:// (plain http is allowed only for a loopback development server)", mcpURL)
+ }
+ metadataURL, err := resourceMetadataURL(mcpURL)
+ if err != nil {
+ return "", err
+ }
+ if client == nil {
+ client = &http.Client{Timeout: 10 * time.Second}
+ }
+ // Never follow a redirect: the check is about this origin, and a redirect could send the
+ // request somewhere the person did not name.
+ c := *client
+ c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, metadataURL, nil)
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Accept", "application/json")
+ resp, err := c.Do(req)
+ if err != nil {
+ return "", fmt.Errorf("could not reach %s: %w", metadataURL, err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("%s answered HTTP %d; it does not look like a Beacon Managed MCP server", metadataURL, resp.StatusCode)
+ }
+ var meta protectedResource
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&meta); err != nil {
+ return "", fmt.Errorf("%s did not return resource metadata JSON: %w", metadataURL, err)
+ }
+ if strings.TrimSpace(meta.Resource) == "" {
+ return "", fmt.Errorf("%s has no \"resource\"", metadataURL)
+ }
+ if !asymptote.IsSecureURL(meta.Resource) {
+ return "", fmt.Errorf("%s names an insecure resource %q", metadataURL, meta.Resource)
+ }
+ return meta.Resource, nil
+}