Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
Remove sam-a2a-bridge in favour of the official a2a CLI
Tomas Tormo6c55c60f93d8
diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex 15f42f93..f58ad57f 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -18,7 +18,6 @@ updates:directories:- "/"- "/cmd/nano-init"- - "/cmd/sam-a2a-bridge"schedule:interval: "weekly"cooldown:diff --git a/Makefile b/Makefileindex 08129dd9..9884bbf4 100644--- a/Makefile+++ b/Makefile@@ -36,9 +36,6 @@ build:# nano-init is a separate module: it carries a userspace TCP stack, which# has no business in the dependency graph every other binary builds from.go -C cmd/nano-init build -v -o "$(OUT_DIR)/nano-init" .- # sam-a2a-bridge is a separate module too: it keeps the a2a SDK out of- # the root dependency graph.- go -C cmd/sam-a2a-bridge build -v -o "$(OUT_DIR)/sam-a2a-bridge" ..PHONY: mobile-ffi-host mobile-ffi-android mobile-ffi-android-x86_64 mobile-ffi-ios mobile-ffi mobile-app-apk mobile-app-apk-emulator mobile-app-bundlediff --git a/agents/skills/sam-a2a-bridge/SKILL.md b/agents/skills/sam-a2a-bridge/SKILL.mddeleted file mode 100644index 8e0c9f12..00000000--- a/agents/skills/sam-a2a-bridge/SKILL.md+++ /dev/null@@ -1,110 +0,0 @@-----name: sam-a2a-bridge-description: "Use when the task should be delegated to a remote A2A agent on the SAM agent mesh: send it work with send_agent_task (with text, structured data, or file attachments), check agent capabilities with get_agent_card, poll results with get_agent_task, hold multi-turn conversations, and enforce data-residency labels on every call. Also use to set up the sam-a2a-bridge MCP server when those tools are not callable yet."------# SAM A2A Bridge Skill--Use this skill to delegate work to A2A agents hosted by SAM mesh peers. The-bridge exposes three tools; everything else (auth, routing, the labels-gate) happens inside the local `sam-node`.--Pick the path that matches the need:--- The tools are not callable yet: [Set Up The Bridge](#set-up-the-bridge).-- Before sending data or files, check what the agent accepts:- [Check Agent Capabilities](#check-agent-capabilities).-- The task needs a remote agent to do something:- [Send A Task](#send-a-task).-- A previous send returned a non-terminal state:- [Poll A Task](#poll-a-task).-- The conversation with the agent continues:- [Multi-Turn](#multi-turn).-- A call failed: [Interpret Errors](#interpret-errors).--## Set Up The Bridge--The bridge is a stdio MCP server that talks to the local `sam-node` sidecar.-Propose each shell command and let the user approve it before running anything.--1. A running, enrolled `sam-node` is required first. If its sidecar does not- answer on `http://localhost:8080`, use the `sam-mesh` skill's bootstrap- path before continuing.-2. Build the bridge (own Go module; the Makefile pins the Go toolchain the- module needs, so a stale system Go still works):- `make -C <sam-repo>/cmd/sam-a2a-bridge build`-3. Register it with the harness, passing the sidecar URL and its API token:- `claude mcp add sam-a2a-bridge -- <sam-repo>/bin/sam-a2a-bridge -url http://localhost:8080 -token <sidecar-token>`- (Agent-returned files land in `~/.sam/a2a-downloads` by default, auto-created; pass `-download-dir` to change it — you must create that directory yourself. No auto-cleanup; prune manually.)-4. Restart the harness session; the three tools appear.--## Check Agent Capabilities--`get_agent_card(peer, service)`--Call this before composing structured data or file attachments to verify what-the agent accepts. Returns a trimmed card including:-- Registered skills with examples-- `default_input_modes` — accepted MIME types for structured data (e.g.,- `application/json`)-- `default_output_modes` — MIME types the agent can return-- Whether the agent supports streaming--Use the capabilities to shape your `data` (JSON object matching the agent's-input schema) and `file_path` attachments appropriately.--## Send A Task--`send_agent_task(peer, service, message?, data?, file_path?, file_name?, required_labels?, context_id?, task_id?)`--- `peer` is the provider node's peer ID; `service` is the a2a service name it- registered. If unknown, discover them with the `sam-node` MCP tool- `discover_remote_services` with `type: a2a`, or ask the user.-- At least one of `message`, `data`, or `file_path` is required. All are combinable.- - `message` is plain text.- - `data` is a JSON object; it becomes a DataPart and routes to the agent's- structured-input handler. Check `default_input_modes` first.- - `file_path` attaches a local file (up to 5 MB); `file_name` optionally- renames what the agent sees (default: the file's base name).-- The call returns immediately with `{"task_id", "context_id", "state", "text",- "data"?, "files"?}` — it never blocks on the agent.- - `data` (optional) contains structured JSON returned inline.- - `files` (optional) is a list of paths where agent-returned files are saved- under the download directory.-- **Data residency**: when the task involves data that must stay in a region or- jurisdiction, set `required_labels` (comma-separated `key=value`, e.g.- `region=eu-west-1`; several pairs must all be attested). The local node then- refuses fail-closed before any data leaves it unless the peer's- control-plane-attested labels match. Never drop- or weaken `required_labels` to make a refused call succeed without the- user's explicit approval — the refusal is the feature.--## Poll A Task--If `state` is not terminal (`completed`, `failed`, `canceled`, `rejected`),-poll with `get_agent_task(peer, service, task_id)` until it is. Space polls a-few seconds apart; agent tasks can be slow. `text` carries the agent's status-message while running and its answer or artifacts when completed. `data` and-`files` appear only when present.--## Multi-Turn--- Follow-up question in the same conversation: pass the returned `context_id`- on the next `send_agent_task`. Without it every message is a cold start.-- The task is in state `input-required` (the agent asked something): answer by- passing BOTH `task_id` and `context_id` — that routes the reply into the- waiting task so it can finish. Terminal tasks cannot receive messages.--## Interpret Errors--- `403: Required labels not attested by provider` — the label gate- refused before egress. Expected for non-matching regions; report it to the- user, do not retry with weaker labels on your own.-- `400: Invalid X-Sam-Required-Labels header ...` — malformed labels; fix the- `key=value,key=value` syntax.-- `404` / `Service not found` — the peer has no a2a service by that name;- re-discover or check the name with the user.-- Connection refused / timeout — the local sidecar URL or token is wrong, or- the node is down; go to [Set Up The Bridge](#set-up-the-bridge).-- Interop note: the remote agent must run a2a-go v2.x; older A2A stacks speak- a different JSON-RPC dialect and will not answer.diff --git a/agents/skills/sam-mesh/SKILL.md b/agents/skills/sam-mesh/SKILL.mdindex 65a76766..7f4a7a8f 100644--- a/agents/skills/sam-mesh/SKILL.md+++ b/agents/skills/sam-mesh/SKILL.md@@ -1,6 +1,6 @@---name: sam-mesh-description: "Use when local tools cannot provide a needed capability and a SAM agent mesh can: inspect mesh state, discover reachable services/tools, describe and call namespaced remote MCP tools, and reach OpenAI-compatible inference models hosted by mesh peers. Also use to set up, join, or reconnect a sam-node when its MCP tools are not callable yet."+description: "Use when local tools cannot provide a needed capability and a SAM agent mesh can: inspect mesh state, discover reachable services/tools, describe and call namespaced remote MCP tools, reach OpenAI-compatible inference models hosted by mesh peers, and hand work to A2A agents on the mesh through the official a2a CLI. Also use to set up, join, or reconnect a sam-node when its MCP tools are not callable yet."---# SAM Agent Skill@@ -21,6 +21,7 @@ Pick the path that matches the need:[Inspect The Mesh](#inspect-the-mesh).- The task needs a model completion:[Use Mesh Inference](#use-mesh-inference).+- The task needs a remote A2A agent: [Call A2A Agents](#call-a2a-agents).## Bootstrap A Node@@ -154,7 +155,8 @@ Use service discovery when you need to inventory reachable service providers:by service name.- Treat `discover_remote_services` as service inventory. Non-MCP service typesare not callable with `call_remote_tool`. For `inference://` services see- [Use Mesh Inference](#use-mesh-inference).+ [Use Mesh Inference](#use-mesh-inference), for `a2a://` services+ [Call A2A Agents](#call-a2a-agents).Use tool discovery when you need remote MCP tools:@@ -243,6 +245,48 @@ curl --unix-socket ~/.config/sam-mesh/sam.sock \Ask the user before sending private or sensitive content to a mesh model, andsay which provider will receive it.+## Call A2A Agents++The mesh also carries `a2a://` services: agents that speak the A2A protocol.+They are plain HTTP behind the node's proxy path and are never invoked with+`call_remote_tool`. Drive them with the official `a2a` CLI+(github.com/a2aproject/a2a-cli, v0.3.0 or later). It ships its own agent+skill, which covers the protocol side: cards, messages, tasks and streaming.+This section only adds what the mesh needs.++Check for the CLI with `a2a version`. If it is missing, propose the install+from its README (`go install github.com/a2aproject/a2a-cli@latest` names the+binary `a2a-cli`; rename it to `a2a`) and its skill with+`npx skills add https://github.com/a2aproject/a2a-cli --skill a2a-cli`, and+let the user approve each command.++1. Call `discover_remote_services` with `{"type":"a2a"}` and take the+ `local_proxy_url` of the provider you want.+2. Point the CLI at the agent card under that URL. The node regenerates the+ card so its interface URL is the proxy path itself; every later request+ then goes through the mesh with no further SAM-specific setup.+3. The CLI speaks TCP only, so it needs the node API token from+ [Talk To The Node Over HTTP](#talk-to-the-node-over-http) as a service+ parameter. Pass it through the CLI's environment, never as a flag, so the+ value stays out of the process arguments and the shell history:++```bash+A2ACLI_SVC_PARAM="X-Sam-Authentication=Bearer $(cat ~/.config/sam-mesh/api-token)" \+ a2a card get <local_proxy_url>/.well-known/agent-card.json+```++Every other `a2a` command takes the same card URL through `-a` and the same+environment. To accept only a provider whose labels the control plane+attested, append `,X-Sam-Required-Labels=region=eu` to that variable: the+node then refuses fail-closed with `403` before any data leaves it. That+refusal is the feature: report it, never retry with weaker labels on your+own. A `--svc-param` flag replaces the whole variable, and the variable is+split on commas, so several label pairs need a `--config` YAML file with+both entries under `svc-param` instead.++Ask the user before sending private or sensitive content to a mesh agent, and+say which peer will receive it.+## Minimal Workflow1. Confirm no local tool can satisfy the task.@@ -263,7 +307,8 @@ say which provider will receive it.`{"peer_id":"...","tool_name":"service.tool","arguments":{...}}`.For a model completion rather than a tool, skip steps 5-7 and follow-[Use Mesh Inference](#use-mesh-inference) instead.+[Use Mesh Inference](#use-mesh-inference) instead; for an A2A agent,+[Call A2A Agents](#call-a2a-agents).## Safety And Reliabilitydiff --git a/cmd/sam-a2a-bridge/.gitignore b/cmd/sam-a2a-bridge/.gitignoredeleted file mode 100644index 5af00c72..00000000--- a/cmd/sam-a2a-bridge/.gitignore+++ /dev/null@@ -1 +0,0 @@-/sam-a2a-bridgediff --git a/cmd/sam-a2a-bridge/Makefile b/cmd/sam-a2a-bridge/Makefiledeleted file mode 100644index ef8e9756..00000000--- a/cmd/sam-a2a-bridge/Makefile+++ /dev/null@@ -1,28 +0,0 @@-# Pinned because a stale system Go (1.24) fails to auto-resolve the-# toolchain go.mod needs; override with GOTOOLCHAIN=auto if yours does.-GOTOOLCHAIN ?= go1.25.7-export GOTOOLCHAIN--BINARY := sam-a2a-bridge-# Binaries land in the repo-root bin/ like every other sam binary.-OUT_DIR := $(abspath ../../bin)--.PHONY: build test vet fmt install clean--build:- go build -o "$(OUT_DIR)/$(BINARY)" .--test:- go test ./...--vet:- go vet ./...--fmt:- gofmt -l .--install:- go install .--clean:- rm -f "$(OUT_DIR)/$(BINARY)"diff --git a/cmd/sam-a2a-bridge/a2a.go b/cmd/sam-a2a-bridge/a2a.godeleted file mode 100644index 92d784fc..00000000--- a/cmd/sam-a2a-bridge/a2a.go+++ /dev/null@@ -1,356 +0,0 @@-// 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"- "errors"- "fmt"- "mime"- "net/http"- "net/url"- "os"- "path/filepath"- "strings"- "time"-- "github.com/a2aproject/a2a-go/v2/a2a"- "github.com/a2aproject/a2a-go/v2/a2aclient"-)--const maxAttachmentBytes = 5 << 20--type bridgeConfig struct {- sidecarURL string- token string- downloadDir 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/" + url.PathEscape(peer) + "/a2a/" + url.PathEscape(service)-}--type getAgentCardParams 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"`-}--// agentCardSummary trims the agent card to what a model can use; full cards-// carry security schemas and provider blurbs a model never needs.-type agentCardSummary struct {- Name string `json:"name"`- Description string `json:"description,omitempty"`- Version string `json:"version,omitempty"`- DefaultInputModes []string `json:"default_input_modes,omitempty"`- DefaultOutputModes []string `json:"default_output_modes,omitempty"`- Streaming bool `json:"streaming"`- Skills []agentCardSkill `json:"skills,omitempty"`-}--type agentCardSkill struct {- ID string `json:"id"`- Name string `json:"name,omitempty"`- Description string `json:"description,omitempty"`- Tags []string `json:"tags,omitempty"`- Examples []string `json:"examples,omitempty"`- InputModes []string `json:"input_modes,omitempty"`- OutputModes []string `json:"output_modes,omitempty"`-}--func handleGetAgentCard(ctx context.Context, cfg bridgeConfig, p getAgentCardParams) (agentCardSummary, error) {- httpClient := &http.Client{- Timeout: 30 * time.Second,- Transport: &samTransport{base: http.DefaultTransport, token: cfg.token},- }- req, err := http.NewRequestWithContext(ctx, http.MethodGet,- cfg.meshURL(p.Peer, p.Service)+"/.well-known/agent-card.json", nil)- if err != nil {- return agentCardSummary{}, err- }- resp, err := httpClient.Do(req)- if err != nil {- return agentCardSummary{}, err- }- defer func() { _ = resp.Body.Close() }()-- var card a2a.AgentCard- if err := json.NewDecoder(resp.Body).Decode(&card); err != nil {- return agentCardSummary{}, fmt.Errorf("agent card is not valid JSON: %w", err)- }- summary := agentCardSummary{- Name: card.Name,- Description: card.Description,- Version: card.Version,- DefaultInputModes: card.DefaultInputModes,- DefaultOutputModes: card.DefaultOutputModes,- Streaming: card.Capabilities.Streaming,- }- for _, skill := range card.Skills {- summary.Skills = append(summary.Skills, agentCardSkill{- ID: skill.ID,- Name: skill.Name,- Description: skill.Description,- Tags: skill.Tags,- Examples: skill.Examples,- InputModes: skill.InputModes,- OutputModes: skill.OutputModes,- })- }- return summary, nil-}--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,omitempty" jsonschema:"Plain-text message for the agent; optional if data or file_path is set"`- Data map[string]any `json:"data,omitempty" jsonschema:"Structured JSON payload sent to the agent as an A2A DataPart"`- FilePath string `json:"file_path,omitempty" jsonschema:"Local file to attach; sent to the agent as bytes, max 5 MB"`- FileName string `json:"file_name,omitempty" jsonschema:"Name shown to the agent for the attached file (default: the file's base name)"`- RequiredLabels string `json:"required_labels,omitempty" jsonschema:"Comma-separated key=value labels the provider must all have attested (e.g. region=eu-west-1,compliance=gdpr); 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 taskResult struct {- 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 handleSendAgentTask(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()-- parts, err := buildParts(p)- if err != nil {- return taskResult{}, err- }- var msg *a2a.Message- if p.TaskID != "" || p.ContextID != "" {- msg = a2a.NewMessageForTask(a2a.MessageRoleUser,- a2a.TaskInfo{TaskID: a2a.TaskID(p.TaskID), ContextID: p.ContextID}, parts...)- } else {- msg = a2a.NewMessage(a2a.MessageRoleUser, parts...)- }- result, err := client.SendMessage(ctx, &a2a.SendMessageRequest{Message: msg})- if err != nil {- return taskResult{}, err- }- return toTaskResult(cfg, result)-}--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"`-}--func handleGetAgentTask(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(cfg, task)-}--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),- )-}--// buildParts builds the message parts in a fixed order (text, data, file) so-// wire output is deterministic across calls with the same params.-func buildParts(p sendAgentTaskParams) ([]*a2a.Part, error) {- var parts []*a2a.Part- if p.Message != "" {- parts = append(parts, a2a.NewTextPart(p.Message))- }- if p.Data != nil {- parts = append(parts, a2a.NewDataPart(p.Data))- }- if p.FilePath != "" {- filePart, err := fileToPart(p.FilePath, p.FileName)- if err != nil {- return nil, err- }- parts = append(parts, filePart)- }- if len(parts) == 0 {- return nil, fmt.Errorf("nothing to send: set message, data, or file_path")- }- return parts, nil-}--// fileToPart reads path into a raw Part; the SDK's Part has no dedicated file-// constructor, so filename/mediaType are set directly on the returned Part.-func fileToPart(path, nameOverride string) (*a2a.Part, error) {- info, err := os.Stat(path)- if err != nil {- return nil, err- }- // A FIFO or device would block or misbehave in ReadFile.- if !info.Mode().IsRegular() {- return nil, fmt.Errorf("file %s is not a regular file", path)- }- if info.Size() > maxAttachmentBytes {- return nil, fmt.Errorf("file %s is %d bytes; attachment cap is %d", path, info.Size(), maxAttachmentBytes)- }- data, err := os.ReadFile(path)- if err != nil {- return nil, err- }- name := nameOverride- if name == "" {- name = filepath.Base(path)- }- mimeType := mime.TypeByExtension(filepath.Ext(name))- if mimeType == "" {- mimeType = http.DetectContentType(data)- }- part := a2a.NewRawPart(data)- part.Filename = name- part.MediaType = mimeType- return part, nil-}--// 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:- 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, nil- 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 err := out.collect(cfg, out.TaskID, v.Status.Message.Parts); err != nil {- return taskResult{}, err- }- }- 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")- }- for _, artifact := range v.Artifacts {- if err := out.collect(cfg, out.TaskID, artifact.Parts); err != nil {- return taskResult{}, err- }- }- return out, nil- }- return taskResult{}, nil-}--// 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")-}--// 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 fmt.Errorf("task %s: saving returned file: %w", taskID, 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"- }- // Both components are remote input naming a local path: keep only leaves.- taskID = filepath.Base(filepath.Clean("/" + taskID))- name = filepath.Base(filepath.Clean("/" + name))- base := taskID + "-" + name- path := filepath.Join(dir, base)- for n := 1; ; n++ {- _, err := os.Stat(path)- if errors.Is(err, os.ErrNotExist) {- break- }- if err != nil {- return "", err- }- 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.godeleted file mode 100644index 236bb841..00000000--- a/cmd/sam-a2a-bridge/a2a_test.go+++ /dev/null@@ -1,393 +0,0 @@-// 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/base64"- "encoding/json"- "io"- "net/http"- "net/http/httptest"- "os"- "path/filepath"- "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 + `}`))- }))-}--// SendMessage results arrive enveloped as {"task":...}/{"message":...} per-// a2a.StreamResponse; GetTask results don't (unmarshaled directly into a2a.Task).--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 := handleSendAgentTask(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 := handleSendAgentTask(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 := handleSendAgentTask(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 := handleSendAgentTask(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 := handleGetAgentTask(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)- }-}--func TestMeshURLEscapesPathSegments(t *testing.T) {- cfg := bridgeConfig{sidecarURL: "http://localhost:8080"}- got := cfg.meshURL("12D3KooWpeer", "../../sam/service/register")- want := "http://localhost:8080/sam/12D3KooWpeer/a2a/..%2F..%2Fsam%2Fservice%2Fregister"- if got != want {- t.Fatalf("meshURL = %q, want %q", got, want)- }-}--func TestSendAgentTaskWithDataPart(t *testing.T) {- var rpc map[string]any- task := `{"kind":"task","id":"t10","contextId":"c10","status":{"state":"completed"}}`- srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", `{"task":`+task+`}`, &rpc)- defer srv.Close()-- _, err := handleSendAgentTask(context.Background(), bridgeConfig{sidecarURL: srv.URL},- sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo",- Data: map[string]any{"answer": 42, "unit": "cm"}})- if err != nil {- t.Fatal(err)- }- raw, _ := json.Marshal(rpc)- if !strings.Contains(string(raw), `"answer":42`) || !strings.Contains(string(raw), `"unit":"cm"`) {- t.Fatalf("data payload not on the wire: %s", raw)- }-}--func TestSendAgentTaskWithFile(t *testing.T) {- dir := t.TempDir()- path := filepath.Join(dir, "hello.txt")- if err := os.WriteFile(path, []byte("hello agent"), 0o644); err != nil {- t.Fatal(err)- }- var rpc map[string]any- task := `{"kind":"task","id":"t11","contextId":"c11","status":{"state":"completed"}}`- srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", `{"task":`+task+`}`, &rpc)- defer srv.Close()-- _, err := handleSendAgentTask(context.Background(), bridgeConfig{sidecarURL: srv.URL},- sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", FilePath: path})- if err != nil {- t.Fatal(err)- }- raw, _ := json.Marshal(rpc)- wantB64 := base64.StdEncoding.EncodeToString([]byte("hello agent"))- if !strings.Contains(string(raw), wantB64) {- t.Fatalf("file bytes not on the wire as base64: %s", raw)- }- if !strings.Contains(string(raw), "hello.txt") {- t.Fatalf("file name not on the wire: %s", raw)- }-}--func TestSendAgentTaskFileTooLarge(t *testing.T) {- dir := t.TempDir()- path := filepath.Join(dir, "big.bin")- if err := os.WriteFile(path, make([]byte, maxAttachmentBytes+1), 0o644); err != nil {- t.Fatal(err)- }- _, err := handleSendAgentTask(context.Background(), bridgeConfig{sidecarURL: "http://127.0.0.1:1"},- sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", FilePath: path})- if err == nil || !strings.Contains(err.Error(), "attachment cap") {- t.Fatalf("oversized file must be rejected before any request, got: %v", err)- }-}--func TestSendAgentTaskRequiresContent(t *testing.T) {- _, err := handleSendAgentTask(context.Background(), bridgeConfig{sidecarURL: "http://127.0.0.1:1"},- sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo"})- if err == nil || !strings.Contains(err.Error(), "nothing to send") {- 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 := handleSendAgentTask(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 := handleSendAgentTask(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)- }-}--func TestGetAgentCardTrims(t *testing.T) {- card := `{"name":"echo-agent","description":"echoes","version":"1.2.0",` +- `"defaultInputModes":["text/plain","application/pdf"],"defaultOutputModes":["text/plain"],` +- `"capabilities":{"streaming":false,"pushNotifications":true},` +- `"securitySchemes":{"corp":{"apiKeySecurityScheme":{"location":"cookie","name":"session"}}},` +- `"provider":{"organization":"acme"},` +- `"skills":[{"id":"echo","name":"Echo","description":"repeats input",` +- `"tags":["test"],"examples":["say hi"],"inputModes":["audio/mpeg"],"outputModes":["text/plain"]}]}`- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet || !strings.HasSuffix(r.URL.Path, "/.well-known/agent-card.json") {- http.Error(w, "not found", http.StatusNotFound)- return- }- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(card))- }))- defer srv.Close()-- got, err := handleGetAgentCard(context.Background(), bridgeConfig{sidecarURL: srv.URL},- getAgentCardParams{Peer: "12D3KooWpeer", Service: "echo"})- if err != nil {- t.Fatal(err)- }- if got.Name != "echo-agent" || got.Version != "1.2.0" {- t.Errorf("identity fields: %+v", got)- }- if len(got.Skills) != 1 || got.Skills[0].ID != "echo" || got.Skills[0].Examples[0] != "say hi" ||- len(got.Skills[0].InputModes) != 1 || got.Skills[0].InputModes[0] != "audio/mpeg" {- t.Errorf("skills not carried: %+v", got.Skills)- }- if len(got.DefaultInputModes) != 2 {- t.Errorf("input modes not carried: %+v", got.DefaultInputModes)- }- if got.Streaming {- t.Error("streaming must reflect the card (false)")- }- raw, _ := json.Marshal(got)- if strings.Contains(string(raw), "session") || strings.Contains(string(raw), "acme") {- t.Fatalf("trim failed, security/provider material leaked: %s", raw)- }-}--func TestResultErrorIncludesTaskID(t *testing.T) {- fileB64 := base64.StdEncoding.EncodeToString([]byte("file content"))- task := `{"kind":"task","id":"t99","contextId":"c99","status":{"state":"completed",` +- `"message":{"kind":"message","messageId":"m1","role":"agent","parts":[` +- `{"raw":"` + fileB64 + `","filename":"test.txt","mediaType":"text/plain"}]}}}`- srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", `{"task":`+task+`}`, nil)- defer srv.Close()-- _, err := handleSendAgentTask(context.Background(),- bridgeConfig{sidecarURL: srv.URL, downloadDir: "/nonexistent-dir-xyz"},- sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", Message: "go"})- if err == nil {- t.Fatal("error expected when download dir does not exist")- }- if !strings.Contains(err.Error(), "task t99") {- t.Errorf("error must include task ID; got: %v", err)- }-}--func TestSaveFilePartSanitizesTaskID(t *testing.T) {- dir := t.TempDir()- path, err := saveFilePart(dir, "../../evil", "a.txt", []byte("x"))- if err != nil {- t.Fatal(err)- }- if filepath.Dir(path) != dir {- t.Fatalf("task id escaped the download dir: %s", path)- }-}--func TestFileToPartRejectsNonRegular(t *testing.T) {- if _, err := fileToPart(t.TempDir(), ""); err == nil || !strings.Contains(err.Error(), "not a regular file") {- t.Fatalf("directory must be rejected, got: %v", err)- }-}diff --git a/cmd/sam-a2a-bridge/go.mod b/cmd/sam-a2a-bridge/go.moddeleted file mode 100644index a3e7082e..00000000--- a/cmd/sam-a2a-bridge/go.mod+++ /dev/null@@ -1,21 +0,0 @@-module github.com/google/sam/cmd/sam-a2a-bridge--go 1.25.13--require (- github.com/a2aproject/a2a-go/v2 v2.5.0- github.com/modelcontextprotocol/go-sdk v1.8.0-)--require (- github.com/google/jsonschema-go v0.4.3 // indirect- github.com/google/uuid v1.6.0 // indirect- github.com/segmentio/asm v1.1.3 // indirect- github.com/segmentio/encoding v0.5.4 // indirect- github.com/yosida95/uritemplate/v3 v3.0.2 // indirect- golang.org/x/mod v0.35.0 // indirect- golang.org/x/oauth2 v0.35.0 // indirect- golang.org/x/sync v0.20.0 // indirect- golang.org/x/sys v0.45.0 // indirect- golang.org/x/time v0.15.0 // indirect-)diff --git a/cmd/sam-a2a-bridge/go.sum b/cmd/sam-a2a-bridge/go.sumdeleted file mode 100644index a1611d3c..00000000--- a/cmd/sam-a2a-bridge/go.sum+++ /dev/null@@ -1,30 +0,0 @@-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/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=-github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=-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/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=-github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=-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=-github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=-github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=-github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=-github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=-github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=-github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=-github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=-github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=-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/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=-golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=-golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=-golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=-golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=-golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=-golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=-golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=-golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=-golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=diff --git a/cmd/sam-a2a-bridge/main.go b/cmd/sam-a2a-bridge/main.godeleted file mode 100644index 44486429..00000000--- a/cmd/sam-a2a-bridge/main.go+++ /dev/null@@ -1,118 +0,0 @@-// 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"- "errors"- "flag"- "log"- "os"- "path/filepath"-- "github.com/modelcontextprotocol/go-sdk/mcp"-)--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()-- // A user-supplied dir is used as-is (the caller creates it); only the- // built-in default is auto-created. Fail fast so a missing dir surfaces- // at startup, not on the first file-bearing result.- 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)- }- } else if info, err := os.Stat(dir); err != nil || !info.IsDir() {- log.Fatalf("-download-dir %s is not a usable directory (create it first): %v", dir, err)- }- cfg := bridgeConfig{sidecarURL: *sidecarURL, token: *token, downloadDir: dir}- if err := newBridgeServer(cfg).Run(context.Background(), &mcp.StdioTransport{}); err != nil {- log.Fatal(err)- }-}--func newBridgeServer(cfg bridgeConfig) *mcp.Server {- server := mcp.NewServer(&mcp.Implementation{- Name: "sam-a2a-bridge",- Version: "0.1.0",- }, nil)-- mcp.AddTool(server, &mcp.Tool{- Name: "get_agent_card",- Description: "Fetch a mesh agent's card, trimmed to essentials: skills with examples, accepted " +- "input/output MIME types, and streaming support. Use before composing data/file sends.",- }, mcpTool(cfg, handleGetAgentCard))-- mcp.AddTool(server, &mcp.Tool{- Name: "send_agent_task",- Description: "Send a message to an A2A agent on the SAM mesh: plain text (message), structured JSON " +- "(data), and/or a local file attachment (file_path, max 5 MB) — at least one required. Returns " +- "immediately with {task_id, context_id, state, text, data?, files?}; received files are saved to " +- "disk and returned as paths. Poll non-terminal states with get_agent_task. Pass context_id to " +- "continue a conversation, task_id to reply into a task waiting for input. required_labels makes " +- "the local node refuse fail-closed unless the provider attested them.",- }, mcpTool(cfg, handleSendAgentTask))-- mcp.AddTool(server, &mcp.Tool{- Name: "get_agent_task",- Description: "Fetch the current state and output of a task previously created with send_agent_task; " +- "same result shape, including data and files.",- }, mcpTool(cfg, handleGetAgentTask))-- return server-}--// mcpTool adapts a handler to the go-sdk tool signature, routing errors-// through toolResult so refusals surface as tool errors.-func mcpTool[Params, Result any](cfg bridgeConfig, handler func(context.Context, bridgeConfig, Params) (Result, error)) func(context.Context, *mcp.CallToolRequest, Params) (*mcp.CallToolResult, any, error) {- return func(ctx context.Context, _ *mcp.CallToolRequest, p Params) (*mcp.CallToolResult, any, error) {- res, err := handler(ctx, cfg, p)- return toolResult(res, err)- }-}--// 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 any, err error) (*mcp.CallToolResult, any, error) {- if err != nil {- text := err.Error()- var se *sidecarError- if errors.As(err, &se) {- text = se.Error()- }- return &mcp.CallToolResult{- IsError: true,- Content: []mcp.Content{&mcp.TextContent{Text: text}},- }, nil, nil- }- out, err := json.Marshal(res)- if err != nil {- return nil, nil, err- }- return &mcp.CallToolResult{- Content: []mcp.Content{&mcp.TextContent{Text: string(out)}},- }, nil, nil-}diff --git a/cmd/sam-a2a-bridge/main_test.go b/cmd/sam-a2a-bridge/main_test.godeleted file mode 100644index 91ebd28a..00000000--- a/cmd/sam-a2a-bridge/main_test.go+++ /dev/null@@ -1,129 +0,0 @@-// 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"- "net/http"- "net/http/httptest"- "strings"- "testing"-- "github.com/modelcontextprotocol/go-sdk/mcp"-)--func textContent(t *testing.T, res *mcp.CallToolResult) string {- t.Helper()- if len(res.Content) != 1 {- t.Fatalf("content items = %d, want 1", len(res.Content))- }- tc, ok := res.Content[0].(*mcp.TextContent)- if !ok {- t.Fatalf("content type = %T, want *mcp.TextContent", res.Content[0])- }- return tc.Text-}--func TestHandleSendAgentTaskSuccess(t *testing.T) {- // SendMessage results arrive enveloped as {"task":...} per a2a.StreamResponse (a2a_test.go).- task := `{"task":{"kind":"task","id":"t1","contextId":"c1","status":{"state":"completed",` +- `"message":{"kind":"message","messageId":"m1","role":"agent","parts":[{"kind":"text","text":"done"}]}}}}`- srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", task, nil)- defer srv.Close()-- res, _, err := mcpTool(bridgeConfig{sidecarURL: srv.URL}, handleSendAgentTask)(- context.Background(), nil, sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", Message: "hi"})- if err != nil {- t.Fatal(err)- }- if res.IsError {- t.Fatalf("unexpected tool error: %s", textContent(t, res))- }- var got taskResult- if err := json.Unmarshal([]byte(textContent(t, res)), &got); err != nil {- t.Fatalf("output is not the 4-field JSON: %v", err)- }- if got.TaskID != "t1" || got.Text != "done" {- t.Errorf("got %+v", got)- }-}--func TestHandleSendAgentTaskRefusalIsToolError(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()-- res, _, err := mcpTool(bridgeConfig{sidecarURL: srv.URL}, handleSendAgentTask)(- context.Background(), nil, sendAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo",- Message: "hi", RequiredLabels: "region=us-east-1"})- if err != nil {- t.Fatalf("refusals are tool errors, not protocol errors: %v", err)- }- if !res.IsError {- t.Fatal("IsError must be true on sidecar refusal")- }- text := textContent(t, res)- if !strings.HasPrefix(text, "403: Required labels not attested by provider") {- t.Errorf("refusal must lead with status + verbatim body, got %q", text)- }-}--func TestHandleGetAgentTask(t *testing.T) {- task := `{"kind":"task","id":"t9","contextId":"c9","status":{"state":"completed"},` +- `"artifacts":[{"artifactId":"a1","parts":[{"kind":"text","text":"result"}]}]}`- srv := fakeSidecar(t, "/sam/12D3KooWpeer/a2a/echo", task, nil)- defer srv.Close()-- res, _, err := mcpTool(bridgeConfig{sidecarURL: srv.URL}, handleGetAgentTask)(- context.Background(), nil, getAgentTaskParams{Peer: "12D3KooWpeer", Service: "echo", TaskID: "t9"})- if err != nil {- t.Fatal(err)- }- var got taskResult- if err := json.Unmarshal([]byte(textContent(t, res)), &got); err != nil {- t.Fatal(err)- }- if got.TaskID != "t9" || got.Text != "result" {- t.Errorf("got %+v", got)- }-}--func TestNewBridgeServerConstructs(t *testing.T) {- if s := newBridgeServer(bridgeConfig{sidecarURL: "http://localhost:8080"}); s == nil {- t.Fatal("newBridgeServer returned nil")- }-}--func TestHandleGetAgentCard(t *testing.T) {- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"name":"echo-agent","capabilities":{"streaming":true},"skills":[]}`))- }))- defer srv.Close()-- res, _, err := mcpTool(bridgeConfig{sidecarURL: srv.URL}, handleGetAgentCard)(- context.Background(), nil, getAgentCardParams{Peer: "12D3KooWpeer", Service: "echo"})- if err != nil {- t.Fatal(err)- }- if res.IsError {- t.Fatalf("unexpected tool error: %s", textContent(t, res))- }- if !strings.Contains(textContent(t, res), `"echo-agent"`) {- t.Errorf("card summary missing: %s", textContent(t, res))- }-}diff --git a/cmd/sam-a2a-bridge/transport.go b/cmd/sam-a2a-bridge/transport.godeleted file mode 100644index 410fd86e..00000000--- a/cmd/sam-a2a-bridge/transport.go+++ /dev/null@@ -1,68 +0,0 @@-// 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 (- "fmt"- "io"- "net/http"- "strings"-)--// Mirrors api.HeaderSamAuthentication / api.HeaderSamRequiredLabels in the root module's api/network.go;-// literals because this module must not depend on it.-const (- headerSamAuthentication = "X-Sam-Authentication"- headerSamRequiredLabels = "X-Sam-Required-Labels"-)--// sidecarError carries a non-2xx sidecar reply so tool handlers can show-// the refusal (e.g. the labels-gate 403) to the harness verbatim.-type sidecarError struct {- Status int- Body string-}--func (e *sidecarError) Error() string {- return fmt.Sprintf("%d: %s", e.Status, strings.TrimSpace(e.Body))-}--// samTransport injects the local sidecar gate headers on every outbound-// request and converts non-2xx replies into sidecarError.-type samTransport struct {- base http.RoundTripper- token string- requiredLabels string-}--func (t *samTransport) RoundTrip(req *http.Request) (*http.Response, error) {- req = req.Clone(req.Context())- if t.token != "" {- req.Header.Set(headerSamAuthentication, "Bearer "+t.token)- }- if t.requiredLabels != "" {- req.Header.Set(headerSamRequiredLabels, t.requiredLabels)- }- resp, err := t.base.RoundTrip(req)- if err != nil {- return nil, err- }- if resp.StatusCode >= 400 {- body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- _ = resp.Body.Close()- return nil, &sidecarError{Status: resp.StatusCode, Body: string(body)}- }- return resp, nil-}diff --git a/cmd/sam-a2a-bridge/transport_test.go b/cmd/sam-a2a-bridge/transport_test.godeleted file mode 100644index 3fe801cf..00000000--- a/cmd/sam-a2a-bridge/transport_test.go+++ /dev/null@@ -1,96 +0,0 @@-// 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 (- "errors"- "io"- "net/http"- "net/http/httptest"- "strings"- "testing"-)--func TestSamTransportInjectsHeaders(t *testing.T) {- var gotAuth, gotLabels string- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- gotAuth = r.Header.Get("X-Sam-Authentication")- gotLabels = r.Header.Get("X-Sam-Required-Labels")- _, _ = w.Write([]byte("ok"))- }))- defer backend.Close()-- client := &http.Client{Transport: &samTransport{base: http.DefaultTransport, token: "tok", requiredLabels: "region=eu"}}- resp, err := client.Get(backend.URL)- if err != nil {- t.Fatal(err)- }- body, _ := io.ReadAll(resp.Body)- _ = resp.Body.Close()- if string(body) != "ok" {- t.Fatalf("body = %q", body)- }- if gotAuth != "Bearer tok" {- t.Errorf("X-Sam-Authentication = %q, want %q", gotAuth, "Bearer tok")- }- if gotLabels != "region=eu" {- t.Errorf("X-Sam-Required-Labels = %q, want %q", gotLabels, "region=eu")- }-}--func TestSamTransportOmitsEmptyHeaders(t *testing.T) {- var sawAuth, sawLabels bool- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- _, sawAuth = r.Header["X-Sam-Authentication"]- _, sawLabels = r.Header["X-Sam-Required-Labels"]- }))- defer backend.Close()-- client := &http.Client{Transport: &samTransport{base: http.DefaultTransport}}- resp, err := client.Get(backend.URL)- if err != nil {- t.Fatal(err)- }- _ = resp.Body.Close()- if sawAuth || sawLabels {- t.Fatalf("empty config must not send gate headers (auth=%v labels=%v)", sawAuth, sawLabels)- }-}--func TestSamTransportMapsRefusalToSidecarError(t *testing.T) {- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- http.Error(w, "Required labels not attested by provider", http.StatusForbidden)- }))- defer backend.Close()-- client := &http.Client{Transport: &samTransport{base: http.DefaultTransport, token: "tok"}}- _, err := client.Get(backend.URL)- if err == nil {- t.Fatal("403 must surface as an error")- }- var se *sidecarError- if !errors.As(err, &se) {- t.Fatalf("error %T does not unwrap to *sidecarError: %v", err, err)- }- if se.Status != http.StatusForbidden {- t.Errorf("status = %d, want 403", se.Status)- }- if !strings.Contains(se.Body, "Required labels not attested by provider") {- t.Errorf("body not verbatim: %q", se.Body)- }- if want := "403: Required labels not attested by provider"; se.Error() != want {- t.Errorf("Error() = %q, want %q", se.Error(), want)- }-}diff --git a/internal/node/mcp.go b/internal/node/mcp.goindex 6b1ee90c..6d2ca9ad 100644--- a/internal/node/mcp.go+++ b/internal/node/mcp.go@@ -52,6 +52,8 @@ Tools on remote services are identified via the format 'scheme://service-name/toInference services ('inference://...') are NOT called via call_remote_tool — they are plain OpenAI-compatible HTTP endpoints. Use discover_remote_services with type 'inference' to get each one's local_proxy_url, then send a normal HTTP request (e.g. POST <local_proxy_url>/chat/completions) directly to that URL.+A2A agents ('a2a://...') are NOT called via call_remote_tool either: discover them with type 'a2a', then point a stock A2A client, e.g. the official a2a CLI (github.com/a2aproject/a2a-cli), at <local_proxy_url>/.well-known/agent-card.json over TCP with the same 'X-Sam-Authentication' header (for that CLI: A2ACLI_SVC_PARAM="X-Sam-Authentication=Bearer <token>").+To authenticate such an HTTP request to this node, try these in order:1. If get_mesh_info reports a local_api_socket, send the request over that Unix socket and skip authentication entirely: it serves this same HTTP API, and only the user who owns the socket can connect to it, so no token is involved and no secret lands in a command line. e.g. 'curl --unix-socket <local_api_socket> <local_proxy_url>/chat/completions'.2. Otherwise use the TCP endpoint with header 'X-Sam-Authentication: Bearer <node API token>'. Do not read your MCP client configuration files to recover that token: they hold every other server's headers too, and reading them puts all of those secrets into the transcript. A daemonized node writes its token to ~/.config/sam-mesh/api-token; have curl read the file itself (e.g. -H @<(printf 'X-Sam-Authentication: Bearer %s' "$(cat ~/.config/sam-mesh/api-token)")) so the value never lands in an argument. If the node was started with --api-token-path or SAM_API_TOKEN, ask the user where the token lives.@@ -74,7 +76,7 @@ func NewMCPServer(node *SamNode) *mcp.Server {// Add discover_remote_services toolmcp.AddTool(mcpServer, &mcp.Tool{Name: "discover_remote_services",- Description: "Discover remote services in the mesh. Provide only `type` to browse every reachable service of that type (returns name + description for each); add `name` to target a specific service. For `type: inference`, each result's `local_proxy_url` is called directly over HTTP (NOT via call_remote_tool) — the response includes a usage hint with the exact headers required.",+ Description: "Discover remote services in the mesh. Provide only `type` to browse every reachable service of that type (returns name + description for each); add `name` to target a specific service. For `type: inference`, each result's `local_proxy_url` is called directly over HTTP (NOT via call_remote_tool) — the response includes a usage hint with the exact headers required. For `type: a2a`, `local_proxy_url` is the agent's base URL for any stock A2A client.",}, node.handleDiscoverRemoteServices)// Add the get_mesh_info tool.diff --git a/site/content/docs/guides/connecting-agents.md b/site/content/docs/guides/connecting-agents.mdindex af08ddf4..3f95c175 100644--- a/site/content/docs/guides/connecting-agents.md+++ b/site/content/docs/guides/connecting-agents.md@@ -53,6 +53,14 @@ ordinary OpenAI request to the node's `/v1` endpoint, with `base_url``http://127.0.0.1:8080/v1` and the token as the API key. `/v1/models` liststhe available models.+A2A agents are not MCP tools either. `discover_remote_services` with+`{"type":"a2a"}` lists them with a `local_proxy_url`, and any stock A2A+client works through that URL, for example the official+[`a2a` CLI](https://github.com/a2aproject/a2a-cli), whose own skill teaches+an agent the protocol. The+[node API reference](../../reference/node-api/#talking-a2a-through-the-proxy)+shows the call.+Two things an agent should know (the skill below tells it): service namesare not unique across the mesh, so the peer ID identifies a provider, anddiscovery is best-effort per peer, so on a partly reachable mesh some entriesdiff --git a/site/content/docs/reference/node-api.md b/site/content/docs/reference/node-api.mdindex 071a59e9..d4161c25 100644--- a/site/content/docs/reference/node-api.md+++ b/site/content/docs/reference/node-api.md@@ -183,6 +183,18 @@ curl -s --unix-socket $SOCK \http://localhost/sam/<peer-id>/a2a/triage/.well-known/agent-card.json```+The official [`a2a` CLI](https://github.com/a2aproject/a2a-cli) (v0.3.0 or+later) is such a client. It speaks TCP only, so the token travels as a+service parameter, set through the environment to keep it off the command+line; `X-Sam-Required-Labels` goes in the same variable, comma-separated:++```bash+CARD=http://127.0.0.1:8080/sam/<peer-id>/a2a/triage/.well-known/agent-card.json+export A2ACLI_SVC_PARAM="X-Sam-Authentication=Bearer $TOKEN"+a2a card get $CARD+a2a send -a $CARD "hello"+```+## Inference`/v1/models` collects the model list of every reachable `inference` providerdiff --git a/site/content/docs/use-cases/chat-a2a.md b/site/content/docs/use-cases/chat-a2a.mdindex 414ba178..b0c0952d 100644--- a/site/content/docs/use-cases/chat-a2a.md+++ b/site/content/docs/use-cases/chat-a2a.md@@ -140,6 +140,17 @@ something else, then ask the agent what your name is. It answers from itsown server-side session. The client never sent the history again, only the`contextId`.+The official [`a2a` CLI](https://github.com/a2aproject/a2a-cli) is another+stock client. Its reply prints the `contextId` the server created; pass it+back as `--context-id` and the agent continues the same conversation:++```bash+export A2ACLI_SVC_PARAM='X-Sam-Authentication=Bearer devtoken'+CARD="http://127.0.0.1:9099/sam/$PEER/a2a/chat/.well-known/agent-card.json"+a2a send -a "$CARD" "hello, I am Ada"+a2a send -a "$CARD" --context-id <contextId from the first reply> "what is my name?"+```+## Configuration| var | default | used by |