Skip to content

Agent Mesh

node: move network diagnostics from MCP tools to /debug REST endpoints

Tomas Tormo1f984a07f82e
diff --git a/agents/skills/sam-mesh/SKILL.md b/agents/skills/sam-mesh/SKILL.md
index d945f7f7..b499ffaa 100644
--- a/agents/skills/sam-mesh/SKILL.md
+++ b/agents/skills/sam-mesh/SKILL.md
@@ -15,6 +15,8 @@ Pick the path that matches the need:
[Bootstrap A Node](#bootstrap-a-node).
- The task needs a plain HTTP call to the node, such as inference or a
`local_proxy_url`: [Talk To The Node Over HTTP](#talk-to-the-node-over-http).
+- The task needs node diagnostics, such as logs or connectivity:
+ [Diagnose The Node](#diagnose-the-node).
- The task needs a remote tool or capability:
[Inspect The Mesh](#inspect-the-mesh).
- The task needs a model completion:
@@ -100,6 +102,19 @@ Never print the token or echo it into the transcript. `Authorization` is not the
node's credential: send it only when the destination service needs its own, and
it passes through to that service untouched.
+## Diagnose The Node
+
+Node diagnostics (logs, connectivity, network and token info, connecting to a
+peer by address) are not MCP tools. Discover them instead of memorizing them:
+
+```bash
+sam-node debug --help
+```
+
+Then run the subcommand that matches the need. They talk to the node over its
+Unix socket, so no token is involved, and each prints the node's JSON response,
+so the output composes with `jq`.
+
## Inspect The Mesh
Start by understanding the local node and mesh state:
diff --git a/cmd/sam-node/debug.go b/cmd/sam-node/debug.go
new file mode 100644
index 00000000..a4272080
--- /dev/null
+++ b/cmd/sam-node/debug.go
@@ -0,0 +1,137 @@
+// 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"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/google/sam/internal/node"
+ "github.com/spf13/cobra"
+)
+
+// newDebugCmd groups the operator diagnostics served by a running node's
+// /debug endpoints, reached over its Unix socket so no token is involved.
+func newDebugCmd() *cobra.Command {
+ debugCmd := &cobra.Command{
+ Use: "debug",
+ Short: "Diagnostics for a running node, over its Unix socket",
+ }
+ debugCmd.PersistentFlags().StringVar(&socketPathFlag, "socket-path", "", "Unix socket of the running node (defaults to <data-dir>/"+node.DefaultSocketName+")")
+
+ debugCmd.AddCommand(
+ newDebugGetCmd("mesh-info", "Show connected peers, DHT size, and the router peer ID", "/debug/mesh-info"),
+ newDebugGetCmd("network-info", "Show local network interfaces and listener addresses", "/debug/network-info"),
+ newDebugGetCmd("token-info", "Show the local auth token's expiration and status", "/debug/token-info"),
+ newDebugGetCmd("logs", "Show the last few lines of the node's log output", "/debug/logs"),
+ )
+
+ debugCmd.AddCommand(&cobra.Command{
+ Use: "connectivity [peer-id]",
+ Short: "Ping the SAM router, or a specific peer",
+ Args: cobra.MaximumNArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ path := "/debug/connectivity"
+ if len(args) == 1 {
+ path += "?peer_id=" + url.QueryEscape(args[0])
+ }
+ return debugRequest(cmd, http.MethodGet, path, nil)
+ },
+ })
+
+ debugCmd.AddCommand(&cobra.Command{
+ Use: "connect-peer <multiaddr>",
+ Short: "Connect the node to a peer by its full multiaddress",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ body, err := json.Marshal(map[string]string{"peer_addr": args[0]})
+ if err != nil {
+ return err
+ }
+ return debugRequest(cmd, http.MethodPost, "/debug/connect-peer", bytes.NewReader(body))
+ },
+ })
+
+ return debugCmd
+}
+
+// newDebugGetCmd builds a no-argument subcommand that GETs one /debug endpoint.
+func newDebugGetCmd(use, short, path string) *cobra.Command {
+ return &cobra.Command{
+ Use: use,
+ Short: short,
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return debugRequest(cmd, http.MethodGet, path, nil)
+ },
+ }
+}
+
+// debugRequest performs one request against the node's Unix socket and prints
+// the JSON response.
+func debugRequest(cmd *cobra.Command, method, path string, body io.Reader) error {
+ socketPath := resolveSocketPath(cmd)
+ if socketPath == "" {
+ return fmt.Errorf("no Unix socket configured (--socket-path is empty); sam-node debug needs the node to serve one")
+ }
+ req, err := http.NewRequestWithContext(cmd.Context(), method, "http://localhost"+path, body)
+ if err != nil {
+ return err
+ }
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ resp, err := socketClient(socketPath, 30*time.Second).Do(req)
+ if err != nil {
+ return fmt.Errorf("cannot reach the node on %s (is it running with a socket?): %w", socketPath, err)
+ }
+ defer func() {
+ _ = resp.Body.Close()
+ }()
+ data, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return err
+ }
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("%s: %s", resp.Status, strings.TrimSpace(string(data)))
+ }
+ fmt.Println(strings.TrimSpace(string(data)))
+ return nil
+}
+
+// socketClient returns an HTTP client that dials the node's Unix socket; the
+// URL host is ignored.
+func socketClient(path string, timeout time.Duration) *http.Client {
+ return &http.Client{
+ Timeout: timeout,
+ Transport: &http.Transport{
+ DisableKeepAlives: true,
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{Timeout: timeout}).DialContext(ctx, "unix", path)
+ },
+ },
+ }
+}
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index 8b6cb71b..f24e366c 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -951,6 +951,7 @@ func main() {
rootCmd.AddCommand(joinCmd)
rootCmd.AddCommand(resetCmd)
rootCmd.AddCommand(newSkillCmd())
+ rootCmd.AddCommand(newDebugCmd())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
diff --git a/internal/node/debug_handlers.go b/internal/node/debug_handlers.go
new file mode 100644
index 00000000..d95e7594
--- /dev/null
+++ b/internal/node/debug_handlers.go
@@ -0,0 +1,240 @@
+// 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 node
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/libp2p/go-libp2p/core/peer"
+ "github.com/multiformats/go-multiaddr"
+)
+
+// Bound the diagnostic dials so a dead peer yields an error instead of a
+// request that hangs for as long as the caller's patience.
+const (
+ connectivityPingTimeout = 15 * time.Second
+ connectPeerTimeout = 30 * time.Second
+)
+
+// newDebugHandler serves the operator diagnostics under /debug. These were MCP
+// tools once; they moved here so agents never see them in their tool list (#318).
+func newDebugHandler(n *SamNode) http.Handler {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /debug/mesh-info", func(w http.ResponseWriter, r *http.Request) {
+ info, err := n.meshInfo()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ writeDebugJSON(w, info)
+ })
+ mux.HandleFunc("GET /debug/connectivity", func(w http.ResponseWriter, r *http.Request) {
+ writeDebugJSON(w, n.connectivityStats(r.Context(), r.URL.Query().Get("peer_id")))
+ })
+ mux.HandleFunc("GET /debug/network-info", func(w http.ResponseWriter, r *http.Request) {
+ writeDebugJSON(w, n.networkInfo())
+ })
+ mux.HandleFunc("GET /debug/token-info", func(w http.ResponseWriter, r *http.Request) {
+ writeDebugJSON(w, n.tokenInfo())
+ })
+ mux.HandleFunc("GET /debug/logs", func(w http.ResponseWriter, r *http.Request) {
+ writeDebugJSON(w, map[string]any{"logs": GetRecentLogs()})
+ })
+ mux.HandleFunc("POST /debug/connect-peer", func(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ PeerAddr string `json:"peer_addr"`
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, "Invalid request body", http.StatusBadRequest)
+ return
+ }
+ if req.PeerAddr == "" {
+ http.Error(w, "peer_addr is required", http.StatusBadRequest)
+ return
+ }
+ if err := n.connectPeer(r.Context(), req.PeerAddr); err != nil {
+ http.Error(w, fmt.Sprintf("Failed to connect: %v", err), http.StatusInternalServerError)
+ return
+ }
+ writeDebugJSON(w, map[string]string{"status": "connected"})
+ })
+
+ // One guard for every handler: refuse loudly on a half-built node instead
+ // of panicking mid-request or fabricating zero-value diagnostics.
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := n.debugReady(); err != nil {
+ http.Error(w, err.Error(), http.StatusServiceUnavailable)
+ return
+ }
+ mux.ServeHTTP(w, r)
+ })
+}
+
+// debugReady reports whether the components the /debug handlers touch exist.
+func (n *SamNode) debugReady() error {
+ switch {
+ case n == nil:
+ return fmt.Errorf("node not initialized")
+ case n.Host == nil:
+ return fmt.Errorf("libp2p host not initialized")
+ case n.DHT == nil:
+ return fmt.Errorf("DHT not initialized")
+ case n.Store == nil:
+ return fmt.Errorf("node store not initialized")
+ }
+ return nil
+}
+
+func writeDebugJSON(w http.ResponseWriter, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(v); err != nil {
+ logger.Errorf("Failed to encode response: %v", err)
+ }
+}
+
+// meshInfo backs both the get_mesh_info MCP tool and GET /debug/mesh-info.
+// The MCP path skips the /debug boundary guard, so it re-checks here.
+func (n *SamNode) meshInfo() (map[string]any, error) {
+ if err := n.debugReady(); err != nil {
+ return nil, err
+ }
+
+ peers := n.Host.Network().Peers()
+ // Pre-sized so zero peers serializes as [] rather than null.
+ connectedPeers := make([]string, 0, len(peers))
+ for _, p := range peers {
+ connectedPeers = append(connectedPeers, p.String())
+ }
+ dhtSize := n.DHT.RoutingTable().Size()
+
+ resData := map[string]any{
+ "peer_id": n.Host.ID().String(),
+ "connected_peers": connectedPeers,
+ "dht_size": dhtSize,
+ "router_peer_id": n.RouterPeerID.String(),
+ }
+ if n.BoundSocketPath != "" {
+ resData["local_api_socket"] = n.BoundSocketPath
+ }
+ return resData, nil
+}
+
+// connectivityStats backs GET /debug/connectivity: with a peer ID it pings that
+// peer, otherwise it pings the SAM router.
+func (n *SamNode) connectivityStats(ctx context.Context, peerIDStr string) map[string]any {
+ ctx, cancel := context.WithTimeout(ctx, connectivityPingTimeout)
+ defer cancel()
+
+ stats := map[string]any{
+ "connected_peers": len(n.Host.Network().Peers()),
+ "total_known_peers": len(n.Host.Peerstore().Peers()),
+ }
+
+ if peerIDStr != "" {
+ pid, err := peer.Decode(peerIDStr)
+ if err == nil {
+ n.preparePeerAddrs(ctx, pid)
+ start := time.Now()
+ err := n.Host.Connect(ctx, peer.AddrInfo{ID: pid})
+ stats["ping_latency_ms"] = time.Since(start).Milliseconds()
+ stats["ping_error"] = err != nil
+ if err != nil {
+ stats["ping_error_msg"] = err.Error()
+ }
+ } else {
+ stats["ping_error"] = true
+ stats["ping_error_msg"] = "invalid peer id"
+ }
+ } else if n.RouterPeerID != "" {
+ start := time.Now()
+ err := n.Host.Connect(ctx, peer.AddrInfo{ID: n.RouterPeerID})
+ stats["router_latency_ms"] = time.Since(start).Milliseconds()
+ stats["router_error"] = err != nil
+ if err != nil {
+ stats["router_error_msg"] = err.Error()
+ }
+ }
+
+ return stats
+}
+
+// tokenInfo backs GET /debug/token-info.
+func (n *SamNode) tokenInfo() map[string]any {
+ info := map[string]any{
+ "has_token": false,
+ }
+
+ token, err := n.Store.LoadIdentity()
+ if err == nil && len(token) > 0 {
+ info["has_token"] = true
+ exp, err := n.Store.LoadIdentityExpiration()
+ if err == nil {
+ info["expires_in_seconds"] = time.Until(time.Unix(exp, 0)).Seconds()
+ info["is_expired"] = time.Now().Unix() > exp
+ }
+ }
+ return info
+}
+
+// networkInfo backs GET /debug/network-info.
+func (n *SamNode) networkInfo() map[string]any {
+ listenAddrs := []string{}
+ for _, a := range n.Host.Network().ListenAddresses() {
+ listenAddrs = append(listenAddrs, a.String())
+ }
+
+ observedAddrs := []string{}
+ for _, a := range n.Host.Addrs() {
+ observedAddrs = append(observedAddrs, a.String())
+ }
+
+ return map[string]any{
+ "listen_addresses": listenAddrs,
+ "observed_addresses": observedAddrs,
+ }
+}
+
+// connectPeer backs POST /debug/connect-peer.
+func (n *SamNode) connectPeer(ctx context.Context, peerAddr string) error {
+ ctx, cancel := context.WithTimeout(ctx, connectPeerTimeout)
+ defer cancel()
+
+ ma, err := multiaddr.NewMultiaddr(peerAddr)
+ if err != nil {
+ return err
+ }
+ addrInfo, err := peer.AddrInfoFromP2pAddr(ma)
+ if err != nil {
+ return err
+ }
+ if n.revokedPeers != nil && n.revokedPeers.Contains(addrInfo.ID.String()) {
+ return fmt.Errorf("failed to dial: failed to dial %s: gater disallows connection to peer", addrInfo.ID)
+ }
+ if n.Store.IsBanned(addrInfo.ID) {
+ return fmt.Errorf("failed to dial: failed to dial %s: gater disallows connection to peer", addrInfo.ID)
+ }
+ conns := n.Host.Network().ConnsToPeer(addrInfo.ID)
+ connectedness := n.Host.Network().Connectedness(addrInfo.ID)
+ logger.Debugf("[connect-peer] Target peer %s, connectedness: %v, active conns: %d", addrInfo.ID, connectedness, len(conns))
+
+ err = n.Host.Connect(ctx, *addrInfo)
+ logger.Debugf("[connect-peer] Host.Connect returned error: %v", err)
+ return err
+}
diff --git a/internal/node/mcp.go b/internal/node/mcp.go
index f2bd8d19..cc566e38 100644
--- a/internal/node/mcp.go
+++ b/internal/node/mcp.go
@@ -46,6 +46,8 @@ To use these remote services and their tools, the client can use the following f
Other useful tools: discover_remote_services browses services by type (e.g. 'MCP' or 'Inference'), get_mesh_info reports connected peers and mesh state, list_local_services shows what this node hosts.
+Node diagnostics (logs, connectivity, network/token info, connecting to a peer by address) are NOT MCP tools. When asked to diagnose this node, run 'sam-node debug --help' in a shell to discover the available diagnostics, then invoke the matching subcommand. They talk to the node over its Unix socket, so no token is involved.
+
Tools on remote services are identified via the format 'scheme://service-name/tool-name' (where 'scheme://service-name' represents the well-known local address of the service, and 'tool-name' is the individual tool to execute on it. Tool names themselves can contain any characters).
Inference services ('inference://...') are NOT called via call_remote_tool — they are plain OpenAI-compatible HTTP endpoints. Use discover_remote_services with type 'inference' to get each one's local_proxy_url, then send a normal HTTP request (e.g. POST <local_proxy_url>/chat/completions) directly to that URL.
@@ -111,12 +113,6 @@ func NewMCPServer(node *SamNode) *mcp.Server {
Description: "Call an MCP tool on a remote agent",
}, node.handleCallRemoteTool)
- // Add the connect_peer tool.
- mcp.AddTool(mcpServer, &mcp.Tool{
- Name: "connect_peer",
- Description: "Connect to a peer in the mesh",
- }, node.handleConnectPeer)
-
// Add the find_remote_tools tool.
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "find_remote_tools",
@@ -129,30 +125,6 @@ func NewMCPServer(node *SamNode) *mcp.Server {
Description: "Return the description, input schema, and output schema for a specific aggregated tool on a specific peer. peer_id and tool_name are both required; tool_name must be a namespaced 'scheme://service/tool' name as returned by find_remote_tools.",
}, node.handleDescribeRemoteTool)
- // Add the check_connectivity tool.
- mcp.AddTool(mcpServer, &mcp.Tool{
- Name: "check_connectivity",
- Description: "Diagnose the node's ability to communicate with the SAM routers and the broader mesh network.",
- }, node.handleCheckConnectivity)
-
- // Add the get_token_info tool.
- mcp.AddTool(mcpServer, &mcp.Tool{
- Name: "get_token_info",
- Description: "Inspects the local auth token, returns its expiration time and status.",
- }, node.handleGetTokenInfo)
-
- // Add the get_network_info tool.
- mcp.AddTool(mcpServer, &mcp.Tool{
- Name: "get_network_info",
- Description: "Returns local network interfaces and listener addresses.",
- }, node.handleGetNetworkInfo)
-
- // Add the get_recent_logs tool.
- mcp.AddTool(mcpServer, &mcp.Tool{
- Name: "get_recent_logs",
- Description: "Returns the last few lines of the node's log output.",
- }, node.handleGetRecentLogs)
-
return mcpServer
}
diff --git a/internal/node/mcp_handlers.go b/internal/node/mcp_handlers.go
index bc4a3464..f7b3f0e2 100644
--- a/internal/node/mcp_handlers.go
+++ b/internal/node/mcp_handlers.go
@@ -27,7 +27,6 @@ import (
samdiscovery "github.com/google/sam/internal/node/discovery"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/modelcontextprotocol/go-sdk/mcp"
- "github.com/multiformats/go-multiaddr"
)
// SendMessageParams defines the parameters for the send_message tool.
@@ -206,25 +205,9 @@ type GetMeshInfoParams struct{}
// handleGetMeshInfo implements the get_mesh_info tool.
func (n *SamNode) handleGetMeshInfo(ctx context.Context, req *mcp.CallToolRequest, params GetMeshInfoParams) (*mcp.CallToolResult, any, error) {
- if n == nil {
- return nil, nil, fmt.Errorf("node not initialized")
- }
-
- peers := n.Host.Network().Peers()
- var connectedPeers []string
- for _, p := range peers {
- connectedPeers = append(connectedPeers, p.String())
- }
- dhtSize := n.DHT.RoutingTable().Size()
-
- resData := map[string]any{
- "peer_id": n.Host.ID().String(),
- "connected_peers": connectedPeers,
- "dht_size": dhtSize,
- "router_peer_id": n.RouterPeerID.String(),
- }
- if n.BoundSocketPath != "" {
- resData["local_api_socket"] = n.BoundSocketPath
+ resData, err := n.meshInfo()
+ if err != nil {
+ return nil, nil, err
}
responseBytes, err := json.Marshal(resData)
if err != nil {
@@ -267,43 +250,6 @@ func (n *SamNode) handleCallRemoteTool(ctx context.Context, req *mcp.CallToolReq
return res, nil, nil
}
-// ConnectPeerParams defines the parameters for the connect_peer tool.
-type ConnectPeerParams struct {
- PeerAddr string `json:"peer_addr" jsonschema:"The full multiaddress of the peer to connect to"`
-}
-
-// handleConnectPeer implements the connect_peer tool.
-func (n *SamNode) handleConnectPeer(ctx context.Context, req *mcp.CallToolRequest, params ConnectPeerParams) (*mcp.CallToolResult, any, error) {
- ma, err := multiaddr.NewMultiaddr(params.PeerAddr)
- if err != nil {
- return nil, nil, err
- }
- addrInfo, err := peer.AddrInfoFromP2pAddr(ma)
- if err != nil {
- return nil, nil, err
- }
- if n.revokedPeers != nil && n.revokedPeers.Contains(addrInfo.ID.String()) {
- return nil, nil, fmt.Errorf("failed to dial: failed to dial %s: gater disallows connection to peer", addrInfo.ID)
- }
- if n.Store.IsBanned(addrInfo.ID) {
- return nil, nil, fmt.Errorf("failed to dial: failed to dial %s: gater disallows connection to peer", addrInfo.ID)
- }
- conns := n.Host.Network().ConnsToPeer(addrInfo.ID)
- connectedness := n.Host.Network().Connectedness(addrInfo.ID)
- logger.Debugf("[connect_peer] Target peer %s, connectedness: %v, active conns: %d", addrInfo.ID, connectedness, len(conns))
-
- err = n.Host.Connect(ctx, *addrInfo)
- logger.Debugf("[connect_peer] Host.Connect returned error: %v", err)
- if err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: "Connected"},
- },
- }, nil, nil
-}
-
// FindRemoteToolsParams defines the parameters for the
// find_remote_tools tool.
type FindRemoteToolsParams struct {
@@ -814,120 +760,3 @@ func (n *SamNode) handleDescribeRemoteTool(ctx context.Context, req *mcp.CallToo
Content: []mcp.Content{&mcp.TextContent{Text: string(data)}},
}, nil, nil
}
-
-// CheckConnectivityParams defines the parameters for the check_connectivity tool.
-type CheckConnectivityParams struct {
- PeerID string `json:"peer_id,omitempty" jsonschema:"Optional peer ID to ping."`
-}
-
-// handleCheckConnectivity implements the check_connectivity tool.
-func (n *SamNode) handleCheckConnectivity(ctx context.Context, req *mcp.CallToolRequest, params CheckConnectivityParams) (*mcp.CallToolResult, any, error) {
- stats := map[string]any{
- "connected_peers": len(n.Host.Network().Peers()),
- "total_known_peers": len(n.Host.Peerstore().Peers()),
- }
-
- if params.PeerID != "" {
- pid, err := peer.Decode(params.PeerID)
- if err == nil {
- n.preparePeerAddrs(ctx, pid)
- start := time.Now()
- err := n.Host.Connect(ctx, peer.AddrInfo{ID: pid})
- stats["ping_latency_ms"] = time.Since(start).Milliseconds()
- stats["ping_error"] = err != nil
- if err != nil {
- stats["ping_error_msg"] = err.Error()
- }
- } else {
- stats["ping_error"] = true
- stats["ping_error_msg"] = "invalid peer id"
- }
- } else if n.RouterPeerID != "" {
- start := time.Now()
- err := n.Host.Connect(ctx, peer.AddrInfo{ID: n.RouterPeerID})
- stats["router_latency_ms"] = time.Since(start).Milliseconds()
- stats["router_error"] = err != nil
- if err != nil {
- stats["router_error_msg"] = err.Error()
- }
- }
-
- data, err := json.Marshal(stats)
- if err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{&mcp.TextContent{Text: string(data)}},
- }, nil, nil
-}
-
-// GetTokenInfoParams defines parameters for the get_token_info tool.
-type GetTokenInfoParams struct{}
-
-// handleGetTokenInfo implements the get_token_info tool.
-func (n *SamNode) handleGetTokenInfo(ctx context.Context, req *mcp.CallToolRequest, params GetTokenInfoParams) (*mcp.CallToolResult, any, error) {
- info := map[string]any{
- "has_token": false,
- }
-
- token, err := n.Store.LoadIdentity()
- if err == nil && len(token) > 0 {
- info["has_token"] = true
- exp, err := n.Store.LoadIdentityExpiration()
- if err == nil {
- info["expires_in_seconds"] = time.Until(time.Unix(exp, 0)).Seconds()
- info["is_expired"] = time.Now().Unix() > exp
- }
- }
-
- data, err := json.Marshal(info)
- if err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{&mcp.TextContent{Text: string(data)}},
- }, nil, nil
-}
-
-// GetNetworkInfoParams defines parameters for the get_network_info tool.
-type GetNetworkInfoParams struct{}
-
-// handleGetNetworkInfo implements the get_network_info tool.
-func (n *SamNode) handleGetNetworkInfo(ctx context.Context, req *mcp.CallToolRequest, params GetNetworkInfoParams) (*mcp.CallToolResult, any, error) {
- listenAddrs := []string{}
- for _, a := range n.Host.Network().ListenAddresses() {
- listenAddrs = append(listenAddrs, a.String())
- }
-
- observedAddrs := []string{}
- for _, a := range n.Host.Addrs() {
- observedAddrs = append(observedAddrs, a.String())
- }
-
- info := map[string]any{
- "listen_addresses": listenAddrs,
- "observed_addresses": observedAddrs,
- }
- data, err := json.Marshal(info)
- if err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{&mcp.TextContent{Text: string(data)}},
- }, nil, nil
-}
-
-// GetRecentLogsParams defines parameters for the get_recent_logs tool.
-type GetRecentLogsParams struct{}
-
-// handleGetRecentLogs implements the get_recent_logs tool.
-func (n *SamNode) handleGetRecentLogs(ctx context.Context, req *mcp.CallToolRequest, params GetRecentLogsParams) (*mcp.CallToolResult, any, error) {
- logs := GetRecentLogs()
- data, err := json.Marshal(map[string]any{"logs": logs})
- if err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{&mcp.TextContent{Text: string(data)}},
- }, nil, nil
-}
diff --git a/internal/node/mcp_handlers_additional_test.go b/internal/node/mcp_handlers_additional_test.go
index a02b230b..fbf1a69f 100644
--- a/internal/node/mcp_handlers_additional_test.go
+++ b/internal/node/mcp_handlers_additional_test.go
@@ -17,6 +17,9 @@ package node
import (
"context"
"encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
"testing"
"github.com/google/sam/api"
@@ -136,7 +139,7 @@ func TestHandleGetMeshInfo(t *testing.T) {
}
}
-func TestHandleConnectPeer(t *testing.T) {
+func TestConnectPeer(t *testing.T) {
ctx := context.Background()
node, cleanup := startBareNode(t, ctx)
defer cleanup()
@@ -144,14 +147,9 @@ func TestHandleConnectPeer(t *testing.T) {
nodeB, cleanupB := startBareNode(t, ctx)
defer cleanupB()
- res, _, err := node.handleConnectPeer(context.Background(), &mcp.CallToolRequest{}, ConnectPeerParams{
- PeerAddr: nodeB.Host.Addrs()[0].String() + "/p2p/" + nodeB.Host.ID().String(),
- })
+ err := node.connectPeer(context.Background(), nodeB.Host.Addrs()[0].String()+"/p2p/"+nodeB.Host.ID().String())
if err != nil {
- t.Fatalf("handleConnectPeer failed: %v", err)
- }
- if res.Content[0].(*mcp.TextContent).Text != "Connected" {
- t.Errorf("expected Connected")
+ t.Fatalf("connectPeer failed: %v", err)
}
}
@@ -169,111 +167,89 @@ func TestHandleCallRemoteServer(t *testing.T) {
}
}
-// TestCheckConnectivityHandler tests the check_connectivity tool.
-func TestCheckConnectivityHandler(t *testing.T) {
+// TestConnectivityStats tests the logic behind GET /debug/connectivity.
+func TestConnectivityStats(t *testing.T) {
node1, cleanup1 := startBareNode(t, context.Background())
defer cleanup1()
- res, _, err := node1.handleCheckConnectivity(context.Background(), nil, CheckConnectivityParams{})
- if err != nil {
- t.Fatalf("handleCheckConnectivity failed: %v", err)
- }
-
- if len(res.Content) != 1 {
- t.Fatalf("expected 1 content block, got %d", len(res.Content))
- }
-
- tc, ok := res.Content[0].(*mcp.TextContent)
- if !ok {
- t.Fatalf("expected TextContent")
- }
-
- var stats map[string]any
- if err := json.Unmarshal([]byte(tc.Text), &stats); err != nil {
- t.Fatalf("failed to parse JSON: %v", err)
- }
+ stats := node1.connectivityStats(context.Background(), "")
if _, ok := stats["connected_peers"]; !ok {
t.Fatalf("missing connected_peers in stats")
}
}
-// TestGetTokenInfoHandler tests the get_token_info tool.
-func TestGetTokenInfoHandler(t *testing.T) {
+// TestTokenInfo tests the logic behind GET /debug/token-info.
+func TestTokenInfo(t *testing.T) {
node1, cleanup1 := startBareNode(t, context.Background())
defer cleanup1()
- res, _, err := node1.handleGetTokenInfo(context.Background(), nil, GetTokenInfoParams{})
- if err != nil {
- t.Fatalf("handleGetTokenInfo failed: %v", err)
- }
-
- tc, ok := res.Content[0].(*mcp.TextContent)
- if !ok {
- t.Fatalf("expected TextContent")
- }
-
- var info map[string]any
- if err := json.Unmarshal([]byte(tc.Text), &info); err != nil {
- t.Fatalf("failed to parse JSON: %v", err)
- }
+ info := node1.tokenInfo()
- // Should have has_token=false initially since no token is built in setupTestNode explicitly for the node's store.
- // Wait, setupTestNode might set a token?
- if hasToken, ok := info["has_token"].(bool); !ok {
+ if _, ok := info["has_token"].(bool); !ok {
t.Fatalf("expected has_token boolean, got %v", info["has_token"])
- } else if hasToken {
- // It might be true if setupTestNode saves a biscuit.
- _ = hasToken
}
}
-// TestGetNetworkInfoHandler tests the get_network_info tool.
-func TestGetNetworkInfoHandler(t *testing.T) {
+// TestNetworkInfo tests the logic behind GET /debug/network-info.
+func TestNetworkInfo(t *testing.T) {
node1, cleanup1 := startBareNode(t, context.Background())
defer cleanup1()
- res, _, err := node1.handleGetNetworkInfo(context.Background(), nil, GetNetworkInfoParams{})
- if err != nil {
- t.Fatalf("handleGetNetworkInfo failed: %v", err)
- }
-
- tc, ok := res.Content[0].(*mcp.TextContent)
- if !ok {
- t.Fatalf("expected TextContent")
- }
-
- var info map[string]any
- if err := json.Unmarshal([]byte(tc.Text), &info); err != nil {
- t.Fatalf("failed to parse JSON: %v", err)
- }
+ info := node1.networkInfo()
if _, ok := info["listen_addresses"]; !ok {
t.Fatalf("missing listen_addresses")
}
}
-// TestGetRecentLogsHandler tests the get_recent_logs tool.
-func TestGetRecentLogsHandler(t *testing.T) {
+// TestDebugHandlerHTTP exercises the /debug mux itself: routing, method
+// gating, and request validation.
+func TestDebugHandlerHTTP(t *testing.T) {
node1, cleanup1 := startBareNode(t, context.Background())
defer cleanup1()
- res, _, err := node1.handleGetRecentLogs(context.Background(), nil, GetRecentLogsParams{})
- if err != nil {
- t.Fatalf("handleGetRecentLogs failed: %v", err)
+ handler := newDebugHandler(node1)
+
+ get := func(path string) *httptest.ResponseRecorder {
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
+ return rec
+ }
+
+ for _, path := range []string{"/debug/mesh-info", "/debug/connectivity", "/debug/network-info", "/debug/token-info", "/debug/logs"} {
+ rec := get(path)
+ if rec.Code != http.StatusOK {
+ t.Errorf("GET %s: got %d, want 200 (body: %s)", path, rec.Code, rec.Body.String())
+ continue
+ }
+ var payload map[string]any
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Errorf("GET %s: invalid JSON: %v", path, err)
+ }
+ }
+
+ rec := get("/debug/connect-peer")
+ if rec.Code != http.StatusMethodNotAllowed {
+ t.Errorf("GET /debug/connect-peer: got %d, want 405", rec.Code)
}
- tc, ok := res.Content[0].(*mcp.TextContent)
- if !ok {
- t.Fatalf("expected TextContent")
+ rec = httptest.NewRecorder()
+ handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/debug/connect-peer", strings.NewReader("not json")))
+ if rec.Code != http.StatusBadRequest {
+ t.Errorf("POST /debug/connect-peer with bad body: got %d, want 400", rec.Code)
}
- var data map[string]any
- if err := json.Unmarshal([]byte(tc.Text), &data); err != nil {
- t.Fatalf("failed to parse JSON: %v", err)
+ rec = httptest.NewRecorder()
+ handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/debug/connect-peer", strings.NewReader("{}")))
+ if rec.Code != http.StatusBadRequest {
+ t.Errorf("POST /debug/connect-peer without peer_addr: got %d, want 400", rec.Code)
}
- if _, ok := data["logs"]; !ok {
- t.Fatalf("missing logs")
+ // A half-built node refuses loudly instead of panicking.
+ rec = httptest.NewRecorder()
+ newDebugHandler(nil).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/debug/logs", nil))
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Errorf("GET /debug/logs on nil node: got %d, want 503", rec.Code)
}
}
diff --git a/internal/node/sidecar.go b/internal/node/sidecar.go
index a9518063..c9d264bb 100644
--- a/internal/node/sidecar.go
+++ b/internal/node/sidecar.go
@@ -78,6 +78,10 @@ func StartSidecarServer(node *SamNode, addr, socketPath, token, certFile, keyFil
handlePeerEvidence(node, w, r)
})))))
+ // Operator diagnostics (#318): agent-invisible, and deliberately not behind
+ // withMeshConnection — they must answer while the mesh is unreachable.
+ mux.Handle("/debug/", withAuth(token, true, newDebugHandler(node)))
+
// Mount Egress Proxy. allowAuthorizationFallback=false is required here: this
// handler forwards Authorization to the destination service, so it must never
// also accept it as the local gate credential (would leak the sidecar token off-node).
diff --git a/site/content/docs/integrations/vscode-copilot.md b/site/content/docs/integrations/vscode-copilot.md
index 1d0f90e7..06e926b4 100644
--- a/site/content/docs/integrations/vscode-copilot.md
+++ b/site/content/docs/integrations/vscode-copilot.md
@@ -338,9 +338,8 @@ The real output:
```text
mesh offered model: openrouter/auto
-mesh granted 15 tools: call_remote_tool, check_connectivity, connect_peer,
- describe_remote_tool, discover_remote_services, find_remote_tools,
- get_mesh_info, get_network_info, get_recent_logs, get_token_info,
+mesh granted 10 tools: call_remote_tool, describe_remote_tool,
+ discover_remote_services, find_remote_tools, get_mesh_info,
list_local_services, mesh_pubsub_broadcast, poll_messages, send_message,
subscribe_topic
step 1: get_mesh_info({})
diff --git a/tests/e2e/datapath.bats b/tests/e2e/datapath.bats
index d0d6cd3d..6c49a0cb 100644
--- a/tests/e2e/datapath.bats
+++ b/tests/e2e/datapath.bats
@@ -45,7 +45,7 @@ teardown() {
# Explicitly connect Node 1 to Node 2 (DHT auto-discovery is slow/unreliable in this E2E setup)
echo "[$(date +%T)] Explicitly connecting Node 1 to Node 2"
local node2_addr="/dns4/${node2_name}/tcp/5002/p2p/${node2_peer_id}"
- run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${node1_name}:8080/mcp" -tool "connect_peer" -args "{\"peer_addr\":\"${node2_addr}\"}"
+ run mesh_connect_peer 1 "${node2_addr}"
[[ "$status" -eq 0 ]]
# Verify connection
diff --git a/tests/e2e/find_remote_tools.bats b/tests/e2e/find_remote_tools.bats
index a5b0e2b5..17cdae37 100644
--- a/tests/e2e/find_remote_tools.bats
+++ b/tests/e2e/find_remote_tools.bats
@@ -58,7 +58,7 @@ teardown() {
echo "[$(date +%T)] Connecting Node 1 to Node 2"
local node2_addr="/dns4/${MESH_PREFIX}-node-2/tcp/5002/p2p/${node2_peer_id}"
- run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${MESH_PREFIX}-node-1:8080/mcp" -tool "connect_peer" -args "{\"peer_addr\":\"${node2_addr}\"}"
+ run mesh_connect_peer 1 "${node2_addr}"
[[ "$status" -eq 0 ]]
mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20
@@ -110,11 +110,7 @@ teardown() {
echo "[$(date +%T)] Connecting Node 1 to Node 2"
local node2_addr="/dns4/${MESH_PREFIX}-node-2/tcp/5002/p2p/${node2_peer_id}"
- run docker run --rm --network "${MESH_NETWORK}" \
- "${MESH_RUNTIME_IMAGE}" mcp-client \
- -url "http://${MESH_PREFIX}-node-1:8080/mcp" \
- -tool "connect_peer" \
- -args "{\"peer_addr\":\"${node2_addr}\"}"
+ run mesh_connect_peer 1 "${node2_addr}"
[[ "$status" -eq 0 ]]
mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20
@@ -159,11 +155,7 @@ teardown() {
echo "[$(date +%T)] Connecting Node 1 to Node 2"
local node2_addr="/dns4/${MESH_PREFIX}-node-2/tcp/5002/p2p/${node2_peer_id}"
- run docker run --rm --network "${MESH_NETWORK}" \
- "${MESH_RUNTIME_IMAGE}" mcp-client \
- -url "http://${MESH_PREFIX}-node-1:8080/mcp" \
- -tool "connect_peer" \
- -args "{\"peer_addr\":\"${node2_addr}\"}"
+ run mesh_connect_peer 1 "${node2_addr}"
[[ "$status" -eq 0 ]]
mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20
@@ -222,11 +214,7 @@ teardown() {
echo "[$(date +%T)] Connecting Node 1 to Node 2"
local node2_addr="/dns4/${MESH_PREFIX}-node-2/tcp/5002/p2p/${node2_peer_id}"
- run docker run --rm --network "${MESH_NETWORK}" \
- "${MESH_RUNTIME_IMAGE}" mcp-client \
- -url "http://${MESH_PREFIX}-node-1:8080/mcp" \
- -tool "connect_peer" \
- -args "{\"peer_addr\":\"${node2_addr}\"}"
+ run mesh_connect_peer 1 "${node2_addr}"
[[ "$status" -eq 0 ]]
mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20
diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index 71d0e51e..01d92098 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -196,6 +196,19 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
return 1
}
+ # POST /debug/connect-peer on node <idx>; the REST endpoint that replaced
+ # the connect_peer MCP tool (#318). Nonzero exit on any non-2xx response.
+ mesh_connect_peer() {
+ local idx="$1"
+ local peer_addr="$2"
+ docker run --rm --network "${MESH_NETWORK}" python:3.12 \
+ curl -sf -X POST --max-time 30 \
+ -H "Content-Type: application/json" \
+ -H "X-Sam-Authentication: Bearer secret-token" \
+ -d "{\"peer_addr\":\"${peer_addr}\"}" \
+ "http://${MESH_PREFIX}-node-${idx}:8080/debug/connect-peer"
+ }
+
mesh_get_node_count_via_mcp() {
local idx="$1"
local output
diff --git a/tests/e2e/policy.bats b/tests/e2e/policy.bats
index 1efad84a..7215b033 100644
--- a/tests/e2e/policy.bats
+++ b/tests/e2e/policy.bats
@@ -213,7 +213,7 @@ attenuation:
# Explicitly connect Node 2 to Node 1 to avoid "no addresses" error
local node1_addr="/dns4/${MESH_PREFIX}-node-1/tcp/5002/p2p/${TARGET_PEER_ID}"
- docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${MESH_PREFIX}-node-2:8080/mcp" -tool "connect_peer" -args "{\"peer_addr\":\"${node1_addr}\"}" >/dev/null
+ mesh_connect_peer 2 "${node1_addr}" >/dev/null
}
teardown() {
diff --git a/tests/e2e/services.bats b/tests/e2e/services.bats
index 0a0b022a..58b44977 100644
--- a/tests/e2e/services.bats
+++ b/tests/e2e/services.bats
@@ -60,11 +60,7 @@ teardown() {
echo "[$(date +%T)] Connecting Node 1 to Node 2"
local node2_addr="/dns4/${node2_name}/tcp/5002/p2p/${node2_peer_id}"
- run docker run --rm --network "${MESH_NETWORK}" \
- "${MESH_RUNTIME_IMAGE}" mcp-client \
- -url "http://${node1_name}:8080/mcp" \
- -tool "connect_peer" \
- -args "{\"peer_addr\":\"${node2_addr}\"}"
+ run mesh_connect_peer 1 "${node2_addr}"
[[ "$status" -eq 0 ]]
mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20
diff --git a/tests/integration/agent_ingress_test.go b/tests/integration/agent_ingress_test.go
index 9d590587..d3a916e9 100644
--- a/tests/integration/agent_ingress_test.go
+++ b/tests/integration/agent_ingress_test.go
@@ -68,7 +68,7 @@ func TestAgentIngressCUJ(t *testing.T) {
addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))
peerB := extractPeerID(addrB)
- callMCP(t, apiAddrA, "connect_peer", map[string]any{"peer_addr": addrB})
+ connectPeer(t, apiAddrA, addrB)
waitForDHTPeers(t, apiAddrB)
// The agent's own server, inside its sandbox.
diff --git a/tests/integration/agent_policy_test.go b/tests/integration/agent_policy_test.go
index d5d3669c..a91fdca3 100644
--- a/tests/integration/agent_policy_test.go
+++ b/tests/integration/agent_policy_test.go
@@ -83,7 +83,7 @@ attenuation:
waitForAPI(t, apiAddrB)
addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
- callMCP(t, apiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})
+ connectPeer(t, apiAddrB, addrA)
waitForDHTPeers(t, apiAddrA)
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/tests/integration/catalog_test.go b/tests/integration/catalog_test.go
index 070adb97..ba2584a1 100644
--- a/tests/integration/catalog_test.go
+++ b/tests/integration/catalog_test.go
@@ -215,8 +215,8 @@ func TestCatalogRoutingAndFailover(t *testing.T) {
addrC := waitForPeerInfoInLog(t, filepath.Join(homeC, "node.log"))
// Force Node A to connect to Node B and Node C
- callMCP(t, mcpAddrA, "connect_peer", map[string]any{"peer_addr": addrB})
- callMCP(t, mcpAddrA, "connect_peer", map[string]any{"peer_addr": addrC})
+ connectPeer(t, mcpAddrA, addrB)
+ connectPeer(t, mcpAddrA, addrC)
// Wait for them to discover each other and publish catalog by polling get_mesh_info
t.Log("Polling for discovery...")
diff --git a/tests/integration/datapath_test.go b/tests/integration/datapath_test.go
index 57911a22..6b60ed82 100644
--- a/tests/integration/datapath_test.go
+++ b/tests/integration/datapath_test.go
@@ -72,7 +72,7 @@ func TestIntegrationStdioDatapath(t *testing.T) {
peerIDA := getPeerIDFromAddr(addrA)
// Connect Node B to Node A
- callMCP(t, actualApiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})
+ connectPeer(t, actualApiAddrB, addrA)
// Register Stdio service on Node A
serviceName := "stdio-tool"
@@ -199,7 +199,7 @@ func TestIntegrationHTTPDatapath(t *testing.T) {
peerIDB := getPeerIDFromAddr(addrB)
// Connect Node B to Node A
- callMCP(t, actualApiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})
+ connectPeer(t, actualApiAddrB, addrA)
// Start a dummy HTTP server on Node A's host (simulating local service).
// It captures the headers it receives so we can assert what actually
diff --git a/tests/integration/mcp_local_tools_test.go b/tests/integration/debug_endpoints_test.go
similarity index 57%
rename from tests/integration/mcp_local_tools_test.go
rename to tests/integration/debug_endpoints_test.go
index e85ec891..af384aa9 100644
--- a/tests/integration/mcp_local_tools_test.go
+++ b/tests/integration/debug_endpoints_test.go
@@ -15,8 +15,11 @@
package integration_test
import (
+ "bytes"
"encoding/json"
"fmt"
+ "io"
+ "net/http"
"os"
"path/filepath"
"strings"
@@ -25,7 +28,57 @@ import (
"github.com/google/sam/api"
)
-func TestMCPLocalTools(t *testing.T) {
+// connectPeerWithToken dials POST /debug/connect-peer, the REST endpoint that
+// replaced the connect_peer MCP tool (#318).
+func connectPeerWithToken(t *testing.T, apiAddr, token, peerAddr string) {
+ t.Helper()
+ body, err := json.Marshal(map[string]string{"peer_addr": peerAddr})
+ if err != nil {
+ t.Fatal(err)
+ }
+ req, err := http.NewRequest(http.MethodPost, "http://"+apiAddr+"/debug/connect-peer", bytes.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("connect-peer request failed: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ respBody, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("connect-peer returned %s: %s", resp.Status, respBody)
+ }
+}
+
+func connectPeer(t *testing.T, apiAddr, peerAddr string) {
+ t.Helper()
+ connectPeerWithToken(t, apiAddr, "test-token", peerAddr)
+}
+
+// debugGet fetches one GET /debug endpoint and returns its JSON body.
+func debugGet(t *testing.T, apiAddr, path string) string {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodGet, "http://"+apiAddr+path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer test-token")
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("GET %s failed: %v", path, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ respBody, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET %s returned %s: %s", path, resp.Status, respBody)
+ }
+ return string(respBody)
+}
+
+func TestDebugEndpoints(t *testing.T) {
nodeBin := buildBinary(t, "./cmd/sam-node")
tmpDir := t.TempDir()
@@ -76,7 +129,7 @@ roles: []
"--jwt", nodeJWT,
)
- // Resolve actual MCP address from log
+ // Resolve actual local API address from log
actualApiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
actualApiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
@@ -87,11 +140,25 @@ roles: []
// Resolve Peer addresses
addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
- // Connect Node B to Node A directly
- callMCP(t, actualApiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})
+ // Connect Node B to Node A directly; exercises POST /debug/connect-peer
+ connectPeer(t, actualApiAddrB, addrA)
+
+ t.Run("mesh-info", func(t *testing.T) {
+ resp := debugGet(t, actualApiAddrA, "/debug/mesh-info")
+ var info map[string]any
+ if err := json.Unmarshal([]byte(resp), &info); err != nil {
+ t.Fatalf("failed to unmarshal JSON: %v", err)
+ }
+ if _, ok := info["connected_peers"]; !ok {
+ t.Errorf("expected connected_peers, got %v", info)
+ }
+ if routerPeerID, ok := info["router_peer_id"].(string); !ok || routerPeerID == "" {
+ t.Errorf("expected router_peer_id, got %v", info)
+ }
+ })
- t.Run("get_token_info", func(t *testing.T) {
- resp := callMCP(t, actualApiAddrA, "get_token_info", map[string]any{})
+ t.Run("token-info", func(t *testing.T) {
+ resp := debugGet(t, actualApiAddrA, "/debug/token-info")
var info map[string]any
if err := json.Unmarshal([]byte(resp), &info); err != nil {
t.Fatalf("failed to unmarshal JSON: %v", err)
@@ -104,8 +171,8 @@ roles: []
}
})
- t.Run("get_network_info", func(t *testing.T) {
- resp := callMCP(t, actualApiAddrA, "get_network_info", map[string]any{})
+ t.Run("network-info", func(t *testing.T) {
+ resp := debugGet(t, actualApiAddrA, "/debug/network-info")
var info map[string]any
if err := json.Unmarshal([]byte(resp), &info); err != nil {
t.Fatalf("failed to unmarshal JSON: %v", err)
@@ -115,8 +182,8 @@ roles: []
}
})
- t.Run("check_connectivity", func(t *testing.T) {
- resp := callMCP(t, actualApiAddrA, "check_connectivity", map[string]any{})
+ t.Run("connectivity", func(t *testing.T) {
+ resp := debugGet(t, actualApiAddrA, "/debug/connectivity")
var info map[string]any
if err := json.Unmarshal([]byte(resp), &info); err != nil {
t.Fatalf("failed to unmarshal JSON: %v", err)
@@ -131,8 +198,8 @@ roles: []
}
})
- t.Run("get_recent_logs", func(t *testing.T) {
- resp := callMCP(t, actualApiAddrA, "get_recent_logs", map[string]any{})
+ t.Run("logs", func(t *testing.T) {
+ resp := debugGet(t, actualApiAddrA, "/debug/logs")
if !strings.Contains(resp, "Starting MCP server") && !strings.Contains(resp, "SAM Node Online") {
t.Errorf("expected logs to contain startup messages, got: %v", resp)
}
diff --git a/tests/integration/identity_evidence_test.go b/tests/integration/identity_evidence_test.go
index 124f4b5b..1b58b187 100644
--- a/tests/integration/identity_evidence_test.go
+++ b/tests/integration/identity_evidence_test.go
@@ -78,7 +78,7 @@ func TestIdentityEvidenceOperatorFlow(t *testing.T) {
if providerPeerID == "" {
t.Fatalf("provider address %q has no PeerID", providerAddr)
}
- callMCP(t, ownerAPI, "connect_peer", map[string]any{"peer_addr": providerAddr})
+ connectPeer(t, ownerAPI, providerAddr)
client := identityEvidenceSocketClient(ownerSocket)
waitForIdentityEvidenceSocket(t, client)
diff --git a/tests/integration/openai_facade_test.go b/tests/integration/openai_facade_test.go
index 5dd87fd4..1f90706b 100644
--- a/tests/integration/openai_facade_test.go
+++ b/tests/integration/openai_facade_test.go
@@ -63,7 +63,7 @@ func TestOpenAIFacadeCUJ(t *testing.T) {
waitForAPI(t, apiAddrB)
addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
- callMCP(t, apiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})
+ connectPeer(t, apiAddrB, addrA)
waitForDHTPeers(t, apiAddrA)
// Fake OpenAI-compatible backend on node A's side.
diff --git a/tests/integration/pubsub_test.go b/tests/integration/pubsub_test.go
index d16edf18..7a6db0a7 100644
--- a/tests/integration/pubsub_test.go
+++ b/tests/integration/pubsub_test.go
@@ -137,7 +137,7 @@ func TestPubSubTools(t *testing.T) {
// Force Node 1 to connect to Node 2
addr2 := waitForPeerInfoInLog(t, filepath.Join(tmpHome2, "node2.log"))
t.Logf("Node 2 address: %s", addr2)
- callTool(mcpAddr1, "connect_peer", map[string]any{"peer_addr": addr2})
+ connectPeer(t, mcpAddr1, addr2)
// Node 1 subscribes to topic "test-topic"
subscribeResult1 := callTool(mcpAddr1, "subscribe_topic", map[string]any{
diff --git a/tests/integration/revocation_test.go b/tests/integration/revocation_test.go
index 8c35e62a..b7f837d8 100644
--- a/tests/integration/revocation_test.go
+++ b/tests/integration/revocation_test.go
@@ -194,21 +194,12 @@ roles:
node2TCPAddr := matchesAddr[1]
// 6. Request Node 1 to connect to Node 2
- connectArgs := fmt.Sprintf(`{"peer_addr":"%s/p2p/%s"}`, node2TCPAddr, node2PeerID)
- stdout, stderr, err := runCommand(t, repoRoot(t), 5*time.Second, nil, "",
- clientBin,
- "-url", fmt.Sprintf("http://127.0.0.1:%d/mcp", node1ApiPort),
- "-token", "node1-token",
- "-tool", "connect_peer",
- "-args", connectArgs,
- )
- if err != nil {
- t.Fatalf("connect_peer failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
- }
+ connectPeerWithToken(t, fmt.Sprintf("127.0.0.1:%d", node1ApiPort), "node1-token",
+ fmt.Sprintf("%s/p2p/%s", node2TCPAddr, node2PeerID))
// Verify Node 1 is connected to Node 2
time.Sleep(1 * time.Second)
- stdout, stderr, err = runCommand(t, repoRoot(t), 5*time.Second, nil, "",
+ stdout, stderr, err := runCommand(t, repoRoot(t), 5*time.Second, nil, "",
clientBin,
"-url", fmt.Sprintf("http://127.0.0.1:%d/mcp", node1ApiPort),
"-token", "node1-token",
diff --git a/tests/integration/sandbox_boundary_test.go b/tests/integration/sandbox_boundary_test.go
index 4da9506b..70a73476 100644
--- a/tests/integration/sandbox_boundary_test.go
+++ b/tests/integration/sandbox_boundary_test.go
@@ -77,7 +77,7 @@ func TestSandboxBoundaryCUJ(t *testing.T) {
addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
peerA := extractPeerID(addrA)
- callMCP(t, apiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})
+ connectPeer(t, apiAddrB, addrA)
waitForDHTPeers(t, apiAddrA)
inference := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/tests/integration/service_discovery_test.go b/tests/integration/service_discovery_test.go
index 3f49e2f2..403f31db 100644
--- a/tests/integration/service_discovery_test.go
+++ b/tests/integration/service_discovery_test.go
@@ -73,7 +73,7 @@ func TestServiceDiscovery(t *testing.T) {
// 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, actualApiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})
+ connectPeer(t, actualApiAddrB, addrA)
// Wait for DHT to have peers on Node A
t.Log("Waiting for DHT to have peers on Node A...")
@@ -176,7 +176,7 @@ func TestServiceDiscoveryStreaming(t *testing.T) {
addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
// Connect Node B to Node A
- callMCP(t, actualApiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})
+ connectPeer(t, actualApiAddrB, addrA)
// Wait for DHT to have peers on Node A
t.Log("Waiting for DHT to have peers on Node A...")