Skip to content

Agent Mesh

feat(sam-node): support run --join for one-command enroll-and-run

Antonio Ojea5e15a8dfb17c
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index bf8622f7..b3266500 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -31,6 +31,7 @@ import (
"github.com/google/sam/internal/node"
"github.com/google/sam/internal/secrets"
golog "github.com/ipfs/go-log/v2"
+ "github.com/mattn/go-isatty"
"github.com/multiformats/go-multiaddr"
madns "github.com/multiformats/go-multiaddr-dns"
"github.com/spf13/cobra"
@@ -52,6 +53,7 @@ func init() {
var (
controlPlaneAddr string
+ joinFlag bool
jwtFlag string
jwtPathFlag string
bootstrapTokenFlag string
@@ -120,6 +122,63 @@ func resolveDaemonSecret(name, path, envVar string) string {
return secret
}
+// isInteractiveTerminal reports whether stdin is a real terminal (not just a
+// character device like /dev/null), so --join knows it can safely block on
+// an interactive OIDC login prompt.
+func isInteractiveTerminal() bool {
+ fd := os.Stdin.Fd()
+ return isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd)
+}
+
+// defaultControlPlane resolves which control plane to use when none was
+// explicitly passed: the previously stored one, or the public testnet.
+func defaultControlPlane(store *node.Store, explicit string) string {
+ if explicit != "" {
+ return explicit
+ }
+ if h, err := store.LoadControlPlaneURL(); err == nil && h != "" {
+ return h
+ }
+ return "https://bananas.sam-mesh.dev"
+}
+
+// normalizeControlPlaneURL adds the https:// scheme if missing and drops any
+// trailing slash.
+func normalizeControlPlaneURL(url string) string {
+ if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
+ url = "https://" + url
+ }
+ return strings.TrimSuffix(url, "/")
+}
+
+// interactiveJoin discovers a control plane's OIDC settings and completes an
+// interactive browser/device-code login against it. Shared by "join" and
+// "run --join"; targetControlPlane must already be a normalized URL.
+func interactiveJoin(ctx context.Context, targetControlPlane string) (string, *api.ControlPlaneInfoResponse, error) {
+ dummyNode := &node.SamNode{}
+
+ fmt.Printf("Discovering control plane info from %s...\n", targetControlPlane)
+ info, err := node.FetchControlPlaneInfo(ctx, targetControlPlane)
+ if err != nil {
+ return "", nil, fmt.Errorf("failed to discover control plane info: %w", err)
+ }
+
+ fmt.Printf("OIDC Issuer discovered: %s\n", info.OidcIssuer)
+ fmt.Printf("Client ID discovered: %s\n", info.ClientId)
+
+ logger.Info("Discovering OIDC endpoints...")
+ tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, info.OidcIssuer)
+ if err != nil {
+ return "", nil, fmt.Errorf("failed to discover OIDC endpoints: %w", err)
+ }
+
+ jwtStr, err := dummyNode.InteractiveLogin(ctx, authURL, tokenURL, info.ClientId, info.Audience, offlineAccessFlag, headlessFlag)
+ if err != nil {
+ return "", nil, fmt.Errorf("failed to get token: %w", err)
+ }
+ return jwtStr, info, nil
+}
+
// parseLabelsFlag parses a comma-separated "key=value" list (see
// api/labels.go) into a label map; an empty string means no claims.
func parseLabelsFlag(s string) (map[string]string, error) {
@@ -224,6 +283,7 @@ func main() {
var meshNode *node.SamNode
var jwtStr string
+ var controlPlaneInfo *api.ControlPlaneInfoResponse
if jwtFlag != "" {
jwtStr = jwtFlag
@@ -247,17 +307,30 @@ func main() {
}
}
+ if jwtStr == "" && bootstrapTokenFlag == "" && joinFlag {
+ token, _ := store.LoadIdentity()
+ switch {
+ case len(token) > 0 && len(controlPlanePubKey) > 0:
+ logger.Debug("--join set but a usable identity is already stored; ignoring")
+ case !isInteractiveTerminal():
+ logger.Warn("--join set but no interactive terminal available; falling back to out-of-band enrollment via the unauthenticated MCP sidecar")
+ default:
+ if len(token) > 0 {
+ logger.Warn("Stored identity is missing its control plane public key; re-joining")
+ }
+ targetControlPlane := normalizeControlPlaneURL(defaultControlPlane(store, controlPlaneAddr))
+ jwtStr, controlPlaneInfo, err = interactiveJoin(ctx, targetControlPlane)
+ if err != nil {
+ logger.Fatalf("Failed to join: %v", err)
+ }
+ controlPlaneAddr = targetControlPlane
+ }
+ }
+
if jwtStr == "" && bootstrapTokenFlag == "" {
token, _ := store.LoadIdentity()
if len(token) == 0 {
- displayControlPlane := controlPlaneAddr
- if displayControlPlane == "" {
- if h, err := store.LoadControlPlaneURL(); err == nil && h != "" {
- displayControlPlane = h
- } else {
- displayControlPlane = "https://bananas.sam-mesh.dev"
- }
- }
+ displayControlPlane := defaultControlPlane(store, controlPlaneAddr)
logger.Infof("No identity found. Starting unauthenticated sidecar for enrollment over MCP...")
unauthSrv, err := node.StartUnauthSidecarServer(displayControlPlane, bindAddrFlag, tlsCertFlag, tlsKeyFlag)
if err != nil {
@@ -272,7 +345,7 @@ func main() {
logger.Infoln("Using stored identity.")
if len(controlPlanePubKey) == 0 {
- logger.Fatal("Control plane public key not found in store and not provided. Cannot verify peers.")
+ logger.Fatal("Control plane public key not found in store and not provided. Re-run with --join to re-enroll, or pass --control-plane-public-key explicitly.")
}
priv := node.GetOrGenerateKey(store)
meshNode, err = node.NewSamNode(node.Options{
@@ -391,6 +464,11 @@ func main() {
if err := store.SaveControlPlaneURL(controlPlaneAddr); err != nil {
logger.Warnf("Failed to save control plane URL: %v", err)
}
+ if controlPlaneInfo != nil {
+ if err := store.SaveOIDCConfig(controlPlaneInfo.OidcIssuer, controlPlaneInfo.ClientId, controlPlaneInfo.Audience); err != nil {
+ logger.Warnf("Failed to save OIDC config: %v", err)
+ }
+ }
if teardownErr := meshNode.Teardown(); teardownErr != nil {
logger.Errorf("Failed to teardown enrollment node: %v", teardownErr)
@@ -493,10 +571,7 @@ func main() {
targetControlPlane = "https://bananas.sam-mesh.dev"
}
- if !strings.HasPrefix(targetControlPlane, "http://") && !strings.HasPrefix(targetControlPlane, "https://") {
- targetControlPlane = "https://" + targetControlPlane
- }
- targetControlPlane = strings.TrimSuffix(targetControlPlane, "/")
+ targetControlPlane = normalizeControlPlaneURL(targetControlPlane)
bootstrapTokenFlag = resolveSecretFlag("bootstrap-token", bootstrapTokenFlag, bootstrapTokenPathFlag)
@@ -515,28 +590,12 @@ func main() {
}
}()
- dummyNode := &node.SamNode{Store: store}
-
- fmt.Printf("Discovering control plane info from %s...\n", targetControlPlane)
- controlPlaneInfo, err := node.FetchControlPlaneInfo(ctx, targetControlPlane)
- if err != nil {
- logger.Fatalf("Failed to discover control plane info: %v", err)
- }
-
var jwtStr string
+ var controlPlaneInfo *api.ControlPlaneInfoResponse
if bootstrapTokenFlag == "" {
- fmt.Printf("OIDC Issuer discovered: %s\n", controlPlaneInfo.OidcIssuer)
- fmt.Printf("Client ID discovered: %s\n", controlPlaneInfo.ClientId)
-
- logger.Info("Discovering OIDC endpoints...")
- tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, controlPlaneInfo.OidcIssuer)
- if err != nil {
- logger.Fatalf("Failed to discover OIDC endpoints: %v", err)
- }
-
- jwtStr, err = dummyNode.InteractiveLogin(ctx, authURL, tokenURL, controlPlaneInfo.ClientId, controlPlaneInfo.Audience, offlineAccessFlag, headlessFlag)
+ jwtStr, controlPlaneInfo, err = interactiveJoin(ctx, targetControlPlane)
if err != nil {
- logger.Fatalf("Failed to get token: %v", err)
+ logger.Fatalf("Failed to join: %v", err)
}
}
@@ -629,6 +688,7 @@ func main() {
runCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/5001/quic-v1", "/ip4/0.0.0.0/tcp/5002"}, "libp2p Listen Addrs")
runCmd.Flags().StringVar(&jwtFlag, "jwt", "", "Pre-fetched JWT token")
runCmd.Flags().StringVar(&jwtPathFlag, "jwt-path", "", "Path to file containing JWT token")
+ runCmd.Flags().BoolVar(&joinFlag, "join", false, "Enroll interactively on first run if no identity exists yet (defaults to the public testnet unless --control-plane is set); a no-op on later restarts")
runCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")
runCmd.Flags().StringVar(&bootstrapTokenPathFlag, "bootstrap-token-path", "", "Path to file containing the bootstrap token (recommended over --bootstrap-token)")
runCmd.Flags().StringVar(&clientIDFlag, "client-id", "", "OIDC Client ID for M2M")
@@ -647,6 +707,7 @@ func main() {
runCmd.Flags().StringVar(&logLevelFlag, "log-level", "info", "Log level (debug, info, warn, error)")
runCmd.Flags().DurationVar(&keyGracePeriodFlag, "key-grace-period", 24*time.Hour, "Key grace period for old keys (e.g. 24h)")
runCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")
+ runCmd.Flags().BoolVar(&offlineAccessFlag, "offline-access", false, "With --join, request OIDC offline access/refresh token for automatic renewal")
joinCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")
joinCmd.Flags().DurationVar(&routerConnectTimeoutFlag, "router-connect-timeout", node.DefaultRouterConnectTimeout, "Timeout for dialing each router address")
joinCmd.Flags().BoolVar(&offlineAccessFlag, "offline-access", false, "Request OIDC offline access/refresh token for automatic renewal")
diff --git a/cmd/sam-node/main_test.go b/cmd/sam-node/main_test.go
index 19ae03cf..d4ddd88d 100644
--- a/cmd/sam-node/main_test.go
+++ b/cmd/sam-node/main_test.go
@@ -14,7 +14,11 @@
package main
-import "testing"
+import (
+ "testing"
+
+ "github.com/google/sam/internal/node"
+)
func TestParseLabelsFlag(t *testing.T) {
if got, err := parseLabelsFlag(""); got != nil || err != nil {
@@ -34,3 +38,38 @@ func TestParseLabelsFlag(t *testing.T) {
t.Error("duplicate label key must be rejected")
}
}
+
+func TestNormalizeControlPlaneURL(t *testing.T) {
+ cases := map[string]string{
+ "bananas.sam-mesh.dev": "https://bananas.sam-mesh.dev",
+ "http://localhost:8080": "http://localhost:8080",
+ "https://bananas.sam-mesh.dev/": "https://bananas.sam-mesh.dev",
+ }
+ for in, want := range cases {
+ if got := normalizeControlPlaneURL(in); got != want {
+ t.Errorf("normalizeControlPlaneURL(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestDefaultControlPlane(t *testing.T) {
+ store, err := node.NewStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ defer func() { _ = store.Close() }()
+
+ if got := defaultControlPlane(store, "https://example.com"); got != "https://example.com" {
+ t.Errorf("explicit control plane should win: got %q", got)
+ }
+ if got := defaultControlPlane(store, ""); got != "https://bananas.sam-mesh.dev" {
+ t.Errorf("no explicit and no stored URL should default to the testnet: got %q", got)
+ }
+
+ if err := store.SaveControlPlaneURL("https://stored.example.com"); err != nil {
+ t.Fatalf("SaveControlPlaneURL: %v", err)
+ }
+ if got := defaultControlPlane(store, ""); got != "https://stored.example.com" {
+ t.Errorf("no explicit should fall back to the stored URL: got %q", got)
+ }
+}
diff --git a/site/content/docs/integrations/antigravity.md b/site/content/docs/integrations/antigravity.md
index c3269109..3599e16d 100644
--- a/site/content/docs/integrations/antigravity.md
+++ b/site/content/docs/integrations/antigravity.md
@@ -10,7 +10,47 @@ Antigravity natively supports Streamable HTTP MCP servers via the `serverUrl` co
## Prerequisites
-- A running `sam-node` (default `http://localhost:8080`) and its the node API token (`SAM_API_TOKEN` env or `--api-token-path`).
+- `sam-node` installed and able to join a mesh (see the [Quick Start](../quickstart/)).
+- The node API token (`SAM_API_TOKEN` env or `--api-token-path`) you'll launch it with.
+
+## Running the Node Alongside Antigravity
+
+Antigravity talks to `sam-node` as a plain HTTP server rather than launching it itself (unlike a `stdio` MCP server, which the harness spawns and manages). That means `sam-node run` has to already be listening on the configured port *before* Antigravity starts, and keep running for the whole session — in practice, two separate long-running processes.
+
+On the very first run, `--join` needs an interactive terminal to complete the browser/device-code login; after that, the identity is stored and `--join` is a no-op, so the node can be started detached/hidden freely.
+
+### macOS / Linux
+Simplest: leave the node running in its own terminal tab, then open a second tab for Antigravity:
+```bash
+# Terminal 1 — leave running
+SAM_API_TOKEN=my-secret-token sam-node run --join --bind-addr 127.0.0.1:8080
+```
+```bash
+# Terminal 2
+agy
+```
+Or background it in the same shell once you've completed the first interactive login:
+```bash
+SAM_API_TOKEN=my-secret-token nohup sam-node run --join --bind-addr 127.0.0.1:8080 > sam-node.log 2>&1 &
+```
+
+### Windows
+PowerShell and cmd.exe don't have a direct equivalent of Unix job control (`&`), so the straightforward option is the same as macOS/Linux: run `sam-node.exe run --join` in one Windows Terminal/PowerShell tab and leave it running, then open a second tab for Antigravity. To start it detached instead (after the first interactive login):
+```powershell
+Start-Process sam-node.exe -ArgumentList "run","--join","--bind-addr","127.0.0.1:8080" -WindowStyle Hidden
+```
+
+### Any OS: Docker
+The Docker image already runs detached, so it doesn't need a second terminal at all — pass `-it` instead of `-d` only for the first run, to complete the interactive login:
+```bash
+docker run -d --name sam-node \
+ --user "$(id -u):$(id -g)" \
+ -v $(pwd)/sam-data:/data \
+ -p 5001:5001/udp -p 5002:5002 -p 8080:8080 \
+ -e SAM_API_TOKEN=my-secret-token \
+ ghcr.io/google/sam-node:latest \
+ run --join --data-dir /data --bind-addr 0.0.0.0:8080
+```
## Configuration
diff --git a/site/content/docs/quickstart.md b/site/content/docs/quickstart.md
index 2e4510e1..5d90c5de 100644
--- a/site/content/docs/quickstart.md
+++ b/site/content/docs/quickstart.md
@@ -38,20 +38,61 @@ Expand-Archive -Path "sam.zip" -DestinationPath "$env:ProgramFiles\sam"
---
-## 2. Join the Mesh
+## 2. Connect Your Node to the Mesh
-To register your node with the mesh and obtain a cryptographic identity token (Biscuit), you can use either the interactive OIDC authorization flow or the non-interactive bootstrap token flow.
+Getting a node onto the mesh takes two things: **joining** — registering the node and obtaining its cryptographic identity (a Biscuit token) via an OIDC login — and **running** it. The `--join` flag on `run` does both in one command: it enrolls the first time (when the node has no identity yet), then starts serving; on every later restart it's a no-op since the identity is already stored.
-### Option A: Interactive OIDC Flow (Default)
+### Recommended: One Command
+
+#### Using the Binary
+The binary is the simplest way to run a node locally — no volumes or port mapping to think about:
+```bash
+SAM_API_TOKEN=my-secret-token sam-node run --join --bind-addr 127.0.0.1:8080
+```
+The CLI will open your browser for login (or print a device code if headless). Once authenticated:
+```text
+Successfully joined the Sovereign Agent Mesh!
+INFO sam-node [AuthN] Successfully authenticated with router via libp2p: ...
+SAM Node Online.
+PeerID: 12D3KooW...
+```
+
+#### Using Docker
+Docker works the same way, but needs a persistent volume for the identity and explicit port mapping (`5001/udp`, `5002/tcp` for libp2p, `8080/tcp` for the local API):
+```bash
+mkdir -p $(pwd)/sam-data
+docker run -it \
+ --user "$(id -u):$(id -g)" \
+ -v $(pwd)/sam-data:/data \
+ -p 5001:5001/udp \
+ -p 5002:5002 \
+ -p 8080:8080 \
+ -e SAM_API_TOKEN=my-secret-token \
+ ghcr.io/google/sam-node:latest \
+ run --join --data-dir /data --bind-addr 0.0.0.0:8080
+```
+Use `-it` for this first run so you can complete the browser/device-code login; once enrolled, restart it detached with `-d` instead (`--join` is a no-op at that point, so it's safe to leave in your start command). If there's no interactive terminal attached (e.g. `-d` on the very first run), the node instead comes up as an unauthenticated sidecar waiting for out-of-band enrollment over MCP.
+
+By default `--join` enrolls with the public testnet (`bananas.sam-mesh.dev`); pass `--control-plane <url>` to join a different mesh.
+
+### Alternative: Join and Run Separately
+
+If you're deploying headlessly with a pre-issued bootstrap token, or just prefer explicit steps, you can join and run as two commands instead.
+
+#### Step 1: Join the Mesh
+
+To register your node with the mesh and obtain a cryptographic identity token (Biscuit), you can use either the interactive OIDC authorization flow or the non-interactive bootstrap token flow.
+
+##### Option A: Interactive OIDC Flow (Default)
The interactive flow uses your browser to authenticate your identity against Dex (OIDC):
-#### Using the Binary
+###### Using the Binary
```bash
sam-node join https://bananas.sam-mesh.dev
```
-#### Using Docker
+###### Using Docker
```bash
mkdir -p $(pwd)/sam-data
docker run -it \
@@ -63,16 +104,16 @@ docker run -it \
The CLI will output a Device Authorization URL (if headless/Docker) or open your browser natively. Once authenticated, the node registers and saves the identity database.
-### Option B: Non-Interactive Bootstrap Flow (Headless)
+##### Option B: Non-Interactive Bootstrap Flow (Headless)
If you are deploying a headless server or router and have a generated bootstrap token from the Control Plane API:
-#### Using the Binary
+###### Using the Binary
```bash
sam-node join --bootstrap-token <your-token> https://bananas.sam-mesh.dev
```
-#### Using Docker
+###### Using Docker
```bash
mkdir -p $(pwd)/sam-data
docker run -it \
@@ -84,13 +125,11 @@ docker run -it \
*Note: In non-interactive mode, unless the control plane runs with `--auto-approve-enrollment`, the enrollment request remains **PENDING** until approved manually by a network administrator.*
----
-
-## 3. Run the Node
+#### Step 2: Run the Node
Start your node in the background. We set a security API token (via the `SAM_API_TOKEN` environment variable or `--api-token-path` file) to protect access to the local control plane API. Tokens are never accepted as command-line values: they would be visible in process listings.
-### Using the Binary
+##### Using the Binary
```bash
SAM_API_TOKEN=my-secret-token sam-node run --bind-addr 127.0.0.1:8080
```
@@ -101,7 +140,7 @@ SAM Node Online.
PeerID: 12D3KooW...
```
-### Using Docker
+##### Using Docker
Map the required ports (`5001/udp`, `5002/tcp` for libp2p, and `8080/tcp` for the local API):
```bash
mkdir -p $(pwd)/sam-data
@@ -118,7 +157,7 @@ docker run -d \
```
Verify the node is running with `docker logs sam-node`.
-## 4. Query the Local MCP API
+## 3. Query the Local MCP API
Your SAM node exposes a standard Model Context Protocol (MCP) server. The easiest way to interact with it is using the `mcp-client` CLI tool (which is installed alongside `sam-node`):
diff --git a/tests/integration/login_test.go b/tests/integration/login_test.go
index c3179ac1..bcb2c4a0 100644
--- a/tests/integration/login_test.go
+++ b/tests/integration/login_test.go
@@ -117,3 +117,42 @@ func TestSamNodeJoin(t *testing.T) {
t.Fatalf("node did not use stored identity:\n%s", out)
}
}
+
+// TestSamNodeRunJoinNonInteractive covers the safe fallback: since the test
+// harness gives the child process no TTY (stdin defaults to /dev/null),
+// "run --join" must not attempt (and block on) an interactive OIDC login; it
+// should fall back to the same unauthenticated MCP sidecar as plain "run".
+func TestSamNodeRunJoinNonInteractive(t *testing.T) {
+ nodeBin := buildBinary(t, "./cmd/sam-node")
+ tmpHome := t.TempDir()
+ env := []string{
+ "HOME=" + tmpHome,
+ "XDG_CONFIG_HOME=" + filepath.Join(tmpHome, ".config"),
+ }
+
+ _, routerAddr := startMockRouter(t)
+
+ stdout, stderr, err := runCommand(
+ t,
+ repoRoot(t),
+ 3*time.Second,
+ env,
+ "", // no stdin: child sees no TTY, same as a container without -it
+ nodeBin,
+ "run", "--join", "--control-plane", routerAddr,
+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
+ "--listen", "/ip4/127.0.0.1/tcp/0",
+ "--bind-addr", "127.0.0.1:0",
+ )
+ if err != context.DeadlineExceeded {
+ t.Fatalf("expected run --join to keep running via the unauthenticated sidecar, got: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
+ }
+
+ out := stdout + stderr
+ if !strings.Contains(out, "no interactive terminal available") {
+ t.Fatalf("expected --join to warn about falling back without a TTY:\n%s", out)
+ }
+ if !strings.Contains(out, "Starting unauthenticated sidecar for enrollment over MCP") {
+ t.Fatalf("expected the unauthenticated sidecar to start:\n%s", out)
+ }
+}