Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
node: regenerate a2a agent cards with the official SDK instead of live rewrite
Antonio Ojeafb5c34999391
diff --git a/development/examples/chat-a2a/agent.py b/development/examples/chat-a2a/agent.pyindex ec4ec8a6..b3802826 100644--- a/development/examples/chat-a2a/agent.py+++ b/development/examples/chat-a2a/agent.py@@ -96,7 +96,7 @@ handler = DefaultRequestHandler(agent_card=agent_card,)# Starlette over FastAPI: the SDK generates the routes, so FastAPI would add nothing.-# JSON-RPC at "/": the mesh card rewrite drops URL subpaths, so clients land on the root.+# JSON-RPC at "/": the mesh card regeneration drops URL subpaths, so clients land on the root.app = Starlette(routes=[*create_jsonrpc_routes(request_handler=handler, rpc_url="/"),diff --git a/go.mod b/go.modindex ef6900e6..9d91fe41 100644--- a/go.mod+++ b/go.mod@@ -3,6 +3,7 @@ module github.com/google/samgo 1.25.7require (+ github.com/a2aproject/a2a-go/v2 v2.5.0github.com/biscuit-auth/biscuit-go/v2 v2.2.0github.com/coreos/go-oidc/v3 v3.20.0github.com/golang-jwt/jwt/v5 v5.3.1diff --git a/go.sum b/go.sumindex 2a449f98..5e185644 100644--- a/go.sum+++ b/go.sum@@ -2,6 +2,8 @@ filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5 h1:JA0fFr+kxpqTdxR9LOBiTWfilippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI=filippo.io/keygen v1.0.0 h1:u0/Fhxlgz3uPv+XxhfgTq3BJt5VesIPM5ue/OuG7qjQ=filippo.io/keygen v1.0.0/go.mod h1:9nnw1SlYHYuPSo/3wjQzNjSbeHlq2NsKo5iEtfJPWP0=+github.com/a2aproject/a2a-go/v2 v2.5.0 h1:ZdcFoxv+nZTUV0i2ue5hES76YCANFPG9vjqd7vK8yWM=+github.com/a2aproject/a2a-go/v2 v2.5.0/go.mod h1:NcRp/ZHxgMzDj12/BteIC2gOjljuEBKaGRfEdJ2lNSI=github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=github.com/alecthomas/participle/v2 v2.1.4 h1:W/H79S8Sat/krZ3el6sQMvMaahJ+XcM9WSI2naI7w2U=diff --git a/internal/node/a2a_service.go b/internal/node/a2a_service.goindex f3282907..22a9a808 100644--- a/internal/node/a2a_service.go+++ b/internal/node/a2a_service.go@@ -15,7 +15,6 @@package nodeimport (- "bytes""context""encoding/json""fmt"@@ -24,14 +23,15 @@ import ("strconv""strings"+ "github.com/a2aproject/a2a-go/v2/a2a""github.com/google/sam/api""github.com/libp2p/go-libp2p/core/peer")func init() {registerEgressMiddleware(api.ServiceTypeStringA2A, egressMiddleware{- gateRequest: a2aEgressGate,- modifyResponse: rewriteA2AAgentCard,+ gateRequest: a2aEgressGate,+ serveLocal: a2aServeAgentCard,})}@@ -56,13 +56,9 @@ func (s *A2AService) Init(ctx context.Context) error {return nil}-// a2aCardBaseURL is the context key carrying the caller-facing mesh base URL-// of an agent-card fetch, set by a2aEgressGate and consumed by the rewrite.-type a2aCardBaseURL struct{}-// a2aEgressGate runs the caller-side A2A checks on a raw egress request:-// the fail-closed labels gate and tagging agent-card fetches for rewrite.-// On refusal it writes the HTTP error itself and returns ok=false.+// the fail-closed labels gate. On refusal it writes the HTTP error itself+// and returns ok=false.func a2aEgressGate(node *SamNode, w http.ResponseWriter, r *http.Request, route egressRoute) (*http.Request, bool) {if labelsHeader := r.Header.Get(api.HeaderSamRequiredLabels); labelsHeader != "" {r.Header.Del(api.HeaderSamRequiredLabels)@@ -82,78 +78,115 @@ func a2aEgressGate(node *SamNode, w http.ResponseWriter, r *http.Request, routereturn r, false}}- if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/.well-known/agent-card.json") {- base := fmt.Sprintf("http://%s/sam/%s/%s/%s", r.Host, route.peerID, route.serviceType, route.serviceName)- r = r.WithContext(context.WithValue(r.Context(), a2aCardBaseURL{}, base))- }return r, true}-// rewriteA2AAgentCard makes a proxied agent card usable by stock A2A clients:-// interface URLs point back at the mesh path, transports the mesh cannot-// carry (gRPC) are dropped, and streaming is advertised off until verified.-func rewriteA2AAgentCard(resp *http.Response) error {- base, ok := resp.Request.Context().Value(a2aCardBaseURL{}).(string)- if !ok || resp.StatusCode != http.StatusOK {- return nil- }- if resp.Header.Get("Content-Encoding") != "" {- logger.Warnf("[A2A] agent card response is content-encoded; skipping rewrite")- return nil+// a2aAgentCardPath is the well-known agent card location (A2A spec / RFC 8615).+const a2aAgentCardPath = ".well-known/agent-card.json"++// maxAgentCardBytes bounds how much of a remote agent card the node ingests.+const maxAgentCardBytes = 1 << 20++// a2aServeAgentCard impersonates the remote agent's card endpoint: it holds+// the client request, fetches the card from the agent over the mesh, and+// serves a regenerated card whose interfaces point at the local mesh URL.+// Stock A2A clients then talk to the agent through this node unmodified.+// Non-card requests are left to the streaming egress proxy.+func a2aServeAgentCard(node *SamNode, rt http.RoundTripper, w http.ResponseWriter, r *http.Request, route egressRoute) bool {+ if r.Method != http.MethodGet || route.upstreamPath != a2aAgentCardPath {+ return false}- body, err := io.ReadAll(resp.Body)- _ = resp.Body.Close()+ resp, err := fetchRemoteAgentCard(node, rt, r, route)if err != nil {- return err+ logger.Warnf("[A2A] agent card fetch from %s failed: %v", route.peerID, err)+ http.Error(w, "Bad Gateway: agent card fetch failed", http.StatusBadGateway)+ return true}- var card map[string]any- if err := json.Unmarshal(body, &card); err != nil {- return fmt.Errorf("agent card is not valid JSON: %w", err)+ defer func() { _ = resp.Body.Close() }()++ body := io.LimitReader(resp.Body, maxAgentCardBytes)+ if resp.StatusCode != http.StatusOK {+ // The agent's own error; relay it as-is.+ if ct := resp.Header.Get("Content-Type"); ct != "" {+ w.Header().Set("Content-Type", ct)+ }+ w.WriteHeader(resp.StatusCode)+ _, _ = io.Copy(w, body)+ return true}- if _, ok := card["url"]; ok {- card["url"] = base++ var card a2a.AgentCard+ if err := json.NewDecoder(body).Decode(&card); err != nil {+ logger.Warnf("[A2A] agent card from %s is not valid JSON: %v", route.peerID, err)+ http.Error(w, "Bad Gateway: agent card is not valid JSON", http.StatusBadGateway)+ return true}- if pt, ok := card["preferredTransport"].(string); ok && !a2aTransportOverHTTP(pt) {- card["preferredTransport"] = "JSONRPC"+ base := fmt.Sprintf("http://%s/sam/%s/%s/%s", r.Host, route.peerID, route.serviceType, route.serviceName)+ if err := regenerateAgentCardForMesh(&card, base); err != nil {+ logger.Warnf("[A2A] agent card from %s unusable through the mesh: %v", route.peerID, err)+ http.Error(w, fmt.Sprintf("Bad Gateway: %v", err), http.StatusBadGateway)+ return true}- for _, key := range []string{"additionalInterfaces", "supportedInterfaces"} {- ifaces, ok := card[key].([]any)- if !ok {- continue- }- kept := make([]any, 0, len(ifaces))- for _, entry := range ifaces {- iface, ok := entry.(map[string]any)- if !ok {- continue- }- transport, _ := iface["transport"].(string)- if transport == "" {- transport, _ = iface["protocolBinding"].(string)- }- if !a2aTransportOverHTTP(transport) {- continue- }- iface["url"] = base- kept = append(kept, iface)- }- card[key] = kept+ out, err := json.Marshal(&card)+ if err != nil {+ http.Error(w, "Internal Server Error", http.StatusInternalServerError)+ return true}- if caps, ok := card["capabilities"].(map[string]any); ok {- caps["streaming"] = false+ w.Header().Set("Content-Type", "application/json")+ w.Header().Set("Content-Length", strconv.Itoa(len(out)))+ _, _ = w.Write(out)+ return true+}++// fetchRemoteAgentCard performs the mesh-side GET for the agent card, reusing+// the headers already prepared for egress (biscuit, agent claim, passthrough+// Authorization) on the incoming request.+func fetchRemoteAgentCard(node *SamNode, rt http.RoundTripper, r *http.Request, route egressRoute) (*http.Response, error) {+ ctx := allowLimitedEgressConn(r.Context())+ if node != nil {+ node.prepareEgressPeer(ctx, route.peerID)}- out, err := json.Marshal(card)+ url := fmt.Sprintf("libp2p://%s/%s/%s/%s", route.peerID, route.serviceType, route.serviceName, a2aAgentCardPath)+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)if err != nil {- return err+ return nil, err+ }+ req.Header = r.Header.Clone()+ // The node decodes the card itself, so negotiate identity encoding+ // regardless of what the held client asked for.+ req.Header.Del("Accept-Encoding")+ req.Host = route.peerID+ return (&http.Client{Transport: rt}).Do(req)+}++// regenerateAgentCardForMesh rebuilds a fetched agent card for mesh use:+// interface URLs point back at the mesh path, bindings the mesh cannot carry+// (gRPC) are dropped, streaming is advertised off until verified, and the+// original signatures are removed since they no longer match the content.+func regenerateAgentCardForMesh(card *a2a.AgentCard, base string) error {+ kept := make([]*a2a.AgentInterface, 0, len(card.SupportedInterfaces))+ for _, iface := range card.SupportedInterfaces {+ if iface == nil || !a2aBindingOverHTTP(iface.ProtocolBinding) {+ continue+ }+ iface.URL = base+ kept = append(kept, iface)}- resp.Body = io.NopCloser(bytes.NewReader(out))- resp.ContentLength = int64(len(out))- resp.Header.Set("Content-Length", strconv.Itoa(len(out)))+ if len(kept) == 0 {+ return fmt.Errorf("agent card advertises no supported interface the mesh can carry (JSONRPC or HTTP+JSON); is the agent serving a pre-1.0 A2A card?")+ }+ card.SupportedInterfaces = kept+ card.Capabilities.Streaming = false+ card.Signatures = nilreturn nil}-// a2aTransportOverHTTP reports whether an A2A transport can traverse the+// a2aBindingOverHTTP reports whether an A2A protocol binding can traverse the// mesh's HTTP-over-libp2p path; gRPC needs its own end-to-end connection.-func a2aTransportOverHTTP(transport string) bool {- return transport == "JSONRPC" || transport == "HTTP+JSON"+func a2aBindingOverHTTP(binding a2a.TransportProtocol) bool {+ switch strings.ToUpper(string(binding)) {+ case string(a2a.TransportProtocolJSONRPC), string(a2a.TransportProtocolHTTPJSON):+ return true+ }+ return false}diff --git a/internal/node/a2a_service_test.go b/internal/node/a2a_service_test.goindex 9a4c38f5..d8f80126 100644--- a/internal/node/a2a_service_test.go+++ b/internal/node/a2a_service_test.go@@ -17,12 +17,14 @@ package nodeimport ("context""encoding/json"+ "errors""io""net/http""net/http/httptest""strings""testing"+ "github.com/a2aproject/a2a-go/v2/a2a""github.com/google/sam/api")@@ -89,87 +91,103 @@ func TestA2AEgressHookMalformedLabels(t *testing.T) {}}-func TestA2AEgressHookTagsCardFetch(t *testing.T) {- rec := httptest.NewRecorder()- req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json", nil)- req.Host = "127.0.0.1:8080"- r2, ok := applyEgressMiddleware(nil, rec, req)- if !ok {- t.Fatal("card fetch must pass through")- }- base, _ := r2.Context().Value(a2aCardBaseURL{}).(string)- want := "http://127.0.0.1:8080/sam/12D3KooWpeer/a2a/agent"- if base != want {- t.Fatalf("card base = %q, want %q", base, want)+// roundTripFunc fakes the mesh transport for agent-card fetches.+type roundTripFunc func(*http.Request) (*http.Response, error)++func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func cardResponse(status int, body string) *http.Response {+ return &http.Response{+ StatusCode: status,+ Header: http.Header{"Content-Type": []string{"application/json"}},+ Body: io.NopCloser(strings.NewReader(body)),}}-func TestRewriteA2AAgentCard(t *testing.T) {- card := `{+func TestA2AServeAgentCardRegenerates(t *testing.T) {+ const upstreamCard = `{"name": "T",- "url": "http://localhost:9999",- "preferredTransport": "GRPC",- "additionalInterfaces": [- {"url": "http://localhost:9999", "transport": "JSONRPC"},- {"url": "localhost:50051", "transport": "GRPC"}- ],+ "description": "d",+ "version": "1.0.0",+ "capabilities": {"streaming": true},"supportedInterfaces": [- {"url": "http://localhost:9999", "protocolBinding": "JSONRPC"},- {"url": "localhost:50051", "protocolBinding": "GRPC"}+ {"url": "http://localhost:7777/", "protocolBinding": "JSONRPC", "protocolVersion": "1.0"},+ {"url": "localhost:50051", "protocolBinding": "GRPC", "protocolVersion": "1.0"}],- "capabilities": {"streaming": true}+ "signatures": [{"protected": "eyJh", "signature": "sig"}],+ "defaultInputModes": ["text"],+ "defaultOutputModes": ["text"],+ "skills": []}`- base := "http://127.0.0.1:8080/sam/12D3KooWpeer/a2a/agent"+ var outbound *http.Request+ rt := roundTripFunc(func(r *http.Request) (*http.Response, error) {+ outbound = r+ return cardResponse(http.StatusOK, upstreamCard), nil+ })++ rec := httptest.NewRecorder()req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json", nil)- req = req.WithContext(context.WithValue(req.Context(), a2aCardBaseURL{}, base))- resp := &http.Response{- StatusCode: http.StatusOK,- Header: http.Header{},- Body: io.NopCloser(strings.NewReader(card)),- Request: req,- }- if err := rewriteA2AAgentCard(resp); err != nil {- t.Fatal(err)- }- body, _ := io.ReadAll(resp.Body)- var got map[string]any- if err := json.Unmarshal(body, &got); err != nil {- t.Fatalf("rewritten card is not JSON: %v", err)- }- if got["url"] != base {- t.Errorf("url = %v, want %s", got["url"], base)- }- if got["preferredTransport"] != "JSONRPC" {- t.Errorf("preferredTransport = %v, want JSONRPC", got["preferredTransport"])- }- for _, key := range []string{"additionalInterfaces", "supportedInterfaces"} {- ifaces, _ := got[key].([]any)- if len(ifaces) != 1 {- t.Fatalf("%s: want 1 HTTP interface after dropping gRPC, got %v", key, got[key])- }- if u := ifaces[0].(map[string]any)["url"]; u != base {- t.Errorf("%s url = %v, want %s", key, u, base)- }+ req.Host = "127.0.0.1:8080"+ req.Header.Set(api.HeaderSamBiscuit, "b64-biscuit")+ req.Header.Set("Accept-Encoding", "gzip")+ if !serveEgressLocally(nil, rt, rec, req) {+ t.Fatal("agent-card GET must be handled locally")+ }++ wantURL := "libp2p://12D3KooWpeer/a2a/agent/.well-known/agent-card.json"+ if got := outbound.URL.String(); got != wantURL {+ t.Errorf("outbound fetch URL = %q, want %q", got, wantURL)}- if s := got["capabilities"].(map[string]any)["streaming"]; s != false {- t.Errorf("streaming = %v, want false", s)+ if outbound.Header.Get(api.HeaderSamBiscuit) != "b64-biscuit" {+ t.Error("egress headers must be carried on the card fetch")+ }+ if outbound.Header.Get("Accept-Encoding") != "" {+ t.Error("card fetch must negotiate identity encoding")}-}-func TestRewriteA2AAgentCardNoopWithoutTag(t *testing.T) {- orig := `{"name":"T","url":"http://localhost:9999"}`- resp := &http.Response{- StatusCode: http.StatusOK,- Header: http.Header{},- Body: io.NopCloser(strings.NewReader(orig)),- Request: httptest.NewRequest("GET", "/anything", nil),+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200, body: %s", rec.Code, rec.Body.String())+ }+ var card a2a.AgentCard+ if err := json.Unmarshal(rec.Body.Bytes(), &card); err != nil {+ t.Fatalf("regenerated card is not a valid AgentCard: %v", err)+ }+ base := "http://127.0.0.1:8080/sam/12D3KooWpeer/a2a/agent"+ if len(card.SupportedInterfaces) != 1 {+ t.Fatalf("want 1 HTTP interface after dropping gRPC, got %v", card.SupportedInterfaces)+ }+ if card.SupportedInterfaces[0].URL != base {+ t.Errorf("interface url = %q, want %q", card.SupportedInterfaces[0].URL, base)+ }+ if card.SupportedInterfaces[0].ProtocolBinding != a2a.TransportProtocolJSONRPC {+ t.Errorf("binding = %q, want JSONRPC", card.SupportedInterfaces[0].ProtocolBinding)+ }+ if card.Capabilities.Streaming {+ t.Error("streaming must be advertised off through the mesh")}- if err := rewriteA2AAgentCard(resp); err != nil {- t.Fatal(err)+ if len(card.Signatures) != 0 {+ t.Error("stale signatures must be dropped from the regenerated card")}- body, _ := io.ReadAll(resp.Body)- if string(body) != orig {- t.Fatalf("untagged response was modified: %s", body)+ if card.Name != "T" || card.Version != "1.0.0" {+ t.Errorf("agent identity fields must survive regeneration: %+v", card)+ }+}++func TestA2AServeAgentCardIgnoresNonCardRequests(t *testing.T) {+ rt := roundTripFunc(func(*http.Request) (*http.Response, error) {+ t.Fatal("no mesh fetch expected")+ return nil, nil+ })+ for _, tc := range []struct{ method, path string }{+ {"POST", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json"},+ {"GET", "/sam/12D3KooWpeer/a2a/agent/tasks/1"},+ {"GET", "/sam/12D3KooWpeer/mcp/svc/.well-known/agent-card.json"},+ } {+ rec := httptest.NewRecorder()+ req := httptest.NewRequest(tc.method, tc.path, nil)+ if serveEgressLocally(nil, rt, rec, req) {+ t.Errorf("%s %s must stream through the proxy", tc.method, tc.path)+ }}}@@ -186,43 +204,76 @@ func TestA2AEgressHookInvalidPeerID(t *testing.T) {}}-func TestRewriteA2AAgentCardSkipsNon200(t *testing.T) {- orig := `{"name":"T","url":"http://localhost:9999"}`- base := "http://127.0.0.1:8080/sam/12D3KooWpeer/a2a/agent"+func TestA2AServeAgentCardNoHTTPBindingFailsClosed(t *testing.T) {+ rt := roundTripFunc(func(*http.Request) (*http.Response, error) {+ return cardResponse(http.StatusOK,+ `{"name":"T","supportedInterfaces":[{"url":"localhost:50051","protocolBinding":"GRPC"}]}`), nil+ })+ rec := httptest.NewRecorder()req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json", nil)- req = req.WithContext(context.WithValue(req.Context(), a2aCardBaseURL{}, base))- resp := &http.Response{- StatusCode: http.StatusNotFound,- Header: http.Header{},- Body: io.NopCloser(strings.NewReader(orig)),- Request: req,+ if !serveEgressLocally(nil, rt, rec, req) {+ t.Fatal("card GET must be handled locally")}- if err := rewriteA2AAgentCard(resp); err != nil {- t.Fatal(err)+ if rec.Code != http.StatusBadGateway {+ t.Fatalf("status = %d, want 502", rec.Code)}- body, _ := io.ReadAll(resp.Body)- if string(body) != orig {- t.Fatalf("non-200 response was modified: %s", body)+ if !strings.Contains(rec.Body.String(), "mesh can carry") {+ t.Errorf("error must name the refusal reason, got: %s", rec.Body.String())}}-func TestRewriteA2AAgentCardSkipsContentEncoded(t *testing.T) {- orig := `{"name":"T","url":"http://localhost:9999"}`- base := "http://127.0.0.1:8080/sam/12D3KooWpeer/a2a/agent"+func TestA2AServeAgentCardPre10CardFailsClosed(t *testing.T) {+ // A2A v0.3-shaped card: interfaces live in additionalInterfaces, which the+ // v1.0 type does not carry, so regeneration must refuse rather than serve+ // a card with no usable interface.+ rt := roundTripFunc(func(*http.Request) (*http.Response, error) {+ return cardResponse(http.StatusOK, `{"name":"T","url":"http://localhost:9999",`++ `"preferredTransport":"JSONRPC",`++ `"additionalInterfaces":[{"url":"http://localhost:9999","transport":"JSONRPC"}]}`), nil+ })+ rec := httptest.NewRecorder()req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json", nil)- req = req.WithContext(context.WithValue(req.Context(), a2aCardBaseURL{}, base))- resp := &http.Response{- StatusCode: http.StatusOK,- Header: http.Header{"Content-Encoding": []string{"gzip"}},- Body: io.NopCloser(strings.NewReader(orig)),- Request: req,- }- if err := rewriteA2AAgentCard(resp); err != nil {- t.Fatal(err)- }- body, _ := io.ReadAll(resp.Body)- if string(body) != orig {- t.Fatalf("content-encoded response was modified: %s", body)+ if !serveEgressLocally(nil, rt, rec, req) {+ t.Fatal("card GET must be handled locally")+ }+ if rec.Code != http.StatusBadGateway {+ t.Fatalf("status = %d, want 502", rec.Code)+ }+ if !strings.Contains(rec.Body.String(), "pre-1.0") {+ t.Errorf("error must hint at the card vintage, got: %s", rec.Body.String())+ }+}++func TestA2AServeAgentCardRelaysUpstreamError(t *testing.T) {+ rt := roundTripFunc(func(*http.Request) (*http.Response, error) {+ resp := cardResponse(http.StatusNotFound, "no card here")+ resp.Header.Set("Content-Type", "text/plain")+ return resp, nil+ })+ rec := httptest.NewRecorder()+ req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json", nil)+ if !serveEgressLocally(nil, rt, rec, req) {+ t.Fatal("card GET must be handled locally")+ }+ if rec.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want the agent's own 404", rec.Code)+ }+ if !strings.Contains(rec.Body.String(), "no card here") {+ t.Errorf("agent's error body must be relayed, got: %s", rec.Body.String())+ }+}++func TestA2AServeAgentCardFetchErrorIs502(t *testing.T) {+ rt := roundTripFunc(func(*http.Request) (*http.Response, error) {+ return nil, errors.New("peer unreachable")+ })+ rec := httptest.NewRecorder()+ req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json", nil)+ if !serveEgressLocally(nil, rt, rec, req) {+ t.Fatal("card GET must be handled locally")+ }+ if rec.Code != http.StatusBadGateway {+ t.Fatalf("status = %d, want 502", rec.Code)}}diff --git a/internal/node/sidecar.go b/internal/node/sidecar.goindex 4b6992ab..b88d5bf4 100644--- a/internal/node/sidecar.go+++ b/internal/node/sidecar.go@@ -659,8 +659,10 @@ type egressMiddleware struct {// gateRequest may refuse the request (writing the HTTP error itself,// returning false) or return a derived request to forward.gateRequest func(node *SamNode, w http.ResponseWriter, r *http.Request, route egressRoute) (*http.Request, bool)- // modifyResponse edits the proxied response; nil means no hook.- modifyResponse func(*http.Response) error+ // serveLocal may fully handle the request at this node (returning true)+ // instead of letting it stream through the proxy; nil means no hook.+ // It runs after the egress headers (biscuit, agent claim) are prepared.+ serveLocal func(node *SamNode, rt http.RoundTripper, w http.ResponseWriter, r *http.Request, route egressRoute) bool}// egressRoute is the parsed /sam/{peer}/{type}/{svc}/{upstream} egress path,@@ -679,17 +681,26 @@ func registerEgressMiddleware(serviceType string, mw egressMiddleware) {egressMiddlewares[strings.ToLower(serviceType)] = mw}-// applyEgressMiddleware routes a raw egress request through the middleware-// registered for its service type, if any.-func applyEgressMiddleware(node *SamNode, w http.ResponseWriter, r *http.Request) (*http.Request, bool) {- parts := strings.SplitN(r.URL.Path, "/", 6)+// parseEgressRoute parses a /sam/{peer}/{type}/{svc}/{upstream} egress path.+func parseEgressRoute(path string) (egressRoute, bool) {+ parts := strings.SplitN(path, "/", 6)if len(parts) < 5 {- return r, true+ return egressRoute{}, false}route := egressRoute{peerID: parts[2], serviceType: strings.ToLower(parts[3]), serviceName: parts[4]}if len(parts) > 5 {route.upstreamPath = parts[5]}+ return route, true+}++// applyEgressMiddleware routes a raw egress request through the middleware+// registered for its service type, if any.+func applyEgressMiddleware(node *SamNode, w http.ResponseWriter, r *http.Request) (*http.Request, bool) {+ route, ok := parseEgressRoute(r.URL.Path)+ if !ok {+ return r, true+ }mw, ok := egressMiddlewares[route.serviceType]if !ok || mw.gateRequest == nil {return r, true@@ -697,15 +708,37 @@ func applyEgressMiddleware(node *SamNode, w http.ResponseWriter, r *http.Requestreturn mw.gateRequest(node, w, r, route)}-// egressModifyResponse dispatches to the middleware of the service type in-// the rewritten path (/{type}/{svc}/...); types without a hook pass through.-func egressModifyResponse(resp *http.Response) error {- parts := strings.SplitN(strings.TrimPrefix(resp.Request.URL.Path, "/"), "/", 2)- mw, ok := egressMiddlewares[strings.ToLower(parts[0])]- if !ok || mw.modifyResponse == nil {- return nil+// serveEgressLocally gives the service type's middleware a chance to answer+// the request from this node (e.g. agent-card regeneration) instead of+// proxying; it reports whether the request was handled.+func serveEgressLocally(node *SamNode, rt http.RoundTripper, w http.ResponseWriter, r *http.Request) bool {+ route, ok := parseEgressRoute(r.URL.Path)+ if !ok {+ return false+ }+ mw, ok := egressMiddlewares[route.serviceType]+ if !ok || mw.serveLocal == nil {+ return false+ }+ return mw.serveLocal(node, rt, w, r, route)+}++// allowLimitedEgressConn lets egress traffic ride limited (relayed) libp2p+// connections while a direct one is established.+func allowLimitedEgressConn(ctx context.Context) context.Context {+ return network.WithAllowLimitedConn(ctx, "egress-proxy")+}++// prepareEgressPeer warms up connectivity to the destination peer of an+// egress request if it is not already connected.+func (node *SamNode) prepareEgressPeer(ctx context.Context, peerID string) {+ pid, err := peer.Decode(peerID)+ if err != nil {+ return+ }+ if cond := node.Host.Network().Connectedness(pid); cond != network.Connected && cond != network.Limited {+ node.preparePeerAddrs(ctx, pid)}- return mw.modifyResponse(resp)}func createEgressProxy(node *SamNode) http.Handler {@@ -713,8 +746,7 @@ func createEgressProxy(node *SamNode) http.Handler {proxy := &httputil.ReverseProxy{Director: func(req *http.Request) {- ctx := req.Context()- ctx = network.WithAllowLimitedConn(ctx, "egress-proxy")+ ctx := allowLimitedEgressConn(req.Context())*req = *req.WithContext(ctx)parts := strings.SplitN(req.URL.Path, "/", 6)@@ -722,12 +754,7 @@ func createEgressProxy(node *SamNode) http.Handler {return}peerID := parts[2]- pid, err := peer.Decode(peerID)- if err == nil {- if cond := node.Host.Network().Connectedness(pid); cond != network.Connected && cond != network.Limited {- node.preparePeerAddrs(ctx, pid)- }- }+ node.prepareEgressPeer(ctx, peerID)serviceType := parts[3]serviceName := parts[4]upstreamPath := ""@@ -747,8 +774,7 @@ func createEgressProxy(node *SamNode) http.Handler {req.URL.RawPath = ""logger.Debugf("[Proxy] Rewriting URL to libp2p://%s%s", req.URL.Host, req.URL.Path)},- Transport: transport,- ModifyResponse: egressModifyResponse,+ Transport: transport,}return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -785,6 +811,10 @@ func createEgressProxy(node *SamNode) http.Handler {// "Authorization" header passes straight through untouched as the destination's own credential.r.Header.Del(api.HeaderSamAuthentication)+ if serveEgressLocally(node, transport, w, r) {+ return+ }+proxy.ServeHTTP(w, r)})}diff --git a/site/content/docs/use-cases/chat-a2a.md b/site/content/docs/use-cases/chat-a2a.mdindex accb519e..028d8590 100644--- a/site/content/docs/use-cases/chat-a2a.md+++ b/site/content/docs/use-cases/chat-a2a.md@@ -7,7 +7,7 @@ weight: 30Hold a multi-turn conversation with an [A2A](https://a2a-protocol.org/)(Agent2Agent) agent hosted on a remote mesh node — using a **stock,unmodified `a2a-sdk` client**. No SAM-specific client code: the mesh's-agent-card rewrite makes the standard SDK work as-is.+agent-card regeneration makes the standard SDK work as-is.Source: [`development/examples/chat-a2a/`](https://github.com/google/sam/tree/main/development/examples/chat-a2a).@@ -25,18 +25,19 @@ agent's own interface URLs — addresses that are only reachable on theprovider's machine. A stock client would fetch the card through the mesh,then try to talk to `http://127.0.0.1:7777/` and fail.-So the caller's node rewrites the card **in transit**: interface URLs are-pointed back at the mesh path the client fetched from, transports the mesh-cannot carry (gRPC needs its own end-to-end connection) are dropped, and-streaming is advertised off. The client follows the rewritten URLs like it-would for any A2A server — discovery, JSON-RPC `message/send`, and-`contextId` round-tripping all work unmodified, while the traffic actually-flows over libp2p between the nodes.+So the caller's node **impersonates the card endpoint**: it holds the+client's request, fetches the card from the agent over the mesh, and serves+a regenerated card — interface URLs point back at the mesh path the client+fetched from, protocol bindings the mesh cannot carry (gRPC needs its own+end-to-end connection) are dropped, and streaming is advertised off. The+client follows the regenerated card like it would for any A2A server —+discovery, JSON-RPC `message/send`, and `contextId` round-tripping all work+unmodified, while the traffic actually flows over libp2p between the nodes.This example proves both halves:-- **Card rewrite** — the bundled REPL is a plain `a2a-sdk` client; it works- only because the rewritten card sends it back through the mesh.+- **Card regeneration** — the bundled REPL is a plain `a2a-sdk` client; it+ works only because the regenerated card sends it back through the mesh.- **Conversation continuity** — the agent keeps one Gemini chat session perA2A `contextId`. Tell it your name, ask for it back two turns later: theanswer shows the context survived the mesh hop. Each turn is still its own@@ -61,7 +62,7 @@ This example proves both halves:LangGraph, a hosted agent) plugs in the same way, one `target_url` line inthe node config.- **Use any stock A2A client** — `chat.py` is just the smallest one. The- rewritten card means SDKs, CLIs, and other agents resolve and call the+ regenerated card means SDKs, CLIs, and other agents resolve and call theservice without knowing SAM exists.- **Let the agent own the conversation** — the same pattern as[Gemini Buddy](../gemini-buddy/), but on the standard A2A wire instead of a@@ -109,7 +110,7 @@ The local node is your entry point: its sidecar API listens onNote the peer ID and export it as `PEER`. Discovery is gossip-fed; retry fora few seconds after startup if the list comes back empty.-### 5. Watch the card rewrite happen+### 5. Watch the card regeneration happenFetch the agent card through the mesh with nothing but `curl`:@@ -120,7 +121,8 @@ curl -s -H 'X-Sam-Authentication: Bearer devtoken' \The interface URLs in the response point back at this`/sam/{peer}/a2a/chat` path — not at the agent's own `127.0.0.1:7777` — and-`capabilities.streaming` is `false`. That rewrite is the whole trick.+`capabilities.streaming` is `false`. That regenerated card is the whole+trick.### 6. Chatdiff --git a/site/content/docs/user/node-configuration.md b/site/content/docs/user/node-configuration.mdindex 413a6ddb..1c57c1b5 100644--- a/site/content/docs/user/node-configuration.md+++ b/site/content/docs/user/node-configuration.md@@ -73,7 +73,7 @@ When configuring `target_url` for `type: inference` services (e.g. Ollama, vLLM,When configuring `type: a2a` services (Agent2Agent protocol agents):* **URL backends only**: register the agent's local HTTP endpoint as `target_url`. `command` backends are rejected.-* **Raw Proxy Access**: remote peers reach the agent at `http://localhost:8080/sam/{peer}/a2a/{service}/...`. The agent card served at `.../.well-known/agent-card.json` is rewritten in transit so its interface URLs point back at this mesh path; transports the mesh cannot carry (gRPC) are dropped and streaming is advertised off.+* **Raw Proxy Access**: remote peers reach the agent at `http://localhost:8080/sam/{peer}/a2a/{service}/...`. For the agent card at `.../.well-known/agent-card.json`, the caller's node impersonates the endpoint: it fetches the card from the agent (A2A v1.0 format) and serves a regenerated one whose interface URLs point back at this mesh path; protocol bindings the mesh cannot carry (gRPC) are dropped, streaming is advertised off, and the original signatures are removed since the content changed.* **Label-gated egress**: setting `X-Sam-Required-Labels: key=value[,key=value]` on a raw a2a request makes the caller's node verify the provider's control-plane-attested labels and refuse fail-closed (HTTP 403) before any data leaves the node. The header is stripped before forwarding.* **Runnable example**: the [A2A Chat use case](../../use-cases/chat-a2a/) walks through hosting an a2a agent on a kind mesh and talking to it with a stock `a2a-sdk` client.diff --git a/tests/integration/a2a_test.go b/tests/integration/a2a_test.goindex 1d317223..721ea035 100644--- a/tests/integration/a2a_test.go+++ b/tests/integration/a2a_test.go@@ -82,10 +82,10 @@ func TestA2ACUJ(t *testing.T) {switch {case r.Method == http.MethodGet && r.URL.Path == "/.well-known/agent-card.json":w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"name":"echo-agent","url":"http://localhost:9999",` +- `"preferredTransport":"JSONRPC",` +- `"additionalInterfaces":[{"url":"http://localhost:9999","transport":"JSONRPC"},` +- `{"url":"localhost:50051","transport":"GRPC"}],` ++ _, _ = w.Write([]byte(`{"name":"echo-agent",` ++ `"supportedInterfaces":[` ++ `{"url":"http://localhost:9999","protocolBinding":"JSONRPC","protocolVersion":"1.0"},` ++ `{"url":"localhost:50051","protocolBinding":"GRPC","protocolVersion":"1.0"}],` +`"capabilities":{"streaming":true}}`))case r.Method == http.MethodPost:sendCount.Add(1)@@ -123,12 +123,10 @@ func TestA2ACUJ(t *testing.T) {time.Sleep(200 * time.Millisecond)}var card struct {- URL string `json:"url"`- PreferredTransport string `json:"preferredTransport"`- AdditionalInterfaces []struct {- URL string `json:"url"`- Transport string `json:"transport"`- } `json:"additionalInterfaces"`+ SupportedInterfaces []struct {+ URL string `json:"url"`+ ProtocolBinding string `json:"protocolBinding"`+ } `json:"supportedInterfaces"`Capabilities struct {Streaming bool `json:"streaming"`} `json:"capabilities"`@@ -136,11 +134,8 @@ func TestA2ACUJ(t *testing.T) {if err := json.Unmarshal(cardBody, &card); err != nil {t.Fatalf("invalid card: %v, body: %s", err, string(cardBody))}- if card.URL != meshBase {- t.Errorf("card url = %q, want mesh base %q", card.URL, meshBase)- }- if len(card.AdditionalInterfaces) != 1 || card.AdditionalInterfaces[0].URL != meshBase {- t.Errorf("interfaces not rewritten / gRPC not dropped: %s", string(cardBody))+ if len(card.SupportedInterfaces) != 1 || card.SupportedInterfaces[0].URL != meshBase {+ t.Errorf("interfaces not regenerated / gRPC not dropped: %s", string(cardBody))}if card.Capabilities.Streaming {t.Error("streaming must be advertised off through the mesh")