Skip to content

Agent Mesh

sdk: agents written with the official A2A SDKs, JavaScript to Python

Antonio Ojea363f9c901ec1
diff --git a/.github/workflows/sdk.yml b/.github/workflows/sdk.yml
index 0e9cebcb..35afc65d 100644
--- a/.github/workflows/sdk.yml
+++ b/.github/workflows/sdk.yml
@@ -99,8 +99,13 @@ jobs:
docker build -f Dockerfile.sam-sdk-js -t sam-sdk-js:ci .
docker build -f Dockerfile.sam-sdk-python -t sam-sdk-python:ci .
# Without a token every example stops at enrollment with this
- # message: the default command (the agent) and the caller both.
+ # message: the default command (the agent), the caller, and the
+ # two written with the official A2A SDK.
docker run --rm sam-sdk-js:ci 2>&1 | grep -q 'exactly one of'
docker run --rm sam-sdk-python:ci 2>&1 | grep -q 'exactly one of'
docker run --rm sam-sdk-js:ci build/examples/call.js 2>&1 | grep -q 'exactly one of'
docker run --rm sam-sdk-python:ci examples/call.py 2>&1 | grep -q 'exactly one of'
+ docker run --rm sam-sdk-js:ci build/examples/a2a-agent.js 2>&1 | grep -q 'exactly one of'
+ docker run --rm sam-sdk-python:ci examples/a2a_agent.py 2>&1 | grep -q 'exactly one of'
+ docker run --rm sam-sdk-js:ci build/examples/a2a-call.js peer 2>&1 | grep -q 'exactly one of'
+ docker run --rm sam-sdk-python:ci examples/a2a_call.py peer 2>&1 | grep -q 'exactly one of'
diff --git a/Dockerfile.sam-sdk-js b/Dockerfile.sam-sdk-js
index b2dfe3ba..5ebc00d6 100644
--- a/Dockerfile.sam-sdk-js
+++ b/Dockerfile.sam-sdk-js
@@ -1,10 +1,12 @@
# The JavaScript SDK with its example programs, as the testnet canaries run
# them: `node build/examples/agent.js [url]` joins as an agent that accepts
# A2A requests, `node build/examples/call.js [peer] <service> <tool|path>
-# [args]` calls a service or an agent. The examples import "@sam-mesh/sdk"
+# [args]` calls a service or an agent, and `a2a-agent.js` and `a2a-call.js`
+# do the same with the official A2A SDK. The examples import "@sam-mesh/sdk"
# by name and resolve it through the package's own exports, so the image
# keeps the package layout: package.json, dist/, build/examples/ and the
-# production node_modules/.
+# production node_modules/ plus the two packages the A2A examples need,
+# which are development dependencies of the SDK, not dependencies.
# Stage 1: Build
FROM node:22-bookworm-slim@sha256:43ac6c60b8f89723f746e8a92ce91abd5017e627ce1ddfe4238355d3a30b772c AS builder
@@ -12,7 +14,8 @@ WORKDIR /src
COPY sdk/js/package.json sdk/js/package-lock.json sdk/js/.npmrc ./
RUN npm ci --no-fund --no-audit
COPY sdk/js/ ./
-RUN npm run build && npm run examples && npm prune --omit=dev --no-fund --no-audit
+RUN npm run build && npm run examples && npm prune --omit=dev --no-fund --no-audit \
+ && npm install --no-save --no-fund --no-audit @a2a-js/sdk express
# Stage 2: Final
FROM node:22-bookworm-slim@sha256:43ac6c60b8f89723f746e8a92ce91abd5017e627ce1ddfe4238355d3a30b772c
diff --git a/Dockerfile.sam-sdk-python b/Dockerfile.sam-sdk-python
index 8376440f..f29f0b02 100644
--- a/Dockerfile.sam-sdk-python
+++ b/Dockerfile.sam-sdk-python
@@ -1,7 +1,9 @@
# The Python SDK with its example programs, as the testnet canaries run them:
# `python examples/agent.py [url]` joins as an agent that accepts A2A
# requests, `python examples/call.py [peer] <service> <tool|path> [args]`
-# calls a service or an agent. fastecdsa, a py-libp2p dependency, builds from
+# calls a service or an agent, and `examples/a2a_agent.py` and
+# `examples/a2a_call.py` do the same with the official A2A SDK, which the
+# `examples` extra installs. fastecdsa, a py-libp2p dependency, builds from
# source against GMP, so the build stage carries a compiler and the final
# image only libgmp10.
@@ -9,7 +11,7 @@
FROM python:3.12-slim-bookworm@sha256:392307d22300de8b5986851a12d9176dfc0fc073e65bf6523ebd7dcbeb23564e AS builder
RUN apt-get update && apt-get install -y --no-install-recommends gcc libgmp-dev python3-dev && rm -rf /var/lib/apt/lists/*
COPY sdk/python /src
-RUN python -m venv /opt/venv && /opt/venv/bin/pip install --no-cache-dir /src
+RUN python -m venv /opt/venv && /opt/venv/bin/pip install --no-cache-dir '/src[examples]'
# Stage 2: Final
FROM python:3.12-slim-bookworm@sha256:392307d22300de8b5986851a12d9176dfc0fc073e65bf6523ebd7dcbeb23564e
diff --git a/Makefile b/Makefile
index efac5c99..af562e3c 100644
--- a/Makefile
+++ b/Makefile
@@ -170,7 +170,7 @@ sdk-js:
sdk-python:
python3 -m venv sdk/python/.venv
- ./sdk/python/.venv/bin/pip install -q -e './sdk/python[test]'
+ ./sdk/python/.venv/bin/pip install -q -e './sdk/python[test,examples]'
./sdk/python/.venv/bin/python -m pytest -q sdk/python/tests
sdk-proto:
diff --git a/sdk/js/examples/a2a-agent.ts b/sdk/js/examples/a2a-agent.ts
new file mode 100644
index 00000000..ed31ebc7
--- /dev/null
+++ b/sdk/js/examples/a2a-agent.ts
@@ -0,0 +1,90 @@
+// 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);
diff --git a/sdk/js/examples/a2a-call.ts b/sdk/js/examples/a2a-call.ts
new file mode 100644
index 00000000..2b0eb4b1
--- /dev/null
+++ b/sdk/js/examples/a2a-call.ts
@@ -0,0 +1,57 @@
+// 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();
diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.json
index 9bd3b5c2..9147e19d 100644
--- a/sdk/js/package-lock.json
+++ b/sdk/js/package-lock.json
@@ -30,14 +30,45 @@
"zod": "^4.6.5"
},
"devDependencies": {
+ "@a2a-js/sdk": "^1.2.1",
"@bufbuild/protoc-gen-es": "^2.15.0",
+ "@types/express": "^5.0.6",
"@types/node": "^26.6.1",
+ "express": "^5.2.1",
"typescript": "^7.0.2"
},
"engines": {
"node": ">=22.18"
}
},
+ "node_modules/@a2a-js/sdk": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@a2a-js/sdk/-/sdk-1.2.1.tgz",
+ "integrity": "sha512-czCgk8Hw5TKgL0y9peDcxhHV3gGlVE8cHwPMhDOKoGM1QMsDCP1G8Fma6Snnpnr7Ci/U/1f0bFHnCyd7YnmioA==",
+ "dev": true,
+ "dependencies": {
+ "jose": "^6.2.3"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "peerDependencies": {
+ "@bufbuild/protobuf": "^2.10.2",
+ "@grpc/grpc-js": "^1.11.0",
+ "express": "^4.21.2 || ^5.1.0"
+ },
+ "peerDependenciesMeta": {
+ "@bufbuild/protobuf": {
+ "optional": true
+ },
+ "@grpc/grpc-js": {
+ "optional": true
+ },
+ "express": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@biscuit-auth/biscuit-wasm": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/@biscuit-auth/biscuit-wasm/-/biscuit-wasm-0.6.0.tgz",
@@ -987,6 +1018,54 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/@types/body-parser": {
+ "version": "1.19.6",
+ "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
+ "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",
+ "dev": true,
+ "dependencies": {
+ "@types/connect": "*",
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/connect": {
+ "version": "3.4.38",
+ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
+ "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/express": {
+ "version": "5.0.6",
+ "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
+ "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",
+ "dev": true,
+ "dependencies": {
+ "@types/body-parser": "*",
+ "@types/express-serve-static-core": "^5.0.0",
+ "@types/serve-static": "^2"
+ }
+ },
+ "node_modules/@types/express-serve-static-core": {
+ "version": "5.1.3",
+ "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.3.tgz",
+ "integrity": "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*",
+ "@types/qs": "*",
+ "@types/range-parser": "*",
+ "@types/send": "*"
+ }
+ },
+ "node_modules/@types/http-errors": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",
+ "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",
+ "dev": true
+ },
"node_modules/@types/node": {
"version": "26.6.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.1.tgz",
@@ -997,6 +1076,37 @@
"undici-types": "~8.9.0"
}
},
+ "node_modules/@types/qs": {
+ "version": "6.15.1",
+ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",
+ "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==",
+ "dev": true
+ },
+ "node_modules/@types/range-parser": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",
+ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
+ "dev": true
+ },
+ "node_modules/@types/send": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
+ "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/serve-static": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",
+ "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",
+ "dev": true,
+ "dependencies": {
+ "@types/http-errors": "*",
+ "@types/node": "*"
+ }
+ },
"node_modules/@typescript/typescript-aix-ppc64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
@@ -1756,7 +1866,6 @@
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
- "license": "MIT",
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.1",
diff --git a/sdk/js/package.json b/sdk/js/package.json
index 46d26a2c..144056fe 100644
--- a/sdk/js/package.json
+++ b/sdk/js/package.json
@@ -55,8 +55,11 @@
"zod": "^4.6.5"
},
"devDependencies": {
+ "@a2a-js/sdk": "^1.2.1",
"@bufbuild/protoc-gen-es": "^2.15.0",
+ "@types/express": "^5.0.6",
"@types/node": "^26.6.1",
+ "express": "^5.2.1",
"typescript": "^7.0.2"
}
}
diff --git a/sdk/python/examples/a2a_agent.py b/sdk/python/examples/a2a_agent.py
new file mode 100644
index 00000000..56ee9431
--- /dev/null
+++ b/sdk/python/examples/a2a_agent.py
@@ -0,0 +1,92 @@
+"""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)
diff --git a/sdk/python/examples/a2a_call.py b/sdk/python/examples/a2a_call.py
new file mode 100644
index 00000000..95f460f4
--- /dev/null
+++ b/sdk/python/examples/a2a_call.py
@@ -0,0 +1,60 @@
+"""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)
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index 9f51ddb0..9492ff74 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -28,6 +28,12 @@ dependencies = [
test = [
"pytest>=8",
]
+# What examples/a2a_agent.py and examples/a2a_call.py need: the official A2A
+# SDK and a server to run its app on. Not a dependency of the package.
+examples = [
+ "a2a-sdk[http-server]>=1.1",
+ "uvicorn>=0.30",
+]
[project.urls]
Homepage = "https://github.com/google/sam"
diff --git a/tests/integration/sdk_a2a_test.go b/tests/integration/sdk_a2a_test.go
new file mode 100644
index 00000000..bf28eac9
--- /dev/null
+++ b/tests/integration/sdk_a2a_test.go
@@ -0,0 +1,152 @@
+// 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 integration_test
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/sam/api"
+)
+
+// TestNativeSDKA2A runs the examples written with the official A2A SDKs
+// (sdk/js/examples/a2a-agent.ts, a2a-call.ts; sdk/python/examples/a2a_agent.py,
+// a2a_call.py) against a real mesh: an agent per language, each an A2A
+// server the mesh SDK accepts requests for, and a caller per language that
+// reaches the other language's agent by peer ID with the A2A SDK's client
+// over the mesh SDK's transport. The caller fetches the agent card, sends a
+// message and gets an answer that names the caller the agent's server saw
+// as the verified peer. A sam-node's egress proxy fetches the same card.
+// A language whose toolchain or A2A SDK is missing is skipped.
+func TestNativeSDKA2A(t *testing.T) {
+ mesh := startSDKMesh(t)
+
+ var launchers []sdkExampleLauncher
+ var cmds []*exec.Cmd
+ for _, l := range sdkExampleLaunchers {
+ cmd, skip := l.cmd(context.Background(), mesh.root, "a2a-agent")
+ if skip == "" {
+ skip = a2aSDKMissing(mesh.root, l.name)
+ }
+ if skip != "" {
+ t.Logf("%s SDK skipped: %s", l.name, skip)
+ continue
+ }
+ launchers = append(launchers, l)
+ cmds = append(cmds, cmd)
+ }
+ if len(launchers) == 0 {
+ t.Skip("no SDK toolchain with the A2A SDK available; see sdk/README.md")
+ }
+ agents := make([]*sdkExampleAgent, len(launchers))
+ errs := make([]error, len(launchers))
+ var wg sync.WaitGroup
+ for i := range launchers {
+ jwtPath := filepath.Join(t.TempDir(), "sam-token")
+ jwt := mesh.mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}})
+ if err := os.WriteFile(jwtPath, []byte(jwt+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ cmds[i].Env = append(os.Environ(),
+ "SAM_CONTROL_PLANE_URL="+mesh.baseURL,
+ "SAM_JWT_PATH="+jwtPath,
+ "SAM_STATE_DIR="+filepath.Join(t.TempDir(), "state"),
+ )
+ cmds[i].Dir = mesh.root
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ agents[i], errs[i] = startExampleAgent(t, launchers[i].name, cmds[i])
+ }(i)
+ }
+ wg.Wait()
+ for _, err := range errs {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, a := range agents {
+ waitForPeerOnRouter(t, mesh.cpPort, mesh.adminToken, a.peerID, 5*time.Second)
+ }
+
+ peerAgent := func(name string) *sdkExampleAgent {
+ for _, a := range agents {
+ if a.name != name {
+ return a
+ }
+ }
+ return agents[0]
+ }
+
+ for _, l := range launchers {
+ l := l
+ target := peerAgent(l.name)
+ t.Run(l.name+"-calls-"+target.name, func(t *testing.T) {
+ t.Parallel()
+ tokenPath := filepath.Join(t.TempDir(), "join-token")
+ if err := os.WriteFile(tokenPath, []byte(mintBootstrapToken(t, mesh.baseURL, mesh.adminToken)+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ env := []string{"SAM_CONTROL_PLANE_URL=" + mesh.baseURL, "SAM_STATE_DIR=" + filepath.Join(t.TempDir(), "state"), "SAM_BOOTSTRAP_TOKEN_PATH=" + tokenPath}
+
+ out := runExample(t, mesh, l, env, "a2a-call", target.peerID, "hello from "+l.name)
+ caller := expectLine(t, out, "on the mesh as ")
+ expectLine(t, out, "agent: Echo agent, ")
+ // The agent's server saw the verified caller, never a name the
+ // caller chose.
+ if want := caller + " said: hello from " + l.name; !strings.Contains(out, want) {
+ t.Fatalf("%s calling the %s agent: want %q in\n%s", l.name, target.name, want, out)
+ }
+ })
+ }
+
+ // A sam-node reaches the same agent card through its egress proxy, and
+ // rewrites the card's URL so an A2A client behind the node can use it.
+ for _, a := range agents {
+ status, body := egressGet(t, mesh.nodeAPI, "node-token", "/sam/"+a.peerID+"/a2a/agent/.well-known/agent-card.json")
+ if status != 200 || !strings.Contains(body, `"Echo agent"`) {
+ t.Fatalf("agent card of the %s agent through the node: %d %s", a.name, status, body)
+ }
+ if !strings.Contains(body, "/sam/"+a.peerID+"/a2a/agent") {
+ t.Fatalf("agent card of the %s agent through the node does not name the mesh path: %s", a.name, body)
+ }
+ }
+}
+
+// a2aSDKMissing reports why a language's A2A example cannot run: the A2A
+// SDK is a dependency of the examples, not of the packages.
+func a2aSDKMissing(root, lang string) string {
+ switch lang {
+ case "js":
+ if _, err := os.Stat(filepath.Join(root, "sdk", "js", "node_modules", "@a2a-js", "sdk")); err != nil {
+ return "@a2a-js/sdk is not installed (cd sdk/js && npm ci)"
+ }
+ case "python":
+ python := filepath.Join(root, "sdk", "python", ".venv", "bin", "python")
+ if _, err := os.Stat(python); err != nil {
+ python = "python3"
+ }
+ if err := exec.Command(python, "-c", "import a2a.client, uvicorn").Run(); err != nil {
+ return "a2a-sdk is not importable (pip install -e 'sdk/python[examples]')"
+ }
+ }
+ return ""
+}
diff --git a/tests/integration/sdk_examples_test.go b/tests/integration/sdk_examples_test.go
index fbdda17d..e28d4f2f 100644
--- a/tests/integration/sdk_examples_test.go
+++ b/tests/integration/sdk_examples_test.go
@@ -66,7 +66,8 @@ var sdkExampleLaunchers = []sdkExampleLauncher{
if err := exec.Command(python, "-c", "import agent_mesh.session").Run(); err != nil {
return nil, "agent_mesh is not importable with libp2p (pip install -e sdk/python)"
}
- entry := filepath.Join(root, "sdk", "python", "examples", example+".py")
+ // Python names its files with underscores: a2a-agent is a2a_agent.py.
+ entry := filepath.Join(root, "sdk", "python", "examples", strings.ReplaceAll(example, "-", "_")+".py")
return exec.CommandContext(ctx, python, append([]string{entry}, args...)...), ""
},
},
@@ -164,7 +165,7 @@ func TestNativeSDKExamples(t *testing.T) {
// The first run spends the token: the sam-node's calc over MCP,
// found by name.
- out := runExample(t, mesh, l, withToken, "mcp://calc", "add", `{"a": 1, "b": 2}`)
+ out := runExample(t, mesh, l, withToken, "call", "mcp://calc", "add", `{"a": 1, "b": 2}`)
caller := expectLine(t, out, "on the mesh as ")
expectLine(t, out, "mcp://calc is served by "+mesh.samNode.peerID.String())
expectLine(t, out, "tools: add")
@@ -177,7 +178,7 @@ func TestNativeSDKExamples(t *testing.T) {
if err := os.Remove(tokenPath); err != nil {
t.Fatal(err)
}
- out = runExample(t, mesh, l, withoutToken, target.peerID, "a2a://agent", "/card")
+ out = runExample(t, mesh, l, withoutToken, "call", target.peerID, "a2a://agent", "/card")
if got := expectLine(t, out, "on the mesh as "); got != caller {
t.Fatalf("second run joined as %s, want the identity of the first run %s", got, caller)
}
@@ -200,7 +201,7 @@ func TestNativeSDKExamples(t *testing.T) {
if other.name == l.name {
continue
}
- out := runExample(t, mesh, other, withoutToken, target.peerID, "a2a://agent", "/card")
+ out := runExample(t, mesh, other, withoutToken, "call", target.peerID, "a2a://agent", "/card")
if got := expectLine(t, out, "on the mesh as "); got != caller {
t.Fatalf("%s resumed %s's state directory as %s, want %s", other.name, l.name, got, caller)
}
@@ -303,12 +304,12 @@ func startExampleAgent(t *testing.T, name string, cmd *exec.Cmd) (*sdkExampleAge
}
}
-// runExample runs a call example to completion and returns its stdout.
-func runExample(t *testing.T, mesh *sdkMesh, l sdkExampleLauncher, env []string, args ...string) string {
+// runExample runs an example that exits on its own to completion and returns its stdout.
+func runExample(t *testing.T, mesh *sdkMesh, l sdkExampleLauncher, env []string, example string, args ...string) string {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
- cmd, skip := l.cmd(ctx, mesh.root, "call", args...)
+ cmd, skip := l.cmd(ctx, mesh.root, example, args...)
if skip != "" {
t.Fatalf("%s: %s", l.name, skip)
}
@@ -318,7 +319,7 @@ func runExample(t *testing.T, mesh *sdkMesh, l sdkExampleLauncher, env []string,
cmd.Stderr = stderr
stdout, err := cmd.Output()
if err != nil {
- t.Fatalf("%s call %v failed: %v\nstdout:\n%s\nstderr:\n%s", l.name, args, err, stdout, stderr.String())
+ t.Fatalf("%s %s %v failed: %v\nstdout:\n%s\nstderr:\n%s", l.name, example, args, err, stdout, stderr.String())
}
return string(stdout)
}