The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
fix(harness): read commented vs code settings in telemetry status (#1061)
Rudy Mizrahi Celekli3761a8780f77
diff --git a/cli/beacon/internal/endpoint/harness/vscode.go b/cli/beacon/internal/endpoint/harness/vscode.goindex e4a5bf99..3cfb8cb8 100644--- a/cli/beacon/internal/endpoint/harness/vscode.go+++ b/cli/beacon/internal/endpoint/harness/vscode.go@@ -1,13 +1,14 @@package harnessimport (- "encoding/json""fmt""net/url""os""path/filepath""runtime""strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/jsonc")const (@@ -113,9 +114,12 @@ func ConfigureVSCode(opts VSCodeConfigOptions) (string, error) {if err != nil {return "", err}- settings := map[string]interface{}{}+ // settings.json is JSONC that people edit by hand. Each key is set in place so the rest of the+ // file, comments included, stays exactly as it was.+ text := ""if data, err := os.ReadFile(path); err == nil {- if err := json.Unmarshal(data, &settings); err != nil {+ text = string(data)+ if _, err := jsonc.Decode(text); err != nil {return "", fmt.Errorf("VS Code settings JSON is invalid: %w", err)}if err := backup(path, data); err != nil {@@ -124,19 +128,22 @@ func ConfigureVSCode(opts VSCodeConfigOptions) (string, error) {} else if !os.IsNotExist(err) {return "", err}- settings["github.copilot.chat.otel.enabled"] = true- settings["github.copilot.chat.otel.exporterType"] = "otlp-http"- settings["github.copilot.chat.otel.otlpEndpoint"] = opts.Endpoint- settings["github.copilot.chat.otel.captureContent"] = opts.CaptureContent- settings["github.copilot.chat.otel.maxAttributeSizeChars"] = 8192- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {- return "", err+ beaconSettings := jsonc.Ordered{+ {Key: "github.copilot.chat.otel.enabled", Value: true},+ {Key: "github.copilot.chat.otel.exporterType", Value: "otlp-http"},+ {Key: "github.copilot.chat.otel.otlpEndpoint", Value: opts.Endpoint},+ {Key: "github.copilot.chat.otel.captureContent", Value: opts.CaptureContent},+ {Key: "github.copilot.chat.otel.maxAttributeSizeChars", Value: 8192},}- data, err := json.MarshalIndent(settings, "", " ")- if err != nil {+ for _, f := range beaconSettings {+ if text, err = jsonc.SetMember(text, nil, f.Key, f.Value); err != nil {+ return "", fmt.Errorf("cannot update VS Code settings %s: %w", path, err)+ }+ }+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {return "", err}- return path, os.WriteFile(path, data, 0600)+ return path, os.WriteFile(path, []byte(text), 0600)}func VSCodeOTelStatus(path, expectedEndpoint string) (TelemetryStatus, string) {@@ -150,8 +157,8 @@ func VSCodeOTelStatus(path, expectedEndpoint string) (TelemetryStatus, string) {}return TelemetryMissing, err.Error()}- var settings map[string]interface{}- if err := json.Unmarshal(data, &settings); err != nil {+ settings, err := jsonc.Decode(string(data))+ if err != nil {return TelemetryMisconfigured, "VS Code settings JSON is invalid"}if vscodeSettingString(settings, "github.copilot.chat.otel.exporterType") == "file" ||diff --git a/cli/beacon/internal/endpoint/harness/vscode_test.go b/cli/beacon/internal/endpoint/harness/vscode_test.goindex 793755c6..07040fde 100644--- a/cli/beacon/internal/endpoint/harness/vscode_test.go+++ b/cli/beacon/internal/endpoint/harness/vscode_test.go@@ -45,7 +45,7 @@ func TestConfigureVSCodePreservesSettingsAndDisablesContentCaptureByDefault(t *tif err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {t.Fatal(err)}- existing := `{"editor.formatOnSave":true}`+ existing := "{\n \"editor.formatOnSave\": true\n}\n"if err := os.WriteFile(path, []byte(existing), 0600); err != nil {t.Fatal(err)}@@ -82,6 +82,57 @@ func TestConfigureVSCodePreservesSettingsAndDisablesContentCaptureByDefault(t *t}}+// Setup sets Beacon's keys in place: a hand-edited settings.json keeps its comments, trailing+// commas, order and indentation, and a value already there is replaced where it stands.+func TestConfigureVSCodeKeepsACommentedSettingsFile(t *testing.T) {+ home := t.TempDir()+ isolateUserConfig(t, home)+ path := vscodeSettingsPathForTest(home)+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ t.Fatal(err)+ }+ existing := `{+ // Editor+ "editor.fontSize": 13,+ /* Copilot: telemetry off until Beacon is set up */+ "github.copilot.chat.otel.enabled": false,+ "files.exclude": {+ "**/.git": true, // keep+ },+}+`+ if err := os.WriteFile(path, []byte(existing), 0600); err != nil {+ t.Fatal(err)+ }+ if _, err := ConfigureVSCode(VSCodeConfigOptions{Endpoint: "http://127.0.0.1:54318"}); err != nil {+ t.Fatalf("ConfigureVSCode returned error: %v", err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ want := `{+ // Editor+ "editor.fontSize": 13,+ /* Copilot: telemetry off until Beacon is set up */+ "github.copilot.chat.otel.enabled": true,+ "files.exclude": {+ "**/.git": true, // keep+ },+ "github.copilot.chat.otel.exporterType": "otlp-http",+ "github.copilot.chat.otel.otlpEndpoint": "http://127.0.0.1:54318",+ "github.copilot.chat.otel.captureContent": false,+ "github.copilot.chat.otel.maxAttributeSizeChars": 8192,+}+`+ if string(data) != want {+ t.Fatalf("settings.json =\n%s\nwant\n%s", data, want)+ }+ if status, msg := VSCodeOTelStatus(path, "http://127.0.0.1:54318"); status != TelemetryEnabled {+ t.Fatalf("status after setup = %s msg=%s, want enabled", status, msg)+ }+}+func TestVSCodeOTelStatus(t *testing.T) {path := filepath.Join(t.TempDir(), "settings.json")if err := os.WriteFile(path, []byte(`{"github.copilot.chat.otel.enabled":true,"github.copilot.chat.otel.otlpEndpoint":"http://127.0.0.1:4318"}`), 0600); err != nil {@@ -101,6 +152,37 @@ func TestVSCodeOTelStatus(t *testing.T) {}}+// VS Code's settings.json is JSONC: comments and trailing commas are legal there, and a+// hand-edited one usually has some.+func TestVSCodeOTelStatusReadsJSONC(t *testing.T) {+ path := filepath.Join(t.TempDir(), "settings.json")+ body := `{+ // Copilot telemetry goes to Beacon.+ "github.copilot.chat.otel.enabled": true,+ /* local receiver, see "beacon endpoint status" */+ "github.copilot.chat.otel.otlpEndpoint": "http://127.0.0.1:4318",+ "editor.rulers": [80, 120,],+ "files.exclude": {"**/*.min.js": true,},+ "url.note": "http://example.com/a//b, not a comment",+}+`+ if err := os.WriteFile(path, []byte(body), 0600); err != nil {+ t.Fatal(err)+ }+ if status, msg := VSCodeOTelStatus(path, "http://127.0.0.1:4318"); status != TelemetryEnabled {+ t.Fatalf("status = %s msg=%s, want enabled", status, msg)+ }+ // A commented-out key is not a setting, and an empty file is VS Code's empty settings.+ for _, doc := range []string{"{\n // \"github.copilot.chat.otel.enabled\": true,\n}\n", ""} {+ if err := os.WriteFile(path, []byte(doc), 0600); err != nil {+ t.Fatal(err)+ }+ if status, msg := VSCodeOTelStatus(path, "http://127.0.0.1:4318"); status != TelemetryDisabled {+ t.Fatalf("%q: status = %s msg=%s, want disabled", doc, status, msg)+ }+ }+}+// vscodeSettingsPathForTest mirrors vscodeUserDataDirsForOS so these tests exercise the real// per-platform layout.// isolateUserConfig points every user-config lookup at a temporary home.diff --git a/cli/beacon/internal/mcpconnect/jsonedit.go b/cli/beacon/internal/jsonc/edit.gosimilarity index 73%rename from cli/beacon/internal/mcpconnect/jsonedit.gorename to cli/beacon/internal/jsonc/edit.goindex 5bcb610f..ff045eea 100644--- a/cli/beacon/internal/mcpconnect/jsonedit.go+++ b/cli/beacon/internal/jsonc/edit.go@@ -1,4 +1,4 @@-package mcpconnect+package jsoncimport ("bytes"@@ -7,17 +7,17 @@ import ("strings")-// ordered is a JSON object whose keys are written in the order given, so the entry Beacon adds+// 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 Ordered []Field-type field struct {+type Field struct {Key stringValue any}-// rawJSON is a value inserted exactly as written, such as an entry's original text.-type rawJSON string+// Raw is a value inserted exactly as written, such as an entry's original text.+type Raw string// jsonStyle is the formatting an edit copies from the document it goes into.type jsonStyle struct {@@ -56,7 +56,8 @@ func (s jsonStyle) indent(depth int) string {return strings.Repeat(s.unit, depth)}-func jsonString(value string) string {+// Quote renders value as a JSON string, leaving <, > and & unescaped.+func Quote(value string) string {var buf bytes.Bufferencoder := json.NewEncoder(&buf)encoder.SetEscapeHTML(false)@@ -68,15 +69,15 @@ func jsonString(value string) string {// indentation, or on one line when the surrounding object is written on one line.func renderJSON(value any, style jsonStyle, depth int, compact bool, sep string) string {switch v := value.(type) {- case rawJSON:+ case Raw:return string(v)- case ordered:+ 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)+ parts[i] = Quote(f.Key) + sep + renderJSON(f.Value, style, depth+1, compact, sep)}if compact {return "{" + strings.Join(parts, ",") + "}"@@ -97,7 +98,7 @@ func renderJSON(value any, style jsonStyle, depth int, compact bool, sep string)inner := style.eol + style.indent(depth+1)return "[" + inner + strings.Join(parts, ","+inner) + style.eol + style.indent(depth) + "]"case string:- return jsonString(v)+ return Quote(v)case bool:if v {return "true"@@ -110,14 +111,30 @@ func renderJSON(value any, style jsonStyle, depth int, compact bool, sep string)}// renderJSONDocument writes a new document holding only value.-func renderJSONDocument(value ordered, style jsonStyle) string {+func renderJSONDocument(value Ordered, style jsonStyle) string {return renderJSON(value, style, 0, false, ": ") + style.eol}+// NewDocument writes a new document holding only value, indented and line-ended like the text it+// replaces.+func NewDocument(value Ordered, like string) string {+ return renderJSONDocument(value, detectJSONStyle(like))+}++// Normalize turns a value into what Decode produces for it.+func Normalize(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+}+// 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}}+ value = Ordered{{Key: path[i], Value: value}}}return value}@@ -150,7 +167,7 @@ func isCompact(text string, n *jsonNode, items []span) bool {// 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]+ between := text[m.keyStart+len(Quote(m.key)) : m.value.start]if strings.TrimSpace(between) == ":" {if strings.HasPrefix(strings.TrimLeft(between, " \t"), ":") && strings.HasSuffix(between, ":") {return ":"@@ -247,17 +264,34 @@ func lookupObject(root *jsonNode, path []string) (chain []*jsonNode, err error)return chain, nil}-// insertJSONMember returns text with path.key set to value. key must not already exist. Objects+// CheckPath reports a shape the editors refuse to work around: a segment of path that is not an+// object or appears more than once, or key appearing more than once in the object at path.+func CheckPath(text string, path []string, key string) error {+ root, err := parseJSONC(text)+ if err != nil || root == nil {+ return err+ }+ chain, err := lookupObject(root, path)+ if err != nil {+ return err+ }+ if len(chain) == len(path)+1 && chain[len(chain)-1].memberCount(key) > 1 {+ return &jsonPathError{fmt.Sprintf("%q appears more than once", key)}+ }+ return nil+}++// InsertMember 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) {+func InsertMember(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)+ 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}@@ -273,19 +307,46 @@ func insertJSONMember(text string, path []string, key string, value any) (updateinsertKey, insertValue := key, valueif len(missing) > 0 {insertKey = missing[0]- insertValue = nest(missing[1:], ordered{{Key: key, Value: value}})+ 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)+ rendered := Quote(insertKey) + sep + renderJSON(insertValue, style, parent.depth+1, compact, sep)return insertItem(text, parent, items, rendered, style), len(missing), nil}-// rawMember returns the original text of path.key's value, as JSON with comments stripped.-func rawMember(text string, path []string, key string) (string, bool) {+// SetMember returns text with path.key set to value. An existing value is replaced where it+// stands, keeping the member's position and everything around it; a missing one is added as+// InsertMember adds it.+func SetMember(text string, path []string, key string, value any) (string, error) {+ root, err := parseJSONC(text)+ if err != nil {+ return "", err+ }+ if root != nil && root.kind == jsonObject {+ chain, err := lookupObject(root, path)+ if err != nil {+ return "", err+ }+ if parent := chain[len(chain)-1]; len(chain) == len(path)+1 && parent.memberCount(key) > 0 {+ if parent.memberCount(key) > 1 {+ return "", &jsonPathError{fmt.Sprintf("%q appears more than once", key)}+ }+ _, old := parent.member(key)+ compact := isCompact(text, parent, memberSpans(parent))+ rendered := renderJSON(value, detectJSONStyle(text), old.depth, compact, keySeparator(text, parent))+ return text[:old.start] + rendered + text[old.end:], nil+ }+ }+ updated, _, err := InsertMember(text, path, key, value)+ return updated, err+}++// RawMember returns the original text of path.key's value, as JSON with comments stripped.+func RawMember(text string, path []string, key string) (string, bool) {root, err := parseJSONC(text)if err != nil || root == nil || root.kind != jsonObject {return "", false@@ -303,9 +364,9 @@ func rawMember(text string, path []string, key string) (string, bool) {return buf.String(), true}-// removeJSONMember returns text without path.key. prune is how many of the innermost path objects+// RemoveMember 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) {+func RemoveMember(text string, path []string, key string, prune int) (string, error) {root, err := parseJSONC(text)if err != nil {return "", err@@ -338,15 +399,15 @@ func removeJSONMember(text string, path []string, key string, prune int) (stringreturn removeItem(text, target, memberSpans(target), index), nil}-// appendJSONElement returns text with value appended to the array at path.key, creating the+// AppendElement 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) {+func AppendElement(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})+ updated, _, err := InsertMember(text, path, key, []any{value})return updated, true, err}chain, err := lookupObject(root, path)@@ -354,7 +415,7 @@ func appendJSONElement(text string, path []string, key string, value any) (strinreturn "", false, err}if len(chain) != len(path)+1 || chain[len(chain)-1].memberCount(key) == 0 {- updated, _, err := insertJSONMember(text, path, key, []any{value})+ updated, _, err := InsertMember(text, path, key, []any{value})return updated, true, err}parent := chain[len(chain)-1]@@ -372,9 +433,9 @@ func appendJSONElement(text string, path []string, key string, value any) (strinreturn insertItem(text, arr, items, rendered, style), false, nil}-// removeJSONElements returns text without the elements of the array at path.key that match. With+// RemoveElements 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) {+func RemoveElements(text string, path []string, key string, match func(any) bool, prune bool) (string, error) {for {root, err := parseJSONC(text)if err != nil {diff --git a/cli/beacon/internal/mcpconnect/jsonc.go b/cli/beacon/internal/jsonc/jsonc.gosimilarity index 90%rename from cli/beacon/internal/mcpconnect/jsonc.gorename to cli/beacon/internal/jsonc/jsonc.goindex b3dcecec..4a64df5c 100644--- a/cli/beacon/internal/mcpconnect/jsonc.go+++ b/cli/beacon/internal/jsonc/jsonc.go@@ -1,4 +1,11 @@-package mcpconnect+// Package jsonc reads and edits the JSON configs that harnesses share with the people who use them.+//+// Several of those configs (OpenCode's opencode.jsonc, VS Code's settings.json and 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 package 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.+package jsoncimport ("bytes"@@ -7,14 +14,6 @@ import ("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 byteconst (@@ -272,10 +271,10 @@ func (p *jsonParser) array(depth int) (*jsonNode, error) {}}-// decodeJSONC parses a JSON or JSONC document into plain Go values, the way the harness reads it.+// Decode 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) {+func Decode(text string) (map[string]any, error) {root, err := parseJSONC(text)if err != nil {return nil, errdiff --git a/cli/beacon/internal/mcpconnect/jsonc_test.go b/cli/beacon/internal/jsonc/jsonc_test.gosimilarity index 54%rename from cli/beacon/internal/mcpconnect/jsonc_test.gorename to cli/beacon/internal/jsonc/jsonc_test.goindex f600acaf..639f5160 100644--- a/cli/beacon/internal/mcpconnect/jsonc_test.go+++ b/cli/beacon/internal/jsonc/jsonc_test.go@@ -1,4 +1,4 @@-package mcpconnect+package jsoncimport ("reflect"@@ -16,11 +16,11 @@ func TestDecodeJSONCMatchesStrictJSONWithoutComments(t *testing.T) {"list": [1, 2, 3,],"nested": {"a": true,},}`- got, err := decodeJSONC(doc)+ got, err := Decode(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}}`)+ want, err := Decode(`{"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)}@@ -41,25 +41,27 @@ func TestParseJSONCRejectsMalformedDocuments(t *testing.T) {`{"a": 1} trailing`,`{,}`,} {- if _, err := decodeJSONC(doc); err == nil {- t.Errorf("decodeJSONC(%q) accepted a malformed document", doc)+ if _, err := Decode(doc); err == nil {+ t.Errorf("Decode(%q) accepted a malformed document", doc)}}}func TestDecodeJSONCTreatsBlankAsEmptyObjectAndRejectsNonObjects(t *testing.T) {for _, doc := range []string{"", " \n", "// only a comment\n"} {- got, err := decodeJSONC(doc)+ got, err := Decode(doc)if err != nil || len(got) != 0 {- t.Errorf("decodeJSONC(%q) = %v, %v; want an empty object", doc, got, err)+ t.Errorf("Decode(%q) = %v, %v; want an empty object", doc, got, err)}}- if _, err := decodeJSONC(`[1, 2]`); err == nil {+ if _, err := Decode(`[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"}}+const entryName = "beacon-managed"++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@@ -86,20 +88,25 @@ func TestInsertThenRemoveJSONMemberIsTheIdentity(t *testing.T) {}for name, doc := range docs {t.Run(name, func(t *testing.T) {- inserted, created, err := insertJSONMember(doc, []string{"mcpServers"}, ServerName, beaconEntry)+ inserted, created, err := InsertMember(doc, []string{"mcpServers"}, entryName, beaconEntry)if err != nil {t.Fatal(err)}- before, _ := decodeJSONC(doc)- after, err := decodeJSONC(inserted)+ before, _ := Decode(doc)+ after, err := Decode(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)) {+ servers, _ := before["mcpServers"].(map[string]any)+ if servers == nil {+ servers = map[string]any{}+ before["mcpServers"] = servers+ }+ servers[entryName] = Normalize(beaconEntry)+ if !reflect.DeepEqual(before, after) {t.Fatalf("insertion changed more than the entry:\n%s", inserted)}- removed, err := removeJSONMember(inserted, []string{"mcpServers"}, ServerName, created)+ removed, err := RemoveMember(inserted, []string{"mcpServers"}, entryName, created)if err != nil {t.Fatal(err)}@@ -130,7 +137,7 @@ func TestInsertJSONMemberCopiesTheDocumentsFormatting(t *testing.T) {}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {- got, _, err := insertJSONMember(tc.doc, []string{"mcpServers"}, ServerName, beaconEntry)+ got, _, err := InsertMember(tc.doc, []string{"mcpServers"}, entryName, beaconEntry)if err != nil {t.Fatal(err)}@@ -149,14 +156,14 @@ func TestJSONEditRefusesShapesItCannotEditSafely(t *testing.T) {"root is an array": `[]`,}for name, doc := range cases {- if _, _, err := insertJSONMember(doc, []string{"mcpServers"}, ServerName, beaconEntry); err == nil {+ if _, _, err := InsertMember(doc, []string{"mcpServers"}, entryName, beaconEntry); err == nil {t.Errorf("%s: insert accepted %q", name, doc)}}- if _, _, err := insertJSONMember(`{"mcpServers": {"beacon-managed": {}}}`, []string{"mcpServers"}, ServerName, beaconEntry); err == nil {+ if _, _, err := InsertMember(`{"mcpServers": {"beacon-managed": {}}}`, []string{"mcpServers"}, entryName, 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 {+ if _, err := RemoveMember(`{"mcpServers": {"beacon-managed": {}, "beacon-managed": {}}}`, []string{"mcpServers"}, entryName, 0); err == nil {t.Error("removal of a duplicated key was accepted")}}@@ -170,7 +177,7 @@ func TestRemoveJSONMemberHandlesEntriesItDidNotPosition(t *testing.T) {{"no container", `{"a": 1}`, `{"a": 1}`},}for _, tc := range cases {- got, err := removeJSONMember(tc.doc, []string{"s"}, ServerName, 0)+ got, err := RemoveMember(tc.doc, []string{"s"}, entryName, 0)if err != nil {t.Fatalf("%s: %v", tc.name, err)}@@ -182,87 +189,69 @@ func TestRemoveJSONMemberHandlesEntriesItDidNotPosition(t *testing.T) {func TestPruneRemovesOnlyContainersLeftEmpty(t *testing.T) {doc := "{\n \"a\": 1\n}\n"- inserted, created, err := insertJSONMember(doc, []string{"mcp", "servers"}, ServerName, beaconEntry)+ inserted, created, err := InsertMember(doc, []string{"mcp", "servers"}, entryName, 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"}})+ shared, _, err := InsertMember(inserted, []string{"mcp", "servers"}, "theirs", Ordered{{"url", "https://t"}})if err != nil {t.Fatal(err)}- got, err := removeJSONMember(shared, []string{"mcp", "servers"}, ServerName, created)+ got, err := RemoveMember(shared, []string{"mcp", "servers"}, entryName, created)if err != nil {t.Fatal(err)}- if !strings.Contains(got, `"theirs"`) || strings.Contains(got, ServerName) {+ if !strings.Contains(got, `"theirs"`) || strings.Contains(got, entryName) {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)+// SetMember replaces a value where it stands, so the comments, order and layout around it survive,+// and adds a missing member the way InsertMember does.+func TestSetMemberReplacesInPlaceOrAppends(t *testing.T) {+ cases := []struct {+ name, doc, key string+ value any+ want string+ }{+ {+ "replace keeps comments and position",+ "{\n // mine\n \"a\": \"old\", /* why */\n \"b\": 1,\n}\n",+ "a", "new",+ "{\n // mine\n \"a\": \"new\", /* why */\n \"b\": 1,\n}\n",+ },+ {+ "replace with another type",+ `{"a": true, "b": 1}`,+ "b", false,+ `{"a": true, "b": false}`,+ },+ {+ "missing key is appended",+ "{\n \"a\": 1 // keep\n}\n",+ "b", 8192,+ "{\n \"a\": 1,\n \"b\": 8192 // keep\n}\n",+ },+ {+ "blank document",+ "",+ "a", true,+ "{\n \"a\": true\n}\n",+ },+ }+ for _, tc := range cases {+ got, err := SetMember(tc.doc, nil, tc.key, tc.value)if err != nil {- t.Fatal(err)+ t.Fatalf("%s: %v", tc.name, err)}- if back != doc {- t.Errorf("array round trip\n doc: %q\n app: %q\n got: %q", doc, appended, back)+ if got != tc.want {+ t.Errorf("%s:\n got %q\nwant %q", tc.name, got, tc.want)}}-}--// 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)+ for _, doc := range []string{`{"a": 1, "a": 2}`, `[]`, `{"a": 1`} {+ if _, err := SetMember(doc, nil, "a", 3); err == nil {+ t.Errorf("SetMember accepted %q", doc)}}- 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/cli_url_test.go b/cli/beacon/internal/mcpconnect/cli_url_test.goindex b58b1db9..158b42bf 100644--- a/cli/beacon/internal/mcpconnect/cli_url_test.go+++ b/cli/beacon/internal/mcpconnect/cli_url_test.go@@ -13,6 +13,8 @@ import ("strings""sync/atomic""testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/jsonc")// fakeClaude stands in for `claude mcp add/remove --scope user`, editing ~/.claude.json the way@@ -129,7 +131,7 @@ func TestDisconnectFallsBackToTheFileWhenTheCLIIsGone(t *testing.T) {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))+ got, _ := jsonc.Decode(readFile(t, fake.path))if servers, _ := got["mcpServers"].(map[string]any); servers[ServerName] != nil {t.Fatal("the entry survived disconnect without the CLI")}@@ -254,7 +256,7 @@ func TestClaudeCLIFailedAddRestoresTheEntryItRemoved(t *testing.T) {if headers, _ := st.entry["headers"].(map[string]any); headers["X-Team"] != "a" {t.Fatalf("the restored entry lost fields: %+v", st.entry)}- got, _ := decodeJSONC(readFile(t, fake.path))+ got, _ := jsonc.Decode(readFile(t, fake.path))if got["numStartups"] == nil {t.Fatal("restoring the entry dropped other state")}diff --git a/cli/beacon/internal/mcpconnect/edit_test.go b/cli/beacon/internal/mcpconnect/edit_test.gonew file mode 100644index 00000000..a48eee27--- /dev/null+++ b/cli/beacon/internal/mcpconnect/edit_test.go@@ -0,0 +1,74 @@+package mcpconnect++import (+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/jsonc"+)++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 := jsonc.AppendElement(doc, nil, "inputs", vscodeInput())+ if err != nil {+ t.Fatal(err)+ }+ back, err := jsonc.RemoveElements(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/engine.go b/cli/beacon/internal/mcpconnect/engine.goindex 4bfc2c61..2deeaf9e 100644--- a/cli/beacon/internal/mcpconnect/engine.go+++ b/cli/beacon/internal/mcpconnect/engine.go@@ -10,6 +10,8 @@ import ("reflect""strings""time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/jsonc")// Action is what connect will do, or did, for one target.@@ -134,19 +136,12 @@ func inspect(t Target, path string) (state, error) {if t.strictJSON && strings.TrimSpace(cf.text) != "" && !json.Valid([]byte(cf.text)) {return st, fmt.Errorf("%s is not plain JSON; %s ignores a config with comments or trailing commas, so Beacon leaves it alone", path, t.DisplayName)}- parsed, err := decodeJSONC(cf.text)+ parsed, err := jsonc.Decode(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)- }+ if err := jsonc.CheckPath(cf.text, t.container, ServerName); err != nil {+ return st, fmt.Errorf("%s: %v", path, err)}container := dig(parsed, t.container)if raw, ok := container[ServerName]; ok {@@ -160,7 +155,7 @@ func inspect(t Target, path string) (state, error) {for _, input := range inputList(parsed) {if id, _ := input["id"].(string); id == vscodeInputID {st.inputHas = true- st.inputOK = reflect.DeepEqual(input, normalizeJSON(vscodeInput()))+ st.inputOK = reflect.DeepEqual(input, jsonc.Normalize(vscodeInput()))}}}@@ -194,25 +189,15 @@ func inputList(doc map[string]any) []map[string]any {return out}-func vscodeInput() ordered {- return ordered{- {"type", "promptString"},- {"id", vscodeInputID},- {"description", "Beacon Cloud MCP token (" + TokenPage + ")"},- {"password", true},+func vscodeInput() jsonc.Ordered {+ return jsonc.Ordered{+ {Key: "type", Value: "promptString"},+ {Key: "id", Value: vscodeInputID},+ {Key: "description", Value: "Beacon Cloud MCP token (" + TokenPage + ")"},+ {Key: "password", Value: 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), "/")}@@ -221,7 +206,7 @@ func sameURL(a, b string) bool {// value from the existing entry where the harness switches a server off that way. Turning// beacon-managed off in the harness is the person's decision, and re-running connect must not undo// it.-func (t Target) desiredEntry(opts Options, existing map[string]any) ordered {+func (t Target) desiredEntry(opts Options, existing map[string]any) jsonc.Ordered {entry := t.entry(opts.URL, opts.TokenEnv)enabled, ok := existing["enabled"].(bool)if !t.switchable || !ok {@@ -233,7 +218,7 @@ func (t Target) desiredEntry(opts Options, existing map[string]any) ordered {return entry}}- return append(entry, field{"enabled", enabled})+ return append(entry, jsonc.Field{Key: "enabled", Value: enabled})}// Plan works out what connect would do for each target without writing anything.@@ -275,8 +260,8 @@ func planOne(opts Options, m *manifest, t Target) Item {it.ExistingURL = st.urlrec, recorded := m.find(t.Name, path)ours := recorded && st.exists && sameURL(st.url, rec.URL)- want := normalizeJSON(t.desiredEntry(opts, st.entry))- same := st.exists && reflect.DeepEqual(normalizeJSON(st.entry), want)+ want := jsonc.Normalize(t.desiredEntry(opts, st.entry))+ same := st.exists && reflect.DeepEqual(jsonc.Normalize(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"@@ -411,24 +396,24 @@ func editForConnect(t Target, text string, st state, opts Options) (updated stri}updated = textif strings.TrimSpace(updated) == "" && len(t.skeleton) > 0 {- updated = renderJSONDocument(t.skeleton, detectJSONStyle(text))+ updated = jsonc.NewDocument(t.skeleton, text)}if st.exists {- if updated, err = removeJSONMember(updated, t.container, ServerName, 0); err != nil {+ if updated, err = jsonc.RemoveMember(updated, t.container, ServerName, 0); err != nil {return "", 0, false, err}}- if updated, created, err = insertJSONMember(updated, t.container, ServerName, entry); err != nil {+ if updated, created, err = jsonc.InsertMember(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 {+ if updated, err = jsonc.RemoveElements(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 {+ if updated, createdInputs, err = jsonc.AppendElement(updated, nil, "inputs", vscodeInput()); err != nil {return "", 0, false, err}}@@ -459,15 +444,15 @@ func verifyConnect(t Target, before, after string, opts Options) error {existing, _ := dig(b, t.container)[ServerName].(map[string]any)if strings.TrimSpace(before) == "" && len(t.skeleton) > 0 {for _, f := range t.skeleton {- b[f.Key] = normalizeJSON(f.Value)+ b[f.Key] = jsonc.Normalize(f.Value)}}- setPath(b, t.container, ServerName, normalizeJSON(t.desiredEntry(opts, existing)))+ setPath(b, t.container, ServerName, jsonc.Normalize(t.desiredEntry(opts, existing)))if t.vscodeInputs {dropBeaconInputs(b)if opts.TokenEnv != "" {list, _ := b["inputs"].([]any)- b["inputs"] = append(list, normalizeJSON(vscodeInput()))+ b["inputs"] = append(list, jsonc.Normalize(vscodeInput()))}}if !reflect.DeepEqual(normalizeValue(b), normalizeValue(a)) {@@ -511,7 +496,7 @@ func dropEmptyTable(doc map[string]any, key string) {}func parseBoth(t Target, before, after string) (map[string]any, map[string]any, error) {- parse := decodeJSONC+ parse := jsonc.Decodeif t.format == formatTOML {parse = parseTOML}@@ -599,7 +584,7 @@ func applyCLI(ctx context.Context, opts Options, it Item, st state, rec Record)// failed add can put it back rather than leave the harness with no server at all.var removed stringif st.exists {- removed, _ = rawMember(st.file.text, it.Target.container, ServerName)+ removed, _ = jsonc.RawMember(st.file.text, it.Target.container, ServerName)if out, err := opts.run(ctx, it.cliPath, "mcp", "remove", ServerName, "--scope", "user"); err != nil {return Record{}, fmt.Errorf("`%s mcp remove` failed: %v: %s", it.Target.cli, err, strings.TrimSpace(string(out)))}@@ -624,8 +609,8 @@ func applyCLI(ctx context.Context, opts Options, it Item, st state, rec Record)if err != nil {return fail(err)}- want := normalizeJSON(it.Target.entry(opts.URL, opts.TokenEnv))- if !after.exists || !reflect.DeepEqual(normalizeJSON(after.entry), want) {+ want := jsonc.Normalize(it.Target.entry(opts.URL, opts.TokenEnv))+ if !after.exists || !reflect.DeepEqual(jsonc.Normalize(after.entry), want) {return fail(fmt.Errorf("`%s mcp add` ran, but %s does not hold the expected %s entry", it.Target.cli, it.Path, ServerName))}return rec, nil@@ -641,7 +626,7 @@ func restoreMember(t Target, path, raw string) error {if st.exists {return fmt.Errorf("%s already holds a %s entry", path, ServerName)}- updated, _, err := insertJSONMember(st.file.text, t.container, ServerName, rawJSON(raw))+ updated, _, err := jsonc.InsertMember(st.file.text, t.container, ServerName, jsonc.Raw(raw))if err != nil {return err}@@ -793,12 +778,12 @@ func editForDisconnect(t Target, text string, rec Record) (string, error) {}return endTOMLWithNewline(stripped, tomlLineEnding(text)), nil}- updated, err := removeJSONMember(text, t.container, ServerName, rec.CreatedParents)+ updated, err := jsonc.RemoveMember(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 {+ if updated, err = jsonc.RemoveElements(updated, nil, "inputs", isBeaconInput, rec.CreatedInputs); err != nil {return "", err}}@@ -807,7 +792,7 @@ func editForDisconnect(t Target, text string, rec Record) (string, error) {// onlySkeleton reports whether a config Beacon created holds nothing but what Beacon put there.func onlySkeleton(t Target, text string) bool {- parse := decodeJSONC+ parse := jsonc.Decodeif t.format == formatTOML {parse = parseTOML}@@ -816,7 +801,7 @@ func onlySkeleton(t Target, text string) bool {return false}for _, f := range t.skeleton {- if reflect.DeepEqual(doc[f.Key], normalizeJSON(f.Value)) {+ if reflect.DeepEqual(doc[f.Key], jsonc.Normalize(f.Value)) {delete(doc, f.Key)}}diff --git a/cli/beacon/internal/mcpconnect/harness_test.go b/cli/beacon/internal/mcpconnect/harness_test.goindex bea73cce..91674e43 100644--- a/cli/beacon/internal/mcpconnect/harness_test.go+++ b/cli/beacon/internal/mcpconnect/harness_test.go@@ -10,6 +10,7 @@ import ("testing""time"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/jsonc""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv")@@ -986,13 +987,13 @@ func TestCreatedFileIsKeptWhenTheUserAddedToIt(t *testing.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"}})+ withTheirs, _, err := jsonc.InsertMember(readFile(t, path), []string{"mcp"}, "theirs", jsonc.Ordered{{Key: "type", Value: "remote"}, {Key: "url", Value: "https://t"}})if err != nil {t.Fatal(err)}writeFile(t, path, withTheirs)disconnect(t, fileOptions(home), target)- got, err := decodeJSONC(readFile(t, path))+ got, err := jsonc.Decode(readFile(t, path))if err != nil {t.Fatal(err)}diff --git a/cli/beacon/internal/mcpconnect/targets.go b/cli/beacon/internal/mcpconnect/targets.goindex eab9867b..6733c79a 100644--- a/cli/beacon/internal/mcpconnect/targets.go+++ b/cli/beacon/internal/mcpconnect/targets.go@@ -12,6 +12,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/hermessession"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/jsonc")// ServerName is the name Beacon registers the Beacon Cloud MCP server under in every harness.@@ -69,9 +70,9 @@ type Target struct {format configFormatpath func(home string) (string, error)container []string // path to the object holding servers, e.g. ["mcpServers"]- entry func(url, tokenEnv string) ordered+ entry func(url, tokenEnv string) jsonc.Ordered// skeleton is the content of a config Beacon creates, besides the server entry.- skeleton ordered+ skeleton jsonc.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.@@ -97,10 +98,10 @@ func Targets() []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}}+ entry: func(url, tokenEnv string) jsonc.Ordered {+ e := jsonc.Ordered{{Key: "type", Value: "http"}, {Key: "url", Value: url}}if tokenEnv != "" {- e = append(e, field{"headers", ordered{{"Authorization", "Bearer ${" + tokenEnv + "}"}}})+ e = append(e, jsonc.Field{Key: "headers", Value: jsonc.Ordered{{Key: "Authorization", Value: "Bearer ${" + tokenEnv + "}"}}})}return e},@@ -111,10 +112,10 @@ func Targets() []Target {Name: "codex_cli", DisplayName: "Codex CLI", Aliases: []string{"codex", "codex-cli"},Automatic: true, format: formatTOML, path: codexConfigPath, container: []string{"mcp_servers"},switchable: true,- entry: func(url, tokenEnv string) ordered {- e := ordered{{"url", url}}+ entry: func(url, tokenEnv string) jsonc.Ordered {+ e := jsonc.Ordered{{Key: "url", Value: url}}if tokenEnv != "" {- e = append(e, field{"bearer_token_env_var", tokenEnv})+ e = append(e, jsonc.Field{Key: "bearer_token_env_var", Value: tokenEnv})}return e},@@ -124,10 +125,10 @@ func Targets() []Target {{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}}+ entry: func(url, tokenEnv string) jsonc.Ordered {+ e := jsonc.Ordered{{Key: "url", Value: url}}if tokenEnv != "" {- e = append(e, field{"headers", ordered{{"Authorization", "Bearer ${env:" + tokenEnv + "}"}}})+ e = append(e, jsonc.Field{Key: "headers", Value: jsonc.Ordered{{Key: "Authorization", Value: "Bearer ${env:" + tokenEnv + "}"}}})}return e},@@ -138,10 +139,10 @@ func Targets() []Target {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}}+ entry: func(url, tokenEnv string) jsonc.Ordered {+ e := jsonc.Ordered{{Key: "type", Value: "http"}, {Key: "url", Value: url}}if tokenEnv != "" {- e = append(e, field{"headers", ordered{{"Authorization", "Bearer ${input:" + vscodeInputID + "}"}}})+ e = append(e, jsonc.Field{Key: "headers", Value: jsonc.Ordered{{Key: "Authorization", Value: "Bearer ${input:" + vscodeInputID + "}"}}})}return e},@@ -151,10 +152,10 @@ func Targets() []Target {{Name: "gemini_cli", DisplayName: "Gemini CLI", Aliases: []string{"gemini", "gemini-cli"},Automatic: true, format: formatJSON, path: func(home string) (string, error) { return harness.GeminiSettingsPath(home), nil }, container: []string{"mcpServers"},- entry: func(url, tokenEnv string) ordered {- e := ordered{{"url", url}, {"type", "http"}}+ entry: func(url, tokenEnv string) jsonc.Ordered {+ e := jsonc.Ordered{{Key: "url", Value: url}, {Key: "type", Value: "http"}}if tokenEnv != "" {- e = append(e, field{"headers", ordered{{"Authorization", "Bearer ${" + tokenEnv + "}"}}})+ e = append(e, jsonc.Field{Key: "headers", Value: jsonc.Ordered{{Key: "Authorization", Value: "Bearer ${" + tokenEnv + "}"}}})}return e},@@ -165,11 +166,11 @@ func Targets() []Target {Name: "opencode", DisplayName: "OpenCode", Aliases: []string{"opencode", "open-code"},Automatic: true, format: formatJSON, path: opencodeConfigPath, container: []string{"mcp"},switchable: true,- skeleton: ordered{{"$schema", "https://opencode.ai/config.json"}},- entry: func(url, tokenEnv string) ordered {- e := ordered{{"type", "remote"}, {"url", url}, {"enabled", true}}+ skeleton: jsonc.Ordered{{Key: "$schema", Value: "https://opencode.ai/config.json"}},+ entry: func(url, tokenEnv string) jsonc.Ordered {+ e := jsonc.Ordered{{Key: "type", Value: "remote"}, {Key: "url", Value: url}, {Key: "enabled", Value: true}}if tokenEnv != "" {- e = append(e, field{"oauth", false}, field{"headers", ordered{{"Authorization", "Bearer {env:" + tokenEnv + "}"}}})+ e = append(e, jsonc.Field{Key: "oauth", Value: false}, jsonc.Field{Key: "headers", Value: jsonc.Ordered{{Key: "Authorization", Value: "Bearer {env:" + tokenEnv + "}"}}})}return e},@@ -179,12 +180,12 @@ func Targets() []Target {{Name: "omp", DisplayName: "Oh My Pi", Aliases: []string{"omp", "oh-my-pi", "ohmypi"},Automatic: true, format: formatJSON, path: ompMCPConfigPath, container: []string{"mcpServers"},- skeleton: ordered{{"$schema", ompMCPSchema}},+ skeleton: jsonc.Ordered{{Key: "$schema", Value: ompMCPSchema}},strictJSON: true, switchable: true,- entry: func(url, tokenEnv string) ordered {- e := ordered{{"type", "http"}, {"url", url}}+ entry: func(url, tokenEnv string) jsonc.Ordered {+ e := jsonc.Ordered{{Key: "type", Value: "http"}, {Key: "url", Value: url}}if tokenEnv != "" {- e = append(e, field{"headers", ordered{{"Authorization", "Bearer ${" + tokenEnv + "}"}}})+ e = append(e, jsonc.Field{Key: "headers", Value: jsonc.Ordered{{Key: "Authorization", Value: "Bearer ${" + tokenEnv + "}"}}})}return e},@@ -204,28 +205,28 @@ func Targets() []Target {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()}})+ jsonSnippet("mcpServers", jsonc.Ordered{{Key: "type", Value: "streamableHttp"}, {Key: "url", Value: url}, {Key: "headers", Value: 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()}})+ jsonSnippet("mcpServers", jsonc.Ordered{{Key: "url", Value: url}, {Key: "headers", Value: 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()}})+ jsonSnippet("mcpServers", jsonc.Ordered{{Key: "serverUrl", Value: url}, {Key: "headers", Value: 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()}})+ jsonSnippet("mcpServers", jsonc.Ordered{{Key: "httpUrl", Value: url}, {Key: "headers", Value: bearerPlaceholder()}})},},{@@ -251,19 +252,19 @@ func Targets() []Target {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()}})+ jsonSnippet("mcpServers", jsonc.Ordered{{Key: "serverUrl", Value: url}, {Key: "headers", Value: bearerPlaceholder()}})},},}}-func bearerPlaceholder() ordered {- return ordered{{"Authorization", "Bearer <token>"}}+func bearerPlaceholder() jsonc.Ordered {+ return jsonc.Ordered{{Key: "Authorization", Value: "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")+func jsonSnippet(container string, entry jsonc.Ordered) string {+ doc := jsonc.Ordered{{Key: container, Value: jsonc.Ordered{{Key: ServerName, Value: entry}}}}+ return strings.TrimRight(jsonc.NewDocument(doc, ""), "\n")}// NormalizeKey folds a harness spelling the way `beacon endpoint` target names are folded.diff --git a/cli/beacon/internal/mcpconnect/tomledit.go b/cli/beacon/internal/mcpconnect/tomledit.goindex b5277800..ec4b0f31 100644--- a/cli/beacon/internal/mcpconnect/tomledit.go+++ b/cli/beacon/internal/mcpconnect/tomledit.go@@ -6,6 +6,7 @@ import ("strconv""strings"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/jsonc""github.com/pelletier/go-toml/v2")@@ -29,7 +30,7 @@ func parseTOML(text string) (map[string]any, error) {// 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)+ return jsonc.Quote(value)}// tomlLineEnding is the line ending the document already uses. A new document gets "\n" on every@@ -43,7 +44,7 @@ func tomlLineEnding(text string) string {// tomlBlock renders [mcp_servers.<name>] with fields in the order given. Values are strings, or// the person's own `enabled` boolean that connect carries over.-func tomlBlock(table string, name string, fields []field, eol string) string {+func tomlBlock(table string, name string, fields []jsonc.Field, eol string) string {var b strings.Builderb.WriteString("[" + table + "." + tomlKey(name) + "]" + eol)for _, f := range fields {