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
mcp: add beacon mcp connect, disconnect and status
Claude8ce91020be5f
diff --git a/cli/beacon/cmd/mcp_connect.go b/cli/beacon/cmd/mcp_connect.gonew file mode 100644index 00000000..2291baa5--- /dev/null+++ b/cli/beacon/cmd/mcp_connect.go@@ -0,0 +1,588 @@+package cmd++import (+ "bufio"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "regexp"+ "sort"+ "strings"+ "text/tabwriter"+ "time"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/mcpconnect"+)++// `beacon mcp connect` registers the Beacon Managed MCP server in the harnesses on this machine.+// It is an explicit, interactive, per-user command: `beacon endpoint install`, onboarding and+// every unattended path (root, system/MDM installs, CI, piped stdin) never run it. It writes no+// secret -- OAuth harnesses get only the URL, and --token-env writes a reference to a variable --+// and it never reads the Beacon account token in ~/.beacon/auth/session.json. Its only network+// request is the resource-metadata check of the URL, which --dry-run skips.++// Seams for tests. Production uses the real discovery, terminal, uid, HTTP client and CLIs.+var (+ mcpDiscover = harness.DiscoverAll+ mcpIsTTY = defaultOnboardingIsTTY+ mcpIsRoot = func() bool { return os.Geteuid() == 0 }+ mcpStdin io.Reader = os.Stdin+ mcpHTTPClient = &http.Client{Timeout: 10 * time.Second}+ mcpLookPath func(string) (string, error)+ mcpRunCLI func(ctx context.Context, name string, args ...string) ([]byte, error)+ mcpIngestURL = defaultMCPIngestURL+)++var mcpConnectOpts struct {+ harnesses []string+ url string+ tokenEnv string+ dryRun bool+ yes bool+ force bool+ check bool+ json bool+}++var mcpConnectCmd = &cobra.Command{+ Use: "connect",+ Short: "Register Beacon Managed MCP in the harnesses on this machine",+ Long: `Register the Beacon Managed MCP server, as "beacon-managed", in every detected harness that+supports it: Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode.++By default only the URL is written, and each harness signs in with OAuth the first time it+connects. With --token-env, each config references an environment variable holding a personal+MCP token instead; the token itself is never written. Harnesses without confirmed MCP OAuth+support get the steps to add the server by hand.++The URL is --url, or the Beacon Managed URL recorded by ` + "`beacon endpoint connect`" + `. It is+checked against the server's OAuth resource metadata before anything is written; that check is+this command's only network request. Every changed file is backed up first, and+` + "`beacon mcp disconnect`" + ` removes exactly what connect added.`,+ SilenceUsage: true,+ Args: cobra.NoArgs,+ RunE: runMCPConnect,+}++var mcpDisconnectCmd = &cobra.Command{+ Use: "disconnect",+ Short: "Remove the Beacon Managed MCP entries that connect wrote",+ SilenceUsage: true,+ Args: cobra.NoArgs,+ RunE: runMCPDisconnect,+}++var mcpStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show where Beacon Managed MCP is configured",+ SilenceUsage: true,+ Args: cobra.NoArgs,+ RunE: runMCPStatus,+}++func init() {+ mcpCmd.AddCommand(mcpConnectCmd, mcpDisconnectCmd, mcpStatusCmd)+ for _, c := range []*cobra.Command{mcpConnectCmd, mcpDisconnectCmd, mcpStatusCmd} {+ c.Flags().StringSliceVar(&mcpConnectOpts.harnesses, "harness", nil, "Harnesses to act on, comma-separated (default: every detected harness)")+ }+ for _, c := range []*cobra.Command{mcpConnectCmd, mcpStatusCmd} {+ c.Flags().StringVar(&mcpConnectOpts.url, "url", "", "Beacon Managed MCP URL (default: the URL recorded by `beacon endpoint connect`)")+ }+ f := mcpConnectCmd.Flags()+ f.StringVar(&mcpConnectOpts.tokenEnv, "token-env", "", "Reference a personal MCP token in this environment variable instead of using OAuth")+ f.BoolVar(&mcpConnectOpts.dryRun, "dry-run", false, "Show the plan without checking the URL or writing anything")+ f.BoolVar(&mcpConnectOpts.yes, "yes", false, "Write without asking")+ f.BoolVar(&mcpConnectOpts.force, "force", false, "Replace a beacon-managed entry that Beacon did not write")+ mcpStatusCmd.Flags().BoolVar(&mcpConnectOpts.check, "check", false, "Also check the MCP URL against the server's resource metadata")+ mcpStatusCmd.Flags().BoolVar(&mcpConnectOpts.json, "json", false, "Print status as JSON")+}++var envNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)++// validateTokenEnv takes the name of a variable. A value that looks like a token is refused, so+// a pasted secret never ends up in a config file.+func validateTokenEnv(name string) error {+ if name == "" {+ return nil+ }+ if strings.HasPrefix(strings.ToLower(name), "bcn_") || !envNamePattern.MatchString(name) {+ return errors.New("--token-env takes the name of an environment variable (for example BEACON_MCP_TOKEN), not a token")+ }+ return nil+}++// defaultMCPIngestURL is the ingest URL `beacon endpoint connect` recorded for this user.+func defaultMCPIngestURL() string {+ enrollment, err := asymptote.LoadEnrollment(true)+ if err != nil {+ return ""+ }+ return enrollment.IngestURL+}++func mcpHome() (string, error) {+ home, err := os.UserHomeDir()+ if err != nil {+ return "", fmt.Errorf("could not find the home directory: %w", err)+ }+ return home, nil+}++// resolveMCPTargets turns --harness values, or the detected harnesses, into targets. Detected+// harnesses Beacon has no MCP recipe for are returned by name so the plan can say so.+func resolveMCPTargets(values []string) (targets []mcpconnect.Target, unsupported []string, err error) {+ seen := map[string]bool{}+ add := func(t mcpconnect.Target) {+ if !seen[t.Name] {+ seen[t.Name] = true+ targets = append(targets, t)+ }+ }+ if len(values) > 0 {+ var unknown []string+ for _, v := range values {+ if strings.TrimSpace(v) == "" {+ continue+ }+ t, ok := lookupMCPTarget(v)+ if !ok {+ unknown = append(unknown, v)+ continue+ }+ add(t)+ }+ if len(unknown) > 0 {+ return nil, nil, fmt.Errorf("unknown harness %s; known: %s", strings.Join(unknown, ", "), strings.Join(mcpTargetNames(), ", "))+ }+ return targets, nil, nil+ }+ for _, h := range mcpDiscover() {+ if !h.Detected {+ continue+ }+ if t, ok := mcpconnect.Lookup(h.Name); ok {+ add(t)+ continue+ }+ unsupported = append(unsupported, h.DisplayName)+ }+ return targets, unsupported, nil+}++// lookupMCPTarget accepts every spelling `beacon endpoint install --harness` accepts, plus the+// discovery names and the aliases of the MCP-only targets.+func lookupMCPTarget(value string) (mcpconnect.Target, bool) {+ if t, ok := mcpconnect.Lookup(value); ok {+ return t, true+ }+ if target, ok := normalizeEndpointTarget(value); ok {+ return mcpconnect.Lookup(target.Name)+ }+ if name, ok := normalizeHookTarget(value); ok {+ return mcpconnect.Lookup(name)+ }+ return mcpconnect.Target{}, false+}++func mcpTargetNames() []string {+ var names []string+ for _, t := range mcpconnect.Targets() {+ names = append(names, t.Aliases[0])+ }+ sort.Strings(names)+ return names+}++func mcpOptions(home, url string) mcpconnect.Options {+ return mcpconnect.Options{+ Home: home, URL: url, TokenEnv: mcpConnectOpts.tokenEnv, Force: mcpConnectOpts.force,+ LookPath: mcpLookPath, Run: mcpRunCLI,+ }+}++// connectRefusal is why connect will not run here, or "" when it may.+func connectRefusal() string {+ switch {+ case mcpIsRoot():+ return "beacon mcp connect configures one person's harnesses; run it as that user, not as root"+ case mcpConnectOpts.dryRun, mcpConnectOpts.yes:+ return ""+ case isCIEnvironment():+ return "beacon mcp connect does not run in CI without --yes"+ case !mcpIsTTY():+ return "beacon mcp connect needs a terminal to confirm the changes; pass --yes to write without asking, or --dry-run to see the plan"+ }+ return ""+}++func runMCPConnect(cmd *cobra.Command, args []string) error {+ out := cmd.OutOrStdout()+ if reason := connectRefusal(); reason != "" {+ return errors.New(reason)+ }+ if err := validateTokenEnv(mcpConnectOpts.tokenEnv); err != nil {+ return err+ }+ home, err := mcpHome()+ if err != nil {+ return err+ }+ targets, unsupported, err := resolveMCPTargets(mcpConnectOpts.harnesses)+ if err != nil {+ return err+ }+ url, derived, err := mcpconnect.ResolveURL(mcpConnectOpts.url, mcpIngestURL())+ if err != nil {+ return fmt.Errorf("%w (Beacon Managed serves MCP at https://mcp.beacon.sh)", err)+ }+ checked := "not checked (--dry-run)"+ if !mcpConnectOpts.dryRun {+ canonical, err := mcpconnect.CheckURL(cmd.Context(), mcpHTTPClient, url, derived)+ if err != nil {+ return fmt.Errorf("the MCP URL check failed, so nothing was written: %w", err)+ }+ url, checked = canonical, "checked"+ }+ if len(targets) == 0 {+ fmt.Fprintln(out, "No harness Beacon can connect was detected. Pass --harness to name one.")+ printUnsupported(out, unsupported)+ return nil+ }+ opts := mcpOptions(home, url)+ plan, err := mcpconnect.Plan(opts, targets)+ if err != nil {+ return err+ }++ fmt.Fprintf(out, "Beacon Managed MCP: %s (%s)\n", url, checked)+ fmt.Fprintf(out, "Server name: %s\n", mcpconnect.ServerName)+ if opts.TokenEnv != "" {+ fmt.Fprintf(out, "Auth: a personal MCP token read from $%s; Beacon writes only the variable's name\n", opts.TokenEnv)+ } else {+ fmt.Fprintln(out, "Auth: OAuth; Beacon writes only the URL, and each harness signs in on first use")+ }+ fmt.Fprintln(out)+ printPlan(out, home, plan)+ printManual(out, plan, opts)+ printUnsupported(out, unsupported)++ writes := 0+ for _, it := range plan {+ if it.Writes() {+ writes+++ }+ }+ if mcpConnectOpts.dryRun {+ fmt.Fprintln(out, "\nDry run: nothing was written.")+ return nil+ }+ if writes == 0 {+ fmt.Fprintln(out, "\nNothing to change.")+ printNextSteps(out, plan, opts)+ return nil+ }+ if !mcpConnectOpts.yes {+ fmt.Fprintf(out, "\nWrite %d change(s)? Each changed file is backed up first. [y/N] ", writes)+ if !confirmNo(mcpStdin) {+ fmt.Fprintln(out, "Nothing was written.")+ return nil+ }+ }+ applied, err := mcpconnect.Apply(cmd.Context(), opts, plan)+ if err != nil {+ return err+ }+ fmt.Fprintln(out)+ var failed []string+ for _, it := range applied {+ if !it.Writes() {+ continue+ }+ if it.Err != nil {+ failed = append(failed, it.Target.DisplayName)+ fmt.Fprintf(out, "✗ %s: %v\n", it.Target.DisplayName, it.Err)+ continue+ }+ fmt.Fprintf(out, "✓ %s: %s %s\n", it.Target.DisplayName, pastTense(it.Action), displayPath(home, it.Path))+ }+ printNextSteps(out, applied, opts)+ if len(failed) > 0 {+ return fmt.Errorf("could not connect %s", strings.Join(failed, ", "))+ }+ return nil+}++func confirmNo(in io.Reader) bool {+ line, err := bufio.NewReader(in).ReadString('\n')+ if err != nil && line == "" {+ return false+ }+ switch strings.ToLower(strings.TrimSpace(line)) {+ case "y", "yes":+ return true+ }+ return false+}++func pastTense(a mcpconnect.Action) string {+ switch a {+ case mcpconnect.ActionAdd:+ return "added to"+ case mcpconnect.ActionUpdate:+ return "updated in"+ case mcpconnect.ActionReplace:+ return "replaced in"+ }+ return string(a)+}++// displayPath shortens a path under the home directory to ~/...+func displayPath(home, path string) string {+ if path == "" {+ return "-"+ }+ if rel, err := filepath.Rel(home, path); err == nil && !strings.HasPrefix(rel, "..") {+ return filepath.Join("~", rel)+ }+ return path+}++func printPlan(out io.Writer, home string, plan []mcpconnect.Item) {+ tw := tabwriter.NewWriter(out, 2, 4, 2, ' ', 0)+ fmt.Fprintln(tw, "HARNESS\tFILE\tACTION\tAUTH\tNOTE")+ for _, it := range plan {+ if it.Action == mcpconnect.ActionManual {+ continue+ }+ note := it.Detail+ if it.Method != "" && it.Method != "file" && it.Writes() {+ note = strings.TrimSpace("via " + it.Method + " " + note)+ }+ auth := string(it.Auth)+ if it.Action == mcpconnect.ActionSkip || it.Action == mcpconnect.ActionConflict {+ auth = "-"+ }+ fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", it.Target.DisplayName, displayPath(home, it.Path), it.Action, auth, note)+ }+ tw.Flush()+}++func printManual(out io.Writer, plan []mcpconnect.Item, opts mcpconnect.Options) {+ var manual []mcpconnect.Item+ for _, it := range plan {+ if it.Action == mcpconnect.ActionManual {+ manual = append(manual, it)+ }+ }+ if len(manual) == 0 {+ return+ }+ fmt.Fprintln(out, "\nAdd by hand (Beacon writes nothing for these; they have no confirmed MCP OAuth support):")+ for _, it := range manual {+ fmt.Fprintf(out, "\n %s\n", it.Target.DisplayName)+ for _, line := range strings.Split(it.NextStep(opts), "\n") {+ fmt.Fprintf(out, " %s\n", line)+ }+ }+}++func printUnsupported(out io.Writer, names []string) {+ if len(names) == 0 {+ return+ }+ fmt.Fprintf(out, "\nNot connected (Beacon does not know how these configure MCP servers): %s\n", strings.Join(names, ", "))+}++func printNextSteps(out io.Writer, items []mcpconnect.Item, opts mcpconnect.Options) {+ var lines []string+ for _, it := range items {+ if it.Err != nil || !(it.Writes() || it.Action == mcpconnect.ActionPresent) {+ continue+ }+ lines = append(lines, fmt.Sprintf(" %s: %s", it.Target.DisplayName, it.NextStep(opts)))+ }+ if len(lines) == 0 {+ return+ }+ fmt.Fprintln(out, "\nNext steps:")+ for _, line := range lines {+ fmt.Fprintln(out, line)+ }+ if opts.TokenEnv == "" {+ fmt.Fprintln(out, " Restart any harness that is already running so it loads the new server.")+ } else {+ fmt.Fprintf(out, " Create a token at %s and export it as %s, then restart any running harness.\n", mcpconnect.TokenPage, opts.TokenEnv)+ }+}++func runMCPDisconnect(cmd *cobra.Command, args []string) error {+ out := cmd.OutOrStdout()+ home, err := mcpHome()+ if err != nil {+ return err+ }+ targets := mcpconnect.Targets()+ if len(mcpConnectOpts.harnesses) > 0 {+ if targets, _, err = resolveMCPTargets(mcpConnectOpts.harnesses); err != nil {+ return err+ }+ }+ items, err := mcpconnect.Disconnect(cmd.Context(), mcpOptions(home, ""), targets)+ if err != nil {+ return err+ }+ removed := 0+ var failed []string+ for _, it := range items {+ switch {+ case it.Err != nil:+ failed = append(failed, it.Target.DisplayName)+ fmt.Fprintf(out, "✗ %s: %v\n", it.Target.DisplayName, it.Err)+ case it.Action == mcpconnect.ActionRemove:+ removed+++ fmt.Fprintf(out, "✓ %s: %s (%s)\n", it.Target.DisplayName, it.Detail, displayPath(home, it.Path))+ case it.Action == mcpconnect.ActionAbsent && it.Path != "" && it.Detail != "nothing written by Beacon":+ fmt.Fprintf(out, "- %s: %s (%s)\n", it.Target.DisplayName, it.Detail, displayPath(home, it.Path))+ }+ }+ if removed == 0 && len(failed) == 0 {+ fmt.Fprintln(out, "Nothing to remove: no Beacon Managed MCP entry written by Beacon was found.")+ }+ if len(failed) > 0 {+ return fmt.Errorf("could not disconnect %s", strings.Join(failed, ", "))+ }+ return nil+}++type mcpStatusRow struct {+ Harness string `json:"harness"`+ Name string `json:"display_name"`+ Path string `json:"path,omitempty"`+ Configured bool `json:"configured"`+ URL string `json:"url,omitempty"`+ Auth string `json:"auth,omitempty"`+ ByBeacon bool `json:"written_by_beacon"`+ Detail string `json:"detail,omitempty"`+}++type mcpStatusReport struct {+ ServerName string `json:"server_name"`+ URL string `json:"url,omitempty"`+ Check string `json:"check,omitempty"`+ Harnesses []mcpStatusRow `json:"harnesses"`+}++func runMCPStatus(cmd *cobra.Command, args []string) error {+ out := cmd.OutOrStdout()+ home, err := mcpHome()+ if err != nil {+ return err+ }+ targets, _, err := resolveMCPTargets(mcpConnectOpts.harnesses)+ if err != nil {+ return err+ }+ shown := map[string]bool{}+ for _, t := range targets {+ shown[t.Name] = true+ }+ if len(mcpConnectOpts.harnesses) == 0 {+ // Also inspect every automatic harness, so an entry in one that is not detected any more+ // still shows up.+ for _, t := range mcpconnect.Targets() {+ if t.Automatic && !shown[t.Name] {+ targets = append(targets, t)+ }+ }+ }+ statuses, err := mcpconnect.Inspect(mcpOptions(home, ""), targets)+ if err != nil {+ return err+ }+ report := mcpStatusReport{ServerName: mcpconnect.ServerName}+ if url, derived, err := mcpconnect.ResolveURL(mcpConnectOpts.url, mcpIngestURL()); err == nil {+ report.URL = url+ if mcpConnectOpts.check {+ if canonical, err := mcpconnect.CheckURL(cmd.Context(), mcpHTTPClient, url, derived); err != nil {+ report.Check = "failed: " + err.Error()+ } else {+ report.URL, report.Check = canonical, "ok"+ }+ }+ } else if mcpConnectOpts.check {+ report.Check = "failed: " + err.Error()+ }+ for _, s := range statuses {+ if !shown[s.Target.Name] && !s.Configured {+ continue+ }+ report.Harnesses = append(report.Harnesses, mcpStatusRow{+ Harness: s.Target.Name, Name: s.Target.DisplayName, Path: s.Path, Configured: s.Configured,+ URL: s.URL, Auth: string(s.Auth), ByBeacon: s.ByBeacon, Detail: s.Detail,+ })+ }+ if mcpConnectOpts.json {+ enc := json.NewEncoder(out)+ enc.SetIndent("", " ")+ if err := enc.Encode(report); err != nil {+ return err+ }+ } else {+ printStatus(out, home, report)+ }+ if mcpConnectOpts.check && report.Check != "ok" {+ return errors.New("the MCP URL check failed")+ }+ return nil+}++func printStatus(out io.Writer, home string, report mcpStatusReport) {+ fmt.Fprintf(out, "Server name: %s\n", report.ServerName)+ if report.URL != "" {+ fmt.Fprintf(out, "Beacon Managed MCP URL: %s\n", report.URL)+ } else {+ fmt.Fprintln(out, "Beacon Managed MCP URL: unknown (run `beacon endpoint connect`, or pass --url)")+ }+ if report.Check != "" {+ fmt.Fprintf(out, "URL check: %s\n", report.Check)+ }+ fmt.Fprintln(out)+ if len(report.Harnesses) == 0 {+ fmt.Fprintln(out, "No harness Beacon can connect was detected.")+ return+ }+ tw := tabwriter.NewWriter(out, 2, 4, 2, ' ', 0)+ fmt.Fprintln(tw, "HARNESS\tCONFIGURED\tURL\tAUTH\tBY BEACON\tFILE")+ for _, r := range report.Harnesses {+ configured, byBeacon, url := "no", "-", "-"+ if r.Configured {+ configured, url = "yes", r.URL+ byBeacon = "no"+ if r.ByBeacon {+ byBeacon = "yes"+ }+ if report.URL != "" && !strings.EqualFold(strings.TrimRight(r.URL, "/"), strings.TrimRight(report.URL, "/")) {+ configured = "yes (other URL)"+ }+ }+ auth := r.Auth+ if auth == "" {+ auth = "-"+ }+ file := displayPath(home, r.Path)+ if r.Detail != "" && !r.Configured {+ file = r.Detail+ }+ fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\n", r.Name, configured, url, auth, byBeacon, file)+ }+ tw.Flush()+}diff --git a/cli/beacon/cmd/mcp_connect_e2e_test.go b/cli/beacon/cmd/mcp_connect_e2e_test.gonew file mode 100644index 00000000..1164421a--- /dev/null+++ b/cli/beacon/cmd/mcp_connect_e2e_test.go@@ -0,0 +1,195 @@+package cmd++import (+ "context"+ "encoding/json"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// These tests run the harnesses' own CLIs against the configs `beacon mcp connect` writes, in a+// temporary home, and skip any CLI that is not installed. They are how the entry shapes were+// verified: each harness must list beacon-managed at the connected URL, and where the CLI connects+// while listing, a token-env config must make it send the token from the environment.++func realCLI(t *testing.T, name string) string {+ t.Helper()+ if testing.Short() {+ t.Skip("real-CLI tests are skipped in -short mode")+ }+ path, err := exec.LookPath(name)+ if err != nil {+ t.Skipf("%s is not installed", name)+ }+ return path+}++func runCLI(t *testing.T, dir, bin string, args ...string) (string, error) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ defer cancel()+ cmd := exec.CommandContext(ctx, bin, args...)+ cmd.Dir = dir+ out, err := cmd.CombinedOutput()+ return string(out), err+}++// realCLIFixture is an MCP fixture whose harness CLIs run for real.+func realCLIFixture(t *testing.T, detected string) *mcpFixture {+ fx := newMCPFixture(t, detected)+ mcpLookPath, mcpRunCLI = exec.LookPath, nil+ t.Setenv("NO_PROXY", "127.0.0.1,localhost")+ t.Setenv("no_proxy", "127.0.0.1,localhost")+ return fx+}++func connectReal(t *testing.T, fx *mcpFixture, harness string, extra ...string) {+ t.Helper()+ stdout, stderr, err := runMCP(t, append([]string{"connect", "--url", fx.url, "--yes", "--harness", harness}, extra...)...)+ if err != nil || !strings.Contains(stdout, "✓") {+ t.Fatalf("connect %s: %v\n%s%s", harness, err, stdout, stderr)+ }+}++const e2eToken = "bcn_mcp_e2e_token_from_the_environment"++func TestMCPConnectEndToEndClaudeCode(t *testing.T) {+ bin := realCLI(t, "claude")+ fx := realCLIFixture(t, "claude_code")+ connectReal(t, fx, "claude")+ out, err := runCLI(t, fx.home, bin, "mcp", "get", "beacon-managed")+ if !strings.Contains(out, "URL: "+fx.url) || !strings.Contains(out, "User config") {+ t.Fatalf("claude mcp get: %v\n%s", err, out)+ }+ if _, _, err := runMCP(t, "disconnect", "--harness", "claude"); err != nil {+ t.Fatal(err)+ }+ if out, _ := runCLI(t, fx.home, bin, "mcp", "get", "beacon-managed"); strings.Contains(out, fx.url) {+ t.Fatalf("still configured after disconnect:\n%s", out)+ }++ t.Setenv("BEACON_MCP_TOKEN", e2eToken)+ connectReal(t, fx, "claude", "--token-env", "BEACON_MCP_TOKEN")+ _, _ = runCLI(t, fx.home, bin, "mcp", "get", "beacon-managed") // connects to the server+ if !containsString(fx.auth.all(), "Bearer "+e2eToken) {+ t.Fatalf("Claude Code did not send the token from BEACON_MCP_TOKEN; saw %q", fx.auth.all())+ }+}++func TestMCPConnectEndToEndCodex(t *testing.T) {+ bin := realCLI(t, "codex")+ fx := realCLIFixture(t, "codex_cli")+ // Codex refuses to create helper binaries under a temporary directory unless CODEX_HOME is+ // set explicitly; it still works, but say where the config lives.+ t.Setenv("CODEX_HOME", filepath.Join(fx.home, ".codex"))+ connectReal(t, fx, "codex", "--token-env", "BEACON_MCP_TOKEN")+ out, err := runCLI(t, fx.home, bin, "mcp", "list", "--json")+ if err != nil {+ t.Fatalf("codex mcp list: %v\n%s", err, out)+ }+ var servers []struct {+ Name string `json:"name"`+ Transport struct {+ URL string `json:"url"`+ BearerTokenEnvVar *string `json:"bearer_token_env_var"`+ } `json:"transport"`+ }+ if err := json.Unmarshal([]byte(out[strings.Index(out, "["):]), &servers); err != nil {+ t.Fatalf("%v\n%s", err, out)+ }+ found := false+ for _, s := range servers {+ if s.Name == "beacon-managed" && s.Transport.URL == fx.url && s.Transport.BearerTokenEnvVar != nil && *s.Transport.BearerTokenEnvVar == "BEACON_MCP_TOKEN" {+ found = true+ }+ }+ if !found {+ t.Fatalf("codex does not list beacon-managed at %s with the token variable:\n%s", fx.url, out)+ }+ if _, _, err := runMCP(t, "disconnect", "--harness", "codex"); err != nil {+ t.Fatal(err)+ }+ if out, _ := runCLI(t, fx.home, bin, "mcp", "list", "--json"); strings.Contains(out, "beacon-managed") {+ t.Fatalf("still listed after disconnect:\n%s", out)+ }+}++func TestMCPConnectEndToEndGemini(t *testing.T) {+ bin := realCLI(t, "gemini")+ fx := realCLIFixture(t, "gemini_cli")+ t.Setenv("BEACON_MCP_TOKEN", e2eToken)+ connectReal(t, fx, "gemini", "--token-env", "BEACON_MCP_TOKEN")+ // Gemini CLI connects to MCP servers only in a trusted folder.+ trusted, _ := json.Marshal(map[string]string{fx.home: "TRUST_FOLDER"})+ if err := os.WriteFile(filepath.Join(fx.home, ".gemini", "trustedFolders.json"), trusted, 0o600); err != nil {+ t.Fatal(err)+ }+ out, err := runCLI(t, fx.home, bin, "mcp", "list")+ if !strings.Contains(out, "beacon-managed: "+fx.url+" (http)") {+ t.Fatalf("gemini mcp list: %v\n%s", err, out)+ }+ if !containsString(fx.auth.all(), "Bearer "+e2eToken) {+ t.Fatalf("Gemini CLI did not send the token from BEACON_MCP_TOKEN; saw %q", fx.auth.all())+ }+ if _, _, err := runMCP(t, "disconnect", "--harness", "gemini"); err != nil {+ t.Fatal(err)+ }+ if out, _ := runCLI(t, fx.home, bin, "mcp", "list"); strings.Contains(out, "beacon-managed") {+ t.Fatalf("still listed after disconnect:\n%s", out)+ }+}++func TestMCPConnectEndToEndOpenCode(t *testing.T) {+ bin := realCLI(t, "opencode")+ fx := realCLIFixture(t, "opencode")+ connectReal(t, fx, "opencode")+ out, err := runCLI(t, fx.home, bin, "mcp", "list")+ if !strings.Contains(out, "beacon-managed") || !strings.Contains(out, fx.url) {+ t.Fatalf("opencode mcp list: %v\n%s", err, out)+ }+ if _, _, err := runMCP(t, "disconnect", "--harness", "opencode"); err != nil {+ t.Fatal(err)+ }++ t.Setenv("BEACON_MCP_TOKEN", e2eToken)+ connectReal(t, fx, "opencode", "--token-env", "BEACON_MCP_TOKEN")+ _, _ = runCLI(t, fx.home, bin, "mcp", "list")+ if !containsString(fx.auth.all(), "Bearer "+e2eToken) {+ t.Fatalf("OpenCode did not send the token from BEACON_MCP_TOKEN; saw %q", fx.auth.all())+ }+}++// Copilot CLI is a manual target: connect prints the command. Running that command, with a+// placeholder token, must produce a server Copilot lists at the URL.+func TestMCPConnectEndToEndCopilotManualStep(t *testing.T) {+ bin := realCLI(t, "copilot")+ fx := realCLIFixture(t, "copilot_cli")+ stdout, _, err := runMCP(t, "connect", "--url", fx.url, "--yes", "--harness", "copilot")+ if err != nil {+ t.Fatal(err)+ }+ want := "copilot mcp add --transport http beacon-managed " + fx.url + ` --header "Authorization: Bearer <token>"`+ if !strings.Contains(stdout, want) {+ t.Fatalf("output lacks the manual step:\n%s", stdout)+ }+ out, err := runCLI(t, fx.home, bin, "mcp", "add", "--transport", "http", "beacon-managed", fx.url, "--header", "Authorization: Bearer placeholder")+ if err != nil {+ t.Fatalf("the printed copilot command failed: %v\n%s", err, out)+ }+ if out, _ := runCLI(t, fx.home, bin, "mcp", "list"); !strings.Contains(out, "beacon-managed") {+ t.Fatalf("copilot mcp list:\n%s", out)+ }+}++func containsString(list []string, want string) bool {+ for _, s := range list {+ if s == want {+ return true+ }+ }+ return false+}diff --git a/cli/beacon/cmd/mcp_connect_test.go b/cli/beacon/cmd/mcp_connect_test.gonew file mode 100644index 00000000..f9b4c021--- /dev/null+++ b/cli/beacon/cmd/mcp_connect_test.go@@ -0,0 +1,521 @@+package cmd++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io"+ "io/fs"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"++ "github.com/spf13/cobra"+ "github.com/spf13/pflag"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/mcpconnect"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++// The account token a signed-in user has. No command in this file may ever write or print it.+const fakeAccountToken = "bcn_cli_ACCOUNT_TOKEN_MUST_NOT_LEAK_7f3a9c"++// requestLog records every HTTP request the commands make, on any transport.+type requestLog struct {+ mu sync.Mutex+ urls []string+}++func (l *requestLog) add(u string) {+ l.mu.Lock()+ defer l.mu.Unlock()+ l.urls = append(l.urls, u)+}++func (l *requestLog) all() []string {+ l.mu.Lock()+ defer l.mu.Unlock()+ return append([]string(nil), l.urls...)+}++type recordingTransport struct {+ log *requestLog+ next http.RoundTripper+}++func (r recordingTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ r.log.add(req.URL.String())+ if r.next == nil {+ return nil, errors.New("network access is not allowed here")+ }+ return r.next.RoundTrip(req)+}++type mcpFixture struct {+ home string+ server *httptest.Server+ url string+ requests *requestLog+ // strays records requests that went anywhere but mcpHTTPClient.+ strays *requestLog+ // auth records the Authorization header of every request to the MCP endpoint itself, which+ // only a real harness makes.+ auth *requestLog+}++// newMCPFixture isolates the home directory, stubs discovery and the terminal, serves resource+// metadata for the MCP URL, and blocks every other HTTP request made in-process.+func newMCPFixture(t *testing.T, detected ...string) *mcpFixture {+ t.Helper()+ fx := &mcpFixture{home: t.TempDir(), requests: &requestLog{}, strays: &requestLog{}, auth: &requestLog{}}+ testenv.SetHome(t, fx.home)+ for _, key := range []string{"XDG_CONFIG_HOME", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "JENKINS_URL", "TEAMCITY_VERSION"} {+ t.Setenv(key, "")+ os.Unsetenv(key)+ }+ fx.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/mcp" {+ fx.auth.add(r.Header.Get("Authorization"))+ w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="`+fx.server.URL+`/.well-known/oauth-protected-resource"`)+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ 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": fx.url, "authorization_servers": []string{fx.server.URL}})+ }))+ t.Cleanup(fx.server.Close)+ fx.url = fx.server.URL + "/mcp"++ // A signed-in Beacon account, whose token must never reach a harness config or the output.+ sessionPath := filepath.Join(fx.home, ".beacon", "auth", "session.json")+ if err := os.MkdirAll(filepath.Dir(sessionPath), 0o700); err != nil {+ t.Fatal(err)+ }+ session := `{"schema_version":1,"base_url":"https://beacon.sh","access_token":"` + fakeAccountToken + `","token_type":"Bearer","scopes":["profile:read","device:enroll"]}`+ if err := os.WriteFile(sessionPath, []byte(session), 0o600); err != nil {+ t.Fatal(err)+ }++ prev := struct {+ discover func() []harness.Harness+ tty, root func() bool+ stdin io.Reader+ client *http.Client+ lookPath func(string) (string, error)+ run func(context.Context, string, ...string) ([]byte, error)+ ingest func() string+ defTransport http.RoundTripper+ }{mcpDiscover, mcpIsTTY, mcpIsRoot, mcpStdin, mcpHTTPClient, mcpLookPath, mcpRunCLI, mcpIngestURL, http.DefaultTransport}+ t.Cleanup(func() {+ mcpDiscover, mcpIsTTY, mcpIsRoot, mcpStdin, mcpHTTPClient = prev.discover, prev.tty, prev.root, prev.stdin, prev.client+ mcpLookPath, mcpRunCLI, mcpIngestURL, http.DefaultTransport = prev.lookPath, prev.run, prev.ingest, prev.defTransport+ })+ mcpDiscover = func() []harness.Harness {+ var out []harness.Harness+ for _, name := range detected {+ out = append(out, harness.Harness{Name: name, DisplayName: name, Detected: true})+ }+ return out+ }+ mcpIsTTY = func() bool { return true }+ mcpIsRoot = func() bool { return false }+ mcpStdin = strings.NewReader("")+ mcpHTTPClient = &http.Client{Transport: recordingTransport{log: fx.requests, next: fx.server.Client().Transport}}+ // Anything that bypasses mcpHTTPClient is recorded and refused.+ http.DefaultTransport = recordingTransport{log: fx.strays}+ mcpLookPath = func(string) (string, error) { return "", errors.New("not on PATH") }+ mcpRunCLI = func(context.Context, string, ...string) ([]byte, error) { return nil, errors.New("no CLI in unit tests") }+ mcpIngestURL = func() string { return "" }+ return fx+}++// runMCP runs `beacon mcp <args>` and returns stdout and stderr.+func runMCP(t *testing.T, args ...string) (string, string, error) {+ t.Helper()+ var reset func(c *cobra.Command)+ reset = func(c *cobra.Command) {+ c.Flags().VisitAll(func(f *pflag.Flag) {+ if sv, ok := f.Value.(pflag.SliceValue); ok {+ _ = sv.Replace(nil)+ } else {+ _ = f.Value.Set(f.DefValue)+ }+ f.Changed = false+ })+ for _, sub := range c.Commands() {+ reset(sub)+ }+ }+ reset(mcpCmd)+ var stdout, stderr bytes.Buffer+ rootCmd.SetOut(&stdout)+ rootCmd.SetErr(&stderr)+ rootCmd.SetArgs(append([]string{"mcp"}, args...))+ t.Cleanup(func() {+ rootCmd.SetOut(nil)+ rootCmd.SetErr(nil)+ rootCmd.SetArgs(nil)+ })+ err := rootCmd.Execute()+ return stdout.String(), stderr.String(), err+}++// filesUnder lists every regular file under dir except the seeded account session.+func filesUnder(t *testing.T, dir string) map[string]string {+ t.Helper()+ out := map[string]string{}+ _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {+ if err != nil || d.IsDir() {+ return nil+ }+ rel, _ := filepath.Rel(dir, path)+ if rel == filepath.Join(".beacon", "auth", "session.json") {+ return nil+ }+ data, _ := os.ReadFile(path)+ out[rel] = string(data)+ return nil+ })+ return out+}++var allAutomatic = []string{"claude_code", "codex_cli", "cursor", "vscode", "gemini_cli", "opencode"}++func TestMCPConnectSubcommandsAreRegistered(t *testing.T) {+ for _, sub := range []string{"connect", "disconnect", "status"} {+ c, _, err := rootCmd.Find([]string{"mcp", sub})+ if err != nil || c.Name() != sub {+ t.Fatalf("mcp %s not registered: %v", sub, err)+ }+ }+ c, _, _ := rootCmd.Find([]string{"mcp", "connect"})+ for _, flag := range []string{"harness", "url", "token-env", "dry-run", "yes", "force"} {+ if c.Flags().Lookup(flag) == nil {+ t.Errorf("mcp connect has no --%s", flag)+ }+ }+ c, _, _ = rootCmd.Find([]string{"mcp", "status"})+ for _, flag := range []string{"harness", "check", "json", "url"} {+ if c.Flags().Lookup(flag) == nil {+ t.Errorf("mcp status has no --%s", flag)+ }+ }+}++func TestMCPConnectRefusesUnattendedRuns(t *testing.T) {+ cases := []struct {+ name string+ arrange func(t *testing.T)+ args []string+ }{+ {"not a terminal", func(*testing.T) { mcpIsTTY = func() bool { return false } }, nil},+ {"CI", func(t *testing.T) { t.Setenv("CI", "true") }, nil},+ {"GitHub Actions", func(t *testing.T) { t.Setenv("GITHUB_ACTIONS", "true") }, nil},+ {"root", func(*testing.T) { mcpIsRoot = func() bool { return true } }, nil},+ {"root even with --yes", func(*testing.T) { mcpIsRoot = func() bool { return true } }, []string{"--yes"}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ fx := newMCPFixture(t, allAutomatic...)+ tc.arrange(t)+ _, _, err := runMCP(t, append([]string{"connect", "--url", fx.url}, tc.args...)...)+ if err == nil {+ t.Fatal("connect ran unattended")+ }+ if got := filesUnder(t, fx.home); len(got) != 0 {+ t.Fatalf("a refused connect wrote %v", got)+ }+ if reqs := fx.requests.all(); len(reqs) != 0 {+ t.Fatalf("a refused connect made requests: %v", reqs)+ }+ })+ }+}++func TestMCPConnectDryRunTouchesNothingAndMakesNoRequest(t *testing.T) {+ fx := newMCPFixture(t, allAutomatic...)+ mcpIsTTY = func() bool { return false }+ stdout, _, err := runMCP(t, "connect", "--url", fx.url, "--dry-run")+ if err != nil {+ t.Fatal(err)+ }+ for _, want := range []string{"not checked (--dry-run)", "Dry run: nothing was written.", "Claude Code", "Codex CLI", "add"} {+ if !strings.Contains(stdout, want) {+ t.Errorf("dry run output lacks %q:\n%s", want, stdout)+ }+ }+ if got := filesUnder(t, fx.home); len(got) != 0 {+ t.Fatalf("dry run wrote %v", got)+ }+ if reqs := append(fx.requests.all(), fx.strays.all()...); len(reqs) != 0 {+ t.Fatalf("dry run made requests: %v", reqs)+ }+}++func TestMCPConnectWritesEveryDetectedHarnessThenDisconnectRestores(t *testing.T) {+ fx := newMCPFixture(t, append(allAutomatic, "copilot_cli", "pi_cli")...)+ cursorPath := filepath.Join(fx.home, ".cursor", "mcp.json")+ original := "{\n // mine\n \"mcpServers\": {\n \"x\": {\"url\": \"https://x\"}\n }\n}\n"+ if err := os.MkdirAll(filepath.Dir(cursorPath), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(cursorPath, []byte(original), 0o644); err != nil {+ t.Fatal(err)+ }+ stdout, stderr, err := runMCP(t, "connect", "--url", fx.url, "--yes")+ if err != nil {+ t.Fatalf("%v\n%s%s", err, stdout, stderr)+ }+ for _, want := range []string{+ "(checked)", "Server name: beacon-managed", "Auth: OAuth",+ "✓ Claude Code", "✓ Codex CLI", "✓ Cursor", "✓ VS Code", "✓ Gemini CLI", "✓ OpenCode",+ "codex mcp login beacon-managed", "opencode mcp auth beacon-managed", "run /mcp",+ "Add by hand", "copilot mcp add --transport http beacon-managed " + fx.url,+ "Not connected (Beacon does not know how these configure MCP servers): pi_cli",+ } {+ if !strings.Contains(stdout, want) {+ t.Errorf("output lacks %q:\n%s", want, stdout)+ }+ }+ statusOut, _, err := runMCP(t, "status", "--url", fx.url, "--json")+ if err != nil {+ t.Fatal(err)+ }+ var report mcpStatusReport+ if err := json.Unmarshal([]byte(statusOut), &report); err != nil {+ t.Fatalf("%v\n%s", err, statusOut)+ }+ configured := map[string]bool{}+ for _, row := range report.Harnesses {+ if row.Configured && row.ByBeacon && row.URL == fx.url && row.Auth == "oauth" {+ configured[row.Harness] = true+ }+ }+ for _, name := range allAutomatic {+ if !configured[name] {+ t.Errorf("status does not show %s configured by Beacon: %+v", name, report.Harnesses)+ }+ }++ again, _, err := runMCP(t, "connect", "--url", fx.url, "--yes")+ if err != nil || !strings.Contains(again, "Nothing to change.") {+ t.Fatalf("a second connect was not a no-op: %v\n%s", err, again)+ }++ if _, _, err := runMCP(t, "disconnect"); err != nil {+ t.Fatal(err)+ }+ left := filesUnder(t, fx.home)+ for path := range left {+ if strings.Contains(path, ".beacon.") && strings.HasSuffix(path, ".bak") {+ delete(left, path) // backups stay, by design+ }+ }+ if len(left) != 1 || left[filepath.Join(".cursor", "mcp.json")] != original {+ t.Fatalf("disconnect did not return the home directory to its original state: %v", left)+ }+}++func TestMCPConnectAsksBeforeWriting(t *testing.T) {+ fx := newMCPFixture(t, "cursor")+ mcpStdin = strings.NewReader("n\n")+ stdout, _, err := runMCP(t, "connect", "--url", fx.url)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(stdout, "[y/N]") || !strings.Contains(stdout, "Nothing was written.") {+ t.Fatalf("output:\n%s", stdout)+ }+ if got := filesUnder(t, fx.home); len(got) != 0 {+ t.Fatalf("declining wrote %v", got)+ }+ mcpStdin = strings.NewReader("y\n")+ if _, _, err := runMCP(t, "connect", "--url", fx.url); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(fx.home, ".cursor", "mcp.json")); err != nil {+ t.Fatal("confirming did not write")+ }+}++// The Beacon account token (bcn_cli_) must never be copied anywhere: not into a harness config,+// the manifest, a backup, or the command's output.+func TestMCPCommandsNeverCopyTheAccountToken(t *testing.T) {+ for _, mode := range [][]string{nil, {"--token-env", "BEACON_MCP_TOKEN"}} {+ fx := newMCPFixture(t, append(allAutomatic, "copilot_cli", "cline", "kiro")...)+ t.Setenv("BEACON_MCP_TOKEN", "bcn_mcp_value_must_not_be_written")+ var outputs []string+ for _, args := range [][]string{+ append([]string{"connect", "--url", fx.url, "--yes"}, mode...),+ {"status", "--url", fx.url, "--check"},+ {"status", "--url", fx.url, "--json"},+ {"disconnect"},+ } {+ stdout, stderr, err := runMCP(t, args...)+ if err != nil {+ t.Fatalf("%v: %v\n%s%s", args, err, stdout, stderr)+ }+ outputs = append(outputs, stdout, stderr)+ for path, content := range filesUnder(t, fx.home) {+ if strings.Contains(content, fakeAccountToken) || strings.Contains(content, "bcn_cli_") {+ t.Fatalf("%v copied the account token into %s", args, path)+ }+ if strings.Contains(content, "bcn_mcp_value_must_not_be_written") {+ t.Fatalf("%v wrote the MCP token value into %s", args, path)+ }+ }+ }+ for _, out := range outputs {+ if strings.Contains(out, fakeAccountToken) || strings.Contains(out, "bcn_mcp_value_must_not_be_written") {+ t.Fatalf("a token was printed:\n%s", out)+ }+ }+ }+}++func TestMCPConnectMakesNoRequestBeyondTheURLCheck(t *testing.T) {+ fx := newMCPFixture(t, allAutomatic...)+ if _, _, err := runMCP(t, "connect", "--url", fx.url, "--yes"); err != nil {+ t.Fatal(err)+ }+ reqs := fx.requests.all()+ if len(reqs) != 1 || reqs[0] != fx.server.URL+"/.well-known/oauth-protected-resource" {+ t.Fatalf("connect made %v, want exactly the resource-metadata request", reqs)+ }+ if strays := fx.strays.all(); len(strays) != 0 {+ t.Fatalf("connect made requests outside the URL check: %v", strays)+ }+ // Status without --check, and disconnect, make none at all.+ for _, args := range [][]string{{"status", "--url", fx.url}, {"disconnect"}} {+ if _, _, err := runMCP(t, args...); err != nil {+ t.Fatal(err)+ }+ }+ if got := len(fx.requests.all()) + len(fx.strays.all()); got != 1 {+ t.Fatalf("status or disconnect made a request (%d total)", got)+ }+}++func TestMCPConnectURLFailuresWriteNothing(t *testing.T) {+ fx := newMCPFixture(t, "cursor")+ cases := map[string][]string{+ "no URL anywhere": {"connect", "--yes"},+ "URL the server disowns": {"connect", "--yes", "--url", fx.server.URL + "/wrong"},+ "plain http remote": {"connect", "--yes", "--url", "http://mcp.example.test/mcp"},+ "token value as env name": {"connect", "--yes", "--url", fx.url, "--token-env", "bcn_mcp_abc123"},+ "unknown harness": {"connect", "--yes", "--url", fx.url, "--harness", "nope"},+ }+ for name, args := range cases {+ _, _, err := runMCP(t, args...)+ if err == nil {+ t.Errorf("%s: connect succeeded", name)+ }+ if name == "no URL anywhere" && (err == nil || !strings.Contains(err.Error(), "beacon endpoint connect")) {+ t.Errorf("the no-URL error does not point at beacon endpoint connect: %v", err)+ }+ }+ if got := filesUnder(t, fx.home); len(got) != 0 {+ t.Fatalf("a failed connect wrote %v", got)+ }+}++func TestMCPConnectDerivesTheURLFromTheManagedConnection(t *testing.T) {+ fx := newMCPFixture(t, "cursor")+ mcpIngestURL = func() string { return fx.server.URL }+ stdout, _, err := runMCP(t, "connect", "--yes")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(stdout, "Beacon Managed MCP: "+fx.url+" (checked)") {+ t.Fatalf("output:\n%s", stdout)+ }+}++func TestMCPConnectHarnessFlagAcceptsEndpointSpellings(t *testing.T) {+ fx := newMCPFixture(t) // nothing detected+ stdout, _, err := runMCP(t, "connect", "--url", fx.url, "--yes", "--harness", "Codex-CLI,claude,vs-code")+ if err != nil {+ t.Fatal(err)+ }+ for _, want := range []string{"✓ Codex CLI", "✓ Claude Code", "✓ VS Code"} {+ if !strings.Contains(stdout, want) {+ t.Errorf("output lacks %q:\n%s", want, stdout)+ }+ }+ if strings.Contains(stdout, "Cursor") {+ t.Error("--harness connected a harness it did not name")+ }+}++func TestMCPConnectReportsConflictsAndForceReplaces(t *testing.T) {+ fx := newMCPFixture(t, "cursor")+ path := filepath.Join(fx.home, ".cursor", "mcp.json")+ theirs := `{"mcpServers": {"beacon-managed": {"url": "https://elsewhere.example"}}}`+ _ = os.MkdirAll(filepath.Dir(path), 0o700)+ _ = os.WriteFile(path, []byte(theirs), 0o644)+ stdout, _, err := runMCP(t, "connect", "--url", fx.url, "--yes")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(stdout, "conflict") || !strings.Contains(stdout, "https://elsewhere.example") {+ t.Fatalf("output:\n%s", stdout)+ }+ if data, _ := os.ReadFile(path); string(data) != theirs {+ t.Fatal("a conflict was overwritten")+ }+ stdout, _, err = runMCP(t, "connect", "--url", fx.url, "--yes", "--force")+ if err != nil || !strings.Contains(stdout, "replaced in") {+ t.Fatalf("--force: %v\n%s", err, stdout)+ }+}++func TestMCPStatusCheckReportsAFailedCheck(t *testing.T) {+ fx := newMCPFixture(t, "cursor")+ stdout, _, err := runMCP(t, "status", "--url", fx.server.URL+"/wrong", "--check")+ if err == nil || !strings.Contains(stdout, "URL check: failed") {+ t.Fatalf("err = %v\n%s", err, stdout)+ }+ stdout, _, err = runMCP(t, "status", "--url", fx.url, "--check")+ if err != nil || !strings.Contains(stdout, "URL check: ok") || !strings.Contains(stdout, "Cursor") {+ t.Fatalf("err = %v\n%s", err, stdout)+ }+}++func TestMCPDisconnectWithNothingToRemove(t *testing.T) {+ newMCPFixture(t, allAutomatic...)+ stdout, _, err := runMCP(t, "disconnect")+ if err != nil || !strings.Contains(stdout, "Nothing to remove") {+ t.Fatalf("err = %v\n%s", err, stdout)+ }+}++func TestMCPConnectTokenEnvPrintsTheVariable(t *testing.T) {+ fx := newMCPFixture(t, "codex_cli")+ stdout, _, err := runMCP(t, "connect", "--url", fx.url, "--yes", "--token-env", "BEACON_MCP_TOKEN")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(stdout, "read from $BEACON_MCP_TOKEN") || !strings.Contains(stdout, "export it as BEACON_MCP_TOKEN") {+ t.Fatalf("output:\n%s", stdout)+ }+ data, _ := os.ReadFile(filepath.Join(fx.home, ".codex", "config.toml"))+ if !strings.Contains(string(data), `bearer_token_env_var = "BEACON_MCP_TOKEN"`) {+ t.Fatalf("config.toml:\n%s", data)+ }+}++func TestMCPServerNamesDoNotCollide(t *testing.T) {+ if mcpconnect.ServerName == "beacon" {+ t.Fatal("the Beacon Managed server must not share the local stdio server's name")+ }+}