Skip to content

Agent Mesh

node: keep the interface path in the regenerated A2A agent card

Vitalii Cherepanov3373bf57c044
diff --git a/internal/node/a2a_service.go b/internal/node/a2a_service.go
index 666d81ee..6f1a9617 100644
--- a/internal/node/a2a_service.go
+++ b/internal/node/a2a_service.go
@@ -15,6 +15,7 @@
package node
import (
+ "bytes"
"context"
"crypto/sha256"
"encoding/hex"
@@ -22,6 +23,7 @@ import (
"fmt"
"io"
"net/http"
+ "net/url"
"strconv"
"strings"
@@ -45,10 +47,15 @@ type A2AService struct{ baseService }
func (s *A2AService) Init(ctx context.Context) error {
switch x := s.backend.(type) {
case *api.RegisterServiceRequest_TargetUrl:
- h, err := newReverseProxyHandler(x.TargetUrl)
+ h, err := newReverseProxy(x.TargetUrl)
if err != nil {
return err
}
+ target, err := parseBackendTarget(x.TargetUrl)
+ if err != nil {
+ return err
+ }
+ h.ModifyResponse = relativizeAgentCardResponse(s.info.GetName(), target.url.EscapedPath())
s.handler = h
case *api.RegisterServiceRequest_Command:
return fmt.Errorf("command-based backends are not supported for A2AService")
@@ -250,7 +257,7 @@ func regenerateAgentCardForMesh(card *a2a.AgentCard, base string) error {
if iface == nil || !a2aBindingOverHTTP(iface.ProtocolBinding) {
continue
}
- iface.URL = base
+ iface.URL = meshInterfaceURL(base, iface.URL)
kept = append(kept, iface)
}
if len(kept) == 0 {
@@ -272,6 +279,147 @@ func regenerateAgentCardForMesh(card *a2a.AgentCard, base string) error {
return nil
}
+// meshInterfaceURL is the mesh URL of one agent interface. The provider's
+// node names an interface it can reach by a reference relative to the
+// service root (relativizeAgentCard), which resolves under base; anything
+// else maps to base itself, as a card from an older provider or from an SDK
+// member always has. A reference that could leave the service (a dot
+// segment, a rooted path, a scheme or a host) also maps to base: a provider
+// must not be able to point the caller at another path on this node.
+func meshInterfaceURL(base, raw string) string {
+ ref, err := url.Parse(raw)
+ if err != nil || ref.Scheme != "" || ref.Host != "" || ref.User != nil || ref.Opaque != "" ||
+ strings.HasPrefix(ref.Path, "/") || hasDotSegment(ref.Path) {
+ return base
+ }
+ out := base
+ if ref.Path != "" {
+ out += "/" + ref.EscapedPath()
+ }
+ if ref.RawQuery != "" {
+ out += "?" + ref.RawQuery
+ }
+ return out
+}
+
+// relativizeAgentCardResponse rewrites the agent card the provider's backend
+// serves so that every interface under the service's target URL is named
+// relative to it: an agent whose JSON-RPC endpoint is "/invoke", or whose
+// HTTP+JSON binding lives under "/rest", stays reachable at the same path
+// below the mesh URL. Only the provider knows the target URL, so this is the
+// one place that can compute that path; the caller's node resolves it
+// (meshInterfaceURL). A card it cannot parse is relayed unchanged.
+func relativizeAgentCardResponse(service, targetPath string) func(*http.Response) error {
+ root := strings.TrimSuffix(targetPath, "/")
+ cardPath := root + "/" + a2aAgentCardPath
+ return func(resp *http.Response) error {
+ if resp.Request == nil || resp.Request.Method != http.MethodGet || resp.Request.URL.EscapedPath() != cardPath ||
+ resp.StatusCode != http.StatusOK {
+ return nil
+ }
+ if enc := resp.Header.Get("Content-Encoding"); enc != "" {
+ logger.Warnf("[A2A] agent card of %q is compressed (%s), relayed with its interface URLs unchanged", service, enc)
+ return nil
+ }
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, maxAgentCardBytes+1))
+ if err != nil {
+ return fmt.Errorf("read agent card of %q: %w", service, err)
+ }
+ if len(raw) > maxAgentCardBytes {
+ logger.Warnf("[A2A] agent card of %q exceeds %d bytes, relayed with its interface URLs unchanged", service, maxAgentCardBytes)
+ resp.Body = struct {
+ io.Reader
+ io.Closer
+ }{io.MultiReader(bytes.NewReader(raw), resp.Body), resp.Body}
+ return nil
+ }
+ if err := resp.Body.Close(); err != nil {
+ logger.Debugf("[A2A] close agent card body of %q: %v", service, err)
+ }
+ out, outside, err := relativizeAgentCard(raw, root)
+ if err != nil {
+ logger.Warnf("[A2A] agent card of %q relayed with its interface URLs unchanged: %v", service, err)
+ out = raw
+ }
+ for _, u := range outside {
+ logger.Warnf("[A2A] agent card of %q names interface %q outside target path %q; callers reach it at the service root", service, truncateForLog(u), targetPath)
+ }
+ resp.Body = io.NopCloser(bytes.NewReader(out))
+ resp.ContentLength = int64(len(out))
+ resp.Header.Set("Content-Length", strconv.Itoa(len(out)))
+ return nil
+ }
+}
+
+// relativizeAgentCard rewrites the url of every HTTP supportedInterfaces
+// entry whose path lies under root to a reference relative to root ("" for root
+// itself), and returns the absolute URLs it left as they were. Every other
+// member is kept as the agent wrote it.
+func relativizeAgentCard(raw []byte, root string) ([]byte, []string, error) {
+ var card map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &card); err != nil {
+ return nil, nil, fmt.Errorf("card is not a JSON object: %w", err)
+ }
+ ifacesRaw, ok := card["supportedInterfaces"]
+ if !ok {
+ return raw, nil, nil
+ }
+ var ifaces []map[string]json.RawMessage
+ if err := json.Unmarshal(ifacesRaw, &ifaces); err != nil {
+ return nil, nil, fmt.Errorf("supportedInterfaces is not a list of objects: %w", err)
+ }
+ var outside []string
+ for _, iface := range ifaces {
+ var u, binding string
+ if iface == nil || json.Unmarshal(iface["url"], &u) != nil || json.Unmarshal(iface["protocolBinding"], &binding) != nil ||
+ !a2aBindingOverHTTP(a2a.TransportProtocol(binding)) {
+ continue
+ }
+ rel, ok := relativeToRoot(u, root)
+ if !ok {
+ outside = append(outside, u)
+ continue
+ }
+ enc, err := json.Marshal(rel)
+ if err != nil {
+ return nil, nil, err
+ }
+ iface["url"] = enc
+ }
+ enc, err := json.Marshal(ifaces)
+ if err != nil {
+ return nil, nil, err
+ }
+ card["supportedInterfaces"] = enc
+ out, err := json.Marshal(card)
+ return out, outside, err
+}
+
+// relativeToRoot returns the part of an absolute interface URL below root,
+// without its leading slash, or ok=false when the URL is not under root.
+func relativeToRoot(raw, root string) (string, bool) {
+ u, err := url.Parse(raw)
+ if err != nil || !u.IsAbs() || u.Opaque != "" {
+ return "", false
+ }
+ p := u.EscapedPath()
+ var rest string
+ switch {
+ case p == root || p == root+"/":
+ case strings.HasPrefix(p, root+"/"):
+ rest = strings.TrimPrefix(p, root+"/")
+ default:
+ return "", false
+ }
+ if hasDotSegment(rest) {
+ return "", false
+ }
+ if u.RawQuery != "" {
+ rest += "?" + u.RawQuery
+ }
+ return rest, true
+}
+
// 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 a2aBindingOverHTTP(binding a2a.TransportProtocol) bool {
diff --git a/internal/node/a2a_service_test.go b/internal/node/a2a_service_test.go
index cfbf0860..7e625f2a 100644
--- a/internal/node/a2a_service_test.go
+++ b/internal/node/a2a_service_test.go
@@ -23,6 +23,7 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "strconv"
"strings"
"testing"
@@ -476,3 +477,163 @@ func TestA2AServeAgentCardCaching(t *testing.T) {
t.Errorf("If-None-Match with the agent's validator: status = %d, want 200", stale.Code)
}
}
+
+// TestA2AServiceCardKeepsInterfacePaths pins that an interface served below
+// the agent's root stays reachable through the mesh: the provider names it
+// relative to its target URL and the caller's card resolves it under the
+// mesh URL. Pointing every interface at the bare service root instead sends
+// a client of an agent whose JSON-RPC endpoint is "/invoke", or whose
+// HTTP+JSON binding lives under "/rest", to a path the agent does not serve.
+func TestA2AServiceCardKeepsInterfacePaths(t *testing.T) {
+ const base = "http://127.0.0.1:8080/mesh/12D3KooWpeer/a2a/agent"
+ for _, tc := range []struct {
+ name string
+ targetPath string
+ ifaces []string // url of each JSONRPC/HTTP+JSON interface, %s is the agent origin
+ want []string // url of each interface in the caller's card
+ }{
+ {
+ name: "agent at the target root",
+ targetPath: "",
+ ifaces: []string{"%s/invoke", "%s/a2a/rest", "%s", "%s/"},
+ want: []string{base + "/invoke", base + "/a2a/rest", base, base},
+ },
+ {
+ name: "target URL with a path",
+ targetPath: "/a2a/app",
+ ifaces: []string{"%s/a2a/app", "%s/a2a/app/rest", "%s/a2a/app/"},
+ want: []string{base, base + "/rest", base},
+ },
+ {
+ name: "interface outside the target keeps the service root",
+ targetPath: "/a2a/app",
+ ifaces: []string{"%s/other", "%s/a2a/application"},
+ want: []string{base, base},
+ },
+ {
+ name: "public URL in front of the agent",
+ targetPath: "",
+ ifaces: []string{"https://agent.example.com/v1/rpc?tenant=a"},
+ want: []string{base + "/v1/rpc?tenant=a"},
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var origin string
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != tc.targetPath+"/.well-known/agent-card.json" {
+ http.NotFound(w, r)
+ return
+ }
+ ifaces := make([]map[string]string, 0, len(tc.ifaces))
+ for i, u := range tc.ifaces {
+ binding := "JSONRPC"
+ if i%2 == 1 {
+ binding = "HTTP+JSON"
+ }
+ u = strings.Replace(u, "%s", origin, 1)
+ ifaces = append(ifaces, map[string]string{"url": u, "protocolBinding": binding, "protocolVersion": "1.0"})
+ }
+ // The mesh drops gRPC; the provider must leave it alone.
+ ifaces = append(ifaces, map[string]string{"url": "localhost:50051", "protocolBinding": "GRPC", "protocolVersion": "1.0"})
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(map[string]any{"name": "T", "supportedInterfaces": ifaces}); err != nil {
+ t.Errorf("encode card: %v", err)
+ }
+ }))
+ defer backend.Close()
+ origin = backend.URL
+
+ svc := &A2AService{baseService: baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_A2A, Name: "agent"},
+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: backend.URL + tc.targetPath},
+ }}
+ if err := svc.Init(context.Background()); err != nil {
+ t.Fatalf("Init: %v", err)
+ }
+ // The provider's ingress strips the routing prefix before the
+ // service handler sees the request.
+ provided := httptest.NewRecorder()
+ svc.Handler().ServeHTTP(provided, httptest.NewRequest("GET", "/.well-known/agent-card.json", nil))
+ if provided.Code != http.StatusOK {
+ t.Fatalf("provider card status = %d, body: %s", provided.Code, provided.Body.String())
+ }
+ if got, want := provided.Header().Get("Content-Length"), strconv.Itoa(provided.Body.Len()); got != want {
+ t.Errorf("provider Content-Length = %q, body is %s bytes", got, want)
+ }
+
+ rt := roundTripFunc(func(*http.Request) (*http.Response, error) {
+ return cardResponse(http.StatusOK, provided.Body.String()), nil
+ })
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "/mesh/12D3KooWpeer/a2a/agent/.well-known/agent-card.json", nil)
+ req.Host = "127.0.0.1:8080"
+ if !serveEgressLocally(nil, rt, rec, req) {
+ t.Fatal("card GET must be handled locally")
+ }
+ if rec.Code != http.StatusOK {
+ t.Fatalf("caller card status = %d, body: %s", rec.Code, rec.Body.String())
+ }
+ var card a2a.AgentCard
+ if err := json.Unmarshal(rec.Body.Bytes(), &card); err != nil {
+ t.Fatalf("caller card is not a valid AgentCard: %v", err)
+ }
+ if len(card.SupportedInterfaces) != len(tc.want) {
+ t.Fatalf("got %d interfaces, want %d: %+v", len(card.SupportedInterfaces), len(tc.want), card.SupportedInterfaces)
+ }
+ for i, iface := range card.SupportedInterfaces {
+ if iface.URL != tc.want[i] {
+ t.Errorf("interface %d url = %q, want %q", i, iface.URL, tc.want[i])
+ }
+ }
+ })
+ }
+}
+
+// TestMeshInterfaceURLStaysInService pins that a provider cannot use the
+// relative interface reference to point a caller at another path on the
+// caller's own node (its debug or admin endpoints, another peer).
+func TestMeshInterfaceURLStaysInService(t *testing.T) {
+ const base = "http://127.0.0.1:8080/mesh/12D3KooWpeer/a2a/agent"
+ for _, tc := range []struct{ ref, want string }{
+ {"", base},
+ {"invoke", base + "/invoke"},
+ {"a2a/rest/", base + "/a2a/rest/"},
+ {"?tenant=a", base + "?tenant=a"},
+ {"../../../../debug/connect-peer", base},
+ {"a/../../x", base},
+ {"%2e%2e/%2e%2e/debug", base},
+ {"./invoke", base},
+ {"/debug/connect-peer", base},
+ {"//evil.example/x", base},
+ {"http://localhost:7777/invoke", base},
+ {"mailto:[email protected]", base},
+ {"%zz", base},
+ } {
+ if got := meshInterfaceURL(base, tc.ref); got != tc.want {
+ t.Errorf("meshInterfaceURL(%q) = %q, want %q", tc.ref, got, tc.want)
+ }
+ }
+}
+
+// TestA2AServiceCardRelayedUnchangedWhenUnparseable pins that the provider's
+// card hook never turns an agent's odd response into an error of its own.
+func TestA2AServiceCardRelayedUnchangedWhenUnparseable(t *testing.T) {
+ for _, body := range []string{"<html>login</html>", `{"supportedInterfaces":"x"}`, `{"name":"no interfaces"}`} {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(body))
+ }))
+ svc := &A2AService{baseService: baseService{
+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_A2A, Name: "agent"},
+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: backend.URL},
+ }}
+ if err := svc.Init(context.Background()); err != nil {
+ t.Fatalf("Init: %v", err)
+ }
+ rec := httptest.NewRecorder()
+ svc.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/.well-known/agent-card.json", nil))
+ backend.Close()
+ if rec.Code != http.StatusOK || rec.Body.String() != body {
+ t.Errorf("card %q: got status %d body %q, want it relayed unchanged", body, rec.Code, rec.Body.String())
+ }
+ }
+}
diff --git a/internal/node/service.go b/internal/node/service.go
index 9a8339c7..12f0914b 100644
--- a/internal/node/service.go
+++ b/internal/node/service.go
@@ -52,6 +52,16 @@ type baseService struct {
// newReverseProxyHandler builds a single-host reverse-proxy handler for a
// URL backend. Same code path as today's URL branch in RegisterService.
func newReverseProxyHandler(targetURL string) (http.Handler, error) {
+ p, err := newReverseProxy(targetURL)
+ if err != nil {
+ return nil, err
+ }
+ return p, nil
+}
+
+// newReverseProxy is newReverseProxyHandler for a service type that hooks
+// the backend's responses (ModifyResponse).
+func newReverseProxy(targetURL string) (*httputil.ReverseProxy, error) {
target, err := parseBackendTarget(targetURL)
if err != nil {
return nil, err
diff --git a/site/content/docs/guides/exposing-services.md b/site/content/docs/guides/exposing-services.md
index fb011388..60e49c9e 100644
--- a/site/content/docs/guides/exposing-services.md
+++ b/site/content/docs/guides/exposing-services.md
@@ -137,8 +137,10 @@ by URL only:
Remote callers reach it at `/mesh/<peer-id>/a2a/triage/` on their own node.
The agent card gets special treatment. The caller's node fetches
`/.well-known/agent-card.json` from the agent and serves a regenerated card
-whose interface URLs point at the mesh path. Bindings that the mesh cannot
-carry (gRPC) are removed, and the original signatures are dropped because the
+whose interface URLs point at the mesh path. An interface served below the
+`target_url`, such as a JSON-RPC endpoint at `/invoke` or an HTTP+JSON
+binding under `/rest`, keeps that path below the mesh path. Bindings that the
+mesh cannot carry (gRPC) are removed, and the original signatures are dropped because the
content changed. Standard A2A client SDKs then work without changes. Cards
must use the A2A 1.0 format. Older formats are refused. The
[A2A chat use case](../../use-cases/chat-a2a/) runs one end to end.
diff --git a/tests/integration/a2a_test.go b/tests/integration/a2a_test.go
index 64ec1d4c..2a91610f 100644
--- a/tests/integration/a2a_test.go
+++ b/tests/integration/a2a_test.go
@@ -69,14 +69,29 @@ func TestA2ACUJ(t *testing.T) {
// Stock-SDK A2A agent on node A's side: a2asrv serving its card and
// echoing message/send. The card deliberately advertises a gRPC
// interface and a stale signature, which the mesh must drop on
- // regeneration, and streaming, which it must keep and carry. The backend
- // exists before the node: services are declared in the node's
- // configuration, never registered at runtime.
+ // regeneration, and streaming, which it must keep and carry. Its
+ // JSON-RPC endpoint is "/invoke", as in the a2a-go samples, not the
+ // root: the mesh URL must keep that path. The backend exists before
+ // the node: services are declared in the node's configuration, never
+ // registered at runtime.
var sendCount atomic.Int32
var sawLabelsHeader atomic.Bool
+ firstStreamEventSeen := make(chan struct{})
echo := a2asrv.AgentExecutorFunc(func(ctx context.Context, ec *a2asrv.ExecutorContext) iter.Seq2[a2a.Event, error] {
return func(yield func(a2a.Event, error) bool) {
sendCount.Add(1)
+ if len(ec.Message.Parts) > 0 && ec.Message.Parts[0].Text() == "stream" {
+ if !yield(a2a.NewSubmittedTask(ec, ec.Message), nil) {
+ return
+ }
+ select {
+ case <-firstStreamEventSeen:
+ case <-ctx.Done():
+ return
+ }
+ yield(a2a.NewStatusUpdateEvent(ec, a2a.TaskStateCompleted, a2a.NewMessageForTask(a2a.MessageRoleAgent, ec, a2a.NewTextPart("echo from eu"))), nil)
+ return
+ }
yield(a2a.NewMessageForTask(a2a.MessageRoleAgent, ec, a2a.NewTextPart("echo from eu")), nil)
}
})
@@ -86,14 +101,14 @@ func TestA2ACUJ(t *testing.T) {
Version: "1.0.0",
Capabilities: a2a.AgentCapabilities{Streaming: true},
SupportedInterfaces: []*a2a.AgentInterface{
- {URL: "http://localhost:9999", ProtocolBinding: a2a.TransportProtocolJSONRPC, ProtocolVersion: "1.0"},
+ {URL: "http://localhost:9999/invoke", ProtocolBinding: a2a.TransportProtocolJSONRPC, ProtocolVersion: "1.0"},
{URL: "localhost:50051", ProtocolBinding: a2a.TransportProtocolGRPC, ProtocolVersion: "1.0"},
},
Signatures: []a2a.AgentCardSignature{{Protected: "eyJhbGciOiJFUzI1NiJ9", Signature: "c3RhbGU"}},
}
mux := http.NewServeMux()
mux.Handle(a2asrv.WellKnownAgentCardPath, a2asrv.NewStaticAgentCardHandler(agentCard))
- mux.Handle("/", a2asrv.NewJSONRPCHandler(a2asrv.NewHandler(echo)))
+ mux.Handle("/invoke", a2asrv.NewJSONRPCHandler(a2asrv.NewHandler(echo)))
agent := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(api.HeaderMeshRequiredLabels) != "" {
sawLabelsHeader.Store(true)
@@ -149,8 +164,8 @@ func TestA2ACUJ(t *testing.T) {
}
time.Sleep(200 * time.Millisecond)
}
- if len(card.SupportedInterfaces) != 1 || card.SupportedInterfaces[0].URL != meshBase {
- t.Errorf("interfaces not regenerated / gRPC not dropped: %+v", card.SupportedInterfaces)
+ if len(card.SupportedInterfaces) != 1 || card.SupportedInterfaces[0].URL != meshBase+"/invoke" {
+ t.Errorf("interfaces not regenerated / gRPC not dropped: got %+v, want exactly one interface with URL %q", card.SupportedInterfaces, meshBase+"/invoke")
}
if card.SupportedInterfaces[0].ProtocolBinding != a2a.TransportProtocolJSONRPC {
t.Errorf("binding = %q, want JSONRPC", card.SupportedInterfaces[0].ProtocolBinding)
@@ -191,19 +206,29 @@ func TestA2ACUJ(t *testing.T) {
}
// CUJ step 2b: the card keeps streaming, so the same client may stream
- // the exchange; the SSE response must cross the mesh as it is.
+ // the exchange; the SSE response must flush across the mesh as each
+ // event is emitted (not buffered until EOF): the server holds the final
+ // event until the client confirms it received the first one.
+ streamReq := &a2a.SendMessageRequest{Message: a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("stream"))}
var streamed []a2a.Event
- for event, err := range euClient.SendStreamingMessage(ctx, req) {
+ for event, err := range euClient.SendStreamingMessage(ctx, streamReq) {
if err != nil {
t.Fatalf("streamed message/send failed: %v", err)
}
streamed = append(streamed, event)
+ if len(streamed) == 1 {
+ close(firstStreamEventSeen)
+ }
+ }
+ if len(streamed) != 2 {
+ t.Fatalf("streamed %d events, want 2 (submitted task + completed status): %+v", len(streamed), streamed)
}
- if len(streamed) != 1 {
- t.Fatalf("streamed %d events, want the one echo: %+v", len(streamed), streamed)
+ if task, ok := streamed[0].(*a2a.Task); !ok || task.Status.State != a2a.TaskStateSubmitted {
+ t.Fatalf("first streamed event = %+v, want *a2a.Task in state %q", streamed[0], a2a.TaskStateSubmitted)
}
- if msg, ok := streamed[0].(*a2a.Message); !ok || len(msg.Parts) == 0 || msg.Parts[0].Text() != "echo from eu" {
- t.Fatalf("streamed event = %+v, want a message with text %q", streamed[0], "echo from eu")
+ if ev, ok := streamed[1].(*a2a.TaskStatusUpdateEvent); !ok || ev.Status.State != a2a.TaskStateCompleted ||
+ ev.Status.Message == nil || len(ev.Status.Message.Parts) == 0 || ev.Status.Message.Parts[0].Text() != "echo from eu" {
+ t.Fatalf("second streamed event = %+v, want completed TaskStatusUpdateEvent with text %q", streamed[1], "echo from eu")
}
// CUJ step 3: a mismatched label refuses fail-closed BEFORE egress —