Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
implement service catalog
Antonio Ojea2d05498b6c1c
diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.goindex 39b43b8b..581f67e3 100644--- a/cmd/sam-hub/main.go+++ b/cmd/sam-hub/main.go@@ -143,7 +143,7 @@ func NewHub(ctx context.Context, policy *api.PolicyConfig) (*Hub, error) {return nil, err}- kadDHT, err := dht.New(ctx, h, dht.Mode(dht.ModeServer))+ kadDHT, err := dht.New(ctx, h, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))if err != nil {return nil, err}diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.goindex de14135e..514c9c1a 100644--- a/cmd/sam-node/main.go+++ b/cmd/sam-node/main.go@@ -20,7 +20,6 @@ import ("encoding/hex""fmt""net"- "net/http""os""os/signal""strings"@@ -58,13 +57,18 @@ var (clientSecretFlag stringtokenURLFlag stringhubPublicKeyFlag string- mcpAddrFlag string+ bindAddrFlag stringmeshFlag stringdiscoveryIntervalFlag stringenableRelayFlag boollogLevelFlag stringlocalPolicyFile stringkeyGracePeriodFlag time.Duration++ apiTokenFlag string+ tlsCertFlag string+ tlsKeyFlag string+ tlsCAFlag string)var logger = golog.Logger("sam-node")@@ -217,8 +221,8 @@ func main() {node.Host.SetStreamHandler(api.AuthProtocolID, node.HandleAuthHandshake)- // Start MCP Server- startMCPServer(node, mcpAddrFlag)+ // Start Sidecar API Server (multiplexed with MCP)+ startSidecarServer(node, bindAddrFlag, apiTokenFlag, tlsCertFlag, tlsKeyFlag, tlsCAFlag)fmt.Printf("SAM Node Online.\nPeerID: %s\nListening on: %v\n", node.Host.ID(), node.Host.Addrs())@@ -305,12 +309,16 @@ func main() {runCmd.Flags().StringVar(&clientIDFlag, "client-id", os.Getenv("SAM_OIDC_ID"), "OIDC Client ID for M2M")runCmd.Flags().StringVar(&clientSecretFlag, "client-secret", os.Getenv("SAM_OIDC_SECRET"), "OIDC Client Secret for M2M")runCmd.Flags().StringVar(&hubPublicKeyFlag, "hub-public-key", "", "Hub Public Key (32-byte Hex)")- runCmd.Flags().StringVar(&mcpAddrFlag, "mcp-addr", "127.0.0.1:8080", "Local TCP address for the MCP HTTP/SSE server")+ runCmd.Flags().StringVar(&bindAddrFlag, "bind-addr", "127.0.0.1:8080", "Local TCP address for the HTTP server (MCP and Sidecar API)")runCmd.Flags().StringVar(&meshFlag, "mesh", DefaultMeshName, "Mesh federation name")runCmd.Flags().StringVar(&discoveryIntervalFlag, "discovery-interval", DefaultDiscoveryInterval, "Polling interval for DHT discovery")runCmd.Flags().BoolVar(&enableRelayFlag, "enable-relay", false, "Allow this node to serve as a relay for others")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().StringVar(&apiTokenFlag, "api-token", "", "Static Bearer token for API authorization")+ runCmd.Flags().StringVar(&tlsCertFlag, "tls-cert", "", "Path to TLS certificate for sidecar API")+ runCmd.Flags().StringVar(&tlsKeyFlag, "tls-key", "", "Path to TLS key for sidecar API")+ runCmd.Flags().StringVar(&tlsCAFlag, "tls-ca", "", "Path to TLS CA for sidecar API mTLS")rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", DefaultHubURL, "Hub URL")rootCmd.PersistentFlags().StringVar(&localPolicyFile, "local-policy", DefaultLocalPolicyFile, "Path to local_policy.yaml")rootCmd.PersistentFlags().StringVar(&tokenURLFlag, "token-url", "", "OIDC Token URL")@@ -355,32 +363,6 @@ func getOrGenerateKey(s *Store) crypto.PrivKey {}return priv}--func startMCPServer(node *SamNode, mcpAddr string) {- mcpHandler := NewMCPHandler(node)- go func() {- if mcpAddr == "" {- mcpAddr = "127.0.0.1:8080"- }-- listener, err := net.Listen("tcp", mcpAddr)- if err != nil {- logger.Errorf("Failed to listen on TCP address %s: %v", mcpAddr, err)- return- }- defer func() {- if err := listener.Close(); err != nil {- logger.Errorf("Failed to close listener: %v", err)- }- }()-- fmt.Printf("Starting MCP server on TCP address %s\n", listener.Addr().String())- if err := http.Serve(listener, mcpHandler); err != nil {- logger.Errorf("MCP server error: %v", err)- }- }()-}-func (n *SamNode) Enroll(ctx context.Context, jwt string) error {if n.HubPeerID == "" {return fmt.Errorf("not connected to any hub")diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.goindex 95adb6e1..83c091c1 100644--- a/cmd/sam-node/node.go+++ b/cmd/sam-node/node.go@@ -46,6 +46,8 @@ import ("github.com/libp2p/go-msgio""github.com/multiformats/go-multiaddr""google.golang.org/protobuf/proto"+ "github.com/ipfs/go-cid"+ "github.com/multiformats/go-multihash")const (@@ -82,6 +84,8 @@ type SamNode struct {trustedKeys []TrustedKeykeysMu sync.RWMutexrateLimiter *PeerRateLimiter+ services map[string]bool+ servicesMu sync.RWMutex}// NewSamNode creates a new Agent instance secured with the 4-layer pipeline.@@ -97,6 +101,7 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.PknownPeers: make(map[string]bool),receivedMsgs: make(map[string][]string),topics: make(map[string]*pubsub.Topic),+ services: make(map[string]bool),LocalPolicy: localPolicy,}@@ -161,7 +166,7 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.Pnode.Host = h// Initialize Rendezvous (DHT Client)- kdht, err := dht.New(ctx, h, dht.Mode(dht.ModeAuto))+ kdht, err := dht.New(ctx, h, dht.Mode(dht.ModeAuto), dht.ProtocolPrefix("/sam"))if err != nil {return nil, err}@@ -602,3 +607,61 @@ func (n *SamNode) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscuireturn nil, fmt.Errorf("no valid key found")}++func serviceNameToCID(name string) (cid.Cid, error) {+ pref := cid.Prefix{+ Version: 1,+ Codec: cid.Raw,+ MhType: multihash.SHA2_256,+ MhLength: -1, // default length+ }+ return pref.Sum([]byte(name))+}++func (n *SamNode) RegisterService(ctx context.Context, serviceName string) error {+ n.servicesMu.Lock()+ n.services[serviceName] = true+ n.servicesMu.Unlock()++ // Announce to DHT+ c, err := serviceNameToCID(serviceName)+ if err != nil {+ return err+ }++ logger.Infof("[ServiceRegistry] Registering service %s (CID: %s)", serviceName, c)+ if n.DHT != nil {+ return n.DHT.Provide(ctx, c, true)+ }+ return nil+}++func (n *SamNode) UnregisterService(ctx context.Context, serviceName string) error {+ n.servicesMu.Lock()+ delete(n.services, serviceName)+ n.servicesMu.Unlock()++ logger.Infof("[ServiceRegistry] Unregistered service %s", serviceName)+ // We can't easily remove provider records from DHT, but we stop providing it.+ return nil+}++func (n *SamNode) IsServiceRegistered(serviceName string) bool {+ n.servicesMu.RLock()+ defer n.servicesMu.RUnlock()+ return n.services[serviceName]+}++func (n *SamNode) FindProviders(ctx context.Context, serviceName string) ([]peer.AddrInfo, error) {+ c, err := serviceNameToCID(serviceName)+ if err != nil {+ return nil, err+ }++ providers := n.DHT.FindProvidersAsync(ctx, c, 20)+ var providerInfos []peer.AddrInfo+ for p := range providers {+ providerInfos = append(providerInfos, p)+ }+ return providerInfos, nil+}diff --git a/cmd/sam-node/sidecar.go b/cmd/sam-node/sidecar.gonew file mode 100644index 00000000..042b8f5c--- /dev/null+++ b/cmd/sam-node/sidecar.go@@ -0,0 +1,217 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package main++import (+ "crypto/tls"+ "crypto/x509"+ "encoding/json"+ "fmt"+ "net"+ "net/http"+ "os"+ "strings"+)++func startSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile string) {+ mux := http.NewServeMux()++ // Public endpoints+ mux.HandleFunc("/healthz", handleHealthz)+ mux.HandleFunc("/readyz", handleReadyz)++ // Protected endpoints+ mux.Handle("/sam/service/register", withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handleRegisterService(node, w, r)+ })))+ mux.Handle("/sam/service/unregister", withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handleUnregisterService(node, w, r)+ })))+ mux.Handle("/sam/service/discover", withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handleDiscoverService(node, w, r)+ })))++ // Mount MCP handler+ mcpHandler := NewMCPHandler(node)+ mux.Handle("/", mcpHandler)++ server := &http.Server{+ Handler: mux,+ }++ listener, err := net.Listen("tcp", addr)+ if err != nil {+ logger.Errorf("Failed to listen on %s: %v", addr, err)+ return+ }++ actualAddr := listener.Addr().String()++ if certFile != "" && keyFile != "" {+ tlsConfig := &tls.Config{}+ if caFile != "" {+ caCert, err := os.ReadFile(caFile)+ if err != nil {+ logger.Errorf("Failed to read CA cert: %v", err)+ return+ }+ caCertPool := x509.NewCertPool()+ caCertPool.AppendCertsFromPEM(caCert)+ tlsConfig.ClientCAs = caCertPool+ tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert+ }++ server.TLSConfig = tlsConfig+ logger.Infof("Starting MCP server on TCP address %s (with TLS Sidecar)", actualAddr)+ go func() {+ if err := server.ServeTLS(listener, certFile, keyFile); err != nil && err != http.ErrServerClosed {+ logger.Errorf("Sidecar API server error: %v", err)+ }+ }()+ } else {+ logger.Infof("Starting MCP server on TCP address %s", actualAddr)+ go func() {+ if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {+ logger.Errorf("Sidecar API server error: %v", err)+ }+ }()+ }+}++func handleHealthz(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ if _, err := w.Write([]byte("OK")); err != nil {+ logger.Errorf("Failed to write response: %v", err)+ }+}++func handleReadyz(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ if _, err := w.Write([]byte("OK")); err != nil {+ logger.Errorf("Failed to write response: %v", err)+ }+}++func withAuth(token string, next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if token == "" {+ next.ServeHTTP(w, r)+ return+ }++ authHeader := r.Header.Get("Authorization")+ if authHeader == "" {+ http.Error(w, "Unauthorized", http.StatusUnauthorized)+ return+ }++ parts := strings.Split(authHeader, " ")+ if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {+ http.Error(w, "Invalid authorization header format", http.StatusUnauthorized)+ return+ }++ if parts[1] != token {+ http.Error(w, "Forbidden", http.StatusForbidden)+ return+ }++ next.ServeHTTP(w, r)+ })+}++type ServiceRequest struct {+ ServiceName string `json:"service_name"`+}++func handleRegisterService(node *SamNode, w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ var req ServiceRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ http.Error(w, "Invalid request body", http.StatusBadRequest)+ return+ }++ if req.ServiceName == "" {+ http.Error(w, "service_name is required", http.StatusBadRequest)+ return+ }++ if err := node.RegisterService(r.Context(), req.ServiceName); err != nil {+ http.Error(w, fmt.Sprintf("Failed to register service: %v", err), http.StatusInternalServerError)+ return+ }++ w.WriteHeader(http.StatusOK)+ if _, err := w.Write([]byte("Service registered")); err != nil {+ logger.Errorf("Failed to write response: %v", err)+ }+}++func handleUnregisterService(node *SamNode, w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ var req ServiceRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ http.Error(w, "Invalid request body", http.StatusBadRequest)+ return+ }++ if req.ServiceName == "" {+ http.Error(w, "service_name is required", http.StatusBadRequest)+ return+ }++ if err := node.UnregisterService(r.Context(), req.ServiceName); err != nil {+ http.Error(w, fmt.Sprintf("Failed to unregister service: %v", err), http.StatusInternalServerError)+ return+ }++ w.WriteHeader(http.StatusOK)+ if _, err := w.Write([]byte("Service unregistered")); err != nil {+ logger.Errorf("Failed to write response: %v", err)+ }+}++func handleDiscoverService(node *SamNode, w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ serviceName := r.URL.Query().Get("name")+ if serviceName == "" {+ http.Error(w, "name query parameter is required", http.StatusBadRequest)+ return+ }++ providers, err := node.FindProviders(r.Context(), serviceName)+ if err != nil {+ http.Error(w, fmt.Sprintf("Failed to discover services: %v", err), http.StatusInternalServerError)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(providers); err != nil {+ logger.Errorf("Failed to encode providers: %v", err)+ }+}diff --git a/cmd/sam-node/sidecar_test.go b/cmd/sam-node/sidecar_test.gonew file mode 100644index 00000000..efdf5bf1--- /dev/null+++ b/cmd/sam-node/sidecar_test.go@@ -0,0 +1,135 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package main++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestWithAuth(t *testing.T) {+ token := "test-token"+ handler := withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))++ tests := []struct {+ name string+ authHeader string+ expectedStatus int+ }{+ {+ name: "Valid token",+ authHeader: "Bearer test-token",+ expectedStatus: http.StatusOK,+ },+ {+ name: "Missing token",+ authHeader: "",+ expectedStatus: http.StatusUnauthorized,+ },+ {+ name: "Invalid format",+ authHeader: "test-token",+ expectedStatus: http.StatusUnauthorized,+ },+ {+ name: "Wrong token",+ authHeader: "Bearer wrong-token",+ expectedStatus: http.StatusForbidden,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req := httptest.NewRequest("GET", "/any", nil)+ if tt.authHeader != "" {+ req.Header.Set("Authorization", tt.authHeader)+ }+ rr := httptest.NewRecorder()+ handler.ServeHTTP(rr, req)++ if rr.Code != tt.expectedStatus {+ t.Errorf("expected status %d, got %d", tt.expectedStatus, rr.Code)+ }+ })+ }+}++func TestPublicEndpoints(t *testing.T) {+ mux := http.NewServeMux()+ mux.HandleFunc("/healthz", handleHealthz)+ mux.HandleFunc("/readyz", handleReadyz)++ endpoints := []string{"/healthz", "/readyz"}++ for _, ep := range endpoints {+ req := httptest.NewRequest("GET", ep, nil)+ rr := httptest.NewRecorder()+ mux.ServeHTTP(rr, req)++ if rr.Code != http.StatusOK {+ t.Errorf("expected status OK for %s, got %d", ep, rr.Code)+ }+ }+}++func TestHandleRegisterService(t *testing.T) {+ node := &SamNode{+ services: make(map[string]bool),+ }++ reqBody := ServiceRequest{ServiceName: "test-service"}+ body, _ := json.Marshal(reqBody)++ req := httptest.NewRequest("POST", "/sam/service/register", bytes.NewBuffer(body))+ rr := httptest.NewRecorder()++ handleRegisterService(node, rr, req)++ if rr.Code != http.StatusOK {+ t.Errorf("expected status OK, got %d", rr.Code)+ }++ if !node.IsServiceRegistered("test-service") {+ t.Errorf("expected service to be registered")+ }+}++func TestHandleUnregisterService(t *testing.T) {+ node := &SamNode{+ services: make(map[string]bool),+ }+ node.services["test-service"] = true++ reqBody := ServiceRequest{ServiceName: "test-service"}+ body, _ := json.Marshal(reqBody)++ req := httptest.NewRequest("POST", "/sam/service/unregister", bytes.NewBuffer(body))+ rr := httptest.NewRecorder()++ handleUnregisterService(node, rr, req)++ if rr.Code != http.StatusOK {+ t.Errorf("expected status OK, got %d", rr.Code)+ }++ if node.IsServiceRegistered("test-service") {+ t.Errorf("expected service to be unregistered")+ }+}diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bashindex 9e39ae97..c42d6de6 100644--- a/tests/e2e/lib/container_mesh.bash+++ b/tests/e2e/lib/container_mesh.bash@@ -241,7 +241,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then--token-url "http://mock-oidc:18080/token" \--listen "/ip4/0.0.0.0/udp/5001/quic-v1" \--listen "/ip4/0.0.0.0/tcp/5002" \- --mcp-addr "0.0.0.0:8080" \+ --bind-addr "0.0.0.0:8080" \--mesh "e2e-mesh" >/dev/nullMESH_CONTAINERS+=("${name}")diff --git a/tests/e2e/policy.bats b/tests/e2e/policy.batsindex 79b2ceb8..6b96579b 100644--- a/tests/e2e/policy.bats+++ b/tests/e2e/policy.bats@@ -215,7 +215,7 @@ EOF"--token-url "http://mock-oidc:18080/token" \--listen "/ip4/0.0.0.0/udp/5001/quic-v1" \--listen "/ip4/0.0.0.0/tcp/5002" \- --mcp-addr "0.0.0.0:8080" \+ --bind-addr "0.0.0.0:8080" \--mesh "e2e-mesh" \--local-policy "/etc/sam/local_policy.yaml" >/dev/nulldiff --git a/tests/integration/catalog_test.go b/tests/integration/catalog_test.goindex 9dfb97ed..eb404109 100644--- a/tests/integration/catalog_test.go+++ b/tests/integration/catalog_test.go@@ -19,7 +19,7 @@ func startBackgroundNode(t *testing.T, nodeBin string, hubAddr string, homeDir s"HOME="+homeDir,"XDG_CONFIG_HOME="+filepath.Join(homeDir, ".config"),)- allArgs := append([]string{"run", "--hub", hubAddr, "--jwt", "test-jwt", "--mcp-addr", "127.0.0.1:0"}, args...)+ allArgs := append([]string{"run", "--hub", hubAddr, "--jwt", "test-jwt", "--bind-addr", "127.0.0.1:0"}, args...)cmd := exec.Command(nodeBin, allArgs...)cmd.Env = envdiff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.goindex a0aea526..74bb1049 100644--- a/tests/integration/fallback_test.go+++ b/tests/integration/fallback_test.go@@ -40,8 +40,8 @@ import ("google.golang.org/protobuf/proto")-// init forces the biscuit-go parser to build its underlying participle-// lexer and reflection caches synchronously at startup. This prevents+// init forces the biscuit-go parser to build its underlying participle+// lexer and reflection caches synchronously at startup. This prevents// a known data race when multiple goroutines parse facts concurrently.func init() {_, _ = parser.FromStringFact(`warmup("cache")`)@@ -67,24 +67,24 @@ func TestFallbackReEnrollment(t *testing.T) {// 3. Create Biscuit token signed by Key B (using pre-computed clientID)builder := biscuit.NewBuilder(privB)-+nodeFact, _ := parser.FromStringFact(fmt.Sprintf(`node("%s")`, clientID))if err := builder.AddAuthorityFact(nodeFact); err != nil {t.Fatal(err)}-+clientPeerFact, _ := parser.FromStringFact(fmt.Sprintf(`client_peer_id("%s")`, clientID))if err := builder.AddAuthorityFact(clientPeerFact); err != nil {t.Fatal(err)}-+toolFact, _ := parser.FromStringFact(`allow_mcp_tool("*")`)if err := builder.AddAuthorityFact(toolFact); err != nil {t.Fatal(err)}-+b, _ := builder.Build()-+// Verify it in testauthorizer, err := b.Authorizer(pubB)if err != nil {@@ -95,7 +95,7 @@ func TestFallbackReEnrollment(t *testing.T) {if err := authorizer.Authorize(); err != nil {t.Fatalf("Token generated in test is invalid: %v", err)}-+tokenBytes, _ := b.Serialize()// 4. Start Mock Hub with dynamic key response@@ -117,12 +117,12 @@ func TestFallbackReEnrollment(t *testing.T) {cmd := exec.Command(nodeBin, "run", "--hub", hubAddr, "--listen", "/ip4/127.0.0.1/tcp/0", "--jwt-path", jwtPath)cmd.Dir = repoRoot(t)cmd.Env = env-+var stdout safeBuffervar stderr safeBuffercmd.Stdout = &stdoutcmd.Stderr = &stderr-+if err := cmd.Start(); err != nil {t.Fatal(err)}@@ -255,7 +255,7 @@ func startMockHubDynamic(t *testing.T, pubA, pubB ed25519.PublicKey) (peer.ID, st.Fatalf("failed to create mock libp2p host: %v", err)}- kdht, err := dht.New(context.Background(), h, dht.Mode(dht.ModeServer))+ kdht, err := dht.New(context.Background(), h, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))if err != nil {t.Fatalf("failed to create DHT on mock hub: %v", err)}diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.goindex a788ebf0..6ae1514c 100644--- a/tests/integration/minimal_helpers_test.go+++ b/tests/integration/minimal_helpers_test.go@@ -98,7 +98,7 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {t.Fatalf("failed to create mock libp2p host: %v", err)}- kdht, err := dht.New(context.Background(), h, dht.Mode(dht.ModeServer))+ kdht, err := dht.New(context.Background(), h, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))if err != nil {t.Fatalf("failed to create DHT on mock hub: %v", err)}diff --git a/tests/integration/pubsub_test.go b/tests/integration/pubsub_test.goindex 9c0f222f..14f51095 100644--- a/tests/integration/pubsub_test.go+++ b/tests/integration/pubsub_test.go@@ -46,7 +46,7 @@ func TestPubSubTools(t *testing.T) {// Start Node 1env1 := append(os.Environ(), "HOME="+tmpHome1, "XDG_CONFIG_HOME="+filepath.Join(tmpHome1, ".config"))- cmd1 := exec.CommandContext(ctx, nodeBin, "run", "--hub", hubAddr, "--mcp-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5003/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5004", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms")+ cmd1 := exec.CommandContext(ctx, nodeBin, "run", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5003/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5004", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms")cmd1.Env = env1logFile1, err := os.Create(filepath.Join(tmpHome1, "node1.log"))if err != nil {@@ -61,7 +61,7 @@ func TestPubSubTools(t *testing.T) {// Start Node 2env2 := append(os.Environ(), "HOME="+tmpHome2, "XDG_CONFIG_HOME="+filepath.Join(tmpHome2, ".config"))- cmd2 := exec.CommandContext(ctx, nodeBin, "run", "--hub", hubAddr, "--mcp-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5005/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5006", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms")+ cmd2 := exec.CommandContext(ctx, nodeBin, "run", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5005/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5006", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms")cmd2.Env = env2logFile2, err := os.Create(filepath.Join(tmpHome2, "node2.log"))if err != nil {diff --git a/tests/integration/service_discovery_test.go b/tests/integration/service_discovery_test.gonew file mode 100644index 00000000..d096aa22--- /dev/null+++ b/tests/integration/service_discovery_test.go@@ -0,0 +1,206 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package integration_test++import (+ "bytes"+ "encoding/json"+ "io"+ "net/http"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/libp2p/go-libp2p/core/peer"+)++func TestServiceDiscovery(t *testing.T) {+ nodeBin := buildBinary(t, "./cmd/sam-node")+ _, hubAddr := startMockLibp2pHub(t)++ homeA := t.TempDir()+ homeB := t.TempDir()++ apiToken := "secret-token"+ apiAddrA := "127.0.0.1:8091"+ apiAddrB := "127.0.0.1:8092"++ // Start Node A+ t.Log("Starting Node A...")+ _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--listen", "/ip4/127.0.0.1/tcp/0",+ "--discovery-interval", "100ms",+ "--bind-addr", apiAddrA,+ "--api-token", apiToken,+ )++ // Start Node B+ t.Log("Starting Node B...")+ _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--listen", "/ip4/127.0.0.1/tcp/0",+ "--discovery-interval", "100ms",+ "--bind-addr", apiAddrB,+ "--api-token", apiToken,+ )++ // Wait for nodes to start sidecar API+ waitForAPI(t, apiAddrA)+ waitForAPI(t, apiAddrB)++ addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))++ // Connect Node B to Node A (to ensure they are in same network)+ // We use the multiplexed HTTP address for MCP calls too!+ callMCP(t, apiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})++ // Wait for DHT to have peers on Node A+ t.Log("Waiting for DHT to have peers on Node A...")+ deadline := time.Now().Add(10 * time.Second)+ var dhtReady bool+ for time.Now().Before(deadline) {+ respData := callMCP(t, apiAddrA, "get_mesh_info", map[string]any{})+ var data map[string]any+ if err := json.Unmarshal([]byte(respData), &data); err == nil {+ dhtSize, _ := data["dht_size"].(float64)+ if dhtSize > 0 {+ dhtReady = true+ break+ }+ }+ time.Sleep(500 * time.Millisecond)+ }+ if !dhtReady {+ t.Fatalf("DHT not ready on Node A (size 0)")+ }++ // Agent A registers a service+ serviceName := "mcp:github-tools"+ registerService(t, apiAddrA, apiToken, serviceName)++ // Wait for DHT propagation+ t.Log("Waiting for DHT propagation...")+ time.Sleep(2 * time.Second)++ // Agent B queries the DHT via Sidecar API+ t.Log("Agent B discovering service...")+ providers := discoverService(t, apiAddrB, apiToken, serviceName)++ if len(providers) == 0 {+ t.Fatalf("Agent B failed to discover any providers for %s", serviceName)+ }++ // Verify Agent A is in the providers list+ peerIDA := getPeerIDFromAddr(addrA)+ found := false+ for _, p := range providers {+ if p.ID == peerIDA {+ found = true+ break+ }+ }++ if !found {+ t.Fatalf("Agent B did not discover Agent A as provider. Providers: %v", providers)+ }++ // Agent A unregisters the service+ unregisterService(t, apiAddrA, apiToken, serviceName)++ t.Log("Service discovery test passed.")+}++func waitForAPI(t *testing.T, addr string) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ resp, err := http.Get("http://" + addr + "/healthz")+ if err == nil && resp.StatusCode == http.StatusOK {+ _ = resp.Body.Close()+ return+ }+ time.Sleep(100 * time.Millisecond)+ }+ t.Fatalf("timeout waiting for API at %s", addr)+}++func registerService(t *testing.T, apiAddr, token, serviceName string) {+ t.Helper()+ reqBody := map[string]string{"service_name": serviceName}+ body, _ := json.Marshal(reqBody)+ req, _ := http.NewRequest("POST", "http://"+apiAddr+"/sam/service/register", bytes.NewBuffer(body))+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("Content-Type", "application/json")++ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("Failed to register service: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusOK {+ bodyBytes, _ := io.ReadAll(resp.Body)+ t.Fatalf("Register service failed with status: %d, body: %s", resp.StatusCode, string(bodyBytes))+ }+}++func unregisterService(t *testing.T, apiAddr, token, serviceName string) {+ t.Helper()+ reqBody := map[string]string{"service_name": serviceName}+ body, _ := json.Marshal(reqBody)+ req, _ := http.NewRequest("POST", "http://"+apiAddr+"/sam/service/unregister", bytes.NewBuffer(body))+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("Content-Type", "application/json")++ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("Failed to unregister service: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("Unregister service failed with status: %d", resp.StatusCode)+ }+}++func discoverService(t *testing.T, apiAddr, token, serviceName string) []peer.AddrInfo {+ t.Helper()+ req, _ := http.NewRequest("GET", "http://"+apiAddr+"/sam/service/discover?name="+serviceName, nil)+ req.Header.Set("Authorization", "Bearer "+token)++ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("Failed to discover service: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("Discover service failed with status: %d", resp.StatusCode)+ }++ var providers []peer.AddrInfo+ if err := json.NewDecoder(resp.Body).Decode(&providers); err != nil {+ t.Fatalf("Failed to decode providers: %v", err)+ }+ return providers+}++func getPeerIDFromAddr(addr string) peer.ID {+ parts := strings.Split(addr, "/p2p/")+ if len(parts) < 2 {+ return ""+ }+ p, _ := peer.Decode(parts[1])+ return p+}