Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
bridge: call a2a agents through the mesh path
Tomas Tormodf7e83db1f14
diff --git a/cmd/sam-a2a-bridge/a2a.go b/cmd/sam-a2a-bridge/a2a.gonew file mode 100644index 00000000..e7ebced4--- /dev/null+++ b/cmd/sam-a2a-bridge/a2a.go@@ -0,0 +1,150 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package main++import (+ "context"+ "net/http"+ "strings"+ "time"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+)++type bridgeConfig struct {+ sidecarURL string+ token string+}++// meshURL is the sidecar's raw egress path for one remote a2a service.+func (c bridgeConfig) meshURL(peer, service string) string {+ return strings.TrimRight(c.sidecarURL, "/") + "/sam/" + peer + "/a2a/" + service+}++type sendAgentTaskParams struct {+ Peer string `json:"peer" jsonschema:"Peer ID of the node hosting the agent"`+ Service string `json:"service" jsonschema:"Name of the a2a service registered on that peer"`+ Message string `json:"message" jsonschema:"Plain-text message for the agent"`+ RequiredLabels string `json:"required_labels,omitempty" jsonschema:"Comma-separated key=value labels the provider must have attested (e.g. region=eu-west-1); the local node refuses fail-closed before any data leaves it"`+ ContextID string `json:"context_id,omitempty" jsonschema:"Continue an existing conversation context"`+ TaskID string `json:"task_id,omitempty" jsonschema:"Reply into an existing task, e.g. one in state input-required"`+}++type getAgentTaskParams struct {+ Peer string `json:"peer" jsonschema:"Peer ID of the node hosting the agent"`+ Service string `json:"service" jsonschema:"Name of the a2a service registered on that peer"`+ TaskID string `json:"task_id" jsonschema:"ID of the task to fetch"`+}++type taskResult struct {+ TaskID string `json:"task_id"`+ ContextID string `json:"context_id"`+ State string `json:"state"`+ Text string `json:"text"`+}++func newMeshClient(ctx context.Context, cfg bridgeConfig, peer, service, requiredLabels string) (*a2aclient.Client, error) {+ httpClient := &http.Client{+ Timeout: 60 * time.Second,+ Transport: &samTransport{+ base: http.DefaultTransport,+ token: cfg.token,+ requiredLabels: requiredLabels,+ },+ }+ return a2aclient.NewFromEndpoints(ctx,+ []*a2a.AgentInterface{a2a.NewAgentInterface(cfg.meshURL(peer, service), a2a.TransportProtocolJSONRPC)},+ a2aclient.WithJSONRPCTransport(httpClient),+ )+}++func sendAgentTask(ctx context.Context, cfg bridgeConfig, p sendAgentTaskParams) (taskResult, error) {+ client, err := newMeshClient(ctx, cfg, p.Peer, p.Service, p.RequiredLabels)+ if err != nil {+ return taskResult{}, err+ }+ defer client.Destroy()++ part := a2a.NewTextPart(p.Message)+ var msg *a2a.Message+ if p.TaskID != "" || p.ContextID != "" {+ msg = a2a.NewMessageForTask(a2a.MessageRoleUser,+ a2a.TaskInfo{TaskID: a2a.TaskID(p.TaskID), ContextID: p.ContextID}, part)+ } else {+ msg = a2a.NewMessage(a2a.MessageRoleUser, part)+ }+ result, err := client.SendMessage(ctx, &a2a.SendMessageRequest{Message: msg})+ if err != nil {+ return taskResult{}, err+ }+ return toTaskResult(result), nil+}++func getAgentTask(ctx context.Context, cfg bridgeConfig, p getAgentTaskParams) (taskResult, error) {+ client, err := newMeshClient(ctx, cfg, p.Peer, p.Service, "")+ if err != nil {+ return taskResult{}, err+ }+ defer client.Destroy()++ task, err := client.GetTask(ctx, &a2a.GetTaskRequest{ID: a2a.TaskID(p.TaskID)})+ if err != nil {+ return taskResult{}, err+ }+ return toTaskResult(task), nil+}++// toTaskResult flattens the SDK's Message|Task union into the 4 fields a+// harness needs; a direct Message reply is final, hence state "completed".+func toTaskResult(result any) taskResult {+ switch v := result.(type) {+ case *a2a.Message:+ return taskResult{+ TaskID: string(v.TaskID),+ ContextID: v.ContextID,+ State: "completed",+ Text: textOf(v.Parts),+ }+ case *a2a.Task:+ out := taskResult{TaskID: string(v.ID), ContextID: v.ContextID, State: string(v.Status.State)}+ if v.Status.Message != nil {+ out.Text = textOf(v.Status.Message.Parts)+ }+ if out.Text == "" {+ var texts []string+ for _, artifact := range v.Artifacts {+ if s := textOf(artifact.Parts); s != "" {+ texts = append(texts, s)+ }+ }+ out.Text = strings.Join(texts, "\n")+ }+ return out+ }+ return taskResult{}+}++// textOf joins the text of every part; a2a.Part is a concrete struct (not an+// interface) so Text() is universal, unlike the docs-only sketch assumed.+func textOf(parts a2a.ContentParts) string {+ var texts []string+ for _, part := range parts {+ if s := part.Text(); s != "" {+ texts = append(texts, s)+ }+ }+ return strings.Join(texts, "\n")+}diff --git a/cmd/sam-a2a-bridge/a2a_test.go b/cmd/sam-a2a-bridge/a2a_test.gonew file mode 100644index 00000000..2744089a--- /dev/null+++ b/cmd/sam-a2a-bridge/a2a_test.go@@ -0,0 +1,161 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package main++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// fakeSidecar records the last JSON-RPC request and returns a canned result.+func fakeSidecar(t *testing.T, wantPath string, result string, capture *map[string]any) *httptest.Server {+ t.Helper()+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !strings.HasPrefix(r.URL.Path, wantPath) {+ t.Errorf("request path = %q, want prefix %q", r.URL.Path, wantPath)+ }+ body, _ := io.ReadAll(r.Body)+ var rpc map[string]any+ _ = json.Unmarshal(body, &rpc)+ if capture != nil {+ *capture = rpc+ }+ w.Header().Set("Content-Type", "application/json")+ id, _ := json.Marshal(rpc["id"])+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":` + string(id) + `,"result":` + result + `}`))+ }))+}++// a2a-go v2.5.0's jsonrpcTransport.SendMessage unmarshals the result through+// a2a.StreamResponse, which discriminates on a {"task":...}/{"message":...}+// envelope key (a2a/core.go type event), not the raw kind-tagged object the+// A2A wire spec uses. GetTask unmarshals the result directly into a2a.Task,+// so its fixture stays unwrapped.++func TestSendAgentTaskMapsTaskResult(t *testing.T) {+ var rpc map[string]any+ task := `{"task":{"kind":"task","id":"t1","contextId":"c1",` ++ `"status":{"state":"working","message":{"kind":"message","messageId":"m1","role":"agent",` ++ `"parts":[{"kind":"text","text":"thinking"}]}}}}`+ srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", task, &rpc)+ defer srv.Close()++ cfg := bridgeConfig{sidecarURL: srv.URL, token: "tok"}+ got, err := sendAgentTask(context.Background(), cfg, sendAgentTaskParams{+ Peer: "12D3KooWpeer", Service: "echo", Message: "hi",+ })+ if err != nil {+ t.Fatal(err)+ }+ if got.TaskID != "t1" || got.ContextID != "c1" {+ t.Errorf("ids = %q/%q, want t1/c1", got.TaskID, got.ContextID)+ }+ if !strings.Contains(strings.ToLower(got.State), "working") {+ t.Errorf("state = %q, want it to convey 'working'", got.State)+ }+ if got.Text != "thinking" {+ t.Errorf("text = %q, want %q", got.Text, "thinking")+ }+ // a2a-go v2.5.0 sends the JSON-RPC method as "SendMessage" (internal/jsonrpc.MethodMessageSend),+ // not the wire-spec "message/send".+ if m, _ := rpc["method"].(string); m != "SendMessage" {+ t.Errorf("jsonrpc method = %q, want SendMessage", m)+ }+}++func TestSendAgentTaskMapsMessageResult(t *testing.T) {+ msg := `{"message":{"kind":"message","messageId":"m2","role":"agent","taskId":"t2","contextId":"c2",` ++ `"parts":[{"kind":"text","text":"4"}]}}`+ srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", msg, nil)+ defer srv.Close()++ got, err := sendAgentTask(context.Background(), bridgeConfig{sidecarURL: srv.URL},+ sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", Message: "2+2?"})+ if err != nil {+ t.Fatal(err)+ }+ if got.Text != "4" || got.TaskID != "t2" || got.ContextID != "c2" {+ t.Errorf("got %+v", got)+ }+ if got.State != "completed" {+ t.Errorf("a direct Message reply is final; state = %q, want completed", got.State)+ }+}++func TestSendAgentTaskThreadsContinuationIDs(t *testing.T) {+ var rpc map[string]any+ task := `{"task":{"kind":"task","id":"t3","contextId":"c3","status":{"state":"completed"}}}`+ srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", task, &rpc)+ defer srv.Close()++ _, err := sendAgentTask(context.Background(), bridgeConfig{sidecarURL: srv.URL},+ sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", Message: "more",+ ContextID: "c3", TaskID: "t3"})+ if err != nil {+ t.Fatal(err)+ }+ params, _ := rpc["params"].(map[string]any)+ message, _ := params["message"].(map[string]any)+ if message["taskId"] != "t3" || message["contextId"] != "c3" {+ t.Errorf("continuation ids not threaded: %v", message)+ }+}++func TestSendAgentTaskSurfacesSidecarRefusal(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Error(w, "Required labels not attested by provider", http.StatusForbidden)+ }))+ defer srv.Close()++ _, err := sendAgentTask(context.Background(), bridgeConfig{sidecarURL: srv.URL},+ sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", Message: "hi",+ RequiredLabels: "region=us-east-1"})+ if err == nil {+ t.Fatal("403 must surface as an error")+ }+ if !strings.Contains(err.Error(), "Required labels not attested by provider") {+ t.Errorf("refusal text lost: %v", err)+ }+}++func TestGetAgentTaskMapsResult(t *testing.T) {+ var rpc map[string]any+ task := `{"kind":"task","id":"t4","contextId":"c4","status":{"state":"completed"},` ++ `"artifacts":[{"artifactId":"a1","parts":[{"kind":"text","text":"final answer"}]}]}`+ srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", task, &rpc)+ defer srv.Close()++ got, err := getAgentTask(context.Background(), bridgeConfig{sidecarURL: srv.URL},+ getAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", TaskID: "t4"})+ if err != nil {+ t.Fatal(err)+ }+ // a2a-go v2.5.0 sends the JSON-RPC method as "GetTask" (internal/jsonrpc.MethodTasksGet),+ // not the wire-spec "tasks/get".+ if m, _ := rpc["method"].(string); m != "GetTask" {+ t.Errorf("jsonrpc method = %q, want GetTask", m)+ }+ if got.TaskID != "t4" || got.Text != "final answer" {+ t.Errorf("got %+v", got)+ }+ if !strings.Contains(strings.ToLower(got.State), "completed") {+ t.Errorf("state = %q, want it to convey 'completed'", got.State)+ }+}diff --git a/cmd/sam-a2a-bridge/go.mod b/cmd/sam-a2a-bridge/go.modindex 897a0ca7..eff75ad6 100644--- a/cmd/sam-a2a-bridge/go.mod+++ b/cmd/sam-a2a-bridge/go.mod@@ -2,7 +2,9 @@ module github.com/google/sam/cmd/sam-a2a-bridgego 1.25.7+require github.com/a2aproject/a2a-go/v2 v2.5.0+require (- github.com/a2aproject/a2a-go/v2 v2.5.0 // indirect- github.com/modelcontextprotocol/go-sdk v1.7.0 // indirect+ github.com/google/uuid v1.6.0 // indirect+ golang.org/x/mod v0.35.0 // indirect)diff --git a/cmd/sam-a2a-bridge/go.sum b/cmd/sam-a2a-bridge/go.sumindex 5058ce6f..799e4584 100644--- a/cmd/sam-a2a-bridge/go.sum+++ b/cmd/sam-a2a-bridge/go.sum@@ -1,4 +1,10 @@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/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=-github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=+golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=+golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=+golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=