Skip to content

Agent Mesh

Commonize MCP handlers

Tomas Tormo443e83593328
diff --git a/cmd/sam-node/gate.go b/cmd/sam-node/gate.go
index a2ab3a4c..ccb02be1 100644
--- a/cmd/sam-node/gate.go
+++ b/cmd/sam-node/gate.go
@@ -16,11 +16,8 @@ package main
import (
"context"
- "encoding/json"
"fmt"
- "github.com/google/sam/api"
-
"github.com/libp2p/go-libp2p/core/connmgr"
"github.com/libp2p/go-libp2p/core/control"
"github.com/libp2p/go-libp2p/core/network"
@@ -92,76 +89,19 @@ func (n *SamNode) HandleMCPStream(s network.Stream) {
mcp.AddTool(server, &mcp.Tool{
Name: "send_message",
Description: "Send a message to another agent in the mesh",
- }, handleSendMessage)
-
- // Add the get_mesh_info tool.
- mcp.AddTool(server, &mcp.Tool{
- Name: "get_mesh_info",
- Description: "Get information about the mesh network",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct{}) (*mcp.CallToolResult, any, error) {
- if n == nil {
- return nil, nil, fmt.Errorf("node not initialized")
- }
- n.mu.Lock()
- var knownPeers []string
- for p := range n.knownPeers {
- knownPeers = append(knownPeers, p)
- }
- n.mu.Unlock()
-
- 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{
- "known_peers": knownPeers,
- "connected_peers": connectedPeers,
- "dht_size": dhtSize,
- "hub_peer_id": n.HubPeerID.String(),
- }
- responseBytes, err := json.Marshal(resData)
- if err != nil {
- return nil, nil, err
- }
- response := string(responseBytes)
-
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: response},
- },
- }, nil, nil
- })
+ }, n.handleSendMessage)
// Add list_local_services tool
- // TODO: Commonize this function since is also present in mcp.go
mcp.AddTool(server, &mcp.Tool{
Name: "list_local_services",
Description: "List services registered on the local node. Optionally filter by type.",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct {
- Type string `json:"type,omitempty" jsonschema:"Optional service type filter (mcp, inference, a2a). Empty means all types."`
- }) (*mcp.CallToolResult, any, error) {
- typeFilter := api.ServiceType_SERVICE_TYPE_UNSPECIFIED
- if params.Type != "" {
- parsed, err := parseServiceType(params.Type)
- if err != nil {
- return nil, nil, err
- }
- typeFilter = parsed
- }
- services := n.ListLocalServices(typeFilter)
- respData, err := json.Marshal(services)
- if err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: string(respData)},
- },
- }, nil, nil
- })
+ }, n.handleListLocalServices)
+
+ // Add the get_mesh_info tool.
+ mcp.AddTool(server, &mcp.Tool{
+ Name: "get_mesh_info",
+ Description: "Get information about the mesh network",
+ }, n.handleGetMeshInfo)
ctx := context.Background()
if err := server.Run(ctx, transport); err != nil {
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
index b601575f..86441952 100644
--- a/cmd/sam-node/mcp.go
+++ b/cmd/sam-node/mcp.go
@@ -25,27 +25,9 @@ import (
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-msgio"
"github.com/modelcontextprotocol/go-sdk/mcp"
- "github.com/multiformats/go-multiaddr"
"google.golang.org/protobuf/proto"
)
-// SendMessageParams defines the parameters for the send_message tool.
-type SendMessageParams struct {
- PeerID string `json:"peer_id" jsonschema:"The Peer ID of the target agent"`
- Message string `json:"message" jsonschema:"The message content"`
-}
-
-// handleSendMessage implements the send_message tool.
-func handleSendMessage(ctx context.Context, req *mcp.CallToolRequest, params SendMessageParams) (*mcp.CallToolResult, any, error) {
- response := fmt.Sprintf("Simulated sending message to %s: %s", params.PeerID, params.Message)
-
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: response},
- },
- }, nil, nil
-}
-
// NewMCPHandler creates a new HTTP handler for the MCP server using the official SDK.
func NewMCPHandler(node *SamNode) http.Handler {
// Create an MCP server.
@@ -58,223 +40,55 @@ func NewMCPHandler(node *SamNode) http.Handler {
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "send_message",
Description: "Send a message to another agent in the mesh",
- }, handleSendMessage)
+ }, node.handleSendMessage)
// Add list_local_services tool
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "list_local_services",
Description: "List services registered on the local node. Optionally filter by type.",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct {
- Type string `json:"type,omitempty" jsonschema:"Optional service type filter (mcp, inference, a2a). Empty means all types."`
- }) (*mcp.CallToolResult, any, error) {
- typeFilter := api.ServiceType_SERVICE_TYPE_UNSPECIFIED
- if params.Type != "" {
- parsed, err := parseServiceType(params.Type)
- if err != nil {
- return nil, nil, err
- }
- typeFilter = parsed
- }
- services := node.ListLocalServices(typeFilter)
- respData, err := json.Marshal(services)
- if err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: string(respData)},
- },
- }, nil, nil
- })
+ }, node.handleListLocalServices)
// Add discover_remote_services tool
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "discover_remote_services",
Description: "Discover remote services in the mesh. Provide only `type` to browse every reachable service of that type (returns name + description for each); add `name` to target a specific service.",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct {
- Type string `json:"type" jsonschema:"Service type (mcp, inference, a2a)"`
- Name string `json:"name,omitempty" jsonschema:"Optional service name. Omit to list all services of the given type."`
- }) (*mcp.CallToolResult, any, error) {
- serviceType, err := parseServiceType(params.Type)
- if err != nil || serviceType == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {
- return nil, nil, fmt.Errorf("invalid or unspecified service type: %s", params.Type)
- }
- providers, err := node.DiscoverRemoteServices(ctx, serviceType, params.Name)
- if err != nil {
- return nil, nil, err
- }
- respData, err := json.Marshal(providers)
- if err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: string(respData)},
- },
- }, nil, nil
- })
+ }, node.handleDiscoverRemoteServices)
// Add the mesh_pubsub_broadcast tool.
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "mesh_pubsub_broadcast",
Description: "Publish an event payload to a custom GossipSub topic",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct {
- Topic string `json:"topic" jsonschema:"GossipSub topic name"`
- Payload string `json:"payload" jsonschema:"Payload to publish"`
- }) (*mcp.CallToolResult, any, error) {
- node.mu.Lock()
- t, ok := node.topics[params.Topic]
- var err error
- if !ok {
- t, err = node.PubSub.Join(params.Topic)
- if err == nil {
- node.topics[params.Topic] = t
- }
- }
- node.mu.Unlock()
- if err != nil {
- return nil, nil, err
- }
- if err := t.Publish(ctx, []byte(params.Payload)); err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: "Published"},
- },
- }, nil, nil
- })
+ }, node.handleMeshPubsubBroadcast)
// Add the poll_messages tool.
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "poll_messages",
Description: "Poll for incoming messages on custom GossipSub topics",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct {
- Topic string `json:"topic" jsonschema:"GossipSub topic name"`
- }) (*mcp.CallToolResult, any, error) {
- node.mu.Lock()
- msgs := node.receivedMsgs[params.Topic]
- delete(node.receivedMsgs, params.Topic) // Clear on read!
- node.mu.Unlock()
-
- response := fmt.Sprintf("Messages on topic %s: %v", params.Topic, msgs)
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: response},
- },
- }, nil, nil
- })
+ }, node.handlePollMessages)
// Add the subscribe_topic tool.
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "subscribe_topic",
Description: "Subscribe to a custom GossipSub topic",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct {
- Topic string `json:"topic" jsonschema:"GossipSub topic name"`
- }) (*mcp.CallToolResult, any, error) {
- if err := node.subscribeToTopic(ctx, params.Topic); err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: "Subscribed"},
- },
- }, nil, nil
- })
+ }, node.handleSubscribeTopic)
// Add the get_mesh_info tool.
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "get_mesh_info",
Description: "Get information about the mesh network",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct{}) (*mcp.CallToolResult, any, error) {
- if node == nil {
- return nil, nil, fmt.Errorf("node not initialized")
- }
- node.mu.Lock()
- var knownPeers []string
- for p := range node.knownPeers {
- knownPeers = append(knownPeers, p)
- }
- node.mu.Unlock()
-
- peers := node.Host.Network().Peers()
- var connectedPeers []string
- for _, p := range peers {
- connectedPeers = append(connectedPeers, p.String())
- }
- dhtSize := node.DHT.RoutingTable().Size()
-
- resData := map[string]any{
- "known_peers": knownPeers,
- "connected_peers": connectedPeers,
- "dht_size": dhtSize,
- "hub_peer_id": node.HubPeerID.String(),
- }
- responseBytes, err := json.Marshal(resData)
- if err != nil {
- return nil, nil, err
- }
- response := string(responseBytes)
-
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: response},
- },
- }, nil, nil
- })
+ }, node.handleGetMeshInfo)
// Add the call_remote_tool tool.
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "call_remote_tool",
Description: "Call an MCP tool on a remote agent",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct {
- PeerID string `json:"peer_id" jsonschema:"The Peer ID of the target agent"`
- ToolName string `json:"tool_name" jsonschema:"The name of the tool to call"`
- Arguments string `json:"arguments" jsonschema:"JSON encoded arguments for the tool"`
- }) (*mcp.CallToolResult, any, error) {
- logger.Infof("[MCP] call_remote_tool called for peer %s, tool %s", params.PeerID, params.ToolName)
- targetPeer, err := peer.Decode(params.PeerID)
- if err != nil {
- return nil, nil, err
- }
- var args map[string]any
- if params.Arguments != "" {
- if err := json.Unmarshal([]byte(params.Arguments), &args); err != nil {
- return nil, nil, err
- }
- }
-
- res, err := node.CallMCPTool(ctx, targetPeer, params.ToolName, args)
- if err != nil {
- return nil, nil, err
- }
- return res, nil, nil
- })
+ }, node.handleCallRemoteTool)
// Add the connect_peer tool.
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "connect_peer",
Description: "Connect to a peer in the mesh",
- }, func(ctx context.Context, req *mcp.CallToolRequest, params struct {
- PeerAddr string `json:"peer_addr" jsonschema:"The full multiaddress of the peer to connect to"`
- }) (*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 err := node.Host.Connect(ctx, *addrInfo); err != nil {
- return nil, nil, err
- }
- return &mcp.CallToolResult{
- Content: []mcp.Content{
- &mcp.TextContent{Text: "Connected"},
- },
- }, nil, nil
- })
+ }, node.handleConnectPeer)
// Create the SSE handler using the SDK
sseHandler := mcp.NewSSEHandler(func(request *http.Request) *mcp.Server {
diff --git a/cmd/sam-node/mcp_handlers.go b/cmd/sam-node/mcp_handlers.go
new file mode 100644
index 00000000..6a8e60ee
--- /dev/null
+++ b/cmd/sam-node/mcp_handlers.go
@@ -0,0 +1,242 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/google/sam/api"
+ "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.
+type SendMessageParams struct {
+ PeerID string `json:"peer_id" jsonschema:"The Peer ID of the target agent"`
+ Message string `json:"message" jsonschema:"The message content"`
+}
+
+// handleSendMessage implements the send_message tool.
+func (n *SamNode) handleSendMessage(ctx context.Context, req *mcp.CallToolRequest, params SendMessageParams) (*mcp.CallToolResult, any, error) {
+ response := fmt.Sprintf("Simulated sending message to %s: %s", params.PeerID, params.Message)
+
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: response},
+ },
+ }, nil, nil
+}
+
+// ListLocalServicesParams defines the parameters for the list_local_services tool.
+type ListLocalServicesParams struct {
+ Type string `json:"type,omitempty" jsonschema:"Optional service type filter (mcp, inference, a2a). Empty means all types."`
+}
+
+// handleListLocalServices implements the list_local_services tool.
+func (n *SamNode) handleListLocalServices(ctx context.Context, req *mcp.CallToolRequest, params ListLocalServicesParams) (*mcp.CallToolResult, any, error) {
+ typeFilter := api.ServiceType_SERVICE_TYPE_UNSPECIFIED
+ if params.Type != "" {
+ parsed, err := parseServiceType(params.Type)
+ if err != nil {
+ return nil, nil, err
+ }
+ typeFilter = parsed
+ }
+ services := n.ListLocalServices(typeFilter)
+ respData, err := json.Marshal(services)
+ if err != nil {
+ return nil, nil, err
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: string(respData)},
+ },
+ }, nil, nil
+}
+
+// DiscoverRemoteServicesParams defines the parameters for the discover_remote_services tool.
+type DiscoverRemoteServicesParams struct {
+ Type string `json:"type" jsonschema:"Service type (mcp, inference, a2a)"`
+ Name string `json:"name,omitempty" jsonschema:"Optional service name. Omit to list all services of the given type."`
+}
+
+// handleDiscoverRemoteServices implements the discover_remote_services tool.
+func (n *SamNode) handleDiscoverRemoteServices(ctx context.Context, req *mcp.CallToolRequest, params DiscoverRemoteServicesParams) (*mcp.CallToolResult, any, error) {
+ serviceType, err := parseServiceType(params.Type)
+ if err != nil || serviceType == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {
+ return nil, nil, fmt.Errorf("invalid or unspecified service type: %s", params.Type)
+ }
+ providers, err := n.DiscoverRemoteServices(ctx, serviceType, params.Name)
+ if err != nil {
+ return nil, nil, err
+ }
+ respData, err := json.Marshal(providers)
+ if err != nil {
+ return nil, nil, err
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: string(respData)},
+ },
+ }, nil, nil
+}
+
+// MeshPubsubBroadcastParams defines the parameters for the mesh_pubsub_broadcast tool.
+type MeshPubsubBroadcastParams struct {
+ Topic string `json:"topic" jsonschema:"GossipSub topic name"`
+ Payload string `json:"payload" jsonschema:"Payload to publish"`
+}
+
+// handleMeshPubsubBroadcast implements the mesh_pubsub_broadcast tool.
+func (n *SamNode) handleMeshPubsubBroadcast(ctx context.Context, req *mcp.CallToolRequest, params MeshPubsubBroadcastParams) (*mcp.CallToolResult, any, error) {
+ n.mu.Lock()
+ t, ok := n.topics[params.Topic]
+ var err error
+ if !ok {
+ t, err = n.PubSub.Join(params.Topic)
+ if err == nil {
+ n.topics[params.Topic] = t
+ }
+ }
+ n.mu.Unlock()
+ if err != nil {
+ return nil, nil, err
+ }
+ if err := t.Publish(ctx, []byte(params.Payload)); err != nil {
+ return nil, nil, err
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: "Published"},
+ },
+ }, nil, nil
+}
+
+// PollMessagesParams defines the parameters for the poll_messages tool.
+type PollMessagesParams struct {
+ Topic string `json:"topic" jsonschema:"GossipSub topic name"`
+}
+
+// handlePollMessages implements the poll_messages tool.
+func (n *SamNode) handlePollMessages(ctx context.Context, req *mcp.CallToolRequest, params PollMessagesParams) (*mcp.CallToolResult, any, error) {
+ n.mu.Lock()
+ msgs := n.receivedMsgs[params.Topic]
+ delete(n.receivedMsgs, params.Topic) // Clear on read!
+ n.mu.Unlock()
+
+ response := fmt.Sprintf("Messages on topic %s: %v", params.Topic, msgs)
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: response},
+ },
+ }, nil, nil
+}
+
+// SubscribeTopicParams defines the parameters for the subscribe_topic tool.
+type SubscribeTopicParams struct {
+ Topic string `json:"topic" jsonschema:"GossipSub topic name"`
+}
+
+// handleSubscribeTopic implements the subscribe_topic tool.
+func (n *SamNode) handleSubscribeTopic(ctx context.Context, req *mcp.CallToolRequest, params SubscribeTopicParams) (*mcp.CallToolResult, any, error) {
+ if err := n.subscribeToTopic(ctx, params.Topic); err != nil {
+ return nil, nil, err
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: "Subscribed"},
+ },
+ }, nil, nil
+}
+
+// GetMeshInfoParams defines the parameters for the get_mesh_info tool.
+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")
+ }
+ n.mu.Lock()
+ var knownPeers []string
+ for p := range n.knownPeers {
+ knownPeers = append(knownPeers, p)
+ }
+ n.mu.Unlock()
+
+ 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{
+ "known_peers": knownPeers,
+ "connected_peers": connectedPeers,
+ "dht_size": dhtSize,
+ "hub_peer_id": n.HubPeerID.String(),
+ }
+ responseBytes, err := json.Marshal(resData)
+ if err != nil {
+ return nil, nil, err
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: string(responseBytes)},
+ },
+ }, nil, nil
+}
+
+// CallRemoteToolParams defines the parameters for the call_remote_tool tool.
+type CallRemoteToolParams struct {
+ PeerID string `json:"peer_id" jsonschema:"The Peer ID of the target agent"`
+ ToolName string `json:"tool_name" jsonschema:"The name of the tool to call"`
+ Arguments string `json:"arguments" jsonschema:"JSON encoded arguments for the tool"`
+}
+
+// handleCallRemoteTool implements the call_remote_tool tool.
+func (n *SamNode) handleCallRemoteTool(ctx context.Context, req *mcp.CallToolRequest, params CallRemoteToolParams) (*mcp.CallToolResult, any, error) {
+ logger.Infof("[MCP] call_remote_tool called for peer %s, tool %s", params.PeerID, params.ToolName)
+ targetPeer, err := peer.Decode(params.PeerID)
+ if err != nil {
+ return nil, nil, err
+ }
+ var args map[string]any
+ if params.Arguments != "" {
+ if err := json.Unmarshal([]byte(params.Arguments), &args); err != nil {
+ return nil, nil, err
+ }
+ }
+ res, err := n.CallMCPTool(ctx, targetPeer, params.ToolName, args)
+ if err != nil {
+ return nil, nil, err
+ }
+ 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 err := n.Host.Connect(ctx, *addrInfo); err != nil {
+ return nil, nil, err
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: "Connected"},
+ },
+ }, nil, nil
+}