diff --git a/internal/node/a2a_service.go b/internal/node/a2a_service.go index 14c1101ae..9817301a3 100644 --- a/internal/node/a2a_service.go +++ b/internal/node/a2a_service.go @@ -24,6 +24,7 @@ import ( "io" "net/http" "net/url" + "path" "strconv" "strings" @@ -35,7 +36,9 @@ import ( func init() { registerEgressMiddleware(api.ServiceTypeStringA2A, egressMiddleware{ gateRequest: a2aEgressGate, - serveLocal: a2aServeAgentCard, + serveLocal: func(node *AgentMeshNode, rt http.RoundTripper, w http.ResponseWriter, r *http.Request, route egressRoute) bool { + return a2aServeAgentCard(node, rt, w, r, route) || a2aServeExtendedAgentCard(node, rt, w, r, route) + }, }) } @@ -169,8 +172,7 @@ func a2aServeAgentCard(node *AgentMeshNode, rt http.RoundTripper, w http.Respons http.Error(w, "Bad Gateway: agent card is not valid JSON", http.StatusBadGateway) return true } - base := fmt.Sprintf("http://%s/mesh/%s/%s/%s", r.Host, route.peerID, route.serviceType, route.serviceName) - if err := regenerateAgentCardForMesh(&card, base); err != nil { + if err := regenerateAgentCardForMesh(&card, meshServiceBase(r, route)); 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 @@ -223,15 +225,38 @@ func etagMatches(header, etag string) bool { // the headers already prepared for egress (biscuit, agent claim, passthrough // Authorization) on the incoming request. func fetchRemoteAgentCard(node *AgentMeshNode, rt http.RoundTripper, r *http.Request, route egressRoute) (*http.Response, error) { + // The well-known public card is a different resource than the held + // client request, so that request's query string is not forwarded. + if r.URL != nil && r.URL.RawQuery != "" { + clone := r.Clone(r.Context()) + clone.URL.RawQuery = "" + r = clone + } + return a2aMeshRequest(node, rt, r, route, http.MethodGet, a2aAgentCardPath, nil) +} + +// a2aMeshRequest sends one request to the agent over the mesh on behalf of +// a held client request whose card answer this node rewrites itself. +func a2aMeshRequest(node *AgentMeshNode, rt http.RoundTripper, r *http.Request, route egressRoute, method, upstreamPath string, body []byte) (*http.Response, error) { ctx := allowLimitedEgressConn(r.Context()) if node != nil { node.prepareEgressPeer(ctx, route.peerID) } - url := fmt.Sprintf("libp2p://%s/%s/%s/%s", route.peerID, route.serviceType, route.serviceName, a2aAgentCardPath) - req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + meshPath := fmt.Sprintf("/%s/%s", route.serviceType, route.serviceName) + if upstreamPath != "" { + meshPath += "/" + upstreamPath + } + var reader io.Reader + if body != nil { + reader = bytes.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, "libp2p://"+route.peerID+meshPath, reader) if err != nil { return nil, err } + if r.URL != nil { + req.URL.RawQuery = r.URL.RawQuery + } req.Header = r.Header.Clone() // The node decodes the card itself, so negotiate identity encoding // regardless of what the held client asked for, and ask for the whole @@ -244,13 +269,173 @@ func fetchRemoteAgentCard(node *AgentMeshNode, rt http.RoundTripper, r *http.Req return (&http.Client{Transport: rt}).Do(req) } +// meshServiceBase is the mesh URL of the service a held client request +// names, which every interface of a card served to that client points at. +func meshServiceBase(r *http.Request, route egressRoute) string { + return fmt.Sprintf("http://%s/mesh/%s/%s/%s", r.Host, route.peerID, route.serviceType, route.serviceName) +} + +// a2aExtendedCardMethod is the JSON-RPC method that returns the extended +// agent card (A2A 1.0, section 3.1.11); a2aExtendedCardSegment ends its +// HTTP+JSON path. +const ( + a2aExtendedCardMethod = "GetExtendedAgentCard" + a2aExtendedCardSegment = "extendedAgentCard" +) + +// maxExtendedCardRequestBytes bounds how much of a JSON-RPC request body the +// node reads to tell a GetExtendedAgentCard call apart. That call carries +// no more than a tenant, so a body past the bound is relayed unread and the +// streaming egress path stays as it was for every other method. +const maxExtendedCardRequestBytes = 64 << 10 + +// a2aServeExtendedAgentCard answers a GetExtendedAgentCard call (JSON-RPC, +// or GET .../extendedAgentCard over HTTP+JSON) from this node: it forwards +// the call to the agent, then serves the extended card with its interfaces +// redacted (redactExtendedAgentCardForMesh), so a client that replaces its +// card with this one (A2A 1.0, section 3.1.11) keeps talking through the +// mesh and never learns the agent's own URLs. Other requests are left to +// the streaming egress proxy, with their body intact. +func a2aServeExtendedAgentCard(node *AgentMeshNode, rt http.RoundTripper, w http.ResponseWriter, r *http.Request, route egressRoute) bool { + body, ok := extendedAgentCardCall(r, route) + if !ok { + return false + } + resp, err := a2aMeshRequest(node, rt, r, route, r.Method, route.upstreamPath, body) + if err != nil { + logger.Warnf("[A2A] extended agent card call to %s failed: %v", route.peerID, err) + http.Error(w, "Bad Gateway: extended agent card call failed", http.StatusBadGateway) + return true + } + defer func() { _ = resp.Body.Close() }() + raw, err := io.ReadAll(io.LimitReader(resp.Body, maxAgentCardBytes+1)) + if err != nil || len(raw) > maxAgentCardBytes { + logger.Warnf("[A2A] extended agent card from %s unreadable or over %d bytes: %v", route.peerID, maxAgentCardBytes, err) + http.Error(w, "Bad Gateway: extended agent card unreadable", http.StatusBadGateway) + return true + } + 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) + _, _ = w.Write(raw) + return true + } + + // The extended card is the whole HTTP+JSON body, or the JSON-RPC result; + // a JSON-RPC error carries no card and is relayed as-is. + var envelope map[string]json.RawMessage + cardJSON := raw + if body != nil { + if err := json.Unmarshal(raw, &envelope); err != nil { + logger.Warnf("[A2A] extended agent card response from %s is not a JSON-RPC response: %v", route.peerID, err) + http.Error(w, "Bad Gateway: extended agent card response is not valid JSON-RPC", http.StatusBadGateway) + return true + } + result, ok := envelope["result"] + errField, hasErr := envelope["error"] + // A JSON-RPC error may also serialize "result": null. Relay it + // unchanged; only a non-null result is a card to redact. + if !ok || bytes.Equal(bytes.TrimSpace(result), []byte("null")) || + (hasErr && !bytes.Equal(bytes.TrimSpace(errField), []byte("null"))) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(raw) + return true + } + cardJSON = result + } + out, err := redactedExtendedAgentCard(node, rt, r, route, cardJSON) + if err != nil { + logger.Warnf("[A2A] extended 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 + } + if envelope != nil { + envelope["result"] = out + if out, err = json.Marshal(envelope); err != nil { + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return true + } + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(len(out))) + _, _ = w.Write(out) + return true +} + +// extendedAgentCardCall reports whether r is a GetExtendedAgentCard call, +// returning the JSON-RPC body to forward (nil over HTTP+JSON). It leaves +// r.Body readable from the start either way. +func extendedAgentCardCall(r *http.Request, route egressRoute) ([]byte, bool) { + switch r.Method { + case http.MethodGet: + // The last segment, unless it is a task or push config ID. + parent := path.Base(path.Dir(route.upstreamPath)) + return nil, path.Base(route.upstreamPath) == a2aExtendedCardSegment && parent != "tasks" && parent != "pushNotificationConfigs" + case http.MethodPost: + if r.Body == nil || r.Body == http.NoBody { + return nil, false + } + peeked, err := io.ReadAll(io.LimitReader(r.Body, maxExtendedCardRequestBytes+1)) + r.Body = struct { + io.Reader + io.Closer + }{io.MultiReader(bytes.NewReader(peeked), r.Body), r.Body} + if err != nil || len(peeked) > maxExtendedCardRequestBytes { + return nil, false + } + // Decoded as Go A2A servers decode it: member names match + // case-insensitively and the last duplicate wins. + var call struct { + Method string `json:"method"` + } + if json.Unmarshal(peeked, &call) != nil || call.Method != a2aExtendedCardMethod { + return nil, false + } + return peeked, true + } + return nil, false +} + +// redactedExtendedAgentCard decodes the agent's extended card and returns it +// redacted against the public card this node serves for the same service. +func redactedExtendedAgentCard(node *AgentMeshNode, rt http.RoundTripper, r *http.Request, route egressRoute, raw []byte) ([]byte, error) { + var ext a2a.AgentCard + if err := json.Unmarshal(raw, &ext); err != nil { + return nil, fmt.Errorf("extended agent card is not valid JSON: %w", err) + } + resp, err := fetchRemoteAgentCard(node, rt, r, route) + if err != nil { + return nil, fmt.Errorf("agent card fetch failed: %w", err) + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("agent card fetch: %s", resp.Status) + } + var public a2a.AgentCard + if err := json.NewDecoder(io.LimitReader(resp.Body, maxAgentCardBytes)).Decode(&public); err != nil { + return nil, fmt.Errorf("agent card is not valid JSON: %w", err) + } + if err := regenerateAgentCardForMesh(&public, meshServiceBase(r, route)); err != nil { + return nil, err + } + if err := redactExtendedAgentCardForMesh(&ext, &public); err != nil { + return nil, err + } + return json.Marshal(&ext) +} + // 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, and the original signatures are removed since they no // longer match the content. Capabilities stay as the agent declares them: // the egress proxy relays an SSE stream as it arrives, and a card that turned // streaming off would oblige the agent behind it to refuse SendStreamingMessage -// and SubscribeToTask (A2A 1.0, section 3.3.4), which it does not do. +// and SubscribeToTask (A2A 1.0, section 3.3.4), which it does not do. The +// extended card stays declared too: this node redacts it when a client asks +// for it (a2aServeExtendedAgentCard). func regenerateAgentCardForMesh(card *a2a.AgentCard, base string) error { kept := make([]*a2a.AgentInterface, 0, len(card.SupportedInterfaces)) for _, iface := range card.SupportedInterfaces { @@ -265,8 +450,68 @@ func regenerateAgentCardForMesh(card *a2a.AgentCard, base string) error { } card.SupportedInterfaces = kept card.Signatures = nil - // Required list fields must stay arrays: encoding/json marshals nil - // slices as null, which strict SDK card parsers (pydantic) reject. + keepRequiredCardLists(card) + return nil +} + +// redactExtendedAgentCardForMesh rebuilds the agent's extended card for mesh +// use against public, the card regenerated for the same service: an +// interface the mesh carries takes the mesh URL public gives its binding, +// and an interface whose binding public does not offer (gRPC, or one only +// reachable inside the agent's network) is dropped, so none of the agent's +// own URLs reach the client. Signatures go as on the public card, since the +// content changed. Skills, input and output modes and every other member +// stay as the agent wrote them: they are what the extended card is for. +func redactExtendedAgentCardForMesh(card, public *a2a.AgentCard) error { + kept := make([]*a2a.AgentInterface, 0, len(card.SupportedInterfaces)) + seen := map[a2a.AgentInterface]bool{} + for _, iface := range card.SupportedInterfaces { + if iface == nil || !a2aBindingOverHTTP(iface.ProtocolBinding) { + continue + } + meshURL, ok := meshURLForBinding(public, iface) + if !ok { + continue + } + redacted := *iface + redacted.URL = meshURL + if seen[redacted] { + continue + } + seen[redacted] = true + kept = append(kept, &redacted) + } + if len(kept) == 0 { + return fmt.Errorf("extended agent card advertises no interface the mesh carries for this agent") + } + card.SupportedInterfaces = kept + card.Signatures = nil + keepRequiredCardLists(card) + return nil +} + +// meshURLForBinding is the URL the regenerated public card gives iface's +// protocol binding, preferring an interface of the same protocol version. +func meshURLForBinding(public *a2a.AgentCard, iface *a2a.AgentInterface) (string, bool) { + fallback, found := "", false + for _, p := range public.SupportedInterfaces { + if !strings.EqualFold(string(p.ProtocolBinding), string(iface.ProtocolBinding)) { + continue + } + if p.ProtocolVersion == iface.ProtocolVersion { + return p.URL, true + } + if !found { + fallback, found = p.URL, true + } + } + return fallback, found +} + +// keepRequiredCardLists keeps the card's required list fields arrays: +// encoding/json marshals nil slices as null, which strict SDK card parsers +// (pydantic) reject. +func keepRequiredCardLists(card *a2a.AgentCard) { if card.Skills == nil { card.Skills = []a2a.AgentSkill{} } @@ -276,7 +521,6 @@ func regenerateAgentCardForMesh(card *a2a.AgentCard, base string) error { if card.DefaultOutputModes == nil { card.DefaultOutputModes = []string{} } - return nil } // meshInterfaceURL is the mesh URL of one agent interface. The provider's diff --git a/internal/node/a2a_service_test.go b/internal/node/a2a_service_test.go index 7e625f2af..0765c52ff 100644 --- a/internal/node/a2a_service_test.go +++ b/internal/node/a2a_service_test.go @@ -166,7 +166,7 @@ func TestA2AServeAgentCardRegenerates(t *testing.T) { "name": "T", "description": "d", "version": "1.0.0", - "capabilities": {"streaming": true}, + "capabilities": {"streaming": true, "extendedAgentCard": true}, "supportedInterfaces": [ {"url": "http://localhost:7777/", "protocolBinding": "JSONRPC", "protocolVersion": "1.0"}, {"url": "localhost:50051", "protocolBinding": "GRPC", "protocolVersion": "1.0"} @@ -222,14 +222,307 @@ func TestA2AServeAgentCardRegenerates(t *testing.T) { if !card.Capabilities.Streaming { t.Errorf("streaming = %v, want true as the agent declares it", card.Capabilities.Streaming) } + if !card.Capabilities.ExtendedAgentCard { + t.Errorf("extendedAgentCard = %v, want true as the agent declares it", card.Capabilities.ExtendedAgentCard) + } if len(card.Signatures) != 0 { - t.Error("stale signatures must be dropped from the regenerated card") + t.Errorf("len(signatures) = %d, want 0: stale signatures must be dropped from the regenerated card", len(card.Signatures)) } if card.Name != "T" || card.Version != "1.0.0" { t.Errorf("agent identity fields must survive regeneration: %+v", card) } } +// extendedCardAgent fakes the mesh transport for an agent whose public card +// names its JSON-RPC endpoint "invoke" and its HTTP+JSON binding "rest" +// (as the provider's node relativizes them), and whose extended card names +// its own URLs, private ones included, and adds a skill and an input mode. +// Extended card calls answer with extended; every outbound request is kept. +func extendedCardAgent(t *testing.T, extended func(*http.Request) *http.Response) (http.RoundTripper, *[]*http.Request) { + t.Helper() + var outbound []*http.Request + return roundTripFunc(func(r *http.Request) (*http.Response, error) { + outbound = append(outbound, r) + if r.Method == http.MethodGet && r.URL.Path == "/a2a/agent/.well-known/agent-card.json" { + return cardResponse(http.StatusOK, `{ + "name": "T", "version": "1.0.0", + "capabilities": {"extendedAgentCard": true}, + "supportedInterfaces": [ + {"url": "invoke", "protocolBinding": "JSONRPC", "protocolVersion": "1.0"}, + {"url": "rest", "protocolBinding": "HTTP+JSON", "protocolVersion": "1.0"} + ], + "skills": [{"id": "echo", "name": "echo", "description": "d", "tags": []}], + "defaultInputModes": ["text"], "defaultOutputModes": ["text"] + }`), nil + } + return extended(r), nil + }), &outbound +} + +const extendedCardJSON = `{ + "name": "T", "version": "1.0.0", + "capabilities": {"extendedAgentCard": true}, + "supportedInterfaces": [ + {"url": "http://10.0.0.5:7777/invoke", "protocolBinding": "JSONRPC", "protocolVersion": "1.0"}, + {"url": "http://agent.internal:8080/rest", "protocolBinding": "HTTP+JSON", "protocolVersion": "1.0", "tenant": "t1"}, + {"url": "10.0.0.5:50051", "protocolBinding": "GRPC", "protocolVersion": "1.0"} + ], + "signatures": [{"protected": "eyJh", "signature": "sig"}], + "skills": [ + {"id": "echo", "name": "echo", "description": "d", "tags": []}, + {"id": "vision", "name": "vision", "description": "d", "tags": []} + ], + "defaultInputModes": ["text", "image/png"], "defaultOutputModes": ["text"] +}` + +// privateCardURLs are the agent's own URLs in extendedCardJSON; none may +// reach a client of the mesh. +var privateCardURLs = []string{"10.0.0.5", "agent.internal"} + +// checkRedactedExtendedCard checks an extended card served through the mesh: +// interfaces at the mesh URLs of the public card, the agent's own URLs gone, +// the extended skills and input modes kept, the stale signature dropped. +func checkRedactedExtendedCard(t *testing.T, raw []byte, card *a2a.AgentCard) { + t.Helper() + for _, private := range privateCardURLs { + if strings.Contains(string(raw), private) { + t.Errorf("served extended card names %q, want none of the agent's own URLs: %s", private, raw) + } + } + base := "http://127.0.0.1:8080/mesh/12D3KooWpeer/a2a/agent" + var got []string + for _, iface := range card.SupportedInterfaces { + got = append(got, string(iface.ProtocolBinding)+" "+iface.URL+" "+iface.Tenant) + } + want := []string{"JSONRPC " + base + "/invoke ", "HTTP+JSON " + base + "/rest t1"} + if strings.Join(got, ", ") != strings.Join(want, ", ") { + t.Errorf("interfaces = %q, want %q", got, want) + } + if !card.Capabilities.ExtendedAgentCard { + t.Errorf("extendedAgentCard = %v, want true as the agent declares it", card.Capabilities.ExtendedAgentCard) + } + if len(card.Skills) != 2 || card.Skills[1].ID != "vision" { + t.Errorf("skills = %+v, want the agent's two extended skills (echo, vision)", card.Skills) + } + if got, want := strings.Join(card.DefaultInputModes, ","), "text,image/png"; got != want { + t.Errorf("defaultInputModes = %q, want %q", got, want) + } + if len(card.Signatures) != 0 { + t.Errorf("len(signatures) = %d, want 0: stale signatures must be dropped from the redacted card", len(card.Signatures)) + } +} + +func TestA2AServeExtendedAgentCardJSONRPCRedacts(t *testing.T) { + const call = `{"jsonrpc":"2.0","id":"7","method":"GetExtendedAgentCard","params":{}}` + rt, outbound := extendedCardAgent(t, func(r *http.Request) *http.Response { + return cardResponse(http.StatusOK, `{"jsonrpc":"2.0","id":"7","result":`+extendedCardJSON+`}`) + }) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/mesh/12D3KooWpeer/a2a/agent/invoke", strings.NewReader(call)) + req.Host = "127.0.0.1:8080" + req.Header.Set("Authorization", "Bearer user") + if !serveEgressLocally(nil, rt, rec, req) { + t.Fatal("GetExtendedAgentCard must be handled locally") + } + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200, body: %s", rec.Code, rec.Body.String()) + } + + if len(*outbound) == 0 { + t.Fatal("no outbound request, want the call forwarded to the agent") + } + forwarded := (*outbound)[0] + if got, want := forwarded.Method+" "+forwarded.URL.String(), "POST libp2p://12D3KooWpeer/a2a/agent/invoke"; got != want { + t.Errorf("forwarded call = %q, want %q", got, want) + } + if got := forwarded.Header.Get("Authorization"); got != "Bearer user" { + t.Errorf("forwarded Authorization = %q, want %q: the extended card is for the authenticated caller", got, "Bearer user") + } + sent, err := io.ReadAll(forwarded.Body) + if err != nil { + t.Fatalf("read forwarded body: %v", err) + } + if string(sent) != call { + t.Errorf("forwarded body = %s, want %s", sent, call) + } + + var resp struct { + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Result json.RawMessage `json:"result"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("response is not JSON-RPC: %v: %s", err, rec.Body.String()) + } + if resp.JSONRPC != "2.0" || resp.ID != "7" { + t.Errorf("jsonrpc, id = %q, %q, want %q, %q", resp.JSONRPC, resp.ID, "2.0", "7") + } + var card a2a.AgentCard + if err := json.Unmarshal(resp.Result, &card); err != nil { + t.Fatalf("result is not an AgentCard: %v", err) + } + checkRedactedExtendedCard(t, rec.Body.Bytes(), &card) +} + +func TestA2AServeExtendedAgentCardHTTPJSONRedacts(t *testing.T) { + rt, outbound := extendedCardAgent(t, func(r *http.Request) *http.Response { + return cardResponse(http.StatusOK, extendedCardJSON) + }) + for _, upstream := range []string{"rest/extendedAgentCard", "rest/t1/extendedAgentCard"} { + *outbound = nil + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/mesh/12D3KooWpeer/a2a/agent/"+upstream, nil) + req.Host = "127.0.0.1:8080" + if !serveEgressLocally(nil, rt, rec, req) { + t.Fatalf("GET %s must be handled locally", upstream) + } + if rec.Code != http.StatusOK { + t.Fatalf("GET %s: status = %d, want 200, body: %s", upstream, rec.Code, rec.Body.String()) + } + if got, want := (*outbound)[0].URL.String(), "libp2p://12D3KooWpeer/a2a/agent/"+upstream; got != want { + t.Errorf("forwarded URL = %q, want %q", got, want) + } + var card a2a.AgentCard + if err := json.Unmarshal(rec.Body.Bytes(), &card); err != nil { + t.Fatalf("GET %s: body is not an AgentCard: %v", upstream, err) + } + checkRedactedExtendedCard(t, rec.Body.Bytes(), &card) + } +} + +func TestA2AServeExtendedAgentCardEmptyPathKeepsQuery(t *testing.T) { + const call = `{"jsonrpc":"2.0","id":"7","method":"GetExtendedAgentCard","params":{}}` + for _, tc := range []struct { + name, path, wantURL string + }{ + {"empty path, no query", "/mesh/12D3KooWpeer/a2a/agent", "libp2p://12D3KooWpeer/a2a/agent"}, + {"empty path, query", "/mesh/12D3KooWpeer/a2a/agent?session=1", "libp2p://12D3KooWpeer/a2a/agent?session=1"}, + {"path and query", "/mesh/12D3KooWpeer/a2a/agent/invoke?session=1", "libp2p://12D3KooWpeer/a2a/agent/invoke?session=1"}, + } { + t.Run(tc.name, func(t *testing.T) { + rt, outbound := extendedCardAgent(t, func(*http.Request) *http.Response { + return cardResponse(http.StatusOK, `{"jsonrpc":"2.0","id":"7","result":`+extendedCardJSON+`}`) + }) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", tc.path, strings.NewReader(call)) + req.Host = "127.0.0.1:8080" + if !serveEgressLocally(nil, rt, rec, req) { + t.Fatal("GetExtendedAgentCard must be handled locally") + } + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200, body: %s", rec.Code, rec.Body.String()) + } + if len(*outbound) == 0 { + t.Fatal("no outbound request, want the call forwarded to the agent") + } + if got := (*outbound)[0].URL.String(); got != tc.wantURL { + t.Errorf("forwarded URL = %q, want %q", got, tc.wantURL) + } + }) + } +} + +func TestA2AServeExtendedAgentCardDropsBindingsTheMeshDoesNotOffer(t *testing.T) { + // Only the extended card names an interface outside the public card's + // bindings, or nothing the mesh carries at all: what the public card + // does not offer through the mesh is redacted, and a card left with no + // interface fails closed rather than going out with the agent's URLs. + ext := &a2a.AgentCard{SupportedInterfaces: []*a2a.AgentInterface{ + {URL: "http://10.0.0.5:7777/", ProtocolBinding: a2a.TransportProtocolJSONRPC, ProtocolVersion: "1.0"}, + {URL: "http://10.0.0.5:7777/rest", ProtocolBinding: a2a.TransportProtocolHTTPJSON, ProtocolVersion: "1.0"}, + }} + public := &a2a.AgentCard{SupportedInterfaces: []*a2a.AgentInterface{ + {URL: "http://mesh/x/invoke", ProtocolBinding: a2a.TransportProtocolJSONRPC, ProtocolVersion: "0.3"}, + }} + if err := redactExtendedAgentCardForMesh(ext, public); err != nil { + t.Fatalf("redactExtendedAgentCardForMesh = %v, want nil", err) + } + if len(ext.SupportedInterfaces) != 1 || ext.SupportedInterfaces[0].URL != "http://mesh/x/invoke" || ext.SupportedInterfaces[0].ProtocolVersion != "1.0" { + t.Errorf("interfaces = %+v, want only JSONRPC 1.0 at %q", ext.SupportedInterfaces, "http://mesh/x/invoke") + } + + grpcOnly := &a2a.AgentCard{SupportedInterfaces: []*a2a.AgentInterface{ + {URL: "10.0.0.5:50051", ProtocolBinding: a2a.TransportProtocolGRPC, ProtocolVersion: "1.0"}, + }} + if err := redactExtendedAgentCardForMesh(grpcOnly, public); err == nil { + t.Errorf("redactExtendedAgentCardForMesh = nil, interfaces %+v; want an error for a card the mesh cannot carry", grpcOnly.SupportedInterfaces) + } +} + +func TestA2AServeExtendedAgentCardFailsClosed(t *testing.T) { + // A card the mesh cannot carry is refused, never relayed as the agent + // wrote it. + rt, _ := extendedCardAgent(t, func(r *http.Request) *http.Response { + return cardResponse(http.StatusOK, `{"name":"T","supportedInterfaces":[{"url":"10.0.0.5:50051","protocolBinding":"GRPC"}]}`) + }) + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/mesh/12D3KooWpeer/a2a/agent/extendedAgentCard", nil) + if !serveEgressLocally(nil, rt, rec, req) { + t.Fatal("extended card GET must be handled locally") + } + if rec.Code != http.StatusBadGateway { + t.Errorf("status = %d, want %d", rec.Code, http.StatusBadGateway) + } + if strings.Contains(rec.Body.String(), "10.0.0.5") { + t.Errorf("body = %q, want none of the agent's own URLs", rec.Body.String()) + } +} + +func TestA2AServeExtendedAgentCardRelaysErrors(t *testing.T) { + for _, tc := range []struct { + name, method, path, body string + status int + reply string + }{ + {"JSON-RPC error", "POST", "/mesh/12D3KooWpeer/a2a/agent", `{"jsonrpc":"2.0","id":1,"method":"GetExtendedAgentCard"}`, + http.StatusOK, `{"jsonrpc":"2.0","id":1,"error":{"code":-32007,"message":"not configured"}}`}, + {"JSON-RPC error with null result", "POST", "/mesh/12D3KooWpeer/a2a/agent", `{"jsonrpc":"2.0","id":1,"method":"GetExtendedAgentCard"}`, + http.StatusOK, `{"jsonrpc":"2.0","id":1,"result":null,"error":{"code":-32007,"message":"not configured"}}`}, + {"HTTP+JSON status", "GET", "/mesh/12D3KooWpeer/a2a/agent/extendedAgentCard", "", + http.StatusUnauthorized, `{"error":"unauthenticated"}`}, + } { + rt, _ := extendedCardAgent(t, func(*http.Request) *http.Response { return cardResponse(tc.status, tc.reply) }) + rec := httptest.NewRecorder() + req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body)) + if !serveEgressLocally(nil, rt, rec, req) { + t.Fatalf("%s: must be handled locally", tc.name) + } + if rec.Code != tc.status || rec.Body.String() != tc.reply { + t.Errorf("%s: got %d %s, want %d %s", tc.name, rec.Code, rec.Body.String(), tc.status, tc.reply) + } + } +} + +func TestA2AServeExtendedAgentCardLeavesOtherCallsToTheProxy(t *testing.T) { + // Every other call streams through the proxy with its body intact, + // including one too large to be a GetExtendedAgentCard call. + rt := roundTripFunc(func(r *http.Request) (*http.Response, error) { + t.Errorf("mesh request %s %s, want none", r.Method, r.URL) + return cardResponse(http.StatusOK, "{}"), nil + }) + large := `{"jsonrpc":"2.0","id":1,"method":"SendMessage","params":{"pad":"` + strings.Repeat("x", maxExtendedCardRequestBytes) + `"}}` + for _, tc := range []struct{ method, path, body string }{ + {"POST", "/mesh/12D3KooWpeer/a2a/agent/invoke", `{"jsonrpc":"2.0","id":1,"method":"SendMessage","params":{}}`}, + {"POST", "/mesh/12D3KooWpeer/a2a/agent", large}, + {"POST", "/mesh/12D3KooWpeer/a2a/agent", `not json`}, + {"GET", "/mesh/12D3KooWpeer/a2a/agent/tasks/extendedAgentCard", ""}, + } { + rec := httptest.NewRecorder() + req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body)) + if serveEgressLocally(nil, rt, rec, req) { + t.Errorf("%s %s must stream through the proxy", tc.method, tc.path) + continue + } + got, err := io.ReadAll(req.Body) + if err != nil { + t.Fatalf("read body left for the proxy: %v", err) + } + if string(got) != tc.body { + t.Errorf("%s %s: body left for the proxy has %d bytes, want the %d sent", tc.method, tc.path, len(got), len(tc.body)) + } + } +} + func TestA2AServeAgentCardMinimalCardStaysParseable(t *testing.T) { // An upstream card that omits skills/defaultInputModes/defaultOutputModes: // the regenerated card must keep them as arrays, not null, or strict SDK diff --git a/sdk/js/src/libp2p-http.test.ts b/sdk/js/src/libp2p-http.test.ts index 95235f76f..aef81aeb3 100644 --- a/sdk/js/src/libp2p-http.test.ts +++ b/sdk/js/src/libp2p-http.test.ts @@ -314,6 +314,17 @@ test("rewriteAgentCard keeps only what the mesh carries", () => { }); }); +// Issue #675: agentmesh-node redacts the extended card, but this transport would relay it +// with the agent's own interface URLs, so the rewritten card declares none. +test("rewriteAgentCard declares no extended card", () => { + const iface = { url: "http://localhost:7777/", protocolBinding: "JSONRPC" }; + assert.deepEqual(rewriteAgentCard({ capabilities: { streaming: true, extendedAgentCard: true }, supportedInterfaces: [iface] }, "http://mesh/x").capabilities, { + streaming: true, + }); + assert.deepEqual(rewriteAgentCard({ capabilities: { extendedAgentCard: false }, supportedInterfaces: [iface] }, "http://mesh/x").capabilities, {}); + assert.deepEqual(rewriteAgentCard({ capabilities: { streaming: false }, supportedInterfaces: [iface] }, "http://mesh/x").capabilities, { streaming: false }); +}); + // As agentmesh-node's TestA2AServiceCardKeepsInterfacePaths: the provider's node names // each interface relative to its target URL, and the caller's card resolves it under // the mesh URL, so an agent whose JSON-RPC endpoint is "/invoke" stays reachable there. diff --git a/sdk/js/src/libp2p-http.ts b/sdk/js/src/libp2p-http.ts index c779878c6..d1321b1b5 100644 --- a/sdk/js/src/libp2p-http.ts +++ b/sdk/js/src/libp2p-http.ts @@ -414,7 +414,9 @@ function agentCardService(method: string, target: string): string | undefined { /** * An agent card rebuilt for the mesh, as agentmesh-node's egress proxy serves it: * HTTP interfaces resolve under base (meshInterfaceURL), gRPC ones go, signatures no longer match. - * Streaming stays as declared, this transport streams. Throws when no interface remains. + * Streaming stays as declared, this transport streams. The extended card does not: agentmesh-node + * redacts it, but this transport relays it with the agent's own interface URLs, so the card + * declares none. Throws when no interface remains. */ export function rewriteAgentCard(card: unknown, base: string): Record { if (typeof card !== "object" || card === null || Array.isArray(card)) { @@ -430,6 +432,13 @@ export function rewriteAgentCard(card: unknown, base: string): Record) }; + delete rest.extendedAgentCard; + out.capabilities = rest; + } return { ...out, supportedInterfaces: kept }; } diff --git a/sdk/python/src/agent_mesh/libp2p_http.py b/sdk/python/src/agent_mesh/libp2p_http.py index 68a483b3b..c2f975a41 100644 --- a/sdk/python/src/agent_mesh/libp2p_http.py +++ b/sdk/python/src/agent_mesh/libp2p_http.py @@ -416,7 +416,9 @@ def rewrite_agent_card(card: object, base: str) -> dict: """An agent card rebuilt for the mesh, as agentmesh-node's egress proxy serves it: HTTP interfaces resolve under base (mesh_interface_url), gRPC ones go, signatures no longer match. - Streaming stays as declared, this transport streams. Raises when no interface remains.""" + Streaming stays as declared, this transport streams. The extended card does + not: agentmesh-node redacts it, but this transport relays it with the agent's + own interface URLs, so the card declares none. Raises when no interface remains.""" if not isinstance(card, dict): raise ValueError("agent card is not a JSON object") interfaces = card.get("supportedInterfaces") @@ -427,7 +429,12 @@ def rewrite_agent_card(card: object, base: str) -> dict: ] if not kept: raise ValueError("agent card advertises no supported interface the mesh can carry (JSONRPC or HTTP+JSON); is the agent serving a pre-1.0 A2A card?") - return {**{k: v for k, v in card.items() if k != "signatures"}, "supportedInterfaces": kept} + out = {**{k: v for k, v in card.items() if k != "signatures"}, "supportedInterfaces": kept} + capabilities = out.get("capabilities") + if isinstance(capabilities, dict) and "extendedAgentCard" in capabilities: + # Dropped rather than set false, as agentmesh-node's omitempty encoding leaves it out. + out["capabilities"] = {k: v for k, v in capabilities.items() if k != "extendedAgentCard"} + return out class StreamedResponse: diff --git a/sdk/python/tests/test_libp2p_http.py b/sdk/python/tests/test_libp2p_http.py index e138c7e5c..d5d692e58 100644 --- a/sdk/python/tests/test_libp2p_http.py +++ b/sdk/python/tests/test_libp2p_http.py @@ -313,6 +313,15 @@ def test_rewrite_agent_card_keeps_only_what_the_mesh_carries(): } +def test_rewrite_agent_card_declares_no_extended_card(): + # Issue #675: agentmesh-node redacts the extended card, but this transport would relay it + # with the agent's own interface URLs, so the rewritten card declares none. + iface = {"url": "http://localhost:7777/", "protocolBinding": "JSONRPC"} + assert rewrite_agent_card({"capabilities": {"streaming": True, "extendedAgentCard": True}, "supportedInterfaces": [iface]}, "http://mesh/x")["capabilities"] == {"streaming": True} + assert rewrite_agent_card({"capabilities": {"extendedAgentCard": False}, "supportedInterfaces": [iface]}, "http://mesh/x")["capabilities"] == {} + assert rewrite_agent_card({"capabilities": {"streaming": False}, "supportedInterfaces": [iface]}, "http://mesh/x")["capabilities"] == {"streaming": False} + + def test_rewrite_agent_card_keeps_the_interface_path_the_provider_names(): # As agentmesh-node's TestA2AServiceCardKeepsInterfacePaths: the provider's node names # each interface relative to its target URL, and the caller's card resolves it under diff --git a/site/content/docs/guides/exposing-services.md b/site/content/docs/guides/exposing-services.md index 82f8ab274..a2c4db455 100644 --- a/site/content/docs/guides/exposing-services.md +++ b/site/content/docs/guides/exposing-services.md @@ -141,7 +141,10 @@ 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 +content changed. The extended agent card stays declared. When a client asks +for it, the node rewrites its interfaces the same way and drops any the mesh +does not carry, so the agent's own URLs never reach the client, while its +extra skills and input modes do. 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/site/content/docs/use-cases/chat-a2a.md b/site/content/docs/use-cases/chat-a2a.md index 0719c6372..d112bac37 100644 --- a/site/content/docs/use-cases/chat-a2a.md +++ b/site/content/docs/use-cases/chat-a2a.md @@ -29,7 +29,9 @@ request, fetches the card from the agent over the mesh, and serves a regenerated card whose interface URLs point back at the mesh path that the client fetched from. Protocol bindings that the mesh cannot carry are dropped (gRPC needs its own end-to-end connection). Capabilities such as -streaming stay as the agent declares them. The client follows the regenerated card as it would for +streaming and the extended agent card stay as the agent declares them. The +extended card is rewritten the same way when the client asks for it, so it +names the mesh path and none of the agent's own interface URLs. The client follows the regenerated card as it would for any A2A server. Discovery, sending messages and `contextId` round-tripping all work without changes, while the traffic flows over libp2p between the nodes. diff --git a/tests/integration/a2a_test.go b/tests/integration/a2a_test.go index 2a91610f1..971967e4b 100644 --- a/tests/integration/a2a_test.go +++ b/tests/integration/a2a_test.go @@ -16,6 +16,7 @@ package integration_test import ( "context" + "encoding/json" "iter" "net/http" "net/http/httptest" @@ -71,9 +72,11 @@ func TestA2ACUJ(t *testing.T) { // interface and a stale signature, which the mesh must drop on // 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. + // root: the mesh URL must keep that path. It also serves an extended + // card with one more skill and input mode, naming its private + // interfaces, which the mesh must redact (issue #675). 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{}) @@ -99,16 +102,30 @@ func TestA2ACUJ(t *testing.T) { Name: "echo-agent", Description: "test a2a agent", Version: "1.0.0", - Capabilities: a2a.AgentCapabilities{Streaming: true}, + Capabilities: a2a.AgentCapabilities{Streaming: true, ExtendedAgentCard: true}, SupportedInterfaces: []*a2a.AgentInterface{ {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"}}, } + extendedCard := *agentCard + extendedCard.Description = "extended" + extendedCard.SupportedInterfaces = []*a2a.AgentInterface{ + {URL: "http://127.0.0.1:7777", ProtocolBinding: a2a.TransportProtocolJSONRPC, ProtocolVersion: "1.0"}, + {URL: "10.0.0.5:50051", ProtocolBinding: a2a.TransportProtocolGRPC, ProtocolVersion: "1.0"}, + } + extendedCard.Skills = []a2a.AgentSkill{{ID: "vision", Name: "vision", Description: "describes images", Tags: []string{}}} + extendedCard.DefaultInputModes = []string{"text", "image/png"} + privateURLs := []string{"127.0.0.1:7777", "10.0.0.5"} + var extendedCardServed atomic.Bool mux := http.NewServeMux() mux.Handle(a2asrv.WellKnownAgentCardPath, a2asrv.NewStaticAgentCardHandler(agentCard)) - mux.Handle("/invoke", a2asrv.NewJSONRPCHandler(a2asrv.NewHandler(echo))) + mux.Handle("/invoke", a2asrv.NewJSONRPCHandler(a2asrv.NewHandler(echo, + a2asrv.WithExtendedAgentCardProducer(a2asrv.ExtendedAgentCardProducerFn(func(context.Context, *a2a.GetExtendedAgentCardRequest) (*a2a.AgentCard, error) { + extendedCardServed.Store(true) + return &extendedCard, nil + }))))) agent := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get(api.HeaderMeshRequiredLabels) != "" { sawLabelsHeader.Store(true) @@ -173,8 +190,11 @@ func TestA2ACUJ(t *testing.T) { if !card.Capabilities.Streaming { t.Errorf("streaming = %v, want true as the agent declares it", card.Capabilities.Streaming) } + if !card.Capabilities.ExtendedAgentCard { + t.Errorf("extendedAgentCard = %v, want true as the agent declares it", card.Capabilities.ExtendedAgentCard) + } if len(card.Signatures) != 0 { - t.Error("stale signatures must be dropped from the regenerated card") + t.Errorf("len(signatures) = %d, want 0: stale signatures must be dropped from the regenerated card", len(card.Signatures)) } // CUJ step 2: a stock SDK client built from that card, constrained to @@ -205,6 +225,42 @@ func TestA2ACUJ(t *testing.T) { t.Fatalf("unexpected reply: %+v", reply) } + // CUJ step 2a: the stock client gets the extended card through the + // mesh with its extra skill and input mode, but with the mesh URL in + // place of the agent's private interfaces, so it can switch to it + // (A2A 1.0, section 3.1.11) and keep talking through the mesh. + ext, err := euClient.GetExtendedAgentCard(ctx, &a2a.GetExtendedAgentCardRequest{}) + if err != nil { + t.Fatalf("GetExtendedAgentCard through the mesh: %v", err) + } + if served := extendedCardServed.Load(); !served { + t.Errorf("extendedCardServed = %v, want true: the call must reach the agent", served) + } + extJSON, err := json.Marshal(ext) + if err != nil { + t.Fatalf("marshal extended card: %v", err) + } + for _, private := range privateURLs { + if strings.Contains(string(extJSON), private) { + t.Errorf("extended card through the mesh names %q, want none of the agent's own URLs: %s", private, extJSON) + } + } + if len(ext.SupportedInterfaces) != 1 || ext.SupportedInterfaces[0].URL != meshBase+"/invoke" { + t.Errorf("extended card interfaces = %+v, want exactly one interface with URL %q", ext.SupportedInterfaces, meshBase+"/invoke") + } + if ext.Description != "extended" || len(ext.Skills) != 1 || ext.Skills[0].ID != "vision" { + t.Errorf("extended card description, skills = %q, %+v; want %q, the vision skill", ext.Description, ext.Skills, "extended") + } + if got, want := strings.Join(ext.DefaultInputModes, ","), "text,image/png"; got != want { + t.Errorf("extended card defaultInputModes = %q, want %q", got, want) + } + if len(ext.Signatures) != 0 { + t.Errorf("len(extended card signatures) = %d, want 0: stale signatures must be dropped", len(ext.Signatures)) + } + if err := euClient.UpdateCard(ext); err != nil { + t.Errorf("UpdateCard(extended card) = %v, want nil: the client's mesh endpoint must stay on the card", err) + } + // CUJ step 2b: the card keeps streaming, so the same client may stream // the exchange; the SSE response must flush across the mesh as each // event is emitted (not buffered until EOF): the server holds the final