Skip to content

Agent Mesh

testnet, docs: agents written with the A2A SDKs talk across languages

Antonio Ojeaa38ce11e3d79
diff --git a/.github/k8s/sam-probe-cronjob-template.yaml b/.github/k8s/sam-probe-cronjob-template.yaml
index 950f7215..21d27bcb 100644
--- a/.github/k8s/sam-probe-cronjob-template.yaml
+++ b/.github/k8s/sam-probe-cronjob-template.yaml
@@ -67,15 +67,15 @@ spec:
readOnly: true
- name: sam-uds
mountPath: /var/run/sam
- # An agent written with each SDK (sdk/js/examples/agent.ts,
- # sdk/python/examples/agent.py), the programs the docs embed. Each
- # accepts A2A requests for a2a://agent and publishes nothing; its
- # stdout goes to the container log and to the shared volume, where
- # the probe reads its peer ID.
+ # An agent written with each SDK and the official A2A SDK
+ # (sdk/js/examples/a2a-agent.ts, sdk/python/examples/a2a_agent.py),
+ # the programs the docs embed. Each accepts A2A requests for
+ # a2a://agent and publishes nothing; its stdout goes to the container
+ # log and to the shared volume, where the probe reads its peer ID.
- name: js-agent
restartPolicy: Always
image: ghcr.io/google/sam-sdk-js:${IMAGE_TAG}
- command: ["/bin/sh", "-c", "node build/examples/agent.js 2>&1 | tee /var/run/sam-agents/js-agent.log"]
+ command: ["/bin/sh", "-c", "node build/examples/a2a-agent.js 2>&1 | tee /var/run/sam-agents/js-agent.log"]
env:
- name: SAM_CONTROL_PLANE_URL
value: "http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"
@@ -105,7 +105,7 @@ spec:
- name: python-agent
restartPolicy: Always
image: ghcr.io/google/sam-sdk-python:${IMAGE_TAG}
- command: ["/bin/sh", "-c", "python examples/agent.py 2>&1 | tee /var/run/sam-agents/python-agent.log"]
+ command: ["/bin/sh", "-c", "python examples/a2a_agent.py 2>&1 | tee /var/run/sam-agents/python-agent.log"]
env:
- name: SAM_CONTROL_PLANE_URL
value: "http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"
@@ -238,10 +238,10 @@ spec:
# 4. An agent written with each SDK, reachable by peer ID alone:
# it published nothing, so there is nothing to discover, and the
# node finds the path through the router by itself. The probe
- # reads the peer ID from the line the agent printed, then calls
- # its A2A endpoint through the egress proxy, the way an agent
- # behind this node reaches another agent. The answer names the
- # verified caller.
+ # reads the peer ID from the line the agent printed, then fetches
+ # its agent card through the egress proxy, the way an A2A client
+ # behind this node would; the node rewrites the card's URL to the
+ # mesh path it serves.
SDK_START=$(date +%s)
SDK_PEERS=""
for lang in ${SDK_AGENTS}; do
@@ -256,8 +256,8 @@ spec:
LAST_ERR=""
CALL_START=$(date +%s)
while :; do
- CODE=$(curl -s --unix-socket "$SOCK" -o /tmp/sdk-card.out -w '%{http_code}' "http://localhost/sam/${AGENT_PEER}/a2a/agent/card")
- if [ "$CODE" = "200" ] && grep -q '"caller"' /tmp/sdk-card.out; then
+ CODE=$(curl -s --unix-socket "$SOCK" -o /tmp/sdk-card.out -w '%{http_code}' "http://localhost/sam/${AGENT_PEER}/a2a/agent/.well-known/agent-card.json")
+ if [ "$CODE" = "200" ] && grep -q 'Echo agent' /tmp/sdk-card.out && grep -q "/sam/${AGENT_PEER}/a2a/agent" /tmp/sdk-card.out; then
break
fi
LAST_ERR="HTTP ${CODE} $(head -c 160 /tmp/sdk-card.out | tr -d '"\n')"
diff --git a/.github/k8s/sam-sdk-canary-template.yaml b/.github/k8s/sam-sdk-canary-template.yaml
index e4988f5f..46e0567e 100644
--- a/.github/k8s/sam-sdk-canary-template.yaml
+++ b/.github/k8s/sam-sdk-canary-template.yaml
@@ -1,9 +1,10 @@
# Two long-lived pairs of SDK members with no sam-node beside them: an agent
-# written with one SDK and a caller written with the other, in one pod, both
-# example programs (sdk/js/examples, sdk/python/examples) unchanged. The agent
-# joins through a router and accepts A2A requests for a2a://agent; it publishes
-# nothing, so the caller learns its peer ID from the line it prints, through a
-# volume the pod shares, and calls it every few minutes. The caller is Ready
+# written with one SDK and the official A2A SDK, and a caller written with the
+# other, in one pod, both example programs (sdk/js/examples,
+# sdk/python/examples) unchanged. The agent joins through a router and accepts
+# A2A requests for a2a://agent; it publishes nothing, so the caller learns its
+# peer ID from the line it prints, through a volume the pod shares, and sends
+# it a message with the A2A SDK's client every few minutes. The caller is Ready
# while its last call succeeded, so the Deployment's availability is the
# answer to "can an agent written with one SDK still be reached by the other
# after hours on the mesh": relay reservations renewed, credentials refreshed,
@@ -31,7 +32,7 @@ spec:
containers:
- name: agent
image: ghcr.io/google/sam-sdk-js:${IMAGE_TAG}
- command: ["/bin/sh", "-c", "node build/examples/agent.js 2>&1 | tee /var/run/sam/agent.log"]
+ command: ["/bin/sh", "-c", "node build/examples/a2a-agent.js 2>&1 | tee /var/run/sam/agent.log"]
env:
- name: SAM_CONTROL_PLANE_URL
value: "http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"
@@ -75,7 +76,7 @@ spec:
- name: CANARY
value: python-calls-js-agent
- name: CALL
- value: "python examples/call.py"
+ value: "python examples/a2a_call.py"
readinessProbe:
exec:
command: ["test", "-f", "/var/run/sam/reachable"]
@@ -137,7 +138,7 @@ spec:
containers:
- name: agent
image: ghcr.io/google/sam-sdk-python:${IMAGE_TAG}
- command: ["/bin/sh", "-c", "python examples/agent.py 2>&1 | tee /var/run/sam/agent.log"]
+ command: ["/bin/sh", "-c", "python examples/a2a_agent.py 2>&1 | tee /var/run/sam/agent.log"]
env:
- name: SAM_CONTROL_PLANE_URL
value: "http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"
@@ -181,7 +182,7 @@ spec:
- name: CANARY
value: js-calls-python-agent
- name: CALL
- value: "node build/examples/call.js"
+ value: "node build/examples/a2a-call.js"
readinessProbe:
exec:
command: ["test", "-f", "/var/run/sam/reachable"]
@@ -230,8 +231,9 @@ metadata:
data:
canary.sh: |
#!/bin/sh
- # Calls the agent beside this container every INTERVAL seconds by the
- # peer ID it printed to /var/run/sam/agent.log, and keeps
+ # Sends the agent beside this container a message with the A2A SDK's
+ # client every INTERVAL seconds, by the peer ID it printed to
+ # /var/run/sam/agent.log, and keeps
# /var/run/sam/reachable present while the last call succeeded; the
# readiness probe reads it. One JSON line per call, for a log-based
# metric. The first call enrolls with the projected token; the later ones
@@ -253,8 +255,8 @@ data:
continue
fi
start=$(date +%s)
- out=$($CALL "$AGENT_PEER" a2a://agent /card 2>&1); rc=$?
- if [ $rc -eq 0 ] && printf '%s' "$out" | grep -q '"caller"'; then
+ out=$($CALL "$AGENT_PEER" "hello from ${CANARY}" 2>&1); rc=$?
+ if [ $rc -eq 0 ] && printf '%s' "$out" | grep -q "said: hello from ${CANARY}"; then
touch "$REACHABLE"
verdict true $(( $(date +%s) - start )) ""
sleep "$INTERVAL"
diff --git a/.github/k8s/sam-sdk-probe-cronjob-template.yaml b/.github/k8s/sam-sdk-probe-cronjob-template.yaml
index 7ee33e2c..0a84389a 100644
--- a/.github/k8s/sam-sdk-probe-cronjob-template.yaml
+++ b/.github/k8s/sam-sdk-probe-cronjob-template.yaml
@@ -1,14 +1,16 @@
# The cold path through the SDKs, on a schedule. Four fresh identities enroll
-# with the control plane, two per SDK: an agent, which joins through a router
-# and accepts A2A requests for a2a://agent, and a caller, which reaches an MCP
-# service a sam-node serves (the everything canary) by name and the other
-# language's agent by peer ID. An agent publishes nothing; the caller learns
-# its peer ID from the line the agent prints, through a volume the pod shares.
-# The programs are the examples the READMEs embed, unchanged; the shell around
-# them only retries discovery, which a member that joined seconds ago can
-# miss, waits for the agent, and prints one verdict line. The agents are
-# native sidecars, stopped when both callers exit, so the Job completes. The
-# control plane's --node-retention sweep reclaims the rows.
+# with the control plane, two per SDK: an agent written with the official A2A
+# SDK, which joins through a router and accepts A2A requests for a2a://agent,
+# and a caller, which reaches an MCP service a sam-node serves (the everything
+# canary) by name and the other language's agent by peer ID, first with the
+# mesh SDK's own client for the agent card, then with the A2A SDK's client for
+# a message. An agent publishes nothing; the caller learns its peer ID from the
+# line the agent prints, through a volume the pod shares. The programs are the
+# examples the READMEs embed, unchanged; the shell around them only retries
+# discovery, which a member that joined seconds ago can miss, waits for the
+# agent, and prints one verdict line. The agents are native sidecars, stopped
+# when both callers exit, so the Job completes. The control plane's
+# --node-retention sweep reclaims the rows.
apiVersion: batch/v1
kind: CronJob
metadata:
@@ -24,8 +26,8 @@ spec:
# One attempt: a retry would hide exactly the flakiness this exists to
# measure. A failed Job is the signal; both callers must succeed.
backoffLimit: 0
- # Two calls with up to 120s each, plus enrollment.
- activeDeadlineSeconds: 420
+ # Three calls with up to 120s each, plus enrollment.
+ activeDeadlineSeconds: 540
template:
metadata:
labels:
@@ -44,7 +46,7 @@ spec:
- name: js-agent
restartPolicy: Always
image: ghcr.io/google/sam-sdk-js:${IMAGE_TAG}
- command: ["/bin/sh", "-c", "node build/examples/agent.js 2>&1 | tee /var/run/sam/js-agent.log"]
+ command: ["/bin/sh", "-c", "node build/examples/a2a-agent.js 2>&1 | tee /var/run/sam/js-agent.log"]
env:
- name: SAM_CONTROL_PLANE_URL
value: "http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"
@@ -74,7 +76,7 @@ spec:
- name: python-agent
restartPolicy: Always
image: ghcr.io/google/sam-sdk-python:${IMAGE_TAG}
- command: ["/bin/sh", "-c", "python examples/agent.py 2>&1 | tee /var/run/sam/python-agent.log"]
+ command: ["/bin/sh", "-c", "python examples/a2a_agent.py 2>&1 | tee /var/run/sam/python-agent.log"]
env:
- name: SAM_CONTROL_PLANE_URL
value: "http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"
@@ -119,6 +121,8 @@ spec:
value: sam-sdk-js
- name: CALL
value: "node build/examples/call.js"
+ - name: A2A_CALL
+ value: "node build/examples/a2a-call.js"
- name: AGENT_LOG
# Where the other SDK's agent prints its peer ID.
value: /var/run/sam/python-agent.log
@@ -160,6 +164,8 @@ spec:
value: sam-sdk-python
- name: CALL
value: "python examples/call.py"
+ - name: A2A_CALL
+ value: "python examples/a2a_call.py"
- name: AGENT_LOG
value: /var/run/sam/js-agent.log
securityContext:
@@ -205,10 +211,11 @@ metadata:
data:
probe.sh: |
#!/bin/sh
- # Runs the SDK's call example against a sam-node's MCP service and the
+ # Runs the SDK's call examples against a sam-node's MCP service and the
# other SDK's agent, and prints one JSON verdict line. PROBE names the
- # run, CALL is the example's command line, AGENT_LOG is where the other
- # SDK's agent prints "accepting a2a://agent as <peer>". Discovery is
+ # run, CALL and A2A_CALL are the examples' command lines, AGENT_LOG is
+ # where the other SDK's agent prints "accepting a2a://agent as <peer>".
+ # Discovery is
# retried: a member that joined seconds ago has a thin routing table, and
# a provider record can name a pod a rollout just replaced. The first
# call enrolls with the projected token; the later ones resume from
@@ -222,14 +229,14 @@ data:
exit 1
}
- # call <stage> <expected substring> <example arguments...>; sets PROVIDER.
+ # call <program> <stage> <expected substring> <arguments...>; sets PROVIDER.
call() {
- stage=$1; want=$2; shift 2
+ program=$1; stage=$2; want=$3; shift 3
stage_start=$(date +%s)
attempts=0
while :; do
attempts=$((attempts + 1))
- out=$($CALL "$@" 2>&1); rc=$?
+ out=$($program "$@" 2>&1); rc=$?
if [ $rc -eq 0 ] && printf '%s' "$out" | grep -q "$want"; then
PROVIDER=$(printf '%s' "$out" | grep -o 'is served by [^ ]*' | tail -1 | cut -d' ' -f4)
return 0
@@ -251,16 +258,22 @@ data:
}
# 1. Enroll, join and call an MCP service a sam-node serves.
- call node-mcp 'Echo: sam-sdk-probe' mcp://everything echo '{"message": "sam-sdk-probe"}'
+ call "$CALL" node-mcp 'Echo: sam-sdk-probe' mcp://everything echo '{"message": "sam-sdk-probe"}'
NODE_PEER=$PROVIDER
NODE_S=$(( $(date +%s) - START ))
# 2. The other SDK's agent, by peer ID, over /libp2p-http through the
- # router: the agent names the verified caller in its answer.
+ # router: its agent card, with the mesh SDK's own client.
wait_for_agent "$AGENT_LOG"
A2A_START=$(date +%s)
- call sdk-a2a '"caller"' "$AGENT_PEER" a2a://agent /card
- A2A_S=$(( $(date +%s) - A2A_START ))
+ call "$CALL" sdk-card 'Echo agent' "$AGENT_PEER" a2a://agent /.well-known/agent-card.json
+ CARD_S=$(( $(date +%s) - A2A_START ))
- printf '{"probe":"%s","ok":true,"node_s":%d,"node_provider":"%s","a2a_s":%d,"agent_peer":"%s","elapsed_s":%d}\n' \
- "$PROBE" "$NODE_S" "$NODE_PEER" "$A2A_S" "$AGENT_PEER" "$(( $(date +%s) - START ))"
+ # 3. A message to the same agent with the A2A SDK's client: the answer
+ # names the caller the agent's server saw as the verified peer.
+ MESSAGE_START=$(date +%s)
+ call "$A2A_CALL" sdk-message "said: hello from ${PROBE}" "$AGENT_PEER" "hello from ${PROBE}"
+ MESSAGE_S=$(( $(date +%s) - MESSAGE_START ))
+
+ printf '{"probe":"%s","ok":true,"node_s":%d,"node_provider":"%s","card_s":%d,"message_s":%d,"agent_peer":"%s","elapsed_s":%d}\n' \
+ "$PROBE" "$NODE_S" "$NODE_PEER" "$CARD_S" "$MESSAGE_S" "$AGENT_PEER" "$(( $(date +%s) - START ))"
diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml
index 73b879ff..63c3d584 100644
--- a/.github/workflows/deploy.yaml
+++ b/.github/workflows/deploy.yaml
@@ -807,8 +807,9 @@ jobs:
}
# Two long-lived pairs with no sam-node: an agent written with one SDK
- # and a caller written with the other, reaching it by peer ID every few
- # minutes. The caller's readiness is the last call's outcome.
+ # and the official A2A SDK, and a caller written with the other that
+ # sends it a message with the A2A SDK's client every few minutes, by
+ # peer ID. The caller's readiness is the last call's outcome.
- name: Deploy SDK Canaries
env:
VAR_ENV_NAME: ${{ vars.ENV_NAME }}
@@ -941,12 +942,13 @@ jobs:
;;
esac
- # The same cold path through each SDK: an agent and a caller enroll
- # with the JavaScript and the Python SDK; each caller reaches the
- # everything canary's MCP server (a sam-node) by name and the other
- # SDK's agent by peer ID. With the node probe above, every pair of
- # implementations is crossed in both directions on every rollout and
- # every 15 minutes after.
+ # The same cold path through each SDK: an agent written with the A2A
+ # SDK and a caller enroll with the JavaScript and the Python SDK; each
+ # caller reaches the everything canary's MCP server (a sam-node) by
+ # name and the other SDK's agent by peer ID, its card with the mesh
+ # SDK's client and a message with the A2A SDK's. With the node probe
+ # above, every pair of implementations is crossed in both directions
+ # on every rollout and every 15 minutes after.
- name: Deploy and run the SDK cold-path probe
env:
VAR_ENV_NAME: ${{ vars.ENV_NAME }}
diff --git a/sdk/README.md b/sdk/README.md
index 94069ee1..9ef484b6 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -468,6 +468,13 @@ holds against the control plane's records.
- `sam-node`: a peer it knows no address for is dialed through every
router it authenticated with, so its egress proxy reaches an agent by
peer ID (`preparePeerAddrs`).
+- Examples with the official A2A SDKs (`a2a-agent.ts`, `a2a-call.ts`;
+ `a2a_agent.py`, `a2a_call.py`): the A2A SDK's server is the listener
+ `acceptA2A` runs (JS) or a uvicorn process `accept_a2a` forwards to
+ (Python), its card names the agent by its mesh URL, and the A2A SDK's
+ client runs on `session.fetch()` or `MeshTransport`. The A2A SDKs are
+ dependencies of the examples only: dev dependencies in `sdk/js`, the
+ `examples` extra in `sdk/python`.
- Tests. Unit: each SDK's ingress behind an in-process host, called with
its own clients: a forwarded A2A server that sees `X-Peer-Id` and never
the biscuit, an SSE body read event by event, an in-process handler (and
@@ -481,7 +488,10 @@ holds against the control plane's records.
lookup, a lookup for `a2a://agent` finds nothing, the member refuses a
`/sam/mcp/1.0.0` stream, and a Go peer whose role the policy grants
nothing gets 403 and is answered once it presents a node-role token.
- About 9 seconds for the whole mesh.
+ About 9 seconds for the whole mesh. `TestNativeSDKA2A` runs the A2A SDK
+ agents and calls each from the other language with the A2A SDK's client;
+ the answer names the caller's peer, and a `sam-node` fetches the card
+ through its egress proxy.
### Milestone 5 — parity and release (done)
@@ -540,22 +550,24 @@ holds against the control plane's records.
Both testnets run the example programs, unchanged, as canaries beside the
`sam-node` ones (`.github/k8s/sam-sdk-canary-template.yaml`): two pairs, an
-agent written with one SDK and a caller written with the other in one pod,
-enrolled with the pod's projected service account token through
-`SAM_JWT_PATH`. The agent accepts `a2a://agent`; the caller reads its peer
-ID from the line it prints, through a volume the pod shares, calls it every
-five minutes and is Ready while the last call succeeded, so the
-Deployment's availability says whether an agent is still reachable after
-hours on the mesh. Two CronJobs cross every implementation boundary every
-15 minutes and once per rollout: the `sam-node` cold-path probe
-(`sam-probe-cronjob-template.yaml`) runs an agent per SDK as sidecars and
-reaches each by peer ID through the egress proxy (node → SDK), and the SDK
-cold-path probe (`sam-sdk-probe-cronjob-template.yaml`) runs each SDK's
-`call` against the everything canary by name (SDK → node) and the other
-SDK's agent by peer ID (SDK → SDK). The images (`Dockerfile.sam-sdk-js`,
-`Dockerfile.sam-sdk-python`) are built per commit by `deploy.yaml`, so
-`bananas` runs the SDKs at the same commit as the Go components they talk
-to.
+agent written with one SDK and the official A2A SDK (`a2a-agent.ts`,
+`a2a_agent.py`) and a caller written with the other in one pod, enrolled
+with the pod's projected service account token through `SAM_JWT_PATH`. The
+agent accepts `a2a://agent`; the caller reads its peer ID from the line it
+prints, through a volume the pod shares, sends it a message with the A2A
+SDK's client every five minutes and is Ready while the last answer named
+the caller, so the Deployment's availability says whether an agent is still
+reachable after hours on the mesh. Two CronJobs cross every implementation
+boundary every 15 minutes and once per rollout: the `sam-node` cold-path
+probe (`sam-probe-cronjob-template.yaml`) runs an agent per SDK as sidecars
+and fetches each one's agent card by peer ID through the egress proxy
+(node → SDK), and the SDK cold-path probe
+(`sam-sdk-probe-cronjob-template.yaml`) runs each SDK's callers against the
+everything canary by name (SDK → node) and the other SDK's agent by peer ID,
+the card with the mesh SDK's client and a message with the A2A SDK's
+(SDK → SDK). The images (`Dockerfile.sam-sdk-js`, `Dockerfile.sam-sdk-python`)
+are built per commit by `deploy.yaml`, so `bananas` runs the SDKs at the
+same commit as the Go components they talk to.
### Later
diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.md
index 89649ba6..c2f84e3c 100644
--- a/site/content/docs/guides/native-sdks.md
+++ b/site/content/docs/guides/native-sdks.md
@@ -448,6 +448,413 @@ The caller and the agent are two identities on the mesh with their own
state directories, `caller` and `agent`. Each spent a token on its first
run; the standing join token of `sam-one` admits any number of members.
+## 5. Agents that speak A2A
+
+The two programs above answer and call HTTP paths by hand. An agent you
+write with an [A2A SDK](https://a2a-protocol.org/) speaks the protocol:
+an agent card, `message/send`, tasks, streaming. It joins the mesh the same
+way, and needs to know two things: the URL it has on the mesh, and how to
+plug the mesh in as its transport.
+
+- An agent on the mesh has the URL `http://mesh/sam/<peer-id>/a2a/agent`
+ (`MeshSession.meshURL(peerId, "a2a://agent")`,
+ `MeshSession.mesh_url(peer_id, "a2a://agent")`). That is what goes in its
+ agent card, and what an A2A client on the mesh is given. The peer ID is in
+ the path because URL parsers lowercase the host and a peer ID is
+ case-sensitive.
+- The A2A JavaScript SDK takes a `fetch` for its client and mounts its server
+ as Express handlers. `session.fetch()` is the fetch;
+ `acceptA2A({ listener: app })` runs the Express app on the mesh, with
+ nothing listening on a port.
+- The A2A Python SDK takes an `httpx.AsyncClient` for its client and runs its
+ server as a Starlette app. `httpx.AsyncClient(transport=MeshTransport(session))`
+ is the client; the server runs under uvicorn on a loopback port, in a
+ thread since the A2A SDK is asyncio and the mesh SDK trio, and
+ `accept_a2a("http://127.0.0.1:<port>")` forwards to it.
+
+Install the A2A SDK next to the mesh SDK:
+
+```bash
+npm install @a2a-js/sdk express
+```
+
+```bash
+pip install 'a2a-sdk[http-server]' uvicorn
+```
+
+The agent, an echo: it answers every message with what was said and who
+said it. Who said it is the peer the mesh verified, which the SDK sets as
+`X-Peer-Id` after authorizing the request and before it reaches the A2A
+server, so the agent reads the header rather than a name in the message.
+
+JavaScript, `a2a-agent.js`:
+
+<!-- embed: sdk/js/examples/a2a-agent.ts -->
+```ts
+// An agent written with the A2A SDK, on the mesh. The A2A SDK builds the agent
+// card and the JSON-RPC handler as an Express app; instead of listening on a
+// port, the app answers requests the mesh SDK accepts for a2a://agent. Other
+// members reach it by peer ID through a router; the mesh policy decides which
+// ones, and the SDK turns the rest away before a request reaches the app.
+//
+// node a2a-agent.js
+//
+// SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
+// SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or
+// SAM_JWT_PATH (a workload identity token your platform issues, such as a
+// Kubernetes projected service account token), and keeps the identity and
+// credential in SAM_STATE_DIR; later runs resume from there, as the same
+// peer, without it.
+import { homedir } from "node:os";
+import { randomUUID } from "node:crypto";
+import express from "express";
+import { A2A_PROTOCOL_VERSION, AGENT_CARD_PATH, Role, type AgentCard, type Message } from "@a2a-js/sdk";
+import { AgentEvent, DefaultRequestHandler, InMemoryTaskStore, type AgentExecutor, type ExecutionEventBus, type RequestContext } from "@a2a-js/sdk/server";
+import { UserBuilder, agentCardHandler, jsonRpcHandler } from "@a2a-js/sdk/server/express";
+import { AgentMesh, MeshSession } from "@sam-mesh/sdk";
+
+const mesh = await AgentMesh.enroll({
+ controlPlaneUrl: process.env.SAM_CONTROL_PLANE_URL ?? "https://mesh.example.com",
+ bootstrapTokenPath: process.env.SAM_BOOTSTRAP_TOKEN_PATH,
+ jwtPath: process.env.SAM_JWT_PATH,
+ stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/a2a-agent`,
+ // A plaintext http:// control plane is otherwise accepted only on loopback.
+ allowInsecure: process.env.SAM_INSECURE_CONTROL_PLANE === "true",
+});
+const session = await mesh.join();
+
+// The card names the agent as the mesh reaches it: the URL an A2A client on
+// the mesh gives its fetch, http://mesh/sam/<peer-id>/a2a/agent.
+const url = MeshSession.meshURL(session.peerId, "a2a://agent");
+const card: AgentCard = {
+ name: "Echo agent",
+ description: "Answers every message with what it said and who sent it.",
+ version: "1.0.0",
+ supportedInterfaces: [{ url, protocolBinding: "JSONRPC", tenant: "", protocolVersion: A2A_PROTOCOL_VERSION }],
+ provider: undefined,
+ documentationUrl: "",
+ capabilities: { streaming: true, pushNotifications: false, extendedAgentCard: false, extensions: [] },
+ securitySchemes: {},
+ securityRequirements: [],
+ defaultInputModes: ["text/plain"],
+ defaultOutputModes: ["text/plain"],
+ skills: [{ id: "echo", name: "Echo", description: "Repeats the message.", tags: ["echo"], examples: ["hello"], inputModes: [], outputModes: [], securityRequirements: [] }],
+ signatures: [],
+ iconUrl: "",
+};
+
+// The agent's logic: one message in, one message out. The user on the call
+// context is the caller the mesh verified, built from X-Peer-Id below.
+class EchoExecutor implements AgentExecutor {
+ async execute(context: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
+ const said = context.userMessage.parts.map((p) => (p.content?.$case === "text" ? p.content.value : "")).join("");
+ const caller = context.context.user?.userName ?? "someone";
+ const reply: Message = {
+ messageId: randomUUID(),
+ contextId: context.contextId,
+ taskId: "",
+ role: Role.ROLE_AGENT,
+ parts: [{ content: { $case: "text", value: `${caller} said: ${said}` }, filename: "", mediaType: "text/plain", metadata: undefined }],
+ metadata: undefined,
+ extensions: [],
+ referenceTaskIds: [],
+ };
+ eventBus.publish(AgentEvent.message(reply));
+ eventBus.finished();
+ }
+
+ async cancelTask(): Promise<void> {}
+}
+
+const requestHandler = new DefaultRequestHandler(card, new InMemoryTaskStore(), new EchoExecutor());
+const app = express();
+app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
+// The SDK sets X-Peer-Id to the peer it verified and authorized, after
+// stripping anything the caller sent under that name.
+const verifiedPeer: UserBuilder = async (req) => ({ isAuthenticated: true, userName: String(req.headers["x-peer-id"] ?? "") });
+app.use(jsonRpcHandler({ requestHandler, userBuilder: verifiedPeer }));
+
+const target = await session.acceptA2A({ listener: app });
+console.log(`accepting ${target} as ${session.peerId}`);
+console.log(`agent card at ${session.agentURL}/${AGENT_CARD_PATH}`);
+
+const stop = () => void session.close().then(() => process.exit(0));
+process.on("SIGINT", stop);
+process.on("SIGTERM", stop);
+```
+<!-- /embed -->
+
+Python, `a2a_agent.py`:
+
+<!-- embed: sdk/python/examples/a2a_agent.py -->
+```python
+"""An agent written with the A2A SDK, on the mesh. The A2A SDK's server runs
+as it always does, a Starlette app under uvicorn on a loopback port; the mesh
+SDK accepts requests for a2a://agent and forwards them to it. Other members
+reach the agent by peer ID through a router; the mesh policy decides which
+ones, and the SDK turns the rest away before a request reaches the app.
+
+ python a2a_agent.py
+
+SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
+SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or SAM_JWT_PATH
+(a workload identity token your platform issues, such as a Kubernetes
+projected service account token), and keeps the identity and credential in
+SAM_STATE_DIR; later runs resume from there, as the same peer, without it.
+"""
+
+import os
+import socket
+import threading
+
+import trio
+import uvicorn
+from a2a.helpers import get_message_text, new_text_message
+from a2a.server.agent_execution import AgentExecutor, RequestContext
+from a2a.server.events 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 import InMemoryTaskStore
+from a2a.types import AgentCapabilities, AgentCard, AgentInterface, AgentSkill, Role
+from agent_mesh import AgentMesh, MeshSession
+from starlette.applications import Starlette
+
+mesh = AgentMesh.enroll(
+ os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
+ bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
+ jwt_path=os.environ.get("SAM_JWT_PATH"),
+ state_dir=os.environ.get("SAM_STATE_DIR", "~/.config/sam-mesh/a2a-agent"),
+ # A plaintext http:// control plane is otherwise accepted only on loopback.
+ allow_insecure=os.environ.get("SAM_INSECURE_CONTROL_PLANE") == "true",
+)
+
+
+class EchoExecutor(AgentExecutor):
+ """One message in, one message out. X-Peer-Id is the caller the mesh
+ verified; the SDK sets it after authorizing the request."""
+
+ async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
+ caller = context.call_context.state["headers"].get("x-peer-id", "someone") if context.call_context else "someone"
+ said = get_message_text(context.message) if context.message else ""
+ await event_queue.enqueue_event(new_text_message(f"{caller} said: {said}", role=Role.ROLE_AGENT, context_id=context.context_id))
+
+ async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
+ pass
+
+
+def a2a_app(agent_url: str) -> Starlette:
+ """The A2A SDK's server, as its samples build it. The card names the agent
+ as the mesh reaches it: http://mesh/sam/<peer-id>/a2a/agent."""
+ card = AgentCard(
+ name="Echo agent",
+ description="Answers every message with what it said and who sent it.",
+ version="1.0.0",
+ default_input_modes=["text/plain"],
+ default_output_modes=["text/plain"],
+ capabilities=AgentCapabilities(streaming=True),
+ supported_interfaces=[AgentInterface(protocol_binding="JSONRPC", url=agent_url, protocol_version="1.0")],
+ skills=[AgentSkill(id="echo", name="Echo", description="Repeats the message.", tags=["echo"], examples=["hello"])],
+ )
+ handler = DefaultRequestHandler(agent_executor=EchoExecutor(), task_store=InMemoryTaskStore(), agent_card=card)
+ return Starlette(routes=[*create_agent_card_routes(card), *create_jsonrpc_routes(handler, "/")])
+
+
+def serve_locally(app: Starlette) -> str:
+ """Runs uvicorn on a free loopback port in a thread and returns its URL.
+ The A2A SDK runs on asyncio, the mesh SDK on trio; a thread keeps them apart."""
+ with socket.socket() as probe:
+ probe.bind(("127.0.0.1", 0))
+ port = probe.getsockname()[1]
+ server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning"))
+ threading.Thread(target=server.run, daemon=True).start()
+ return f"http://127.0.0.1:{port}"
+
+
+async def main() -> None:
+ backend_url = serve_locally(a2a_app(MeshSession.mesh_url(mesh.identity.peer_id, "a2a://agent")))
+ async with mesh.join() as session:
+ target = await session.accept_a2a(backend_url)
+ print(f"accepting {target} as {session.peer_id}", flush=True)
+ print(f"agent card at {session.agent_url}/.well-known/agent-card.json", flush=True)
+ await trio.sleep_forever()
+
+
+trio.run(main)
+```
+<!-- /embed -->
+
+```bash
+node a2a-agent.js
+# or
+python a2a_agent.py
+```
+
+```text
+accepting a2a://agent as 12D3KooWQmB5…
+agent card at http://mesh/sam/12D3KooWQmB5…/a2a/agent/.well-known/agent-card.json
+```
+
+The caller, with the A2A SDK's client: it fetches the card, sends one
+message and prints the answer.
+
+JavaScript, `a2a-call.js`:
+
+<!-- embed: sdk/js/examples/a2a-call.ts -->
+```ts
+// Talks to an agent on the mesh with the A2A SDK's client. The mesh SDK hands
+// the A2A client a `fetch` bound to the mesh; the client fetches the agent
+// card and sends messages as it would to any A2A server, and every request
+// travels to the peer through a router with this member's credential.
+//
+// node a2a-call.js 12D3KooW... "hello"
+//
+// SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
+// SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or
+// SAM_JWT_PATH (a workload identity token your platform issues, such as a
+// Kubernetes projected service account token), and keeps the identity and
+// credential in SAM_STATE_DIR; later runs resume from there without it.
+import { homedir } from "node:os";
+import { randomUUID } from "node:crypto";
+import { Message, Role, type SendMessageRequest } from "@a2a-js/sdk";
+import { ClientFactory, DefaultAgentCardResolver, JsonRpcTransportFactory } from "@a2a-js/sdk/client";
+import { AgentMesh, MeshSession } from "@sam-mesh/sdk";
+
+const [peerId, text = "hello"] = process.argv.slice(2);
+if (peerId === undefined) {
+ throw new Error("usage: a2a-call.js <peer-id> [text]");
+}
+
+const mesh = await AgentMesh.enroll({
+ controlPlaneUrl: process.env.SAM_CONTROL_PLANE_URL ?? "https://mesh.example.com",
+ bootstrapTokenPath: process.env.SAM_BOOTSTRAP_TOKEN_PATH,
+ jwtPath: process.env.SAM_JWT_PATH,
+ stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/a2a-caller`,
+ // A plaintext http:// control plane is otherwise accepted only on loopback.
+ allowInsecure: process.env.SAM_INSECURE_CONTROL_PLANE === "true",
+});
+const session = await mesh.join();
+console.log(`on the mesh as ${session.peerId}`);
+
+// The agent's URL on the mesh, and a fetch that carries requests to it.
+const agentURL = MeshSession.meshURL(peerId, "a2a://agent");
+const fetchImpl = session.fetch();
+const factory = new ClientFactory({
+ transports: [new JsonRpcTransportFactory({ fetchImpl })],
+ cardResolver: new DefaultAgentCardResolver({ fetchImpl }),
+});
+// The card lives under the agent's URL; the trailing slash keeps the last segment when the resolver appends the well-known path.
+const client = await factory.createFromUrl(agentURL + "/");
+const card = await client.getAgentCard();
+console.log(`agent: ${card.name}, ${card.description}`);
+
+const request: SendMessageRequest = {
+ tenant: "",
+ message: Message.fromJSON({ messageId: randomUUID(), role: Role[Role.ROLE_USER], parts: [{ text }] }),
+ configuration: undefined,
+ metadata: undefined,
+};
+const answer = await client.sendMessage(request);
+const parts = "parts" in answer ? answer.parts : (answer.status?.message?.parts ?? []);
+console.log(parts.map((p) => (p.content?.$case === "text" ? p.content.value : "")).join(""));
+
+await session.close();
+```
+<!-- /embed -->
+
+Python, `a2a_call.py`:
+
+<!-- embed: sdk/python/examples/a2a_call.py -->
+```python
+"""Talks to an agent on the mesh with the A2A SDK's client. The mesh SDK is an
+httpx transport; the A2A client fetches the agent card and sends messages as
+it would to any A2A server, and every request travels to the peer through a
+router with this member's credential.
+
+ python a2a_call.py 12D3KooW... "hello"
+
+SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
+SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or SAM_JWT_PATH
+(a workload identity token your platform issues, such as a Kubernetes
+projected service account token), and keeps the identity and credential in
+SAM_STATE_DIR; later runs resume from there without it.
+"""
+
+import os
+import sys
+
+import httpx
+import trio
+from a2a.client import A2ACardResolver, ClientConfig, create_client
+from a2a.helpers import get_message_text, new_text_message
+from a2a.types import Role, SendMessageRequest
+from agent_mesh import AgentMesh, MeshSession, MeshTransport
+
+if len(sys.argv) < 2:
+ raise SystemExit("usage: a2a_call.py <peer-id> [text]")
+peer_id = sys.argv[1]
+text = sys.argv[2] if len(sys.argv) > 2 else "hello"
+
+mesh = AgentMesh.enroll(
+ os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
+ bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
+ jwt_path=os.environ.get("SAM_JWT_PATH"),
+ state_dir=os.environ.get("SAM_STATE_DIR", "~/.config/sam-mesh/a2a-caller"),
+ # A plaintext http:// control plane is otherwise accepted only on loopback.
+ allow_insecure=os.environ.get("SAM_INSECURE_CONTROL_PLANE") == "true",
+)
+
+
+async def main() -> None:
+ async with mesh.join() as session:
+ print(f"on the mesh as {session.peer_id}")
+
+ # The agent's URL on the mesh, and an httpx client that carries requests to it.
+ agent_url = MeshSession.mesh_url(peer_id, "a2a://agent")
+ async with httpx.AsyncClient(transport=MeshTransport(session), timeout=60) as http:
+ card = await A2ACardResolver(http, agent_url).get_agent_card()
+ print(f"agent: {card.name}, {card.description}")
+
+ client = await create_client(card, ClientConfig(httpx_client=http, streaming=False))
+ request = SendMessageRequest(message=new_text_message(text, role=Role.ROLE_USER))
+ async for response in client.send_message(request):
+ if response.HasField("message"):
+ print(get_message_text(response.message))
+ elif response.HasField("task") and response.task.status.HasField("message"):
+ print(get_message_text(response.task.status.message))
+ await client.close()
+
+
+trio.run(main)
+```
+<!-- /embed -->
+
+In a second terminal, call the agent from the other language:
+
+```bash
+python a2a_call.py 12D3KooWQmB5… "hello from python"
+```
+
+```text
+on the mesh as 12D3KooWHZ2M…
+agent: Echo agent, Answers every message with what it said and who sent it.
+12D3KooWHZ2M… said: hello from python
+```
+
+The A2A client did what it does against any A2A server; the mesh carried
+each request to the peer through a router, with the caller's credential,
+and the agent's server received it with the caller already verified.
+`message/stream` works the same way: response bodies stream through both
+SDKs.
+
+Treat what another agent sends as input from outside your control. The
+mesh verifies the peer's identity and credential; it does not inspect the
+content the peer sends. An agent card's `description` or a skill's text
+pasted into a prompt is a prompt injection path like any other.
+
+The public testnets run these programs: an agent written with each SDK
+and, every fifteen minutes, a caller written with the other that sends it a
+message and checks the answer names the caller.
+
## What happened
`enroll` sent the token and the program's public key to the control plane
@@ -502,19 +909,9 @@ or a pattern) and the members it may reach; see
on the mesh; `discover("mcp://everything")` those of one service.
- **A member's own catalog.** `listTools(peer, "")` returns a `sam-node`'s
`list_local_services` tool.
-- **An agent written with an A2A SDK.** Run its server on a local port and
- pass the URL: `acceptA2A({ url: "http://127.0.0.1:9999" })`,
- `accept_a2a("http://127.0.0.1:9999")`. In JavaScript an Express app with
- the A2A SDK's handlers can also run in the process:
- `acceptA2A({ listener: app })`. The agent's name defaults to `agent`;
- `name` picks another, and callers use `a2a://<name>`.
-- **Calling an agent with an A2A SDK client.** The mesh is a transport for
- HTTP clients. A peer's service has the URL
- `http://mesh/sam/<peer-id>/a2a/agent` (`MeshSession.meshURL`,
- `MeshSession.mesh_url`); the A2A JavaScript client takes
- `fetchImpl: session.fetch()`, the Python one an
- `httpx.AsyncClient(transport=MeshTransport(session))`. Response bodies
- stream, so `message/stream` works.
+- **Another agent name.** `acceptA2A({ name: "reviewer", ... })` and
+ `accept_a2a(target, name="reviewer")` answer as `a2a://reviewer`; callers
+ use that target and the matching mesh URL.
- **Reading the policy.** `session.policyRules` (`session.policy_rules`)
holds the Datalog the session enforces, for logging or tests.