Skip to content

Agent Mesh

refactor

Antonio Ojeaed9c3f0fb87b
diff --git a/.gitignore b/.gitignore
index 4173f720..1f6c7b3e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -32,3 +32,4 @@ go.work.sum
# .vscode/
#
bin/
+tests/e2e/logs/
diff --git a/Makefile b/Makefile
index 1dfc74e6..e4f1f995 100644
--- a/Makefile
+++ b/Makefile
@@ -8,6 +8,7 @@ export GOROOT GO111MODULE CGO_ENABLED
build:
go build -v -o "$(OUT_DIR)/sam-node" ./cmd/sam-node
go build -v -o "$(OUT_DIR)/sam-hub" ./cmd/sam-hub
+ go build -v -o "$(OUT_DIR)/mcp-client" ./cmd/mcp-client
.PHONY: proto
proto:
@@ -36,7 +37,7 @@ test-e2e: build
}
SAM_NODE_BINARY=$(OUT_DIR)/sam-node SAM_HUB_BINARY=$(OUT_DIR)/sam-hub bats --verbose-run tests/e2e/
-test-e2e-container: docker-build
+test-e2e-container: build docker-build
@command -v docker >/dev/null 2>&1 || { echo "docker not found"; exit 1; }
@docker info >/dev/null 2>&1 || { echo "docker daemon is not running"; exit 1; }
@command -v bats >/dev/null 2>&1 || { echo "bats not found"; exit 1; }
diff --git a/api/sam.pb.go b/api/sam.pb.go
index 00279233..099d159b 100644
--- a/api/sam.pb.go
+++ b/api/sam.pb.go
@@ -35,6 +35,55 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
+type MeshEvent_Type int32
+
+const (
+ MeshEvent_JOIN MeshEvent_Type = 0
+ MeshEvent_EXIT MeshEvent_Type = 1
+ MeshEvent_BANNED MeshEvent_Type = 2
+)
+
+// Enum value maps for MeshEvent_Type.
+var (
+ MeshEvent_Type_name = map[int32]string{
+ 0: "JOIN",
+ 1: "EXIT",
+ 2: "BANNED",
+ }
+ MeshEvent_Type_value = map[string]int32{
+ "JOIN": 0,
+ "EXIT": 1,
+ "BANNED": 2,
+ }
+)
+
+func (x MeshEvent_Type) Enum() *MeshEvent_Type {
+ p := new(MeshEvent_Type)
+ *p = x
+ return p
+}
+
+func (x MeshEvent_Type) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (MeshEvent_Type) Descriptor() protoreflect.EnumDescriptor {
+ return file_api_sam_proto_enumTypes[0].Descriptor()
+}
+
+func (MeshEvent_Type) Type() protoreflect.EnumType {
+ return &file_api_sam_proto_enumTypes[0]
+}
+
+func (x MeshEvent_Type) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use MeshEvent_Type.Descriptor instead.
+func (MeshEvent_Type) EnumDescriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{7, 0}
+}
+
type AuthEnvelope struct {
state protoimpl.MessageState `protogen:"open.v1"`
Biscuit []byte `protobuf:"bytes,1,opt,name=biscuit,proto3" json:"biscuit,omitempty"`
@@ -471,6 +520,66 @@ func (x *RevocationMsg) GetSignature() []byte {
return nil
}
+type MeshEvent struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Type MeshEvent_Type `protobuf:"varint,1,opt,name=type,proto3,enum=sam.v1.MeshEvent_Type" json:"type,omitempty"`
+ PeerId string `protobuf:"bytes,2,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
+ Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MeshEvent) Reset() {
+ *x = MeshEvent{}
+ mi := &file_api_sam_proto_msgTypes[7]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MeshEvent) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MeshEvent) ProtoMessage() {}
+
+func (x *MeshEvent) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[7]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use MeshEvent.ProtoReflect.Descriptor instead.
+func (*MeshEvent) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *MeshEvent) GetType() MeshEvent_Type {
+ if x != nil {
+ return x.Type
+ }
+ return MeshEvent_JOIN
+}
+
+func (x *MeshEvent) GetPeerId() string {
+ if x != nil {
+ return x.PeerId
+ }
+ return ""
+}
+
+func (x *MeshEvent) GetTimestamp() int64 {
+ if x != nil {
+ return x.Timestamp
+ }
+ return 0
+}
+
type EnrollRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Jwt string `protobuf:"bytes,1,opt,name=jwt,proto3" json:"jwt,omitempty"`
@@ -481,7 +590,7 @@ type EnrollRequest struct {
func (x *EnrollRequest) Reset() {
*x = EnrollRequest{}
- mi := &file_api_sam_proto_msgTypes[7]
+ mi := &file_api_sam_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -493,7 +602,7 @@ func (x *EnrollRequest) String() string {
func (*EnrollRequest) ProtoMessage() {}
func (x *EnrollRequest) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[7]
+ mi := &file_api_sam_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -506,7 +615,7 @@ func (x *EnrollRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use EnrollRequest.ProtoReflect.Descriptor instead.
func (*EnrollRequest) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{7}
+ return file_api_sam_proto_rawDescGZIP(), []int{8}
}
func (x *EnrollRequest) GetJwt() string {
@@ -530,13 +639,14 @@ type EnrollResponse struct {
HubPublicKey []byte `protobuf:"bytes,3,opt,name=hub_public_key,json=hubPublicKey,proto3" json:"hub_public_key,omitempty"`
HubAddresses []string `protobuf:"bytes,4,rep,name=hub_addresses,json=hubAddresses,proto3" json:"hub_addresses,omitempty"`
Expiration int64 `protobuf:"varint,5,opt,name=expiration,proto3" json:"expiration,omitempty"`
+ KnownPeers []string `protobuf:"bytes,6,rep,name=known_peers,json=knownPeers,proto3" json:"known_peers,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *EnrollResponse) Reset() {
*x = EnrollResponse{}
- mi := &file_api_sam_proto_msgTypes[8]
+ mi := &file_api_sam_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -548,7 +658,7 @@ func (x *EnrollResponse) String() string {
func (*EnrollResponse) ProtoMessage() {}
func (x *EnrollResponse) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[8]
+ mi := &file_api_sam_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -561,7 +671,7 @@ func (x *EnrollResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use EnrollResponse.ProtoReflect.Descriptor instead.
func (*EnrollResponse) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{8}
+ return file_api_sam_proto_rawDescGZIP(), []int{9}
}
func (x *EnrollResponse) GetBiscuitToken() []byte {
@@ -599,6 +709,13 @@ func (x *EnrollResponse) GetExpiration() int64 {
return 0
}
+func (x *EnrollResponse) GetKnownPeers() []string {
+ if x != nil {
+ return x.KnownPeers
+ }
+ return nil
+}
+
var File_api_sam_proto protoreflect.FileDescriptor
const file_api_sam_proto_rawDesc = "" +
@@ -640,10 +757,19 @@ const file_api_sam_proto_rawDesc = "" +
"\x0etarget_peer_id\x18\x01 \x01(\tR\ftargetPeerId\x12\x16\n" +
"\x06reason\x18\x02 \x01(\tR\x06reason\x12\x1c\n" +
"\ttimestamp\x18\x03 \x01(\x03R\ttimestamp\x12\x1c\n" +
- "\tsignature\x18\x04 \x01(\fR\tsignature\":\n" +
+ "\tsignature\x18\x04 \x01(\fR\tsignature\"\x96\x01\n" +
+ "\tMeshEvent\x12*\n" +
+ "\x04type\x18\x01 \x01(\x0e2\x16.sam.v1.MeshEvent.TypeR\x04type\x12\x17\n" +
+ "\apeer_id\x18\x02 \x01(\tR\x06peerId\x12\x1c\n" +
+ "\ttimestamp\x18\x03 \x01(\x03R\ttimestamp\"&\n" +
+ "\x04Type\x12\b\n" +
+ "\x04JOIN\x10\x00\x12\b\n" +
+ "\x04EXIT\x10\x01\x12\n" +
+ "\n" +
+ "\x06BANNED\x10\x02\":\n" +
"\rEnrollRequest\x12\x10\n" +
"\x03jwt\x18\x01 \x01(\tR\x03jwt\x12\x17\n" +
- "\apeer_id\x18\x02 \x01(\tR\x06peerId\"\xc5\x01\n" +
+ "\apeer_id\x18\x02 \x01(\tR\x06peerId\"\xe6\x01\n" +
"\x0eEnrollResponse\x12#\n" +
"\rbiscuit_token\x18\x01 \x01(\fR\fbiscuitToken\x12#\n" +
"\rerror_message\x18\x02 \x01(\tR\ferrorMessage\x12$\n" +
@@ -651,7 +777,9 @@ const file_api_sam_proto_rawDesc = "" +
"\rhub_addresses\x18\x04 \x03(\tR\fhubAddresses\x12\x1e\n" +
"\n" +
"expiration\x18\x05 \x01(\x03R\n" +
- "expirationB\x1bZ\x19github.com/google/sam/apib\x06proto3"
+ "expiration\x12\x1f\n" +
+ "\vknown_peers\x18\x06 \x03(\tR\n" +
+ "knownPeersB\x1bZ\x19github.com/google/sam/apib\x06proto3"
var (
file_api_sam_proto_rawDescOnce sync.Once
@@ -665,30 +793,34 @@ func file_api_sam_proto_rawDescGZIP() []byte {
return file_api_sam_proto_rawDescData
}
-var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 11)
+var file_api_sam_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 12)
var file_api_sam_proto_goTypes = []any{
- (*AuthEnvelope)(nil), // 0: sam.v1.AuthEnvelope
- (*HubConfig)(nil), // 1: sam.v1.HubConfig
- (*PeerProfile)(nil), // 2: sam.v1.PeerProfile
- (*PeerRegistry)(nil), // 3: sam.v1.PeerRegistry
- (*ModelProperty)(nil), // 4: sam.v1.ModelProperty
- (*AgentCard)(nil), // 5: sam.v1.AgentCard
- (*RevocationMsg)(nil), // 6: sam.v1.RevocationMsg
- (*EnrollRequest)(nil), // 7: sam.v1.EnrollRequest
- (*EnrollResponse)(nil), // 8: sam.v1.EnrollResponse
- nil, // 9: sam.v1.PeerRegistry.PeersEntry
- nil, // 10: sam.v1.AgentCard.MetadataEntry
+ (MeshEvent_Type)(0), // 0: sam.v1.MeshEvent.Type
+ (*AuthEnvelope)(nil), // 1: sam.v1.AuthEnvelope
+ (*HubConfig)(nil), // 2: sam.v1.HubConfig
+ (*PeerProfile)(nil), // 3: sam.v1.PeerProfile
+ (*PeerRegistry)(nil), // 4: sam.v1.PeerRegistry
+ (*ModelProperty)(nil), // 5: sam.v1.ModelProperty
+ (*AgentCard)(nil), // 6: sam.v1.AgentCard
+ (*RevocationMsg)(nil), // 7: sam.v1.RevocationMsg
+ (*MeshEvent)(nil), // 8: sam.v1.MeshEvent
+ (*EnrollRequest)(nil), // 9: sam.v1.EnrollRequest
+ (*EnrollResponse)(nil), // 10: sam.v1.EnrollResponse
+ nil, // 11: sam.v1.PeerRegistry.PeersEntry
+ nil, // 12: sam.v1.AgentCard.MetadataEntry
}
var file_api_sam_proto_depIdxs = []int32{
- 9, // 0: sam.v1.PeerRegistry.peers:type_name -> sam.v1.PeerRegistry.PeersEntry
- 4, // 1: sam.v1.AgentCard.models:type_name -> sam.v1.ModelProperty
- 10, // 2: sam.v1.AgentCard.metadata:type_name -> sam.v1.AgentCard.MetadataEntry
- 2, // 3: sam.v1.PeerRegistry.PeersEntry.value:type_name -> sam.v1.PeerProfile
- 4, // [4:4] is the sub-list for method output_type
- 4, // [4:4] is the sub-list for method input_type
- 4, // [4:4] is the sub-list for extension type_name
- 4, // [4:4] is the sub-list for extension extendee
- 0, // [0:4] is the sub-list for field type_name
+ 11, // 0: sam.v1.PeerRegistry.peers:type_name -> sam.v1.PeerRegistry.PeersEntry
+ 5, // 1: sam.v1.AgentCard.models:type_name -> sam.v1.ModelProperty
+ 12, // 2: sam.v1.AgentCard.metadata:type_name -> sam.v1.AgentCard.MetadataEntry
+ 0, // 3: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type
+ 3, // 4: sam.v1.PeerRegistry.PeersEntry.value:type_name -> sam.v1.PeerProfile
+ 5, // [5:5] is the sub-list for method output_type
+ 5, // [5:5] is the sub-list for method input_type
+ 5, // [5:5] is the sub-list for extension type_name
+ 5, // [5:5] is the sub-list for extension extendee
+ 0, // [0:5] is the sub-list for field type_name
}
func init() { file_api_sam_proto_init() }
@@ -701,13 +833,14 @@ func file_api_sam_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),
- NumEnums: 0,
- NumMessages: 11,
+ NumEnums: 1,
+ NumMessages: 12,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_api_sam_proto_goTypes,
DependencyIndexes: file_api_sam_proto_depIdxs,
+ EnumInfos: file_api_sam_proto_enumTypes,
MessageInfos: file_api_sam_proto_msgTypes,
}.Build()
File_api_sam_proto = out.File
diff --git a/api/sam.proto b/api/sam.proto
index 0612e47d..73fb3c54 100644
--- a/api/sam.proto
+++ b/api/sam.proto
@@ -60,6 +60,17 @@ message RevocationMsg {
bytes signature = 4;
}
+message MeshEvent {
+ enum Type {
+ JOIN = 0;
+ EXIT = 1;
+ BANNED = 2;
+ }
+ Type type = 1;
+ string peer_id = 2;
+ int64 timestamp = 3;
+}
+
message EnrollRequest {
string jwt = 1;
string peer_id = 2;
@@ -71,4 +82,5 @@ message EnrollResponse {
bytes hub_public_key = 3;
repeated string hub_addresses = 4;
int64 expiration = 5;
+ repeated string known_peers = 6;
}
diff --git a/cmd/mcp-client/main.go b/cmd/mcp-client/main.go
new file mode 100644
index 00000000..1777b707
--- /dev/null
+++ b/cmd/mcp-client/main.go
@@ -0,0 +1,77 @@
+// 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"
+ "flag"
+ "fmt"
+ "log"
+ "net"
+ "net/http"
+
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+func main() {
+ socketPath := flag.String("socket", "", "Path to Unix domain socket")
+ flag.Parse()
+
+ if *socketPath == "" {
+ log.Fatal("Must specify -socket")
+ }
+
+ ctx := context.Background()
+
+ // Override default HTTP client transport to use Unix socket
+ http.DefaultClient.Transport = &http.Transport{
+ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
+ return net.Dial("unix", *socketPath)
+ },
+ }
+
+ // Create MCP client
+ client := mcp.NewClient(&mcp.Implementation{
+ Name: "mcp-test-client",
+ Version: "0.1.0",
+ }, nil)
+
+ // Connect to server using the URL (host is ignored by custom dialer)
+ session, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: "http://localhost/mcp"}, nil)
+ if err != nil {
+ log.Fatalf("Failed to connect: %v", err)
+ }
+ defer func() {
+ if err := session.Close(); err != nil {
+ log.Printf("Failed to close session: %v", err)
+ }
+ }()
+
+ // Call tool get_mesh_info
+ result, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: "get_mesh_info",
+ Arguments: map[string]any{},
+ })
+ if err != nil {
+ log.Printf("CallTool failed: %v", err)
+ return
+ }
+
+ for _, content := range result.Content {
+ if textContent, ok := content.(*mcp.TextContent); ok {
+ fmt.Println(textContent.Text)
+ }
+ }
+}
diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.go
index 5a7c33ec..8c807348 100644
--- a/cmd/sam-hub/main.go
+++ b/cmd/sam-hub/main.go
@@ -177,7 +177,7 @@ func (h *Hub) handleEnroll(s network.Stream) {
if req.PeerId != remotePeer.String() {
fmt.Printf("[Enroll] Peer ID mismatch: %s != %s\n", req.PeerId, remotePeer)
- h.sendEnrollResponse(s, nil, "Peer ID mismatch", 0)
+ h.sendEnrollResponse(s, nil, "Peer ID mismatch", 0, nil)
return
}
@@ -186,13 +186,13 @@ func (h *Hub) handleEnroll(s network.Stream) {
jwtToken, _, err := parser.ParseUnverified(req.Jwt, jwt.MapClaims{})
if err != nil {
fmt.Printf("[Enroll] Failed to parse JWT: %v\n", err)
- h.sendEnrollResponse(s, nil, "Failed to parse JWT", 0)
+ h.sendEnrollResponse(s, nil, "Failed to parse JWT", 0, nil)
return
}
claims, ok := jwtToken.Claims.(jwt.MapClaims)
if !ok {
fmt.Printf("[Enroll] Invalid JWT claims\n")
- h.sendEnrollResponse(s, nil, "Invalid JWT claims", 0)
+ h.sendEnrollResponse(s, nil, "Invalid JWT claims", 0, nil)
return
}
iss, _ := claims["iss"].(string)
@@ -210,18 +210,16 @@ func (h *Hub) handleEnroll(s network.Stream) {
provider, ok := h.Providers[iss]
if !ok {
fmt.Printf("[Enroll] Unknown issuer: %s\n", iss)
- h.sendEnrollResponse(s, nil, fmt.Sprintf("Unknown issuer: %s", iss), 0)
+ h.sendEnrollResponse(s, nil, fmt.Sprintf("Unknown issuer: %s", iss), 0, nil)
return
}
- // TODO: Revisit client check later (enforce specific audience)
- // For now we accept whatever audience is in the token by passing it as expected ClientID
verifier := provider.Verifier(&oidc.Config{ClientID: aud})
token, err := verifier.Verify(context.Background(), req.Jwt)
if err != nil {
fmt.Printf("[Enroll] JWT validation failed: %v\n", err)
- h.sendEnrollResponse(s, nil, fmt.Sprintf("JWT validation failed: %v", err), 0)
+ h.sendEnrollResponse(s, nil, fmt.Sprintf("JWT validation failed: %v", err), 0, nil)
return
}
@@ -241,7 +239,7 @@ func (h *Hub) handleEnroll(s network.Stream) {
IDs: []biscuit.Term{biscuit.Date(token.Expiry)},
}}); err != nil {
fmt.Printf("[Enroll] Failed to add expiration fact: %v\n", err)
- h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0)
+ h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0, nil)
return
}
@@ -250,7 +248,7 @@ func (h *Hub) handleEnroll(s network.Stream) {
IDs: []biscuit.Term{biscuit.String(remotePeer.String())},
}}); err != nil {
fmt.Printf("[Enroll] Failed to add node fact: %v\n", err)
- h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0)
+ h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0, nil)
return
}
@@ -260,7 +258,7 @@ func (h *Hub) handleEnroll(s network.Stream) {
IDs: []biscuit.Term{biscuit.String(role)},
}}); err != nil {
fmt.Printf("[Enroll] Failed to add group fact: %v\n", err)
- h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0)
+ h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0, nil)
return
}
}
@@ -268,27 +266,50 @@ func (h *Hub) handleEnroll(s network.Stream) {
t, err := builder.Build()
if err != nil {
fmt.Printf("[Enroll] Failed to build biscuit: %v\n", err)
- h.sendEnrollResponse(s, nil, "Failed to build biscuit", 0)
+ h.sendEnrollResponse(s, nil, "Failed to build biscuit", 0, nil)
return
}
biscuitData, err := t.Serialize()
if err != nil {
fmt.Printf("[Enroll] Failed to serialize biscuit: %v\n", err)
- h.sendEnrollResponse(s, nil, "Failed to serialize biscuit", 0)
+ h.sendEnrollResponse(s, nil, "Failed to serialize biscuit", 0, nil)
return
}
h.gater.mu.Lock()
h.gater.authenticated[remotePeer] = true
delete(h.gater.pending, remotePeer)
+
+ // Collect authenticated peers
+ var knownPeers []string
+ for p := range h.gater.authenticated {
+ knownPeers = append(knownPeers, p.String())
+ }
h.gater.mu.Unlock()
- h.sendEnrollResponse(s, biscuitData, "", token.Expiry.Unix())
+ h.sendEnrollResponse(s, biscuitData, "", token.Expiry.Unix(), knownPeers)
fmt.Printf("[Enroll] Successfully enrolled peer %s\n", remotePeer)
+
+ // Publish JOIN event
+ event := &api.MeshEvent{
+ Type: api.MeshEvent_JOIN,
+ PeerId: remotePeer.String(),
+ Timestamp: time.Now().Unix(),
+ }
+ eventData, err := proto.Marshal(event)
+ if err != nil {
+ fmt.Printf("[Enroll] Failed to marshal event: %v\n", err)
+ } else {
+ if err := h.EventTopic.Publish(context.Background(), eventData); err != nil {
+ fmt.Printf("[Enroll] Failed to publish event: %v\n", err)
+ } else {
+ fmt.Printf("[Enroll] Published JOIN event for %s\n", remotePeer)
+ }
+ }
}
-func (h *Hub) sendEnrollResponse(s network.Stream, biscuitToken []byte, errMsg string, expiration int64) {
+func (h *Hub) sendEnrollResponse(s network.Stream, biscuitToken []byte, errMsg string, expiration int64, knownPeers []string) {
var hubAddrs []string
for _, addr := range h.Host.Addrs() {
hubAddrs = append(hubAddrs, addr.String()+"/p2p/"+h.Host.ID().String())
@@ -302,6 +323,7 @@ func (h *Hub) sendEnrollResponse(s network.Stream, biscuitToken []byte, errMsg s
HubPublicKey: pubKey,
HubAddresses: hubAddrs,
Expiration: expiration,
+ KnownPeers: knownPeers,
}
data, err := proto.Marshal(resp)
if err != nil {
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index 244d835f..e52bdef1 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -22,6 +22,8 @@ import (
"fmt"
"log"
"net"
+ "net/http"
+ "path/filepath"
"os"
"os/signal"
"strings"
@@ -46,6 +48,9 @@ var (
clientSecretFlag string
tokenURLFlag string
hubPublicKeyFlag string
+ mcpSocketFlag string
+ meshFlag string
+ discoveryIntervalFlag string
)
func main() {
@@ -127,7 +132,7 @@ func main() {
log.Fatal("Hub public key not found in store and not provided. Cannot verify peers.")
}
priv := getOrGenerateKey(store)
- node, err = NewSamNode(context.Background(), priv, hubPubKey, hubAddrs, store)
+ node, err = NewSamNode(context.Background(), priv, hubPubKey, hubAddrs, store, meshFlag, discoveryIntervalFlag)
if err != nil {
log.Fatalf("Failed to start mesh node: %v", err)
}
@@ -158,7 +163,7 @@ func main() {
}
priv := getOrGenerateKey(store)
- node, err = NewSamNode(context.Background(), priv, nil, initHubAddrs, store)
+ node, err = NewSamNode(context.Background(), priv, nil, initHubAddrs, store, meshFlag, discoveryIntervalFlag)
if err != nil {
log.Fatalf("Failed to initialize node for enrollment: %v", err)
}
@@ -233,6 +238,34 @@ func main() {
node.Host.SetStreamHandler(AuthProtocolID, node.HandleAuthHandshake)
+ // Start MCP Server
+ mcpHandler := NewMCPHandler(node)
+ go func() {
+ socketPath := mcpSocketFlag
+ if socketPath == "" {
+ socketPath = filepath.Join(dataDir, "mcp.sock")
+ }
+
+ // Remove old socket file if it exists
+ _ = os.Remove(socketPath)
+
+ listener, err := net.Listen("unix", socketPath)
+ if err != nil {
+ log.Printf("Failed to listen on Unix socket %s: %v", socketPath, err)
+ return
+ }
+ defer func() {
+ if err := listener.Close(); err != nil {
+ log.Printf("Failed to close listener: %v", err)
+ }
+ }()
+
+ fmt.Printf("Starting MCP server on Unix socket %s\n", socketPath)
+ if err := http.Serve(listener, mcpHandler); err != nil {
+ log.Printf("MCP server error: %v", err)
+ }
+ }()
+
fmt.Printf("SAM Node Online.\nPeerID: %s\nListening on: %v\n", node.Host.ID(), listenAddrs)
// Block forever
@@ -292,7 +325,7 @@ func main() {
}
priv := getOrGenerateKey(store)
- node, err := NewSamNode(context.Background(), priv, nil, initHubAddrs, store)
+ node, err := NewSamNode(context.Background(), priv, nil, initHubAddrs, store, meshFlag, discoveryIntervalFlag)
if err != nil {
log.Fatalf("Failed to initialize node for enrollment: %v", err)
}
@@ -313,6 +346,9 @@ func main() {
runCmd.Flags().StringVar(&clientIDFlag, "client-id", os.Getenv("SAM_OIDC_ID"), "OIDC Client ID for M2M")
runCmd.Flags().StringVar(&clientSecretFlag, "client-secret", os.Getenv("SAM_OIDC_SECRET"), "OIDC Client Secret for M2M")
runCmd.Flags().StringVar(&hubPublicKeyFlag, "hub-public-key", "", "Hub Public Key (32-byte Hex)")
+ runCmd.Flags().StringVar(&mcpSocketFlag, "mcp-socket", "", "Path to Unix domain socket for local MCP server (default: <datadir>/mcp.sock)")
+ runCmd.Flags().StringVar(&meshFlag, "mesh", "public-mesh", "Mesh federation name")
+ runCmd.Flags().StringVar(&discoveryIntervalFlag, "discovery-interval", "2s", "Polling interval for DHT discovery")
rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", "http://localhost:8080", "Hub URL")
rootCmd.PersistentFlags().StringVar(&tokenURLFlag, "token-url", "", "OIDC Token URL")
@@ -415,6 +451,14 @@ func (n *SamNode) Enroll(ctx context.Context, jwt string) error {
return fmt.Errorf("failed to save hub config: %v", err)
}
+ // Add known peers from response
+ n.mu.Lock()
+ for _, p := range resp.KnownPeers {
+ n.knownPeers[p] = true
+ fmt.Printf("[Enroll] Added known peer from hub: %s\n", p)
+ }
+ n.mu.Unlock()
+
fmt.Println("Successfully enrolled and stored identity and hub config.")
return nil
}
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
new file mode 100644
index 00000000..b59f0573
--- /dev/null
+++ b/cmd/sam-node/mcp.go
@@ -0,0 +1,90 @@
+// 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"
+
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+// SendMessageParams defines the parameters for the send_message tool.
+type SendMessageParams struct {
+ PeerID string `json:"peer_id" jsonschema:"The Peer ID of the target agent"`
+ Message string `json:"message" jsonschema:"The message content"`
+}
+
+// handleSendMessage implements the send_message tool.
+func handleSendMessage(ctx context.Context, req *mcp.CallToolRequest, params SendMessageParams) (*mcp.CallToolResult, any, error) {
+ response := fmt.Sprintf("Simulated sending message to %s: %s", params.PeerID, params.Message)
+
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: response},
+ },
+ }, nil, nil
+}
+
+// NewMCPHandler creates a new HTTP handler for the MCP server using the official SDK.
+func NewMCPHandler(node *SamNode) http.Handler {
+ // Create an MCP server.
+ server := mcp.NewServer(&mcp.Implementation{
+ Name: "sam-node-mcp",
+ Version: "0.1.0",
+ }, nil)
+
+ // Add the send_message tool.
+ mcp.AddTool(server, &mcp.Tool{
+ Name: "send_message",
+ Description: "Send a message to another agent in the mesh",
+ }, handleSendMessage)
+
+ // Add the get_mesh_info tool.
+ mcp.AddTool(server, &mcp.Tool{
+ Name: "get_mesh_info",
+ Description: "Get information about the mesh network",
+ }, func(ctx context.Context, req *mcp.CallToolRequest, params struct{}) (*mcp.CallToolResult, any, error) {
+ if node == nil {
+ return nil, nil, fmt.Errorf("node not initialized")
+ }
+ node.mu.Lock()
+ knownCount := len(node.knownPeers)
+ var knownPeers []string
+ for p := range node.knownPeers {
+ knownPeers = append(knownPeers, p)
+ }
+ node.mu.Unlock()
+
+ peers := node.Host.Network().Peers()
+ dhtSize := node.DHT.RoutingTable().Size()
+
+ response := fmt.Sprintf("Known peers count: %d\nKnown peers list: %v\nConnected peers: %d\nDHT Routing Table size: %d\nHub Peer ID: %s", knownCount, knownPeers, len(peers), dhtSize, node.HubPeerID)
+
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: response},
+ },
+ }, nil, nil
+ })
+
+ // Create the streamable HTTP handler.
+ handler := mcp.NewStreamableHTTPHandler(func(req *http.Request) *mcp.Server {
+ return server
+ }, nil)
+
+ return handler
+}
diff --git a/cmd/sam-node/mcp_test.go b/cmd/sam-node/mcp_test.go
new file mode 100644
index 00000000..215c6252
--- /dev/null
+++ b/cmd/sam-node/mcp_test.go
@@ -0,0 +1,61 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package main
+
+import (
+ "bytes"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestMCPServer(t *testing.T) {
+ handler := NewMCPHandler(nil)
+
+ t.Run("initialize", func(t *testing.T) {
+ reqBody := []byte(`{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0"}},"id":1}`)
+ req := httptest.NewRequest(http.MethodPost, "/mcp", bytes.NewBuffer(reqBody))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json, text/event-stream")
+ w := httptest.NewRecorder()
+
+ handler.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Errorf("Expected status OK, got %v", w.Code)
+ }
+ })
+
+ t.Run("tools/list", func(t *testing.T) {
+ reqBody := []byte(`{"jsonrpc":"2.0","method":"tools/list","id":2}`)
+ req := httptest.NewRequest(http.MethodPost, "/mcp", bytes.NewBuffer(reqBody))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json, text/event-stream")
+ w := httptest.NewRecorder()
+
+ handler.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Errorf("Expected status OK, got %v", w.Code)
+ }
+
+ body := w.Body.String()
+ // We expect an error because we haven't established a full session (SSE handshake + initialize).
+ if !strings.Contains(body, "invalid during session initialization") {
+ t.Errorf("Expected session initialization error, got: %s", body)
+ }
+ })
+}
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index 5c8d1c55..29854915 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -18,12 +18,16 @@ import (
"context"
"crypto/ed25519"
"fmt"
+ "sync"
"github.com/biscuit-auth/biscuit-go/v2"
"github.com/google/sam/api"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
pubsub "github.com/libp2p/go-libp2p-pubsub"
+ "github.com/libp2p/go-libp2p/p2p/discovery/routing"
+ "github.com/libp2p/go-libp2p/p2p/discovery/util"
+ "time"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
@@ -46,13 +50,16 @@ type SamNode struct {
Store *Store
HubPublicKey ed25519.PublicKey
HubPeerID peer.ID
+ knownPeers map[string]bool
+ mu sync.Mutex
}
// NewSamNode creates a new Agent instance secured with the 4-layer pipeline.
-func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.PublicKey, hubAddrs []multiaddr.Multiaddr, store *Store) (*SamNode, error) {
+func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.PublicKey, hubAddrs []multiaddr.Multiaddr, store *Store, meshID string, discoveryInterval string) (*SamNode, error) {
node := &SamNode{
Store: store,
HubPublicKey: hubPubKey,
+ knownPeers: make(map[string]bool),
}
// Layer 2: Attach the Bouncer (Gater)
@@ -118,6 +125,15 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.P
// Listen for Network Evictions/Revocations from the Hub
go node.listenForHubEvents(ctx)
+ interval, err := time.ParseDuration(discoveryInterval)
+ if err != nil {
+ fmt.Printf("[Warning] Invalid discovery interval '%s', using default 2s: %v\n", discoveryInterval, err)
+ interval = 2 * time.Second
+ }
+
+ // Start DHT Discovery
+ go node.startDiscovery(ctx, meshID, interval)
+
// Layer 3: Open the Lobby Door (Auth Protocol is bypassed by Layer 4)
node.WrapSecurely(AuthProtocolID, node.HandleAuthHandshake)
@@ -140,12 +156,54 @@ func (n *SamNode) listenForHubEvents(ctx context.Context) {
if err != nil {
return
}
- var revMsg api.RevocationMsg
- if err := proto.Unmarshal(msg.Data, &revMsg); err != nil {
- fmt.Printf("[Mesh Event] Failed to unmarshal revocation message from %s: %v\n", msg.ReceivedFrom, err)
+ var event api.MeshEvent
+ if err := proto.Unmarshal(msg.Data, &event); err != nil {
+ fmt.Printf("[Mesh Event] Failed to unmarshal event from %s: %v\n", msg.ReceivedFrom, err)
continue
}
- fmt.Printf("[Mesh Event] Received Hub update from %s for target %s\n", msg.ReceivedFrom, revMsg.TargetPeerId)
+
+ n.mu.Lock()
+ switch event.Type {
+ case api.MeshEvent_JOIN:
+ n.knownPeers[event.PeerId] = true
+ fmt.Printf("[Mesh Event] Peer joined: %s\n", event.PeerId)
+ case api.MeshEvent_EXIT, api.MeshEvent_BANNED:
+ delete(n.knownPeers, event.PeerId)
+ fmt.Printf("[Mesh Event] Peer left/banned: %s\n", event.PeerId)
+ }
+ n.mu.Unlock()
+ }
+}
+
+func (n *SamNode) startDiscovery(ctx context.Context, meshID string, interval time.Duration) {
+ routingDiscovery := routing.NewRoutingDiscovery(n.DHT)
+ util.Advertise(ctx, routingDiscovery, meshID)
+
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ peers, err := routingDiscovery.FindPeers(ctx, meshID)
+ if err != nil {
+ fmt.Printf("[Discovery] Failed to find peers: %v\n", err)
+ continue
+ }
+ for p := range peers {
+ if p.ID == n.Host.ID() {
+ continue
+ }
+ n.mu.Lock()
+ if !n.knownPeers[p.ID.String()] {
+ n.knownPeers[p.ID.String()] = true
+ fmt.Printf("[Discovery] Found new peer via DHT: %s\n", p.ID)
+ }
+ n.mu.Unlock()
+ }
+ }
}
}
diff --git a/go.mod b/go.mod
index 72152e5f..5b947ae0 100644
--- a/go.mod
+++ b/go.mod
@@ -10,6 +10,7 @@ require (
github.com/libp2p/go-libp2p-kad-dht v0.39.1
github.com/libp2p/go-libp2p-pubsub v0.16.0
github.com/libp2p/go-msgio v0.3.0
+ github.com/modelcontextprotocol/go-sdk v1.5.0
github.com/multiformats/go-multiaddr v0.16.1
github.com/spf13/cobra v1.10.2
go.etcd.io/bbolt v1.4.3
@@ -33,6 +34,7 @@ require (
github.com/go-logr/stdr v1.2.2 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/google/gopacket v1.1.19 // indirect
+ github.com/google/jsonschema-go v0.4.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
@@ -99,10 +101,13 @@ require (
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/quic-go/webtransport-go v0.10.0 // indirect
+ github.com/segmentio/asm v1.1.3 // indirect
+ github.com/segmentio/encoding v0.5.4 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 // indirect
github.com/wlynxg/anet v0.0.5 // indirect
+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel v1.43.0 // indirect
go.opentelemetry.io/otel/metric v1.43.0 // indirect
diff --git a/go.sum b/go.sum
index b82d441b..53e5a91d 100644
--- a/go.sum
+++ b/go.sum
@@ -167,6 +167,8 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=
github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=
+github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
+github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
@@ -322,6 +324,8 @@ github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0Qu
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
+github.com/modelcontextprotocol/go-sdk v1.5.0 h1:CHU0FIX9kpueNkxuYtfYQn1Z0slhFzBZuq+x6IiblIU=
+github.com/modelcontextprotocol/go-sdk v1.5.0/go.mod h1:gggDIhoemhWs3BGkGwd1umzEXCEMMvAnhTrnbXJKKKA=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
@@ -424,6 +428,10 @@ github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
+github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
+github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
+github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
+github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/shurcooL/go v0.0.0-20200502201357-93f07166e636/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=
github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
@@ -465,6 +473,8 @@ github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 h1:EKhdz
github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1/go.mod h1:8UvriyWtv5Q5EOgjHaSseUEdkQfvwFv1I/In/O2M9gc=
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
diff --git a/tests/e2e/container_mesh.bats b/tests/e2e/container_mesh.bats
index c5417855..e6618602 100644
--- a/tests/e2e/container_mesh.bats
+++ b/tests/e2e/container_mesh.bats
@@ -12,9 +12,20 @@ setup() {
fi
mesh_setup_env
+ mkdir -p tests/e2e/logs
}
teardown() {
+ if [[ "${BATS_TEST_COMPLETED:-0}" -ne 1 ]]; then
+ mkdir -p tests/e2e/logs
+ local ids
+ ids="$(docker ps -aq --filter "name=mesh-")"
+ for id in ${ids}; do
+ local name
+ name="$(docker inspect -f '{{.Name}}' "${id}" | tr -d '/')"
+ docker logs "${id}" > "tests/e2e/logs/${name}.log" 2>&1 || true
+ done
+ fi
mesh_cleanup_env
}
@@ -30,6 +41,7 @@ teardown() {
for i in $(seq 1 "$node_count"); do
run mesh_start_node "$i"
[[ "$status" -eq 0 ]]
+ sleep 2
done
# Verify every container remains healthy enough to keep the process running.
@@ -40,4 +52,16 @@ teardown() {
run mesh_assert_container_running "${MESH_PREFIX}-node-${i}"
[[ "$status" -eq 0 ]]
done
+
+ # Wait for MCP readiness on each node.
+ for i in $(seq 1 "$node_count"); do
+ run mesh_wait_for_mcp_ready "${i}" 20
+ [[ "$status" -eq 0 ]]
+ done
+
+ # Verify connected peer count via MCP (wait for full mesh).
+ for i in $(seq 1 "$node_count"); do
+ run mesh_wait_for_node_count "${i}" "${node_count}" 60
+ [[ "$status" -eq 0 ]]
+ done
}
diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index 9c059642..16b43620 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -10,6 +10,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
MESH_NETWORK=""
MESH_CONTAINERS=()
MESH_PREFIX=""
+ MESH_SOCKET_DIR=""
# Best-effort cleanup of leaked resources from prior failed runs.
mesh_cleanup_stale_resources() {
@@ -58,6 +59,9 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
if ! docker network create --subnet "${subnet}" "${MESH_NETWORK}" >/dev/null 2>&1; then
docker network create "${MESH_NETWORK}" >/dev/null
fi
+
+ MESH_SOCKET_DIR="/tmp/${MESH_PREFIX}-sockets"
+ mkdir -p "${MESH_SOCKET_DIR}"
}
mesh_cleanup_env() {
@@ -68,6 +72,9 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
if [[ -n "${MESH_NETWORK}" ]]; then
docker network rm "${MESH_NETWORK}" >/dev/null 2>&1 || true
fi
+ if [[ -n "${MESH_SOCKET_DIR}" ]]; then
+ rm -rf "${MESH_SOCKET_DIR}"
+ fi
MESH_CONTAINERS=()
MESH_NETWORK=""
}
@@ -90,6 +97,69 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
return 1
}
+ mesh_wait_for_mcp_ready() {
+ local idx="$1"
+ local timeout_s="${2:-20}"
+ local i
+ local data='{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}},"id":1}'
+
+ for ((i=0; i<timeout_s; i++)); do
+ if docker run --rm -v "${MESH_SOCKET_DIR}:/sockets" -e SOCKET_PATH="/sockets/node-${idx}.sock" -e DATA="${data}" python:3.12 python3 -c "
+import socket
+import os
+import sys
+
+try:
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ s.connect(os.environ['SOCKET_PATH'])
+
+ data = os.environ['DATA'].encode('utf-8')
+ request = f\"POST /mcp HTTP/1.1\\r\\nHost: localhost\\r\\nContent-Type: application/json\\r\\nAccept: application/json, text/event-stream\\r\\nContent-Length: {len(data)}\\r\\n\\r\\n\".encode('utf-8') + data
+
+ s.sendall(request)
+ response = s.recv(4096).decode('utf-8')
+ s.close()
+
+ if 'protocolVersion' in response:
+ sys.exit(0)
+except Exception as e:
+ pass
+sys.exit(1)
+" >/dev/null 2>&1; then
+ return 0
+ fi
+ sleep 1
+ done
+ return 1
+ }
+
+ mesh_get_node_count_via_mcp() {
+ local idx="$1"
+ local output
+ output="$(docker run --rm -v "${MESH_SOCKET_DIR}:/sockets" -v "$(pwd)/bin/mcp-client:/mcp-client" python:3.12 /mcp-client -socket "/sockets/node-${idx}.sock" 2>/dev/null)"
+
+ echo "${output}" | grep "Known peers count:" | awk '{print $4}' | tr -d '\r'
+ }
+
+ mesh_wait_for_node_count() {
+ local idx="$1"
+ local expected="$2"
+ local timeout_s="${3:-20}"
+ local i
+ for ((i=0; i<timeout_s; i++)); do
+ local output
+ output="$(docker run --rm -v "${MESH_SOCKET_DIR}:/sockets" -v "$(pwd)/bin/mcp-client:/mcp-client" python:3.12 /mcp-client -socket "/sockets/node-${idx}.sock" 2>/dev/null)"
+ local count
+ count="$(echo "${output}" | grep "Known peers count:" | awk '{print $4}' | tr -d '\r')"
+ echo "Node ${idx} reported output: ${output}"
+ if [[ "${count}" -eq "${expected}" ]]; then
+ return 0
+ fi
+ sleep 1
+ done
+ return 1
+ }
+
mesh_start_mock_oidc() {
local name="${MESH_PREFIX}-oidc"
local cmd
@@ -255,6 +325,7 @@ EOF
--name "${name}" \
--network "${MESH_NETWORK}" \
--network-alias "sam-node-${idx}" \
+ -v "${MESH_SOCKET_DIR}:/sockets" \
"sam-node:local" \
run \
--hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" \
@@ -262,10 +333,11 @@ EOF
--client-secret "sam-e2e-secret" \
--token-url "http://mock-oidc:18080/token" \
--listen "/ip4/0.0.0.0/udp/5001/quic-v1" \
- --listen "/ip4/0.0.0.0/tcp/5002" >/dev/null
+ --listen "/ip4/0.0.0.0/tcp/5002" \
+ --mcp-socket "/sockets/node-${idx}.sock" \
+ --mesh "e2e-mesh" >/dev/null
MESH_CONTAINERS+=("${name}")
- mesh_wait_for_log "${name}" "SAM Node Online" 20
}
mesh_assert_container_running() {