Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
a2a: cover the CUJ with stock SDKs at every level and fix what that found
Antonio Ojeaa3d9c4f60e23
diff --git a/charts/sam-mesh/templates/bootstrap-job.yaml b/charts/sam-mesh/templates/bootstrap-job.yamlindex 1365c176..88dc086b 100644--- a/charts/sam-mesh/templates/bootstrap-job.yaml+++ b/charts/sam-mesh/templates/bootstrap-job.yaml@@ -118,7 +118,7 @@ spec:{"name": "sam-admin", "allowed_services": ["*"], "allowed_targets": ["*"]},{"name": "sam:role:sambox", "allowed_services": ["*"], "allowed_targets": ["*"]},{"name": "sam:role:router", "allowed_services": ["*"], "allowed_targets": ["*"]},- {"name": "sam:role:node", "allowed_services": {{ toJson .Values.bootstrap.nodeServices }}, "allowed_targets": ["*"]}+ {"name": "sam:role:node", "allowed_services": {{ toJson .Values.bootstrap.nodeServices }}, "allowed_targets": ["*"], "allowed_labels": {{ toJson .Values.bootstrap.nodeLabels }}}],"bindings": {{ toJson $bindings }}}' \diff --git a/charts/sam-mesh/tests/bootstrap-job_test.yaml b/charts/sam-mesh/tests/bootstrap-job_test.yamlindex 621e0dc7..f40723ac 100644--- a/charts/sam-mesh/tests/bootstrap-job_test.yaml+++ b/charts/sam-mesh/tests/bootstrap-job_test.yaml@@ -32,3 +32,24 @@ tests:value: 100- exists:path: spec.template.spec.containers[0].resources.limits++ - it: node role grants no labels by default (fail closed)+ documentSelector:+ path: kind+ value: Job+ asserts:+ - matchRegex:+ path: spec.template.spec.containers[0].args[0]+ pattern: '"name": "sam:role:node".*"allowed_labels": \[\]'++ - it: node role grants only the configured label patterns+ documentSelector:+ path: kind+ value: Job+ set:+ bootstrap:+ nodeLabels: ["region=*", "team=platform"]+ asserts:+ - matchRegex:+ path: spec.template.spec.containers[0].args[0]+ pattern: '"name": "sam:role:node".*"allowed_labels": \["region=\*","team=platform"\]'diff --git a/charts/sam-mesh/values.yaml b/charts/sam-mesh/values.yamlindex bda5d30e..de03c9ec 100644--- a/charts/sam-mesh/values.yaml+++ b/charts/sam-mesh/values.yaml@@ -182,3 +182,6 @@ bootstrap:bindings: []# Services sam:role:node may callnodeServices: ["*"]+ # Label patterns ("key=value" or "key=*") sam:role:node may attest with+ # --labels. Empty means nodes cannot enroll with any label (fail closed).+ nodeLabels: []diff --git a/internal/node/a2a_service.go b/internal/node/a2a_service.goindex 22a9a808..fae5af62 100644--- a/internal/node/a2a_service.go+++ b/internal/node/a2a_service.go@@ -91,9 +91,13 @@ const maxAgentCardBytes = 1 << 20// 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.+// The card is served both at the well-known path (resolvers that append it,+// e.g. the python SDK) and at the bare service root (resolvers that treat a+// pathful base URL as the card location, e.g. a2a-go; a root GET is not part+// of any A2A binding, JSON-RPC being POST-only). Everything else is 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 {+ if r.Method != http.MethodGet || (route.upstreamPath != a2aAgentCardPath && route.upstreamPath != "") {return false}resp, err := fetchRemoteAgentCard(node, rt, r, route)@@ -178,6 +182,17 @@ func regenerateAgentCardForMesh(card *a2a.AgentCard, base string) error {card.SupportedInterfaces = keptcard.Capabilities.Streaming = falsecard.Signatures = nil+ // Required list fields must stay arrays: encoding/json marshals nil+ // slices as null, which strict SDK card parsers (pydantic) reject.+ if card.Skills == nil {+ card.Skills = []a2a.AgentSkill{}+ }+ if card.DefaultInputModes == nil {+ card.DefaultInputModes = []string{}+ }+ if card.DefaultOutputModes == nil {+ card.DefaultOutputModes = []string{}+ }return nil}diff --git a/internal/node/a2a_service_test.go b/internal/node/a2a_service_test.goindex d8f80126..5c234b1d 100644--- a/internal/node/a2a_service_test.go+++ b/internal/node/a2a_service_test.go@@ -173,6 +173,67 @@ func TestA2AServeAgentCardRegenerates(t *testing.T) {}}+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+ // parsers (pydantic) refuse the whole card.+ rt := roundTripFunc(func(*http.Request) (*http.Response, error) {+ return cardResponse(http.StatusOK, `{"name":"minimal",`++ `"supportedInterfaces":[{"url":"http://localhost:7777","protocolBinding":"JSONRPC"}],`++ `"capabilities":{}}`), 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.StatusOK {+ t.Fatalf("status = %d, want 200, body: %s", rec.Code, rec.Body.String())+ }+ var raw map[string]any+ if err := json.Unmarshal(rec.Body.Bytes(), &raw); err != nil {+ t.Fatalf("regenerated card is not JSON: %v", err)+ }+ for _, key := range []string{"skills", "defaultInputModes", "defaultOutputModes", "supportedInterfaces"} {+ if _, ok := raw[key].([]any); !ok {+ t.Errorf("%s = %v (%T), must be a JSON array", key, raw[key], raw[key])+ }+ }+}++func TestA2AServeAgentCardAtServiceRoot(t *testing.T) {+ // a2a-go's stock resolver treats a pathful base URL as the card URL+ // itself, so the bare service root must serve the card too; the fetch+ // upstream still targets the agent's well-known path.+ var outbound *http.Request+ rt := roundTripFunc(func(r *http.Request) (*http.Response, error) {+ outbound = r+ return cardResponse(http.StatusOK,+ `{"name":"T","supportedInterfaces":[{"url":"http://localhost:7777","protocolBinding":"JSONRPC"}]}`), nil+ })+ for _, path := range []string{"/sam/12D3KooWpeer/a2a/agent", "/sam/12D3KooWpeer/a2a/agent/"} {+ rec := httptest.NewRecorder()+ req := httptest.NewRequest("GET", path, nil)+ req.Host = "127.0.0.1:8080"+ if !serveEgressLocally(nil, rt, rec, req) {+ t.Fatalf("GET %s must serve the card", path)+ }+ if rec.Code != http.StatusOK {+ t.Fatalf("GET %s status = %d, body: %s", path, rec.Code, rec.Body.String())+ }+ if want := "libp2p://12D3KooWpeer/a2a/agent/.well-known/agent-card.json"; outbound.URL.String() != want {+ t.Errorf("upstream fetch URL = %q, want %q", outbound.URL.String(), want)+ }+ var card a2a.AgentCard+ if err := json.Unmarshal(rec.Body.Bytes(), &card); err != nil {+ t.Fatalf("GET %s: invalid card: %v", path, err)+ }+ if len(card.SupportedInterfaces) != 1 || card.SupportedInterfaces[0].URL != "http://127.0.0.1:8080/sam/12D3KooWpeer/a2a/agent" {+ t.Errorf("GET %s: interfaces = %+v", path, card.SupportedInterfaces)+ }+ }+}+func TestA2AServeAgentCardIgnoresNonCardRequests(t *testing.T) {rt := roundTripFunc(func(*http.Request) (*http.Response, error) {t.Fatal("no mesh fetch expected")@@ -180,6 +241,7 @@ func TestA2AServeAgentCardIgnoresNonCardRequests(t *testing.T) {})for _, tc := range []struct{ method, path string }{{"POST", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json"},+ {"POST", "/sam/12D3KooWpeer/a2a/agent"},{"GET", "/sam/12D3KooWpeer/a2a/agent/tasks/1"},{"GET", "/sam/12D3KooWpeer/mcp/svc/.well-known/agent-card.json"},} {diff --git a/tests/e2e/a2a_mesh.bats b/tests/e2e/a2a_mesh.batsnew file mode 100644index 00000000..f4e17a17--- /dev/null+++ b/tests/e2e/a2a_mesh.bats@@ -0,0 +1,106 @@+#!/usr/bin/env bats++load "lib/container_mesh.bash"++A2A_ECHO_IMAGE="sam-a2a-echo:local"++build_a2a_echo_image() {+ if ! docker image inspect "${A2A_ECHO_IMAGE}" >/dev/null 2>&1; then+ docker build -t "${A2A_ECHO_IMAGE}" \+ -f tests/e2e/docker/a2a-echo/Dockerfile \+ tests/e2e/docker/a2a-echo >/dev/null+ fi+}++start_a2a_echo() {+ local name="${MESH_PREFIX}-a2a-echo"+ docker run -d \+ --name "${name}" \+ --network "${MESH_NETWORK}" \+ --network-alias a2a-echo \+ "${A2A_ECHO_IMAGE}" >/dev/null+ MESH_CONTAINERS+=("${name}")+ mesh_wait_for_log "${name}" "Uvicorn running on" 30+}++setup() {+ mesh_setup_env+ build_a2a_echo_image+}++teardown() {+ mesh_cleanup_env+}++# CUJ: bring a stock a2a-sdk agent onto the mesh via node config, then use a+# stock a2a-sdk client on another node — bootstrapping from the regenerated+# agent card — plus the fail-closed labels gate on the raw a2a egress path.+@test "a2a: stock SDK client chats with a mesh-hosted agent via the regenerated card" {+ run mesh_start_mock_oidc+ [[ "$status" -eq 0 ]]++ mesh_start_router++ echo "[$(date +%T)] Starting Node 1 (consumer)"+ mesh_start_node 1 "--log-level debug"+ mesh_wait_for_log "${MESH_PREFIX}-node-1" "SAM Node Online" 60+ mesh_wait_for_mcp_ready 1 20++ echo "[$(date +%T)] Starting a2a echo agent backend"+ start_a2a_echo++ echo "[$(date +%T)] Starting Node 2 (provider, region=eu) with the echo service"+ mesh_start_node 2 \+ "--log-level debug --labels region=eu" \+ "tests/e2e/docker/a2a-echo/sam-node-config.yaml"+ mesh_wait_for_log "${MESH_PREFIX}-node-2" "SAM Node Online" 20+ mesh_wait_for_mcp_ready 2 20++ local node2_peer_id+ node2_peer_id=$(docker logs "${MESH_PREFIX}-node-2" 2>&1 | grep "PeerID:" | head -n 1 | awk '{print $2}' | tr -d '\r')++ echo "[$(date +%T)] Connecting Node 1 to Node 2"+ local node2_addr="/dns4/${MESH_PREFIX}-node-2/tcp/5002/p2p/${node2_peer_id}"+ run mesh_connect_peer 1 "${node2_addr}"+ [[ "$status" -eq 0 ]]+ mesh_wait_for_peer_connection 1 "${node2_peer_id}" 20++ local mesh_base="http://${MESH_PREFIX}-node-1:8080/sam/${node2_peer_id}/a2a/echo"++ # Stock python client: resolves the card through the mesh (client.py asserts+ # the regenerated URLs, the gRPC drop and streaming-off) and gets an echo.+ echo "[$(date +%T)] Running stock a2a-sdk client against ${mesh_base}"+ run docker run --rm --network "${MESH_NETWORK}" \+ -e SAM_API_TOKEN="secret-token" \+ "${A2A_ECHO_IMAGE}" python3 /workspace/client.py "${mesh_base}" "hello mesh"+ echo "client output: $output"+ [[ "$status" -eq 0 ]]+ [[ "$output" == *"agent> echo: hello mesh"* ]]++ local send_body='{"jsonrpc":"2.0","id":1,"method":"SendMessage","params":{}}'++ # The label the provider attests (region=eu) is admitted end to end over+ # the real attestation chain — same stock client, labels via header.+ echo "[$(date +%T)] Labelled send (region=eu) must be admitted"+ run docker run --rm --network "${MESH_NETWORK}" \+ -e SAM_API_TOKEN="secret-token" \+ -e SAM_REQUIRED_LABELS="region=eu" \+ "${A2A_ECHO_IMAGE}" python3 /workspace/client.py "${mesh_base}" "hello eu"+ echo "labelled client output: $output"+ [[ "$status" -eq 0 ]]+ [[ "$output" == *"agent> echo: hello eu"* ]]++ # A label the provider does not attest refuses fail-closed before egress:+ # the 403 comes from the caller-side gate before the body is even parsed.+ echo "[$(date +%T)] Labelled send (region=us-east-1) must fail closed"+ run docker run --rm --network "${MESH_NETWORK}" python:3.12 curl -s -o /dev/null -w '%{http_code}' \+ -X POST "${mesh_base}/" \+ -H "X-Sam-Authentication: Bearer secret-token" \+ -H "X-Sam-Required-Labels: region=us-east-1" \+ -H "Content-Type: application/json" \+ --max-time 30 \+ -d "${send_body}"+ echo "mismatched-label status: $output"+ [[ "$status" -eq 0 ]]+ [[ "$output" == "403" ]]+}diff --git a/tests/e2e/docker/a2a-echo/Dockerfile b/tests/e2e/docker/a2a-echo/Dockerfilenew file mode 100644index 00000000..edfa13fa--- /dev/null+++ b/tests/e2e/docker/a2a-echo/Dockerfile@@ -0,0 +1,8 @@+FROM python:3.12-slim++WORKDIR /workspace+COPY ./requirements.txt /workspace/requirements.txt+RUN pip install -r requirements.txt+COPY ./agent.py ./client.py /workspace/++CMD ["python3", "/workspace/agent.py"]diff --git a/tests/e2e/docker/a2a-echo/agent.py b/tests/e2e/docker/a2a-echo/agent.pynew file mode 100644index 00000000..98c49fd6--- /dev/null+++ b/tests/e2e/docker/a2a-echo/agent.py@@ -0,0 +1,89 @@+"""Stock a2a-sdk echo agent for the e2e mesh CUJ: deterministic, no external APIs.++The card deliberately advertises a gRPC interface and streaming so the test+can verify the mesh regenerates the card (drops gRPC, turns streaming off).+"""+import uuid++import uvicorn+from a2a.server.agent_execution.agent_executor import AgentExecutor+from a2a.server.agent_execution.context import RequestContext+from a2a.server.events.event_queue import EventQueue+from a2a.server.request_handlers import DefaultRequestHandler+from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes+from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore+from a2a.types import (+ AgentCapabilities,+ AgentCard,+ AgentInterface,+ AgentSkill,+ Message,+ Part,+ Role,+)+from starlette.applications import Starlette++PORT = 7777+++class EchoExecutor(AgentExecutor):+ async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:+ await event_queue.enqueue_event(+ Message(+ role=Role.ROLE_AGENT,+ message_id=str(uuid.uuid4()),+ parts=[Part(text=f"echo: {context.get_user_input()}")],+ context_id=context.context_id,+ task_id=context.task_id,+ )+ )++ async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:+ pass+++agent_card = AgentCard(+ name="echo",+ description="Deterministic echo agent for the a2a e2e CUJ",+ version="0.1.0",+ capabilities=AgentCapabilities(streaming=True),+ default_input_modes=["text"],+ default_output_modes=["text"],+ skills=[+ AgentSkill(+ id="echo",+ name="echo",+ description="Echoes the input back",+ tags=["echo"],+ )+ ],+ supported_interfaces=[+ AgentInterface(+ protocol_binding="JSONRPC",+ protocol_version="1.0",+ url=f"http://127.0.0.1:{PORT}/",+ ),+ # Unreachable through the mesh; the regenerated card must drop it.+ AgentInterface(+ protocol_binding="GRPC",+ protocol_version="1.0",+ url="127.0.0.1:50051",+ ),+ ],+)++handler = DefaultRequestHandler(+ agent_executor=EchoExecutor(),+ task_store=InMemoryTaskStore(),+ agent_card=agent_card,+)+# 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="/"),+ *create_agent_card_routes(agent_card=agent_card),+ ]+)++if __name__ == "__main__":+ uvicorn.run(app, host="0.0.0.0", port=PORT)diff --git a/tests/e2e/docker/a2a-echo/client.py b/tests/e2e/docker/a2a-echo/client.pynew file mode 100644index 00000000..e9943eb5--- /dev/null+++ b/tests/e2e/docker/a2a-echo/client.py@@ -0,0 +1,45 @@+"""One-shot stock a2a-sdk client for the e2e CUJ: resolve, verify, send, print.++Exits non-zero if the regenerated card is not mesh-usable or no reply arrives.+"""+import asyncio+import os+import sys+import uuid++import httpx+from a2a.client import A2ACardResolver, ClientConfig, create_client+from a2a.helpers import get_message_text+from a2a.types import Message, Part, Role, SendMessageRequest+++async def main(url: str, text: str) -> None:+ token = os.environ.get("SAM_API_TOKEN", "secret-token")+ headers = {"X-Sam-Authentication": f"Bearer {token}"}+ labels = os.environ.get("SAM_REQUIRED_LABELS")+ if labels:+ headers["X-Sam-Required-Labels"] = labels+ async with httpx.AsyncClient(timeout=60, headers=headers) as http:+ card = await A2ACardResolver(http, url).get_agent_card()+ bindings = [i.protocol_binding for i in card.supported_interfaces]+ assert "GRPC" not in bindings, f"gRPC interface not dropped: {bindings}"+ assert all(i.url == url for i in card.supported_interfaces), \+ f"interface URLs not regenerated to {url}: {card.supported_interfaces}"+ assert not card.capabilities.streaming, "streaming not advertised off"+ client = await create_client(card, client_config=ClientConfig(httpx_client=http))+ message = Message(+ role=Role.ROLE_USER,+ message_id=str(uuid.uuid4()),+ parts=[Part(text=text)],+ )+ async for event in client.send_message(SendMessageRequest(message=message)):+ if event.HasField("message"):+ print(f"agent> {get_message_text(event.message)}")+ return+ sys.exit("no message reply received")+++if __name__ == "__main__":+ if len(sys.argv) != 3:+ sys.exit("usage: client.py <mesh-a2a-base-url> <text>")+ asyncio.run(main(sys.argv[1], sys.argv[2]))diff --git a/tests/e2e/docker/a2a-echo/requirements.txt b/tests/e2e/docker/a2a-echo/requirements.txtnew file mode 100644index 00000000..70e80861--- /dev/null+++ b/tests/e2e/docker/a2a-echo/requirements.txt@@ -0,0 +1,5 @@+a2a-sdk>=1.0+httpx>=0.27+sse-starlette>=2.0+starlette>=0.40+uvicorn>=0.30diff --git a/tests/e2e/docker/a2a-echo/sam-node-config.yaml b/tests/e2e/docker/a2a-echo/sam-node-config.yamlnew file mode 100644index 00000000..0ceb2f4b--- /dev/null+++ b/tests/e2e/docker/a2a-echo/sam-node-config.yaml@@ -0,0 +1,8 @@+version: "v1alpha1"+attenuation:+ policies: []+services:+ - type: "a2a"+ name: "echo"+ description: "Deterministic echo agent for the a2a e2e CUJ"+ target_url: "http://a2a-echo:7777"diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bashindex 01d92098..3dd19273 100644--- a/tests/e2e/lib/container_mesh.bash+++ b/tests/e2e/lib/container_mesh.bash@@ -399,7 +399,8 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then--set router.hostPort=4501--set console.enabled=false--set 'router.externalAddrs={/dns4/sam-router/tcp/4501}'- --set 'bootstrap.nodeServices={mcp://calculator,mcp://db-agent,mcp://http-tool,mcp://stdio-tool,system://sam.catalog}')+ --set 'bootstrap.nodeServices={mcp://calculator,mcp://db-agent,mcp://http-tool,mcp://stdio-tool,a2a://echo,system://sam.catalog}'+ --set 'bootstrap.nodeLabels={region=*}')if ! "${helm_bin}" "${helm_args[@]}"; then# The reused cluster may hold StatefulSets whose immutable spec (e.g.# volumeClaimTemplates) changed; drop them (PVCs survive) and retry.diff --git a/tests/integration/a2a_test.go b/tests/integration/a2a_test.goindex 721ea035..06ef32f2 100644--- a/tests/integration/a2a_test.go+++ b/tests/integration/a2a_test.go@@ -16,8 +16,9 @@ package integration_testimport ("bytes"- "encoding/json"+ "context""io"+ "iter""net/http""net/http/httptest""path/filepath"@@ -28,13 +29,40 @@ import ("google.golang.org/protobuf/encoding/protojson"+ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+ "github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"+ "github.com/a2aproject/a2a-go/v2/a2asrv""github.com/google/sam/api")-// TestA2ACUJ covers the "A2A agent behind the mesh" CUJ: node A (attested-// region=eu) hosts an a2a service; node B's raw egress proxy serves it with-// a rewritten agent card, admits a region=eu-labelled request, and refuses a-// region=us-east-1 request fail-closed before any payload leaves node B.+// headerRoundTripper stamps fixed headers (mesh auth, labels) on every+// request so the stock A2A SDK client needs no SAM-specific code.+type headerRoundTripper struct {+ headers map[string]string+}++func (h headerRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {+ r = r.Clone(r.Context())+ for k, v := range h.headers {+ r.Header.Set(k, v)+ }+ return http.DefaultTransport.RoundTrip(r)+}++func meshHTTPClient(token string, extra map[string]string) *http.Client {+ headers := map[string]string{api.HeaderSamAuthentication: "Bearer " + token}+ for k, v := range extra {+ headers[k] = v+ }+ return &http.Client{Transport: headerRoundTripper{headers: headers}}+}++// TestA2ACUJ covers the "A2A agent behind the mesh" CUJ with the official+// SDK on both ends: node A (attested region=eu) hosts a stock a2asrv agent;+// a stock a2aclient bootstraps from the regenerated card served by node B,+// holds a message exchange, and a region-mismatched request is refused+// fail-closed before any payload leaves node B.func TestA2ACUJ(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")_, hubAddr := startMockRouter(t)@@ -72,117 +100,113 @@ func TestA2ACUJ(t *testing.T) {}peerA := addrA[idx+len("/p2p/"):]- // Fake A2A agent on node A's side: serves its card and echoes message/send.+ // Stock-SDK A2A agent on node A's side: a2asrv serving its card and+ // echoing message/send. The card deliberately advertises a gRPC+ // interface, streaming, and a stale signature: the mesh must drop all+ // three on regeneration.var sendCount atomic.Int32var sawLabelsHeader atomic.Bool+ 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)+ yield(a2a.NewMessageForTask(a2a.MessageRoleAgent, ec, a2a.NewTextPart("echo from eu")), nil)+ }+ })+ agentCard := &a2a.AgentCard{+ Name: "echo-agent",+ Description: "test a2a agent",+ Version: "1.0.0",+ Capabilities: a2a.AgentCapabilities{Streaming: true},+ SupportedInterfaces: []*a2a.AgentInterface{+ {URL: "http://localhost:9999", 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)))agent := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.Header.Get(api.HeaderSamRequiredLabels) != "" {sawLabelsHeader.Store(true)}- 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",` +- `"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)- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"kind":"message",` +- `"messageId":"m1","role":"agent","parts":[{"kind":"text","text":"echo from eu"}]}}`))- default:- http.Error(w, "not found", http.StatusNotFound)- }+ mux.ServeHTTP(w, r)}))defer agent.Close()registerA2AService(t, apiAddrA, apiToken, "echo-agent", agent.URL)meshBase := "http://" + apiAddrB + "/sam/" + peerA + "/a2a/echo-agent"+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()- // CUJ step 1: the agent card comes back rewritten for mesh use. Poll:- // the first fetch can race connectivity establishment.+ // CUJ step 1: a stock SDK resolver bootstraps from the regenerated card.+ // Poll: the first fetch can race connectivity establishment.+ resolver := agentcard.NewResolver(meshHTTPClient(apiToken, nil))+ var card *a2a.AgentCarddeadline := time.Now().Add(30 * time.Second)- var cardBody []bytefor {- req, _ := http.NewRequest("GET", meshBase+"/.well-known/agent-card.json", nil)- req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)- resp, err := http.DefaultClient.Do(req)+ var err error+ card, err = resolver.Resolve(ctx, meshBase)if err == nil {- cardBody, _ = io.ReadAll(resp.Body)- _ = resp.Body.Close()- if resp.StatusCode == http.StatusOK {- break- }+ break}if time.Now().After(deadline) {- t.Fatalf("timeout fetching agent card, last body: %s", string(cardBody))+ t.Fatalf("timeout resolving agent card through the mesh: %v", err)}time.Sleep(200 * time.Millisecond)}- var card struct {- SupportedInterfaces []struct {- URL string `json:"url"`- ProtocolBinding string `json:"protocolBinding"`- } `json:"supportedInterfaces"`- Capabilities struct {- Streaming bool `json:"streaming"`- } `json:"capabilities"`- }- if err := json.Unmarshal(cardBody, &card); err != nil {- t.Fatalf("invalid card: %v, body: %s", err, string(cardBody))- }if len(card.SupportedInterfaces) != 1 || card.SupportedInterfaces[0].URL != meshBase {- t.Errorf("interfaces not regenerated / gRPC not dropped: %s", string(cardBody))+ t.Errorf("interfaces not regenerated / gRPC not dropped: %+v", card.SupportedInterfaces)+ }+ 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 len(card.Signatures) != 0 {+ t.Error("stale signatures must be dropped from the regenerated card")+ }- // CUJ step 2: message/send constrained to region=eu is admitted.- sendBody := `{"jsonrpc":"2.0","id":1,"method":"message/send","params":{"message":` +- `{"kind":"message","messageId":"c1","role":"user","parts":[{"kind":"text","text":"hi"}]}}}`+ // CUJ step 2: a stock SDK client built from that card, constrained to+ // region=eu, is admitted and gets the echo back.+ euClient, err := a2aclient.NewFromCard(ctx, card,+ a2aclient.WithJSONRPCTransport(meshHTTPClient(apiToken, map[string]string{api.HeaderSamRequiredLabels: "region=eu"})))+ if err != nil {+ t.Fatalf("stock client rejected the regenerated card: %v", err)+ }+ req := &a2a.SendMessageRequest{Message: a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("hi"))}deadline = time.Now().Add(30 * time.Second)+ var result a2a.SendMessageResultfor {- req, _ := http.NewRequest("POST", meshBase+"/", strings.NewReader(sendBody))- req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)- req.Header.Set("Content-Type", "application/json")- req.Header.Set(api.HeaderSamRequiredLabels, "region=eu")- resp, err := http.DefaultClient.Do(req)- if err != nil {- t.Fatalf("labelled message/send failed: %v", err)- }- body, _ := io.ReadAll(resp.Body)- _ = resp.Body.Close()- if resp.StatusCode == http.StatusOK {- if !strings.Contains(string(body), "echo from eu") {- t.Fatalf("unexpected message/send response: %s", string(body))- }+ result, err = euClient.SendMessage(ctx, req)+ if err == nil {break}if time.Now().After(deadline) {- t.Fatalf("labelled message/send status: %d, body: %s", resp.StatusCode, string(body))+ t.Fatalf("labelled message/send failed: %v", err)}time.Sleep(200 * time.Millisecond)}+ reply, ok := result.(*a2a.Message)+ if !ok {+ t.Fatalf("send result = %T, want *a2a.Message", result)+ }+ if len(reply.Parts) == 0 || reply.Parts[0].Text() != "echo from eu" {+ t.Fatalf("unexpected reply: %+v", reply)+ }// CUJ step 3: a mismatched label refuses fail-closed BEFORE egress —// the agent backend must never see the request.before := sendCount.Load()- req, _ := http.NewRequest("POST", meshBase+"/", strings.NewReader(sendBody))- req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)- req.Header.Set("Content-Type", "application/json")- req.Header.Set(api.HeaderSamRequiredLabels, "region=us-east-1")- respUS, err := http.DefaultClient.Do(req)+ usClient, err := a2aclient.NewFromCard(ctx, card,+ a2aclient.WithJSONRPCTransport(meshHTTPClient(apiToken, map[string]string{api.HeaderSamRequiredLabels: "region=us-east-1"})))if err != nil {- t.Fatalf("mismatched-label message/send failed: %v", err)+ t.Fatalf("client construction failed: %v", err)}- usBody, _ := io.ReadAll(respUS.Body)- _ = respUS.Body.Close()- if respUS.StatusCode != http.StatusForbidden {- t.Fatalf("mismatched label must fail closed with 403: got %d, body: %s", respUS.StatusCode, string(usBody))+ if _, err := usClient.SendMessage(ctx, req); err == nil {+ t.Fatal("mismatched label must fail closed")}if sendCount.Load() != before {t.Fatal("payload reached the agent despite label refusal")