Skip to content

Agent Mesh

Add describe_remote_tool mcp tool

Tomas Tormof3ffbee26b85
diff --git a/cmd/sam-node/gate.go b/cmd/sam-node/gate.go
index 46408136..ff43b990 100644
--- a/cmd/sam-node/gate.go
+++ b/cmd/sam-node/gate.go
@@ -104,6 +104,12 @@ func (n *SamNode) HandleMCPStream(s network.Stream) {
Description: "Get information about the mesh network",
}, n.handleGetMeshInfo)
+ // Add the describe_local_tool tool.
+ mcp.AddTool(server, &mcp.Tool{
+ Name: "describe_local_tool",
+ Description: "Return the description, input schema, and output schema for a named aggregated tool on this node.",
+ }, n.handleDescribeLocalTool)
+
// Register aggregated hosted-service tools from MCP services.
infos := n.services.List(api.ServiceType_SERVICE_TYPE_MCP)
for _, info := range infos {
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
index 740b62a8..2337d370 100644
--- a/cmd/sam-node/mcp.go
+++ b/cmd/sam-node/mcp.go
@@ -96,6 +96,12 @@ func NewMCPHandler(node *SamNode) http.Handler {
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)
+ // Add the describe_remote_tool tool.
+ mcp.AddTool(mcpServer, &mcp.Tool{
+ Name: "describe_remote_tool",
+ Description: "Return the description, input schema, and output schema for a specific aggregated tool on a specific peer. peer_id and tool_name are both required; tool_name must be a namespaced '<service>.<tool>' name as returned by find_remote_tools.",
+ }, node.handleDescribeRemoteTool)
+
// 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 a03a99bb..d57434c9 100644
--- a/cmd/sam-node/mcp_handlers.go
+++ b/cmd/sam-node/mcp_handlers.go
@@ -444,3 +444,146 @@ func (n *SamNode) fanOutFetch(ctx context.Context, peers []peer.ID, serviceName
return rows
}
+
+// remoteToolDescription is the JSON payload describe_local_tool emits on the
+// peer side and describe_remote_tool re-emits on the caller side. The
+// caller-side handler fills PeerID; the peer-side handler leaves it empty.
+//
+// InputSchema and OutputSchema mirror mcp.Tool's typing (`any`): the SDK
+// surfaces them as map[string]any on the client side, and we re-marshal
+// them verbatim without imposing a typed-schema constraint.
+type remoteToolDescription struct {
+ PeerID string `json:"peer_id,omitempty"`
+ ToolName string `json:"tool_name"`
+ Description string `json:"description"`
+ InputSchema any `json:"input_schema,omitempty"`
+ OutputSchema any `json:"output_schema,omitempty"`
+}
+
+// DescribeLocalToolParams defines parameters for the describe_local_tool
+// peer-facing infra tool.
+type DescribeLocalToolParams struct {
+ ToolName string `json:"tool_name" jsonschema:"Namespaced tool name (e.g. 'code-reviewer.review_pr'). Required."`
+}
+
+// handleDescribeLocalTool implements the describe_local_tool peer-facing
+// infra tool. It scans MCP-typed services in the registry for an aggregated
+// tool whose namespaced Name matches params.ToolName and returns its
+// description + schemas as JSON in a TextContent.
+//
+// Errors: empty tool name → invalid argument; no match → "tool not found".
+// Both surface to the caller as MCP errors.
+func (n *SamNode) handleDescribeLocalTool(ctx context.Context, req *mcp.CallToolRequest, params DescribeLocalToolParams) (*mcp.CallToolResult, any, error) {
+ if params.ToolName == "" {
+ return nil, nil, fmt.Errorf("tool_name is required")
+ }
+ svcInfos := n.services.List(api.ServiceType_SERVICE_TYPE_MCP)
+ for _, info := range svcInfos {
+ svc, ok := n.services.Get(info.Name)
+ if !ok {
+ continue
+ }
+ mcpSvc, ok := svc.(*MCPService)
+ if !ok {
+ continue
+ }
+ for _, tool := range mcpSvc.Tools() {
+ if tool == nil || tool.Name != params.ToolName {
+ continue
+ }
+ payload := remoteToolDescription{
+ ToolName: tool.Name,
+ Description: tool.Description,
+ InputSchema: tool.InputSchema,
+ OutputSchema: tool.OutputSchema,
+ }
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return nil, nil, fmt.Errorf("marshal description: %w", err)
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: string(body)}},
+ }, nil, nil
+ }
+ }
+ return nil, nil, fmt.Errorf("tool not found: %s", params.ToolName)
+}
+
+// DescribeRemoteToolParams defines parameters for the describe_remote_tool
+// sidecar tool.
+type DescribeRemoteToolParams struct {
+ PeerID string `json:"peer_id" jsonschema:"Peer ID of the node hosting the tool. Required."`
+ ToolName string `json:"tool_name" jsonschema:"Namespaced tool name as returned by find_remote_tools (e.g. 'code-reviewer.review_pr'). Required."`
+}
+
+// handleDescribeRemoteTool implements the describe_remote_tool sidecar
+// tool: validate inputs, open a libp2p MCP stream to the peer, call its
+// describe_local_tool, decorate the response with peer_id, and return.
+//
+// Validation: peer_id and tool_name must both be set; peer_id cannot equal
+// this node's own peer ID; tool_name must contain "." (describe_remote_tool
+// is for namespaced aggregated tools only); peer_id must parse as a libp2p
+// peer.ID.
+func (n *SamNode) handleDescribeRemoteTool(ctx context.Context, req *mcp.CallToolRequest, params DescribeRemoteToolParams) (*mcp.CallToolResult, any, error) {
+ if params.PeerID == "" {
+ return nil, nil, fmt.Errorf("peer_id is required")
+ }
+ if params.ToolName == "" {
+ return nil, nil, fmt.Errorf("tool_name is required")
+ }
+ if !strings.Contains(params.ToolName, ".") {
+ return nil, nil, fmt.Errorf("tool_name %q must be namespaced (contain '.'); describe_remote_tool is for aggregated tools only", params.ToolName)
+ }
+ selfID := n.Host.ID().String()
+ if params.PeerID == selfID {
+ return nil, nil, fmt.Errorf("peer_id %q is this node; cross-mesh describe cannot target self", params.PeerID)
+ }
+ targetPeer, err := peer.Decode(params.PeerID)
+ if err != nil {
+ return nil, nil, fmt.Errorf("invalid peer_id %q: %w", params.PeerID, err)
+ }
+
+ res, err := n.CallMCPTool(ctx, targetPeer, "describe_local_tool", DescribeLocalToolParams{
+ ToolName: params.ToolName,
+ })
+ if err != nil {
+ return nil, nil, fmt.Errorf("describe_local_tool on %s: %w", targetPeer, err)
+ }
+ if res == nil {
+ return nil, nil, fmt.Errorf("nil response from %s", targetPeer)
+ }
+ // The Go SDK packs handler-returned errors into CallToolResult.IsError
+ // rather than propagating them as Go errors from session.CallTool. Check
+ // IsError before the empty-content guard so an errored response with no
+ // body still surfaces as a describe_local_tool error rather than an
+ // ambiguous "empty response".
+ if res.IsError {
+ errText := "(no detail)"
+ if len(res.Content) > 0 {
+ if tc, ok := res.Content[0].(*mcp.TextContent); ok && tc.Text != "" {
+ errText = tc.Text
+ }
+ }
+ return nil, nil, fmt.Errorf("describe_local_tool on %s: %s", targetPeer, errText)
+ }
+ if len(res.Content) == 0 {
+ return nil, nil, fmt.Errorf("empty response from %s", targetPeer)
+ }
+ tc, ok := res.Content[0].(*mcp.TextContent)
+ if !ok {
+ return nil, nil, fmt.Errorf("unexpected content type from %s: %T", targetPeer, res.Content[0])
+ }
+ var remoteToolDesc remoteToolDescription
+ if err := json.Unmarshal([]byte(tc.Text), &remoteToolDesc); err != nil {
+ return nil, nil, fmt.Errorf("parse describe response from %s: %w", targetPeer, err)
+ }
+ remoteToolDesc.PeerID = params.PeerID
+
+ mRemoteToolDesc, err := json.Marshal(remoteToolDesc)
+ if err != nil {
+ return nil, nil, fmt.Errorf("marshal description: %w", err)
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: string(mRemoteToolDesc)}},
+ }, nil, nil
+}
diff --git a/cmd/sam-node/mcp_handlers_test.go b/cmd/sam-node/mcp_handlers_test.go
index 05b41f14..fd0dddfa 100644
--- a/cmd/sam-node/mcp_handlers_test.go
+++ b/cmd/sam-node/mcp_handlers_test.go
@@ -6,6 +6,7 @@ import (
"crypto/ed25519"
"crypto/rand"
"encoding/json"
+ "fmt"
"net/http/httptest"
"strings"
"testing"
@@ -462,3 +463,380 @@ func TestNewMCPHandler_RegistersFindRemoteTools(t *testing.T) {
t.Errorf("find_remote_tools missing from sidecar tools/list; got %v", names)
}
}
+
+func TestHandleDescribeLocalTool_HappyPath(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", "properties": map[string]any{"pr_url": map[string]any{"type": "string"}}, "required": []any{"pr_url"}},
+ OutputSchema: map[string]any{"type": "object", "properties": map[string]any{"summary": map[string]any{"type": "string"}}},
+ },
+ }
+ upstream := httptest.NewServer(newFakeMCPHandler(t, tools))
+ defer upstream.Close()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ 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)
+ }
+ node.services.insertService(svc)
+ t.Cleanup(func() { _ = svc.Teardown() })
+
+ res, _, err := node.handleDescribeLocalTool(ctx, &mcp.CallToolRequest{}, DescribeLocalToolParams{
+ ToolName: "code-reviewer.review_pr",
+ })
+ if err != nil {
+ t.Fatalf("handleDescribeLocalTool: %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])
+ }
+ var desc remoteToolDescription
+ if err := json.Unmarshal([]byte(tc.Text), &desc); err != nil {
+ t.Fatalf("response not JSON: %v (text: %q)", err, tc.Text)
+ }
+ if desc.ToolName != "code-reviewer.review_pr" {
+ t.Errorf("ToolName = %q, want %q", desc.ToolName, "code-reviewer.review_pr")
+ }
+ if desc.Description != "Run a code review" {
+ t.Errorf("Description = %q, want %q", desc.Description, "Run a code review")
+ }
+ if desc.InputSchema == nil {
+ t.Error("InputSchema is nil; expected the schema declared on the tool")
+ }
+ if desc.OutputSchema == nil {
+ t.Error("OutputSchema is nil; expected the schema declared on the tool")
+ }
+ if desc.PeerID != "" {
+ t.Errorf("PeerID should be empty on the peer-side payload, got %q", desc.PeerID)
+ }
+}
+
+func TestHandleDescribeLocalTool_NotFound(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ tools := []*mcp.Tool{
+ {Name: "review_pr", Description: "x", InputSchema: map[string]any{"type": "object"}},
+ }
+ upstream := httptest.NewServer(newFakeMCPHandler(t, tools))
+ defer upstream.Close()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ 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)
+ }
+ node.services.insertService(svc)
+ t.Cleanup(func() { _ = svc.Teardown() })
+
+ _, _, err := node.handleDescribeLocalTool(ctx, &mcp.CallToolRequest{}, DescribeLocalToolParams{
+ ToolName: "code-reviewer.does-not-exist",
+ })
+ if err == nil {
+ t.Fatal("expected error for unknown tool")
+ }
+ if !strings.Contains(err.Error(), "tool not found") {
+ t.Errorf("error %q does not mention 'tool not found'", err.Error())
+ }
+}
+
+func TestHandleDescribeLocalTool_EmptyToolName(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ _, _, err := node.handleDescribeLocalTool(ctx, &mcp.CallToolRequest{}, DescribeLocalToolParams{})
+ if err == nil {
+ t.Fatal("expected error for empty tool_name")
+ }
+}
+
+func TestHandleDescribeRemoteTool_EmptyPeerID(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ _, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
+ ToolName: "code-reviewer.review_pr",
+ })
+ if err == nil {
+ t.Fatal("expected error for empty peer_id")
+ }
+}
+
+func TestHandleDescribeRemoteTool_EmptyToolName(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ _, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
+ PeerID: "12D3KooWFakePeerID",
+ })
+ if err == nil {
+ t.Fatal("expected error for empty tool_name")
+ }
+}
+
+func TestHandleDescribeRemoteTool_NonNamespacedRejected(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ _, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
+ PeerID: "12D3KooWFakePeerID",
+ ToolName: "send_message", // no dot
+ })
+ if err == nil {
+ t.Fatal("expected error for tool_name without '.'")
+ }
+ if !strings.Contains(err.Error(), "namespaced") {
+ t.Errorf("error %q does not explain the namespacing requirement", err.Error())
+ }
+}
+
+func TestHandleDescribeRemoteTool_SelfPeerRejected(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ _, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
+ PeerID: node.Host.ID().String(),
+ ToolName: "code-reviewer.review_pr",
+ })
+ if err == nil {
+ t.Fatal("expected error when peer_id equals self peer ID")
+ }
+}
+
+func TestHandleDescribeRemoteTool_InvalidPeerID(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ node, cleanup := startBareNode(t, ctx)
+ defer cleanup()
+
+ _, _, err := node.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
+ PeerID: "not-a-valid-peer-id",
+ ToolName: "code-reviewer.review_pr",
+ })
+ if err == nil {
+ t.Fatal("expected error for malformed peer_id")
+ }
+}
+
+func TestHandleDescribeRemoteTool_RoundTrip(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ 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)
+ }
+ nodeB.keysMu.Lock()
+ nodeB.trustedKeys = append(nodeB.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
+ nodeB.keysMu.Unlock()
+
+ tools := []*mcp.Tool{
+ {
+ Name: "review_pr",
+ Description: "Run a code review",
+ InputSchema: map[string]any{
+ "type": "object",
+ "required": []any{"pr_url"},
+ "properties": map[string]any{
+ "pr_url": map[string]any{"type": "string"},
+ },
+ },
+ OutputSchema: map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "summary": map[string]any{"type": "string"},
+ },
+ },
+ },
+ }
+ hostedSrv := httptest.NewServer(newFakeMCPHandler(t, tools))
+ defer hostedSrv.Close()
+
+ 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)
+ }
+ defer func() { _ = nodeB.UnregisterService(ctx, "code-reviewer") }()
+
+ res, _, err := nodeA.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
+ PeerID: nodeB.Host.ID().String(),
+ ToolName: "code-reviewer.review_pr",
+ })
+ if err != nil {
+ t.Fatalf("handleDescribeRemoteTool: %v", err)
+ }
+ tc, ok := res.Content[0].(*mcp.TextContent)
+ if !ok {
+ t.Fatalf("expected TextContent, got %T", res.Content[0])
+ }
+
+ var desc remoteToolDescription
+ if err := json.Unmarshal([]byte(tc.Text), &desc); err != nil {
+ t.Fatalf("unmarshal: %v (text: %q)", err, tc.Text)
+ }
+ if desc.PeerID != nodeB.Host.ID().String() {
+ t.Errorf("PeerID = %q, want %q", desc.PeerID, nodeB.Host.ID().String())
+ }
+ if desc.ToolName != "code-reviewer.review_pr" {
+ t.Errorf("ToolName = %q, want %q", desc.ToolName, "code-reviewer.review_pr")
+ }
+ if desc.Description != "Run a code review" {
+ t.Errorf("Description = %q, want %q", desc.Description, "Run a code review")
+ }
+ inSchema, ok := desc.InputSchema.(map[string]any)
+ if !ok {
+ t.Fatalf("InputSchema type = %T, want map[string]any", desc.InputSchema)
+ }
+ if inSchema["type"] != "object" {
+ t.Errorf("InputSchema.type = %v, want 'object'", inSchema["type"])
+ }
+ outSchema, ok := desc.OutputSchema.(map[string]any)
+ if !ok {
+ t.Fatalf("OutputSchema type = %T, want map[string]any", desc.OutputSchema)
+ }
+ if outSchema["type"] != "object" {
+ t.Errorf("OutputSchema.type = %v, want 'object'", outSchema["type"])
+ }
+}
+
+func TestHandleDescribeRemoteTool_RoundTrip_UnknownTool(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ 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)
+ }
+ nodeB.keysMu.Lock()
+ nodeB.trustedKeys = append(nodeB.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})
+ nodeB.keysMu.Unlock()
+
+ tools := []*mcp.Tool{
+ {Name: "review_pr", Description: "x", InputSchema: map[string]any{"type": "object"}},
+ }
+ hostedSrv := httptest.NewServer(newFakeMCPHandler(t, tools))
+ defer hostedSrv.Close()
+ if err := nodeB.RegisterService(ctx, &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "code-reviewer"},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: hostedSrv.URL},
+ }); err != nil {
+ t.Fatalf("RegisterService: %v", err)
+ }
+ defer func() { _ = nodeB.UnregisterService(ctx, "code-reviewer") }()
+
+ _, _, err = nodeA.handleDescribeRemoteTool(ctx, &mcp.CallToolRequest{}, DescribeRemoteToolParams{
+ PeerID: nodeB.Host.ID().String(),
+ ToolName: "code-reviewer.does-not-exist",
+ })
+ if err == nil {
+ t.Fatal("expected error from peer when tool is not registered")
+ }
+ // Pin the exact wrapper format produced by handleDescribeRemoteTool's
+ // IsError branch. Matching the full prefix guarantees we exercised the
+ // IsError codepath, not a transport-level retry timeout or a JSON-parse
+ // fallback that happens to mention "tool not found".
+ wantPrefix := fmt.Sprintf("describe_local_tool on %s: tool not found:", nodeB.Host.ID())
+ if !strings.HasPrefix(err.Error(), wantPrefix) {
+ t.Errorf("error %q does not start with %q", err.Error(), wantPrefix)
+ }
+}
+
+func TestNewMCPHandler_RegistersDescribeRemoteTool(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 == "describe_remote_tool" {
+ found = true
+ }
+ }
+ if !found {
+ var names []string
+ for _, tl := range res.Tools {
+ names = append(names, tl.Name)
+ }
+ t.Errorf("describe_remote_tool missing from sidecar tools/list; got %v", names)
+ }
+}
diff --git a/tests/e2e/find_remote_tools.bats b/tests/e2e/find_remote_tools.bats
index a4f3e289..26017228 100644
--- a/tests/e2e/find_remote_tools.bats
+++ b/tests/e2e/find_remote_tools.bats
@@ -139,3 +139,121 @@ teardown() {
# calc-mcp returns add(2,3)=5 as a TextContent string; "5" must appear in the response.
[[ "$output" == *"5"* ]]
}
+
+@test "describe_remote_tool returns input schema for an aggregated tool" {
+ 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 describe_remote_tool for calculator.add"
+ local describe_args
+ describe_args="{\"peer_id\":\"${node2_peer_id}\",\"tool_name\":\"calculator.add\"}"
+ run docker run --rm --network "${MESH_NETWORK}" \
+ "${MESH_RUNTIME_IMAGE}" mcp-client \
+ -url "http://sam-node-1:8080/mcp/events" \
+ -tool "describe_remote_tool" \
+ -args "${describe_args}"
+ echo "describe_remote_tool output: $output"
+ [[ "$status" -eq 0 ]]
+
+ # mcp-client prints each TextContent line; the JSON payload is the last non-empty line.
+ local payload
+ payload=$(echo "$output" | tail -n 1)
+
+ # Assert peer_id, namespaced tool_name, and an input_schema with an object type.
+ local got_peer
+ got_peer=$(echo "$payload" | jq -r '.peer_id')
+ [[ "${got_peer}" == "${node2_peer_id}" ]]
+
+ local got_name
+ got_name=$(echo "$payload" | jq -r '.tool_name')
+ [[ "${got_name}" == "calculator.add" ]]
+
+ local got_input_type
+ got_input_type=$(echo "$payload" | jq -r '.input_schema.type')
+ [[ "${got_input_type}" == "object" ]]
+}
+
+@test "describe_remote_tool surfaces an error for an unknown tool" {
+ 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 describe_remote_tool for an unknown tool"
+ local describe_args
+ describe_args="{\"peer_id\":\"${node2_peer_id}\",\"tool_name\":\"calculator.does-not-exist\"}"
+ run docker run --rm --network "${MESH_NETWORK}" \
+ "${MESH_RUNTIME_IMAGE}" mcp-client \
+ -url "http://sam-node-1:8080/mcp/events" \
+ -tool "describe_remote_tool" \
+ -args "${describe_args}"
+ echo "describe_remote_tool output: $output"
+
+ # The peer's describe_local_tool handler returns "tool not found: <name>";
+ # handleDescribeRemoteTool wraps it as "describe_local_tool on <peer>: tool
+ # not found: ...". Either mcp-client exits non-zero or the wrapper text
+ # appears in stdout.
+ [[ "${status}" -ne 0 || "$output" == *"tool not found"* ]]
+}