Skip to content

Agent Mesh

sdk: the documented programs are the tested programs

Antonio Ojeaeec5f968afd0
diff --git a/.github/workflows/sdk.yml b/.github/workflows/sdk.yml
index 8129ad06..21044d87 100644
--- a/.github/workflows/sdk.yml
+++ b/.github/workflows/sdk.yml
@@ -12,9 +12,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-# Native SDKs (sdk/): unit tests per language, then both SDKs enrolling
-# against a real control plane through tests/integration/sdk_enroll_test.go.
-# api/sam.proto is a trigger because the SDKs ship bindings generated from it.
+# Native SDKs (sdk/): unit tests per language, then both SDKs on a mesh with
+# a real control plane, router and sam-node through tests/integration, and
+# the example programs the docs embed run the same way. api/sam.proto is a
+# trigger because the SDKs ship bindings generated from it; the docs are
+# because they embed the examples.
name: SDK
on:
@@ -24,6 +26,9 @@ on:
- 'sdk/**'
- 'api/sam.proto'
- 'hack/gen-sdk-proto.sh'
+ - 'hack/gen-sdk-docs/**'
+ - 'hack/verify-sdk-generated.sh'
+ - 'site/content/docs/guides/native-sdks.md'
- 'tests/integration/sdk_*_test.go'
- '.github/workflows/sdk.yml'
pull_request:
@@ -32,6 +37,9 @@ on:
- 'sdk/**'
- 'api/sam.proto'
- 'hack/gen-sdk-proto.sh'
+ - 'hack/gen-sdk-docs/**'
+ - 'hack/verify-sdk-generated.sh'
+ - 'site/content/docs/guides/native-sdks.md'
- 'tests/integration/sdk_*_test.go'
- '.github/workflows/sdk.yml'
@@ -75,8 +83,8 @@ jobs:
- name: Python SDK
run: make sdk-python
- - name: Generated bindings are current
+ - name: Generated bindings, embedded examples and lockfile are current
run: ./hack/verify-sdk-generated.sh
- - name: Both SDKs on a mesh with a real control plane, router and sam-node
- run: go test ./tests/integration -run TestNativeSDKs -count=1 -v
+ - name: Both SDKs and the documented examples on a mesh with a real control plane, router and sam-node
+ run: go test ./tests/integration -run TestNativeSDK -count=1 -v
diff --git a/Makefile b/Makefile
index b6c5c78c..efac5c99 100644
--- a/Makefile
+++ b/Makefile
@@ -161,10 +161,12 @@ e2e-test: build docker-build
# Native SDKs under sdk/. sdk-js and sdk-python run each SDK's own unit
# tests and leave it installed, which is what TestNativeSDKs needs to run
-# both against a real control plane instead of skipping.
-.PHONY: sdk-js sdk-python sdk-proto sdk-test
+# both against a real control plane instead of skipping. sdk-js also
+# compiles the example programs the docs embed; TestNativeSDKExamples runs
+# them.
+.PHONY: sdk-js sdk-python sdk-proto sdk-docs sdk-test
sdk-js:
- cd sdk/js && npm ci --no-fund --no-audit && npm test && npm run build
+ cd sdk/js && npm ci --no-fund --no-audit && npm test && npm run build && npm run examples
sdk-python:
python3 -m venv sdk/python/.venv
@@ -174,8 +176,11 @@ sdk-python:
sdk-proto:
./hack/gen-sdk-proto.sh
+sdk-docs:
+ go run ./hack/gen-sdk-docs sdk site/content/docs
+
sdk-test: sdk-js sdk-python
- go test ./tests/integration -run TestNativeSDKs -count=1 -v
+ go test ./tests/integration -run TestNativeSDK -count=1 -v
.PHONY: ui-test
ui-test: build
diff --git a/hack/gen-sdk-docs/main.go b/hack/gen-sdk-docs/main.go
new file mode 100644
index 00000000..be6cbfd5
--- /dev/null
+++ b/hack/gen-sdk-docs/main.go
@@ -0,0 +1,161 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Command gen-sdk-docs copies the SDK example programs into the Markdown
+// that shows them, so what the READMEs and the guide print is the file CI
+// compiles and runs against a mesh. A Markdown file marks where a file goes
+// with a path relative to the repository root:
+//
+// <!-- embed: sdk/js/examples/call.ts -->
+// ```ts
+// (replaced with the file)
+// ```
+// <!-- /embed -->
+//
+// Usage: gen-sdk-docs [-check] <markdown file or directory>...
+//
+// Directories are walked for .md files. With -check nothing is written and
+// the exit status is 1 when any file is stale; hack/verify-sdk-generated.sh
+// runs it that way.
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+var embedBlock = regexp.MustCompile("(?s)<!-- embed: (\\S+) -->\n.*?<!-- /embed -->")
+
+var fenceLanguages = map[string]string{
+ ".ts": "ts",
+ ".js": "js",
+ ".py": "python",
+ ".go": "go",
+ ".sh": "bash",
+ ".yaml": "yaml",
+ ".json": "json",
+}
+
+func main() {
+ check := false
+ var paths []string
+ for _, arg := range os.Args[1:] {
+ if arg == "-check" {
+ check = true
+ continue
+ }
+ paths = append(paths, arg)
+ }
+ if len(paths) == 0 {
+ fmt.Fprintln(os.Stderr, "usage: gen-sdk-docs [-check] <markdown file or directory>...")
+ os.Exit(2)
+ }
+ files, err := markdownFiles(paths)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ stale := 0
+ for _, file := range files {
+ changed, err := render(file, !check)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "%s: %v\n", file, err)
+ os.Exit(1)
+ }
+ if changed {
+ stale++
+ if check {
+ fmt.Fprintf(os.Stderr, "%s: embedded examples are stale\n", file)
+ } else {
+ fmt.Printf("%s: updated\n", file)
+ }
+ }
+ }
+ if check && stale > 0 {
+ fmt.Fprintln(os.Stderr, "Run: go run ./hack/gen-sdk-docs sdk site/content/docs")
+ os.Exit(1)
+ }
+}
+
+func markdownFiles(paths []string) ([]string, error) {
+ var files []string
+ for _, p := range paths {
+ info, err := os.Stat(p)
+ if err != nil {
+ return nil, err
+ }
+ if !info.IsDir() {
+ files = append(files, p)
+ continue
+ }
+ err = filepath.WalkDir(p, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() && (d.Name() == "node_modules" || d.Name() == ".venv" || d.Name() == "dist" || d.Name() == "build") {
+ return filepath.SkipDir
+ }
+ if !d.IsDir() && strings.HasSuffix(path, ".md") {
+ files = append(files, path)
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ }
+ return files, nil
+}
+
+// render rewrites every embed block in a Markdown file from the file it
+// names and reports whether the result differs from what is on disk.
+func render(file string, write bool) (bool, error) {
+ before, err := os.ReadFile(file)
+ if err != nil {
+ return false, err
+ }
+ var renderErr error
+ after := embedBlock.ReplaceAllFunc(before, func(block []byte) []byte {
+ source := string(embedBlock.FindSubmatch(block)[1])
+ content, err := os.ReadFile(source)
+ if err != nil {
+ renderErr = err
+ return block
+ }
+ language := fenceLanguages[filepath.Ext(source)]
+ var out bytes.Buffer
+ fmt.Fprintf(&out, "<!-- embed: %s -->\n```%s\n", source, language)
+ out.Write(content)
+ if !bytes.HasSuffix(content, []byte("\n")) {
+ out.WriteByte('\n')
+ }
+ out.WriteString("```\n<!-- /embed -->")
+ return out.Bytes()
+ })
+ if renderErr != nil {
+ return false, renderErr
+ }
+ if bytes.Equal(before, after) {
+ return false, nil
+ }
+ if write {
+ return true, os.WriteFile(file, after, 0o644)
+ }
+ return true, nil
+}
diff --git a/hack/verify-sdk-generated.sh b/hack/verify-sdk-generated.sh
index 1c469ad7..d744a5b0 100755
--- a/hack/verify-sdk-generated.sh
+++ b/hack/verify-sdk-generated.sh
@@ -14,8 +14,10 @@
# limitations under the License.
# Fails when the protobuf bindings or the baseline Datalog artifact the SDKs
-# ship are stale relative to api/. Regenerates in place, so run it on a
-# clean checkout.
+# ship are stale relative to api/, when the example programs embedded in the
+# SDK READMEs and the Native SDKs guide differ from the files CI runs, or
+# when the JavaScript lockfile resolves packages anywhere but the public
+# registry. Regenerates in place, so run it on a clean checkout.
set -o errexit
set -o nounset
@@ -34,3 +36,14 @@ if ! git diff --exit-code -- "${GENERATED[@]}"; then
exit 1
fi
echo "SDK generated files are up to date."
+
+go run ./hack/gen-sdk-docs -check sdk site/content/docs
+echo "SDK examples embedded in the docs are up to date."
+
+if grep -E '"resolved": "https?://' sdk/js/package-lock.json | grep -qv '"resolved": "https://registry.npmjs.org/'; then
+ echo "ERROR: sdk/js/package-lock.json resolves packages outside https://registry.npmjs.org/."
+ grep -E '"resolved": "https?://' sdk/js/package-lock.json | grep -v '"resolved": "https://registry.npmjs.org/' | head -3
+ echo "Regenerate it with the public registry (sdk/js/.npmrc pins it)."
+ exit 1
+fi
+echo "SDK lockfile resolves against the public registry."
diff --git a/sdk/README.md b/sdk/README.md
index a03e7924..e177547e 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -295,18 +295,24 @@ holds against the control plane's records.
### Milestone 3 — call tools (done)
-- Discovery: `session.discover(type, name)` looks the mesh DHT up for the
- service key `internal/node/service.go` derives. JS: `@libp2p/kad-dht` in
- client mode on `/sam/kad/1.0.0`; Python: the SDK's own bounded
- GET_PROVIDERS walk on the same protocol (see the facts above).
-- `/sam/mcp/1.0.0` client: `session.openMCP(addr, "mcp://<name>")` sends
+- Discovery: `session.discover("mcp://calc")`, or `(type, name)`, or a type
+ alone, looks the mesh DHT up for the service key
+ `internal/node/service.go` derives. JS: `@libp2p/kad-dht` in client mode
+ on `/sam/kad/1.0.0`; Python: the SDK's own bounded GET_PROVIDERS walk on
+ the same protocol (see the facts above).
+- Naming a peer: every call takes a `Peer`, which is a provider `discover`
+ returned, a peer id, or a multiaddr. For the first two the SDK dials the
+ advertised addresses and `<router>/p2p-circuit/p2p/<peer>` through every
+ admitted router, as `preparePeerAddrs` in `internal/node/mcp.go` does; a
+ multiaddr is dialed as given.
+- `/sam/mcp/1.0.0` client: `session.openMCP(peer, "mcp://<name>")` sends
the `AuthFrame` naming the service, verifies the provider's credential
and the caller's required labels (`checkPeerLabels`), then runs the
official MCP client over the varint-framed stream. JS: a `Transport` for
`@modelcontextprotocol/sdk`; Python: a pair of memory streams pumped to
and from the libp2p stream for `mcp.ClientSession`. `""` as the target is
the provider's own catalog (`list_local_services`, `get_mesh_info`).
-- `session.listTools(addr, service)` and `session.callTool(addr, service,
+- `session.listTools(peer, service)` and `session.callTool(peer, service,
tool, args)` on top of that.
- Tests. Unit: each SDK calls a tool on an in-process provider that serves
`/sam/mcp/1.0.0` as `sam-node` does with the official MCP server behind
@@ -433,15 +439,16 @@ holds against the control plane's records.
./hack/gen-sdk-proto.sh
# JavaScript
-cd sdk/js && npm ci && npm test && npm run build
+cd sdk/js && npm ci && npm test && npm run build && npm run examples
# Python
python3 -m venv sdk/python/.venv
sdk/python/.venv/bin/pip install -e 'sdk/python[test]'
sdk/python/.venv/bin/pytest sdk/python/tests
-# Both against a real control plane, router and sam-node
-go test ./tests/integration -run TestNativeSDKs -v
+# Both against a real control plane, router and sam-node, and the example
+# programs the docs embed against the same
+go test ./tests/integration -run TestNativeSDK -v
```
`make sdk-test` runs all of the above. The integration tests skip an SDK
@@ -453,6 +460,18 @@ holds, then takes JSON commands on stdin (`auth`, `discover`, `tools`,
`call`, `serve`, `http`, `peers`, `sync`, `banned`, `quit`) so the Go test
can drive both languages through the same script.
+The programs the package READMEs and the Native SDKs guide show are
+`sdk/js/examples/*.ts` and `sdk/python/examples/*.py`. The Markdown embeds
+them between `<!-- embed: <path> -->` and `<!-- /embed -->` markers;
+`make sdk-docs` (`go run ./hack/gen-sdk-docs sdk site/content/docs`) copies
+the files in, `hack/verify-sdk-generated.sh` fails when a copy is stale, and
+`TestNativeSDKExamples` runs the files themselves against a mesh. Edit the
+example, regenerate, commit both.
+
+`sdk/js/.npmrc` pins the public registry so `package-lock.json` never
+resolves packages through a local mirror; the verify script checks the
+lockfile too.
+
Interoperability facts that the tests pin: `sdk/testdata/identity_vectors.json`
holds key encodings, peer IDs and challenge signatures produced with
go-libp2p, `sdk/testdata/biscuit_vectors.json` holds tokens minted by the
@@ -473,7 +492,7 @@ one follows is named so a change on one side can be carried to the others.
| `identity.ts` | `identity.py` | ed25519 key pair, libp2p key encodings, peer ID |
| `controlplane.ts` | `controlplane.py` | `/info`, `/keys`, `/enroll`, `/enroll/status`, `/register`, `/refresh`, `/policies`, `/nodes/catalog`, with the challenges of `api/network.go` |
| `credential.ts` | `credential.py` | what a member holds, `AuthFrame` encoding, `issuedUnderKeys` |
-| `mesh.ts` | `mesh.py` | `AgentMesh`: enroll, load, refresh, `syncControlPlane` as `SyncControlPlane` in `internal/node/controlplane_sync.go`; state directory (`identity.key`, `credential.json`) |
+| `mesh.ts` | `mesh.py` | `AgentMesh`: enroll (resumes an unexpired credential in the state directory before spending a token), load, refresh, `syncControlPlane` as `SyncControlPlane` in `internal/node/controlplane_sync.go`; state directory (`identity.key`, `credential.json`, the same layout in both languages) |
| `biscuit.ts` | `biscuit.py` | verification of a peer's credential, as `internal/identity.verifyBiscuit` |
| `host.ts` | `host.py` | the libp2p host as `internal/node/node.go` configures it, plus gossipsub and the connection gater |
| `auth.ts` | `auth.py` | `/sam/auth/1.0.0` on both sides, as `HandleAuthHandshake` |
@@ -485,6 +504,7 @@ one follows is named so a change on one side can be carried to the others.
| `serve.ts` | `serve.py` | `/sam/mcp/1.0.0` server, `/libp2p-http` server and client, service registry, as `WithBiscuitAuth` and `StartIngressServer` |
| `sync.ts` | `sync.py` | ban set and mesh event verification, as `reconcileBannedPeers` and `verifyEvent` |
| `conformance.ts`, `conformance-join.ts` | `conformance.py`, `conformance_join.py` | the runners the integration tests drive |
+| `../examples/` | `../../examples/` | the programs the docs embed and `TestNativeSDKExamples` runs |
| `gen/` | `_proto/`, `_gen/` | generated by `hack/gen-sdk-proto.sh` from `api/sam.proto`, `sdk/python/proto/circuit.proto` and `api/datalog.go` |
Unit tests sit beside the code (`*.test.ts`, `tests/test_*.py`) and build a
diff --git a/sdk/js/README.md b/sdk/js/README.md
index af3fde8a..4a526932 100644
--- a/sdk/js/README.md
+++ b/sdk/js/README.md
@@ -6,73 +6,137 @@ the agent enrolls with the control plane, joins the mesh through a router,
finds services and calls them, publishes services of its own, and follows
the control plane's keys, bans and policy while it runs.
-Guide: [sam-mesh.dev/docs/guides/native-sdks](https://sam-mesh.dev/docs/guides/native-sdks/).
+Guide: [sam-mesh.dev/docs/guides/native-sdks](https://sam-mesh.dev/docs/guides/native-sdks/),
+from an empty machine to two programs on a mesh.
Source: [github.com/google/sam/tree/main/sdk/js](https://github.com/google/sam/tree/main/sdk/js).
## Install
```bash
-npm install @sam-mesh/sdk
+npm install @sam-mesh/sdk @modelcontextprotocol/sdk zod
```
Requires Node.js 22.18 or later.
## Use
+Both programs below are in
+[`examples/`](https://github.com/google/sam/tree/main/sdk/js/examples) and
+run against a real mesh in the repository's tests. They read the mesh from
+`SAM_CONTROL_PLANE_URL` and the enrollment token from
+`SAM_BOOTSTRAP_TOKEN_PATH`; the guide shows how to get both from `sam-one`
+or from the operator of an existing mesh.
+
+Find a service and call it:
+
+<!-- embed: sdk/js/examples/call.ts -->
```ts
+// Finds a service on the mesh and calls it: a tool of an MCP service, or a
+// path of an inference or A2A service.
+//
+// node call.js mcp://greeter greet '{"name": "Ada"}'
+// node call.js a2a://greeter /card
+// node call.js inference://ollama /v1/models
+//
+// SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+// holding the token the mesh operator gave you; the first run spends it and
+// keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+// there without it.
+import { homedir } from "node:os";
import { AgentMesh } from "@sam-mesh/sdk";
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import { z } from "zod";
+
+const [service = "mcp://greeter", toolOrPath = "greet", args = '{"name": "world"}'] = process.argv.slice(2);
const mesh = await AgentMesh.enroll({
- controlPlaneUrl: "https://hub.sam-mesh.dev",
- bootstrapTokenPath: "/run/secrets/sam-bootstrap-token",
- stateDir: `${process.env.HOME}/.config/sam-mesh/agent`,
+ controlPlaneUrl: process.env.SAM_CONTROL_PLANE_URL ?? "https://mesh.example.com",
+ bootstrapTokenPath: process.env.SAM_BOOTSTRAP_TOKEN_PATH,
+ stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/caller`,
});
-console.log(mesh.peerId); // 12D3Koo...
-
-// On the mesh: authenticated with a router, reachable through it, credential
-// kept fresh, keys, bans and policy followed from the control plane until close().
const session = await mesh.join();
-console.log(session.relayAddresses.map(String));
+console.log(`on the mesh as ${session.peerId}`);
+
+const [provider] = await session.discover(service);
+if (provider === undefined) {
+ throw new Error(`no member of the mesh serves ${service}`);
+}
+console.log(`${service} is served by ${provider.peerId}`);
+
+if (service.startsWith("mcp://")) {
+ const tools = await session.listTools(provider, service);
+ console.log(`tools: ${tools.map((t) => t.name).join(", ")}`);
+ const result = await session.callTool(provider, service, toolOrPath, JSON.parse(args));
+ console.log(result.text.join("\n"));
+} else {
+ const response = await session.request(provider, service, toolOrPath);
+ console.log(response.status, response.text());
+}
-// Reach another member (directly or through a router) and verify it.
-const peer = await session.authenticate("/ip4/.../p2p/<router>/p2p-circuit/p2p/<peer>");
-console.log(peer.roles, peer.labels, peer.expiration);
+await session.close();
+```
+<!-- /embed -->
+
+Publish services of your own:
+
+<!-- embed: sdk/js/examples/serve.ts -->
+```ts
+// Publishes services on the mesh and answers callers until stopped: an MCP
+// tool, an A2A endpoint and, when OLLAMA_URL is set, the Ollama server running
+// beside this program as an inference service. The mesh policy decides which
+// members may call; the SDK turns the others away before anything reaches
+// this code or Ollama.
+//
+// node serve.js
+//
+// SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+// holding the token the mesh operator gave you; the first run spends it and
+// keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+// there without it.
+import { homedir } from "node:os";
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { AgentMesh } from "@sam-mesh/sdk";
+import { z } from "zod";
-// Find a service in the mesh DHT and call one of its tools.
-const [provider] = await session.discover("mcp", "calc");
-const addr = `${session.routers[0].addr}/p2p-circuit/p2p/${provider.peerId}`;
-console.log(await session.listTools(addr, "mcp://calc"));
-const result = await session.callTool(addr, "mcp://calc", "add", { a: 1, b: 2 }, { requiredLabels: { region: "eu" } });
-console.log(result.text);
+const mesh = await AgentMesh.enroll({
+ controlPlaneUrl: process.env.SAM_CONTROL_PLANE_URL ?? "https://mesh.example.com",
+ bootstrapTokenPath: process.env.SAM_BOOTSTRAP_TOKEN_PATH,
+ stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/greeter`,
+});
+const session = await mesh.join();
-// Publish services of your own. Callers are authorized with the mesh policy
-// before anything reaches your code or your backend.
await session.serve({
type: "mcp",
- name: "echo",
+ name: "greeter",
createServer: () => {
- const server = new McpServer({ name: "echo", version: "1.0.0" });
- server.tool("echo", { text: z.string() }, async ({ text }) => ({ content: [{ type: "text", text }] }));
+ const server = new McpServer({ name: "greeter", version: "1.0.0" });
+ server.registerTool("greet", { description: "Greets someone by name", inputSchema: { name: z.string() } }, async ({ name }) => ({
+ content: [{ type: "text", text: `hello ${name}` }],
+ }));
return server;
},
});
-await session.serve({ type: "inference", name: "llm", target: "http://127.0.0.1:8000" });
-await session.serve({ type: "a2a", name: "reviewer", target: (request, caller) => new Response(`hello ${caller.peerId}`) });
-// Call an inference or A2A service on another member.
-const models = await session.request(addr, "inference://llm", "/v1/models");
-console.log(models.status, models.text());
-await session.close();
+await session.serve({
+ type: "a2a",
+ name: "greeter",
+ target: (request, caller) => Response.json({ name: "greeter", path: new URL(request.url).pathname, caller: caller.peerId }),
+});
+
+if (process.env.OLLAMA_URL !== undefined) {
+ await session.serve({ type: "inference", name: "ollama", target: process.env.OLLAMA_URL });
+}
+
+console.log(`serving ${session.servedServices.map((s) => `${s.type}://${s.name}`).join(", ")} as ${session.peerId}`);
-// Later, in a new process:
-const resumed = await AgentMesh.load({ controlPlaneUrl: "https://hub.sam-mesh.dev", stateDir: "..." });
+const stop = () => void session.close().then(() => process.exit(0));
+process.on("SIGINT", stop);
+process.on("SIGTERM", stop);
```
+<!-- /embed -->
-`enroll` takes exactly one of `bootstrapTokenPath`, `bootstrapToken` or
-`jwt`. Read tokens from a file or the environment; do not put them on a
-command line.
+`enroll` reuses the identity and credential saved in `stateDir` when they
+are still valid for that control plane, and needs exactly one of
+`bootstrapTokenPath`, `bootstrapToken` or `jwt` otherwise. Read tokens from
+a file or the environment; do not put them on a command line.
A plaintext `http://` control plane is accepted only on loopback. Pass
`allowInsecure: true` for a network you trust.
diff --git a/sdk/js/examples/call.ts b/sdk/js/examples/call.ts
new file mode 100644
index 00000000..ddccacb6
--- /dev/null
+++ b/sdk/js/examples/call.ts
@@ -0,0 +1,41 @@
+// Finds a service on the mesh and calls it: a tool of an MCP service, or a
+// path of an inference or A2A service.
+//
+// node call.js mcp://greeter greet '{"name": "Ada"}'
+// node call.js a2a://greeter /card
+// node call.js inference://ollama /v1/models
+//
+// SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+// holding the token the mesh operator gave you; the first run spends it and
+// keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+// there without it.
+import { homedir } from "node:os";
+import { AgentMesh } from "@sam-mesh/sdk";
+
+const [service = "mcp://greeter", toolOrPath = "greet", args = '{"name": "world"}'] = process.argv.slice(2);
+
+const mesh = await AgentMesh.enroll({
+ controlPlaneUrl: process.env.SAM_CONTROL_PLANE_URL ?? "https://mesh.example.com",
+ bootstrapTokenPath: process.env.SAM_BOOTSTRAP_TOKEN_PATH,
+ stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/caller`,
+});
+const session = await mesh.join();
+console.log(`on the mesh as ${session.peerId}`);
+
+const [provider] = await session.discover(service);
+if (provider === undefined) {
+ throw new Error(`no member of the mesh serves ${service}`);
+}
+console.log(`${service} is served by ${provider.peerId}`);
+
+if (service.startsWith("mcp://")) {
+ const tools = await session.listTools(provider, service);
+ console.log(`tools: ${tools.map((t) => t.name).join(", ")}`);
+ const result = await session.callTool(provider, service, toolOrPath, JSON.parse(args));
+ console.log(result.text.join("\n"));
+} else {
+ const response = await session.request(provider, service, toolOrPath);
+ console.log(response.status, response.text());
+}
+
+await session.close();
diff --git a/sdk/js/examples/serve.ts b/sdk/js/examples/serve.ts
new file mode 100644
index 00000000..a3c3fca0
--- /dev/null
+++ b/sdk/js/examples/serve.ts
@@ -0,0 +1,51 @@
+// Publishes services on the mesh and answers callers until stopped: an MCP
+// tool, an A2A endpoint and, when OLLAMA_URL is set, the Ollama server running
+// beside this program as an inference service. The mesh policy decides which
+// members may call; the SDK turns the others away before anything reaches
+// this code or Ollama.
+//
+// node serve.js
+//
+// SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+// holding the token the mesh operator gave you; the first run spends it and
+// keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+// there without it.
+import { homedir } from "node:os";
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { AgentMesh } from "@sam-mesh/sdk";
+import { z } from "zod";
+
+const mesh = await AgentMesh.enroll({
+ controlPlaneUrl: process.env.SAM_CONTROL_PLANE_URL ?? "https://mesh.example.com",
+ bootstrapTokenPath: process.env.SAM_BOOTSTRAP_TOKEN_PATH,
+ stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/greeter`,
+});
+const session = await mesh.join();
+
+await session.serve({
+ type: "mcp",
+ name: "greeter",
+ createServer: () => {
+ const server = new McpServer({ name: "greeter", version: "1.0.0" });
+ server.registerTool("greet", { description: "Greets someone by name", inputSchema: { name: z.string() } }, async ({ name }) => ({
+ content: [{ type: "text", text: `hello ${name}` }],
+ }));
+ return server;
+ },
+});
+
+await session.serve({
+ type: "a2a",
+ name: "greeter",
+ target: (request, caller) => Response.json({ name: "greeter", path: new URL(request.url).pathname, caller: caller.peerId }),
+});
+
+if (process.env.OLLAMA_URL !== undefined) {
+ await session.serve({ type: "inference", name: "ollama", target: process.env.OLLAMA_URL });
+}
+
+console.log(`serving ${session.servedServices.map((s) => `${s.type}://${s.name}`).join(", ")} as ${session.peerId}`);
+
+const stop = () => void session.close().then(() => process.exit(0));
+process.on("SIGINT", stop);
+process.on("SIGTERM", stop);
diff --git a/sdk/js/package.json b/sdk/js/package.json
index d9f56911..81257d9b 100644
--- a/sdk/js/package.json
+++ b/sdk/js/package.json
@@ -28,6 +28,7 @@
},
"scripts": {
"build": "tsc -p tsconfig.build.json",
+ "examples": "tsc -p tsconfig.examples.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"pretest": "tsc -p tsconfig.test.json",
"test": "node --test 'build/**/*.test.js'"
diff --git a/sdk/js/tsconfig.examples.json b/sdk/js/tsconfig.examples.json
new file mode 100644
index 00000000..e994ff01
--- /dev/null
+++ b/sdk/js/tsconfig.examples.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "outDir": "build/examples",
+ "rootDir": "examples"
+ },
+ "include": ["examples/**/*.ts"]
+}
diff --git a/sdk/python/README.md b/sdk/python/README.md
index f440334b..7a6288c8 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -7,7 +7,8 @@ finds services and calls them, publishes services of its own, and follows
the control plane's keys, bans and policy while it runs. Import it as
`agent_mesh`.
-Guide: [sam-mesh.dev/docs/guides/native-sdks](https://sam-mesh.dev/docs/guides/native-sdks/).
+Guide: [sam-mesh.dev/docs/guides/native-sdks](https://sam-mesh.dev/docs/guides/native-sdks/),
+from an empty machine to two programs on a mesh.
Source: [github.com/google/sam/tree/main/sdk/python](https://github.com/google/sam/tree/main/sdk/python).
## Install
@@ -22,72 +23,140 @@ asyncio, use it through `anyio` with the trio backend. One dependency,
## Use
+Both programs below are in
+[`examples/`](https://github.com/google/sam/tree/main/sdk/python/examples)
+and run against a real mesh in the repository's tests. They read the mesh
+from `SAM_CONTROL_PLANE_URL` and the enrollment token from
+`SAM_BOOTSTRAP_TOKEN_PATH`; the guide shows how to get both from `sam-one`
+or from the operator of an existing mesh.
+
+Find a service and call it:
+
+<!-- embed: sdk/python/examples/call.py -->
```python
+"""Finds a service on the mesh and calls it: a tool of an MCP service, or a
+path of an inference or A2A service.
+
+ python call.py mcp://greeter greet '{"name": "Ada"}'
+ python call.py a2a://greeter /card
+ python call.py inference://ollama /v1/models
+
+SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+holding the token the mesh operator gave you; the first run spends it and
+keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+there without it.
+"""
+
+import json
+import os
+import sys
+
import trio
-from agent_mesh import AgentMesh, HTTPRequest, HTTPResponse, HTTPService, MCPService, VerifiedBiscuit
-from mcp.server.mcpserver import MCPServer
+from agent_mesh import AgentMesh
+
+argv = sys.argv[1:]
+service = argv[0] if len(argv) > 0 else "mcp://greeter"
+tool_or_path = argv[1] if len(argv) > 1 else "greet"
+args = json.loads(argv[2]) if len(argv) > 2 else {"name": "world"}
mesh = AgentMesh.enroll(
- "https://hub.sam-mesh.dev",
- bootstrap_token_path="/run/secrets/sam-bootstrap-token",
- state_dir="~/.config/sam-mesh/agent",
+ os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
+ bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
+ state_dir=os.environ.get("SAM_STATE_DIR", "~/.config/sam-mesh/caller"),
)
-print(mesh.peer_id) # 12D3Koo...
-async def main():
- # On the mesh: authenticated with a router, reachable through it,
- # credential kept fresh, keys, bans and policy followed from the control
- # plane for as long as the block is open.
+async def main() -> None:
async with mesh.join() as session:
- print(session.relay_addresses)
- # Reach another member (directly or through a router) and verify it.
- peer = await session.authenticate("/ip4/.../p2p/<router>/p2p-circuit/p2p/<peer>")
- print(peer.roles, peer.labels, peer.expiration)
+ print(f"on the mesh as {session.peer_id}")
- # Find a service in the mesh DHT and call one of its tools.
- provider = (await session.discover("mcp", "calc"))[0]
- addr = f"{session.routers[0].addr}/p2p-circuit/p2p/{provider.peer_id}"
- print(await session.list_tools(addr, "mcp://calc"))
- result = await session.call_tool(addr, "mcp://calc", "add", {"a": 1, "b": 2}, required_labels={"region": "eu"})
- print(result.text)
+ providers = await session.discover(service)
+ if not providers:
+ raise SystemExit(f"no member of the mesh serves {service}")
+ provider = providers[0]
+ print(f"{service} is served by {provider.peer_id}")
- # Publish services of your own. Callers are authorized with the mesh
- # policy before anything reaches your code or your backend.
- def create_server() -> MCPServer:
- server = MCPServer("echo")
+ if service.startswith("mcp://"):
+ tools = await session.list_tools(provider, service)
+ print("tools:", ", ".join(t.name for t in tools))
+ result = await session.call_tool(provider, service, tool_or_path, args)
+ print("\n".join(result.text))
+ else:
+ response = await session.request(provider, service, tool_or_path)
+ print(response.status, response.text)
- @server.tool()
- def echo(text: str) -> str:
- return text
- return server
+trio.run(main)
+```
+<!-- /embed -->
- await session.serve(MCPService(name="echo", create_server=create_server))
- await session.serve(HTTPService(type="inference", name="llm", target="http://127.0.0.1:8000"))
+Publish services of your own:
- async def card(request: HTTPRequest, caller: VerifiedBiscuit) -> HTTPResponse:
- return HTTPResponse(status=200, body=f"hello {caller.peer_id}".encode())
+<!-- embed: sdk/python/examples/serve.py -->
+```python
+"""Publishes services on the mesh and answers callers until stopped: an MCP
+tool, an A2A endpoint and, when OLLAMA_URL is set, the Ollama server running
+beside this program as an inference service. The mesh policy decides which
+members may call; the SDK turns the others away before anything reaches this
+code or Ollama.
- await session.serve(HTTPService(type="a2a", name="reviewer", target=card))
+ python serve.py
- # Call an inference or A2A service on another member.
- models = await session.request(addr, "inference://llm", "/v1/models")
- print(models.status, models.text)
+SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+holding the token the mesh operator gave you; the first run spends it and
+keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+there without it.
+"""
+import json
+import os
-trio.run(main)
+import trio
+from agent_mesh import AgentMesh, HTTPRequest, HTTPResponse, HTTPService, MCPService, VerifiedBiscuit
+from mcp.server.mcpserver import MCPServer
+
+mesh = AgentMesh.enroll(
+ os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
+ bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
+ state_dir=os.environ.get("SAM_STATE_DIR", "~/.config/sam-mesh/greeter"),
+)
+
+
+def create_server() -> MCPServer:
+ server = MCPServer("greeter")
+
+ @server.tool(description="Greets someone by name")
+ def greet(name: str) -> str:
+ return f"hello {name}"
+
+ return server
-# Later, in a new process:
-mesh = AgentMesh.load("~/.config/sam-mesh/agent")
-```
-py-libp2p runs on trio, so `join()` is a trio async context manager; under
-asyncio use it through `anyio` with the trio backend.
+async def card(request: HTTPRequest, caller: VerifiedBiscuit) -> HTTPResponse:
+ body = json.dumps({"name": "greeter", "path": request.path, "caller": caller.peer_id})
+ return HTTPResponse(status=200, headers={"content-type": "application/json"}, body=body.encode())
+
+
+async def main() -> None:
+ async with mesh.join() as session:
+ await session.serve(MCPService(name="greeter", create_server=create_server))
+ await session.serve(HTTPService(type="a2a", name="greeter", target=card))
+ if "OLLAMA_URL" in os.environ:
+ await session.serve(HTTPService(type="inference", name="ollama", target=os.environ["OLLAMA_URL"]))
+
+ served = ", ".join(f"{t}://{n}" for t, n, _ in session.services.list())
+ print(f"serving {served} as {session.peer_id}", flush=True)
+ await trio.sleep_forever()
+
+
+trio.run(main)
+```
+<!-- /embed -->
-`enroll` takes exactly one of `bootstrap_token_path`, `bootstrap_token` or
-`jwt`. Read tokens from a file or the environment; do not put them on a
-command line.
+`enroll` reuses the identity and credential saved in `state_dir` when they
+are still valid for that control plane, and needs exactly one of
+`bootstrap_token_path`, `bootstrap_token` or `jwt` otherwise. Read tokens
+from a file or the environment; do not put them on a command line.
A plaintext `http://` control plane is accepted only on loopback. Pass
`allow_insecure=True` for a network you trust.
diff --git a/sdk/python/examples/call.py b/sdk/python/examples/call.py
new file mode 100644
index 00000000..721838dc
--- /dev/null
+++ b/sdk/python/examples/call.py
@@ -0,0 +1,53 @@
+"""Finds a service on the mesh and calls it: a tool of an MCP service, or a
+path of an inference or A2A service.
+
+ python call.py mcp://greeter greet '{"name": "Ada"}'
+ python call.py a2a://greeter /card
+ python call.py inference://ollama /v1/models
+
+SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+holding the token the mesh operator gave you; the first run spends it and
+keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+there without it.
+"""
+
+import json
+import os
+import sys
+
+import trio
+from agent_mesh import AgentMesh
+
+argv = sys.argv[1:]
+service = argv[0] if len(argv) > 0 else "mcp://greeter"
+tool_or_path = argv[1] if len(argv) > 1 else "greet"
+args = json.loads(argv[2]) if len(argv) > 2 else {"name": "world"}
+
+mesh = AgentMesh.enroll(
+ os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
+ bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
+ state_dir=os.environ.get("SAM_STATE_DIR", "~/.config/sam-mesh/caller"),
+)
+
+
+async def main() -> None:
+ async with mesh.join() as session:
+ print(f"on the mesh as {session.peer_id}")
+
+ providers = await session.discover(service)
+ if not providers:
+ raise SystemExit(f"no member of the mesh serves {service}")
+ provider = providers[0]
+ print(f"{service} is served by {provider.peer_id}")
+
+ if service.startswith("mcp://"):
+ tools = await session.list_tools(provider, service)
+ print("tools:", ", ".join(t.name for t in tools))
+ result = await session.call_tool(provider, service, tool_or_path, args)
+ print("\n".join(result.text))
+ else:
+ response = await session.request(provider, service, tool_or_path)
+ print(response.status, response.text)
+
+
+trio.run(main)
diff --git a/sdk/python/examples/serve.py b/sdk/python/examples/serve.py
new file mode 100644
index 00000000..7f5e2935
--- /dev/null
+++ b/sdk/python/examples/serve.py
@@ -0,0 +1,56 @@
+"""Publishes services on the mesh and answers callers until stopped: an MCP
+tool, an A2A endpoint and, when OLLAMA_URL is set, the Ollama server running
+beside this program as an inference service. The mesh policy decides which
+members may call; the SDK turns the others away before anything reaches this
+code or Ollama.
+
+ python serve.py
+
+SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+holding the token the mesh operator gave you; the first run spends it and
+keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+there without it.
+"""
+
+import json
+import os
+
+import trio
+from agent_mesh import AgentMesh, HTTPRequest, HTTPResponse, HTTPService, MCPService, VerifiedBiscuit
+from mcp.server.mcpserver import MCPServer
+
+mesh = AgentMesh.enroll(
+ os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
+ bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
+ state_dir=os.environ.get("SAM_STATE_DIR", "~/.config/sam-mesh/greeter"),
+)
+
+
+def create_server() -> MCPServer:
+ server = MCPServer("greeter")
+
+ @server.tool(description="Greets someone by name")
+ def greet(name: str) -> str:
+ return f"hello {name}"
+
+ return server
+
+
+async def card(request: HTTPRequest, caller: VerifiedBiscuit) -> HTTPResponse:
+ body = json.dumps({"name": "greeter", "path": request.path, "caller": caller.peer_id})
+ return HTTPResponse(status=200, headers={"content-type": "application/json"}, body=body.encode())
+
+
+async def main() -> None:
+ async with mesh.join() as session:
+ await session.serve(MCPService(name="greeter", create_server=create_server))
+ await session.serve(HTTPService(type="a2a", name="greeter", target=card))
+ if "OLLAMA_URL" in os.environ:
+ await session.serve(HTTPService(type="inference", name="ollama", target=os.environ["OLLAMA_URL"]))
+
+ served = ", ".join(f"{t}://{n}" for t, n, _ in session.services.list())
+ print(f"serving {served} as {session.peer_id}", flush=True)
+ await trio.sleep_forever()
+
+
+trio.run(main)
diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.md
index 59e8c13e..6f62b1ea 100644
--- a/site/content/docs/guides/native-sdks.md
+++ b/site/content/docs/guides/native-sdks.md
@@ -4,193 +4,458 @@ linkTitle: "Native SDKs"
weight: 6
---
-An agent written in JavaScript or Python can be a mesh member itself, with no
-`sam-node` beside it. The SDKs under `sdk/` speak the same protocols the Go
-components speak: they enroll with the control plane, join through a router,
-find services in the mesh DHT, call MCP tools and inference or A2A endpoints,
-and publish services of their own, authorizing every caller with the same
-Datalog a `sam-node` evaluates.
+An agent written in JavaScript or Python can be a member of the mesh itself,
+with no `sam-node` beside it. The SDK enrolls with the control plane, joins
+through a router, finds services, calls MCP tools and inference or A2A
+endpoints, and publishes services of its own. Every caller of those services
+is checked against the mesh policy before anything reaches your code.
-This guide shows the whole journey with each SDK. It assumes a running mesh:
-a control plane, at least one router, and a bootstrap token minted for the
-agent (see [Headless enrollment](../headless-enrollment/)).
+This guide takes you from nothing to two programs on a mesh: one that
+publishes a tool and an agent card, and one that finds them and calls them.
+Both programs are in the repository under
+[`sdk/js/examples`](https://github.com/google/sam/tree/main/sdk/js/examples)
+and
+[`sdk/python/examples`](https://github.com/google/sam/tree/main/sdk/python/examples),
+and the repository's tests run them against a real mesh, so what you read
+here is what runs.
-## Install
+## 1. Get a mesh
-```bash
-npm install @sam-mesh/sdk # Node.js 22 or later
-pip install sam-mesh # Python 3.11 or later
-```
+A program needs the URL of a control plane and a token that lets it enroll.
+You get them in one of two ways.
-Both packages are published from the repository's release workflow, at the
-version of the release tag. The Python package runs on trio; under asyncio,
-use it through `anyio` with the trio backend.
+### Run your own
-## Enroll and join
+`sam-one` runs a control plane, a router and a web console in one process.
+The [install script](../../getting-started/quickstart/#1-install) provides
+it. Start it with a directory for its state:
-Read the bootstrap token from a file or the environment. Do not put it on a
-command line; it would sit in `ps` output and shell history. The state
-directory keeps the identity key and the credential across restarts, so an
-agent enrolls once and resumes with `load` afterwards.
-
-JavaScript:
+```bash
+sam-one --data-dir ~/sam-one
+```
-```ts
-import { AgentMesh } from "@sam-mesh/sdk";
+The banner it prints has the URL, and the token is written to
+`~/sam-one/join-token`:
-const mesh = await AgentMesh.enroll({
- controlPlaneUrl: "https://hub.sam-mesh.dev",
- bootstrapTokenPath: "/run/secrets/sam-bootstrap-token",
- stateDir: `${process.env.HOME}/.config/sam-mesh/reviewer`,
-});
-const session = await mesh.join();
-console.log(session.peerId, session.relayAddresses.map(String));
+```text
+API URL: http://0.0.0.0:33775
+Join Token: sam_tok_…
```
-Python:
+On first boot `sam-one` seeds an open development policy, so any enrolled
+member may publish and call any service. That is right for trying the
+programs below on your laptop. Before you share the mesh, replace it, as
+[Your own mesh](../../getting-started/your-own-mesh/#5-before-you-share-it)
+explains.
-```python
-import trio
-from agent_mesh import AgentMesh
+This mesh is reachable from your machine only. To let programs on other
+machines join, start `sam-one` with `--tunnel cloudflare`, which publishes
+the port on a temporary public `https` hostname and prints that URL in the
+banner instead. Use that URL as the control plane URL everywhere below. [Your
+own mesh](../../getting-started/your-own-mesh/) covers the tunnel, a real
+hostname and the console.
-mesh = AgentMesh.enroll(
- "https://hub.sam-mesh.dev",
- bootstrap_token_path="/run/secrets/sam-bootstrap-token",
- state_dir="~/.config/sam-mesh/reviewer",
-)
+### Join a mesh someone else runs
-async def main():
- async with mesh.join() as session:
- print(session.peer_id, session.relay_addresses)
- ...
+Ask the operator for the control plane URL and a bootstrap token. Operators
+mint tokens in the console or with `sam-one token create`; a mesh with an
+identity provider lets you mint your own from the console after logging in.
+Save the token in a file that only you can read. Do not put it on a command
+line: it would sit in `ps` output and shell history.
-trio.run(main)
-```
+### Tell the programs about it
-`join` connects to the routers named in the credential, runs the
-`/sam/auth/1.0.0` handshake with each, requires the router role on the
-credential the router answers with, and reserves a relay slot so other
-members reach the agent through the router. While the session is open the
-SDK keeps the credential fresh, pulls keys, bans and router addresses from
-the control plane on `sam-node`'s interval, and listens to the control
-plane's gossip events, so a ban or a key rotation reaches the agent within
-seconds.
+The programs below read the mesh from two environment variables. Set them in
+every terminal you use:
-## Call services
+```bash
+export SAM_CONTROL_PLANE_URL=http://127.0.0.1:33775 # the API URL from the banner
+export SAM_BOOTSTRAP_TOKEN_PATH=~/sam-one/join-token
+```
-Discovery is a DHT lookup by service type and name. A provider found there is
-only a peer that announced itself; the call verifies its credential before
-sending anything.
+A plain `http://` URL is accepted only for a control plane on the same
+machine. Anything else needs `https://`, because the control plane is the
+trust root of every member and the SDK refuses to fetch it over plaintext
+from a remote address.
-```ts
-const [provider] = await session.discover("mcp", "calc");
-const addr = `${session.routers[0].addr}/p2p-circuit/p2p/${provider.peerId}`;
-const tools = await session.listTools(addr, "mcp://calc");
-const result = await session.callTool(addr, "mcp://calc", "add", { a: 1, b: 2 }, { requiredLabels: { region: "eu" } });
-console.log(result.text);
+## 2. Install the SDK
-const models = await session.request(addr, "inference://llm", "/v1/models");
-console.log(models.status, models.text());
+```bash
+npm install @sam-mesh/sdk @modelcontextprotocol/sdk zod # Node.js 22 or later
```
-```python
-provider = (await session.discover("mcp", "calc"))[0]
-addr = f"{session.routers[0].addr}/p2p-circuit/p2p/{provider.peer_id}"
-tools = await session.list_tools(addr, "mcp://calc")
-result = await session.call_tool(addr, "mcp://calc", "add", {"a": 1, "b": 2}, required_labels={"region": "eu"})
-print(result.text)
-
-models = await session.request(addr, "inference://llm", "/v1/models")
-print(models.status, models.text)
+```bash
+pip install sam-mesh # Python 3.11 or later
```
-`requiredLabels` refuses a provider whose control-plane-attested labels do not
-carry the requested values, the way `sam-node`'s label gate does.
-`request` speaks `/libp2p-http` for inference and A2A services, one request
-per stream, the way `sam-node`'s egress proxy does for
-`/sam/<peer>/<type>/<name>/<path>`.
+The JavaScript package depends on the MCP SDK and zod; the install line
+names them so your project can import them directly. The Python package is
+imported as `agent_mesh`. It runs on trio, because py-libp2p does; under
+asyncio, use it through `anyio` with the trio backend.
-## Publish services
+## 3. Publish a service
-`serve` registers a service, announces it in the DHT and reports it to the
-control plane's catalog. The first call fetches the mesh policy. From then on
-every caller is authorized before anything reaches your code or your backend:
-its credential must be signed by a trusted control plane key, bound to the
-connection's peer, unexpired, and its role must be granted the service by the
-mesh policy, evaluated on the same Datalog text a `sam-node` evaluates.
+This program publishes an MCP tool named `greet` under the service
+`mcp://greeter` and an A2A endpoint under `a2a://greeter`, and stays on the
+mesh answering callers until you stop it. With `OLLAMA_URL` set, it also
+publishes the Ollama server running beside it as `inference://ollama`, so a
+model on your laptop becomes a model on the mesh.
-An MCP service takes a factory for an MCP server, one per session:
+JavaScript, `serve.js`:
+<!-- embed: sdk/js/examples/serve.ts -->
```ts
+// Publishes services on the mesh and answers callers until stopped: an MCP
+// tool, an A2A endpoint and, when OLLAMA_URL is set, the Ollama server running
+// beside this program as an inference service. The mesh policy decides which
+// members may call; the SDK turns the others away before anything reaches
+// this code or Ollama.
+//
+// node serve.js
+//
+// SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+// holding the token the mesh operator gave you; the first run spends it and
+// keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+// there without it.
+import { homedir } from "node:os";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { AgentMesh } from "@sam-mesh/sdk";
import { z } from "zod";
+const mesh = await AgentMesh.enroll({
+ controlPlaneUrl: process.env.SAM_CONTROL_PLANE_URL ?? "https://mesh.example.com",
+ bootstrapTokenPath: process.env.SAM_BOOTSTRAP_TOKEN_PATH,
+ stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/greeter`,
+});
+const session = await mesh.join();
+
await session.serve({
type: "mcp",
- name: "echo",
+ name: "greeter",
createServer: () => {
- const server = new McpServer({ name: "echo", version: "1.0.0" });
- server.tool("echo", { text: z.string() }, async ({ text }) => ({ content: [{ type: "text", text }] }));
+ const server = new McpServer({ name: "greeter", version: "1.0.0" });
+ server.registerTool("greet", { description: "Greets someone by name", inputSchema: { name: z.string() } }, async ({ name }) => ({
+ content: [{ type: "text", text: `hello ${name}` }],
+ }));
return server;
},
});
+
+await session.serve({
+ type: "a2a",
+ name: "greeter",
+ target: (request, caller) => Response.json({ name: "greeter", path: new URL(request.url).pathname, caller: caller.peerId }),
+});
+
+if (process.env.OLLAMA_URL !== undefined) {
+ await session.serve({ type: "inference", name: "ollama", target: process.env.OLLAMA_URL });
+}
+
+console.log(`serving ${session.servedServices.map((s) => `${s.type}://${s.name}`).join(", ")} as ${session.peerId}`);
+
+const stop = () => void session.close().then(() => process.exit(0));
+process.on("SIGINT", stop);
+process.on("SIGTERM", stop);
```
+<!-- /embed -->
+
+Python, `serve.py`:
+<!-- embed: sdk/python/examples/serve.py -->
```python
-from agent_mesh import MCPService
+"""Publishes services on the mesh and answers callers until stopped: an MCP
+tool, an A2A endpoint and, when OLLAMA_URL is set, the Ollama server running
+beside this program as an inference service. The mesh policy decides which
+members may call; the SDK turns the others away before anything reaches this
+code or Ollama.
+
+ python serve.py
+
+SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+holding the token the mesh operator gave you; the first run spends it and
+keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+there without it.
+"""
+
+import json
+import os
+
+import trio
+from agent_mesh import AgentMesh, HTTPRequest, HTTPResponse, HTTPService, MCPService, VerifiedBiscuit
from mcp.server.mcpserver import MCPServer
+mesh = AgentMesh.enroll(
+ os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
+ bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
+ state_dir=os.environ.get("SAM_STATE_DIR", "~/.config/sam-mesh/greeter"),
+)
+
+
def create_server() -> MCPServer:
- server = MCPServer("echo")
+ server = MCPServer("greeter")
- @server.tool()
- def echo(text: str) -> str:
- return text
+ @server.tool(description="Greets someone by name")
+ def greet(name: str) -> str:
+ return f"hello {name}"
return server
-await session.serve(MCPService(name="echo", create_server=create_server))
+
+async def card(request: HTTPRequest, caller: VerifiedBiscuit) -> HTTPResponse:
+ body = json.dumps({"name": "greeter", "path": request.path, "caller": caller.peer_id})
+ return HTTPResponse(status=200, headers={"content-type": "application/json"}, body=body.encode())
+
+
+async def main() -> None:
+ async with mesh.join() as session:
+ await session.serve(MCPService(name="greeter", create_server=create_server))
+ await session.serve(HTTPService(type="a2a", name="greeter", target=card))
+ if "OLLAMA_URL" in os.environ:
+ await session.serve(HTTPService(type="inference", name="ollama", target=os.environ["OLLAMA_URL"]))
+
+ served = ", ".join(f"{t}://{n}" for t, n, _ in session.services.list())
+ print(f"serving {served} as {session.peer_id}", flush=True)
+ await trio.sleep_forever()
+
+
+trio.run(main)
```
+<!-- /embed -->
+
+Run one of them:
+
+```bash
+node serve.js
+# or
+python serve.py
+```
+
+```text
+serving mcp://greeter, a2a://greeter as 12D3KooWQmB5…
+```
+
+The program spent the token, saved its identity and credential under
+`~/.config/sam-mesh/greeter`, joined through the router and announced its
+services. Run it again and it resumes from that directory; the token is no
+longer needed. The service is reachable from every member of the mesh:
+another program written with an SDK, a `sam-node` on any machine, or a
+phone.
+
+## 4. Call it
+
+This program finds a service by name and calls it: a tool of an MCP service,
+or a path of an inference or A2A service.
-An inference or A2A service forwards authorized requests to a local URL or to
-a handler in the process. The caller's biscuit never reaches the backend;
-`X-Peer-Id` names the verified caller.
+JavaScript, `call.js`:
+<!-- embed: sdk/js/examples/call.ts -->
```ts
-await session.serve({ type: "inference", name: "llm", target: "http://127.0.0.1:8000" });
-await session.serve({
- type: "a2a",
- name: "reviewer",
- target: (request, caller) => new Response(`hello ${caller.peerId}`),
+// Finds a service on the mesh and calls it: a tool of an MCP service, or a
+// path of an inference or A2A service.
+//
+// node call.js mcp://greeter greet '{"name": "Ada"}'
+// node call.js a2a://greeter /card
+// node call.js inference://ollama /v1/models
+//
+// SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+// holding the token the mesh operator gave you; the first run spends it and
+// keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+// there without it.
+import { homedir } from "node:os";
+import { AgentMesh } from "@sam-mesh/sdk";
+
+const [service = "mcp://greeter", toolOrPath = "greet", args = '{"name": "world"}'] = process.argv.slice(2);
+
+const mesh = await AgentMesh.enroll({
+ controlPlaneUrl: process.env.SAM_CONTROL_PLANE_URL ?? "https://mesh.example.com",
+ bootstrapTokenPath: process.env.SAM_BOOTSTRAP_TOKEN_PATH,
+ stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/caller`,
});
+const session = await mesh.join();
+console.log(`on the mesh as ${session.peerId}`);
+
+const [provider] = await session.discover(service);
+if (provider === undefined) {
+ throw new Error(`no member of the mesh serves ${service}`);
+}
+console.log(`${service} is served by ${provider.peerId}`);
+
+if (service.startsWith("mcp://")) {
+ const tools = await session.listTools(provider, service);
+ console.log(`tools: ${tools.map((t) => t.name).join(", ")}`);
+ const result = await session.callTool(provider, service, toolOrPath, JSON.parse(args));
+ console.log(result.text.join("\n"));
+} else {
+ const response = await session.request(provider, service, toolOrPath);
+ console.log(response.status, response.text());
+}
+
+await session.close();
```
+<!-- /embed -->
+Python, `call.py`:
+
+<!-- embed: sdk/python/examples/call.py -->
```python
-from agent_mesh import HTTPRequest, HTTPResponse, HTTPService, VerifiedBiscuit
+"""Finds a service on the mesh and calls it: a tool of an MCP service, or a
+path of an inference or A2A service.
-await session.serve(HTTPService(type="inference", name="llm", target="http://127.0.0.1:8000"))
+ python call.py mcp://greeter greet '{"name": "Ada"}'
+ python call.py a2a://greeter /card
+ python call.py inference://ollama /v1/models
-async def card(request: HTTPRequest, caller: VerifiedBiscuit) -> HTTPResponse:
- return HTTPResponse(status=200, body=f"hello {caller.peer_id}".encode())
+SAM_CONTROL_PLANE_URL names the mesh. SAM_BOOTSTRAP_TOKEN_PATH is the file
+holding the token the mesh operator gave you; the first run spends it and
+keeps the identity and credential in SAM_STATE_DIR, later runs resume from
+there without it.
+"""
+
+import json
+import os
+import sys
+
+import trio
+from agent_mesh import AgentMesh
-await session.serve(HTTPService(type="a2a", name="reviewer", target=card))
+argv = sys.argv[1:]
+service = argv[0] if len(argv) > 0 else "mcp://greeter"
+tool_or_path = argv[1] if len(argv) > 1 else "greet"
+args = json.loads(argv[2]) if len(argv) > 2 else {"name": "world"}
+
+mesh = AgentMesh.enroll(
+ os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
+ bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
+ state_dir=os.environ.get("SAM_STATE_DIR", "~/.config/sam-mesh/caller"),
+)
+
+
+async def main() -> None:
+ async with mesh.join() as session:
+ print(f"on the mesh as {session.peer_id}")
+
+ providers = await session.discover(service)
+ if not providers:
+ raise SystemExit(f"no member of the mesh serves {service}")
+ provider = providers[0]
+ print(f"{service} is served by {provider.peer_id}")
+
+ if service.startswith("mcp://"):
+ tools = await session.list_tools(provider, service)
+ print("tools:", ", ".join(t.name for t in tools))
+ result = await session.call_tool(provider, service, tool_or_path, args)
+ print("\n".join(result.text))
+ else:
+ response = await session.request(provider, service, tool_or_path)
+ print(response.status, response.text)
+
+
+trio.run(main)
+```
+<!-- /embed -->
+
+In a second terminal, with the same two environment variables set, call the
+tool and the agent card. Either language finds a service published from the
+other:
+
+```bash
+node call.js mcp://greeter greet '{"name": "Ada"}'
+```
+
+```text
+on the mesh as 12D3KooWHZ2M…
+mcp://greeter is served by 12D3KooWQmB5…
+tools: greet
+hello Ada
+```
+
+```bash
+python call.py a2a://greeter /card
+```
+
+```text
+on the mesh as 12D3KooWHZ2M…
+a2a://greeter is served by 12D3KooWQmB5…
+200 {"name": "greeter", "path": "/card", "caller": "12D3KooWHZ2M…"}
+```
+
+If you started the server with `OLLAMA_URL=http://127.0.0.1:11434`, ask it
+for its models:
+
+```bash
+node call.js inference://ollama /v1/models
```
-The mesh policy decides who may call. A role must be granted the service
-(`allowed_services: ["mcp://echo"]`, or a pattern) and a target that matches
-the agent's identity, exactly as for a service behind a `sam-node`; see
-[Mesh policy](../../reference/policy/). A caller whose role grants nothing
-receives `AuthResponse{success: false}` on the MCP stream and `403` on the
-HTTP path.
+The caller and the server are two identities on the mesh with their own
+state directories, `caller` and `greeter`. Each spent a token on its first
+run; the standing join token of `sam-one` admits any number of members.
+
+## What happened
+
+`enroll` sent the token and the program's public key to the control plane
+and received a credential: a signed token that names the member, its role
+and the routers it may use. The identity key and the credential live in the
+state directory, so the next run resumes without a token, and the SDK
+renews the credential before it expires. Delete the directory to enroll
+afresh, for instance with other labels.
+
+`join` connected to the routers named in the credential, proved the
+program's identity to each and verified the router's own credential, and
+reserved a relay slot so that other members reach the program through the
+router. The program opens no port of its own. While the session is open,
+the SDK follows the control plane: keys, bans and router addresses on
+`sam-node`'s schedule, and sooner when the control plane announces a change
+over the mesh.
+
+`discover` looked the service up by name in a table the routers host. Every
+call then dials the addresses the provider advertised and the path through
+the router, and verifies the provider's credential before sending anything.
+`requiredLabels` (`required_labels` in Python) refuses a provider whose
+control-plane-attested labels do not carry the values you ask for.
+
+`serve` fetched the mesh policy and started answering. Every caller must
+present a credential signed by a trusted control plane key, bound to the
+connection's peer and unexpired, and its role must be granted the service
+by the policy. The check runs on the same Datalog text a `sam-node`
+evaluates. A caller the policy does not admit is turned away before the
+request reaches your handler or your backend. Your handler sees the verified
+caller as `caller.peerId` (`caller.peer_id`) and, for a forwarded backend
+such as Ollama, as the `X-Peer-Id` header; the caller's credential is never
+forwarded.
+
+Under the open development policy of `sam-one`, every member holds the
+`node` role and that role may call any service. On a shared mesh the policy
+grants a role the services it may call (`allowed_services: ["mcp://greeter"]`
+or a pattern) and the members it may reach; see
+[Mesh policy](../../reference/policy/). A refused MCP caller receives
+`AuthResponse{success: false}` on the stream; a refused HTTP caller receives
+`403`.
+
+## Beyond the examples
+
+- **Naming a peer.** `callTool`, `listTools`, `request`, `authenticate` and
+ `connect` accept a provider from `discover`, a peer id, or a multiaddr.
+ With a peer id alone the SDK goes through the routers.
+- **Every service of a type.** `discover("mcp")` lists every MCP provider
+ on the mesh; `discover("mcp://greeter")` those of one service.
+- **A member's own catalog.** `listTools(peer, "")` returns the provider's
+ `list_local_services` tool, the same one a `sam-node` offers.
+- **Forwarding to a local server.** `serve({ type: "inference", name,
+ target: "http://127.0.0.1:8000" })` and
+ `HTTPService(type="inference", name=..., target="http://...")` forward
+ authorized requests to a URL; a function instead of a URL handles them in
+ the process.
+- **Reading the policy.** `session.policyRules` (`session.policy_rules`)
+ holds the Datalog the session enforces, for logging or tests.
## What the SDKs do not do
- They do not run a sidecar API or a sandbox. An agent that needs the egress
policy enforcement of `sam-box` runs beside a `sam-node`.
-- They do not serve the DHT. A member is a DHT client; the routers hold the
- records.
+- They do not serve the discovery table. A member is a client of it; the
+ routers hold the records.
- They do not run in a browser. Node.js and CPython only, until the transport
to routers from a browser is designed.
-The wire contract, the interoperability facts the tests pin, and the plan are
-in [`sdk/README.md`](https://github.com/google/sam/blob/main/sdk/README.md).
+The wire contract and the interoperability facts the tests pin are in
+[`sdk/README.md`](https://github.com/google/sam/blob/main/sdk/README.md).
diff --git a/tests/integration/sdk_examples_test.go b/tests/integration/sdk_examples_test.go
new file mode 100644
index 00000000..d28eb883
--- /dev/null
+++ b/tests/integration/sdk_examples_test.go
@@ -0,0 +1,298 @@
+// 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 (
+ "bufio"
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// sdkExampleLauncher starts one of the example programs the SDK READMEs and
+// the Native SDKs guide embed (sdk/js/examples, sdk/python/examples), so
+// the documented programs are the ones exercised here.
+type sdkExampleLauncher struct {
+ name string
+ cmd func(ctx context.Context, root, example string, args ...string) (*exec.Cmd, string)
+}
+
+var sdkExampleLaunchers = []sdkExampleLauncher{
+ {
+ name: "js",
+ cmd: func(ctx context.Context, root, example string, args ...string) (*exec.Cmd, string) {
+ entry := filepath.Join(root, "sdk", "js", "build", "examples", example+".js")
+ if _, err := exec.LookPath("node"); err != nil {
+ return nil, "node is not installed"
+ }
+ if _, err := os.Stat(entry); err != nil {
+ return nil, "sdk/js examples are not built (cd sdk/js && npm ci && npm run build && npm run examples)"
+ }
+ return exec.CommandContext(ctx, "node", append([]string{entry}, args...)...), ""
+ },
+ },
+ {
+ name: "python",
+ cmd: func(ctx context.Context, root, example string, args ...string) (*exec.Cmd, string) {
+ python := filepath.Join(root, "sdk", "python", ".venv", "bin", "python")
+ if _, err := os.Stat(python); err != nil {
+ var lookErr error
+ if python, lookErr = exec.LookPath("python3"); lookErr != nil {
+ return nil, "python3 is not installed"
+ }
+ }
+ 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")
+ return exec.CommandContext(ctx, python, append([]string{entry}, args...)...), ""
+ },
+ },
+}
+
+// sdkExampleServer is a running serve example.
+type sdkExampleServer struct {
+ name string
+ peerID string
+}
+
+var servingLine = regexp.MustCompile(`^serving (.*) as (\S+)$`)
+
+// TestNativeSDKExamples runs the programs the SDK READMEs and the Native
+// SDKs guide embed, unchanged, against a real mesh. Each SDK's serve
+// example publishes mcp://greeter, a2a://greeter and inference://ollama,
+// the last forwarding to a stand-in for Ollama this test runs. Each SDK's
+// call example then reaches the sam-node's mcp://calc and a greeter, which
+// is whichever serve example the DHT lists first when both toolchains are
+// present, naming providers only by what discover returned; the SDK finds
+// the path through the router by itself. The first run spends a bootstrap
+// token, the later runs resume from the state directory without one.
+// Cross-language calls with a fixed pairing are TestNativeSDKsMesh's job.
+func TestNativeSDKExamples(t *testing.T) {
+ mesh := startSDKMesh(t)
+
+ ollama := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/models" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"object":"list","data":[{"id":"gemma3","object":"model","owned_by":"`+r.Header.Get("X-Peer-Id")+`"}]}`)
+ }))
+ t.Cleanup(ollama.Close)
+
+ var launchers []sdkExampleLauncher
+ var cmds []*exec.Cmd
+ for _, l := range sdkExampleLaunchers {
+ cmd, skip := l.cmd(context.Background(), mesh.root, "serve")
+ 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 available; see sdk/README.md")
+ }
+ servers := make([]*sdkExampleServer, len(launchers))
+ errs := make([]error, len(launchers))
+ var wg sync.WaitGroup
+ for i := range launchers {
+ 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)
+ }
+ cmds[i].Env = append(os.Environ(),
+ "SAM_CONTROL_PLANE_URL="+mesh.baseURL,
+ "SAM_BOOTSTRAP_TOKEN_PATH="+tokenPath,
+ "SAM_STATE_DIR="+filepath.Join(t.TempDir(), "state"),
+ "OLLAMA_URL="+ollama.URL,
+ )
+ cmds[i].Dir = mesh.root
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ servers[i], errs[i] = startExampleServer(t, launchers[i].name, cmds[i])
+ }(i)
+ }
+ wg.Wait()
+ for _, err := range errs {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, s := range servers {
+ waitForPeerOnRouter(t, mesh.cpPort, mesh.adminToken, s.peerID, 5*time.Second)
+ }
+
+ servedBy := func(t *testing.T, out, service string) {
+ t.Helper()
+ got := expectLine(t, out, service+" is served by ")
+ for _, s := range servers {
+ if s.peerID == got {
+ return
+ }
+ }
+ t.Fatalf("%s is served by %s, which is none of the serve examples", service, got)
+ }
+
+ for _, l := range launchers {
+ l := l
+ t.Run(l.name+"-calls", func(t *testing.T) {
+ t.Parallel()
+ stateDir := filepath.Join(t.TempDir(), "state")
+ 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)
+ }
+ withToken := []string{"SAM_CONTROL_PLANE_URL=" + mesh.baseURL, "SAM_STATE_DIR=" + stateDir, "SAM_BOOTSTRAP_TOKEN_PATH=" + tokenPath}
+ withoutToken := withToken[:2]
+
+ // The first run spends the token: the sam-node's calc over MCP.
+ out := runExample(t, mesh, l, withToken, "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")
+ expectLine(t, out, "fake-result:add")
+
+ // The state directory now holds the identity and credential; the
+ // token file is gone and not needed. The HTTP path: an in-process
+ // A2A handler on one side, a forward to the Ollama stand-in on the
+ // other. The provider sees the verified caller as X-Peer-Id, never
+ // the biscuit.
+ if err := os.Remove(tokenPath); err != nil {
+ t.Fatal(err)
+ }
+ out = runExample(t, mesh, l, withoutToken, "a2a://greeter", "/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)
+ }
+ servedBy(t, out, "a2a://greeter")
+ card := expectLine(t, out, "200 ")
+ if !strings.Contains(card, `"path": "/card"`) && !strings.Contains(card, `"path":"/card"`) {
+ t.Fatalf("a2a card %q does not echo the path", card)
+ }
+ if !strings.Contains(card, caller) {
+ t.Fatalf("a2a card %q does not name the verified caller %s", card, caller)
+ }
+ out = runExample(t, mesh, l, withoutToken, "inference://ollama", "/v1/models")
+ servedBy(t, out, "inference://ollama")
+ models := expectLine(t, out, "200 ")
+ if !strings.Contains(models, `"gemma3"`) || !strings.Contains(models, caller) {
+ t.Fatalf("models %q: want gemma3 owned by the caller %s", models, caller)
+ }
+ })
+ }
+}
+
+// startExampleServer starts a configured serve example and waits for its
+// "serving ... as <peer>" line. Safe to call from several goroutines at
+// once, so it reports failures instead of ending the test.
+func startExampleServer(t *testing.T, name string, cmd *exec.Cmd) (*sdkExampleServer, error) {
+ stderr := &bytes.Buffer{}
+ cmd.Stderr = stderr
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return nil, err
+ }
+ if err := cmd.Start(); err != nil {
+ return nil, fmt.Errorf("failed to start %s serve example: %w", name, err)
+ }
+ t.Cleanup(func() {
+ _ = cmd.Process.Signal(os.Interrupt)
+ done := make(chan struct{})
+ go func() { _ = cmd.Wait(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ _ = cmd.Process.Kill()
+ <-done
+ }
+ if t.Failed() {
+ t.Logf("%s serve example stderr:\n%s", name, stderr.String())
+ }
+ })
+
+ lines := make(chan string, 1)
+ go func() {
+ scanner := bufio.NewScanner(stdout)
+ for scanner.Scan() {
+ if m := servingLine.FindStringSubmatch(scanner.Text()); m != nil {
+ lines <- scanner.Text()
+ return
+ }
+ }
+ close(lines)
+ }()
+ select {
+ case line, ok := <-lines:
+ if !ok {
+ return nil, fmt.Errorf("%s serve example exited before serving\nstderr:\n%s", name, stderr.String())
+ }
+ m := servingLine.FindStringSubmatch(line)
+ for _, want := range []string{"mcp://greeter", "a2a://greeter", "inference://ollama"} {
+ if !strings.Contains(m[1], want) {
+ return nil, fmt.Errorf("%s serve example serves %q, want %s among them", name, m[1], want)
+ }
+ }
+ return &sdkExampleServer{name: name, peerID: m[2]}, nil
+ case <-time.After(30 * time.Second):
+ return nil, fmt.Errorf("%s serve example did not report serving within 30s\nstderr:\n%s", name, stderr.String())
+ }
+}
+
+// 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 {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ cmd, skip := l.cmd(ctx, mesh.root, "call", args...)
+ if skip != "" {
+ t.Fatalf("%s: %s", l.name, skip)
+ }
+ cmd.Env = append(os.Environ(), env...)
+ cmd.Dir = mesh.root
+ stderr := &bytes.Buffer{}
+ 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())
+ }
+ return string(stdout)
+}
+
+// expectLine returns the rest of the first stdout line starting with prefix.
+func expectLine(t *testing.T, out, prefix string) string {
+ t.Helper()
+ for _, line := range strings.Split(out, "\n") {
+ if strings.HasPrefix(line, prefix) {
+ return strings.TrimSpace(strings.TrimPrefix(line, prefix))
+ }
+ }
+ t.Fatalf("no line starting with %q in output:\n%s", prefix, out)
+ return ""
+}
diff --git a/tests/integration/sdk_mesh_test.go b/tests/integration/sdk_mesh_test.go
index 15c977e5..60fed942 100644
--- a/tests/integration/sdk_mesh_test.go
+++ b/tests/integration/sdk_mesh_test.go
@@ -51,6 +51,130 @@ import (
"google.golang.org/protobuf/proto"
)
+// sdkMesh is the real mesh the SDK tests run against: a control plane
+// publishing gossip events, a sam-router, and a sam-node serving the MCP
+// service "calc" from a backend the test runs.
+type sdkMesh struct {
+ root string
+ store *storage.SQLStore
+ publisher *controlplane.P2PMeshAdapter
+ baseURL string
+ adminToken string
+ cpPort int
+ cpPriv ed25519.PrivateKey
+ cpPub ed25519.PublicKey
+ routerAddr string
+ routerPeer string
+ samNode *backgroundNode
+ nodeAPI string
+}
+
+const sdkMeshAdminToken = "test-admin-token"
+
+func startSDKMesh(t *testing.T) *sdkMesh {
+ t.Helper()
+ root := repoRoot(t)
+ oidcURL, mintToken := startCustomMockOIDC(t)
+
+ store, err := storage.NewSQLStore("sqlite", filepath.Join(t.TempDir(), "cp.db"))
+ if err != nil {
+ t.Fatalf("failed to create store: %v", err)
+ }
+ t.Cleanup(func() { _ = store.Close() })
+
+ srv, err := controlplane.NewServer(controlplane.Options{
+ ListenAddr: "127.0.0.1:0",
+ AdminToken: sdkMeshAdminToken,
+ OIDCIssuer: oidcURL,
+ AllowedAudiences: []string{"sam-mesh-audience"},
+ AutoApproveEnrollment: true,
+ }, store)
+ if err != nil {
+ t.Fatalf("failed to create control plane: %v", err)
+ }
+ if err := srv.Start(); err != nil {
+ t.Fatalf("failed to start control plane: %v", err)
+ }
+ t.Cleanup(func() { _ = srv.Close() })
+ baseURL := "http://" + srv.Addr()
+ _, portStr, _ := net.SplitHostPort(srv.Addr())
+ cpPort, _ := strconv.Atoi(portStr)
+
+ // Bans and rotations reach the mesh as gossip events through the routers,
+ // as the sam-control-plane binary publishes them.
+ publisher, err := controlplane.NewMeshPublisher(context.Background(), store, 500*time.Millisecond)
+ if err != nil {
+ t.Fatalf("failed to start mesh event publisher: %v", err)
+ }
+ t.Cleanup(func() { _ = publisher.Close() })
+ srv.SetMeshAdapter(publisher)
+
+ // The router enrolls through OIDC with group "routers" and the node with
+ // user mock-user. Every member holds the node role, which may reach any
+ // service on any target; the SDK members get it from their bootstrap
+ // token and the node from its binding.
+ policyFile := filepath.Join(t.TempDir(), "policy.yaml")
+ policy := fmt.Sprintf(`roles:
+ - name: %s
+ allowed_services: []
+ allowed_targets: ["*"]
+ - name: %s
+ allowed_services: ["*"]
+ allowed_targets: ["*"]
+bindings:
+ - role: %s
+ members: ["group:routers"]
+ - role: %s
+ members: ["user:mock-user"]
+`, api.RoleRouter, api.RoleNode, api.RoleRouter, api.RoleNode)
+ if err := os.WriteFile(policyFile, []byte(policy), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ injectPolicyYAML(t, cpPort, sdkMeshAdminToken, policyFile)
+
+ routerAddr, _ := startRouter(t, t.TempDir(), cpPort, mintToken, "router")
+
+ cpPriv, cpPub, err := store.GetCurrentKey(context.Background())
+ if err != nil {
+ t.Fatalf("failed to load control plane signing key: %v", err)
+ }
+
+ // The Go node: a sam-node enrolled through OIDC, listening on loopback,
+ // serving the MCP service "calc" from a backend this test runs.
+ backend := httptest.NewServer(newBoundaryMCPHandler(t))
+ t.Cleanup(backend.Close)
+ nodeBin := buildBinary(t, "./cmd/sam-node")
+ nodeHome := filepath.Join(t.TempDir(), "node")
+ if err := os.MkdirAll(nodeHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ samNode := launchNode(t, nodeBin,
+ append(os.Environ(), "HOME="+nodeHome, "XDG_CONFIG_HOME="+filepath.Join(nodeHome, ".config")),
+ nodeHome, "run",
+ "--control-plane", baseURL,
+ "--jwt", mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}}),
+ "--allow-loopback",
+ "--api-token-path", tokenPath(t, "node-token"),
+ "--discovery-interval", "100ms",
+ "--config", writeNodeConfig(t, nodeHome, nil, svcDecl{Type: "mcp", Name: "calc", TargetURL: backend.URL}),
+ "--log-level", "debug",
+ )
+ return &sdkMesh{
+ root: root,
+ store: store,
+ publisher: publisher,
+ baseURL: baseURL,
+ adminToken: sdkMeshAdminToken,
+ cpPort: cpPort,
+ cpPriv: cpPriv,
+ cpPub: cpPub,
+ routerAddr: routerAddr,
+ routerPeer: extractPeerID(routerAddr),
+ samNode: samNode,
+ nodeAPI: samNode.waitForAPI(t),
+ }
+}
+
// sdkMember is a running SDK conformance-join runner: a mesh member written
// in another language that the test drives over stdin/stdout. Both runners
// (sdk/js/src/conformance-join.ts, sdk/python/src/agent_mesh/conformance_join.py)
@@ -140,97 +264,12 @@ var sdkMemberLaunchers = []sdkRunner{
// whose toolchain is missing is skipped, and the matrix shrinks to the
// members present.
func TestNativeSDKsMesh(t *testing.T) {
- root := repoRoot(t)
- oidcURL, mintToken := startCustomMockOIDC(t)
-
- store, err := storage.NewSQLStore("sqlite", filepath.Join(t.TempDir(), "cp.db"))
- if err != nil {
- t.Fatalf("failed to create store: %v", err)
- }
- t.Cleanup(func() { _ = store.Close() })
-
- const adminToken = "test-admin-token"
- srv, err := controlplane.NewServer(controlplane.Options{
- ListenAddr: "127.0.0.1:0",
- AdminToken: adminToken,
- OIDCIssuer: oidcURL,
- AllowedAudiences: []string{"sam-mesh-audience"},
- AutoApproveEnrollment: true,
- }, store)
- if err != nil {
- t.Fatalf("failed to create control plane: %v", err)
- }
- if err := srv.Start(); err != nil {
- t.Fatalf("failed to start control plane: %v", err)
- }
- t.Cleanup(func() { _ = srv.Close() })
- baseURL := "http://" + srv.Addr()
- _, portStr, _ := net.SplitHostPort(srv.Addr())
- cpPort, _ := strconv.Atoi(portStr)
-
- // Bans and rotations reach the mesh as gossip events through the routers,
- // as the sam-control-plane binary publishes them.
- publisher, err := controlplane.NewMeshPublisher(context.Background(), store, 500*time.Millisecond)
- if err != nil {
- t.Fatalf("failed to start mesh event publisher: %v", err)
- }
- t.Cleanup(func() { _ = publisher.Close() })
- srv.SetMeshAdapter(publisher)
-
- // The router enrolls through OIDC with group "routers" and the node with
- // user mock-user. Every member holds the node role, which may reach any
- // service on any target; the SDK members get it from their bootstrap
- // token and the node from its binding.
- policyFile := filepath.Join(t.TempDir(), "policy.yaml")
- policy := fmt.Sprintf(`roles:
- - name: %s
- allowed_services: []
- allowed_targets: ["*"]
- - name: %s
- allowed_services: ["*"]
- allowed_targets: ["*"]
-bindings:
- - role: %s
- members: ["group:routers"]
- - role: %s
- members: ["user:mock-user"]
-`, api.RoleRouter, api.RoleNode, api.RoleRouter, api.RoleNode)
- if err := os.WriteFile(policyFile, []byte(policy), 0o600); err != nil {
- t.Fatal(err)
- }
- injectPolicyYAML(t, cpPort, adminToken, policyFile)
-
- routerAddr, _ := startRouter(t, t.TempDir(), cpPort, mintToken, "router")
- routerPeer := extractPeerID(routerAddr)
-
- ctx := context.Background()
- cpPriv, cpPub, err := store.GetCurrentKey(ctx)
- if err != nil {
- t.Fatalf("failed to load control plane signing key: %v", err)
- }
-
- // The Go node: a sam-node enrolled through OIDC, listening on loopback,
- // serving the MCP service "calc" from a backend this test runs.
+ mesh := startSDKMesh(t)
+ root, baseURL, adminToken, cpPort := mesh.root, mesh.baseURL, mesh.adminToken, mesh.cpPort
+ routerAddr, routerPeer, cpPriv, cpPub := mesh.routerAddr, mesh.routerPeer, mesh.cpPriv, mesh.cpPub
+ store, publisher, samNode, nodeAPI := mesh.store, mesh.publisher, mesh.samNode, mesh.nodeAPI
const serviceName = "calc"
- backend := httptest.NewServer(newBoundaryMCPHandler(t))
- t.Cleanup(backend.Close)
- nodeBin := buildBinary(t, "./cmd/sam-node")
- nodeHome := filepath.Join(t.TempDir(), "node")
- if err := os.MkdirAll(nodeHome, 0o755); err != nil {
- t.Fatal(err)
- }
- samNode := launchNode(t, nodeBin,
- append(os.Environ(), "HOME="+nodeHome, "XDG_CONFIG_HOME="+filepath.Join(nodeHome, ".config")),
- nodeHome, "run",
- "--control-plane", baseURL,
- "--jwt", mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}}),
- "--allow-loopback",
- "--api-token-path", tokenPath(t, "node-token"),
- "--discovery-interval", "100ms",
- "--config", writeNodeConfig(t, nodeHome, nil, svcDecl{Type: "mcp", Name: serviceName, TargetURL: backend.URL}),
- "--log-level", "debug",
- )
- nodeAPI := samNode.waitForAPI(t)
+ ctx := context.Background()
// One member per SDK, each listening directly on loopback too so both
// the direct and the relayed path can be walked.