Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
refactor
Antonio Ojea84371b622b7e
diff --git a/cmd/sam-agent/call.go b/cmd/sam-agent/call.goindex 19e3e0b9..636aef79 100644--- a/cmd/sam-agent/call.go+++ b/cmd/sam-agent/call.go@@ -128,7 +128,7 @@ func runCall(parent context.Context, cfg *runConfig, targetArg string) error {Nonce: nonce,Capability: capability,},- MCPRequest: requestJSON,+ Request: requestJSON,}, observer)if err != nil {return fmt.Errorf("A2A call failed: %w", err)diff --git a/cmd/sam-agent/inspect.go b/cmd/sam-agent/inspect.goindex 21634e37..66f94e75 100644--- a/cmd/sam-agent/inspect.go+++ b/cmd/sam-agent/inspect.go@@ -24,6 +24,7 @@ import ("sam/pkg/economy"protocol "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")// newInspectCmd creates the "sam inspect" command for decoding SAM artifacts.@@ -142,16 +143,17 @@ func runInspectCard(cfg *runConfig, input string) error {fmt.Printf("Algorithm: %s\n", card.Algorithm)fmt.Printf("Issued At: %s\n", card.IssuedAt.Format("2006-01-02T15:04:05Z07:00"))- if len(card.Skills) > 0 {- fmt.Println("\nSkills:")- for _, skill := range card.Skills {- fmt.Printf(" - %s: %s\n", skill.ID, skill.Description)+ if len(card.Capabilities) > 0 {+ fmt.Println("\nCapabilities:")+ for _, capability := range card.Capabilities {+ fmt.Printf(" - %s: %s\n", capability.ID, capability.Description)}}- if len(card.Resources) > 0 {+ resources := mcpprotocol.ResourcesFromCard(&card)+ if len(resources) > 0 {fmt.Println("\nResources:")- for _, res := range card.Resources {+ for _, res := range resources {fmt.Printf(" - %s (%s): %s\n", res.Name, res.Kind, res.Endpoint)}}diff --git a/cmd/sam-agent/proxy.go b/cmd/sam-agent/proxy.goindex b3fc3572..c2ac63ae 100644--- a/cmd/sam-agent/proxy.go+++ b/cmd/sam-agent/proxy.go@@ -36,6 +36,7 @@ import (a2aprotocol "sam/pkg/protocol/a2a"protocol "sam/pkg/protocol/discovery"httpprotocol "sam/pkg/protocol/http"+ mcpprotocol "sam/pkg/protocol/mcp")func newProxyCmd(cfg *runConfig) *cobra.Command {@@ -475,7 +476,8 @@ func buildGlobalMCPCatalog(cards []*protocol.AgentCard) []meshToolEntry {if card == nil || strings.TrimSpace(card.PeerID) == "" {continue}- for _, res := range card.Resources {+ resources := mcpprotocol.ResourcesFromCard(card)+ for _, res := range resources {name := strings.TrimSpace(res.Name)if name == "" {continue@@ -488,7 +490,7 @@ func buildGlobalMCPCatalog(cards []*protocol.AgentCard) []meshToolEntry {Description: strings.TrimSpace(res.Description),})}- if len(card.Resources) > 0 {+ if len(resources) > 0 {continue}for _, capability := range card.CapabilityNames() {diff --git a/cmd/sam-agent/proxy_reserved_test.go b/cmd/sam-agent/proxy_reserved_test.goindex 6977a2b1..faf0b775 100644--- a/cmd/sam-agent/proxy_reserved_test.go+++ b/cmd/sam-agent/proxy_reserved_test.go@@ -30,6 +30,7 @@ import ("sam/pkg/identity"samnet "sam/pkg/net"protocol "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")func TestExtractBearerToken(t *testing.T) {@@ -122,7 +123,7 @@ func TestSAMReservedSearchReturnsPublishedWriterCard(t *testing.T) {if priv == nil {t.Fatalf("publisher private key missing")}- card, err := protocol.NewAgentCard(nodeA.PeerID(), []string{"writer"}, []protocol.MCPResource{{Name: "writer", Kind: "tool", Endpoint: "mcp://writer"}}, priv)+ card, err := protocol.NewAgentCard(nodeA.PeerID(), []string{"writer"}, priv, mcpprotocol.WithResources([]mcpprotocol.Resource{{Name: "writer", Kind: "tool", Endpoint: "mcp://writer"}}))if err != nil {t.Fatalf("creating writer card: %v", err)}diff --git a/cmd/sam-agent/publish.go b/cmd/sam-agent/publish.goindex 190c66fb..ce94cfb8 100644--- a/cmd/sam-agent/publish.go+++ b/cmd/sam-agent/publish.go@@ -114,14 +114,14 @@ func runPublish(parent context.Context, cfg *runConfig) error {if resourceName == "" {resourceName = cfg.capabilities[0]}- resource := protocol.MCPResource{+ resource := mcpprotocol.Resource{Name: resourceName,Kind: strings.TrimSpace(cfg.resourceKind),Endpoint: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),Description: strings.TrimSpace(cfg.resourceDesc),}- card, err := protocol.NewAgentCard(node.PeerID(), cfg.capabilities, []protocol.MCPResource{resource}, priv)+ card, err := protocol.NewAgentCard(node.PeerID(), cfg.capabilities, priv, mcpprotocol.WithResources([]mcpprotocol.Resource{resource}))if err != nil {return fmt.Errorf("building agent card: %w", err)}@@ -246,14 +246,14 @@ func runPublishDryRunClient(cfg *runConfig) error {if resourceName == "" {resourceName = cfg.capabilities[0]}- resource := protocol.MCPResource{+ resource := mcpprotocol.Resource{Name: resourceName,Kind: strings.TrimSpace(cfg.resourceKind),Endpoint: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),Description: strings.TrimSpace(cfg.resourceDesc),}- card, err := protocol.NewAgentCard(peerID, cfg.capabilities, []protocol.MCPResource{resource}, privKey)+ card, err := protocol.NewAgentCard(peerID, cfg.capabilities, privKey, mcpprotocol.WithResources([]mcpprotocol.Resource{resource}))if err != nil {return fmt.Errorf("building agent card: %w", err)}diff --git a/cmd/sam-agent/publish_card.go b/cmd/sam-agent/publish_card.goindex c88fac0c..f99559b4 100644--- a/cmd/sam-agent/publish_card.go+++ b/cmd/sam-agent/publish_card.go@@ -25,6 +25,7 @@ import ("github.com/spf13/cobra"protocol "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")func newPublishCardCmd(cfg *runConfig) *cobra.Command {@@ -59,13 +60,13 @@ func runPublishCard(parent context.Context, cfg *runConfig) error {return fmt.Errorf("local node private key unavailable")}- resource := protocol.MCPResource{+ resource := mcpprotocol.Resource{Name: strings.TrimSpace(cfg.resourceName),Kind: strings.TrimSpace(cfg.resourceKind),Endpoint: strings.TrimSpace(cfg.resourceEP),Description: strings.TrimSpace(cfg.resourceDesc),}- card, err := protocol.NewAgentCard(node.PeerID(), cfg.capabilities, []protocol.MCPResource{resource}, priv)+ card, err := protocol.NewAgentCard(node.PeerID(), cfg.capabilities, priv, mcpprotocol.WithResources([]mcpprotocol.Resource{resource}))if err != nil {return fmt.Errorf("building agent card: %w", err)}diff --git a/cmd/sam-agent/publish_mcp.go b/cmd/sam-agent/publish_mcp.goindex 6b4a0d0c..0c1a95ab 100644--- a/cmd/sam-agent/publish_mcp.go+++ b/cmd/sam-agent/publish_mcp.go@@ -69,12 +69,12 @@ func runPublishMCP(parent context.Context, cfg *runConfig) error {return fmt.Errorf("local node private key unavailable")}- resource := protocol.MCPResource{+ resource := mcpprotocol.Resource{Name: strings.TrimSpace(cfg.resourceName),Kind: strings.TrimSpace(cfg.resourceKind),Endpoint: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),}- card, err := protocol.NewAgentCard(node.PeerID(), cfg.capabilities, []protocol.MCPResource{resource}, priv)+ card, err := protocol.NewAgentCard(node.PeerID(), cfg.capabilities, priv, mcpprotocol.WithResources([]mcpprotocol.Resource{resource}))if err != nil {return fmt.Errorf("building agent card: %w", err)}diff --git a/pkg/protocol/a2a/a2a.go b/pkg/protocol/a2a/a2a.goindex c4c1c576..6bdcf392 100644--- a/pkg/protocol/a2a/a2a.go+++ b/pkg/protocol/a2a/a2a.go@@ -47,8 +47,8 @@ const (FailureTypeInternal = "Internal")-// MCPConnector opens a local MCP JSON-RPC transport endpoint.-type MCPConnector interface {+// JSONRPCConnector opens a local backend JSON-RPC transport endpoint.+type JSONRPCConnector interface {Open(ctx context.Context) (mcp.Transport, error)}@@ -93,7 +93,7 @@ type ExecuteRequest struct {Capability stringBiscuit stringPayment economy.Micropayment- MCPRequest json.RawMessage+ Request json.RawMessage}type a2aHeader struct {@@ -126,11 +126,11 @@ func IsAllowAllGate(g FederationGate) bool {}}-// A2AService serves /sam/a2a/1.0 and forwards JSON-RPC over a local MCP connector.+// A2AService serves /sam/a2a/1.0 and forwards JSON-RPC over a local backend connector.type A2AService struct {host host.Hostobserver Observer- mcp MCPConnector+ backend JSONRPCConnectorgate FederationGateskillGate *economy.BiscuitSkillGate}@@ -151,17 +151,17 @@ func WithSkillGate(g *economy.BiscuitSkillGate) A2AServiceOption {}// NewA2AService registers a handler for /sam/a2a/1.0 on host h.-func NewA2AService(h host.Host, connector MCPConnector, observer Observer, opts ...A2AServiceOption) (*A2AService, error) {+func NewA2AService(h host.Host, connector JSONRPCConnector, observer Observer, opts ...A2AServiceOption) (*A2AService, error) {if h == nil {return nil, fmt.Errorf("host is nil")}if connector == nil {- return nil, fmt.Errorf("mcp connector is nil")+ return nil, fmt.Errorf("backend connector is nil")}if observer == nil {observer = NopObserver{}}- s := &A2AService{host: h, observer: observer, mcp: connector, gate: AllowAllGate{}}+ s := &A2AService{host: h, observer: observer, backend: connector, gate: AllowAllGate{}}for _, o := range opts {o(s)}@@ -207,12 +207,12 @@ func Execute(ctx context.Context, h host.Host, req ExecuteRequest, observer Obseif strings.TrimSpace(req.Biscuit) == "" {return nil, fmt.Errorf("biscuit token is required")}- payload := []byte(strings.TrimSpace(string(req.MCPRequest)))+ payload := []byte(strings.TrimSpace(string(req.Request)))if len(payload) == 0 {- return nil, fmt.Errorf("mcp request is required")+ return nil, fmt.Errorf("json-rpc request is required")}if _, err := jsonrpc.DecodeMessage(payload); err != nil {- return nil, fmt.Errorf("invalid mcp request JSON-RPC payload: %w", err)+ return nil, fmt.Errorf("invalid A2A JSON-RPC payload: %w", err)}if observer == nil {@@ -353,7 +353,7 @@ func (s *A2AService) handleStream(stream network.Stream) {}// Identity gate: verify the requester's PeerID is allowed in this federation- // before forwarding any payload to the local MCP backend.+ // before forwarding any payload to the local agent backend.authCtx := withAuthenticatedPassportClaims(context.Background(), claims)if err := s.gate.Allow(authCtx, peerID, strings.TrimSpace(header.Capability)); err != nil {fail(FailureTypeProtocol, fmt.Errorf("federation gate denied peer %s: %w", peerID, err))@@ -382,25 +382,25 @@ func (s *A2AService) handleStream(stream network.Stream) {return}- transport, err := s.mcp.Open(context.Background())+ transport, err := s.backend.Open(context.Background())if err != nil {- fail(FailureTypeInternal, fmt.Errorf("opening local MCP transport: %w", err))+ fail(FailureTypeInternal, fmt.Errorf("opening local backend transport: %w", err))return}conn, err := transport.Connect(context.Background())if err != nil {- fail(FailureTypeInternal, fmt.Errorf("connecting local MCP transport: %w", err))+ fail(FailureTypeInternal, fmt.Errorf("connecting local backend transport: %w", err))return}defer func() { _ = conn.Close() }()if err := conn.Write(context.Background(), msg); err != nil {- fail(FailureTypeInternal, fmt.Errorf("writing local MCP request: %w", err))+ fail(FailureTypeInternal, fmt.Errorf("writing local backend request: %w", err))return}respMsg, err := conn.Read(context.Background())if err != nil {- fail(FailureTypeInternal, fmt.Errorf("reading local MCP response: %w", err))+ fail(FailureTypeInternal, fmt.Errorf("reading local backend response: %w", err))return}respBytes, err := jsonrpc.EncodeMessage(respMsg)diff --git a/pkg/protocol/a2a/a2a_test.go b/pkg/protocol/a2a/a2a_test.goindex 5d720fbe..a39cae82 100644--- a/pkg/protocol/a2a/a2a_test.go+++ b/pkg/protocol/a2a/a2a_test.go@@ -150,10 +150,10 @@ func TestExecuteSuccessRecordsObserver(t *testing.T) {t.Fatalf("SetLocalPassport(client) error = %v", err)}resp, err := Execute(ctx, clientHost, ExecuteRequest{- Target: peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()},- Biscuit: "test-biscuit",- Payment: economy.Micropayment{Amount: 1, Asset: "sam-credit", Nonce: "n-1"},- MCPRequest: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"ping"}}`),+ Target: peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()},+ Biscuit: "test-biscuit",+ Payment: economy.Micropayment{Amount: 1, Asset: "sam-credit", Nonce: "n-1"},+ Request: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"ping"}}`),}, clientObserver)if err != nil {t.Fatalf("Execute() error = %v", err)@@ -202,10 +202,10 @@ func TestExecuteReturnsLivenessErrorWhenPeerDown(t *testing.T) {t.Fatalf("SetLocalPassport() error = %v", err)}_, err = Execute(ctx, clientHost, ExecuteRequest{- Target: target,- Biscuit: "test-biscuit",- Payment: economy.Micropayment{Amount: 1, Asset: "sam-credit", Nonce: "n-2"},- MCPRequest: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"ping"}}`),+ Target: target,+ Biscuit: "test-biscuit",+ Payment: economy.Micropayment{Amount: 1, Asset: "sam-credit", Nonce: "n-2"},+ Request: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"ping"}}`),}, clientObserver)if err == nil {t.Fatalf("Execute() error = nil, want liveness error")diff --git a/pkg/protocol/a2a/agent_card_adapter.go b/pkg/protocol/a2a/agent_card_adapter.gonew file mode 100644index 00000000..317a7118--- /dev/null+++ b/pkg/protocol/a2a/agent_card_adapter.go@@ -0,0 +1,236 @@+// 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 a2a++import (+ "fmt"+ "sort"+ "strings"+ "time"++ mcpprotocol "sam/pkg/protocol/mcp"++ a2asdk "github.com/a2aproject/a2a-go/v2/a2a"++ "sam/pkg/protocol/discovery"+)++const protocolPayloadName = "a2a"++// ToA2ACard converts a generic discovery AgentCard into the official A2A SDK representation.+func ToA2ACard(card *discovery.AgentCard, interfaceURL string) (*a2asdk.AgentCard, error) {+ if card == nil {+ return nil, fmt.Errorf("agent card is nil")+ }+ if strings.TrimSpace(card.Version) == "" {+ return nil, fmt.Errorf("card version is required")+ }+ if strings.TrimSpace(card.Name) == "" {+ return nil, fmt.Errorf("card name is required")+ }+ if strings.TrimSpace(card.PeerID) == "" {+ return nil, fmt.Errorf("card peer ID is required")+ }+ if len(card.Capabilities) == 0 {+ return nil, fmt.Errorf("at least one capability is required")+ }++ out, _ := synthesizeA2ACard(card)+ if err := card.DecodeProtocolPayload(protocolPayloadName, &out); err == nil {+ out = normalizeA2ASDKCard(out)+ }+ if strings.TrimSpace(interfaceURL) != "" {+ out.SupportedInterfaces = []*a2asdk.AgentInterface{+ a2asdk.NewAgentInterface(strings.TrimSpace(interfaceURL), a2asdk.TransportProtocolJSONRPC),+ }+ }+ return &out, nil+}++// AgentCardFromA2A converts an A2A SDK AgentCard into the generic discovery AgentCard.+func AgentCardFromA2A(peerID string, card *a2asdk.AgentCard, resources []mcpprotocol.Resource) (*discovery.AgentCard, error) {+ if card == nil {+ return nil, fmt.Errorf("a2a agent card is nil")+ }+ peerID = strings.TrimSpace(peerID)+ if peerID == "" {+ return nil, fmt.Errorf("peer ID is required")+ }++ capabilities := make([]string, 0, len(card.Skills))+ for _, skill := range card.Skills {+ if id := strings.TrimSpace(skill.ID); id != "" {+ capabilities = append(capabilities, id)+ continue+ }+ if name := strings.TrimSpace(skill.Name); name != "" {+ capabilities = append(capabilities, name)+ }+ }+ if len(capabilities) == 0 {+ return nil, fmt.Errorf("a2a card must contain at least one skill")+ }++ out := &discovery.AgentCard{+ Version: discovery.AgentCardVersion,+ Name: strings.TrimSpace(card.Name),+ Description: strings.TrimSpace(card.Description),+ Capabilities: capabilitiesFromSkills(card.Skills),+ Interfaces: interfacesFromA2A(card.SupportedInterfaces),+ PeerID: peerID,+ IssuedAt: time.Now().UTC(),+ Algorithm: discovery.AgentCardSignAlgo,+ }+ if err := mcpprotocol.SetResources(out, resources); err != nil {+ return nil, err+ }+ if err := out.SetProtocolPayload(protocolPayloadName, normalizeA2ASDKCard(*card)); err != nil {+ return nil, err+ }+ return out, nil+}++func synthesizeA2ACard(card *discovery.AgentCard) (a2asdk.AgentCard, error) {+ if card == nil {+ return a2asdk.AgentCard{}, fmt.Errorf("agent card is nil")+ }+ out := a2asdk.AgentCard{+ Capabilities: a2asdk.AgentCapabilities{Streaming: true},+ Description: strings.TrimSpace(card.Description),+ Name: strings.TrimSpace(card.Name),+ Skills: skillsFromCapabilities(card.Capabilities),+ Version: discovery.AgentCardVersion,+ }+ for _, item := range card.Interfaces {+ if item.Protocol != protocolPayloadName {+ continue+ }+ binding := a2asdk.TransportProtocolJSONRPC+ if strings.TrimSpace(item.Binding) != "" {+ binding = a2asdk.TransportProtocol(strings.TrimSpace(item.Binding))+ }+ iface := a2asdk.NewAgentInterface(strings.TrimSpace(item.URL), binding)+ iface.Tenant = strings.TrimSpace(item.Tenant)+ out.SupportedInterfaces = append(out.SupportedInterfaces, iface)+ }+ return normalizeA2ASDKCard(out), nil+}++func skillsFromCapabilities(in []discovery.Capability) []a2asdk.AgentSkill {+ out := make([]a2asdk.AgentSkill, 0, len(in))+ for _, capability := range in {+ identifier := strings.TrimSpace(capability.ID)+ if identifier == "" {+ identifier = strings.TrimSpace(capability.Name)+ }+ if identifier == "" {+ continue+ }+ out = append(out, a2asdk.AgentSkill{+ ID: identifier,+ Name: strings.TrimSpace(capability.Name),+ Description: strings.TrimSpace(capability.Description),+ Tags: append([]string(nil), capability.Tags...),+ })+ }+ return normalizeSkills(out)+}++func capabilitiesFromSkills(in []a2asdk.AgentSkill) []discovery.Capability {+ out := make([]discovery.Capability, 0, len(in))+ for _, skill := range in {+ identifier := strings.TrimSpace(skill.ID)+ name := strings.TrimSpace(skill.Name)+ if identifier == "" {+ identifier = name+ }+ if name == "" {+ name = identifier+ }+ if identifier == "" {+ continue+ }+ out = append(out, discovery.Capability{+ ID: identifier,+ Name: name,+ Description: strings.TrimSpace(skill.Description),+ Tags: append([]string(nil), skill.Tags...),+ })+ }+ return out+}++func interfacesFromA2A(in []*a2asdk.AgentInterface) []discovery.Interface {+ out := make([]discovery.Interface, 0, len(in))+ for _, item := range in {+ if item == nil {+ continue+ }+ out = append(out, discovery.Interface{+ Protocol: protocolPayloadName,+ URL: strings.TrimSpace(item.URL),+ Binding: string(item.ProtocolBinding),+ Tenant: strings.TrimSpace(item.Tenant),+ })+ }+ return out+}++func normalizeA2ASDKCard(card a2asdk.AgentCard) a2asdk.AgentCard {+ card.Skills = normalizeSkills(card.Skills)+ card.SupportedInterfaces = normalizeInterfaces(card.SupportedInterfaces)+ card.Signatures = nil+ return card+}++func normalizeSkills(skills []a2asdk.AgentSkill) []a2asdk.AgentSkill {+ cloned := append([]a2asdk.AgentSkill(nil), skills...)+ for index := range cloned {+ cloned[index].ID = strings.TrimSpace(cloned[index].ID)+ cloned[index].Name = strings.TrimSpace(cloned[index].Name)+ cloned[index].Description = strings.TrimSpace(cloned[index].Description)+ sort.Strings(cloned[index].Tags)+ sort.Strings(cloned[index].Examples)+ sort.Strings(cloned[index].InputModes)+ sort.Strings(cloned[index].OutputModes)+ }+ sort.Slice(cloned, func(i, j int) bool {+ if cloned[i].ID == cloned[j].ID {+ return cloned[i].Name < cloned[j].Name+ }+ return cloned[i].ID < cloned[j].ID+ })+ return cloned+}++func normalizeInterfaces(in []*a2asdk.AgentInterface) []*a2asdk.AgentInterface {+ cloned := make([]*a2asdk.AgentInterface, 0, len(in))+ for _, item := range in {+ if item == nil {+ continue+ }+ copyItem := *item+ copyItem.URL = strings.TrimSpace(copyItem.URL)+ copyItem.Tenant = strings.TrimSpace(copyItem.Tenant)+ cloned = append(cloned, ©Item)+ }+ sort.Slice(cloned, func(i, j int) bool {+ if cloned[i].URL == cloned[j].URL {+ return cloned[i].Tenant < cloned[j].Tenant+ }+ return cloned[i].URL < cloned[j].URL+ })+ return cloned+}diff --git a/pkg/protocol/discovery/agent_card_a2a_test.go b/pkg/protocol/a2a/agent_card_adapter_test.gosimilarity index 58%rename from pkg/protocol/discovery/agent_card_a2a_test.gorename to pkg/protocol/a2a/agent_card_adapter_test.goindex 1fa38b10..dc9176e9 100644--- a/pkg/protocol/discovery/agent_card_a2a_test.go+++ b/pkg/protocol/a2a/agent_card_adapter_test.go@@ -12,17 +12,17 @@// See the License for the specific language governing permissions and// limitations under the License.-package discovery_test+package a2aimport ("testing"- "time"- "github.com/a2aproject/a2a-go/v2/a2a"+ a2asdk "github.com/a2aproject/a2a-go/v2/a2a""github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer"- protocol "sam/pkg/protocol/discovery"+ "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")func TestToA2ACard(t *testing.T) {@@ -35,22 +35,22 @@ func TestToA2ACard(t *testing.T) {t.Fatalf("IDFromPrivateKey() error = %v", err)}- card, err := protocol.NewAgentCard(+ card, err := discovery.NewAgentCard(pid,[]string{"inference", "search"},- []protocol.MCPResource{{Name: "mcp", Kind: "tool"}},priv,+ mcpprotocol.WithResources([]mcpprotocol.Resource{{Name: "mcp", Kind: "tool"}}),)if err != nil {t.Fatalf("NewAgentCard() error = %v", err)}- a2aCard, err := card.ToA2ACard("https://example.com/a2a")+ a2aCard, err := ToA2ACard(card, "https://example.com/a2a")if err != nil {t.Fatalf("ToA2ACard() error = %v", err)}- if a2aCard.Version != card.Version {- t.Fatalf("a2a version = %q, want %q", a2aCard.Version, card.Version)+ if a2aCard.Version != discovery.AgentCardVersion {+ t.Fatalf("a2a version = %q, want %q", a2aCard.Version, discovery.AgentCardVersion)}if len(a2aCard.Skills) != 2 {t.Fatalf("len(skills) = %d, want 2", len(a2aCard.Skills))@@ -61,29 +61,39 @@ func TestToA2ACard(t *testing.T) {}func TestAgentCardFromA2A(t *testing.T) {- a2aCard := &a2a.AgentCard{- SupportedInterfaces: []*a2a.AgentInterface{a2a.NewAgentInterface("https://example.com/a2a", a2a.TransportProtocolJSONRPC)},- Capabilities: a2a.AgentCapabilities{Streaming: true},+ a2aCard := &a2asdk.AgentCard{+ SupportedInterfaces: []*a2asdk.AgentInterface{a2asdk.NewAgentInterface("https://example.com/a2a", a2asdk.TransportProtocolJSONRPC)},+ Capabilities: a2asdk.AgentCapabilities{Streaming: true},DefaultInputModes: []string{"application/json"},DefaultOutputModes: []string{"application/json"},Description: "test",Name: "test-agent",- Skills: []a2a.AgentSkill{+ Skills: []a2asdk.AgentSkill{{ID: "inference", Name: "Inference", Description: "run inference", Tags: []string{"sam"}},},Version: "a2a.v1",}- card, err := protocol.AgentCardFromA2A("12D3KooWQK6Jk5hY5YAL3mVyYBVN1w8w5kZdeMNF8f9mJ5JPgX5R", a2aCard, nil)+ card, err := AgentCardFromA2A("12D3KooWQK6Jk5hY5YAL3mVyYBVN1w8w5kZdeMNF8f9mJ5JPgX5R", a2aCard, nil)if err != nil {t.Fatalf("AgentCardFromA2A() error = %v", err)}+ var stored a2asdk.AgentCard+ if err := card.DecodeProtocolPayload(protocolPayloadName, &stored); err != nil {+ t.Fatalf("DecodeProtocolPayload() error = %v", err)+ }+ if stored.Name != a2aCard.Name {+ t.Fatalf("stored protocol payload name = %q, want %q", stored.Name, a2aCard.Name)+ }+ resources := mcpprotocol.ResourcesFromCard(card)+ if len(resources) != 0 {+ t.Fatalf("len(resources) = %d, want 0", len(resources))+ }capabilities := card.CapabilityNames()if len(capabilities) != 1 || capabilities[0] != "inference" {t.Fatalf("capabilities = %#v, want [inference]", capabilities)}- card.IssuedAt = time.Now().UTC()- if card.Algorithm != protocol.AgentCardSignAlgo {- t.Fatalf("algorithm = %q, want %q", card.Algorithm, protocol.AgentCardSignAlgo)+ if card.Algorithm != discovery.AgentCardSignAlgo {+ t.Fatalf("algorithm = %q, want %q", card.Algorithm, discovery.AgentCardSignAlgo)}}diff --git a/pkg/protocol/discovery/agent_card.go b/pkg/protocol/discovery/agent_card.goindex 39bdd237..b6119441 100644--- a/pkg/protocol/discovery/agent_card.go+++ b/pkg/protocol/discovery/agent_card.go@@ -15,7 +15,7 @@package discoveryimport (- "cmp"+ "bytes""encoding/base64""encoding/json""fmt"@@ -23,7 +23,6 @@ import ("strings""time"- "github.com/a2aproject/a2a-go/v2/a2a""github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer")@@ -34,36 +33,58 @@ const (AgentDHTNamespaceBase = "/sam/v1/agents/")-// MCPResource describes an MCP-compatible tool or data source advertised by an agent.-type MCPResource struct {- Name string `json:"name"`- Kind string `json:"kind"`- Endpoint string `json:"endpoint,omitempty"`- Description string `json:"description,omitempty"`+// CardOption lets protocol packages enrich generic discovery cards without+// leaking protocol-specific fields into discovery itself.+type CardOption func(*AgentCard) error++// Capability describes a normalized capability advertised by an agent.+type Capability struct {+ ID string `json:"id"`+ Name string `json:"name,omitempty"`+ Description string `json:"description,omitempty"`+ Tags []string `json:"tags,omitempty"`+}++// Interface describes a protocol endpoint injected by a protocol-specific adapter.+type Interface struct {+ Protocol string `json:"protocol"`+ URL string `json:"url"`+ Binding string `json:"binding,omitempty"`+ Tenant string `json:"tenant,omitempty"`+ Description string `json:"description,omitempty"`+ Metadata map[string]string `json:"metadata,omitempty"`}// AgentCard is the signed capability document advertised in the SAM mesh.//// The signature covers all fields except Signature.type AgentCard struct {- a2a.AgentCard- PeerID string `json:"peer_id"`- Resources []MCPResource `json:"resources"`- IssuedAt time.Time `json:"issued_at"`- Algorithm string `json:"alg"`- Signature string `json:"signature"`+ Version string `json:"version"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ Capabilities []Capability `json:"capabilities"`+ Interfaces []Interface `json:"interfaces,omitempty"`+ Protocols map[string]json.RawMessage `json:"protocols,omitempty"`+ PeerID string `json:"peer_id"`+ IssuedAt time.Time `json:"issued_at"`+ Algorithm string `json:"alg"`+ Signature string `json:"signature"`}type agentCardPayload struct {- AgentCard a2a.AgentCard `json:"agent_card"`- PeerID string `json:"peer_id"`- Resources []MCPResource `json:"resources"`- IssuedAt time.Time `json:"issued_at"`- Algorithm string `json:"alg"`+ Version string `json:"version"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ Capabilities []Capability `json:"capabilities"`+ Interfaces []Interface `json:"interfaces,omitempty"`+ Protocols map[string]json.RawMessage `json:"protocols,omitempty"`+ PeerID string `json:"peer_id"`+ IssuedAt time.Time `json:"issued_at"`+ Algorithm string `json:"alg"`}// NewAgentCard builds and signs an AgentCard for DHT advertisement.-func NewAgentCard(peerID peer.ID, capabilities []string, resources []MCPResource, privateKey crypto.PrivKey) (*AgentCard, error) {+func NewAgentCard(peerID peer.ID, capabilities []string, privateKey crypto.PrivKey, opts ...CardOption) (*AgentCard, error) {if privateKey == nil {return nil, fmt.Errorf("private key is required")}@@ -74,9 +95,9 @@ func NewAgentCard(peerID peer.ID, capabilities []string, resources []MCPResourceif len(normalizedCaps) == 0 {return nil, fmt.Errorf("at least one capability is required")}- skills := make([]a2a.AgentSkill, 0, len(normalizedCaps))+ descriptors := make([]Capability, 0, len(normalizedCaps))for _, capability := range normalizedCaps {- skills = append(skills, a2a.AgentSkill{+ descriptors = append(descriptors, Capability{ID: capability,Name: capability,Description: "SAM capability " + capability,@@ -85,21 +106,16 @@ func NewAgentCard(peerID peer.ID, capabilities []string, resources []MCPResource}card := &AgentCard{- AgentCard: a2a.AgentCard{- Capabilities: a2a.AgentCapabilities{- Streaming: true,- },- DefaultInputModes: []string{"application/json"},- DefaultOutputModes: []string{"application/json"},- Description: "SAM agent " + peerID.String(),- Name: "sam-agent-" + peerID.String(),- Skills: skills,- Version: AgentCardVersion,- },- PeerID: peerID.String(),- Resources: normalizeResources(resources),- IssuedAt: time.Now().UTC(),- Algorithm: AgentCardSignAlgo,+ Version: AgentCardVersion,+ Name: "sam-agent-" + peerID.String(),+ Description: "SAM agent " + peerID.String(),+ Capabilities: descriptors,+ PeerID: peerID.String(),+ IssuedAt: time.Now().UTC(),+ Algorithm: AgentCardSignAlgo,+ }+ if err := ApplyCardOptions(card, opts...); err != nil {+ return nil, err}if err := SignAgentCard(card, privateKey); err != nil {@@ -198,7 +214,7 @@ func (c *AgentCard) validateBase() error {if _, err := peer.Decode(c.PeerID); err != nil {return fmt.Errorf("invalid peer ID %q: %w", c.PeerID, err)}- if len(c.Skills) == 0 {+ if len(c.Capabilities) == 0 {return fmt.Errorf("at least one capability is required")}if c.IssuedAt.IsZero() {@@ -207,16 +223,27 @@ func (c *AgentCard) validateBase() error {if strings.TrimSpace(c.Algorithm) == "" {return fmt.Errorf("signature algorithm is required")}+ if _, err := normalizeProtocolPayloads(c.Protocols); err != nil {+ return err+ }return nil}func (c *AgentCard) signingPayload() ([]byte, error) {+ protocols, err := normalizeProtocolPayloads(c.Protocols)+ if err != nil {+ return nil, err+ }p := agentCardPayload{- AgentCard: normalizeA2ACard(c.AgentCard),- PeerID: c.PeerID,- Resources: normalizeResources(c.Resources),- IssuedAt: c.IssuedAt.UTC(),- Algorithm: c.Algorithm,+ Version: strings.TrimSpace(c.Version),+ Name: strings.TrimSpace(c.Name),+ Description: strings.TrimSpace(c.Description),+ Capabilities: normalizeCapabilityDescriptors(c.Capabilities),+ Interfaces: normalizeInterfaces(c.Interfaces),+ Protocols: protocols,+ PeerID: c.PeerID,+ IssuedAt: c.IssuedAt.UTC(),+ Algorithm: c.Algorithm,}return json.Marshal(p)}@@ -226,11 +253,11 @@ func (c *AgentCard) CapabilityNames() []string {if c == nil {return nil}- names := make([]string, 0, len(c.Skills))- for _, skill := range c.Skills {- name := strings.TrimSpace(skill.ID)+ names := make([]string, 0, len(c.Capabilities))+ for _, capability := range c.Capabilities {+ name := strings.TrimSpace(capability.ID)if name == "" {- name = strings.TrimSpace(skill.Name)+ name = strings.TrimSpace(capability.Name)}if name != "" {names = append(names, name)@@ -239,6 +266,101 @@ func (c *AgentCard) CapabilityNames() []string {return normalizeCapabilities(names)}+// SetProtocolPayload stores a protocol-specific payload in canonical JSON form.+func (c *AgentCard) SetProtocolPayload(name string, payload any) error {+ if c == nil {+ return fmt.Errorf("agent card is nil")+ }+ raw, err := json.Marshal(payload)+ if err != nil {+ return fmt.Errorf("encoding protocol payload %q: %w", name, err)+ }+ return c.SetProtocolRawPayload(name, raw)+}++// SetProtocolRawPayload stores a raw protocol payload after compacting it.+func (c *AgentCard) SetProtocolRawPayload(name string, payload []byte) error {+ if c == nil {+ return fmt.Errorf("agent card is nil")+ }+ name = strings.ToLower(strings.TrimSpace(name))+ if name == "" {+ return fmt.Errorf("protocol name is required")+ }+ var compact bytes.Buffer+ if err := json.Compact(&compact, payload); err != nil {+ return fmt.Errorf("protocol payload %q must be valid JSON: %w", name, err)+ }+ if c.Protocols == nil {+ c.Protocols = make(map[string]json.RawMessage, 1)+ }+ c.Protocols[name] = append(json.RawMessage(nil), compact.Bytes()...)+ return nil+}++// DecodeProtocolPayload decodes a protocol-specific payload into out.+func (c *AgentCard) DecodeProtocolPayload(name string, out any) error {+ if c == nil {+ return fmt.Errorf("agent card is nil")+ }+ name = strings.ToLower(strings.TrimSpace(name))+ raw := c.Protocols[name]+ if len(raw) == 0 {+ return fmt.Errorf("protocol payload %q not found", name)+ }+ if err := json.Unmarshal(raw, out); err != nil {+ return fmt.Errorf("decoding protocol payload %q: %w", name, err)+ }+ return nil+}++// ApplyCardOptions applies protocol-owned hooks to the card.+func ApplyCardOptions(card *AgentCard, opts ...CardOption) error {+ if card == nil {+ return fmt.Errorf("agent card is nil")+ }+ for _, opt := range opts {+ if opt == nil {+ continue+ }+ if err := opt(card); err != nil {+ return err+ }+ }+ return nil+}++// WithName overrides the generic display name in the discovery card.+func WithName(name string) CardOption {+ return func(card *AgentCard) error {+ card.Name = strings.TrimSpace(name)+ return nil+ }+}++// WithDescription overrides the generic description in the discovery card.+func WithDescription(description string) CardOption {+ return func(card *AgentCard) error {+ card.Description = strings.TrimSpace(description)+ return nil+ }+}++// WithInterface appends a generic protocol interface advertisement.+func WithInterface(iface Interface) CardOption {+ return func(card *AgentCard) error {+ card.Interfaces = append(card.Interfaces, iface)+ return nil+ }+}++// WithProtocolPayload stores protocol-specific metadata in the card.+func WithProtocolPayload(name string, payload any) CardOption {+ return func(card *AgentCard) error {+ return card.SetProtocolPayload(name, payload)+ }+}+func normalizeCapabilities(capabilities []string) []string {seen := make(map[string]struct{}, len(capabilities))out := make([]string, 0, len(capabilities))@@ -257,70 +379,82 @@ func normalizeCapabilities(capabilities []string) []string {return out}-func normalizeResources(resources []MCPResource) []MCPResource {- out := make([]MCPResource, 0, len(resources))- for _, r := range resources {- r.Name = strings.TrimSpace(r.Name)- r.Kind = strings.TrimSpace(r.Kind)- r.Endpoint = strings.TrimSpace(r.Endpoint)- r.Description = strings.TrimSpace(r.Description)- if r.Name == "" {+func normalizeCapabilityDescriptors(in []Capability) []Capability {+ cloned := make([]Capability, 0, len(in))+ for _, capability := range in {+ capability.ID = strings.ToLower(strings.TrimSpace(capability.ID))+ capability.Name = strings.TrimSpace(capability.Name)+ capability.Description = strings.TrimSpace(capability.Description)+ if capability.ID == "" {+ capability.ID = strings.ToLower(strings.TrimSpace(capability.Name))+ }+ if capability.Name == "" {+ capability.Name = capability.ID+ }+ if capability.ID == "" {continue}- out = append(out, r)- }- sort.Slice(out, func(i, j int) bool {- if out[i].Name == out[j].Name {- return out[i].Kind < out[j].Kind+ for index := range capability.Tags {+ capability.Tags[index] = strings.TrimSpace(capability.Tags[index])}- return out[i].Name < out[j].Name- })- return out-}--func normalizeA2ACard(card a2a.AgentCard) a2a.AgentCard {- card.Skills = normalizeSkills(card.Skills)- card.SupportedInterfaces = normalizeInterfaces(card.SupportedInterfaces)- card.Signatures = nil- return card-}--func normalizeSkills(skills []a2a.AgentSkill) []a2a.AgentSkill {- cloned := append([]a2a.AgentSkill(nil), skills...)- for index := range cloned {- cloned[index].ID = strings.TrimSpace(cloned[index].ID)- cloned[index].Name = strings.TrimSpace(cloned[index].Name)- cloned[index].Description = strings.TrimSpace(cloned[index].Description)- sort.Strings(cloned[index].Tags)- sort.Strings(cloned[index].Examples)- sort.Strings(cloned[index].InputModes)- sort.Strings(cloned[index].OutputModes)+ capability.Tags = normalizeCapabilities(capability.Tags)+ cloned = append(cloned, capability)}sort.Slice(cloned, func(i, j int) bool {- return cmp.Or(- strings.Compare(cloned[i].ID, cloned[j].ID),- strings.Compare(cloned[i].Name, cloned[j].Name),- ) < 0+ if cloned[i].ID == cloned[j].ID {+ return cloned[i].Name < cloned[j].Name+ }+ return cloned[i].ID < cloned[j].ID})return cloned}-func normalizeInterfaces(in []*a2a.AgentInterface) []*a2a.AgentInterface {- cloned := make([]*a2a.AgentInterface, 0, len(in))+func normalizeInterfaces(in []Interface) []Interface {+ cloned := make([]Interface, 0, len(in))for _, item := range in {- if item == nil {+ item.Protocol = strings.ToLower(strings.TrimSpace(item.Protocol))+ item.URL = strings.TrimSpace(item.URL)+ item.Binding = strings.TrimSpace(item.Binding)+ item.Tenant = strings.TrimSpace(item.Tenant)+ item.Description = strings.TrimSpace(item.Description)+ if item.Protocol == "" || item.URL == "" {continue}- copyItem := *item- copyItem.URL = strings.TrimSpace(copyItem.URL)- copyItem.Tenant = strings.TrimSpace(copyItem.Tenant)- cloned = append(cloned, ©Item)+ if len(item.Metadata) == 0 {+ item.Metadata = nil+ }+ cloned = append(cloned, item)}sort.Slice(cloned, func(i, j int) bool {- return cmp.Or(- strings.Compare(cloned[i].URL, cloned[j].URL),- strings.Compare(string(cloned[i].ProtocolBinding), string(cloned[j].ProtocolBinding)),- ) < 0+ if cloned[i].Protocol == cloned[j].Protocol {+ if cloned[i].URL == cloned[j].URL {+ return cloned[i].Binding < cloned[j].Binding+ }+ return cloned[i].URL < cloned[j].URL+ }+ return cloned[i].Protocol < cloned[j].Protocol})return cloned}++func normalizeProtocolPayloads(in map[string]json.RawMessage) (map[string]json.RawMessage, error) {+ if len(in) == 0 {+ return nil, nil+ }+ out := make(map[string]json.RawMessage, len(in))+ for name, payload := range in {+ name = strings.ToLower(strings.TrimSpace(name))+ if name == "" || len(payload) == 0 {+ continue+ }+ var compact bytes.Buffer+ if err := json.Compact(&compact, payload); err != nil {+ return nil, fmt.Errorf("protocol payload %q must be valid JSON: %w", name, err)+ }+ out[name] = append(json.RawMessage(nil), compact.Bytes()...)+ }+ if len(out) == 0 {+ return nil, nil+ }+ return out, nil+}diff --git a/pkg/protocol/discovery/agent_card_a2a.go b/pkg/protocol/discovery/agent_card_a2a.godeleted file mode 100644index 8c38d332..00000000--- a/pkg/protocol/discovery/agent_card_a2a.go+++ /dev/null@@ -1,78 +0,0 @@-// 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 discovery--import (- "fmt"- "strings"-- "github.com/a2aproject/a2a-go/v2/a2a"-)--// ToA2ACard converts a SAM AgentCard to the official A2A SDK representation.-//-// interfaceURL should point to the remote endpoint where this agent accepts-// A2A requests. It is used to populate AgentCard.SupportedInterfaces.-func (c *AgentCard) ToA2ACard(interfaceURL string) (*a2a.AgentCard, error) {- if c == nil {- return nil, fmt.Errorf("agent card is nil")- }- if err := c.validateBase(); err != nil {- return nil, err- }- out := normalizeA2ACard(c.AgentCard)- if strings.TrimSpace(interfaceURL) != "" {- out.SupportedInterfaces = []*a2a.AgentInterface{- a2a.NewAgentInterface(interfaceURL, a2a.TransportProtocolJSONRPC),- }- }- return &out, nil-}--// AgentCardFromA2A converts an A2A SDK AgentCard into the local SAM AgentCard.-//-// peerID must be provided by the SAM node identity layer and becomes the-// signature identity for the resulting card.-func AgentCardFromA2A(peerID string, card *a2a.AgentCard, resources []MCPResource) (*AgentCard, error) {- if card == nil {- return nil, fmt.Errorf("a2a agent card is nil")- }- peerID = strings.TrimSpace(peerID)- if peerID == "" {- return nil, fmt.Errorf("peer ID is required")- }-- capabilities := make([]string, 0, len(card.Skills))- for _, skill := range card.Skills {- if strings.TrimSpace(skill.ID) != "" {- capabilities = append(capabilities, skill.ID)- continue- }- if strings.TrimSpace(skill.Name) != "" {- capabilities = append(capabilities, skill.Name)- }- }-- out := &AgentCard{- AgentCard: normalizeA2ACard(*card),- PeerID: peerID,- Resources: normalizeResources(resources),- Algorithm: AgentCardSignAlgo,- }- if len(capabilities) == 0 {- return nil, fmt.Errorf("a2a card must contain at least one skill")- }- return out, nil-}diff --git a/pkg/protocol/discovery/agent_card_test.go b/pkg/protocol/discovery/agent_card_test.goindex 1eed8377..05dfd7a9 100644--- a/pkg/protocol/discovery/agent_card_test.go+++ b/pkg/protocol/discovery/agent_card_test.go@@ -18,11 +18,11 @@ import ("testing""time"- "github.com/a2aproject/a2a-go/v2/a2a""github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer"protocol "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")func TestAgentCardSignVerify(t *testing.T) {@@ -38,8 +38,8 @@ func TestAgentCardSignVerify(t *testing.T) {card, err := protocol.NewAgentCard(pid,[]string{"Inference", "search", "search"},- []protocol.MCPResource{{Name: "local-mcp", Kind: "tool", Endpoint: "unix:///tmp/mcp.sock"}},priv,+ mcpprotocol.WithResources([]mcpprotocol.Resource{{Name: "local-mcp", Kind: "tool", Endpoint: "unix:///tmp/mcp.sock"}}),)if err != nil {t.Fatalf("NewAgentCard() error = %v", err)@@ -68,16 +68,15 @@ func TestAgentCardVerifyRejectsTamper(t *testing.T) {card, err := protocol.NewAgentCard(pid,[]string{"inference"},- nil,priv,)if err != nil {t.Fatalf("NewAgentCard() error = %v", err)}- card.Skills = append(card.Skills, card.Skills[0])- card.Skills[1].ID = "search"- card.Skills[1].Name = "search"+ card.Capabilities = append(card.Capabilities, card.Capabilities[0])+ card.Capabilities[1].ID = "search"+ card.Capabilities[1].Name = "search"if err := protocol.VerifyAgentCard(card); err == nil {t.Fatal("VerifyAgentCard() should fail for tampered card")}@@ -94,11 +93,12 @@ func TestAgentCardVerifyRejectsMissingSignature(t *testing.T) {}card := &protocol.AgentCard{- AgentCard: a2a.AgentCard{- Name: "sam-agent-" + pid.String(),- Skills: []a2a.AgentSkill{{ID: "inference", Name: "inference"}},- Version: protocol.AgentCardVersion,- },+ Version: protocol.AgentCardVersion,+ Name: "sam-agent-" + pid.String(),+ Capabilities: []protocol.Capability{{+ ID: "inference",+ Name: "inference",+ }},PeerID: pid.String(),IssuedAt: time.Now().UTC(),Algorithm: protocol.AgentCardSignAlgo,diff --git a/pkg/protocol/discovery/discovery_test.go b/pkg/protocol/discovery/discovery_test.goindex 1f6eed54..1d9566aa 100644--- a/pkg/protocol/discovery/discovery_test.go+++ b/pkg/protocol/discovery/discovery_test.go@@ -88,7 +88,7 @@ func TestDiscoverReturnsVerifiedCards(t *testing.T) {defer func() { _ = consumerHost.Close() }()providerPriv := providerHost.Peerstore().PrivKey(providerHost.ID())- card, err := protocol.NewAgentCard(providerHost.ID(), []string{"inference"}, nil, providerPriv)+ card, err := protocol.NewAgentCard(providerHost.ID(), []string{"inference"}, providerPriv)if err != nil {t.Fatalf("NewAgentCard() error = %v", err)}@@ -238,7 +238,7 @@ func TestDiscoverPrefersDHTCard(t *testing.T) {t.Fatalf("IDFromPrivateKey() error = %v", err)}- card, err := protocol.NewAgentCard(providerID, []string{"inference"}, nil, priv)+ card, err := protocol.NewAgentCard(providerID, []string{"inference"}, priv)if err != nil {t.Fatalf("NewAgentCard() error = %v", err)}@@ -293,7 +293,7 @@ func TestDiscoverFallsBackToStreamWhenDHTCardInvalid(t *testing.T) {defer func() { _ = consumerHost.Close() }()providerPriv := providerHost.Peerstore().PrivKey(providerHost.ID())- card, err := protocol.NewAgentCard(providerHost.ID(), []string{"inference"}, nil, providerPriv)+ card, err := protocol.NewAgentCard(providerHost.ID(), []string{"inference"}, providerPriv)if err != nil {t.Fatalf("NewAgentCard() error = %v", err)}@@ -351,7 +351,7 @@ func TestDiscoverAllowsStaleDHTCardWhenMaxAgeDisabled(t *testing.T) {t.Fatalf("IDFromPrivateKey() error = %v", err)}- card, err := protocol.NewAgentCard(providerID, []string{"inference"}, nil, priv)+ card, err := protocol.NewAgentCard(providerID, []string{"inference"}, priv)if err != nil {t.Fatalf("NewAgentCard() error = %v", err)}diff --git a/pkg/protocol/discovery/publish_test.go b/pkg/protocol/discovery/publish_test.goindex 604dc9aa..61af9dcc 100644--- a/pkg/protocol/discovery/publish_test.go+++ b/pkg/protocol/discovery/publish_test.go@@ -62,7 +62,7 @@ func TestPublisherPublishesPeerAndCapabilityNamespaces(t *testing.T) {t.Fatalf("IDFromPrivateKey() error = %v", err)}- card, err := protocol.NewAgentCard(pid, []string{"inference", "search"}, nil, priv)+ card, err := protocol.NewAgentCard(pid, []string{"inference", "search"}, priv)if err != nil {t.Fatalf("NewAgentCard() error = %v", err)}@@ -109,7 +109,7 @@ func TestPublisherRejectsPeerMismatch(t *testing.T) {t.Fatalf("IDFromPrivateKey() error = %v", err)}- card, err := protocol.NewAgentCard(pidA, []string{"inference"}, nil, privA)+ card, err := protocol.NewAgentCard(pidA, []string{"inference"}, privA)if err != nil {t.Fatalf("NewAgentCard() error = %v", err)}diff --git a/pkg/protocol/mcp/agent_card_adapter.go b/pkg/protocol/mcp/agent_card_adapter.gonew file mode 100644index 00000000..87137ac1--- /dev/null+++ b/pkg/protocol/mcp/agent_card_adapter.go@@ -0,0 +1,88 @@+// 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 mcp++import (+ "sort"+ "strings"++ "sam/pkg/protocol/discovery"+)++const cardProtocolName = "mcp"++// Resource describes an MCP-compatible tool or data source advertised by an agent.+type Resource struct {+ Name string `json:"name"`+ Kind string `json:"kind"`+ Endpoint string `json:"endpoint,omitempty"`+ Description string `json:"description,omitempty"`+}++type cardMetadata struct {+ Resources []Resource `json:"resources,omitempty"`+}++// WithResources attaches MCP-specific resource metadata to a generic discovery card.+func WithResources(resources []Resource) discovery.CardOption {+ return func(card *discovery.AgentCard) error {+ return SetResources(card, resources)+ }+}++// SetResources stores MCP resources in the card's protocol-specific payload.+func SetResources(card *discovery.AgentCard, resources []Resource) error {+ if card == nil {+ return nil+ }+ normalized := normalizeResources(resources)+ if len(normalized) == 0 {+ return nil+ }+ return card.SetProtocolPayload(cardProtocolName, cardMetadata{Resources: normalized})+}++// ResourcesFromCard extracts MCP resources from a generic discovery card.+func ResourcesFromCard(card *discovery.AgentCard) []Resource {+ if card == nil {+ return nil+ }+ var metadata cardMetadata+ if err := card.DecodeProtocolPayload(cardProtocolName, &metadata); err != nil {+ return nil+ }+ return normalizeResources(metadata.Resources)+}++func normalizeResources(resources []Resource) []Resource {+ out := make([]Resource, 0, len(resources))+ for _, resource := range resources {+ resource.Name = strings.TrimSpace(resource.Name)+ resource.Kind = strings.TrimSpace(resource.Kind)+ resource.Endpoint = strings.TrimSpace(resource.Endpoint)+ resource.Description = strings.TrimSpace(resource.Description)+ if resource.Name == "" {+ continue+ }+ out = append(out, resource)+ }+ sort.Slice(out, func(i, j int) bool {+ if out[i].Name == out[j].Name {+ return out[i].Kind < out[j].Kind+ }+ return out[i].Name < out[j].Name+ })+ return out+}diff --git a/pkg/protocol/mcp/agent_card_adapter_test.go b/pkg/protocol/mcp/agent_card_adapter_test.gonew file mode 100644index 00000000..4aa4b28a--- /dev/null+++ b/pkg/protocol/mcp/agent_card_adapter_test.go@@ -0,0 +1,54 @@+// 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 mcp++import (+ "testing"++ "github.com/libp2p/go-libp2p/core/crypto"+ "github.com/libp2p/go-libp2p/core/peer"++ "sam/pkg/protocol/discovery"+)++func TestWithResources(t *testing.T) {+ priv, _, err := crypto.GenerateEd25519Key(nil)+ if err != nil {+ t.Fatalf("GenerateEd25519Key() error = %v", err)+ }+ pid, err := peer.IDFromPrivateKey(priv)+ if err != nil {+ t.Fatalf("IDFromPrivateKey() error = %v", err)+ }+ card, err := discovery.NewAgentCard(+ pid,+ []string{"search"},+ priv,+ WithResources([]Resource{{Name: "search", Kind: "tool", Endpoint: "mcp://search"}}),+ )+ if err != nil {+ t.Fatalf("NewAgentCard() error = %v", err)+ }+ resources := ResourcesFromCard(card)+ if len(resources) != 1 {+ t.Fatalf("len(resources) = %d, want 1", len(resources))+ }+ if resources[0].Endpoint != "mcp://search" {+ t.Fatalf("resource endpoint = %q, want %q", resources[0].Endpoint, "mcp://search")+ }+ if err := discovery.VerifyAgentCard(card); err != nil {+ t.Fatalf("VerifyAgentCard() error = %v", err)+ }+}diff --git a/tests/integration/call_test.go b/tests/integration/call_test.goindex 3e00649b..a62d6367 100644--- a/tests/integration/call_test.go+++ b/tests/integration/call_test.go@@ -41,6 +41,7 @@ import (samnet "sam/pkg/net"a2aprotocol "sam/pkg/protocol/a2a"protocol "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")const (@@ -239,8 +240,8 @@ func runCallProviderRole() error {card, err := protocol.NewAgentCard(node.PeerID(),[]string{callCapability},- []protocol.MCPResource{{Name: "weather", Kind: "tool", Endpoint: "mcp://weather"}},priv,+ mcpprotocol.WithResources([]mcpprotocol.Resource{{Name: "weather", Kind: "tool", Endpoint: "mcp://weather"}}),)if err != nil {return fmt.Errorf("provider card creation: %w", err)@@ -340,7 +341,7 @@ func runCallConsumerRole() error {Nonce: "nonce-success",Capability: callCapability,},- MCPRequest: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"weather"}}`),+ Request: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"weather"}}`),}if _, err := a2aprotocol.Execute(ctx, node.Host(), req, observer); err != nil {diff --git a/tests/integration/mesh_test.go b/tests/integration/mesh_test.goindex 7375fc29..42873781 100644--- a/tests/integration/mesh_test.go+++ b/tests/integration/mesh_test.go@@ -202,8 +202,8 @@ func runMeshPublisher() error {card, err := protocol.NewAgentCard(node.PeerID(),[]string{meshCapability},- []protocol.MCPResource{{Name: "summarizer", Kind: "tool", Endpoint: "mcp://summarizer"}},priv,+ mcpprotocol.WithResources([]mcpprotocol.Resource{{Name: "summarizer", Kind: "tool", Endpoint: "mcp://summarizer"}}),)if err != nil {return fmt.Errorf("publisher card creation: %w", err)diff --git a/tests/integration/p2p_test.go b/tests/integration/p2p_test.goindex 2357b03b..0236235e 100644--- a/tests/integration/p2p_test.go+++ b/tests/integration/p2p_test.go@@ -168,8 +168,8 @@ func runProviderRole() error {card, err := protocol.NewAgentCard(node.PeerID(),[]string{capabilityName},- []protocol.MCPResource{{Name: "echo", Kind: "tool", Endpoint: "mcp://echo"}},priv,+ mcpprotocol.WithResources([]mcpprotocol.Resource{{Name: "echo", Kind: "tool", Endpoint: "mcp://echo"}}),)if err != nil {return fmt.Errorf("provider card creation: %w", err)