Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
node: replace map[string]any /debug payloads with typed structs
Antonio Ojea38896e365a8e
diff --git a/agents/skills/sam-mesh/SKILL.md b/agents/skills/sam-mesh/SKILL.mdindex b499ffaa..f6e8f348 100644--- a/agents/skills/sam-mesh/SKILL.md+++ b/agents/skills/sam-mesh/SKILL.md@@ -15,7 +15,7 @@ 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:+- The node is up but the mesh seems broken:[Diagnose The Node](#diagnose-the-node).- The task needs a remote tool or capability:[Inspect The Mesh](#inspect-the-mesh).@@ -104,16 +104,30 @@ 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:+Operator diagnostics are not MCP tools, so they never appear in the tool list.+A running node serves them under `/debug`, and the `sam-node` CLI wraps each+endpoint over the node's Unix socket — no token involved:```bash-sam-node debug --help+sam-node debug mesh-info # connected peers, DHT size, router peer ID+sam-node debug connectivity [peer-id] # ping the SAM router, or a specific peer+sam-node debug network-info # listen and observed addresses+sam-node debug token-info # local auth token expiration and status+sam-node debug logs # recent log lines+sam-node debug connect-peer <multiaddr> # manually dial a peer```-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`.+Each command prints the endpoint's raw JSON, so it composes with `jq`. The same+data is one `curl` away when the CLI is not at hand:++```bash+curl --unix-socket ~/.config/sam-mesh/sam.sock http://localhost/debug/mesh-info+```++These endpoints answer even while the mesh is unreachable — that is the state+they exist to diagnose. When the node runs but mesh tools fail, check+`debug connectivity` for `router_error_msg` and `debug token-info` for an+expired token before restarting or re-enrolling anything.## Inspect The Meshdiff --git a/internal/node/debug_handlers.go b/internal/node/debug_handlers.goindex d95e7594..118345cb 100644--- a/internal/node/debug_handlers.go+++ b/internal/node/debug_handlers.go@@ -54,7 +54,7 @@ func newDebugHandler(n *SamNode) http.Handler {writeDebugJSON(w, n.tokenInfo())})mux.HandleFunc("GET /debug/logs", func(w http.ResponseWriter, r *http.Request) {- writeDebugJSON(w, map[string]any{"logs": GetRecentLogs()})+ writeDebugJSON(w, logsResponse{Logs: GetRecentLogs()})})mux.HandleFunc("POST /debug/connect-peer", func(w http.ResponseWriter, r *http.Request) {var req struct {@@ -109,9 +109,47 @@ func writeDebugJSON(w http.ResponseWriter, v any) {}}+// The types below are the /debug payloads. They are unexported on purpose:+// these endpoints are unversioned operator diagnostics, not part of the+// api/sam.proto mesh contract.++type meshInfoResponse struct {+ PeerID string `json:"peer_id"`+ ConnectedPeers []string `json:"connected_peers"`+ DHTSize int `json:"dht_size"`+ RouterPeerID string `json:"router_peer_id"`+ LocalAPISocket string `json:"local_api_socket,omitempty"`+}++type connectivityResponse struct {+ ConnectedPeers int `json:"connected_peers"`+ TotalKnownPeers int `json:"total_known_peers"`+ PingLatencyMS *int64 `json:"ping_latency_ms,omitempty"`+ PingError *bool `json:"ping_error,omitempty"`+ PingErrorMsg string `json:"ping_error_msg,omitempty"`+ RouterLatencyMS *int64 `json:"router_latency_ms,omitempty"`+ RouterError *bool `json:"router_error,omitempty"`+ RouterErrorMsg string `json:"router_error_msg,omitempty"`+}++type tokenInfoResponse struct {+ HasToken bool `json:"has_token"`+ ExpiresInSeconds *float64 `json:"expires_in_seconds,omitempty"`+ IsExpired *bool `json:"is_expired,omitempty"`+}++type networkInfoResponse struct {+ ListenAddresses []string `json:"listen_addresses"`+ ObservedAddresses []string `json:"observed_addresses"`+}++type logsResponse struct {+ Logs []string `json:"logs"`+}+// 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) {+func (n *SamNode) meshInfo() (*meshInfoResponse, error) {if err := n.debugReady(); err != nil {return nil, err}@@ -122,29 +160,25 @@ func (n *SamNode) meshInfo() (map[string]any, error) {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+ return &meshInfoResponse{+ PeerID: n.Host.ID().String(),+ ConnectedPeers: connectedPeers,+ DHTSize: n.DHT.RoutingTable().Size(),+ RouterPeerID: n.RouterPeerID.String(),+ LocalAPISocket: n.BoundSocketPath,+ }, 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 {+func (n *SamNode) connectivityStats(ctx context.Context, peerIDStr string) connectivityResponse {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()),+ stats := connectivityResponse{+ ConnectedPeers: len(n.Host.Network().Peers()),+ TotalKnownPeers: len(n.Host.Peerstore().Peers()),}if peerIDStr != "" {@@ -153,22 +187,27 @@ func (n *SamNode) connectivityStats(ctx context.Context, peerIDStr string) map[sn.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+ latency := time.Since(start).Milliseconds()+ failed := err != nil+ stats.PingLatencyMS = &latency+ stats.PingError = &failedif err != nil {- stats["ping_error_msg"] = err.Error()+ stats.PingErrorMsg = err.Error()}} else {- stats["ping_error"] = true- stats["ping_error_msg"] = "invalid peer id"+ failed := true+ stats.PingError = &failed+ stats.PingErrorMsg = "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+ latency := time.Since(start).Milliseconds()+ failed := err != nil+ stats.RouterLatencyMS = &latency+ stats.RouterError = &failedif err != nil {- stats["router_error_msg"] = err.Error()+ stats.RouterErrorMsg = err.Error()}}@@ -176,25 +215,24 @@ func (n *SamNode) connectivityStats(ctx context.Context, peerIDStr string) map[s}// tokenInfo backs GET /debug/token-info.-func (n *SamNode) tokenInfo() map[string]any {- info := map[string]any{- "has_token": false,- }-+func (n *SamNode) tokenInfo() tokenInfoResponse {+ var info tokenInfoResponsetoken, err := n.Store.LoadIdentity()if err == nil && len(token) > 0 {- info["has_token"] = true+ info.HasToken = trueexp, 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+ expiresIn := time.Until(time.Unix(exp, 0)).Seconds()+ expired := time.Now().Unix() > exp+ info.ExpiresInSeconds = &expiresIn+ info.IsExpired = &expired}}return info}// networkInfo backs GET /debug/network-info.-func (n *SamNode) networkInfo() map[string]any {+func (n *SamNode) networkInfo() networkInfoResponse {listenAddrs := []string{}for _, a := range n.Host.Network().ListenAddresses() {listenAddrs = append(listenAddrs, a.String())@@ -205,9 +243,9 @@ func (n *SamNode) networkInfo() map[string]any {observedAddrs = append(observedAddrs, a.String())}- return map[string]any{- "listen_addresses": listenAddrs,- "observed_addresses": observedAddrs,+ return networkInfoResponse{+ ListenAddresses: listenAddrs,+ ObservedAddresses: observedAddrs,}}diff --git a/internal/node/mcp_handlers_additional_test.go b/internal/node/mcp_handlers_additional_test.goindex fbf1a69f..ca18797a 100644--- a/internal/node/mcp_handlers_additional_test.go+++ b/internal/node/mcp_handlers_additional_test.go@@ -173,9 +173,13 @@ func TestConnectivityStats(t *testing.T) {defer cleanup1()stats := node1.connectivityStats(context.Background(), "")+ if stats.ConnectedPeers < 0 || stats.TotalKnownPeers < 0 {+ t.Fatalf("nonsensical peer counts: %+v", stats)+ }- if _, ok := stats["connected_peers"]; !ok {- t.Fatalf("missing connected_peers in stats")+ invalid := node1.connectivityStats(context.Background(), "not-a-peer-id")+ if invalid.PingError == nil || !*invalid.PingError || invalid.PingErrorMsg != "invalid peer id" {+ t.Fatalf("expected invalid peer id ping error, got %+v", invalid)}}@@ -185,9 +189,8 @@ func TestTokenInfo(t *testing.T) {defer cleanup1()info := node1.tokenInfo()-- if _, ok := info["has_token"].(bool); !ok {- t.Fatalf("expected has_token boolean, got %v", info["has_token"])+ if info.HasToken {+ t.Fatalf("bare node should have no token, got %+v", info)}}@@ -197,9 +200,8 @@ func TestNetworkInfo(t *testing.T) {defer cleanup1()info := node1.networkInfo()-- if _, ok := info["listen_addresses"]; !ok {- t.Fatalf("missing listen_addresses")+ if len(info.ListenAddresses) == 0 {+ t.Fatalf("expected listen addresses, got %+v", info)}}