Skip to content

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

cli: request mcp:token:create at login and add beacon mcp token create

Claudeaf1836923e77
diff --git a/CLAUDE.md b/CLAUDE.md
index 0e230dee..9331f680 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -25,7 +25,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc
- Beacon is visibility-first endpoint telemetry for local AI agent runtimes, not a hosted policy service or general endpoint protection product.
- Preserve the local-only default. The public Beacon build must not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution, and hooks themselves never touch the network.
-- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key; never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.
+- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key, and `beacon mcp token create` may send it to `POST /api/cli/mcp/tokens` (scope `mcp:token:create`, listed on the sign-in page) to mint a personal MCP token that is printed once to stdout and never written to a file; never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.
- Beacon Managed forwarding (`cli/beacon/internal/endpoint/asymptote`, `beacon endpoint connect`, `beacon endpoint asymptote`) is Vector-shaped: Beacon writes local JSONL, Vector ships runtime lines only from the connection point forward and reads inventory from the beginning to establish the endpoint's current baseline, and the `bcn_device_*` key stays only in `<BaseDir>/asymptote/vector-secrets.json` via Vector's secret backend. The onboarding wizard preselects Managed, and confirming it connects this endpoint in the same command once the local install has succeeded; an endpoint that is already enrolled is never re-enrolled, because enrollment rotates the device key. Standard mode ships locally sanitized retained content; metadata-only uses local Vector transforms to remove prompts, responses, reasoning, tool arguments/results, command output, raw fields, diffs, inventory content, and MCP definitions before buffering/upload. Keep the ingest URL `https://`, the wire contract aligned with `beacon-ingest` (`/v1/ingest/{runtime,inventory}` and `/v1/ingest/health`), and do not add another endpoint network channel. The cloud-sandbox shuttle is the bounded exception: only with `BEACON_ORIGIN=cloud`, it can upload new runtime lines to GCS, S3, or the same Beacon ingest contract because no Vector/service manager/browser/persistent disk exists there.
- `beacon endpoint install` has a full-screen onboarding wizard on interactive user TTYs. It signs in, preselects Beacon Managed, requires an explicit choice to opt out to Local, and asks Managed users to choose Standard or Metadata-only privacy. Signing in alone still moves no telemetry. Confirming Managed does: the confirm screen states that it installs Beacon and starts forwarding, and names what the selected privacy mode sends, so that screen is the consent point. The managed destination is recorded only after enrollment succeeds, so a failed enrollment leaves a working local install, prints `beacon endpoint connect` as the retry, and re-offers the question on the next install. The onboarding record is written only after `lifecycle.Install` returns, because a profile written first left a failed install looking onboarded and silently skipped the wizard on the retry. Explicit `install --connect` is unchanged. The wizard is skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`; those unattended paths must never gain an account or browser dependency. Legacy `BEACON_ONBOARDING_EMAIL`/`USAGE` submissions remain only for fleet compatibility. Implementation lives in `cli/beacon/internal/onboarding` and `cli/beacon/cmd/endpoint_onboarding.go`; keep `docs/cli/endpoint-onboarding.mdx` in sync.
- Do not add dependency vulnerability scanning, OSV/GHSA lookups, package remediation, or other vulnerability-enforcement flows to the public hook path.
@@ -67,7 +67,7 @@ Supported runtime surfaces today:
- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network. A small frozen baseline is embedded so `scan` works before any rules are installed.
- Session handoff via `beacon handoff list|export|resume` (`cli/beacon/internal/handoff`, `cli/beacon/cmd/handoff*.go`; docs in `docs/cli/handoff.mdx` and `docs/concepts/session-handoff.mdx`). Every runtime is one entry in the registry in `cli/beacon/internal/handoff/runtimes.go`: its session source, the names it answers to, and the commands that reopen it or start it from a brief; `TestRegistryIsConsistent` checks the entries. Handoff reads the session stores of Claude Code, Codex CLI, OpenCode, Cline, Pi, Prime Agent, Factory Droid, GitHub Copilot CLI, Hermes Agent, DeepSeek Harness, fx, Grok Build, OpenClaw Gateway and Cursor read-only and never touches the network. Oh My Pi, Gemini CLI, Qwen Code, Kiro, Antigravity CLI, Devin CLI, Muse Code, OpenHands and goose have no store Beacon reads: their sessions come from the runtime log, and they take a brief as the target of `--agent`. `resume` reopens a session natively with its runtime's own command when it can, and otherwise writes a brief to `~/.beacon/endpoint/handoffs` (0700/0600) and starts a new session pointed at it. DeepSeek Harness cannot be started, and Hermes Agent and fx only reopen their own sessions, so their sessions continue in another runtime. fx, Grok Build and Cursor find a session by the directory they run in, so they are reopened natively only in the session's own directory. The brief is passed by absolute path, never inlined on a command line. Every launch keeps the runtime's approvals on: Beacon never passes a flag that turns them off, names the approval mode that asks where a CLI takes one (Cline always gets `--auto-approve false`, because Cline defaults to approving every tool call), and removes or overrides environment switches that would approve everything (`COPILOT_ALLOW_ALL`, `COPILOT_PLAN_THEN_AUTOPILOT`, `HERMES_YOLO_MODE`, `GOOSE_MODE`); `--print` shows them under `env`. Briefs run every event through `SanitizeEvent`, and quoted content goes in fences longer than any backtick run it contains, with inline fields reduced to one line, so quoted content cannot forge brief structure. A new session's first prompt ends with the `[beacon-handoff from=<harness> session=<id>]` marker (`pkg/asymptoteobserve/handoff.go`). The hook and plugin prompt paths and the session-store mappers record a `session.handoff` event with `handoff.{source_harness,source_session_id}` when they see it; that is an observed claim, not a verified identity.
- Commit-to-session links via `beacon git setup|status|remove|link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git*.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand.
-- Beacon Managed MCP registration via `beacon mcp connect|disconnect|status` (`cli/beacon/internal/mcpconnect`, `cli/beacon/cmd/mcp_connect.go`; docs in `docs/cli/mcp-connect.mdx`). It registers the Beacon Managed MCP server as `beacon-managed`, a different name from the local stdio server `beacon`, in the user-level config of Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode. It prints manual steps for runtimes without confirmed MCP OAuth support. OAuth is the default and writes only the URL; `--token-env` writes a reference to an environment variable in each harness's own syntax, never a value. The account token is never read or copied, and Beacon does not mint MCP tokens. It is explicit and interactive: never run by `endpoint install` or onboarding (the install only suggests it after the wizard's Managed choice), refused as root, and refused in CI or without a terminal unless `--yes` is given. Its one network request is the RFC 9728 resource-metadata check of the URL, which `--dry-run` skips. Configs are edited like the Kimi Code writer: never re-serialized, spliced as text, parsed back and compared before an atomic replace, backed up first. What was written is recorded in `~/.beacon/mcp/connections.json`, and `disconnect` removes only entries recorded there that still point at the recorded URL. `cmd/mcp_connect_e2e_test.go` runs the real harness CLIs when they are installed; re-run it when a harness changes its MCP config format.
+- Beacon Managed MCP registration via `beacon mcp connect|disconnect|status` (`cli/beacon/internal/mcpconnect`, `cli/beacon/cmd/mcp_connect.go`; docs in `docs/cli/mcp-connect.mdx`). It registers the Beacon Managed MCP server as `beacon-managed`, a different name from the local stdio server `beacon`, in the user-level config of Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode. It prints manual steps for runtimes without confirmed MCP OAuth support. OAuth is the default and writes only the URL; `--token-env` writes a reference to an environment variable in each harness's own syntax, never a value. `connect` never reads or copies the account token and never writes a token; minting one is the separate, explicit `beacon mcp token create`. It is explicit and interactive: never run by `endpoint install` or onboarding (the install only suggests it after the wizard's Managed choice), refused as root, and refused in CI or without a terminal unless `--yes` is given. Its one network request is the RFC 9728 resource-metadata check of the URL, which `--dry-run` skips. Configs are edited like the Kimi Code writer: never re-serialized, spliced as text, parsed back and compared before an atomic replace, backed up first. What was written is recorded in `~/.beacon/mcp/connections.json`, and `disconnect` removes only entries recorded there that still point at the recorded URL. `cmd/mcp_connect_e2e_test.go` runs the real harness CLIs when they are installed; re-run it when a harness changes its MCP config format.
- An optional, off-by-default policy seam in the hook path (`cli/beacon-hooks/internal/policy`) governed by the stable contract in `pkg/asymptoteobserve/policycontract`. When `BEACON_POLICY_PROVIDER` names an executable, the `pre-tool` and `permission-request` hooks send it a JSON request describing the imminent tool call and honor an allow/deny response, returning the runtime's native deny shape and `policy.enforcement=enforce` telemetry on a deny. The seam is inert when unset and fail-open on any error (timeout, non-zero exit, malformed output), so the open build ships no enforcement of its own; all audit/enforce decision logic lives in the external provider. `rules/agent-control/agent-permission-bypass-spawn.rule.yaml` is the open detect twin that flags the same pattern in `beacon scan`.
Current non-goals unless explicitly requested:
diff --git a/cli/beacon/cmd/mcp_token.go b/cli/beacon/cmd/mcp_token.go
new file mode 100644
index 00000000..d3fdcc76
--- /dev/null
+++ b/cli/beacon/cmd/mcp_token.go
@@ -0,0 +1,111 @@
+package cmd
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
+)
+
+// `beacon mcp token create` mints a personal Beacon Managed MCP token with the signed-in account.
+// The token goes to stdout exactly once, so it can be captured into a variable for
+// `beacon mcp connect --token-env`; everything else goes to stderr. It is never written to a
+// file, and the account token that authorizes the request is never printed.
+
+const defaultMCPTokenExpiryDays = 90
+
+var (
+ mcpTokenAccountLoad = account.Load
+ mcpTokenCreate = account.CreateMCPToken
+ mcpTokenHostname = os.Hostname
+ mcpTokenHTTPClient = &http.Client{Timeout: 30 * time.Second}
+)
+
+var mcpTokenOpts struct {
+ name string
+ expiresInDays int
+ json bool
+}
+
+var mcpTokenCmd = &cobra.Command{
+ Use: "token",
+ Short: "Manage personal Beacon Managed MCP tokens",
+}
+
+var mcpTokenCreateCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a personal Beacon Managed MCP token with your Beacon sign-in",
+ Long: `Create a personal Beacon Managed MCP token for the account signed in with ` + "`beacon login`" + `.
+
+The token is printed to stdout once and cannot be shown again; progress and details go to
+stderr. Capture it into a variable and reference that variable with
+` + "`beacon mcp connect --token-env`" + `:
+
+ export BEACON_MCP_TOKEN="$(beacon mcp token create --name laptop)"
+ beacon mcp connect --token-env BEACON_MCP_TOKEN
+
+The token reads your Beacon Managed data and counts toward the limit of 25 active tokens.
+Revoke it at beacon.sh → Dashboard → MCP Access. Beacon never writes it to a file.`,
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: runMCPTokenCreate,
+}
+
+func init() {
+ mcpCmd.AddCommand(mcpTokenCmd)
+ mcpTokenCmd.AddCommand(mcpTokenCreateCmd)
+ f := mcpTokenCreateCmd.Flags()
+ f.StringVar(&mcpTokenOpts.name, "name", "", "Token name shown in the dashboard (default: beacon-cli on this machine's hostname)")
+ f.IntVar(&mcpTokenOpts.expiresInDays, "expires-in-days", defaultMCPTokenExpiryDays, fmt.Sprintf("Days until the token expires, 1-%d, or 0 for never", account.MaxMCPTokenExpiryDays))
+ f.BoolVar(&mcpTokenOpts.json, "json", false, "Print the token and its details as JSON on stdout")
+}
+
+func runMCPTokenCreate(cmd *cobra.Command, args []string) error {
+ name := mcpTokenOpts.name
+ if name == "" {
+ name = "beacon-cli"
+ if host, err := mcpTokenHostname(); err == nil && host != "" {
+ name = "beacon-cli on " + host
+ }
+ }
+ req := account.MCPTokenRequest{Name: name, ExpiresInDays: mcpTokenOpts.expiresInDays}
+ if err := account.ValidateMCPTokenRequest(req); err != nil {
+ return err
+ }
+ session, err := mcpTokenAccountLoad()
+ if errors.Is(err, account.ErrNotSignedIn) {
+ return errors.New("not signed in to Beacon: run `beacon login` first")
+ }
+ if err != nil {
+ return err
+ }
+ if session.Expired(time.Now()) {
+ return errors.New("Beacon sign-in expired: run `beacon login` again")
+ }
+ token, err := mcpTokenCreate(commandContext(cmd), *session, req, mcpTokenHTTPClient)
+ if err != nil {
+ return err
+ }
+ if mcpTokenOpts.json {
+ return json.NewEncoder(cmd.OutOrStdout()).Encode(token)
+ }
+ fmt.Fprintln(cmd.OutOrStdout(), token.Token)
+ errOut := cmd.ErrOrStderr()
+ fmt.Fprintf(errOut, "Created MCP token %q (%s).\n", token.Info.Name, token.Info.Prefix)
+ if token.Info.ExpiresAt != nil {
+ fmt.Fprintf(errOut, "Expires: %s\n", token.Info.ExpiresAt.UTC().Format(time.RFC3339))
+ } else {
+ fmt.Fprintln(errOut, "Expires: never")
+ }
+ if token.MCPURL != "" {
+ fmt.Fprintf(errOut, "MCP URL: %s\n", token.MCPURL)
+ }
+ fmt.Fprintln(errOut, "The token is shown only once. Revoke it at beacon.sh → Dashboard → MCP Access.")
+ return nil
+}
diff --git a/cli/beacon/cmd/mcp_token_test.go b/cli/beacon/cmd/mcp_token_test.go
new file mode 100644
index 00000000..ceb3b222
--- /dev/null
+++ b/cli/beacon/cmd/mcp_token_test.go
@@ -0,0 +1,113 @@
+package cmd
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
+)
+
+func withMCPTokenFakes(t *testing.T, session *account.Session, loadErr error) *account.MCPTokenRequest {
+ t.Helper()
+ origLoad, origCreate, origHost, origOpts := mcpTokenAccountLoad, mcpTokenCreate, mcpTokenHostname, mcpTokenOpts
+ t.Cleanup(func() {
+ mcpTokenAccountLoad, mcpTokenCreate, mcpTokenHostname, mcpTokenOpts = origLoad, origCreate, origHost, origOpts
+ })
+ mcpTokenOpts.name, mcpTokenOpts.expiresInDays, mcpTokenOpts.json = "", defaultMCPTokenExpiryDays, false
+ mcpTokenAccountLoad = func() (*account.Session, error) { return session, loadErr }
+ mcpTokenHostname = func() (string, error) { return "mac.local", nil }
+ sent := &account.MCPTokenRequest{}
+ mcpTokenCreate = func(_ context.Context, s account.Session, req account.MCPTokenRequest, _ *http.Client) (*account.MCPToken, error) {
+ *sent = req
+ return &account.MCPToken{Token: "bcn_mcp_secret", MCPURL: "https://mcp.beacon.sh", Info: account.MCPTokenInfo{Name: req.Name, Prefix: "bcn_mcp_sec"}}, nil
+ }
+ return sent
+}
+
+func runMCPTokenCreateForTest(t *testing.T) (string, string, error) {
+ t.Helper()
+ var stdout, stderr bytes.Buffer
+ cmd := &cobra.Command{}
+ cmd.SetContext(context.Background())
+ cmd.SetOut(&stdout)
+ cmd.SetErr(&stderr)
+ err := runMCPTokenCreate(cmd, nil)
+ return stdout.String(), stderr.String(), err
+}
+
+func signedInMCPSession() *account.Session {
+ return &account.Session{
+ BaseURL: "https://beacon.sh", AccessToken: "never-print-this-token", TokenType: "Bearer",
+ ExpiresAt: time.Now().Add(time.Hour),
+ Scopes: []string{account.ScopeProfileRead, account.ScopeDeviceEnroll, account.ScopeMCPTokenCreate},
+ }
+}
+
+func TestMCPTokenCreatePrintsOnlyTheTokenOnStdout(t *testing.T) {
+ sent := withMCPTokenFakes(t, signedInMCPSession(), nil)
+ stdout, stderr, err := runMCPTokenCreateForTest(t)
+ if err != nil {
+ t.Fatalf("runMCPTokenCreate: %v", err)
+ }
+ if stdout != "bcn_mcp_secret\n" {
+ t.Fatalf("stdout = %q", stdout)
+ }
+ if strings.Contains(stderr, "bcn_mcp_secret") || strings.Contains(stdout+stderr, "never-print-this-token") {
+ t.Fatalf("stderr leaked a secret: %q", stderr)
+ }
+ if sent.Name != "beacon-cli on mac.local" || sent.ExpiresInDays != defaultMCPTokenExpiryDays {
+ t.Fatalf("request = %#v", sent)
+ }
+}
+
+func TestMCPTokenCreateJSON(t *testing.T) {
+ withMCPTokenFakes(t, signedInMCPSession(), nil)
+ mcpTokenOpts.json = true
+ stdout, _, err := runMCPTokenCreateForTest(t)
+ if err != nil {
+ t.Fatalf("runMCPTokenCreate: %v", err)
+ }
+ var out map[string]any
+ if err := json.Unmarshal([]byte(stdout), &out); err != nil || out["token"] != "bcn_mcp_secret" || out["mcp_url"] != "https://mcp.beacon.sh" {
+ t.Fatalf("stdout = %q err = %v", stdout, err)
+ }
+ if strings.Contains(stdout, "never-print-this-token") {
+ t.Fatal("JSON leaked the account token")
+ }
+}
+
+func TestMCPTokenCreateRefusesBeforeCalling(t *testing.T) {
+ expired := signedInMCPSession()
+ expired.ExpiresAt = time.Now().Add(-time.Hour)
+ for name, tc := range map[string]struct {
+ session *account.Session
+ loadErr error
+ days int
+ want string
+ }{
+ "not signed in": {nil, account.ErrNotSignedIn, defaultMCPTokenExpiryDays, "beacon login"},
+ "expired": {expired, nil, defaultMCPTokenExpiryDays, "expired"},
+ "bad expiry": {signedInMCPSession(), nil, 400, "between 0"},
+ } {
+ t.Run(name, func(t *testing.T) {
+ withMCPTokenFakes(t, tc.session, tc.loadErr)
+ mcpTokenOpts.expiresInDays = tc.days
+ called := false
+ mcpTokenCreate = func(context.Context, account.Session, account.MCPTokenRequest, *http.Client) (*account.MCPToken, error) {
+ called = true
+ return nil, nil
+ }
+ stdout, _, err := runMCPTokenCreateForTest(t)
+ if err == nil || !strings.Contains(err.Error(), tc.want) || called || stdout != "" {
+ t.Fatalf("err = %v called = %t stdout = %q", err, called, stdout)
+ }
+ })
+ }
+}
diff --git a/cli/beacon/internal/account/login.go b/cli/beacon/internal/account/login.go
index 77df7104..a2c0b765 100644
--- a/cli/beacon/internal/account/login.go
+++ b/cli/beacon/internal/account/login.go
@@ -34,8 +34,15 @@ const (
CLIGrantVersion = "2026-09-01"
ScopeProfileRead = "profile:read"
ScopeDeviceEnroll = "device:enroll"
+ // ScopeMCPTokenCreate lets the account token mint personal Beacon Managed MCP
+ // tokens (`beacon mcp token create`). The sign-in page lists it, and beacon.sh
+ // approves the sign-in only when the permissions it showed match these.
+ ScopeMCPTokenCreate = "mcp:token:create"
)
+// LoginScopes are the permissions every `beacon login` asks for.
+var LoginScopes = []string{ScopeProfileRead, ScopeDeviceEnroll, ScopeMCPTokenCreate}
+
type LoginOptions struct {
BaseURL string
Version string
@@ -180,13 +187,13 @@ func Login(ctx context.Context, opts LoginOptions) (*Session, error) {
Arch: runtime.GOARCH,
GrantVersion: CLIGrantVersion,
},
- Scopes: []string{ScopeProfileRead, ScopeDeviceEnroll},
+ Scopes: LoginScopes,
}, nil); err != nil {
return nil, fmt.Errorf("start Beacon sign-in: %w", err)
}
port := callback.Port()
- loginURL := buildLoginURL(baseURL, pkce.State, port)
+ loginURL := buildLoginURL(baseURL, pkce.State, port, LoginScopes)
report := opts.OnPrompt
if report != nil {
out = io.Discard
@@ -352,7 +359,10 @@ func SSHForwardCommand(port int) string {
return fmt.Sprintf("ssh -L %d:127.0.0.1:%d <this machine>", port, port)
}
-func buildLoginURL(baseURL, state string, port int) string {
+// buildLoginURL is the sign-in page for this request. scopes goes along space-separated so the
+// page shows every permission requested; beacon.sh refuses the approval if they differ from the
+// ones sent to LoginInitPath.
+func buildLoginURL(baseURL, state string, port int, scopes []string) string {
u, err := url.Parse(baseURL + LoginPagePath)
if err != nil {
return baseURL + LoginPagePath
@@ -360,7 +370,8 @@ func buildLoginURL(baseURL, state string, port int) string {
query := u.Query()
query.Set("state", state)
query.Set("port", fmt.Sprint(port))
- u.RawQuery = query.Encode()
+ query.Set("scopes", strings.Join(scopes, " "))
+ u.RawQuery = strings.ReplaceAll(query.Encode(), "+", "%20")
return u.String()
}
diff --git a/cli/beacon/internal/account/login_test.go b/cli/beacon/internal/account/login_test.go
index 57e86320..bcea318b 100644
--- a/cli/beacon/internal/account/login_test.go
+++ b/cli/beacon/internal/account/login_test.go
@@ -83,6 +83,12 @@ func (s *fakeAuthService) approve(t *testing.T) func(string) error {
if parsed.Query().Get("code_challenge") != "" {
t.Errorf("login URL leaked code challenge: %s", rawURL)
}
+ if got, want := parsed.Query().Get("scopes"), strings.Join(LoginScopes, " "); got != want {
+ t.Errorf("login URL scopes = %q, want %q", got, want)
+ }
+ if strings.Contains(parsed.RawQuery, "+") {
+ t.Errorf("login URL encodes spaces as +: %s", rawURL)
+ }
state, port := parsed.Query().Get("state"), parsed.Query().Get("port")
go func() {
callbackURL := fmt.Sprintf("http://127.0.0.1:%s/callback?state=%s&exchange_code=code-123", port, state)
@@ -131,7 +137,7 @@ func TestLoginUsesPKCEAndReturnsPrivateSession(t *testing.T) {
t.Fatalf("client payload = %#v", client)
}
scopes := service.init["scopes"].([]any)
- if len(scopes) != 2 || scopes[0] != ScopeProfileRead || scopes[1] != ScopeDeviceEnroll {
+ if len(scopes) != 3 || scopes[0] != ScopeProfileRead || scopes[1] != ScopeDeviceEnroll || scopes[2] != ScopeMCPTokenCreate {
t.Fatalf("requested scopes = %#v", scopes)
}
if service.exchange["state"] != service.init["state"] || service.exchange["exchange_code"] != "code-123" || service.exchange["code_verifier"] == "" {
diff --git a/cli/beacon/internal/account/mcp_token.go b/cli/beacon/internal/account/mcp_token.go
new file mode 100644
index 00000000..49ca4abb
--- /dev/null
+++ b/cli/beacon/internal/account/mcp_token.go
@@ -0,0 +1,143 @@
+package account
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+)
+
+const (
+ MCPTokenPath = "/api/cli/mcp/tokens"
+ // MaxMCPTokenExpiryDays is the longest lifetime beacon.sh accepts; 0 means the token never
+ // expires.
+ MaxMCPTokenExpiryDays = 366
+ maxMCPTokenNameLength = 100
+ mcpTokenPrefix = "bcn_mcp_"
+)
+
+// ErrMCPTokenScope means the signed-in session cannot mint MCP tokens: it was issued before
+// `beacon login` asked for ScopeMCPTokenCreate, or beacon.sh refused that scope.
+var ErrMCPTokenScope = errors.New("this Beacon sign-in cannot create MCP tokens: run `beacon login` again")
+
+type MCPTokenRequest struct {
+ Name string `json:"name"`
+ ExpiresInDays int `json:"expires_in_days"`
+}
+
+// MCPTokenInfo describes a created token. It never holds the token itself.
+type MCPTokenInfo struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Prefix string `json:"prefix"`
+ Scopes []string `json:"scopes"`
+ CreatedAt time.Time `json:"created_at"`
+ ExpiresAt *time.Time `json:"expires_at"`
+}
+
+// MCPToken is the response of MCPTokenPath: the same shape as the dashboard's MCP token
+// creation. Token is shown once and cannot be retrieved again.
+type MCPToken struct {
+ Token string `json:"token"`
+ Info MCPTokenInfo `json:"access_token"`
+ MCPURL string `json:"mcp_url"`
+}
+
+// ValidateMCPTokenRequest applies beacon.sh's limits locally, so a bad name or lifetime is
+// reported without sending the account token anywhere.
+func ValidateMCPTokenRequest(req MCPTokenRequest) error {
+ name := strings.TrimSpace(req.Name)
+ switch {
+ case name == "":
+ return errors.New("an MCP token needs a name")
+ case len([]rune(name)) > maxMCPTokenNameLength:
+ return fmt.Errorf("an MCP token name can be at most %d characters", maxMCPTokenNameLength)
+ case strings.ContainsRune(name, 0):
+ return errors.New("an MCP token name cannot contain NUL")
+ case req.ExpiresInDays < 0 || req.ExpiresInDays > MaxMCPTokenExpiryDays:
+ return fmt.Errorf("expiry must be between 0 (never) and %d days", MaxMCPTokenExpiryDays)
+ }
+ return nil
+}
+
+// CreateMCPToken mints a personal Beacon Managed MCP token for the signed-in user. The account
+// token authorizes the request and is sent only to the session's own auth service.
+func CreateMCPToken(ctx context.Context, session Session, req MCPTokenRequest, client *http.Client) (*MCPToken, error) {
+ req.Name = strings.TrimSpace(req.Name)
+ if err := ValidateMCPTokenRequest(req); err != nil {
+ return nil, err
+ }
+ if !secureURL(session.BaseURL) {
+ return nil, errors.New("refusing to send the Beacon credential to an insecure URL")
+ }
+ if session.AccessToken == "" {
+ return nil, ErrNotSignedIn
+ }
+ if !hasScope(session.Scopes, ScopeMCPTokenCreate) {
+ return nil, ErrMCPTokenScope
+ }
+ if client == nil {
+ client = &http.Client{Timeout: defaultTimeout}
+ }
+ // A redirect would resend the account token somewhere else.
+ clientCopy := *client
+ clientCopy.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ body, err := json.Marshal(req)
+ if err != nil {
+ return nil, err
+ }
+ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(session.BaseURL, "/")+MCPTokenPath, bytes.NewReader(body))
+ if err != nil {
+ return nil, err
+ }
+ httpReq.Header.Set("Authorization", firstNonEmpty(session.TokenType, "Bearer")+" "+session.AccessToken)
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("Accept", "application/json")
+ httpReq.Header.Set("User-Agent", CLIClientName)
+ resp, err := clientCopy.Do(httpReq)
+ if err != nil {
+ return nil, fmt.Errorf("create MCP token: %w", err)
+ }
+ defer resp.Body.Close()
+ payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if err != nil {
+ return nil, fmt.Errorf("create MCP token: %w", err)
+ }
+ if resp.StatusCode < 200 || resp.StatusCode > 299 {
+ var failure struct {
+ Detail string `json:"detail"`
+ Error string `json:"error"`
+ }
+ _ = json.Unmarshal(payload, &failure)
+ detail := firstNonEmpty(failure.Detail, failure.Error, fmt.Sprintf("HTTP %d", resp.StatusCode))
+ switch resp.StatusCode {
+ case http.StatusUnauthorized:
+ return nil, fmt.Errorf("Beacon rejected the sign-in (%s): run `beacon login` again", detail)
+ case http.StatusForbidden:
+ return nil, ErrMCPTokenScope
+ }
+ return nil, fmt.Errorf("create MCP token: %s", detail)
+ }
+ var token MCPToken
+ if err := json.Unmarshal(payload, &token); err != nil {
+ return nil, fmt.Errorf("parse MCP token response: %w", err)
+ }
+ if !strings.HasPrefix(token.Token, mcpTokenPrefix) {
+ return nil, errors.New("MCP token response did not include a token")
+ }
+ return &token, nil
+}
+
+func hasScope(scopes []string, target string) bool {
+ for _, scope := range scopes {
+ if scope == target {
+ return true
+ }
+ }
+ return false
+}
diff --git a/cli/beacon/internal/account/mcp_token_test.go b/cli/beacon/internal/account/mcp_token_test.go
new file mode 100644
index 00000000..571e58d9
--- /dev/null
+++ b/cli/beacon/internal/account/mcp_token_test.go
@@ -0,0 +1,127 @@
+package account
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func mcpSession(baseURL string) Session {
+ return Session{
+ BaseURL: baseURL,
+ AccessToken: "bcn_cli_test_secret",
+ TokenType: "Bearer",
+ Scopes: []string{ScopeProfileRead, ScopeDeviceEnroll, ScopeMCPTokenCreate},
+ }
+}
+
+func TestCreateMCPTokenPostsNameAndExpiryWithAccountToken(t *testing.T) {
+ var authorization string
+ var request map[string]any
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != MCPTokenPath {
+ http.NotFound(w, r)
+ return
+ }
+ authorization = r.Header.Get("Authorization")
+ _ = json.NewDecoder(r.Body).Decode(&request)
+ w.WriteHeader(http.StatusCreated)
+ _, _ = w.Write([]byte(`{"token":"bcn_mcp_secret","access_token":{"id":"tok-1","name":"laptop","prefix":"bcn_mcp_sec","scopes":["mcp:read"],"created_at":"2026-09-28T00:00:00Z","expires_at":"2026-10-28T00:00:00Z"},"mcp_url":"https://mcp.beacon.sh"}`))
+ }))
+ defer server.Close()
+
+ token, err := CreateMCPToken(context.Background(), mcpSession(server.URL), MCPTokenRequest{Name: " laptop ", ExpiresInDays: 30}, server.Client())
+ if err != nil {
+ t.Fatalf("CreateMCPToken returned error: %v", err)
+ }
+ if authorization != "Bearer bcn_cli_test_secret" {
+ t.Fatalf("authorization = %q", authorization)
+ }
+ if request["name"] != "laptop" || request["expires_in_days"] != float64(30) {
+ t.Fatalf("request = %#v", request)
+ }
+ if token.Token != "bcn_mcp_secret" || token.Info.ID != "tok-1" || token.Info.ExpiresAt == nil || token.MCPURL != "https://mcp.beacon.sh" {
+ t.Fatalf("token = %#v", token)
+ }
+}
+
+func TestCreateMCPTokenNeedsTheScopeBeforeSendingAnything(t *testing.T) {
+ called := false
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true }))
+ defer server.Close()
+
+ session := mcpSession(server.URL)
+ session.Scopes = []string{ScopeProfileRead, ScopeDeviceEnroll}
+ _, err := CreateMCPToken(context.Background(), session, MCPTokenRequest{Name: "laptop"}, server.Client())
+ if !errors.Is(err, ErrMCPTokenScope) || called {
+ t.Fatalf("err = %v called = %t", err, called)
+ }
+}
+
+func TestCreateMCPTokenRejectsUnsafeInputs(t *testing.T) {
+ for name, tc := range map[string]struct {
+ session Session
+ req MCPTokenRequest
+ }{
+ "insecure url": {mcpSession("http://beacon.example.com"), MCPTokenRequest{Name: "laptop"}},
+ "empty name": {mcpSession("https://beacon.sh"), MCPTokenRequest{Name: " "}},
+ "long name": {mcpSession("https://beacon.sh"), MCPTokenRequest{Name: strings.Repeat("n", 101)}},
+ "negative days": {mcpSession("https://beacon.sh"), MCPTokenRequest{Name: "laptop", ExpiresInDays: -1}},
+ "too many days": {mcpSession("https://beacon.sh"), MCPTokenRequest{Name: "laptop", ExpiresInDays: 367}},
+ "no access token": {Session{BaseURL: "https://beacon.sh", Scopes: []string{ScopeMCPTokenCreate}}, MCPTokenRequest{Name: "laptop"}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ if _, err := CreateMCPToken(context.Background(), tc.session, tc.req, nil); err == nil {
+ t.Fatal("CreateMCPToken accepted unsafe input")
+ }
+ })
+ }
+}
+
+func TestCreateMCPTokenReportsServerRefusals(t *testing.T) {
+ for name, tc := range map[string]struct {
+ status int
+ body string
+ want string
+ }{
+ "old login": {http.StatusForbidden, `{"detail":"access token does not grant MCP token creation; run beacon login again"}`, "run `beacon login` again"},
+ "bad token": {http.StatusUnauthorized, `{"detail":"invalid access token"}`, "invalid access token"},
+ "token limit": {http.StatusConflict, `{"detail":"revoke an existing token before creating another; at most 25 can be active"}`, "at most 25"},
+ "no token": {http.StatusCreated, `{"mcp_url":"https://mcp.beacon.sh"}`, "did not include a token"},
+ } {
+ t.Run(name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(tc.status)
+ _, _ = w.Write([]byte(tc.body))
+ }))
+ defer server.Close()
+ _, err := CreateMCPToken(context.Background(), mcpSession(server.URL), MCPTokenRequest{Name: "laptop"}, server.Client())
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("err = %v, want %q", err, tc.want)
+ }
+ })
+ }
+}
+
+func TestCreateMCPTokenDoesNotFollowRedirects(t *testing.T) {
+ var leaked string
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ leaked = r.Header.Get("Authorization")
+ }))
+ defer target.Close()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)
+ }))
+ defer server.Close()
+
+ if _, err := CreateMCPToken(context.Background(), mcpSession(server.URL), MCPTokenRequest{Name: "laptop"}, server.Client()); err == nil {
+ t.Fatal("CreateMCPToken succeeded on a redirect")
+ }
+ if leaked != "" {
+ t.Fatalf("redirect target received Authorization %q", leaked)
+ }
+}
diff --git a/docs/cli/account-auth.mdx b/docs/cli/account-auth.mdx
index f3a3d65a..f3b37f3b 100644
--- a/docs/cli/account-auth.mdx
+++ b/docs/cli/account-auth.mdx
@@ -95,11 +95,12 @@ Signing out does not stop an already configured managed forwarder. Use `beacon e
The CLI uses the versioned `2026-09-01` grant contract:
- `POST /api/cli/auth/init` registers the PKCE challenge, state, loopback port, CLI version, operating system, and architecture.
-- `GET /cli/auth?state=...&port=...` authenticates the person and redirects to the loopback callback with `state` and a one-time `exchange_code`.
+- `GET /cli/auth?state=...&port=...&scopes=...` authenticates the person, lists every requested scope (space-separated in `scopes`), and redirects to the loopback callback with `state` and a one-time `exchange_code`.
- `POST /api/cli/auth/exchange` accepts the exchange code, state, and PKCE verifier. It returns a scoped access token, expiry, user identity, organization memberships, and optional active organization.
+- `POST /api/cli/mcp/tokens` accepts `{"name": ..., "expires_in_days": ...}` with the access token as a Bearer credential and returns a personal Beacon Managed MCP token (`token`, `access_token` metadata, `mcp_url`). It requires `mcp:token:create`.
- `POST /api/cli/auth/revoke` accepts the access token as a Bearer credential and revokes it.
-The intended initial scopes are `profile:read` and `device:enroll`. A later `beacon endpoint connect` can use `device:enroll` to mint a device-specific ingest key without treating the account token as an ingest credential.
+`beacon login` requests `profile:read`, `device:enroll` and `mcp:token:create`. A later `beacon endpoint connect` can use `device:enroll` to mint a device-specific ingest key without treating the account token as an ingest credential, and `beacon mcp token create` uses `mcp:token:create` to mint a personal MCP token. beacon.sh approves the sign-in only when the permissions its page showed match the ones the CLI registered, so a crafted link cannot hide one. A session from an older `beacon login` lacks `mcp:token:create`; run `beacon login` again to create MCP tokens from the CLI.
For that enrollment, `beacon endpoint connect` sends the machine description to
`POST /api/cli/enroll/account` with the CLI access token. The response uses the
diff --git a/docs/cli/mcp-connect.mdx b/docs/cli/mcp-connect.mdx
index bc7700d6..a9103468 100644
--- a/docs/cli/mcp-connect.mdx
+++ b/docs/cli/mcp-connect.mdx
@@ -128,11 +128,12 @@ harness connects, Beacon Managed answers `401` with a pointer to its OAuth metad
then registers itself, opens a browser, and you approve access on beacon.sh. No secret is written
by Beacon, and access is revoked from the dashboard.
-**A personal token** is for harnesses or setups where browser sign-in does not work. Create one at
-beacon.sh → Dashboard → MCP Access, export it, and connect with `--token-env`:
+**A personal token** is for harnesses or setups where browser sign-in does not work. Create one
+with `beacon mcp token create` (or at beacon.sh → Dashboard → MCP Access), export it, and connect
+with `--token-env`:
```bash
-export BEACON_MCP_TOKEN=... # from beacon.sh → Dashboard → MCP Access
+export BEACON_MCP_TOKEN="$(beacon mcp token create --name laptop)"
beacon mcp connect --token-env BEACON_MCP_TOKEN
```
@@ -141,10 +142,33 @@ written, and connect refuses a `--token-env` value that looks like a token rathe
name. The harness must be started from an environment where the variable is set.
<Warning>
- Beacon does not create MCP tokens. The Beacon account token from `beacon login` is never copied
- into a harness config, an environment, a log or the command's output.
+ `beacon mcp connect` never creates or writes a token. The Beacon account token from
+ `beacon login` is never copied into a harness config, an environment, a log or any command's
+ output.
</Warning>
+## Create a token from the CLI
+
+```bash
+beacon mcp token create [--name NAME] [--expires-in-days N] [--json]
+```
+
+`beacon mcp token create` uses your `beacon login` session to create a personal MCP token. The
+token is printed to stdout once and cannot be shown again; its name, prefix, expiry and the MCP URL
+go to stderr, so `$(...)` captures only the token. `--json` prints the token and its details as
+JSON on stdout instead. Beacon never writes the token to a file.
+
+| Flag | Meaning |
+|---|---|
+| `--name NAME` | Name shown in the dashboard (default `beacon-cli on <hostname>`) |
+| `--expires-in-days N` | Days until the token expires, 1 to 366, or 0 for never (default 90) |
+| `--json` | Print the token and its details as JSON |
+
+The token reads your Beacon Managed data, counts toward the limit of 25 active tokens, and is
+revoked at beacon.sh → Dashboard → MCP Access. It needs the `mcp:token:create` permission, which
+`beacon login` requests and the sign-in page lists; a session from an older `beacon login` is
+refused with a prompt to sign in again.
+
## Per-harness notes
Connect writes these entries (OAuth mode shown, then what `--token-env NAME` adds):
diff --git a/docs/cli/mcp.mdx b/docs/cli/mcp.mdx
index 8fa0637a..d68fc63a 100644
--- a/docs/cli/mcp.mdx
+++ b/docs/cli/mcp.mdx
@@ -27,12 +27,13 @@ the other:
| Server name | What it reads | Commands |
|---|---|---|
| `beacon` | This machine's `runtime.jsonl` and approved local memory, served locally over stdio or loopback HTTP | [`serve`](/cli/mcp-serve), [`doctor`](/cli/mcp-doctor) |
-| `beacon-managed` | The session history this endpoint forwards to Beacon Managed, served by Beacon Managed over HTTPS | [`connect`, `disconnect`, `status`](/cli/mcp-connect) |
+| `beacon-managed` | The session history this endpoint forwards to Beacon Managed, served by Beacon Managed over HTTPS | [`connect`, `disconnect`, `status`, `token create`](/cli/mcp-connect) |
`beacon mcp connect` registers `beacon-managed` in Claude Code, Codex CLI, Cursor, VS Code,
Gemini CLI and OpenCode. By default it writes only the URL, and each harness signs in with OAuth.
-With `--token-env`, the config instead references a personal token from beacon.sh → Dashboard →
-MCP Access, held in an environment variable. For other harnesses it prints the steps to add the
+With `--token-env`, the config instead references a personal token, created with
+`beacon mcp token create` or at beacon.sh → Dashboard → MCP Access and held in an environment
+variable. For other harnesses it prints the steps to add the
server by hand.
## Commands