Skip to content

Agent Mesh

find_remote_tools: discover hosted MCP service tools across the mesh

Tomas Tormo11d2172d23ba
diff --git a/cmd/sam-node/bridge_transport.go b/cmd/sam-node/bridge_transport.go
new file mode 100644
index 00000000..dca37a61
--- /dev/null
+++ b/cmd/sam-node/bridge_transport.go
@@ -0,0 +1,74 @@
+// 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 (
+ "context"
+ "io"
+
+ "github.com/modelcontextprotocol/go-sdk/jsonrpc"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+// bridgeTransport adapts a StdioBridge to the mcp.Transport interface.
+// Reads pull lines from a Subscribe channel; writes go through Send.
+// Multiple bridgeTransports can coexist on one bridge; JSON-RPC IDs
+// distinguish their responses, as with HTTP/SSE subscribers.
+type bridgeTransport struct {
+ bridge *StdioBridge
+ ch <-chan string
+ unsub func()
+}
+
+func newBridgeTransport(b *StdioBridge) *bridgeTransport {
+ return &bridgeTransport{bridge: b}
+}
+
+func (t *bridgeTransport) Connect(ctx context.Context) (mcp.Connection, error) {
+ ch, unsub := t.bridge.Subscribe()
+ t.ch = ch
+ t.unsub = unsub
+ return t, nil
+}
+
+func (t *bridgeTransport) Read(ctx context.Context) (jsonrpc.Message, error) {
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case line, ok := <-t.ch:
+ if !ok {
+ return nil, io.EOF
+ }
+ return jsonrpc.DecodeMessage([]byte(line))
+ }
+}
+
+func (t *bridgeTransport) Write(ctx context.Context, msg jsonrpc.Message) error {
+ data, err := jsonrpc.EncodeMessage(msg)
+ if err != nil {
+ return err
+ }
+ return t.bridge.Send(data)
+}
+
+func (t *bridgeTransport) Close() error {
+ if t.unsub != nil {
+ t.unsub()
+ t.unsub = nil
+ }
+ return nil
+}
+
+func (t *bridgeTransport) SessionID() string { return "" }
diff --git a/cmd/sam-node/bridge_transport_test.go b/cmd/sam-node/bridge_transport_test.go
new file mode 100644
index 00000000..2e7c53b3
--- /dev/null
+++ b/cmd/sam-node/bridge_transport_test.go
@@ -0,0 +1,95 @@
+// 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
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/modelcontextprotocol/go-sdk/jsonrpc"
+)
+
+func TestBridgeTransport_WriteSendsToStdin(t *testing.T) {
+ b, stdoutWriter, stdinBuf := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ tr := newBridgeTransport(b)
+ conn, err := tr.Connect(context.Background())
+ if err != nil {
+ t.Fatalf("Connect: %v", err)
+ }
+ defer func() { _ = conn.Close() }()
+
+ id, _ := jsonrpc.MakeID(float64(1))
+ req := &jsonrpc.Request{ID: id, Method: "tools/list"}
+ if err := conn.Write(context.Background(), req); err != nil {
+ t.Fatalf("Write: %v", err)
+ }
+
+ got := stdinBuf.String()
+ if len(got) == 0 || got[len(got)-1] != '\n' {
+ t.Fatalf("Write: expected newline-terminated frame on stdin, got %q", got)
+ }
+ var parsed map[string]any
+ if err := json.Unmarshal([]byte(got[:len(got)-1]), &parsed); err != nil {
+ t.Fatalf("Write: stdin frame is not valid JSON: %v (raw=%q)", err, got)
+ }
+ if parsed["method"] != "tools/list" {
+ t.Fatalf("Write: method = %v, want tools/list", parsed["method"])
+ }
+}
+
+func TestBridgeTransport_ReadReceivesFromStdout(t *testing.T) {
+ b, stdoutWriter, _ := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ tr := newBridgeTransport(b)
+ conn, err := tr.Connect(context.Background())
+ if err != nil {
+ t.Fatalf("Connect: %v", err)
+ }
+ defer func() { _ = conn.Close() }()
+
+ go func() {
+ _, _ = stdoutWriter.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{}}` + "\n"))
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ msg, err := conn.Read(ctx)
+ if err != nil {
+ t.Fatalf("Read: %v", err)
+ }
+ resp, ok := msg.(*jsonrpc.Response)
+ if !ok {
+ t.Fatalf("Read: expected *jsonrpc.Response, got %T", msg)
+ }
+ wantID, _ := jsonrpc.MakeID(float64(1))
+ if resp.ID != wantID {
+ t.Fatalf("Read: id = %v, want 1", resp.ID)
+ }
+}
+
+func TestBridgeTransport_CloseUnsubscribes(t *testing.T) {
+ b, stdoutWriter, _ := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ tr := newBridgeTransport(b)
+ conn, err := tr.Connect(context.Background())
+ if err != nil {
+ t.Fatalf("Connect: %v", err)
+ }
+ if err := conn.Close(); err != nil {
+ t.Fatalf("Close: %v", err)
+ }
+ if err := conn.Close(); err != nil {
+ t.Fatalf("Close (second call): %v", err)
+ }
+}
diff --git a/cmd/sam-node/gate.go b/cmd/sam-node/gate.go
index ccb02be1..46408136 100644
--- a/cmd/sam-node/gate.go
+++ b/cmd/sam-node/gate.go
@@ -18,6 +18,7 @@ import (
"context"
"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"
@@ -103,6 +104,20 @@ func (n *SamNode) HandleMCPStream(s network.Stream) {
Description: "Get information about the mesh network",
}, n.handleGetMeshInfo)
+ // Register aggregated hosted-service tools from MCP services.
+ infos := n.services.List(api.ServiceType_SERVICE_TYPE_MCP)
+ for _, info := range infos {
+ svc, ok := n.services.Get(info.Name)
+ if !ok {
+ continue
+ }
+ mcpSvc, ok := svc.(*MCPService)
+ if !ok {
+ continue
+ }
+ mcpSvc.RegisterAggregatedTools(server)
+ }
+
ctx := context.Background()
if err := server.Run(ctx, transport); err != nil {
fmt.Printf("MCP server error on stream from %s: %v\n", s.Conn().RemotePeer(), err)
diff --git a/cmd/sam-node/gate_test.go b/cmd/sam-node/gate_test.go
index 59c353b9..1ae2425b 100644
--- a/cmd/sam-node/gate_test.go
+++ b/cmd/sam-node/gate_test.go
@@ -15,13 +15,18 @@
package main
import (
+ "context"
+ "net/http/httptest"
"testing"
"time"
+ "github.com/google/sam/api"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
+ "github.com/libp2p/go-libp2p/core/protocol"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
"go.etcd.io/bbolt"
)
@@ -92,3 +97,175 @@ func TestConnectionGater(t *testing.T) {
t.Errorf("expected InterceptSecured to deny peer3 (in store)")
}
}
+
+// startBareNode brings up a SamNode without hub/enrollment.
+func startBareNode(t *testing.T, ctx context.Context) (*SamNode, func()) {
+ t.Helper()
+ dir := t.TempDir()
+ store, err := NewStore(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ node, err := NewSamNode(ctx, priv, nil, nil, store, "test-mesh", "1s",
+ []string{"/ip4/127.0.0.1/tcp/0"}, false, &NodeConfigComplete{}, 24*time.Hour)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ cleanup := func() {
+ _ = node.Teardown()
+ _ = store.Close()
+ }
+ return node, cleanup
+}
+
+const testMCPProtocol = protocol.ID("/sam-test/mcp/1.0.0")
+
+func TestHandleMCPStream_RegistersAggregatedTools(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ tools := []*mcp.Tool{
+ {Name: "review_pr", Description: "Run a code review", InputSchema: map[string]any{"type": "object"}},
+ }
+ upstream := httptest.NewServer(newFakeMCPHandler(t, tools))
+ defer upstream.Close()
+
+ nodeA, cleanupA := startBareNode(t, ctx)
+ defer cleanupA()
+ nodeB, cleanupB := startBareNode(t, ctx)
+ defer cleanupB()
+
+ // Init a real MCPService so session + aggregatedTools are populated; insert
+ // directly to skip DHT advertisement.
+ svc := &MCPService{baseService: baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "code-reviewer"},
+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: upstream.URL},
+ }}
+ if err := svc.Init(ctx); err != nil {
+ t.Fatalf("MCPService.Init: %v", err)
+ }
+ nodeA.services.insertService(svc)
+ t.Cleanup(func() { _ = svc.Teardown() })
+
+ // Bypass biscuit auth by exposing HandleMCPStream on a test-only protocol.
+ nodeA.Host.SetStreamHandler(testMCPProtocol, nodeA.HandleMCPStream)
+
+ if err := nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()}); err != nil {
+ t.Fatalf("connect: %v", err)
+ }
+
+ s, err := nodeB.Host.NewStream(ctx, nodeA.Host.ID(), testMCPProtocol)
+ if err != nil {
+ t.Fatalf("NewStream: %v", err)
+ }
+ defer func() { _ = s.Close() }()
+
+ client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0.0.1"}, nil)
+ session, err := client.Connect(ctx, NewStreamTransport(s), nil)
+ if err != nil {
+ t.Fatalf("client.Connect: %v", err)
+ }
+ defer func() { _ = session.Close() }()
+
+ res, err := session.ListTools(ctx, nil)
+ if err != nil {
+ t.Fatalf("ListTools: %v", err)
+ }
+
+ var names []string
+ for _, tl := range res.Tools {
+ names = append(names, tl.Name)
+ }
+ found := false
+ for _, n := range names {
+ if n == "code-reviewer.review_pr" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Errorf("expected tools/list to include %q; got %v", "code-reviewer.review_pr", names)
+ }
+
+ // Sanity: at least one infra tool is still present.
+ infraFound := false
+ for _, n := range names {
+ if n == "send_message" {
+ infraFound = true
+ break
+ }
+ }
+ if !infraFound {
+ t.Errorf("expected infra tool send_message to be present; got %v", names)
+ }
+}
+
+func TestHandleMCPStream_ForwarderRoutesCalls(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ tools := []*mcp.Tool{
+ {Name: "echo", Description: "echo", InputSchema: map[string]any{"type": "object"}},
+ }
+ upstream := httptest.NewServer(newFakeMCPHandler(t, tools))
+ defer upstream.Close()
+
+ nodeA, cleanupA := startBareNode(t, ctx)
+ defer cleanupA()
+ nodeB, cleanupB := startBareNode(t, ctx)
+ defer cleanupB()
+
+ svc := &MCPService{baseService: baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "svc"},
+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: upstream.URL},
+ }}
+ if err := svc.Init(ctx); err != nil {
+ t.Fatalf("MCPService.Init: %v", err)
+ }
+ nodeA.services.insertService(svc)
+ t.Cleanup(func() { _ = svc.Teardown() })
+
+ nodeA.Host.SetStreamHandler(testMCPProtocol, nodeA.HandleMCPStream)
+
+ if err := nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()}); err != nil {
+ t.Fatalf("connect: %v", err)
+ }
+
+ s, err := nodeB.Host.NewStream(ctx, nodeA.Host.ID(), testMCPProtocol)
+ if err != nil {
+ t.Fatalf("NewStream: %v", err)
+ }
+ defer func() { _ = s.Close() }()
+
+ client := mcp.NewClient(&mcp.Implementation{Name: "tc", Version: "0.0.1"}, nil)
+ session, err := client.Connect(ctx, NewStreamTransport(s), nil)
+ if err != nil {
+ t.Fatalf("client.Connect: %v", err)
+ }
+ defer func() { _ = session.Close() }()
+
+ res, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: "svc.echo",
+ Arguments: map[string]any{"unused": true},
+ })
+ if err != nil {
+ t.Fatalf("CallTool: %v", err)
+ }
+ if len(res.Content) == 0 {
+ t.Fatal("expected non-empty Content")
+ }
+ tc, ok := res.Content[0].(*mcp.TextContent)
+ if !ok {
+ t.Fatalf("expected TextContent, got %T", res.Content[0])
+ }
+ // newFakeMCPHandler echoes "fake-result:<tool-name>" using the un-namespaced form.
+ if tc.Text != "fake-result:echo" {
+ t.Errorf("forwarder did not pass un-namespaced name; got %q", tc.Text)
+ }
+}
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
index 86441952..740b62a8 100644
--- a/cmd/sam-node/mcp.go
+++ b/cmd/sam-node/mcp.go
@@ -90,6 +90,12 @@ func NewMCPHandler(node *SamNode) http.Handler {
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",
+ Description: "Discover MCP tools available on hosted services across the mesh. Returns name + description per tool. Optionally narrow by peer_id, service_name, or intent (intent is reserved for future ranking and is accepted-but-ignored).",
+ }, node.handleFindRemoteTools)
+
// Create the SSE handler using the SDK
sseHandler := mcp.NewSSEHandler(func(request *http.Request) *mcp.Server {
return mcpServer
diff --git a/cmd/sam-node/mcp_handlers.go b/cmd/sam-node/mcp_handlers.go
index 6a8e60ee..a03a99bb 100644
--- a/cmd/sam-node/mcp_handlers.go
+++ b/cmd/sam-node/mcp_handlers.go
@@ -4,11 +4,16 @@ import (
"context"
"encoding/json"
"fmt"
+ "strings"
+ "sync"
+ "time"
"github.com/google/sam/api"
"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.
@@ -240,3 +245,202 @@ func (n *SamNode) handleConnectPeer(ctx context.Context, req *mcp.CallToolReques
},
}, nil, nil
}
+
+// FindRemoteToolsParams defines the parameters for the
+// find_remote_tools tool.
+type FindRemoteToolsParams struct {
+ Intent string `json:"intent,omitempty" jsonschema:"Natural-language description of what the caller is looking for. Reserved for future semantic ranking; currently accepted but ignored."`
+ PeerID string `json:"peer_id,omitempty" jsonschema:"Restrict the search to a single peer. Empty means search the whole mesh."`
+ ServiceName string `json:"service_name,omitempty" jsonschema:"Restrict results to tools whose name starts with this service prefix (e.g. 'code-reviewer'). Empty means no service filter."`
+}
+
+// remoteToolRow is one entry in the find_remote_tools response.
+type remoteToolRow struct {
+ PeerID string `json:"peer_id"`
+ ToolName string `json:"tool_name"`
+ Description string `json:"description"`
+}
+
+// handleFindRemoteTools implements the find_remote_tools tool.
+//
+// Scope:
+// - If params.PeerID is set, only that peer is queried.
+// - Otherwise the candidate list is obtained via DiscoverRemoteServices.
+//
+// Filtering:
+// - Tools without a "." in their name (infra tools) are excluded.
+// - If params.ServiceName is set, only tools whose name starts with
+// "<service_name>." are returned.
+// - params.Intent is accepted and logged at debug level, but does not
+// filter or rank results in this implementation (placeholder for
+// future semantic search).
+func (n *SamNode) handleFindRemoteTools(ctx context.Context, req *mcp.CallToolRequest, params FindRemoteToolsParams) (*mcp.CallToolResult, any, error) {
+ if params.Intent != "" {
+ logger.Debugf("[find_remote_tools] intent (ignored): %q", params.Intent)
+ }
+
+ selfID := n.Host.ID().String()
+ if params.PeerID != "" && params.PeerID == selfID {
+ return nil, nil, fmt.Errorf("peer_id %q is this node; cross-mesh discovery cannot target self", params.PeerID)
+ }
+
+ var rows []remoteToolRow
+
+ if params.PeerID != "" {
+ pid, err := peer.Decode(params.PeerID)
+ if err != nil {
+ return nil, nil, fmt.Errorf("invalid peer_id %q: %w", params.PeerID, err)
+ }
+ tools, err := n.fetchRemoteToolCatalogue(ctx, pid)
+ if err != nil {
+ return nil, nil, err
+ }
+ rows = appendFilteredRows(rows, params.PeerID, tools, params.ServiceName)
+ } else {
+ providers, err := n.DiscoverRemoteServices(ctx, api.ServiceType_SERVICE_TYPE_MCP, "")
+ if err != nil {
+ return nil, nil, fmt.Errorf("discover providers: %w", err)
+ }
+ seen := map[string]bool{}
+ var peerIDs []peer.ID
+ for _, p := range providers {
+ if p.PeerId == selfID || seen[p.PeerId] {
+ continue
+ }
+ seen[p.PeerId] = true
+ pid, err := peer.Decode(p.PeerId)
+ if err != nil {
+ continue
+ }
+ peerIDs = append(peerIDs, pid)
+ }
+
+ rows = n.fanOutFetch(ctx, peerIDs, params.ServiceName)
+ }
+
+ if rows == nil {
+ rows = []remoteToolRow{}
+ }
+ respData, err := json.Marshal(rows)
+ if err != nil {
+ return nil, nil, err
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: string(respData)}},
+ }, nil, nil
+}
+
+// fetchRemoteToolCatalogue opens a libp2p MCP stream to the target peer
+// (with the same auth handshake callMCPToolOnce uses), calls tools/list,
+// and returns the result.
+func (n *SamNode) fetchRemoteToolCatalogue(ctx context.Context, targetPeer peer.ID) ([]*mcp.Tool, error) {
+ s, err := n.Host.NewStream(ctx, targetPeer, api.MCPProtocolID)
+ if err != nil {
+ return nil, fmt.Errorf("open stream: %w", err)
+ }
+ defer func() {
+ _ = s.Close()
+ }()
+
+ biscuitBytes, err := n.Store.LoadIdentity()
+ if err != nil {
+ return nil, fmt.Errorf("load identity: %w", err)
+ }
+ authFrame := api.AuthFrame{Biscuit: biscuitBytes}
+ authBytes, _ := proto.Marshal(&authFrame)
+
+ writer := msgio.NewVarintWriter(s)
+ if err := writer.WriteMsg(authBytes); err != nil {
+ return nil, fmt.Errorf("write auth frame: %w", err)
+ }
+
+ // TODO: Consider increasing this to 1MB to allocate large MCP tool catalogues
+ reader := msgio.NewVarintReaderSize(s, 1024*64)
+ respMsg, err := reader.ReadMsg()
+ if err != nil {
+ return nil, fmt.Errorf("read auth response: %w", err)
+ }
+ defer reader.ReleaseMsg(respMsg)
+
+ var resp api.AuthResponse
+ if err := proto.Unmarshal(respMsg, &resp); err != nil {
+ return nil, fmt.Errorf("parse auth response: %w", err)
+ }
+ if !resp.Success {
+ return nil, fmt.Errorf("auth rejected by %s: %s", targetPeer, resp.Error)
+ }
+
+ transport := NewStreamTransport(s)
+ client := mcp.NewClient(&mcp.Implementation{Name: "sam-node-find", Version: "0.1.0"}, nil)
+ session, err := client.Connect(ctx, transport, nil)
+ if err != nil {
+ return nil, fmt.Errorf("mcp connect: %w", err)
+ }
+ defer func() { _ = session.Close() }()
+
+ listRes, err := session.ListTools(ctx, nil)
+ if err != nil {
+ return nil, fmt.Errorf("list tools: %w", err)
+ }
+ return listRes.Tools, nil
+}
+
+// appendFilteredRows appends rows for tools that have a namespaced name
+// (containing ".") and, if serviceName is non-empty, whose name starts
+// with "<serviceName>.".
+func appendFilteredRows(rows []remoteToolRow, peerID string, tools []*mcp.Tool, serviceName string) []remoteToolRow {
+ for _, tool := range tools {
+ if !strings.Contains(tool.Name, ".") {
+ continue
+ }
+ if serviceName != "" && !strings.HasPrefix(tool.Name, serviceName+".") {
+ continue
+ }
+ rows = append(rows, remoteToolRow{
+ PeerID: peerID,
+ ToolName: tool.Name,
+ Description: tool.Description,
+ })
+ }
+ return rows
+}
+
+// fanOutFetch queries each peer's tool catalogue concurrently with a
+// small cap and returns the filtered rows. Per-peer failures are
+// logged at debug level and skipped — best-effort mesh-wide fetch.
+func (n *SamNode) fanOutFetch(ctx context.Context, peers []peer.ID, serviceName string) []remoteToolRow {
+ const maxConcurrent = 8
+ sem := make(chan struct{}, maxConcurrent)
+
+ var (
+ mu sync.Mutex
+ rows []remoteToolRow
+ )
+
+ var wg sync.WaitGroup
+ for _, pid := range peers {
+ pid := pid
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+
+ peerCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+
+ tools, err := n.fetchRemoteToolCatalogue(peerCtx, pid)
+ if err != nil {
+ logger.Debugf("[find_remote_tools] peer %s skipped: %v", pid, err)
+ return
+ }
+
+ mu.Lock()
+ rows = appendFilteredRows(rows, pid.String(), tools, serviceName)
+ mu.Unlock()
+ }()
+ }
+ wg.Wait()
+
+ return rows
+}
diff --git a/cmd/sam-node/mcp_handlers_test.go b/cmd/sam-node/mcp_handlers_test.go
new file mode 100644
index 00000000..05b41f14
--- /dev/null
+++ b/cmd/sam-node/mcp_handlers_test.go
@@ -0,0 +1,464 @@
+// Copyright 2026 Google LLC
+package main
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/biscuit-auth/biscuit-go/v2"
+ "github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p/core/crypto"
+ "github.com/libp2p/go-libp2p/core/peer"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+// buildAndSaveBiscuit builds a biscuit signed with rootPriv that identifies
+// node as caller, grants allow_mcp_tool("*"), and saves it to node's store.
+func buildAndSaveBiscuit(node *SamNode, rootPriv ed25519.PrivateKey) error {
+ callerID := node.Host.ID().String()
+ builder := biscuit.NewBuilder(rootPriv)
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "node",
+ IDs: []biscuit.Term{biscuit.String(callerID)},
+ }}); err != nil {
+ return err
+ }
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "client_peer_id",
+ IDs: []biscuit.Term{biscuit.String(callerID)},
+ }}); err != nil {
+ return err
+ }
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactMCPTool,
+ IDs: []biscuit.Term{biscuit.String("*")},
+ }}); err != nil {
+ return err
+ }
+ bisc, err := builder.Build()
+ if err != nil {
+ return err
+ }
+ biscBytes, err := bisc.Serialize()
+ if err != nil {
+ return err
+ }
+ return node.Store.SaveIdentity(biscBytes)
+}
+
+func TestHandleFindRemoteTools_EmptyMesh_ReturnsEmptyArray(t *testing.T) {
+ ctx, cancel := contextWithShortTimeout()
+ defer cancel()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ res, _, err := node.handleFindRemoteTools(ctx, &mcp.CallToolRequest{}, FindRemoteToolsParams{})
+ if err != nil {
+ t.Fatalf("handleFindRemoteTools: %v", err)
+ }
+ if len(res.Content) == 0 {
+ t.Fatal("expected non-empty result content")
+ }
+ tc, ok := res.Content[0].(*mcp.TextContent)
+ if !ok {
+ t.Fatalf("expected TextContent, got %T", res.Content[0])
+ }
+ var rows []map[string]any
+ if err := json.Unmarshal([]byte(tc.Text), &rows); err != nil {
+ t.Fatalf("response not JSON array: %v (text: %q)", err, tc.Text)
+ }
+ if len(rows) != 0 {
+ t.Errorf("expected empty results for empty mesh, got %d rows", len(rows))
+ }
+}
+
+func TestHandleFindRemoteTools_SelfPeerRejected(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ _, _, err := node.handleFindRemoteTools(ctx, &mcp.CallToolRequest{}, FindRemoteToolsParams{
+ PeerID: node.Host.ID().String(),
+ })
+ if err == nil {
+ t.Fatal("expected error when peer_id equals self peer ID")
+ }
+}
+
+// contextWithShortTimeout returns a context with a small deadline so
+// that tests fail fast if a libp2p dial hangs.
+func contextWithShortTimeout() (context.Context, context.CancelFunc) {
+ return context.WithTimeout(context.Background(), 3*time.Second)
+}
+
+func TestHandleFindRemoteTools_SinglePeer(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ tools := []*mcp.Tool{
+ {Name: "review_pr", Description: "Run a code review", InputSchema: map[string]any{"type": "object"}},
+ {Name: "add_comment", Description: "Add a comment", InputSchema: map[string]any{"type": "object"}},
+ }
+ hostedSrv := httptest.NewServer(newFakeMCPHandler(t, tools))
+ defer hostedSrv.Close()
+
+ nodeA, cleanupA := startBareNode(t, ctx)
+ defer cleanupA()
+ nodeB, cleanupB := startBareNode(t, ctx)
+ defer cleanupB()
+
+ if err := nodeA.Host.Connect(ctx, peer.AddrInfo{ID: nodeB.Host.ID(), Addrs: nodeB.Host.Addrs()}); err != nil {
+ t.Fatalf("connect: %v", err)
+ }
+
+ rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("gen root key: %v", err)
+ }
+ if err := buildAndSaveBiscuit(nodeA, rootPriv); err != nil {
+ t.Fatalf("buildAndSaveBiscuit: %v", err)
+ }
+
+ // B trusts the same root key used to sign A's biscuit.
+ nodeB.keysMu.Lock()
+ nodeB.trustedKeys = append(nodeB.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
+ nodeB.keysMu.Unlock()
+
+ // Register an MCP service on B with two tools.
+ regReq := &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "code-reviewer"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: hostedSrv.URL},
+ }
+ if err := nodeB.RegisterService(ctx, regReq); err != nil {
+ t.Fatalf("RegisterService: %v", err)
+ }
+
+ res, _, err := nodeA.handleFindRemoteTools(ctx, &mcp.CallToolRequest{}, FindRemoteToolsParams{
+ PeerID: nodeB.Host.ID().String(),
+ })
+ if err != nil {
+ t.Fatalf("handleFindRemoteTools: %v", err)
+ }
+ tc, ok := res.Content[0].(*mcp.TextContent)
+ if !ok {
+ t.Fatalf("expected TextContent, got %T", res.Content[0])
+ }
+ var rows []remoteToolRow
+ if err := json.Unmarshal([]byte(tc.Text), &rows); err != nil {
+ t.Fatalf("unmarshal: %v (text: %q)", err, tc.Text)
+ }
+
+ wantNames := map[string]bool{
+ "code-reviewer.review_pr": false,
+ "code-reviewer.add_comment": false,
+ }
+ for _, row := range rows {
+ if row.PeerID != nodeB.Host.ID().String() {
+ t.Errorf("row has peer_id %q, want %q", row.PeerID, nodeB.Host.ID().String())
+ }
+ if _, ok := wantNames[row.ToolName]; ok {
+ wantNames[row.ToolName] = true
+ }
+ }
+ for name, found := range wantNames {
+ if !found {
+ t.Errorf("expected tool %q in response, not found; rows=%+v", name, rows)
+ }
+ }
+}
+
+func TestHandleFindRemoteTools_MeshWide(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ // B hosts "code-reviewer", C hosts "summarizer".
+ bTools := []*mcp.Tool{
+ {Name: "review_pr", Description: "review", InputSchema: map[string]any{"type": "object"}},
+ }
+ cTools := []*mcp.Tool{
+ {Name: "summarize", Description: "summarize", InputSchema: map[string]any{"type": "object"}},
+ }
+ bSrv := httptest.NewServer(newFakeMCPHandler(t, bTools))
+ defer bSrv.Close()
+ cSrv := httptest.NewServer(newFakeMCPHandler(t, cTools))
+ defer cSrv.Close()
+
+ nodeA, cleanupA := startBareNode(t, ctx)
+ defer cleanupA()
+ nodeB, cleanupB := startBareNode(t, ctx)
+ defer cleanupB()
+ nodeC, cleanupC := startBareNode(t, ctx)
+ defer cleanupC()
+
+ // Connect A to both B and C, and set up biscuit auth so A's stream
+ // to B/C passes WithBiscuitAuth.
+ rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("gen root: %v", err)
+ }
+ if err := buildAndSaveBiscuit(nodeA, rootPriv); err != nil {
+ t.Fatalf("buildAndSaveBiscuit: %v", err)
+ }
+ for _, target := range []*SamNode{nodeB, nodeC} {
+ if err := nodeA.Host.Connect(ctx, peer.AddrInfo{ID: target.Host.ID(), Addrs: target.Host.Addrs()}); err != nil {
+ t.Fatalf("connect to %s: %v", target.Host.ID(), err)
+ }
+ target.keysMu.Lock()
+ target.trustedKeys = append(target.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
+ target.keysMu.Unlock()
+ }
+
+ if err := nodeB.RegisterService(ctx, &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "code-reviewer"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: bSrv.URL},
+ }); err != nil {
+ t.Fatalf("RegisterService B: %v", err)
+ }
+ if err := nodeC.RegisterService(ctx, &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "summarizer"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: cSrv.URL},
+ }); err != nil {
+ t.Fatalf("RegisterService C: %v", err)
+ }
+
+ // Direct fan-out test: invoke fetchRemoteToolCatalogue for both peers,
+ // confirm both return their tools. This isolates the lower-level path
+ // from DHT convergence concerns.
+ rowsB, errB := nodeA.fetchRemoteToolCatalogue(ctx, nodeB.Host.ID())
+ if errB != nil {
+ t.Fatalf("fetch from B: %v", errB)
+ }
+ rowsC, errC := nodeA.fetchRemoteToolCatalogue(ctx, nodeC.Host.ID())
+ if errC != nil {
+ t.Fatalf("fetch from C: %v", errC)
+ }
+
+ gotNames := map[string]bool{}
+ for _, tool := range append(rowsB, rowsC...) {
+ gotNames[tool.Name] = true
+ }
+ if !gotNames["code-reviewer.review_pr"] {
+ t.Errorf("missing code-reviewer.review_pr; got %v", gotNames)
+ }
+ if !gotNames["summarizer.summarize"] {
+ t.Errorf("missing summarizer.summarize; got %v", gotNames)
+ }
+}
+
+func TestHandleFindRemoteTools_MeshWideViaHandler(t *testing.T) {
+ t.Skip("requires DHT convergence; isolated libp2p hosts cannot form a functional provider store. Covered by e2e tests.")
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ bSrv := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{
+ {Name: "review_pr", Description: "x", InputSchema: map[string]any{"type": "object"}},
+ }))
+ defer bSrv.Close()
+
+ nodeA, cleanupA := startBareNode(t, ctx)
+ defer cleanupA()
+ nodeB, cleanupB := startBareNode(t, ctx)
+ defer cleanupB()
+
+ rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := buildAndSaveBiscuit(nodeA, rootPriv); err != nil {
+ t.Fatalf("buildAndSaveBiscuit: %v", err)
+ }
+ if err := nodeA.Host.Connect(ctx, peer.AddrInfo{ID: nodeB.Host.ID(), Addrs: nodeB.Host.Addrs()}); err != nil {
+ t.Fatal(err)
+ }
+ nodeB.keysMu.Lock()
+ nodeB.trustedKeys = append(nodeB.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
+ nodeB.keysMu.Unlock()
+
+ if err := nodeB.RegisterService(ctx, &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "code-reviewer"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: bSrv.URL},
+ }); err != nil {
+ t.Fatalf("RegisterService: %v", err)
+ }
+
+ // Give the DHT a moment to record the provider.
+ time.Sleep(5 * time.Second)
+
+ res, _, err := nodeA.handleFindRemoteTools(ctx, &mcp.CallToolRequest{}, FindRemoteToolsParams{})
+ if err != nil {
+ t.Fatalf("handler: %v", err)
+ }
+ tc := res.Content[0].(*mcp.TextContent)
+ var rows []remoteToolRow
+ if err := json.Unmarshal([]byte(tc.Text), &rows); err != nil {
+ t.Fatal(err)
+ }
+
+ found := false
+ for _, r := range rows {
+ if r.ToolName == "code-reviewer.review_pr" && r.PeerID == nodeB.Host.ID().String() {
+ found = true
+ }
+ }
+ if !found {
+ t.Errorf("expected code-reviewer.review_pr from B; got rows=%+v", rows)
+ }
+}
+
+func TestAppendFilteredRows_ServiceNameFilter(t *testing.T) {
+ tools := []*mcp.Tool{
+ {Name: "code-reviewer.review_pr"},
+ {Name: "code-reviewer.add_comment"},
+ {Name: "summarizer.summarize"},
+ {Name: "send_message"}, // infra tool — no dot
+ }
+
+ rows := appendFilteredRows(nil, "peerB", tools, "code-reviewer")
+ if len(rows) != 2 {
+ t.Errorf("service filter: got %d rows, want 2; rows=%+v", len(rows), rows)
+ }
+ for _, r := range rows {
+ if !strings.HasPrefix(r.ToolName, "code-reviewer.") {
+ t.Errorf("row %+v doesn't match service prefix", r)
+ }
+ }
+}
+
+func TestAppendFilteredRows_AggregatedOnly(t *testing.T) {
+ tools := []*mcp.Tool{
+ {Name: "code-reviewer.review_pr"},
+ {Name: "send_message"},
+ {Name: "list_local_services"},
+ {Name: "get_mesh_info"},
+ }
+
+ rows := appendFilteredRows(nil, "peerB", tools, "")
+ if len(rows) != 1 {
+ t.Errorf("aggregated-only filter: got %d rows, want 1; rows=%+v", len(rows), rows)
+ }
+ if rows[0].ToolName != "code-reviewer.review_pr" {
+ t.Errorf("unexpected name %q", rows[0].ToolName)
+ }
+}
+
+func TestAppendFilteredRows_PartialPrefixMatch(t *testing.T) {
+ // "code" should NOT match "code-reviewer.review_pr" because the filter
+ // requires exact service-name + "." prefix.
+ tools := []*mcp.Tool{
+ {Name: "code-reviewer.review_pr"},
+ {Name: "code.something"},
+ }
+ rows := appendFilteredRows(nil, "peerB", tools, "code")
+ if len(rows) != 1 || rows[0].ToolName != "code.something" {
+ t.Errorf("expected exactly one row 'code.something'; got %+v", rows)
+ }
+}
+
+func TestHandleFindRemoteTools_PartialFailure(t *testing.T) {
+ if testing.Short() {
+ t.Skip("network/dial: skipped in -short")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ cSrv := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{
+ {Name: "summarize", Description: "x", InputSchema: map[string]any{"type": "object"}},
+ }))
+ defer cSrv.Close()
+
+ nodeA, cleanupA := startBareNode(t, ctx)
+ defer cleanupA()
+ nodeC, cleanupC := startBareNode(t, ctx)
+ defer cleanupC()
+
+ rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := buildAndSaveBiscuit(nodeA, rootPriv); err != nil {
+ t.Fatalf("buildAndSaveBiscuit: %v", err)
+ }
+
+ // A connects to C only; B is a fictional peer ID that won't resolve.
+ if err := nodeA.Host.Connect(ctx, peer.AddrInfo{ID: nodeC.Host.ID(), Addrs: nodeC.Host.Addrs()}); err != nil {
+ t.Fatal(err)
+ }
+ nodeC.keysMu.Lock()
+ nodeC.trustedKeys = append(nodeC.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
+ nodeC.keysMu.Unlock()
+
+ if err := nodeC.RegisterService(ctx, &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "summarizer"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: cSrv.URL},
+ }); err != nil {
+ t.Fatalf("RegisterService: %v", err)
+ }
+
+ // Generate a fictitious peer ID from a fresh keypair we never connect to.
+ _, fakePub, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fictitiousPID, err := peer.IDFromPublicKey(fakePub)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ rows := nodeA.fanOutFetch(ctx, []peer.ID{nodeC.Host.ID(), fictitiousPID}, "")
+
+ gotSummarizer := false
+ for _, r := range rows {
+ if r.ToolName == "summarizer.summarize" {
+ gotSummarizer = true
+ }
+ }
+ if !gotSummarizer {
+ t.Errorf("expected summarizer.summarize from C even with B unreachable; got %+v", rows)
+ }
+}
+
+func TestNewMCPHandler_RegistersFindRemoteTools(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ srv := httptest.NewServer(NewMCPHandler(node))
+ defer srv.Close()
+
+ client := mcp.NewClient(&mcp.Implementation{Name: "tc", Version: "0.0.1"}, nil)
+ transport := &mcp.SSEClientTransport{Endpoint: srv.URL + "/mcp/events"}
+ session, err := client.Connect(ctx, transport, nil)
+ if err != nil {
+ t.Fatalf("connect: %v", err)
+ }
+ defer func() { _ = session.Close() }()
+
+ res, err := session.ListTools(ctx, nil)
+ if err != nil {
+ t.Fatalf("list tools: %v", err)
+ }
+ found := false
+ for _, tl := range res.Tools {
+ if tl.Name == "find_remote_tools" {
+ found = true
+ }
+ }
+ if !found {
+ var names []string
+ for _, tl := range res.Tools {
+ names = append(names, tl.Name)
+ }
+ t.Errorf("find_remote_tools missing from sidecar tools/list; got %v", names)
+ }
+}
diff --git a/cmd/sam-node/mcp_service.go b/cmd/sam-node/mcp_service.go
new file mode 100644
index 00000000..dffc6c44
--- /dev/null
+++ b/cmd/sam-node/mcp_service.go
@@ -0,0 +1,133 @@
+// 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 (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/google/sam/api"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+// MCPService extends baseService with an MCP ClientSession used to aggregate
+// the backend's tools at Init time. Other parts of the codebase reach the
+// tool list via type assertion (svc.(*MCPService)).
+type MCPService struct {
+ baseService
+ session *mcp.ClientSession
+ aggregatedTools []*mcp.Tool
+}
+
+// Init builds the ingress handler via baseService.Init, then opens an MCP
+// session over the appropriate native transport (StreamableClient for URL,
+// bridgeTransport for stdio). ListTools is best-effort: failures are logged
+// and the service still registers.
+func (m *MCPService) Init(ctx context.Context) error {
+ if err := m.baseService.Init(ctx); err != nil {
+ return err
+ }
+ success := false
+ defer func() {
+ if !success {
+ _ = m.baseService.Teardown()
+ }
+ }()
+
+ var transport mcp.Transport
+ switch x := m.backend.(type) {
+ case *api.RegisterServiceRequest_TargetUrl:
+ // TODO: Consider routing URL-backed MCP ingress through the session
+ // (as the stdio path effectively does via the bridge) so we can
+ // decode/inspect MCP payloads and add per-tool-call observability
+ // or policy enforcement at this boundary.
+ transport = &mcp.StreamableClientTransport{Endpoint: x.TargetUrl}
+ case *api.RegisterServiceRequest_Command:
+ bridge, ok := m.handler.(*StdioBridge)
+ if !ok {
+ return fmt.Errorf("expected *StdioBridge handler for command-backed MCP service, got %T", m.handler)
+ }
+ transport = newBridgeTransport(bridge)
+ default:
+ return fmt.Errorf("unsupported backend type %T", m.backend)
+ }
+
+ client := mcp.NewClient(&mcp.Implementation{Name: "sam-node-aggregator", Version: "0.1.0"}, nil)
+ s, err := client.Connect(ctx, transport, nil)
+ if err != nil {
+ // Best-effort: backend may not speak MCP (e.g. a plain HTTP service,
+ // or `cat` used as a stdio echo). Ingress proxy still works.
+ logger.Warnf("[MCPService] %s: mcp connect failed, registering without tool aggregation: %v", m.info.Name, err)
+ success = true
+ return nil
+ }
+ m.session = s
+
+ res, err := s.ListTools(ctx, nil)
+ if err != nil {
+ logger.Warnf("[MCPService] %s: tools/list failed: %v", m.info.Name, err)
+ success = true
+ return nil
+ }
+ aggregated := make([]*mcp.Tool, 0, len(res.Tools))
+ for _, tool := range res.Tools {
+ namespaced := *tool
+ namespaced.Name = fmt.Sprintf("%s.%s", m.info.Name, tool.Name)
+ aggregated = append(aggregated, &namespaced)
+ }
+ m.aggregatedTools = aggregated
+
+ success = true
+ return nil
+}
+
+// Teardown closes the MCP session and chains to baseService.Teardown.
+func (m *MCPService) Teardown() error {
+ if m.session != nil {
+ _ = m.session.Close()
+ m.session = nil
+ }
+ m.aggregatedTools = nil
+ return m.baseService.Teardown()
+}
+
+// Tools returns the namespaced aggregated tool list.
+func (m *MCPService) Tools() []*mcp.Tool { return m.aggregatedTools }
+
+// RegisterAggregatedTools adds this service's aggregated tools to the given
+// MCP server. Each tool's invocation is forwarded to the underlying session
+// with the service-name prefix stripped. No-op if aggregation produced
+// nothing (e.g. ListTools failed at Init time).
+func (m *MCPService) RegisterAggregatedTools(server *mcp.Server) {
+ if m.session == nil {
+ return
+ }
+ sess := m.session
+ for _, tool := range m.aggregatedTools {
+ toolCopy := tool
+ parts := strings.SplitN(toolCopy.Name, ".", 2)
+ if len(parts) != 2 {
+ continue
+ }
+ originalName := parts[1]
+ server.AddTool(toolCopy, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return sess.CallTool(ctx, &mcp.CallToolParams{
+ Name: originalName,
+ Arguments: req.Params.Arguments,
+ })
+ })
+ }
+}
diff --git a/cmd/sam-node/mcp_service_test.go b/cmd/sam-node/mcp_service_test.go
new file mode 100644
index 00000000..f342d8de
--- /dev/null
+++ b/cmd/sam-node/mcp_service_test.go
@@ -0,0 +1,127 @@
+// 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 (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/google/sam/api"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+// newFakeMCPHandler returns an http.Handler serving a tiny MCP server over
+// streamable-http with the given tools registered.
+func newFakeMCPHandler(t *testing.T, tools []*mcp.Tool) http.Handler {
+ t.Helper()
+ srv := mcp.NewServer(&mcp.Implementation{Name: "fake", Version: "0.0.1"}, nil)
+ for _, tool := range tools {
+ toolCopy := tool
+ srv.AddTool(toolCopy, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: "fake-result:" + toolCopy.Name}},
+ }, nil
+ })
+ }
+ return mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, nil)
+}
+
+func TestMCPService_InitURL_AggregatesNamespacedTools(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ tools := []*mcp.Tool{
+ {Name: "review_pr", Description: "Run a code review", InputSchema: map[string]any{"type": "object"}},
+ {Name: "add_comment", Description: "Add a comment", InputSchema: map[string]any{"type": "object"}},
+ }
+ upstream := httptest.NewServer(newFakeMCPHandler(t, tools))
+ defer upstream.Close()
+
+ svc := &MCPService{baseService: baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "code-reviewer"},
+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: upstream.URL},
+ }}
+
+ if err := svc.Init(ctx); err != nil {
+ t.Fatalf("Init: %v", err)
+ }
+ defer func() { _ = svc.Teardown() }()
+
+ got := svc.Tools()
+ if len(got) != 2 {
+ t.Fatalf("Tools length: got %d, want 2", len(got))
+ }
+ names := map[string]bool{}
+ for _, tool := range got {
+ names[tool.Name] = true
+ }
+ for _, want := range []string{"code-reviewer.review_pr", "code-reviewer.add_comment"} {
+ if !names[want] {
+ t.Errorf("expected namespaced tool %q in %v", want, names)
+ }
+ }
+ if svc.handler == nil {
+ t.Errorf("Handler is nil after Init")
+ }
+}
+
+func TestMCPService_InitURL_InvalidURLRollsBack(t *testing.T) {
+ svc := &MCPService{baseService: baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "broken"},
+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "::not a url::"},
+ }}
+ if err := svc.Init(context.Background()); err == nil {
+ t.Fatal("Init: expected error for invalid URL, got nil")
+ }
+ if svc.cmd != nil {
+ t.Errorf("rollback failed: cmd should be nil, got %v", svc.cmd)
+ }
+ if svc.session != nil {
+ t.Errorf("rollback failed: session should be nil")
+ }
+}
+
+func TestMCPService_InitURL_ListToolsFailureBestEffort(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ // Handler that 500s on every request: Connect may succeed, ListTools won't.
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer upstream.Close()
+
+ svc := &MCPService{baseService: baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "broken"},
+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: upstream.URL},
+ }}
+ // Init may return nil (best-effort) OR an error from Connect. Both are acceptable.
+ // Only assert no panic and clean Teardown.
+ _ = svc.Init(ctx)
+ if err := svc.Teardown(); err != nil {
+ t.Errorf("Teardown: %v", err)
+ }
+}
+
+func TestMCPService_Teardown_NilSafe(t *testing.T) {
+ svc := &MCPService{baseService: baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "x"},
+ }}
+ if err := svc.Teardown(); err != nil {
+ t.Fatalf("Teardown on uninitialised MCPService: %v", err)
+ }
+}
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index c6bd52ac..28215d99 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -15,19 +15,14 @@
package main
import (
- "bufio"
"context"
"crypto/ed25519"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
- "io"
"net/http"
- "net/http/httputil"
- "net/url"
"os"
- "os/exec"
"strings"
"sync"
@@ -54,7 +49,6 @@ import (
"github.com/libp2p/go-libp2p/p2p/transport/tcp"
"github.com/libp2p/go-msgio"
"github.com/multiformats/go-multiaddr"
- "github.com/multiformats/go-multihash"
"google.golang.org/protobuf/proto"
)
@@ -76,12 +70,6 @@ type TrustedKey struct {
ReceivedAt time.Time
}
-type ServiceManifest struct {
- Info *api.ServiceInfo
- Handler http.Handler
- Cmd *exec.Cmd
-}
-
type SamNode struct {
Host host.Host
DHT *dht.IpfsDHT
@@ -98,8 +86,7 @@ type SamNode struct {
trustedKeys []TrustedKey
keysMu sync.RWMutex
rateLimiter *PeerRateLimiter
- services map[string]*ServiceManifest
- servicesMu sync.RWMutex
+ services *ServiceRegistry
BoundHTTPAddr string
}
@@ -116,7 +103,6 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.P
knownPeers: make(map[string]bool),
receivedMsgs: make(map[string][]string),
topics: make(map[string]*pubsub.Topic),
- services: make(map[string]*ServiceManifest),
LocalPolicy: nodeConfig,
}
@@ -191,6 +177,8 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.P
return nil, fmt.Errorf("failed to bootstrap DHT: %w", err)
}
+ node.services = NewServiceRegistry(node.DHT)
+
// Bootstrap: Connect and Auth to the Hub
for _, addr := range hubAddrs {
if err := node.ConnectAndAuthWithHub(ctx, addr); err != nil {
@@ -228,8 +216,6 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.P
// Start key pruning
node.startKeyPruning(ctx, keyGracePeriod)
- // Register static services from config
-
// Start Ingress HTTP Server
if err := node.StartIngressServer(ctx); err != nil {
return nil, fmt.Errorf("failed to start ingress server: %w", err)
@@ -263,36 +249,12 @@ dhtLoop:
var errs []error
for _, sCfg := range services {
- sType, err := parseServiceType(sCfg.Type)
+ req, err := buildRegisterRequest(sCfg)
if err != nil {
- logger.Errorf("[ServiceRegistry] Invalid service type %q for static service %s: %v", sCfg.Type, sCfg.Name, err)
- errs = append(errs, fmt.Errorf("invalid service type %q for static service %s: %w", sCfg.Type, sCfg.Name, err))
- continue
- }
-
- req := &api.RegisterServiceRequest{
- Service: &api.ServiceInfo{
- Type: sType,
- Name: sCfg.Name,
- Description: sCfg.Description,
- },
- }
-
- if sCfg.TargetURL != "" {
- req.Backend = &api.RegisterServiceRequest_TargetUrl{TargetUrl: sCfg.TargetURL}
- } else if len(sCfg.Command) > 0 {
- req.Backend = &api.RegisterServiceRequest_Command{
- Command: &api.CommandBackend{
- Command: sCfg.Command,
- Env: sCfg.Env,
- },
- }
- } else {
- logger.Errorf("[ServiceRegistry] Static service %s has no backend specified", sCfg.Name)
- errs = append(errs, fmt.Errorf("static service %s has no backend specified", sCfg.Name))
+ logger.Errorf("[ServiceRegistry] %v", err)
+ errs = append(errs, err)
continue
}
-
if err := n.RegisterService(ctx, req); err != nil {
logger.Errorf("[ServiceRegistry] Failed to register static service %s: %v", sCfg.Name, err)
errs = append(errs, fmt.Errorf("failed to register static service %s: %w", sCfg.Name, err))
@@ -742,255 +704,32 @@ func (n *SamNode) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscui
return nil, fmt.Errorf("no valid key found")
}
-func serviceTypeToString(t api.ServiceType) (string, error) {
- switch t {
- case api.ServiceType_SERVICE_TYPE_MCP:
- return "mcp", nil
- case api.ServiceType_SERVICE_TYPE_INFERENCE:
- return "inference", nil
- case api.ServiceType_SERVICE_TYPE_A2A:
- return "a2a", nil
- default:
- return "", fmt.Errorf("invalid or unspecified service type")
- }
-}
-
-func parseServiceType(s string) (api.ServiceType, error) {
- switch strings.ToLower(s) {
- case "mcp":
- return api.ServiceType_SERVICE_TYPE_MCP, nil
- case "inference":
- return api.ServiceType_SERVICE_TYPE_INFERENCE, nil
- case "a2a":
- return api.ServiceType_SERVICE_TYPE_A2A, nil
- default:
- return api.ServiceType_SERVICE_TYPE_UNSPECIFIED, fmt.Errorf("invalid service type: %s", s)
- }
-}
-
-// serviceKeyToCID hashes "sam:service[:part]..." into a DHT rendezvous CID.
-func serviceKeyToCID(parts ...string) (cid.Cid, error) {
- srvKey := strings.Join(append([]string{"sam:service"}, parts...), ":")
- hash, err := multihash.Sum([]byte(srvKey), multihash.SHA2_256, -1)
- if err != nil {
- return cid.Undef, err
- }
- return cid.NewCidV1(cid.Raw, hash), nil
-}
-
-func serviceNameToCID(serviceType api.ServiceType, serviceName string) (cid.Cid, error) {
- srvTypeStr, err := serviceTypeToString(serviceType)
- if err != nil {
- return cid.Undef, err
- }
- return serviceKeyToCID(srvTypeStr, serviceName)
-}
-
-func serviceTypeToCID(serviceType api.ServiceType) (cid.Cid, error) {
- srvTypeStr, err := serviceTypeToString(serviceType)
- if err != nil {
- return cid.Undef, err
- }
- return serviceKeyToCID(srvTypeStr)
-}
-
-type StdioBridge struct {
- cmd *exec.Cmd
- stdin io.WriteCloser
- stdout io.ReadCloser
- mu sync.Mutex
- clients map[chan string]bool
-}
-
-func (b *StdioBridge) Start() {
- b.clients = make(map[chan string]bool)
- go func() {
- scanner := bufio.NewScanner(b.stdout)
- for scanner.Scan() {
- line := scanner.Text()
- b.mu.Lock()
- for ch := range b.clients {
- select {
- case ch <- line:
- default:
- }
- }
- b.mu.Unlock()
- }
- }()
-}
-
-func (b *StdioBridge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- switch r.Method {
- case http.MethodGet:
- w.Header().Set("Content-Type", "text/event-stream")
- w.Header().Set("Cache-Control", "no-cache")
- w.Header().Set("Connection", "keep-alive")
-
- flusher, ok := w.(http.Flusher)
- if !ok {
- http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
- return
- }
-
- ch := make(chan string, 10)
- b.mu.Lock()
- b.clients[ch] = true
- b.mu.Unlock()
-
- // Flush headers immediately to establish the stream
- w.WriteHeader(http.StatusOK)
- flusher.Flush()
-
- defer func() {
- b.mu.Lock()
- delete(b.clients, ch)
- b.mu.Unlock()
- close(ch)
- }()
-
- ctx := r.Context()
- for {
- select {
- case <-ctx.Done():
- return
- case line := <-ch:
- if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil {
- logger.Errorf("Failed to write to SSE client: %v", err)
- return
- }
- flusher.Flush()
- }
- }
- case http.MethodPost:
- body, err := io.ReadAll(r.Body)
- if err != nil {
- http.Error(w, "Failed to read body", http.StatusInternalServerError)
- return
- }
- _ = r.Body.Close()
-
- b.mu.Lock()
- _, err = b.stdin.Write(append(body, '\n'))
- b.mu.Unlock()
-
- if err != nil {
- http.Error(w, "Failed to write to process stdin", http.StatusInternalServerError)
- return
- }
- w.WriteHeader(http.StatusOK)
- default:
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- }
-}
-
-func (n *SamNode) createStdioBridgeHandler(cmdBackend *api.CommandBackend) (http.Handler, *exec.Cmd, error) {
- cmd := exec.Command(cmdBackend.Command[0], cmdBackend.Command[1:]...)
- cmd.Env = os.Environ()
- for k, v := range cmdBackend.Env {
- cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
- }
-
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- return nil, nil, err
- }
- stdin, err := cmd.StdinPipe()
- if err != nil {
- return nil, nil, err
- }
-
- if err := cmd.Start(); err != nil {
- return nil, nil, err
- }
-
- bridge := &StdioBridge{
- cmd: cmd,
- stdin: stdin,
- stdout: stdout,
- }
- bridge.Start()
-
- return bridge, cmd, nil
-}
-
func (n *SamNode) RegisterService(ctx context.Context, req *api.RegisterServiceRequest) error {
- info := req.Service
- if info.Type == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {
- return fmt.Errorf("cannot register service with unspecified type")
- }
- srvNameCID, err := serviceNameToCID(info.Type, info.Name)
- if err != nil {
- return err
- }
- srvTypeCID, err := serviceTypeToCID(info.Type)
+ svc, err := NewServiceFromRequest(req)
if err != nil {
return err
}
-
- if n.DHT == nil {
- return fmt.Errorf("DHT not initialized")
- }
-
- if err := n.DHT.Provide(ctx, srvNameCID, true); err != nil {
- return fmt.Errorf("failed to provide service to DHT: %w", err)
- }
- // Per-type rendezvous record so type-only discovery finds this peer.
- if err := n.DHT.Provide(ctx, srvTypeCID, true); err != nil {
- return fmt.Errorf("failed to provide service type to DHT: %w", err)
- }
-
- var handler http.Handler
- var cmd *exec.Cmd
-
- switch b := req.Backend.(type) {
- case *api.RegisterServiceRequest_TargetUrl:
- targetURL, err := url.Parse(b.TargetUrl)
- if err != nil {
- return fmt.Errorf("invalid target URL: %w", err)
- }
- handler = httputil.NewSingleHostReverseProxy(targetURL)
- case *api.RegisterServiceRequest_Command:
- handler, cmd, err = n.createStdioBridgeHandler(b.Command)
- if err != nil {
- return fmt.Errorf("failed to create stdio bridge: %w", err)
- }
- default:
- return fmt.Errorf("unsupported backend type")
- }
-
- n.servicesMu.Lock()
- n.services[info.Name] = &ServiceManifest{
- Info: info,
- Handler: handler,
- Cmd: cmd,
- }
- n.servicesMu.Unlock()
-
- logger.Infof("[ServiceRegistry] Registering service %s/%s (name CID: %s, type CID: %s)", info.Type, info.Name, srvNameCID, srvTypeCID)
- return nil
+ return n.services.Register(ctx, svc)
}
func (n *SamNode) UnregisterService(ctx context.Context, serviceName string) error {
- n.servicesMu.Lock()
- manifest, ok := n.services[serviceName]
- if ok && manifest.Cmd != nil {
- if err := manifest.Cmd.Process.Kill(); err != nil {
- logger.Errorf("Failed to kill process for service %s: %v", serviceName, err)
- }
- }
- delete(n.services, serviceName)
- n.servicesMu.Unlock()
+ return n.services.Unregister(ctx, serviceName)
+}
- logger.Infof("[ServiceRegistry] Unregistered service %s", serviceName)
- // We can't easily remove provider records from DHT, but we stop providing it.
+// Teardown detaches all registered services and closes the libp2p host.
+// Store is owned by the caller and is not closed here.
+func (n *SamNode) Teardown() error {
+ if n.services != nil {
+ n.services.TeardownAll()
+ }
+ if n.Host != nil {
+ return n.Host.Close()
+ }
return nil
}
func (n *SamNode) IsServiceRegistered(serviceName string) bool {
- n.servicesMu.RLock()
- defer n.servicesMu.RUnlock()
- _, ok := n.services[serviceName]
+ _, ok := n.services.Get(serviceName)
return ok
}
@@ -1134,17 +873,7 @@ func (n *SamNode) discoverServicesByType(ctx context.Context, serviceType api.Se
// ListLocalServices returns services registered on this node. If
// typeFilter is SERVICE_TYPE_UNSPECIFIED, all services are returned.
func (n *SamNode) ListLocalServices(typeFilter api.ServiceType) []*api.ServiceInfo {
- n.servicesMu.RLock()
- defer n.servicesMu.RUnlock()
-
- services := []*api.ServiceInfo{}
- for _, manifest := range n.services {
- if typeFilter != api.ServiceType_SERVICE_TYPE_UNSPECIFIED && manifest.Info.Type != typeFilter {
- continue
- }
- services = append(services, manifest.Info)
- }
- return services
+ return n.services.List(typeFilter)
}
func (n *SamNode) StartIngressServer(ctx context.Context) error {
@@ -1174,17 +903,14 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
return
}
- n.servicesMu.RLock()
- manifest, ok := n.services[serviceName]
- n.servicesMu.RUnlock()
-
- if !ok || manifest.Handler == nil {
+ svc, ok := n.services.Get(serviceName)
+ if !ok || svc.Handler() == nil {
http.Error(w, "Service not found", http.StatusNotFound)
return
}
r.URL.Path = "/" + upstreamPath
- manifest.Handler.ServeHTTP(w, r)
+ svc.Handler().ServeHTTP(w, r)
}),
}
@@ -1207,15 +933,3 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
return nil
}
-
-func (n *SamNode) RegisterServiceHandler(name string, handler http.Handler) {
- n.servicesMu.Lock()
- defer n.servicesMu.Unlock()
- if manifest, ok := n.services[name]; ok {
- manifest.Handler = handler
- } else {
- n.services[name] = &ServiceManifest{
- Handler: handler,
- }
- }
-}
diff --git a/cmd/sam-node/node_test.go b/cmd/sam-node/node_test.go
index 0d451ce2..b18b36ae 100644
--- a/cmd/sam-node/node_test.go
+++ b/cmd/sam-node/node_test.go
@@ -101,3 +101,4 @@ func TestHandleKeyRotationEvent(t *testing.T) {
t.Errorf("Expected 1 trusted key, got %d", len(node.trustedKeys))
}
}
+
diff --git a/cmd/sam-node/proxy_test.go b/cmd/sam-node/proxy_test.go
index 09084f7b..1eeaeed8 100644
--- a/cmd/sam-node/proxy_test.go
+++ b/cmd/sam-node/proxy_test.go
@@ -84,7 +84,9 @@ func TestDatapathIntegration(t *testing.T) {
expectedBody := `{"status":"success"}`
dummyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Header.Get("X-Test-Header") != expectedHeaderValue {
+ // Only assert the test header on the actual proxied request; MCP aggregation
+ // probes use other paths (/sse, /message) and don't carry it.
+ if r.URL.Path == "/api/v1/test" && r.Header.Get("X-Test-Header") != expectedHeaderValue {
t.Errorf("Expected header X-Test-Header to be %s, got %s", expectedHeaderValue, r.Header.Get("X-Test-Header"))
}
w.Header().Set("Content-Type", "application/json")
@@ -99,7 +101,7 @@ func TestDatapathIntegration(t *testing.T) {
Type: api.ServiceType_SERVICE_TYPE_MCP,
Name: serviceName,
}
-
+
// We register it in the DHT and also setup the local handler.
// We ignore the error because DHT Provide might fail if routing table is empty in this isolated test.
_ = nodeA.RegisterService(ctx, &api.RegisterServiceRequest{
@@ -110,12 +112,10 @@ func TestDatapathIntegration(t *testing.T) {
// Manually add to services map to ensure it's registered for the test lookup
// because RegisterService might have failed due to DHT not being ready in this isolated test.
targetURL, _ := url.Parse(dummyServer.URL)
- nodeA.servicesMu.Lock()
- nodeA.services[serviceName] = &ServiceManifest{
- Info: serviceInfo,
- Handler: httputil.NewSingleHostReverseProxy(targetURL),
- }
- nodeA.servicesMu.Unlock()
+ nodeA.services.insertService(&testService{
+ info: serviceInfo,
+ handler: httputil.NewSingleHostReverseProxy(targetURL),
+ })
// Start the Sidecar server for Node B to get BoundHTTPAddr populated
// We don't need full sidecar for Node B in this test if we call createEgressProxy directly,
@@ -123,13 +123,13 @@ func TestDatapathIntegration(t *testing.T) {
nodeB.BoundHTTPAddr = "127.0.0.1:0" // Dummy
// 4. Execution: Node B makes a request via its local Egress Proxy
-
+
// We need to create the egress proxy for Node B.
// The user request says: "Implement a reverse proxy on the local `sam-node` HTTP server that intercepts requests to `/sam/`"
// In sidecar.go we have `createEgressProxy(node)`. We can use it here.
-
+
proxyHandler := createEgressProxy(nodeB)
-
+
// We start a test server for Node B's proxy to simulate the local agent calling it.
proxyServer := httptest.NewServer(proxyHandler)
defer proxyServer.Close()
@@ -145,16 +145,16 @@ func TestDatapathIntegration(t *testing.T) {
req.Header.Set("X-Test-Header", expectedHeaderValue)
client := &http.Client{}
-
+
pidStr := nodeA.Host.ID().String()
_, err = peer.Decode(pidStr)
if err != nil {
t.Fatalf("Failed to decode generated peer ID %s: %v", pidStr, err)
}
-
+
// Wait for DHT/routing to settle or just retry a few times if needed.
// Since we connected directly, it should work immediately if the protocol is registered.
-
+
var resp *http.Response
for i := 0; i < 3; i++ {
resp, err = client.Do(req)
@@ -248,19 +248,21 @@ func TestStdioDatapathIntegration(t *testing.T) {
// Manually add to services map to ensure it's registered for the test lookup
// and avoid double start by not calling RegisterService.
- handler, cmd, err := nodeA.createStdioBridgeHandler(req.Backend.(*api.RegisterServiceRequest_Command).Command)
+ handler, cmd, err := createStdioBridgeHandler(req.Backend.(*api.RegisterServiceRequest_Command).Command)
if err != nil {
t.Fatal(err)
}
- nodeA.servicesMu.Lock()
- nodeA.services[serviceName] = &ServiceManifest{
- Info: serviceInfo,
- Handler: handler,
- Cmd: cmd,
- }
- nodeA.servicesMu.Unlock()
+ nodeA.services.insertService(&testService{
+ info: serviceInfo,
+ handler: handler,
+ })
- defer func() { _ = nodeA.UnregisterService(ctx, serviceName) }()
+ defer func() {
+ _ = nodeA.UnregisterService(ctx, serviceName)
+ if cmd != nil && cmd.Process != nil {
+ _ = cmd.Process.Kill()
+ }
+ }()
// Start the Sidecar server for Node B to get BoundHTTPAddr populated
nodeB.BoundHTTPAddr = "127.0.0.1:0" // Dummy
diff --git a/cmd/sam-node/service.go b/cmd/sam-node/service.go
new file mode 100644
index 00000000..77d34e74
--- /dev/null
+++ b/cmd/sam-node/service.go
@@ -0,0 +1,196 @@
+// 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 (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "os/exec"
+ "strings"
+
+ "github.com/google/sam/api"
+ "github.com/ipfs/go-cid"
+ "github.com/multiformats/go-multihash"
+)
+
+// Service is the contract the ServiceRegistry and ingress server use.
+// Implementations own all type-specific behaviour; the registry stays
+// type-agnostic.
+type Service interface {
+ Info() *api.ServiceInfo
+ Init(ctx context.Context) error
+ Handler() http.Handler
+ Teardown() error
+}
+
+// baseService is the shared embeddable. Holds the fields and default
+// Init/Teardown behaviour every service kind needs. backend is typed as
+// any because the proto-generated oneof interface is unexported.
+type baseService struct {
+ info *api.ServiceInfo
+ backend any
+ handler http.Handler
+ cmd *exec.Cmd // nil for URL-backed
+}
+
+// newReverseProxyHandler builds a single-host reverse-proxy handler for a
+// URL backend. Same code path as today's URL branch in RegisterService.
+func newReverseProxyHandler(targetURL string) (http.Handler, error) {
+ u, err := url.Parse(targetURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid target URL: %w", err)
+ }
+ return httputil.NewSingleHostReverseProxy(u), nil
+}
+
+func (b *baseService) Info() *api.ServiceInfo { return b.info }
+func (b *baseService) Handler() http.Handler { return b.handler }
+
+// Init builds the ingress handler for the backend. URL -> reverse-proxy,
+// Command -> StdioBridge. MCPService extends this; it does not replace it.
+func (b *baseService) Init(ctx context.Context) error {
+ switch x := b.backend.(type) {
+ case *api.RegisterServiceRequest_TargetUrl:
+ h, err := newReverseProxyHandler(x.TargetUrl)
+ if err != nil {
+ return err
+ }
+ b.handler = h
+ case *api.RegisterServiceRequest_Command:
+ h, cmd, err := createStdioBridgeHandler(x.Command)
+ if err != nil {
+ return err
+ }
+ b.handler = h
+ b.cmd = cmd
+ default:
+ return fmt.Errorf("unsupported backend type %T", b.backend)
+ }
+ return nil
+}
+
+// Teardown kills the child process if any. Safe to call when cmd is nil
+// or already dead.
+func (b *baseService) Teardown() error {
+ if b.cmd == nil || b.cmd.Process == nil {
+ return nil
+ }
+ return b.cmd.Process.Kill()
+}
+
+// InferenceService and A2AService are zero-override embeddings. They exist
+// so the factory produces a distinct type per ServiceType, leaving room for
+// future per-kind behaviour without churn.
+type InferenceService struct{ baseService }
+type A2AService struct{ baseService }
+
+func NewServiceFromRequest(req *api.RegisterServiceRequest) (Service, error) {
+ info := req.Service
+ switch info.Type {
+ case api.ServiceType_SERVICE_TYPE_MCP:
+ return &MCPService{baseService: baseService{info: info, backend: req.Backend}}, nil
+ case api.ServiceType_SERVICE_TYPE_INFERENCE:
+ return &InferenceService{baseService: baseService{info: info, backend: req.Backend}}, nil
+ case api.ServiceType_SERVICE_TYPE_A2A:
+ return &A2AService{baseService: baseService{info: info, backend: req.Backend}}, nil
+ default:
+ return nil, fmt.Errorf("unspecified or unsupported service type: %v", info.Type)
+ }
+}
+
+// buildRegisterRequest converts a static-config service entry into the
+// RegisterServiceRequest the registry consumes.
+func buildRegisterRequest(sCfg api.ServiceConfig) (*api.RegisterServiceRequest, error) {
+ sType, err := parseServiceType(sCfg.Type)
+ if err != nil {
+ return nil, fmt.Errorf("invalid service type %q for service %s: %w", sCfg.Type, sCfg.Name, err)
+ }
+ req := &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{
+ Type: sType,
+ Name: sCfg.Name,
+ Description: sCfg.Description,
+ },
+ }
+ switch {
+ case sCfg.TargetURL != "":
+ req.Backend = &api.RegisterServiceRequest_TargetUrl{TargetUrl: sCfg.TargetURL}
+ case len(sCfg.Command) > 0:
+ req.Backend = &api.RegisterServiceRequest_Command{
+ Command: &api.CommandBackend{
+ Command: sCfg.Command,
+ Env: sCfg.Env,
+ },
+ }
+ default:
+ return nil, fmt.Errorf("service %s has no backend specified", sCfg.Name)
+ }
+ return req, nil
+}
+
+func serviceTypeToString(t api.ServiceType) (string, error) {
+ switch t {
+ case api.ServiceType_SERVICE_TYPE_MCP:
+ return "mcp", nil
+ case api.ServiceType_SERVICE_TYPE_INFERENCE:
+ return "inference", nil
+ case api.ServiceType_SERVICE_TYPE_A2A:
+ return "a2a", nil
+ default:
+ return "", fmt.Errorf("invalid or unspecified service type")
+ }
+}
+
+func parseServiceType(s string) (api.ServiceType, error) {
+ switch strings.ToLower(s) {
+ case "mcp":
+ return api.ServiceType_SERVICE_TYPE_MCP, nil
+ case "inference":
+ return api.ServiceType_SERVICE_TYPE_INFERENCE, nil
+ case "a2a":
+ return api.ServiceType_SERVICE_TYPE_A2A, nil
+ default:
+ return api.ServiceType_SERVICE_TYPE_UNSPECIFIED, fmt.Errorf("invalid service type: %s", s)
+ }
+}
+
+// serviceKeyToCID hashes "sam:service[:part]..." into a DHT rendezvous CID.
+func serviceKeyToCID(parts ...string) (cid.Cid, error) {
+ srvKey := strings.Join(append([]string{"sam:service"}, parts...), ":")
+ hash, err := multihash.Sum([]byte(srvKey), multihash.SHA2_256, -1)
+ if err != nil {
+ return cid.Undef, err
+ }
+ return cid.NewCidV1(cid.Raw, hash), nil
+}
+
+func serviceNameToCID(serviceType api.ServiceType, serviceName string) (cid.Cid, error) {
+ srvTypeStr, err := serviceTypeToString(serviceType)
+ if err != nil {
+ return cid.Undef, err
+ }
+ return serviceKeyToCID(srvTypeStr, serviceName)
+}
+
+func serviceTypeToCID(serviceType api.ServiceType) (cid.Cid, error) {
+ srvTypeStr, err := serviceTypeToString(serviceType)
+ if err != nil {
+ return cid.Undef, err
+ }
+ return serviceKeyToCID(srvTypeStr)
+}
diff --git a/cmd/sam-node/service_registry.go b/cmd/sam-node/service_registry.go
new file mode 100644
index 00000000..f0f67450
--- /dev/null
+++ b/cmd/sam-node/service_registry.go
@@ -0,0 +1,144 @@
+// 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 (
+ "context"
+ "fmt"
+ "sync"
+
+ "github.com/google/sam/api"
+ "github.com/ipfs/go-cid"
+)
+
+// dhtProvider is the narrow DHT surface ServiceRegistry depends on.
+// Production wires this to *dht.IpfsDHT; tests use a fake.
+type dhtProvider interface {
+ Provide(ctx context.Context, c cid.Cid, broadcast bool) error
+}
+
+// ServiceRegistry is the type-agnostic owner of registered services.
+type ServiceRegistry struct {
+ mu sync.RWMutex
+ services map[string]Service
+ dht dhtProvider
+}
+
+func NewServiceRegistry(d dhtProvider) *ServiceRegistry {
+ return &ServiceRegistry{
+ services: map[string]Service{},
+ dht: d,
+ }
+}
+
+// Register initialises a service, advertises it on the DHT, and inserts it
+// into the map. Init runs before Provide so a failed handler-build never
+// briefly advertises an unservable name.
+func (r *ServiceRegistry) Register(ctx context.Context, svc Service) error {
+ info := svc.Info()
+ if info.Type == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {
+ return fmt.Errorf("cannot register service with unspecified type")
+ }
+
+ if err := svc.Init(ctx); err != nil {
+ return fmt.Errorf("init %s: %w", info.Name, err)
+ }
+
+ srvNameCID, err := serviceNameToCID(info.Type, info.Name)
+ if err != nil {
+ return err
+ }
+ srvTypeCID, err := serviceTypeToCID(info.Type)
+ if err != nil {
+ return err
+ }
+
+ if err := r.dht.Provide(ctx, srvNameCID, true); err != nil {
+ logger.Warnf("[ServiceRegistry] DHT Provide (name) for %s: %v", info.Name, err)
+ }
+ if err := r.dht.Provide(ctx, srvTypeCID, true); err != nil {
+ logger.Warnf("[ServiceRegistry] DHT Provide (type) for %s: %v", info.Name, err)
+ }
+
+ r.mu.Lock()
+ r.services[info.Name] = svc
+ r.mu.Unlock()
+
+ logger.Infof("[ServiceRegistry] Registered %s/%s (name CID: %s, type CID: %s)", info.Type, info.Name, srvNameCID, srvTypeCID)
+ return nil
+}
+
+// Unregister removes the service from the map and calls Teardown.
+// Unknown names are a no-op.
+func (r *ServiceRegistry) Unregister(ctx context.Context, name string) error {
+ r.mu.Lock()
+ svc, ok := r.services[name]
+ delete(r.services, name)
+ r.mu.Unlock()
+ if !ok {
+ return nil
+ }
+ if err := svc.Teardown(); err != nil {
+ logger.Errorf("[ServiceRegistry] Teardown %s: %v", name, err)
+ }
+ logger.Infof("[ServiceRegistry] Unregistered %s", name)
+ return nil
+}
+
+// Get returns the service registered under name, if any.
+func (r *ServiceRegistry) Get(name string) (Service, bool) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ svc, ok := r.services[name]
+ return svc, ok
+}
+
+// List returns the ServiceInfo for every registered service, optionally
+// filtered by type. SERVICE_TYPE_UNSPECIFIED means "all types."
+func (r *ServiceRegistry) List(typeFilter api.ServiceType) []*api.ServiceInfo {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ out := []*api.ServiceInfo{}
+ for _, svc := range r.services {
+ info := svc.Info()
+ if typeFilter != api.ServiceType_SERVICE_TYPE_UNSPECIFIED && info.Type != typeFilter {
+ continue
+ }
+ out = append(out, info)
+ }
+ return out
+}
+
+// insertService inserts a service into the registry without calling Init or
+// advertising on the DHT. For tests only.
+func (r *ServiceRegistry) insertService(svc Service) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.services[svc.Info().Name] = svc
+}
+
+// TeardownAll calls Teardown on every registered service and clears the
+// map. Per-service errors are logged; iteration continues.
+func (r *ServiceRegistry) TeardownAll() {
+ r.mu.Lock()
+ svcs := r.services
+ r.services = map[string]Service{}
+ r.mu.Unlock()
+ for name, svc := range svcs {
+ if err := svc.Teardown(); err != nil {
+ logger.Errorf("[ServiceRegistry] Teardown %s: %v", name, err)
+ }
+ }
+}
diff --git a/cmd/sam-node/service_registry_test.go b/cmd/sam-node/service_registry_test.go
new file mode 100644
index 00000000..a6462553
--- /dev/null
+++ b/cmd/sam-node/service_registry_test.go
@@ -0,0 +1,163 @@
+// 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 (
+ "context"
+ "errors"
+ "net/http"
+ "sync/atomic"
+ "testing"
+
+ "github.com/google/sam/api"
+ "github.com/ipfs/go-cid"
+)
+
+type fakeDHT struct {
+ calls []cid.Cid
+ failNth int
+ count int32
+}
+
+func (f *fakeDHT) Provide(ctx context.Context, c cid.Cid, _ bool) error {
+ n := atomic.AddInt32(&f.count, 1)
+ f.calls = append(f.calls, c)
+ if f.failNth > 0 && int(n) == f.failNth {
+ return errors.New("fake dht failure")
+ }
+ return nil
+}
+
+type fakeService struct {
+ info *api.ServiceInfo
+ initCalls int
+ teardownCalls int
+ initErr error
+ handler http.Handler
+}
+
+func (f *fakeService) Info() *api.ServiceInfo { return f.info }
+func (f *fakeService) Init(ctx context.Context) error {
+ f.initCalls++
+ return f.initErr
+}
+func (f *fakeService) Handler() http.Handler { return f.handler }
+func (f *fakeService) Teardown() error {
+ f.teardownCalls++
+ return nil
+}
+
+func newFakeSvc(name string, st api.ServiceType) *fakeService {
+ return &fakeService{
+ info: &api.ServiceInfo{Name: name, Type: st},
+ handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {}),
+ }
+}
+
+// newServiceRegistryForTest builds a registry against the fake DHT for tests.
+func newServiceRegistryForTest(d dhtProvider) *ServiceRegistry {
+ return &ServiceRegistry{
+ services: map[string]Service{},
+ dht: d,
+ }
+}
+
+func TestServiceRegistry_RegisterCallsInitThenProvide(t *testing.T) {
+ dht := &fakeDHT{}
+ r := newServiceRegistryForTest(dht)
+
+ svc := newFakeSvc("demo", api.ServiceType_SERVICE_TYPE_MCP)
+ if err := r.Register(context.Background(), svc); err != nil {
+ t.Fatalf("Register: %v", err)
+ }
+ if svc.initCalls != 1 {
+ t.Errorf("Init called %d times, want 1", svc.initCalls)
+ }
+ if len(dht.calls) != 2 {
+ t.Fatalf("Provide called %d times, want 2 (name + type CID)", len(dht.calls))
+ }
+}
+
+func TestServiceRegistry_InitErrorBlocksProvideAndInsertion(t *testing.T) {
+ dht := &fakeDHT{}
+ r := newServiceRegistryForTest(dht)
+
+ svc := newFakeSvc("demo", api.ServiceType_SERVICE_TYPE_MCP)
+ svc.initErr = errors.New("init failed")
+ if err := r.Register(context.Background(), svc); err == nil {
+ t.Fatal("expected error from Register, got nil")
+ }
+ if len(dht.calls) != 0 {
+ t.Errorf("Provide called %d times after Init failure, want 0", len(dht.calls))
+ }
+ if _, ok := r.Get("demo"); ok {
+ t.Error("service should not be in map after Init failure")
+ }
+}
+
+func TestServiceRegistry_UnregisterRemovesAndCallsTeardown(t *testing.T) {
+ dht := &fakeDHT{}
+ r := newServiceRegistryForTest(dht)
+
+ svc := newFakeSvc("demo", api.ServiceType_SERVICE_TYPE_MCP)
+ _ = r.Register(context.Background(), svc)
+ if err := r.Unregister(context.Background(), "demo"); err != nil {
+ t.Fatalf("Unregister: %v", err)
+ }
+ if svc.teardownCalls != 1 {
+ t.Errorf("Teardown called %d times, want 1", svc.teardownCalls)
+ }
+ if _, ok := r.Get("demo"); ok {
+ t.Error("service still present after Unregister")
+ }
+}
+
+func TestServiceRegistry_UnregisterUnknownIsNoOp(t *testing.T) {
+ r := newServiceRegistryForTest(&fakeDHT{})
+ if err := r.Unregister(context.Background(), "missing"); err != nil {
+ t.Fatalf("Unregister missing: %v", err)
+ }
+}
+
+func TestServiceRegistry_ListFiltersByType(t *testing.T) {
+ r := newServiceRegistryForTest(&fakeDHT{})
+ _ = r.Register(context.Background(), newFakeSvc("a", api.ServiceType_SERVICE_TYPE_MCP))
+ _ = r.Register(context.Background(), newFakeSvc("b", api.ServiceType_SERVICE_TYPE_INFERENCE))
+
+ all := r.List(api.ServiceType_SERVICE_TYPE_UNSPECIFIED)
+ if len(all) != 2 {
+ t.Errorf("List(all): got %d, want 2", len(all))
+ }
+ mcpOnly := r.List(api.ServiceType_SERVICE_TYPE_MCP)
+ if len(mcpOnly) != 1 || mcpOnly[0].Name != "a" {
+ t.Errorf("List(MCP): got %v, want [a]", mcpOnly)
+ }
+}
+
+func TestServiceRegistry_TeardownAllContinuesOnError(t *testing.T) {
+ r := newServiceRegistryForTest(&fakeDHT{})
+ a := newFakeSvc("a", api.ServiceType_SERVICE_TYPE_MCP)
+ b := newFakeSvc("b", api.ServiceType_SERVICE_TYPE_MCP)
+ _ = r.Register(context.Background(), a)
+ _ = r.Register(context.Background(), b)
+
+ r.TeardownAll()
+
+ if a.teardownCalls != 1 || b.teardownCalls != 1 {
+ t.Errorf("teardown calls: a=%d b=%d, want both 1", a.teardownCalls, b.teardownCalls)
+ }
+ if len(r.List(api.ServiceType_SERVICE_TYPE_UNSPECIFIED)) != 0 {
+ t.Error("registry not empty after TeardownAll")
+ }
+}
diff --git a/cmd/sam-node/service_test.go b/cmd/sam-node/service_test.go
new file mode 100644
index 00000000..512ea021
--- /dev/null
+++ b/cmd/sam-node/service_test.go
@@ -0,0 +1,207 @@
+// 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 (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "testing"
+
+ "github.com/google/sam/api"
+)
+
+// testService is a minimal Service implementation for test setup. Tests use
+// this with ServiceRegistry.insertDirect to inject a pre-built handler
+// without going through Init or DHT advertisement.
+type testService struct {
+ info *api.ServiceInfo
+ handler http.Handler
+}
+
+func (t *testService) Info() *api.ServiceInfo { return t.info }
+func (t *testService) Init(_ context.Context) error { return nil }
+func (t *testService) Handler() http.Handler { return t.handler }
+func (t *testService) Teardown() error { return nil }
+
+func TestBaseService_InitURLBackend_BuildsReverseProxy(t *testing.T) {
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte("ok"))
+ }))
+ defer upstream.Close()
+
+ b := &baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_INFERENCE, Name: "demo"},
+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: upstream.URL},
+ }
+ if err := b.Init(context.Background()); err != nil {
+ t.Fatalf("Init: %v", err)
+ }
+ if _, ok := b.handler.(*httputil.ReverseProxy); !ok {
+ t.Fatalf("handler type: got %T, want *httputil.ReverseProxy", b.handler)
+ }
+ if b.cmd != nil {
+ t.Errorf("cmd should be nil for URL backend, got %v", b.cmd)
+ }
+ if err := b.Teardown(); err != nil {
+ t.Errorf("Teardown: %v", err)
+ }
+}
+
+func TestBaseService_InitURLBackend_InvalidURL(t *testing.T) {
+ b := &baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_INFERENCE, Name: "demo"},
+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "::not a url::"},
+ }
+ if err := b.Init(context.Background()); err == nil {
+ t.Fatal("Init: expected error for invalid URL, got nil")
+ }
+}
+
+func TestBaseService_InitCommandBackend_BuildsBridge(t *testing.T) {
+ b := &baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "demo"},
+ backend: &api.RegisterServiceRequest_Command{
+ Command: &api.CommandBackend{Command: []string{"/bin/cat"}},
+ },
+ }
+ if err := b.Init(context.Background()); err != nil {
+ t.Fatalf("Init: %v", err)
+ }
+ defer func() { _ = b.Teardown() }()
+ if _, ok := b.handler.(*StdioBridge); !ok {
+ t.Fatalf("handler type: got %T, want *StdioBridge", b.handler)
+ }
+ if b.cmd == nil {
+ t.Error("cmd should be non-nil for Command backend")
+ }
+}
+
+func TestBaseService_TeardownIsNilSafe(t *testing.T) {
+ b := &baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_INFERENCE, Name: "demo"},
+ }
+ if err := b.Teardown(); err != nil {
+ t.Fatalf("Teardown on uninitialised base: %v", err)
+ }
+}
+
+func TestNewServiceFromRequest_ReturnsMCPService(t *testing.T) {
+ req := &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "x"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://example.com"},
+ }
+ svc, err := NewServiceFromRequest(req)
+ if err != nil {
+ t.Fatalf("NewServiceFromRequest: %v", err)
+ }
+ if _, ok := svc.(*MCPService); !ok {
+ t.Fatalf("got %T, want *MCPService", svc)
+ }
+}
+
+func TestNewServiceFromRequest_ReturnsInferenceService(t *testing.T) {
+ req := &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_INFERENCE, Name: "x"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://example.com"},
+ }
+ svc, err := NewServiceFromRequest(req)
+ if err != nil {
+ t.Fatalf("NewServiceFromRequest: %v", err)
+ }
+ if _, ok := svc.(*InferenceService); !ok {
+ t.Fatalf("got %T, want *InferenceService", svc)
+ }
+}
+
+func TestNewServiceFromRequest_ReturnsA2AService(t *testing.T) {
+ req := &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_A2A, Name: "x"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://example.com"},
+ }
+ svc, err := NewServiceFromRequest(req)
+ if err != nil {
+ t.Fatalf("NewServiceFromRequest: %v", err)
+ }
+ if _, ok := svc.(*A2AService); !ok {
+ t.Fatalf("got %T, want *A2AService", svc)
+ }
+}
+
+func TestNewServiceFromRequest_UnspecifiedTypeFails(t *testing.T) {
+ req := &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_UNSPECIFIED, Name: "x"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://example.com"},
+ }
+ if _, err := NewServiceFromRequest(req); err == nil {
+ t.Fatal("expected error for unspecified service type, got nil")
+ }
+}
+
+func TestBuildRegisterRequest_URL(t *testing.T) {
+ req, err := buildRegisterRequest(api.ServiceConfig{
+ Type: "mcp",
+ Name: "demo",
+ TargetURL: "http://localhost:9000",
+ })
+ if err != nil {
+ t.Fatalf("buildRegisterRequest: %v", err)
+ }
+ if req.Service.Type != api.ServiceType_SERVICE_TYPE_MCP {
+ t.Errorf("Type = %v, want MCP", req.Service.Type)
+ }
+ tb, ok := req.Backend.(*api.RegisterServiceRequest_TargetUrl)
+ if !ok {
+ t.Fatalf("backend type: got %T, want *RegisterServiceRequest_TargetUrl", req.Backend)
+ }
+ if tb.TargetUrl != "http://localhost:9000" {
+ t.Errorf("TargetUrl = %q, want http://localhost:9000", tb.TargetUrl)
+ }
+}
+
+func TestBuildRegisterRequest_Command(t *testing.T) {
+ req, err := buildRegisterRequest(api.ServiceConfig{
+ Type: "inference",
+ Name: "demo",
+ Command: []string{"/bin/echo", "hi"},
+ Env: map[string]string{"K": "V"},
+ })
+ if err != nil {
+ t.Fatalf("buildRegisterRequest: %v", err)
+ }
+ cb, ok := req.Backend.(*api.RegisterServiceRequest_Command)
+ if !ok {
+ t.Fatalf("backend type: got %T, want *RegisterServiceRequest_Command", req.Backend)
+ }
+ if got := cb.Command.Command; len(got) != 2 || got[0] != "/bin/echo" || got[1] != "hi" {
+ t.Errorf("Command = %v, want [/bin/echo hi]", got)
+ }
+ if cb.Command.Env["K"] != "V" {
+ t.Errorf("Env[K] = %q, want V", cb.Command.Env["K"])
+ }
+}
+
+func TestBuildRegisterRequest_MissingBackend(t *testing.T) {
+ if _, err := buildRegisterRequest(api.ServiceConfig{Type: "mcp", Name: "demo"}); err == nil {
+ t.Fatal("expected error for missing backend, got nil")
+ }
+}
+
+func TestBuildRegisterRequest_InvalidType(t *testing.T) {
+ if _, err := buildRegisterRequest(api.ServiceConfig{Type: "bogus", Name: "demo", TargetURL: "http://x"}); err == nil {
+ t.Fatal("expected error for invalid type, got nil")
+ }
+}
diff --git a/cmd/sam-node/sidecar_test.go b/cmd/sam-node/sidecar_test.go
index dfc82b19..ed1ce99a 100644
--- a/cmd/sam-node/sidecar_test.go
+++ b/cmd/sam-node/sidecar_test.go
@@ -27,7 +27,9 @@ import (
"github.com/google/sam/api"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
+ "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
"google.golang.org/protobuf/encoding/protojson"
)
@@ -145,13 +147,17 @@ func TestHandleRegisterService(t *testing.T) {
time.Sleep(100 * time.Millisecond)
node := &SamNode{
- services: make(map[string]*ServiceManifest),
+ services: NewServiceRegistry(d),
DHT: d,
}
+ // MCPService.Init() opens a live session to the URL; serve a fake MCP backend.
+ upstream := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{}))
+ defer upstream.Close()
+
reqBody := &api.RegisterServiceRequest{
Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "test-service", Description: "test desc"},
- Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://localhost:8080"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: upstream.URL},
}
body, err := protojson.Marshal(reqBody)
if err != nil {
@@ -170,13 +176,19 @@ func TestHandleRegisterService(t *testing.T) {
if !node.IsServiceRegistered("test-service") {
t.Errorf("expected service to be registered")
}
+
+ // Tear down so the live MCP session releases the upstream SSE stream;
+ // otherwise upstream.Close() blocks waiting for in-flight handlers.
+ if err := node.UnregisterService(context.Background(), "test-service"); err != nil {
+ t.Errorf("unregister: %v", err)
+ }
}
func TestHandleUnregisterService(t *testing.T) {
node := &SamNode{
- services: make(map[string]*ServiceManifest),
+ services: NewServiceRegistry(&fakeDHT{}),
}
- node.services["test-service"] = &ServiceManifest{Info: &api.ServiceInfo{Name: "test-service"}}
+ node.services.insertService(&testService{info: &api.ServiceInfo{Name: "test-service"}})
reqBody := &api.ServiceInfo{Name: "test-service"}
body, err := json.Marshal(reqBody)
@@ -211,9 +223,9 @@ func TestHandleDiscoverService(t *testing.T) {
defer func() { _ = d.Close() }()
node := &SamNode{
- services: make(map[string]*ServiceManifest),
- DHT: d,
- Host: h,
+ services: NewServiceRegistry(d),
+ DHT: d,
+ Host: h,
BoundHTTPAddr: "127.0.0.1:8080",
}
@@ -270,14 +282,14 @@ func TestHandleDiscoverService(t *testing.T) {
func TestListLocalServices(t *testing.T) {
node := &SamNode{
- services: make(map[string]*ServiceManifest),
+ services: NewServiceRegistry(&fakeDHT{}),
}
-
+
service1 := &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "service1"}
service2 := &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_INFERENCE, Name: "service2"}
-
- node.services["service1"] = &ServiceManifest{Info: service1}
- node.services["service2"] = &ServiceManifest{Info: service2}
+
+ node.services.insertService(&testService{info: service1})
+ node.services.insertService(&testService{info: service2})
services := node.ListLocalServices(api.ServiceType_SERVICE_TYPE_UNSPECIFIED)
@@ -288,14 +300,14 @@ func TestListLocalServices(t *testing.T) {
func TestListLocalServices_TypeFilter(t *testing.T) {
node := &SamNode{
- services: make(map[string]*ServiceManifest),
+ services: NewServiceRegistry(&fakeDHT{}),
}
mcpA := &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "mcp-a"}
mcpB := &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "mcp-b"}
inf := &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_INFERENCE, Name: "inf-a"}
- node.services["mcp-a"] = &ServiceManifest{Info: mcpA}
- node.services["mcp-b"] = &ServiceManifest{Info: mcpB}
- node.services["inf-a"] = &ServiceManifest{Info: inf}
+ node.services.insertService(&testService{info: mcpA})
+ node.services.insertService(&testService{info: mcpB})
+ node.services.insertService(&testService{info: inf})
cases := []struct {
name string
@@ -388,7 +400,7 @@ func TestServiceKeyToCID_Equivalence(t *testing.T) {
func TestHandleRegisterService_Validation(t *testing.T) {
node := &SamNode{
- services: make(map[string]*ServiceManifest),
+ services: NewServiceRegistry(&fakeDHT{}),
}
tests := []struct {
@@ -448,7 +460,7 @@ func TestHandleRegisterService_Validation(t *testing.T) {
func TestStartSidecarServer_TokenMandatory(t *testing.T) {
node := &SamNode{}
-
+
// Test case: No token, no TLS
err := startSidecarServer(node, "127.0.0.1:0", "", "", "", "")
if err == nil {
@@ -466,3 +478,117 @@ func TestStartSidecarServer_TokenMandatory(t *testing.T) {
}
}
}
+
+func TestRegisterService_PopulatesAggregatedTools(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ tools := []*mcp.Tool{
+ {Name: "do_thing", Description: "x", InputSchema: map[string]any{"type": "object"}},
+ }
+ handler := newFakeMCPHandler(t, tools)
+ hostedSrv := httptest.NewServer(handler)
+ defer hostedSrv.Close()
+
+ dir := t.TempDir()
+ store, err := NewStore(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = store.Close() }()
+
+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ node, err := NewSamNode(ctx, priv, nil, nil, store, "test-mesh", "1s",
+ []string{"/ip4/127.0.0.1/tcp/0"}, false, &NodeConfigComplete{}, 24*time.Hour)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = node.Teardown() }()
+
+ req := &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "svc"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: hostedSrv.URL},
+ }
+ _ = node.RegisterService(ctx, req) // DHT.Provide may fail in isolated test; aggregation is independent.
+
+ svc, ok := node.services.Get("svc")
+ if !ok {
+ t.Fatal("service was not stored in registry")
+ }
+ mcpSvc, ok := svc.(*MCPService)
+ if !ok {
+ t.Fatalf("expected *MCPService, got %T", svc)
+ }
+ aggregated := mcpSvc.Tools()
+ if len(aggregated) != 1 {
+ t.Fatalf("expected 1 aggregated tool, got %d", len(aggregated))
+ }
+ if got := aggregated[0].Name; got != "svc.do_thing" {
+ t.Errorf("aggregated tool name: got %q, want %q", got, "svc.do_thing")
+ }
+}
+
+func TestUnregisterService_DetachesAggregation(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ tools := []*mcp.Tool{
+ {Name: "do_thing", Description: "x", InputSchema: map[string]any{"type": "object"}},
+ }
+ handler := newFakeMCPHandler(t, tools)
+ hostedSrv := httptest.NewServer(handler)
+ defer hostedSrv.Close()
+
+ dir := t.TempDir()
+ store, err := NewStore(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = store.Close() }()
+
+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ node, err := NewSamNode(ctx, priv, nil, nil, store, "test-mesh", "1s",
+ []string{"/ip4/127.0.0.1/tcp/0"}, false, &NodeConfigComplete{}, 24*time.Hour)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = node.Teardown() }()
+
+ req := &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "svc"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: hostedSrv.URL},
+ }
+ _ = node.RegisterService(ctx, req)
+
+ svc, ok := node.services.Get("svc")
+ if !ok {
+ t.Fatal("expected service registered")
+ }
+ mcpSvc, ok := svc.(*MCPService)
+ if !ok {
+ t.Fatalf("expected *MCPService, got %T", svc)
+ }
+ if mcpSvc.session == nil {
+ t.Fatal("expected active MCP session before unregister")
+ }
+
+ if err := node.UnregisterService(ctx, "svc"); err != nil {
+ t.Fatalf("UnregisterService: %v", err)
+ }
+
+ if mcpSvc.session != nil {
+ t.Error("session should be nil after Unregister")
+ }
+ if mcpSvc.Tools() != nil {
+ t.Error("aggregatedTools should be nil after Unregister")
+ }
+ if _, stillThere := node.services.Get("svc"); stillThere {
+ t.Error("service should be removed from registry")
+ }
+}
diff --git a/cmd/sam-node/static_service_test.go b/cmd/sam-node/static_service_test.go
index e3cb0d71..2cff1a3d 100644
--- a/cmd/sam-node/static_service_test.go
+++ b/cmd/sam-node/static_service_test.go
@@ -15,6 +15,7 @@ import (
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/multiformats/go-multiaddr"
"google.golang.org/protobuf/proto"
)
@@ -104,13 +105,17 @@ func TestStaticServiceRegistrationRequiresConnection(t *testing.T) {
}
}()
+ // Stand up a real MCP upstream so MCPService.Init() can complete its handshake.
+ upstream := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{}))
+ defer upstream.Close()
+
// 5. Try to register static services BEFORE connecting to hub
services := []api.ServiceConfig{
{
Type: "mcp",
Name: "test-service",
Description: "Test Service",
- TargetURL: "http://localhost:8080",
+ TargetURL: upstream.URL,
},
}
@@ -138,6 +143,11 @@ func TestStaticServiceRegistrationRequiresConnection(t *testing.T) {
if err != nil {
t.Fatalf("Expected RegisterStaticServices to succeed after enrollment, but failed: %v", err)
}
+
+ // Tear down the live MCP session so upstream.Close() can return.
+ if err := node.UnregisterService(ctx, "test-service"); err != nil {
+ t.Errorf("unregister: %v", err)
+ }
}
func TestStaticServiceRegistrationCommandFailure(t *testing.T) {
@@ -193,7 +203,7 @@ func TestStaticServiceRegistrationCommandFailure(t *testing.T) {
if err == nil {
t.Fatal("Expected RegisterStaticServices to fail with non-existent command, but it succeeded")
}
- if !strings.Contains(err.Error(), "failed to create stdio bridge") {
- t.Fatalf("Expected error to contain 'failed to create stdio bridge', got: %v", err)
+ if !strings.Contains(err.Error(), "/non-existent/binary") {
+ t.Fatalf("Expected error to mention the missing binary, got: %v", err)
}
}
diff --git a/cmd/sam-node/stdio_bridge.go b/cmd/sam-node/stdio_bridge.go
new file mode 100644
index 00000000..f7fc49d2
--- /dev/null
+++ b/cmd/sam-node/stdio_bridge.go
@@ -0,0 +1,176 @@
+// 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 (
+ "bufio"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "os/exec"
+ "sync"
+
+ "github.com/google/sam/api"
+)
+
+type StdioBridge struct {
+ cmd *exec.Cmd
+ stdin io.WriteCloser
+ stdout io.ReadCloser
+ mu sync.Mutex
+ clients map[chan string]bool
+}
+
+func (b *StdioBridge) Start() {
+ b.clients = make(map[chan string]bool)
+ go func() {
+ scanner := bufio.NewScanner(b.stdout)
+ for scanner.Scan() {
+ line := scanner.Text()
+ b.mu.Lock()
+ for ch := range b.clients {
+ select {
+ case ch <- line:
+ default:
+ }
+ }
+ b.mu.Unlock()
+ }
+ }()
+}
+
+func (b *StdioBridge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("Connection", "keep-alive")
+
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
+ return
+ }
+
+ ch := make(chan string, 10)
+ b.mu.Lock()
+ b.clients[ch] = true
+ b.mu.Unlock()
+
+ // Flush headers immediately to establish the stream
+ w.WriteHeader(http.StatusOK)
+ flusher.Flush()
+
+ defer func() {
+ b.mu.Lock()
+ delete(b.clients, ch)
+ b.mu.Unlock()
+ close(ch)
+ }()
+
+ ctx := r.Context()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case line := <-ch:
+ if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil {
+ logger.Errorf("Failed to write to SSE client: %v", err)
+ return
+ }
+ flusher.Flush()
+ }
+ }
+ case http.MethodPost:
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, "Failed to read body", http.StatusInternalServerError)
+ return
+ }
+ _ = r.Body.Close()
+
+ b.mu.Lock()
+ _, err = b.stdin.Write(append(body, '\n'))
+ b.mu.Unlock()
+
+ if err != nil {
+ http.Error(w, "Failed to write to process stdin", http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ default:
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ }
+}
+
+// Subscribe registers a new subscriber channel for stdout lines and returns
+// it along with an idempotent unsubscribe function. Buffered (cap 10); drops
+// on slow consumers match the SSE behaviour in ServeHTTP.
+func (b *StdioBridge) Subscribe() (<-chan string, func()) {
+ ch := make(chan string, 10)
+ b.mu.Lock()
+ b.clients[ch] = true
+ b.mu.Unlock()
+
+ var once sync.Once
+ unsub := func() {
+ once.Do(func() {
+ b.mu.Lock()
+ delete(b.clients, ch)
+ b.mu.Unlock()
+ close(ch)
+ })
+ }
+ return ch, unsub
+}
+
+// Send writes data to the child's stdin, appending a newline.
+func (b *StdioBridge) Send(data []byte) error {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ _, err := b.stdin.Write(append(data, '\n'))
+ return err
+}
+
+func createStdioBridgeHandler(cmdBackend *api.CommandBackend) (http.Handler, *exec.Cmd, error) {
+ cmd := exec.Command(cmdBackend.Command[0], cmdBackend.Command[1:]...)
+ cmd.Env = os.Environ()
+ for k, v := range cmdBackend.Env {
+ cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
+ }
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return nil, nil, err
+ }
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ return nil, nil, err
+ }
+
+ if err := cmd.Start(); err != nil {
+ return nil, nil, err
+ }
+
+ bridge := &StdioBridge{
+ cmd: cmd,
+ stdin: stdin,
+ stdout: stdout,
+ }
+ bridge.Start()
+
+ return bridge, cmd, nil
+}
diff --git a/cmd/sam-node/stdio_bridge_test.go b/cmd/sam-node/stdio_bridge_test.go
new file mode 100644
index 00000000..6e125e01
--- /dev/null
+++ b/cmd/sam-node/stdio_bridge_test.go
@@ -0,0 +1,79 @@
+// 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
+package main
+
+import (
+ "bytes"
+ "io"
+ "testing"
+ "time"
+)
+
+// newPipeBridge returns a StdioBridge wired to two in-memory pipes so tests
+// can drive stdin/stdout without a real subprocess.
+func newPipeBridge() (*StdioBridge, *io.PipeWriter, *bytes.Buffer) {
+ stdoutReader, stdoutWriter := io.Pipe()
+ stdinBuf := &bytes.Buffer{}
+ b := &StdioBridge{
+ stdin: nopWriteCloser{stdinBuf},
+ stdout: stdoutReader,
+ }
+ b.Start()
+ return b, stdoutWriter, stdinBuf
+}
+
+type nopWriteCloser struct{ io.Writer }
+
+func (nopWriteCloser) Close() error { return nil }
+
+func TestStdioBridge_SubscribeReceivesLines(t *testing.T) {
+ b, stdoutWriter, _ := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ ch, unsub := b.Subscribe()
+ defer unsub()
+
+ go func() {
+ _, _ = stdoutWriter.Write([]byte("hello\nworld\n"))
+ }()
+
+ want := []string{"hello", "world"}
+ for _, w := range want {
+ select {
+ case got := <-ch:
+ if got != w {
+ t.Fatalf("Subscribe: got %q, want %q", got, w)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatalf("Subscribe: timed out waiting for %q", w)
+ }
+ }
+}
+
+func TestStdioBridge_UnsubscribeIsIdempotent(t *testing.T) {
+ b, stdoutWriter, _ := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ _, unsub := b.Subscribe()
+ unsub()
+ unsub() // must not panic
+}
+
+func TestStdioBridge_SendWritesToStdin(t *testing.T) {
+ b, stdoutWriter, stdinBuf := newPipeBridge()
+ defer func() { _ = stdoutWriter.Close() }()
+
+ if err := b.Send([]byte(`{"jsonrpc":"2.0","id":1}`)); err != nil {
+ t.Fatalf("Send returned error: %v", err)
+ }
+ got := stdinBuf.String()
+ want := `{"jsonrpc":"2.0","id":1}` + "\n"
+ if got != want {
+ t.Fatalf("Send: stdin got %q, want %q", got, want)
+ }
+}
diff --git a/tests/e2e/docker/calc-mcp/sam-node-config.yaml b/tests/e2e/docker/calc-mcp/sam-node-config.yaml
index 69faf1bc..fb4809ff 100644
--- a/tests/e2e/docker/calc-mcp/sam-node-config.yaml
+++ b/tests/e2e/docker/calc-mcp/sam-node-config.yaml
@@ -8,4 +8,4 @@ services:
- type: "mcp"
name: "calculator"
description: "Simple math operations"
- target_url: "http://calc-mcp:7777"
+ target_url: "http://calc-mcp:7777/mcp"
diff --git a/tests/e2e/find_remote_tools.bats b/tests/e2e/find_remote_tools.bats
new file mode 100644
index 00000000..a4f3e289
--- /dev/null
+++ b/tests/e2e/find_remote_tools.bats
@@ -0,0 +1,141 @@
+#!/usr/bin/env bats
+
+load "lib/container_mesh.bash"
+
+CALC_MCP_IMAGE="sam-calc-mcp:local"
+
+build_calc_mcp_image() {
+ if ! docker image inspect "${CALC_MCP_IMAGE}" >/dev/null 2>&1; then
+ docker build -t "${CALC_MCP_IMAGE}" \
+ -f tests/e2e/docker/calc-mcp/Dockerfile \
+ tests/e2e/docker/calc-mcp >/dev/null
+ fi
+}
+
+start_calc_mcp() {
+ local name="${MESH_PREFIX}-calc-mcp"
+ docker run -d \
+ --name "${name}" \
+ --network "${MESH_NETWORK}" \
+ --network-alias calc-mcp \
+ "${CALC_MCP_IMAGE}" >/dev/null
+ MESH_CONTAINERS+=("${name}")
+ mesh_wait_for_log "${name}" "Uvicorn running on" 20
+}
+
+setup() {
+ if ! mesh_require_docker; then
+ skip "docker not available or daemon not running"
+ fi
+ mesh_setup_env
+ build_calc_mcp_image
+}
+
+teardown() {
+ mesh_cleanup_env
+}
+
+@test "find_remote_tools surfaces aggregated tools from a remote peer" {
+ run mesh_start_mock_oidc
+ [[ "$status" -eq 0 ]]
+
+ mesh_start_hub
+
+ echo "[$(date +%T)] Starting Node 1"
+ run mesh_start_node 1 "--discovery-interval 100ms --log-level debug"
+ [[ "$status" -eq 0 ]]
+ mesh_wait_for_log "${MESH_PREFIX}-node-1" "SAM Node Online" 60
+ mesh_wait_for_mcp_ready 1 20
+
+ echo "[$(date +%T)] Starting calc-mcp backend"
+ start_calc_mcp
+
+ echo "[$(date +%T)] Starting Node 2 with calculator service"
+ run mesh_start_node 2 \
+ "--discovery-interval 100ms --log-level debug" \
+ "tests/e2e/docker/calc-mcp/sam-node-config.yaml"
+ [[ "$status" -eq 0 ]]
+ mesh_wait_for_log "${MESH_PREFIX}-node-2" "SAM Node Online" 20
+ mesh_wait_for_mcp_ready 2 20
+
+ local node2_peer_id
+ node2_peer_id=$(docker logs "${MESH_PREFIX}-node-2" 2>&1 | grep "PeerID:" | head -n 1 | awk '{print $2}' | tr -d '\r')
+
+ echo "[$(date +%T)] Connecting Node 1 to Node 2"
+ local node2_addr="/dns4/sam-node-2/tcp/5002/p2p/${node2_peer_id}"
+ run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://sam-node-1:8080/mcp/events" -tool "connect_peer" -args "{\"peer_addr\":\"${node2_addr}\"}"
+ [[ "$status" -eq 0 ]]
+ mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20
+
+ echo "[$(date +%T)] Calling find_remote_tools from Node 1, targeting Node 2"
+ run docker run --rm --network "${MESH_NETWORK}" \
+ "${MESH_RUNTIME_IMAGE}" mcp-client \
+ -url "http://sam-node-1:8080/mcp/events" \
+ -tool "find_remote_tools" \
+ -args "{\"peer_id\":\"${node2_peer_id}\"}"
+ echo "find_remote_tools output: $output"
+ [[ "$status" -eq 0 ]]
+
+ # mcp-client prints each text-content line; the catalog JSON is the last non-empty line.
+ local catalog
+ catalog=$(echo "$output" | tail -n 1)
+
+ local match_count
+ match_count=$(echo "$catalog" | jq --arg pid "${node2_peer_id}" '
+ [.[] | select(.peer_id == $pid
+ and (.tool_name | startswith("calculator.")))] | length
+ ')
+ echo "Matching calculator tool entries: ${match_count}"
+ [[ "${match_count}" -ge 1 ]]
+}
+
+@test "call_remote_tool invokes an aggregated hosted-service tool end to end" {
+ run mesh_start_mock_oidc
+ [[ "$status" -eq 0 ]]
+
+ mesh_start_hub
+
+ echo "[$(date +%T)] Starting Node 1"
+ run mesh_start_node 1 "--discovery-interval 100ms --log-level debug"
+ [[ "$status" -eq 0 ]]
+ mesh_wait_for_log "${MESH_PREFIX}-node-1" "SAM Node Online" 60
+ mesh_wait_for_mcp_ready 1 20
+
+ echo "[$(date +%T)] Starting calc-mcp backend"
+ start_calc_mcp
+
+ echo "[$(date +%T)] Starting Node 2 with calculator service"
+ run mesh_start_node 2 \
+ "--discovery-interval 100ms --log-level debug" \
+ "tests/e2e/docker/calc-mcp/sam-node-config.yaml"
+ [[ "$status" -eq 0 ]]
+ mesh_wait_for_log "${MESH_PREFIX}-node-2" "SAM Node Online" 20
+ mesh_wait_for_mcp_ready 2 20
+
+ local node2_peer_id
+ node2_peer_id=$(docker logs "${MESH_PREFIX}-node-2" 2>&1 | grep "PeerID:" | head -n 1 | awk '{print $2}' | tr -d '\r')
+
+ echo "[$(date +%T)] Connecting Node 1 to Node 2"
+ local node2_addr="/dns4/sam-node-2/tcp/5002/p2p/${node2_peer_id}"
+ run docker run --rm --network "${MESH_NETWORK}" \
+ "${MESH_RUNTIME_IMAGE}" mcp-client \
+ -url "http://sam-node-1:8080/mcp/events" \
+ -tool "connect_peer" \
+ -args "{\"peer_addr\":\"${node2_addr}\"}"
+ [[ "$status" -eq 0 ]]
+ mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20
+
+ echo "[$(date +%T)] Calling call_remote_tool for calculator.add"
+ local call_args
+ call_args="{\"peer_id\":\"${node2_peer_id}\",\"tool_name\":\"calculator.add\",\"arguments\":\"{\\\"a\\\":2,\\\"b\\\":3}\"}"
+ run docker run --rm --network "${MESH_NETWORK}" \
+ "${MESH_RUNTIME_IMAGE}" mcp-client \
+ -url "http://sam-node-1:8080/mcp/events" \
+ -tool "call_remote_tool" \
+ -args "${call_args}"
+ echo "call_remote_tool output: $output"
+ [[ "$status" -eq 0 ]]
+
+ # calc-mcp returns add(2,3)=5 as a TextContent string; "5" must appear in the response.
+ [[ "$output" == *"5"* ]]
+}