Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
bridge: surface data parts inline and save file parts to disk
Tomas Tormoaebf4d2ade3f
diff --git a/cmd/sam-a2a-bridge/a2a.go b/cmd/sam-a2a-bridge/a2a.goindex 3d8124dc..1f18aad9 100644--- a/cmd/sam-a2a-bridge/a2a.go+++ b/cmd/sam-a2a-bridge/a2a.go@@ -16,6 +16,7 @@ package mainimport ("context"+ "errors""fmt""mime""net/http"@@ -30,8 +31,9 @@ import ()type bridgeConfig struct {- sidecarURL string- token string+ sidecarURL string+ token string+ downloadDir string}// meshURL is the sidecar's raw egress path for one remote a2a service.@@ -111,10 +113,12 @@ type getAgentTaskParams struct {}type taskResult struct {- TaskID string `json:"task_id"`- ContextID string `json:"context_id"`- State string `json:"state"`- Text string `json:"text"`+ TaskID string `json:"task_id"`+ ContextID string `json:"context_id"`+ State string `json:"state"`+ Text string `json:"text"`+ Data []any `json:"data,omitempty"`+ Files []string `json:"files,omitempty"`}func newMeshClient(ctx context.Context, cfg bridgeConfig, peer, service, requiredLabels string) (*a2aclient.Client, error) {@@ -154,7 +158,7 @@ func sendAgentTask(ctx context.Context, cfg bridgeConfig, p sendAgentTaskParams)if err != nil {return taskResult{}, err}- return toTaskResult(result), nil+ return toTaskResult(cfg, result)}func getAgentTask(ctx context.Context, cfg bridgeConfig, p getAgentTaskParams) (taskResult, error) {@@ -168,24 +172,32 @@ func getAgentTask(ctx context.Context, cfg bridgeConfig, p getAgentTaskParams) (if err != nil {return taskResult{}, err}- return toTaskResult(task), nil+ return toTaskResult(cfg, task)}-// 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 {+// toTaskResult flattens the SDK's Message|Task union into the fields a+// harness needs, also collecting data/file parts from every location;+// a direct Message reply is final, hence state "completed".+func toTaskResult(cfg bridgeConfig, result any) (taskResult, error) {switch v := result.(type) {case *a2a.Message:- return taskResult{+ out := taskResult{TaskID: string(v.TaskID),ContextID: v.ContextID,State: "completed",Text: textOf(v.Parts),}+ if err := out.collect(cfg, out.TaskID, v.Parts); err != nil {+ return taskResult{}, err+ }+ return out, nilcase *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 err := out.collect(cfg, out.TaskID, v.Status.Message.Parts); err != nil {+ return taskResult{}, err+ }}if out.Text == "" {var texts []string@@ -196,9 +208,14 @@ func toTaskResult(result any) taskResult {}out.Text = strings.Join(texts, "\n")}- return out+ for _, artifact := range v.Artifacts {+ if err := out.collect(cfg, out.TaskID, artifact.Parts); err != nil {+ return taskResult{}, err+ }+ }+ return out, nil}- return taskResult{}+ return taskResult{}, nil}// textOf joins the text of every part; a2a.Part is a concrete struct (not an@@ -212,3 +229,48 @@ func textOf(parts a2a.ContentParts) string {}return strings.Join(texts, "\n")}++// collect appends data parts inline and saves file parts, returning paths.+// Paths, not base64: inline bytes flood the model's context; a path the+// model can act on is the useful representation.+func (r *taskResult) collect(cfg bridgeConfig, taskID string, parts a2a.ContentParts) error {+ for _, part := range parts {+ if d := part.Data(); d != nil {+ r.Data = append(r.Data, d)+ }+ if uri := part.URL(); uri != "" {+ r.Files = append(r.Files, string(uri))+ continue+ }+ if b := part.Raw(); b != nil {+ path, err := saveFilePart(cfg.downloadDir, taskID, part.Filename, b)+ if err != nil {+ return err+ }+ r.Files = append(r.Files, path)+ }+ }+ return nil+}++func saveFilePart(dir, taskID, name string, data []byte) (string, error) {+ if taskID == "" {+ taskID = "msg"+ }+ if name == "" {+ name = "file"+ }+ name = filepath.Base(filepath.Clean("/" + name)) // remote input names a local path: keep only a leaf+ base := taskID + "-" + name+ path := filepath.Join(dir, base)+ for n := 1; ; n++ {+ if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {+ break+ }+ path = filepath.Join(dir, fmt.Sprintf("%s.%d", base, n))+ }+ if err := os.WriteFile(path, data, 0o644); err != nil {+ return "", err+ }+ return path, nil+}diff --git a/cmd/sam-a2a-bridge/a2a_test.go b/cmd/sam-a2a-bridge/a2a_test.goindex e0861e12..b0460019 100644--- a/cmd/sam-a2a-bridge/a2a_test.go+++ b/cmd/sam-a2a-bridge/a2a_test.go@@ -233,3 +233,83 @@ func TestSendAgentTaskRequiresContent(t *testing.T) {t.Fatalf("empty send must be rejected, got: %v", err)}}++func TestResultCollectsDataAndFiles(t *testing.T) {+ downloads := t.TempDir()+ fileB64 := base64.StdEncoding.EncodeToString([]byte("report body"))+ task := `{"kind":"task","id":"t20","contextId":"c20","status":{"state":"completed",` ++ `"message":{"kind":"message","messageId":"m1","role":"agent","parts":[` ++ `{"text":"done"},{"data":{"anomalies":2}}]}},` ++ `"artifacts":[{"artifactId":"a1","name":"report","parts":[` ++ `{"raw":"` + fileB64 + `","filename":"report.txt","mediaType":"text/plain"},` ++ `{"data":{"rows":14002}}]}]}`+ srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", `{"task":`+task+`}`, nil)+ defer srv.Close()++ got, err := sendAgentTask(context.Background(),+ bridgeConfig{sidecarURL: srv.URL, downloadDir: downloads},+ sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", Message: "go"})+ if err != nil {+ t.Fatal(err)+ }+ if got.Text != "done" {+ t.Errorf("text = %q, want done (text logic unchanged)", got.Text)+ }+ if len(got.Data) != 2 {+ t.Fatalf("data = %v, want 2 entries (status message + artifact)", got.Data)+ }+ if len(got.Files) != 1 {+ t.Fatalf("files = %v, want 1", got.Files)+ }+ if !strings.HasPrefix(filepath.Base(got.Files[0]), "t20-") {+ t.Errorf("file name %q not task-id-prefixed", got.Files[0])+ }+ content, err := os.ReadFile(got.Files[0])+ if err != nil || string(content) != "report body" {+ t.Fatalf("saved file wrong: %v %q", err, content)+ }+}++func TestSaveFilePartSanitizesName(t *testing.T) {+ dir := t.TempDir()+ path, err := saveFilePart(dir, "t1", "../../evil.txt", []byte("x"))+ if err != nil {+ t.Fatal(err)+ }+ if filepath.Dir(path) != dir {+ t.Fatalf("escaped the download dir: %s", path)+ }+}++func TestSaveFilePartCollision(t *testing.T) {+ dir := t.TempDir()+ first, err := saveFilePart(dir, "t1", "a.txt", []byte("1"))+ if err != nil {+ t.Fatal(err)+ }+ second, err := saveFilePart(dir, "t1", "a.txt", []byte("2"))+ if err != nil {+ t.Fatal(err)+ }+ if first == second {+ t.Fatalf("collision not uniquified: %s", second)+ }+}++func TestResultIncludesFileURIs(t *testing.T) {+ task := `{"kind":"task","id":"t21","contextId":"c21","status":{"state":"completed"},` ++ `"artifacts":[{"artifactId":"a1","parts":[` ++ `{"url":"https://example.com/big.bin","mediaType":"application/octet-stream"}]}]}`+ srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", `{"task":`+task+`}`, nil)+ defer srv.Close()++ got, err := sendAgentTask(context.Background(),+ bridgeConfig{sidecarURL: srv.URL, downloadDir: t.TempDir()},+ sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", Message: "go"})+ if err != nil {+ t.Fatal(err)+ }+ if len(got.Files) != 1 || got.Files[0] != "https://example.com/big.bin" {+ t.Fatalf("URI file part must pass through as-is: %v", got.Files)+ }+}diff --git a/cmd/sam-a2a-bridge/main.go b/cmd/sam-a2a-bridge/main.goindex 1821379d..fc54f26f 100644--- a/cmd/sam-a2a-bridge/main.go+++ b/cmd/sam-a2a-bridge/main.go@@ -20,6 +20,8 @@ import ("errors""flag""log"+ "os"+ "path/filepath""github.com/modelcontextprotocol/go-sdk/mcp")@@ -27,9 +29,23 @@ import (func main() {sidecarURL := flag.String("url", "http://localhost:8080", "Sidecar API base URL")token := flag.String("token", "", "Authorization Bearer token for protected sidecar endpoints")+ downloadDir := flag.String("download-dir", "", "Directory for files returned by agents (default: ~/.sam/a2a-downloads, created if missing)")flag.Parse()- cfg := bridgeConfig{sidecarURL: *sidecarURL, token: *token}+ // A user-supplied dir is used as-is (the caller creates it); only the+ // built-in default is auto-created.+ dir := *downloadDir+ if dir == "" {+ home, err := os.UserHomeDir()+ if err != nil {+ log.Fatal(err)+ }+ dir = filepath.Join(home, ".sam", "a2a-downloads")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ log.Fatal(err)+ }+ }+ cfg := bridgeConfig{sidecarURL: *sidecarURL, token: *token, downloadDir: dir}if err := newBridgeServer(cfg).Run(context.Background(), &mcp.StdioTransport{}); err != nil {log.Fatal(err)}@@ -73,7 +89,7 @@ func handleGetAgentTask(cfg bridgeConfig) func(context.Context, *mcp.CallToolReq// toolResult renders errors as tool errors (not protocol errors) so the// harness model sees refusal text like the labels-gate 403 verbatim.-func toolResult(res taskResult, err error) (*mcp.CallToolResult, any, error) {+func toolResult(res any, err error) (*mcp.CallToolResult, any, error) {if err != nil {text := err.Error()var se *sidecarError