Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
refactor protocol
Antonio Ojeaae52ea5f8b9d
diff --git a/cmd/sam-agent/agent_discovery.go b/cmd/sam-agent/agent_discovery.goindex 3e09de51..27dfda63 100644--- a/cmd/sam-agent/agent_discovery.go+++ b/cmd/sam-agent/agent_discovery.go@@ -22,7 +22,7 @@ import ("time"samnet "sam/pkg/net"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")func newAgentDiscoverer(node samnet.Node, federation string, maxDHTCardAge time.Duration) (samnet.AgentDiscoverFunc, error) {diff --git a/cmd/sam-agent/call.go b/cmd/sam-agent/call.goindex d0994480..19e3e0b9 100644--- a/cmd/sam-agent/call.go+++ b/cmd/sam-agent/call.go@@ -29,7 +29,8 @@ import ("sam/pkg/economy""sam/pkg/identity"samnet "sam/pkg/net"- "sam/pkg/protocol"+ a2aprotocol "sam/pkg/protocol/a2a"+ protocol "sam/pkg/protocol/discovery")func newCallCmd(cfg *runConfig) *cobra.Command {@@ -99,7 +100,7 @@ func runCall(parent context.Context, cfg *runConfig, targetArg string) error {return fmt.Errorf("configuring local passport auth: %w", err)}- observer, err := protocol.NewBoltObserverWithFallback(defaultFederationID)+ observer, err := a2aprotocol.NewBoltObserverWithFallback(defaultFederationID)if err != nil {return fmt.Errorf("creating reputation observer: %w", err)}@@ -117,7 +118,7 @@ func runCall(parent context.Context, cfg *runConfig, targetArg string) error {return err}- resp, err := protocol.Execute(ctx, node.Host(), protocol.ExecuteRequest{+ resp, err := a2aprotocol.Execute(ctx, node.Host(), a2aprotocol.ExecuteRequest{Target: target,Capability: capability,Biscuit: cfg.callBiscuit,diff --git a/cmd/sam-agent/inspect.go b/cmd/sam-agent/inspect.goindex abfee1ef..21634e37 100644--- a/cmd/sam-agent/inspect.go+++ b/cmd/sam-agent/inspect.go@@ -23,7 +23,7 @@ import ("github.com/spf13/cobra""sam/pkg/economy"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")// newInspectCmd creates the "sam inspect" command for decoding SAM artifacts.diff --git a/cmd/sam-agent/mesh_get_agents.go b/cmd/sam-agent/mesh_get_agents.goindex bf058dc3..3e8faf04 100644--- a/cmd/sam-agent/mesh_get_agents.go+++ b/cmd/sam-agent/mesh_get_agents.go@@ -31,7 +31,7 @@ import ("github.com/spf13/cobra"samnet "sam/pkg/net"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")func newMeshGetAgentsCmd(cfg *runConfig) *cobra.Command {diff --git a/cmd/sam-agent/output.go b/cmd/sam-agent/output.goindex 3f38b14b..7764360d 100644--- a/cmd/sam-agent/output.go+++ b/cmd/sam-agent/output.go@@ -22,7 +22,7 @@ import ("text/tabwriter""time"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")// outputFormat controls how command results are rendered.diff --git a/cmd/sam-agent/proxy.go b/cmd/sam-agent/proxy.goindex 77ca80da..b3fc3572 100644--- a/cmd/sam-agent/proxy.go+++ b/cmd/sam-agent/proxy.go@@ -33,7 +33,9 @@ import ("sam/pkg/identity"samnet "sam/pkg/net"- "sam/pkg/protocol"+ a2aprotocol "sam/pkg/protocol/a2a"+ protocol "sam/pkg/protocol/discovery"+ httpprotocol "sam/pkg/protocol/http")func newProxyCmd(cfg *runConfig) *cobra.Command {@@ -112,7 +114,7 @@ func runProxy(parent context.Context, cfg *runConfig) error {}start := time.Now()- observer, err := protocol.NewBoltObserverWithFallback(defaultFederationID)+ observer, err := a2aprotocol.NewBoltObserverWithFallback(defaultFederationID)if err != nil {http.Error(w, "reputation observer unavailable", http.StatusInternalServerError)return@@ -146,7 +148,7 @@ func runProxy(parent context.Context, cfg *runConfig) error {body, err := io.ReadAll(r.Body)if err != nil {- observer.OnFailure(target.ID.String(), protocol.FailureTypeProtocol)+ observer.OnFailure(target.ID.String(), a2aprotocol.FailureTypeProtocol)http.Error(w, fmt.Sprintf("reading request body: %v", err), http.StatusBadRequest)return}@@ -154,7 +156,7 @@ func runProxy(parent context.Context, cfg *runConfig) error {requestHeaders := r.Header.Clone()requestHeaders.Del(cfg.proxyTargetHdr)- tunnelReq := protocol.HTTPTunnelRequest{+ tunnelReq := httpprotocol.HTTPTunnelRequest{Method: r.Method,Path: r.URL.RequestURI(),Headers: requestHeaders,@@ -169,18 +171,18 @@ func runProxy(parent context.Context, cfg *runConfig) error {_ = node.Connect(ctx, target)}- resp, err := protocol.TunnelHTTP(ctx, node.Host(), target.ID, protocol.HTTPTunnelOpenRequest{+ resp, err := httpprotocol.TunnelHTTP(ctx, node.Host(), target.ID, httpprotocol.HTTPTunnelOpenRequest{Biscuit: strings.TrimSpace(cfg.proxyBiscuit),Capability: capability,Request: tunnelReq,})if err != nil {- observer.OnFailure(target.ID.String(), protocol.FailureTypeLiveness)+ observer.OnFailure(target.ID.String(), a2aprotocol.FailureTypeLiveness)http.Error(w, fmt.Sprintf("tunnel request failed: %v", err), http.StatusBadGateway)return}if resp.Error != "" {- observer.OnFailure(target.ID.String(), protocol.FailureTypeRemote)+ observer.OnFailure(target.ID.String(), a2aprotocol.FailureTypeRemote)status := resp.StatusCodeif status == 0 {status = http.StatusBadGatewaydiff --git a/cmd/sam-agent/proxy_reserved_test.go b/cmd/sam-agent/proxy_reserved_test.goindex 418472dc..6977a2b1 100644--- a/cmd/sam-agent/proxy_reserved_test.go+++ b/cmd/sam-agent/proxy_reserved_test.go@@ -29,7 +29,7 @@ import ("sam/pkg/identity"samnet "sam/pkg/net"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")func TestExtractBearerToken(t *testing.T) {diff --git a/cmd/sam-agent/publish.go b/cmd/sam-agent/publish.goindex bed0012b..190c66fb 100644--- a/cmd/sam-agent/publish.go+++ b/cmd/sam-agent/publish.go@@ -28,7 +28,9 @@ import ("sam/pkg/economy"samnet "sam/pkg/net"- "sam/pkg/protocol"+ a2aprotocol "sam/pkg/protocol/a2a"+ protocol "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")// newPublishCmd creates the "sam publish" group command and attaches its@@ -136,7 +138,7 @@ func runPublish(parent context.Context, cfg *runConfig) error {client: &http.Client{Timeout: 30 * time.Second},addr: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),}- if _, err := protocol.NewMCPBridge(node.Host(), economy.AllowAllVerifier{}, connector); err != nil {+ if _, err := mcpprotocol.NewMCPBridge(node.Host(), economy.AllowAllVerifier{}, connector); err != nil {return fmt.Errorf("creating MCP bridge: %w", err)}@@ -155,12 +157,12 @@ func runPublish(parent context.Context, cfg *runConfig) error {}func ensureSecurePublishPreflight() error {- gate, closeFn, err := protocol.NewPassportGateWithCleanup()+ gate, closeFn, err := a2aprotocol.NewPassportGateWithCleanup()if err != nil {return fmt.Errorf("publish security preflight failed: %w", err)}defer func() { _ = closeFn() }()- if protocol.IsAllowAllGate(gate) {+ if a2aprotocol.IsAllowAllGate(gate) {return fmt.Errorf("refusing publish: A2A authentication middleware is permissive (AllowAllGate)")}return nildiff --git a/cmd/sam-agent/publish_card.go b/cmd/sam-agent/publish_card.goindex e00cd630..c88fac0c 100644--- a/cmd/sam-agent/publish_card.go+++ b/cmd/sam-agent/publish_card.go@@ -24,7 +24,7 @@ import ("github.com/spf13/cobra"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")func newPublishCardCmd(cfg *runConfig) *cobra.Command {diff --git a/cmd/sam-agent/publish_mcp.go b/cmd/sam-agent/publish_mcp.goindex 068ec04d..6b4a0d0c 100644--- a/cmd/sam-agent/publish_mcp.go+++ b/cmd/sam-agent/publish_mcp.go@@ -29,7 +29,8 @@ import ("github.com/spf13/cobra""sam/pkg/economy"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")func newPublishMCPCmd(cfg *runConfig) *cobra.Command {@@ -85,7 +86,7 @@ func runPublishMCP(parent context.Context, cfg *runConfig) error {client: &http.Client{Timeout: 30 * time.Second},addr: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),}- if _, err := protocol.NewMCPBridge(node.Host(), economy.AllowAllVerifier{}, connector); err != nil {+ if _, err := mcpprotocol.NewMCPBridge(node.Host(), economy.AllowAllVerifier{}, connector); err != nil {return fmt.Errorf("creating MCP bridge: %w", err)}diff --git a/cmd/sam-agent/up.go b/cmd/sam-agent/up.goindex 99b984ed..113ea3a0 100644--- a/cmd/sam-agent/up.go+++ b/cmd/sam-agent/up.go@@ -25,7 +25,7 @@ import ("sam/pkg/economy""sam/pkg/identity"- "sam/pkg/protocol"+ httpprotocol "sam/pkg/protocol/http")func newUpCmd(cfg *runConfig) *cobra.Command {@@ -75,18 +75,18 @@ func runUp(parent context.Context, cfg *runConfig) error {}log.Info("hub configured", "url", cfg.hub, "peer_id", creds.PeerID)- var tunnel *protocol.HTTPTunnelService+ var tunnel *httpprotocol.HTTPTunnelServiceif cfg.tunnelHTTPEndpoint != "" {- tunnel, err = protocol.NewHTTPTunnelService(+ tunnel, err = httpprotocol.NewHTTPTunnelService(node.Host(),cfg.tunnelHTTPEndpoint,- protocol.WithHTTPTunnelSkillGate(economy.NewBiscuitSkillGate(nil)),+ httpprotocol.WithHTTPTunnelSkillGate(economy.NewBiscuitSkillGate(nil)),)if err != nil {return fmt.Errorf("initializing HTTP tunnel listener: %w", err)}defer tunnel.Close()- log.Info("HTTP tunnel listener enabled", "protocol", protocol.HTTPTunnelProtocolID, "endpoint", cfg.tunnelHTTPEndpoint)+ log.Info("HTTP tunnel listener enabled", "protocol", httpprotocol.HTTPTunnelProtocolID, "endpoint", cfg.tunnelHTTPEndpoint)}addrs := make([]string, 0, len(node.Addrs()))diff --git a/pkg/economy/biscuit.go b/pkg/economy/biscuit.goindex a5f08191..6ef68fc5 100644--- a/pkg/economy/biscuit.go+++ b/pkg/economy/biscuit.go@@ -25,6 +25,13 @@ import (// the requested skill (allow_skill caveat mismatch).var ErrSkillCaveatDenied = errors.New("biscuit skill caveat denied")+// ErrProtocolPolicyDenied indicates claim-based protocol authorization failure.+var ErrProtocolPolicyDenied = errors.New("protocol authz policy denied")++// ErrCapabilityDenied is returned when a token's action/resource caveats deny+// a requested operation.+var ErrCapabilityDenied = errors.New("biscuit capability denied")+// ParsedBiscuit holds the claims extracted from a raw Biscuit token.// In this simplified implementation the token itself encodes caveats as a// structured string of the form:@@ -35,8 +42,10 @@ var ErrSkillCaveatDenied = errors.New("biscuit skill caveat denied")// the biscuit-go library. This interface keeps the contract stable for that// future migration.type ParsedBiscuit struct {- Subject string- AllowedSkills []string // empty means "allow all"+ Subject string+ AllowedSkills []string // empty means "allow all"+ AllowedActions []string // empty means "allow all"+ AllowedResources []string // empty means "allow all"}// BiscuitParser extracts claims from a raw token string.@@ -64,6 +73,8 @@ func (SimpleBiscuitParser) Parse(_ context.Context, token string) (*ParsedBiscui}caveat := strings.TrimSpace(parts[1])const skillPrefix = "allow_skill="+ const actionPrefix = "allow_operation="+ const resourcePrefix = "allow_resource="if strings.HasPrefix(caveat, skillPrefix) {raw := strings.TrimPrefix(caveat, skillPrefix)for _, s := range strings.Split(raw, ",") {@@ -71,6 +82,52 @@ func (SimpleBiscuitParser) Parse(_ context.Context, token string) (*ParsedBiscuip.AllowedSkills = append(p.AllowedSkills, s)}}+ return p, nil+ }+ if strings.HasPrefix(caveat, actionPrefix) {+ raw := strings.TrimPrefix(caveat, actionPrefix)+ for _, s := range strings.Split(raw, ",") {+ if s = strings.TrimSpace(s); s != "" {+ p.AllowedActions = append(p.AllowedActions, s)+ }+ }+ return p, nil+ }+ if strings.HasPrefix(caveat, resourcePrefix) {+ raw := strings.TrimPrefix(caveat, resourcePrefix)+ for _, s := range strings.Split(raw, ",") {+ if s = strings.TrimSpace(s); s != "" {+ p.AllowedResources = append(p.AllowedResources, s)+ }+ }+ return p, nil+ }+ // Parse multiple caveats separated by ';' when present.+ for _, clause := range strings.Split(parts[1], ";") {+ clause = strings.TrimSpace(clause)+ switch {+ case strings.HasPrefix(clause, skillPrefix):+ raw := strings.TrimPrefix(clause, skillPrefix)+ for _, s := range strings.Split(raw, ",") {+ if s = strings.TrimSpace(s); s != "" {+ p.AllowedSkills = append(p.AllowedSkills, s)+ }+ }+ case strings.HasPrefix(clause, actionPrefix):+ raw := strings.TrimPrefix(clause, actionPrefix)+ for _, s := range strings.Split(raw, ",") {+ if s = strings.TrimSpace(s); s != "" {+ p.AllowedActions = append(p.AllowedActions, s)+ }+ }+ case strings.HasPrefix(clause, resourcePrefix):+ raw := strings.TrimPrefix(clause, resourcePrefix)+ for _, s := range strings.Split(raw, ",") {+ if s = strings.TrimSpace(s); s != "" {+ p.AllowedResources = append(p.AllowedResources, s)+ }+ }+ }}return p, nil}@@ -113,3 +170,96 @@ func (g *BiscuitSkillGate) CheckSkill(ctx context.Context, token, skill string)ErrSkillCaveatDenied, parsed.Subject, skill,strings.Join(parsed.AllowedSkills, ", "))}++// EvaluateProtocolPolicies enforces Datalog-like claim predicates for a protocol.+//+// Policies are keyed by protocol ID and contain required claim key/value pairs.+// A wildcard "*" policy applies to every protocol and is merged with protocol-specific+// requirements.+func EvaluateProtocolPolicies(protocol string, claims map[string]string, policies map[string]map[string]string) error {+ protocol = strings.TrimSpace(protocol)+ if protocol == "" || len(policies) == 0 {+ return nil+ }+ required := map[string]string{}+ for k, v := range policies["*"] {+ required[k] = v+ }+ for k, v := range policies[protocol] {+ required[k] = v+ }+ if len(required) == 0 {+ return nil+ }+ if claims == nil {+ claims = map[string]string{}+ }+ for key, want := range required {+ key = strings.TrimSpace(key)+ want = strings.TrimSpace(want)+ if key == "" {+ continue+ }+ got := strings.TrimSpace(claims[key])+ if !strings.EqualFold(got, want) {+ return fmt.Errorf("%w: protocol %q requires %s=%q", ErrProtocolPolicyDenied, protocol, key, want)+ }+ }+ return nil+}++// CheckCapability validates action/resource caveats for an operation.+// Empty caveat lists are treated as unrestricted for that dimension.+func CheckCapability(ctx context.Context, parser BiscuitParser, token, action, resource string) error {+ action = strings.TrimSpace(action)+ resource = strings.TrimSpace(resource)+ if parser == nil {+ parser = SimpleBiscuitParser{}+ }+ parsed, err := parser.Parse(ctx, token)+ if err != nil {+ return fmt.Errorf("parsing biscuit: %w", err)+ }+ if len(parsed.AllowedActions) > 0 {+ allowed := false+ for _, a := range parsed.AllowedActions {+ if strings.EqualFold(strings.TrimSpace(a), action) {+ allowed = true+ break+ }+ }+ if !allowed {+ return fmt.Errorf("%w: token for %q does not allow action %q", ErrCapabilityDenied, parsed.Subject, action)+ }+ }+ if len(parsed.AllowedResources) > 0 {+ allowed := false+ for _, r := range parsed.AllowedResources {+ if strings.EqualFold(strings.TrimSpace(r), resource) {+ allowed = true+ break+ }+ }+ if !allowed {+ return fmt.Errorf("%w: token for %q does not allow resource %q", ErrCapabilityDenied, parsed.Subject, resource)+ }+ }+ return nil+}++// Restriction templates that agents can append to attenuate delegated tokens.+const (+ RestrictionTemplateOperationRead = "allow_operation=read"+ RestrictionTemplateOperationWrite = "allow_operation=write"+ RestrictionTemplateResourcePattern = "allow_resource=%s"+)++// RestrictionTemplateOperation returns a clause that limits token usage to an operation.+func RestrictionTemplateOperation(operation string) string {+ return "allow_operation=" + strings.TrimSpace(operation)+}++// RestrictionTemplateResource returns a clause that limits token usage to one resource.+func RestrictionTemplateResource(resource string) string {+ return fmt.Sprintf(RestrictionTemplateResourcePattern, strings.TrimSpace(resource))+}diff --git a/pkg/net/middleware.go b/pkg/net/middleware.gonew file mode 100644index 00000000..02f644cb--- /dev/null+++ b/pkg/net/middleware.go@@ -0,0 +1,141 @@+// 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 samnet++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"++ "github.com/libp2p/go-libp2p/core/host"+ "github.com/libp2p/go-libp2p/core/network"+ coreprotocol "github.com/libp2p/go-libp2p/core/protocol"++ "sam/pkg/economy"+ "sam/pkg/identity"+)++const (+ a2aProtocolID = "/sam/a2a/1.0.0"+ mcpProtocolID = "/sam/mcp/1.0.0"+)++// Middleware wraps stream handlers registered on a host.+type Middleware func(h host.Host, pid coreprotocol.ID, next network.StreamHandler) network.StreamHandler++// AuthMiddlewareConfig controls global authn/authz behavior for all registered protocols.+type AuthMiddlewareConfig struct {+ // AttemptAuthWhenMissing attempts /sam/auth/1.0.0 when a peer is not yet validated.+ AttemptAuthWhenMissing bool+ // ProtocolPolicies stores Datalog-like required facts per protocol, for example:+ // "/sam/a2a/1.0.0" -> {"mesh_membership":"finance"}+ ProtocolPolicies map[string]map[string]string+}++// WrapHost returns a host that applies middleware to every subsequently registered stream handler.+func WrapHost(h host.Host, middlewares ...Middleware) host.Host {+ if h == nil || len(middlewares) == 0 {+ return h+ }+ return &middlewareHost{Host: h, middlewares: middlewares}+}++type middlewareHost struct {+ host.Host+ middlewares []Middleware+}++func (h *middlewareHost) SetStreamHandler(pid coreprotocol.ID, handler network.StreamHandler) {+ wrapped := handler+ for i := len(h.middlewares) - 1; i >= 0; i-- {+ wrapped = h.middlewares[i](h, pid, wrapped)+ }+ h.Host.SetStreamHandler(pid, wrapped)+}++func (h *middlewareHost) SetStreamHandlerMatch(pid coreprotocol.ID, m func(coreprotocol.ID) bool, handler network.StreamHandler) {+ wrapped := handler+ for i := len(h.middlewares) - 1; i >= 0; i-- {+ wrapped = h.middlewares[i](h, pid, wrapped)+ }+ h.Host.SetStreamHandlerMatch(pid, m, wrapped)+}++// NewAuthMiddleware creates a protocol-independent auth middleware that enforces+// authenticated connections and optional claim-based authorization policies.+func NewAuthMiddleware(cfg AuthMiddlewareConfig) Middleware {+ return func(h host.Host, pid coreprotocol.ID, next network.StreamHandler) network.StreamHandler {+ return func(stream network.Stream) {+ protocolName := string(pid)+ if bypassAuthMiddleware(pid) {+ next(stream)+ return+ }++ if err := identity.EnsurePassportAuth(h, "default"); err != nil {+ writeUnauthorizedAndReset(stream, protocolName, fmt.Sprintf("failed to initialize auth middleware: %v", err))+ return+ }++ remote := stream.Conn().RemotePeer()+ claims, err := identity.AuthenticatedPeerPassport(h, remote)+ if err != nil && cfg.AttemptAuthWhenMissing {+ if authErr := identity.AuthenticatePeerPassport(context.Background(), h, remote); authErr == nil {+ claims, err = identity.AuthenticatedPeerPassport(h, remote)+ } else {+ err = authErr+ }+ }+ if err != nil {+ writeUnauthorizedAndReset(stream, protocolName, fmt.Sprintf("passport auth required: %v", err))+ return+ }++ if policyErr := economy.EvaluateProtocolPolicies(protocolName, claims.Claims, cfg.ProtocolPolicies); policyErr != nil {+ writeUnauthorizedAndReset(stream, protocolName, policyErr.Error())+ return+ }++ next(stream)+ }+ }+}++func bypassAuthMiddleware(pid coreprotocol.ID) bool {+ p := string(pid)+ if p == string(identity.PassportAuthProtocolID) {+ return true+ }+ return !strings.HasPrefix(p, "/sam/")+}++func writeUnauthorizedAndReset(stream network.Stream, protocolName, reason string) {+ resp := map[string]string{+ "error": "Unauthorized",+ "code": "unauthorized",+ "protocol": protocolName,+ "reason": strings.TrimSpace(reason),+ }++ switch protocolName {+ case a2aProtocolID, mcpProtocolID:+ _ = json.NewEncoder(stream).Encode(resp)+ _ = stream.Close()+ return+ }++ _ = stream.Reset()+}diff --git a/pkg/net/node.go b/pkg/net/node.goindex c593a344..bee402be 100644--- a/pkg/net/node.go+++ b/pkg/net/node.go@@ -116,20 +116,27 @@ func (n *node) Start(ctx context.Context) error {return fmt.Errorf("creating libp2p host: %w", err)}- n.host = h+ middlewares := []Middleware{+ NewAuthMiddleware(AuthMiddlewareConfig{+ AttemptAuthWhenMissing: n.opts.AttemptAuthWhenMissing,+ ProtocolPolicies: n.opts.ProtocolPolicies,+ }),+ }+ middlewares = append(middlewares, n.opts.StreamMiddlewares...)+ n.host = WrapHost(h, middlewares...)n.kdht = kdhtspan.SetAttributes(- attribute.String("peer_id", h.ID().String()),- attribute.Int("listen_addrs", len(h.Addrs())),+ attribute.String("peer_id", n.host.ID().String()),+ attribute.Int("listen_addrs", len(n.host.Addrs())),)// Start relay v2 service if configured, allowing other peers to// relay through this node.if n.opts.EnableRelayService {- n.relay, err = relayv2.New(h)+ n.relay, err = relayv2.New(n.host)if err != nil {- _ = h.Close()+ _ = n.host.Close()return fmt.Errorf("starting relay service: %w", err)}n.logger.Info("relay v2 service enabled")@@ -137,7 +144,7 @@ func (n *node) Start(ctx context.Context) error {// Bootstrap the DHT routing table.if err := n.kdht.Bootstrap(ctx); err != nil {- _ = h.Close()+ _ = n.host.Close()return fmt.Errorf("bootstrapping DHT: %w", err)}@@ -148,19 +155,19 @@ func (n *node) Start(ctx context.Context) error {// Initialize routing-based discovery backed by the DHT.n.disc = drouting.NewRoutingDiscovery(n.kdht)- gs, err := pubsub.NewGossipSub(ctx, h)+ gs, err := pubsub.NewGossipSub(ctx, n.host)if err != nil {- _ = h.Close()+ _ = n.host.Close()return fmt.Errorf("initializing gossipsub: %w", err)}n.gsub = gs- trust, err := reputation.NewTrustStore(h, gs)+ trust, err := reputation.NewTrustStore(n.host, gs)if err != nil {- _ = h.Close()+ _ = n.host.Close()return fmt.Errorf("initializing reputation trust store: %w", err)}if err := trust.Start(ctx); err != nil {- _ = h.Close()+ _ = n.host.Close()return fmt.Errorf("starting reputation trust store: %w", err)}n.trust = trust@@ -169,8 +176,8 @@ func (n *node) Start(ctx context.Context) error {n.started = truen.logger.Info("node started",- "peer_id", h.ID(),- "addrs", h.Addrs(),+ "peer_id", n.host.ID(),+ "addrs", n.host.Addrs(),"relay_fallback", n.opts.RelayFallbackHost,"rendezvous_namespace", n.opts.RendezvousNamespace,)diff --git a/pkg/net/options.go b/pkg/net/options.goindex 523d2b79..77fafbff 100644--- a/pkg/net/options.go+++ b/pkg/net/options.go@@ -64,6 +64,14 @@ type Options struct {RelayFallbackHost string// RendezvousNamespace scopes capability discovery advertisements.RendezvousNamespace string+ // AttemptAuthWhenMissing triggers a /sam/auth/1.0.0 exchange when a stream+ // arrives from an unvalidated peer before rejecting it.+ AttemptAuthWhenMissing bool+ // ProtocolPolicies defines required claims per protocol ID.+ // Example: {"/sam/a2a/1.0.0": {"mesh_membership": "finance"}}+ ProtocolPolicies map[string]map[string]string+ // StreamMiddlewares are additional wrappers applied to every stream handler.+ StreamMiddlewares []Middleware}// Option is a functional option for node configuration.@@ -77,13 +85,15 @@ func DefaultOptions() Options {tcpV4, _ := multiaddr.NewMultiaddr("/ip4/0.0.0.0/tcp/0")tcpV6, _ := multiaddr.NewMultiaddr("/ip6/::/tcp/0")return Options{- ListenAddrs: []multiaddr.Multiaddr{quicV1, quicV1v6, tcpV4, tcpV6},- DHTMode: DHTModeAuto,- UserAgent: "sam/0.1.0",- Logger: slog.Default(),- FederationID: "default",- RelayFallbackHost: DefaultRelayFallbackHost,- RendezvousNamespace: DefaultRendezvousNamespace,+ ListenAddrs: []multiaddr.Multiaddr{quicV1, quicV1v6, tcpV4, tcpV6},+ DHTMode: DHTModeAuto,+ UserAgent: "sam/0.1.0",+ Logger: slog.Default(),+ FederationID: "default",+ RelayFallbackHost: DefaultRelayFallbackHost,+ RendezvousNamespace: DefaultRendezvousNamespace,+ AttemptAuthWhenMissing: true,+ ProtocolPolicies: map[string]map[string]string{},}}@@ -110,6 +120,9 @@ func (o *Options) validate() error {if o.RendezvousNamespace == "" {o.RendezvousNamespace = DefaultRendezvousNamespace}+ if o.ProtocolPolicies == nil {+ o.ProtocolPolicies = map[string]map[string]string{}+ }return nil}@@ -172,3 +185,32 @@ func WithRendezvousNamespace(ns string) Option {func WithRelayFallbackHost(host string) Option {return func(o *Options) { o.RelayFallbackHost = host }}++// WithAttemptAuthWhenMissing configures whether global middleware attempts+// /sam/auth/1.0.0 when the peer is not yet validated.+func WithAttemptAuthWhenMissing(enabled bool) Option {+ return func(o *Options) { o.AttemptAuthWhenMissing = enabled }+}++// WithProtocolPolicy requires claim=value for the given protocol ID.+func WithProtocolPolicy(protocolID, claim, value string) Option {+ return func(o *Options) {+ if o.ProtocolPolicies == nil {+ o.ProtocolPolicies = map[string]map[string]string{}+ }+ if _, ok := o.ProtocolPolicies[protocolID]; !ok {+ o.ProtocolPolicies[protocolID] = map[string]string{}+ }+ o.ProtocolPolicies[protocolID][claim] = value+ }+}++// WithStreamMiddleware appends a custom global stream middleware wrapper.+func WithStreamMiddleware(m Middleware) Option {+ return func(o *Options) {+ if m == nil {+ return+ }+ o.StreamMiddlewares = append(o.StreamMiddlewares, m)+ }+}diff --git a/pkg/protocol/a2a.go b/pkg/protocol/a2a/a2a.gosimilarity index 96%rename from pkg/protocol/a2a.gorename to pkg/protocol/a2a/a2a.goindex 6aeb9f4d..c4c1c576 100644--- a/pkg/protocol/a2a.go+++ b/pkg/protocol/a2a/a2a.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package a2aimport ("bufio"@@ -30,9 +30,11 @@ import ("github.com/libp2p/go-libp2p/core/peer"coreprotocol "github.com/libp2p/go-libp2p/core/protocol""github.com/modelcontextprotocol/go-sdk/jsonrpc"+ "github.com/modelcontextprotocol/go-sdk/mcp""sam/pkg/economy""sam/pkg/identity"+ "sam/pkg/protocol/middleware""sam/pkg/reputation")@@ -45,6 +47,11 @@ const (FailureTypeInternal = "Internal")+// MCPConnector opens a local MCP JSON-RPC transport endpoint.+type MCPConnector interface {+ Open(ctx context.Context) (mcp.Transport, error)+}+// Observer receives task health callbacks after every A2A attempt.type Observer interface {OnSuccess(peerID string, latency time.Duration)@@ -154,9 +161,6 @@ func NewA2AService(h host.Host, connector MCPConnector, observer Observer, optsif observer == nil {observer = NopObserver{}}- if err := identity.EnsurePassportAuth(h, ""); err != nil {- return nil, fmt.Errorf("installing passport auth: %w", err)- }s := &A2AService{host: h, observer: observer, mcp: connector, gate: AllowAllGate{}}for _, o := range opts {o(s)@@ -338,7 +342,11 @@ func (s *A2AService) handleStream(stream network.Stream) {fail(FailureTypeProtocol, fmt.Errorf("missing biscuit token"))return}- claims, err := identity.EnsureAuthenticatedPeer(context.Background(), s.host, stream.Conn().RemotePeer())+ if err := (middleware.PassportAuthz{}).CheckCapability(context.Background(), header.Biscuit, "a2a.negotiate", strings.TrimSpace(header.Capability)); err != nil {+ fail(FailureTypeProtocol, err)+ return+ }+ claims, err := identity.AuthenticatedPeerPassport(s.host, stream.Conn().RemotePeer())if err != nil {fail(FailureTypeProtocol, fmt.Errorf("passport authentication required: %w", err))returndiff --git a/pkg/protocol/a2a_test.go b/pkg/protocol/a2a/a2a_test.gosimilarity index 99%rename from pkg/protocol/a2a_test.gorename to pkg/protocol/a2a/a2a_test.goindex 460a833f..5d720fbe 100644--- a/pkg/protocol/a2a_test.go+++ b/pkg/protocol/a2a/a2a_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package a2aimport ("context"diff --git a/pkg/protocol/federation_gate.go b/pkg/protocol/a2a/federation_gate.gosimilarity index 99%rename from pkg/protocol/federation_gate.gorename to pkg/protocol/a2a/federation_gate.goindex 6ded6574..ec45e031 100644--- a/pkg/protocol/federation_gate.go+++ b/pkg/protocol/a2a/federation_gate.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package a2aimport ("context"diff --git a/pkg/protocol/federation_gate_test.go b/pkg/protocol/a2a/federation_gate_test.gosimilarity index 98%rename from pkg/protocol/federation_gate_test.gorename to pkg/protocol/a2a/federation_gate_test.goindex b659a652..fd1c5bf4 100644--- a/pkg/protocol/federation_gate_test.go+++ b/pkg/protocol/a2a/federation_gate_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package a2aimport ("context"diff --git a/pkg/protocol/observer_db.go b/pkg/protocol/a2a/observer_db.gosimilarity index 99%rename from pkg/protocol/observer_db.gorename to pkg/protocol/a2a/observer_db.goindex 14522ba4..0f6af353 100644--- a/pkg/protocol/observer_db.go+++ b/pkg/protocol/a2a/observer_db.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package a2aimport ("context"diff --git a/pkg/protocol/auth/auth.go b/pkg/protocol/auth/auth.gonew file mode 100644index 00000000..19ac374b--- /dev/null+++ b/pkg/protocol/auth/auth.go@@ -0,0 +1,22 @@+// 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 auth contains shared connection authorization hooks used by mesh+// protocols (A2A, HTTP tunnel, MCP bridge).+package auth++import "sam/pkg/protocol/middleware"++type ConnectionAuthz = middleware.ConnectionAuthz+type PassportAuthz = middleware.PassportAuthzdiff --git a/pkg/protocol/agent_card.go b/pkg/protocol/discovery/agent_card.gosimilarity index 99%rename from pkg/protocol/agent_card.gorename to pkg/protocol/discovery/agent_card.goindex 5e48c4fc..39bdd237 100644--- a/pkg/protocol/agent_card.go+++ b/pkg/protocol/discovery/agent_card.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package discoveryimport ("cmp"diff --git a/pkg/protocol/agent_card_a2a.go b/pkg/protocol/discovery/agent_card_a2a.gosimilarity index 99%rename from pkg/protocol/agent_card_a2a.gorename to pkg/protocol/discovery/agent_card_a2a.goindex a03eb005..8c38d332 100644--- a/pkg/protocol/agent_card_a2a.go+++ b/pkg/protocol/discovery/agent_card_a2a.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package discoveryimport ("fmt"diff --git a/pkg/protocol/agent_card_a2a_test.go b/pkg/protocol/discovery/agent_card_a2a_test.gosimilarity index 97%rename from pkg/protocol/agent_card_a2a_test.gorename to pkg/protocol/discovery/agent_card_a2a_test.goindex f8e3d18b..1fa38b10 100644--- a/pkg/protocol/agent_card_a2a_test.go+++ b/pkg/protocol/discovery/agent_card_a2a_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol_test+package discovery_testimport ("testing"@@ -22,7 +22,7 @@ import ("github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")func TestToA2ACard(t *testing.T) {diff --git a/pkg/protocol/agent_card_test.go b/pkg/protocol/discovery/agent_card_test.gosimilarity index 97%rename from pkg/protocol/agent_card_test.gorename to pkg/protocol/discovery/agent_card_test.goindex 8cc6d6f8..1eed8377 100644--- a/pkg/protocol/agent_card_test.go+++ b/pkg/protocol/discovery/agent_card_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol_test+package discovery_testimport ("testing"@@ -22,7 +22,7 @@ import ("github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")func TestAgentCardSignVerify(t *testing.T) {diff --git a/pkg/protocol/discovery.go b/pkg/protocol/discovery/discovery.gosimilarity index 99%rename from pkg/protocol/discovery.gorename to pkg/protocol/discovery/discovery.goindex 8f5e65be..dfc4b2e3 100644--- a/pkg/protocol/discovery.go+++ b/pkg/protocol/discovery/discovery.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package discoveryimport ("context"diff --git a/pkg/protocol/discovery_test.go b/pkg/protocol/discovery/discovery_test.gosimilarity index 99%rename from pkg/protocol/discovery_test.gorename to pkg/protocol/discovery/discovery_test.goindex 4bb9e843..1f6eed54 100644--- a/pkg/protocol/discovery_test.go+++ b/pkg/protocol/discovery/discovery_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol_test+package discovery_testimport ("context"@@ -30,7 +30,7 @@ import ("github.com/multiformats/go-multiaddr"samnet "sam/pkg/net"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")type fakeDiscoveryNode struct {diff --git a/pkg/protocol/publish.go b/pkg/protocol/discovery/publish.gosimilarity index 99%rename from pkg/protocol/publish.gorename to pkg/protocol/discovery/publish.goindex 5e9fb759..6c6f76c0 100644--- a/pkg/protocol/publish.go+++ b/pkg/protocol/discovery/publish.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package discoveryimport ("context"diff --git a/pkg/protocol/publish_test.go b/pkg/protocol/discovery/publish_test.gosimilarity index 98%rename from pkg/protocol/publish_test.gorename to pkg/protocol/discovery/publish_test.goindex 78addce2..604dc9aa 100644--- a/pkg/protocol/publish_test.go+++ b/pkg/protocol/discovery/publish_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol_test+package discovery_testimport ("context"@@ -22,7 +22,7 @@ import ("github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery")type fakePublisherNode struct {diff --git a/pkg/protocol/http_tunnel.go b/pkg/protocol/http/http_tunnel.gosimilarity index 97%rename from pkg/protocol/http_tunnel.gorename to pkg/protocol/http/http_tunnel.goindex a2bb5d23..5acfec6f 100644--- a/pkg/protocol/http_tunnel.go+++ b/pkg/protocol/http/http_tunnel.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package httpprotocolimport ("bufio"@@ -96,10 +96,6 @@ func NewHTTPTunnelService(h host.Host, endpoint string, opts ...HTTPTunnelServicfor _, opt := range opts {opt(s)}- if err := identity.EnsurePassportAuth(h, ""); err != nil {- return nil, fmt.Errorf("installing passport auth: %w", err)- }-h.SetStreamHandler(HTTPTunnelProtocolID, s.handleStream)return s, nil}@@ -177,7 +173,7 @@ func (s *HTTPTunnelService) handleStream(stream network.Stream) {}func (s *HTTPTunnelService) verifyMetadata(ctx context.Context, remotePeer peer.ID, req *HTTPTunnelOpenRequest) error {- if _, err := identity.EnsureAuthenticatedPeer(ctx, s.host, remotePeer); err != nil {+ if _, err := identity.AuthenticatedPeerPassport(s.host, remotePeer); err != nil {return fmt.Errorf("passport authentication required: %w", err)}if strings.TrimSpace(req.Biscuit) == "" {diff --git a/pkg/protocol/http_tunnel_test.go b/pkg/protocol/http/http_tunnel_test.gosimilarity index 98%rename from pkg/protocol/http_tunnel_test.gorename to pkg/protocol/http/http_tunnel_test.goindex c0609750..b8cb3946 100644--- a/pkg/protocol/http_tunnel_test.go+++ b/pkg/protocol/http/http_tunnel_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package httpprotocolimport "testing"diff --git a/pkg/protocol/mcp_bridge.go b/pkg/protocol/mcp/mcp_bridge.gosimilarity index 94%rename from pkg/protocol/mcp_bridge.gorename to pkg/protocol/mcp/mcp_bridge.goindex 29697ddf..9034e13a 100644--- a/pkg/protocol/mcp_bridge.go+++ b/pkg/protocol/mcp/mcp_bridge.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package mcpimport ("bufio"@@ -29,6 +29,7 @@ import ("sam/pkg/economy""sam/pkg/identity"+ "sam/pkg/protocol/middleware""sam/pkg/reputation")@@ -72,9 +73,6 @@ func NewMCPBridge(h host.Host, verifier economy.Verifier, connector MCPConnector}b := &MCPBridge{host: h, verifier: verifier, connector: connector}- if err := identity.EnsurePassportAuth(h, ""); err != nil {- return nil, fmt.Errorf("installing passport auth: %w", err)- }h.SetStreamHandler(MCPProtocolID, b.handleInbound)return b, nil}@@ -100,7 +98,7 @@ func (b *MCPBridge) Open(ctx context.Context, peerID peer.ID, req BridgeOpenRequfunc (b *MCPBridge) handleInbound(stream network.Stream) {defer func() { _ = stream.Close() }()- if _, err := identity.EnsureAuthenticatedPeer(context.Background(), b.host, stream.Conn().RemotePeer()); err != nil {+ if _, err := identity.AuthenticatedPeerPassport(b.host, stream.Conn().RemotePeer()); err != nil {_ = writeBridgeError(stream, fmt.Errorf("passport authentication required: %w", err))return}@@ -136,6 +134,14 @@ func (b *MCPBridge) handleInbound(stream network.Stream) {_ = writeBridgeError(stream, economy.ErrMissingMicropayNonce)return}+ resource := openReq.Capability+ if resource == "" {+ resource = MCPProtocolID+ }+ if err := (middleware.PassportAuthz{}).CheckCapability(context.Background(), openReq.BiscuitToken, "mcp.tool_call", resource); err != nil {+ _ = writeBridgeError(stream, err)+ return+ }verifyReq := economy.VerifyRequest{Token: openReq.BiscuitToken,diff --git a/pkg/protocol/mcp_bridge_test.go b/pkg/protocol/mcp/mcp_bridge_test.gosimilarity index 99%rename from pkg/protocol/mcp_bridge_test.gorename to pkg/protocol/mcp/mcp_bridge_test.goindex b1dba85c..e789ee03 100644--- a/pkg/protocol/mcp_bridge_test.go+++ b/pkg/protocol/mcp/mcp_bridge_test.go@@ -12,7 +12,7 @@// See the License for the specific language governing permissions and// limitations under the License.-package protocol+package mcpimport ("context"diff --git a/pkg/protocol/middleware/authz.go b/pkg/protocol/middleware/authz.gonew file mode 100644index 00000000..2911f37b--- /dev/null+++ b/pkg/protocol/middleware/authz.go@@ -0,0 +1,85 @@+// 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 middleware++import (+ "context"+ "fmt"++ "github.com/libp2p/go-libp2p/core/host"+ "github.com/libp2p/go-libp2p/core/peer"++ "sam/pkg/economy"+ "sam/pkg/identity"+)++// ConnectionAuthz is a reusable per-connection authorization hook that can be+// shared across protocol implementations.+type ConnectionAuthz interface {+ Install(host.Host) error+ AuthorizeOutbound(context.Context, host.Host, peer.ID) error+ AuthorizeInbound(context.Context, host.Host, peer.ID) (*identity.PassportClaims, error)+ CheckCapability(context.Context, string, string, string) error+}++// PassportAuthz enforces hub-issued passport authentication on libp2p+// connections. This is the default SAM connection authz middleware.+type PassportAuthz struct{}++func (PassportAuthz) Install(h host.Host) error {+ if h == nil {+ return fmt.Errorf("host is nil")+ }+ if err := identity.EnsurePassportAuth(h, ""); err != nil {+ return fmt.Errorf("installing passport auth: %w", err)+ }+ return nil+}++func (PassportAuthz) AuthorizeOutbound(ctx context.Context, h host.Host, target peer.ID) error {+ if h == nil {+ return fmt.Errorf("host is nil")+ }+ if target == "" {+ return fmt.Errorf("target peer id is required")+ }+ if err := identity.AuthenticatePeerPassport(ctx, h, target); err != nil {+ return fmt.Errorf("passport authentication failed for %s: %w", target, err)+ }+ return nil+}++func (PassportAuthz) AuthorizeInbound(ctx context.Context, h host.Host, remote peer.ID) (*identity.PassportClaims, error) {+ if h == nil {+ return nil, fmt.Errorf("host is nil")+ }+ if remote == "" {+ return nil, fmt.Errorf("remote peer id is required")+ }+ claims, err := identity.EnsureAuthenticatedPeer(ctx, h, remote)+ if err != nil {+ return nil, fmt.Errorf("passport authentication required: %w", err)+ }+ return claims, nil+}++// CheckCapability enforces action/resource caveats embedded in Biscuit tokens.+// If the token does not carry action/resource restrictions, the request is allowed.+func (PassportAuthz) CheckCapability(ctx context.Context, token, action, resource string) error {+ if err := economy.CheckCapability(ctx, nil, token, action, resource); err != nil {+ return fmt.Errorf("authorization denied for action=%q resource=%q: %w", action, resource, err)+ }+ return nil+}diff --git a/tests/integration/call_test.go b/tests/integration/call_test.goindex 7926d76d..3e00649b 100644--- a/tests/integration/call_test.go+++ b/tests/integration/call_test.go@@ -39,7 +39,8 @@ import ("sam/pkg/economy""sam/pkg/identity"samnet "sam/pkg/net"- "sam/pkg/protocol"+ a2aprotocol "sam/pkg/protocol/a2a"+ protocol "sam/pkg/protocol/discovery")const (@@ -147,7 +148,7 @@ func runCallIntegration(t *testing.T) {if rec.OK {successes++}- if !rec.OK && strings.EqualFold(rec.ErrorType, protocol.FailureTypeLiveness) {+ if !rec.OK && strings.EqualFold(rec.ErrorType, a2aprotocol.FailureTypeLiveness) {livenessFailures++}return nil@@ -205,7 +206,7 @@ func runCallProviderRole() error {// Register the A2A handler BEFORE writing the info file so the consumer// cannot connect and attempt Execute before the protocol is ready.- a2aSvc, err := protocol.NewA2AService(node.Host(), delayedResponseConnector{delay: 1500 * time.Millisecond}, protocol.NopObserver{})+ a2aSvc, err := a2aprotocol.NewA2AService(node.Host(), delayedResponseConnector{delay: 1500 * time.Millisecond}, a2aprotocol.NopObserver{})if err != nil {return fmt.Errorf("provider A2A service setup: %w", err)}@@ -323,13 +324,13 @@ func runCallConsumerRole() error {// directly after bootstrap connection instead of waiting for DHT convergence.target := peer.AddrInfo{ID: providerID, Addrs: node.Host().Peerstore().Addrs(providerID)}- observer, err := protocol.NewBoltObserver(os.Getenv(callRepDBEnv))+ observer, err := a2aprotocol.NewBoltObserver(os.Getenv(callRepDBEnv))if err != nil {return fmt.Errorf("creating bolt observer: %w", err)}defer func() { _ = observer.Close() }()- req := protocol.ExecuteRequest{+ req := a2aprotocol.ExecuteRequest{Target: target,Capability: callCapability,Biscuit: "integration-biscuit",@@ -342,7 +343,7 @@ func runCallConsumerRole() error {MCPRequest: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"weather"}}`),}- if _, err := protocol.Execute(ctx, node.Host(), req, observer); err != nil {+ if _, err := a2aprotocol.Execute(ctx, node.Host(), req, observer); err != nil {return fmt.Errorf("expected initial call success, got: %w", err)}@@ -354,7 +355,7 @@ func runCallConsumerRole() error {req.Payment.Nonce = "nonce-failure"failCtx, failCancel := context.WithTimeout(ctx, 5*time.Second)defer failCancel()- if _, err := protocol.Execute(failCtx, node.Host(), req, observer); err == nil {+ if _, err := a2aprotocol.Execute(failCtx, node.Host(), req, observer); err == nil {return fmt.Errorf("expected second call to fail after provider kill")}diff --git a/tests/integration/mesh_test.go b/tests/integration/mesh_test.goindex ba66f349..7375fc29 100644--- a/tests/integration/mesh_test.go+++ b/tests/integration/mesh_test.go@@ -55,7 +55,8 @@ import ("sam/pkg/economy""sam/pkg/identity"samnet "sam/pkg/net"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")// ---------------------------------------------------------------------------@@ -225,7 +226,7 @@ func runMeshPublisher() error {}// meshAllowVerifier accepts any token so the subscriber test needs no real Biscuit token.- if _, err := protocol.NewMCPBridge(node.Host(), meshAllowVerifier{}, meshEchoConnector{}); err != nil {+ if _, err := mcpprotocol.NewMCPBridge(node.Host(), meshAllowVerifier{}, meshEchoConnector{}); err != nil {return fmt.Errorf("publisher bridge setup: %w", err)}@@ -322,7 +323,7 @@ func runMeshSubscriber() error {}// 3. Open a QUIC/MCP bridge stream to the publisher and do an echo round-trip.- bridge, err := protocol.NewMCPBridge(node.Host(), meshAllowVerifier{}, meshEchoConnector{})+ bridge, err := mcpprotocol.NewMCPBridge(node.Host(), meshAllowVerifier{}, meshEchoConnector{})if err != nil {return fmt.Errorf("subscriber bridge setup: %w", err)}@@ -337,8 +338,8 @@ func runMeshSubscriber() error {// Round-trip helper// ----------------------------------------------------------------------------func meshEchoRoundTrip(ctx context.Context, bridge *protocol.MCPBridge, target peer.ID) error {- stream, err := bridge.Open(ctx, target, protocol.BridgeOpenRequest{+func meshEchoRoundTrip(ctx context.Context, bridge *mcpprotocol.MCPBridge, target peer.ID) error {+ stream, err := bridge.Open(ctx, target, mcpprotocol.BridgeOpenRequest{BiscuitToken: "mesh-token",Amount: 1,Asset: "sam-credit",diff --git a/tests/integration/p2p_test.go b/tests/integration/p2p_test.goindex 63b8c788..2357b03b 100644--- a/tests/integration/p2p_test.go+++ b/tests/integration/p2p_test.go@@ -43,7 +43,8 @@ import ("sam/pkg/economy""sam/pkg/identity"samnet "sam/pkg/net"- "sam/pkg/protocol"+ protocol "sam/pkg/protocol/discovery"+ mcpprotocol "sam/pkg/protocol/mcp")const (@@ -192,7 +193,7 @@ func runProviderRole() error {return fmt.Errorf("provider register local card: %w", err)}- if _, err := protocol.NewMCPBridge(node.Host(), tokenVerifier{token: validBiscuit}, echoConnector{}); err != nil {+ if _, err := mcpprotocol.NewMCPBridge(node.Host(), tokenVerifier{token: validBiscuit}, echoConnector{}); err != nil {return fmt.Errorf("provider bridge setup: %w", err)}@@ -284,7 +285,7 @@ func runConsumerRole() error {}_ = peerIDs- bridge, err := protocol.NewMCPBridge(node.Host(), allowVerifier{}, echoConnector{})+ bridge, err := mcpprotocol.NewMCPBridge(node.Host(), allowVerifier{}, echoConnector{})if err != nil {return fmt.Errorf("consumer bridge setup: %w", err)}@@ -372,8 +373,8 @@ func discoverCardsWithRetry(ctx context.Context, svc *protocol.DiscoveryService,}}-func expectDeniedBridge(ctx context.Context, bridge *protocol.MCPBridge, providerID peer.ID) error {- stream, err := bridge.Open(ctx, providerID, protocol.BridgeOpenRequest{+func expectDeniedBridge(ctx context.Context, bridge *mcpprotocol.MCPBridge, providerID peer.ID) error {+ stream, err := bridge.Open(ctx, providerID, mcpprotocol.BridgeOpenRequest{BiscuitToken: "invalid-biscuit",Amount: 1,Asset: "sam-credit",@@ -396,8 +397,8 @@ func expectDeniedBridge(ctx context.Context, bridge *protocol.MCPBridge, providereturn nil}-func expectAllowedBridge(ctx context.Context, bridge *protocol.MCPBridge, providerID peer.ID) error {- stream, err := bridge.Open(ctx, providerID, protocol.BridgeOpenRequest{+func expectAllowedBridge(ctx context.Context, bridge *mcpprotocol.MCPBridge, providerID peer.ID) error {+ stream, err := bridge.Open(ctx, providerID, mcpprotocol.BridgeOpenRequest{BiscuitToken: validBiscuit,Amount: 2,Asset: "sam-credit",diff --git a/tests/integration/proxy_test.go b/tests/integration/proxy_test.goindex bb5b15a3..86db4632 100644--- a/tests/integration/proxy_test.go+++ b/tests/integration/proxy_test.go@@ -37,7 +37,8 @@ import ("sam/pkg/economy""sam/pkg/identity"samnet "sam/pkg/net"- "sam/pkg/protocol"+ a2aprotocol "sam/pkg/protocol/a2a"+ httpprotocol "sam/pkg/protocol/http")const proxyRecordVersion = 1@@ -65,7 +66,7 @@ func runProxyTunnelLegacyFlowIntegration(t *testing.T) {t.Setenv("XDG_CONFIG_HOME", filepath.Join(tmpHome, ".config"))federation := "proxy-legacy"- observer, err := protocol.NewBoltObserverForFederation(federation)+ observer, err := a2aprotocol.NewBoltObserverForFederation(federation)if err != nil {t.Fatalf("creating observer: %v", err)}@@ -105,10 +106,10 @@ func runProxyTunnelLegacyFlowIntegration(t *testing.T) {}defer func() { _ = providerNode.Stop(context.Background()) }()- tunnelSvc, err := protocol.NewHTTPTunnelService(+ tunnelSvc, err := httpprotocol.NewHTTPTunnelService(providerNode.Host(),backend.URL,- protocol.WithHTTPTunnelSkillGate(economy.NewBiscuitSkillGate(nil)),+ httpprotocol.WithHTTPTunnelSkillGate(economy.NewBiscuitSkillGate(nil)),)if err != nil {t.Fatalf("creating tunnel service: %v", err)@@ -244,7 +245,7 @@ func runProxyTunnelUnauthorizedBeforeDial(t *testing.T) {}defer func() { _ = providerNode.Stop(context.Background()) }()- tunnelSvc, err := protocol.NewHTTPTunnelService(providerNode.Host(), backend.URL)+ tunnelSvc, err := httpprotocol.NewHTTPTunnelService(providerNode.Host(), backend.URL)if err != nil {t.Fatalf("creating tunnel service: %v", err)}@@ -259,7 +260,7 @@ func runProxyTunnelUnauthorizedBeforeDial(t *testing.T) {}defer func() { _ = consumerNode.Stop(context.Background()) }()- proxySrv := httptest.NewServer(proxyTunnelHandler(consumerNode, protocol.NopObserver{}, "X-SAM-Target", "", ""))+ proxySrv := httptest.NewServer(proxyTunnelHandler(consumerNode, a2aprotocol.NopObserver{}, "X-SAM-Target", "", ""))defer proxySrv.Close()req, err := http.NewRequestWithContext(ctx, http.MethodGet, proxySrv.URL+"/blocked", nil)@@ -283,7 +284,7 @@ func runProxyTunnelUnauthorizedBeforeDial(t *testing.T) {}}-func proxyTunnelHandler(node samnet.Node, observer protocol.Observer, targetHeader, biscuit string, passport string) http.Handler {+func proxyTunnelHandler(node samnet.Node, observer a2aprotocol.Observer, targetHeader, biscuit string, passport string) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if strings.TrimSpace(passport) == "" {http.Error(w, "unauthorized: local identity login required", http.StatusUnauthorized)@@ -311,10 +312,10 @@ func proxyTunnelHandler(node samnet.Node, observer protocol.Observer, targetHeadheaders.Del(targetHeader)start := time.Now()- resp, err := protocol.TunnelHTTP(r.Context(), node.Host(), targetID, protocol.HTTPTunnelOpenRequest{+ resp, err := httpprotocol.TunnelHTTP(r.Context(), node.Host(), targetID, httpprotocol.HTTPTunnelOpenRequest{Biscuit: biscuit,Capability: "risk-audit",- Request: protocol.HTTPTunnelRequest{+ Request: httpprotocol.HTTPTunnelRequest{Method: r.Method,Path: r.URL.RequestURI(),Headers: headers,@@ -322,12 +323,12 @@ func proxyTunnelHandler(node samnet.Node, observer protocol.Observer, targetHead},})if err != nil {- observer.OnFailure(targetID.String(), protocol.FailureTypeLiveness)+ observer.OnFailure(targetID.String(), a2aprotocol.FailureTypeLiveness)http.Error(w, fmt.Sprintf("tunnel request failed: %v", err), http.StatusBadGateway)return}if resp.Error != "" {- observer.OnFailure(targetID.String(), protocol.FailureTypeRemote)+ observer.OnFailure(targetID.String(), a2aprotocol.FailureTypeRemote)status := resp.StatusCodeif status == 0 {status = http.StatusBadGateway