Skip to content

Agent Mesh

sdk/js: publish an agentmesh MCP stdio server to the MCP registry

Mrunal Pendemdc9cfeca49ee
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 41b4ca65..6014fa6b 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -97,6 +97,27 @@ jobs:
*) tag=latest ;;
esac
npm publish --provenance --access public --tag "$tag"
+ - name: Install mcp-publisher
+ run: |
+ curl -fsSL -o "$RUNNER_TEMP/mcp-publisher.tar.gz" \
+ https://github.com/modelcontextprotocol/registry/releases/download/v1.8.7/mcp-publisher_linux_amd64.tar.gz
+ echo "00b21004149a4ce66f0782508ae4a2bce67d1bea395a8da0bd8028159fb59579 $RUNNER_TEMP/mcp-publisher.tar.gz" | sha256sum -c -
+ tar -xzf "$RUNNER_TEMP/mcp-publisher.tar.gz" -C "$RUNNER_TEMP" mcp-publisher
+ echo "$RUNNER_TEMP" >> "$GITHUB_PATH"
+ - name: Publish dev.sam-mesh/mesh to the MCP registry
+ # The registry checks mcpName in the npm package, so this runs after npm publish.
+ # If this version is already listed, skip so the job can be safely retried.
+ working-directory: sdk/js
+ env:
+ MCP_REGISTRY_PRIVATE_KEY: ${{ secrets.MCP_REGISTRY_PRIVATE_KEY }}
+ run: |
+ ver="${SDK_VERSION#v}"
+ if curl -fsS "https://registry.modelcontextprotocol.io/v0.1/servers/dev.sam-mesh%2Fmesh/versions/${ver}" >/dev/null 2>&1; then
+ echo "dev.sam-mesh/mesh ${ver} is already listed in the MCP registry; skipping."
+ exit 0
+ fi
+ mcp-publisher login dns --domain sam-mesh.dev --private-key "$MCP_REGISTRY_PRIVATE_KEY"
+ mcp-publisher publish
publish-sdk-python:
runs-on: ubuntu-latest
diff --git a/hack/sdk-version.sh b/hack/sdk-version.sh
index 67743bb7..0439e00d 100755
--- a/hack/sdk-version.sh
+++ b/hack/sdk-version.sh
@@ -43,6 +43,8 @@ if [[ "${target}" == "all" || "${target}" == "js" ]]; then
# presents to MCP peers follows.
(cd sdk/js && npm version --no-git-tag-version --allow-same-version "${VERSION}" >/dev/null)
sed -i -E "s/^(export const MCP_CLIENT_INFO = \{ name: \"agent-mesh-sdk\", version: \")[^\"]+(\" \};)$/\1${VERSION}\2/" sdk/js/src/mcp.ts
+ # The MCP registry entry and its npm package entry.
+ sed -i -E "s/^( +\"version\": \")[^\"]+(\",)$/\1${VERSION}\2/" sdk/js/server.json
fi
if [[ "${target}" == "all" || "${target}" == "python" ]]; then
@@ -53,7 +55,7 @@ fi
files=()
if [[ "${target}" == "all" || "${target}" == "js" ]]; then
- files+=(sdk/js/package.json sdk/js/src/mcp.ts)
+ files+=(sdk/js/package.json sdk/js/src/mcp.ts sdk/js/server.json)
fi
if [[ "${target}" == "all" || "${target}" == "python" ]]; then
files+=(sdk/python/pyproject.toml sdk/python/src/agent_mesh/__init__.py sdk/python/src/agent_mesh/mcp_client.py)
diff --git a/sdk/js/README.md b/sdk/js/README.md
index 1e067d4f..ce77a34e 100644
--- a/sdk/js/README.md
+++ b/sdk/js/README.md
@@ -24,6 +24,71 @@ Requires Node.js 22.18 or later. In a browser, bundle it with the page
[In a browser](https://google.github.io/agentmesh/docs/guides/native-sdks/#in-a-browser)
section has the details and an example page.
+## MCP client over stdio
+
+The package's `agentmesh` executable joins as its own mesh member and exposes
+five MCP tools: `get_mesh_info`, `discover_remote_services`, `find_remote_tools`,
+`describe_remote_tool` and `call_remote_tool`. A stdio-capable MCP client starts
+and stops the process; no node daemon is needed for this caller. Providers still
+publish their services through `agentmesh-node`.
+
+To try the executable from a source checkout:
+
+```bash
+cd sdk/js
+npm ci
+npm run build
+```
+
+Use absolute paths in your MCP client's configuration:
+
+```json
+{
+ "mcpServers": {
+ "agentmesh": {
+ "command": "node",
+ "args": ["/absolute/path/to/agentmesh/sdk/js/dist/cli.js"],
+ "env": {
+ "AGENTMESH_CONTROL_PLANE_URL": "https://your-control-plane.example",
+ "AGENTMESH_BOOTSTRAP_TOKEN_PATH": "/absolute/path/to/join-token",
+ "AGENTMESH_STATE_DIR": "/absolute/path/to/this-client-identity"
+ }
+ }
+ }
+}
+```
+
+Get the control plane URL and token file from your mesh operator or
+[`agentmesh-one`](https://google.github.io/agentmesh/docs/guides/native-sdks/).
+Alternatively, set `AGENTMESH_JWT_PATH` to a workload/OIDC token file; do not set
+both token paths. Credentials are read from files, never command-line values.
+
+The first run enrolls and saves its identity; later runs resume from the state
+directory without the bootstrap token. JWT enrollment rereads the token file
+when refreshing. Use a distinct state directory for each client identity and
+mesh; do not run multiple processes against the same directory. The default is
+`~/.config/agentmesh/mcp`. Plain HTTP is allowed on loopback only unless
+`AGENTMESH_INSECURE_CONTROL_PLANE=true` explicitly permits it elsewhere.
+
+Stdout contains only MCP messages; diagnostics go to stderr. Closing stdin or
+sending SIGINT/SIGTERM shuts down the mesh session. Tool calls use the member's
+existing authenticated streams and policy, including provider label checks.
+Remote tool results retain text, non-text content, structured output and errors.
+Discovery follows tool pagination, rejects looping catalogs and bounds each
+search to 64 providers, 256 services per provider, 256 tools per service and
+1024 results. Requests have a 10-second deadline; narrow a large search by peer
+or service. `intent` is accepted but ignored, matching the node's current tool.
+
+This member publishes no services, so it has no `list_local_services` tool.
+Inference and A2A discovery return metadata, but this executable provides no
+HTTP proxy, `/v1` endpoint, local socket or `local_proxy_url`. Use an SDK client
+or an `agentmesh-node` HTTP proxy to invoke those protocols.
+
+This source implementation is the executable portion of
+[#544](https://github.com/google/agentmesh/issues/544). Official MCP registry
+registration and release automation are separate work; this configuration does
+not depend on a published registry entry.
+
## Use
Both programs below are in
diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.json
index 8fdf3c13..1905f752 100644
--- a/sdk/js/package-lock.json
+++ b/sdk/js/package-lock.json
@@ -32,6 +32,9 @@
"uint8arrays": "^6.1.1",
"zod": "^4.6.5"
},
+ "bin": {
+ "agentmesh": "dist/cli.js"
+ },
"devDependencies": {
"@a2a-js/sdk": "^1.3.0",
"@bufbuild/protoc-gen-es": "^2.16.0",
diff --git a/sdk/js/package.json b/sdk/js/package.json
index db58b0ee..f35ecefa 100644
--- a/sdk/js/package.json
+++ b/sdk/js/package.json
@@ -9,6 +9,9 @@
"directory": "sdk/js"
},
"type": "module",
+ "bin": {
+ "agentmesh": "./dist/cli.js"
+ },
"engines": {
"node": ">=22.18"
},
@@ -72,5 +75,6 @@
"esbuild": "^0.28.2",
"express": "^5.2.1",
"typescript": "^7.0.2"
- }
+ },
+ "mcpName": "dev.sam-mesh/mesh"
}
diff --git a/sdk/js/server.json b/sdk/js/server.json
new file mode 100644
index 00000000..ced6d4aa
--- /dev/null
+++ b/sdk/js/server.json
@@ -0,0 +1,55 @@
+{
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "name": "dev.sam-mesh/mesh",
+ "title": "Agent Mesh",
+ "description": "Discover and call remote MCP tools as your own authenticated Agent Mesh member.",
+ "repository": {
+ "url": "https://github.com/google/agentmesh",
+ "source": "github",
+ "subfolder": "sdk/js"
+ },
+ "version": "0.1.0",
+ "packages": [
+ {
+ "registryType": "npm",
+ "registryBaseUrl": "https://registry.npmjs.org",
+ "identifier": "@agentmesh-p2p/sdk",
+ "version": "0.1.0",
+ "runtimeHint": "npx",
+ "transport": {
+ "type": "stdio"
+ },
+ "environmentVariables": [
+ {
+ "name": "AGENTMESH_CONTROL_PLANE_URL",
+ "description": "Control plane URL supplied by your mesh operator. HTTPS is required beyond loopback unless explicitly permitted below.",
+ "format": "string",
+ "isRequired": true
+ },
+ {
+ "name": "AGENTMESH_BOOTSTRAP_TOKEN_PATH",
+ "description": "Absolute path to a bootstrap token file for first enrollment. Set this OR AGENTMESH_JWT_PATH; leave both empty only when resuming saved credentials.",
+ "format": "filepath",
+ "isSecret": true
+ },
+ {
+ "name": "AGENTMESH_JWT_PATH",
+ "description": "Absolute path to an OIDC/workload token file. Alternative to the bootstrap token; reread during credential refresh.",
+ "format": "filepath",
+ "isSecret": true
+ },
+ {
+ "name": "AGENTMESH_STATE_DIR",
+ "description": "Absolute directory for this client identity. Use a distinct directory per client and mesh. If omitted, uses ~/.config/agentmesh/mcp.",
+ "format": "filepath"
+ },
+ {
+ "name": "AGENTMESH_INSECURE_CONTROL_PLANE",
+ "description": "Allow plaintext HTTP beyond loopback. Development only: exposes enrollment traffic to the network.",
+ "format": "boolean",
+ "default": "false"
+ }
+ ]
+ }
+ ]
+}
diff --git a/sdk/js/src/cli.ts b/sdk/js/src/cli.ts
new file mode 100644
index 00000000..f5a106ae
--- /dev/null
+++ b/sdk/js/src/cli.ts
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+// 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.
+
+import { readFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { isAbsolute, join } from "node:path";
+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
+import { AgentMesh, type EnrollOptions } from "./mesh.ts";
+import { createMeshMCPServer } from "./mcp-server.ts";
+import type { MeshSession } from "./session.ts";
+
+function options(): EnrollOptions {
+ const env = process.env;
+ const controlPlaneUrl = env.AGENTMESH_CONTROL_PLANE_URL?.trim();
+ if (!controlPlaneUrl) throw new Error("AGENTMESH_CONTROL_PLANE_URL is required");
+ if (env.AGENTMESH_BOOTSTRAP_TOKEN_PATH && env.AGENTMESH_JWT_PATH) {
+ throw new Error("set only one of AGENTMESH_BOOTSTRAP_TOKEN_PATH and AGENTMESH_JWT_PATH");
+ }
+ if (env.AGENTMESH_INSECURE_CONTROL_PLANE && !["true", "false"].includes(env.AGENTMESH_INSECURE_CONTROL_PLANE)) {
+ throw new Error("AGENTMESH_INSECURE_CONTROL_PLANE must be true or false");
+ }
+ // A client launches this from any working directory; a relative path would
+ // silently read credentials or enrol an identity somewhere unexpected.
+ for (const name of ["AGENTMESH_BOOTSTRAP_TOKEN_PATH", "AGENTMESH_JWT_PATH", "AGENTMESH_STATE_DIR"] as const) {
+ if (env[name] && !isAbsolute(env[name])) throw new Error(`${name} must be an absolute path`);
+ }
+ return {
+ controlPlaneUrl,
+ bootstrapTokenPath: env.AGENTMESH_BOOTSTRAP_TOKEN_PATH || undefined,
+ jwtPath: env.AGENTMESH_JWT_PATH || undefined,
+ stateDir: env.AGENTMESH_STATE_DIR || join(homedir(), ".config", "agentmesh", "mcp"),
+ allowInsecure: env.AGENTMESH_INSECURE_CONTROL_PLANE === "true",
+ };
+}
+
+async function main(): Promise<void> {
+ if (process.argv.length > 2) {
+ if (process.argv.length !== 3 || !["--help", "-h"].includes(process.argv[2]!)) {
+ throw new Error("agentmesh accepts no arguments other than --help; configure it through AGENTMESH_* environment variables");
+ }
+ console.error("agentmesh: MCP over stdio\n" +
+ "AGENTMESH_CONTROL_PLANE_URL Mesh control plane URL (required)\n" +
+ "AGENTMESH_BOOTSTRAP_TOKEN_PATH Bootstrap token file for first enrollment\n" +
+ "AGENTMESH_JWT_PATH OIDC/workload token file, read again on refresh\n" +
+ "AGENTMESH_STATE_DIR Identity directory (default: ~/.config/agentmesh/mcp)\n" +
+ "AGENTMESH_INSECURE_CONTROL_PLANE true permits plaintext HTTP beyond loopback (default: false)");
+ return;
+ }
+ const config = options();
+ const { version } = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")) as { version: string };
+ const abort = new AbortController();
+ let stop!: () => void;
+ const stopped = new Promise<void>((resolve) => { stop = () => { abort.abort(); resolve(); }; });
+ process.once("SIGINT", stop);
+ process.once("SIGTERM", stop);
+ process.stdin.once("end", stop);
+ let session: MeshSession | undefined;
+ const ready = AgentMesh.enroll({
+ ...config,
+ signal: abort.signal,
+ // EnrollOptions.signal bounds pending approval, not every HTTP request.
+ // The executable owns this client: shutdown must also cancel enrollment,
+ // credential resume and key fetches while the control plane is silent.
+ fetch: (input, init) => fetch(input, {
+ ...init,
+ signal: AbortSignal.any([abort.signal, ...(init?.signal ? [init.signal] : [])]),
+ }),
+ }).then(async (mesh) => {
+ session = await mesh.join({ signal: abort.signal });
+ return session;
+ });
+ // Handle startup failure immediately, including before a client calls a tool.
+ void ready.catch((err: unknown) => {
+ if (!abort.signal.aborted) {
+ console.error(`agentmesh: ${err instanceof Error ? err.message : String(err)}`);
+ process.exitCode = 1;
+ }
+ stop();
+ });
+ const server = createMeshMCPServer(ready, version);
+ server.server.onclose = stop;
+ try {
+ await server.connect(new StdioServerTransport());
+ await stopped;
+ } finally {
+ stop();
+ try {
+ await server.close();
+ } finally {
+ await ready.catch(() => undefined);
+ try {
+ await session?.close();
+ } finally {
+ process.removeListener("SIGINT", stop);
+ process.removeListener("SIGTERM", stop);
+ process.stdin.removeListener("end", stop);
+ }
+ }
+ }
+}
+
+void main().catch((err: unknown) => {
+ console.error(`agentmesh: ${err instanceof Error ? err.message : String(err)}`);
+ process.exitCode = 1;
+});
diff --git a/sdk/js/src/mcp-server.test.ts b/sdk/js/src/mcp-server.test.ts
new file mode 100644
index 00000000..f4dbee73
--- /dev/null
+++ b/sdk/js/src/mcp-server.test.ts
@@ -0,0 +1,285 @@
+// 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.
+
+import assert from "node:assert/strict";
+import { test, type TestContext } from "node:test";
+import { once } from "node:events";
+import { createServer } from "node:http";
+import { mkdtemp, writeFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { spawn } from "node:child_process";
+import { peerIdFromString } from "@libp2p/peer-id";
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { Server } from "@modelcontextprotocol/sdk/server/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import { CallToolRequestSchema, CallToolResultSchema, ListToolsRequestSchema, type Tool } from "@modelcontextprotocol/sdk/types.js";
+import { createMeshMCPServer } from "./mcp-server.ts";
+import { Identity } from "./identity.ts";
+import { AuthRejectedError } from "./auth.ts";
+import type { MCPSessionOptions, MCPSession } from "./mcp.ts";
+
+// Protocol-level fixture: real MCP client/server transports, a stub mesh
+// session. Authentication and persisted enrollment are tested with Go nodes
+// in TestNativeSDKMCPStdio, not simulated here.
+async function fixture(t: TestContext, mode = "normal") {
+ const peerId = Identity.generate().peerId;
+ const self = Identity.generate().peerId;
+ const stalled = Identity.generate().peerId;
+ const calls: { service: string; name: string; args: unknown; labels: unknown }[] = [];
+ let opened = 0, closed = 0;
+ let markStarted!: () => void, markFinished!: () => void;
+ const started = new Promise<void>((resolve) => { markStarted = resolve; });
+ const finished = new Promise<void>((resolve) => { markFinished = resolve; });
+ const tool: Tool = { name: "add", description: "add numbers", inputSchema: { type: "object", properties: { a: { type: "number" } } }, outputSchema: { type: "object", properties: { answer: { type: "number" } } } };
+ const session = {
+ peerId: self, routers: [], isHeldRouter: () => false,
+ node: { getPeers: () => [peerIdFromString(peerId)] },
+ async discover() { return mode === "stalled" ? [{ peerId: stalled, addrs: [] }, { peerId, addrs: [] }] : [{ peerId, addrs: [] }]; },
+ async openMCP(peer: unknown, service: string, options: MCPSessionOptions = {}): Promise<MCPSession> {
+ if ((peer as { peerId?: string }).peerId === stalled) {
+ // A provider that never answers; only the caller's deadline ends it.
+ return new Promise<never>((_resolve, reject) => { options.signal?.addEventListener("abort", () => { reject(options.signal!.reason); }, { once: true }); });
+ }
+ if (service === "mcp://denied") throw new AuthRejectedError(peerId, "not granted");
+ opened++;
+ const remote = new Server({ name: "fixture", version: "1" }, { capabilities: { tools: {} } });
+ remote.setRequestHandler(ListToolsRequestSchema, async (req) => {
+ if (mode === "loop") return { tools: [], nextCursor: "again" };
+ if (req.params?.cursor === undefined) return { tools: [{ ...tool, name: "first" }], nextCursor: "second" };
+ return { tools: [tool] };
+ });
+ remote.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
+ if (mode === "hang") {
+ markStarted();
+ await new Promise<void>((resolve) => { extra.signal.addEventListener("abort", () => { resolve(); }, { once: true }); });
+ }
+ calls.push({ service, name: req.params.name, args: req.params.arguments, labels: options.requiredLabels });
+ if (service === "system://mesh.catalog") return { content: [{ type: "text", text: JSON.stringify([{ type: 1, name: "calc", description: "calculator" }, { type: 1, name: "denied" }]) }] };
+ return { content: [{ type: "text", text: "3" }, { type: "image", data: "AA==", mimeType: "image/png" }], structuredContent: { answer: 3 }, isError: mode === "error" };
+ });
+ const [a, b] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: "fixture-client", version: "1" });
+ await remote.connect(a);
+ await client.connect(b);
+ return {
+ client, provider: {} as MCPSession["provider"],
+ async close() { closed++; await client.close(); await remote.close(); markFinished(); },
+ };
+ },
+ };
+ const server = createMeshMCPServer(session, "1");
+ const [a, b] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: "test", version: "1" });
+ await server.connect(a);
+ await client.connect(b);
+ t.after(async () => { await client.close(); await server.close(); assert.equal(closed, opened, "every remote session closes"); });
+ return { client, calls, peerId, self, stalled, tool, started, finished };
+}
+
+function payload(result: unknown): unknown {
+ const content = CallToolResultSchema.parse(result).content[0];
+ assert.equal(content?.type, "text");
+ return JSON.parse((content as { text: string }).text);
+}
+
+test("stdio surface exposes exactly the five caller tools and their parameter contracts", async (t) => {
+ const { client } = await fixture(t);
+ const expected: Record<string, string[]> = {
+ get_mesh_info: [], discover_remote_services: ["type", "name", "limit", "offset"],
+ find_remote_tools: ["intent", "peer_id", "service_name", "tool_name"],
+ describe_remote_tool: ["peer_id", "tool_name"],
+ call_remote_tool: ["peer_id", "tool_name", "arguments", "required_labels"],
+ };
+ const { tools } = await client.listTools();
+ assert.deepEqual(tools.map((x) => x.name).sort(), Object.keys(expected).sort());
+ for (const tool of tools) assert.deepEqual(Object.keys(tool.inputSchema.properties ?? {}).sort(), expected[tool.name]!.sort());
+});
+
+test("remote calls preserve structured/non-text results and pass required labels to authenticated open", async (t) => {
+ const { client, calls, peerId } = await fixture(t);
+ const result = await client.callTool({ name: "call_remote_tool", arguments: { peer_id: peerId, tool_name: "mcp://calc/add", arguments: { a: 1, b: 2 }, required_labels: "region=eu,team=platform" } });
+ assert.deepEqual(result.structuredContent, { answer: 3 });
+ assert.equal((result.content as { type: string }[])[1]?.type, "image");
+ assert.deepEqual(calls[0]?.args, { a: 1, b: 2 });
+ assert.deepEqual({ ...calls[0]?.labels as object }, { region: "eu", team: "platform" });
+ assert.equal(calls[0]?.service, "mcp://calc");
+ assert.equal(calls[0]?.name, "add");
+});
+
+test("remote isError stays an MCP tool failure", async (t) => {
+ const { client, peerId } = await fixture(t, "error");
+ const result = await client.callTool({ name: "call_remote_tool", arguments: { peer_id: peerId, tool_name: "mcp://calc/add" } });
+ assert.equal(result.isError, true);
+});
+
+test("invalid names, stringified arguments and malformed labels never invoke a remote tool", async (t) => {
+ const { client, calls, peerId } = await fixture(t);
+ for (const args of [
+ { peer_id: peerId, tool_name: "system://catalog/list_local_services" },
+ { peer_id: peerId, tool_name: "mcp://calc/add", arguments: "{}" },
+ { peer_id: peerId, tool_name: "mcp://calc/add", required_labels: "region" },
+ { peer_id: peerId, tool_name: "mcp://calc/add", required_labels: "region=eu,region=us" },
+ { peer_id: peerId, tool_name: "mcp://calc?scope=all/add" },
+ { peer_id: peerId, tool_name: "mcp://calc/" },
+ { peer_id: "not-a-peer", tool_name: "mcp://calc/add" },
+ ]) {
+ const result = await client.callTool({ name: "call_remote_tool", arguments: args });
+ assert.equal(result.isError, true, JSON.stringify(args));
+ }
+ assert.equal(calls.length, 0);
+});
+
+test("describe follows pagination and preserves both schemas", async (t) => {
+ const { client, peerId, tool } = await fixture(t);
+ assert.deepEqual(payload(await client.callTool({ name: "describe_remote_tool", arguments: { peer_id: peerId, tool_name: "mcp://calc/add" } })), {
+ peer_id: peerId, tool_name: "mcp://calc/add", description: tool.description,
+ input_schema: tool.inputSchema, output_schema: tool.outputSchema,
+ });
+});
+
+test("looping pagination fails and closes the remote session", async (t) => {
+ const { client, peerId } = await fixture(t, "loop");
+ const result = await client.callTool({ name: "describe_remote_tool", arguments: { peer_id: peerId, tool_name: "mcp://calc/add" } });
+ assert.equal(result.isError, true);
+ assert.match(JSON.stringify(result), /unbounded tool catalog/);
+});
+
+test("find confirms tools, applies filters, omits unauthorized services and rejects self", async (t) => {
+ const { client, peerId, self } = await fixture(t);
+ const result = await client.callTool({ name: "find_remote_tools", arguments: { tool_name: "add", intent: "accepted but ignored" } });
+ assert.deepEqual(payload(result), [{ peer_id: peerId, tool_name: "mcp://calc/add", description: "add numbers" }]);
+ assert.deepEqual(payload(await client.callTool({ name: "find_remote_tools", arguments: { service_name: "missing" } })), []);
+ assert.equal((await client.callTool({ name: "find_remote_tools", arguments: { peer_id: self } })).isError, true);
+});
+
+test("discovery returns service metadata without inventing an HTTP proxy", async (t) => {
+ const { client, calls, peerId } = await fixture(t);
+ // A named lookup is answered by the directory alone, as in agentmesh-node.
+ assert.deepEqual(payload(await client.callTool({ name: "discover_remote_services", arguments: { type: "MCP", name: "calc" } })), [{ peer_id: peerId, srv_name: "mcp://calc", srv_description: "" }]);
+ assert.equal(calls.length, 0);
+ assert.deepEqual(payload(await client.callTool({ name: "discover_remote_services", arguments: { type: "mcp" } })), [
+ { peer_id: peerId, srv_name: "mcp://calc", srv_description: "calculator" },
+ { peer_id: peerId, srv_name: "mcp://denied", srv_description: "" },
+ ]);
+ assert.deepEqual(payload(await client.callTool({ name: "discover_remote_services", arguments: { type: "mcp", offset: 99 } })), []);
+ assert.equal((await client.callTool({ name: "discover_remote_services", arguments: { type: "invalid" } })).isError, true);
+});
+
+test("CLI configuration failures and help write no non-MCP stdout", async () => {
+ for (const args of [[], ["--help"], ["--token", "must-not-appear"]]) {
+ const env = { ...process.env };
+ for (const key of Object.keys(env)) if (key.startsWith("AGENTMESH_")) delete env[key];
+ const child = spawn(process.execPath, [new URL("./cli.js", import.meta.url).pathname, ...args], { env });
+ let stdout = "", stderr = "";
+ child.stdout.on("data", (data) => { stdout += String(data); });
+ child.stderr.on("data", (data) => { stderr += String(data); });
+ child.stdin.end();
+ const code = await new Promise<number | null>((resolve, reject) => { child.once("exit", resolve); child.once("error", reject); });
+ assert.equal(code, args[0] === "--help" ? 0 : 1);
+ assert.equal(stdout, "");
+ assert.ok(stderr.includes("AGENTMESH_"));
+ assert.ok(!stderr.includes("must-not-appear"));
+ }
+});
+
+
+test("CLI rejects relative credential and identity paths", async () => {
+ for (const name of ["AGENTMESH_BOOTSTRAP_TOKEN_PATH", "AGENTMESH_JWT_PATH", "AGENTMESH_STATE_DIR"]) {
+ const env: NodeJS.ProcessEnv = { ...process.env };
+ for (const key of Object.keys(env)) if (key.startsWith("AGENTMESH_")) delete env[key];
+ Object.assign(env, { AGENTMESH_CONTROL_PLANE_URL: "http://127.0.0.1:9", [name]: "relative/path" });
+ const child = spawn(process.execPath, [new URL("./cli.js", import.meta.url).pathname], { env });
+ let stdout = "", stderr = "";
+ child.stdout.on("data", (data) => { stdout += String(data); });
+ child.stderr.on("data", (data) => { stderr += String(data); });
+ child.stdin.end();
+ const code = await new Promise<number | null>((resolve, reject) => { child.once("exit", resolve); child.once("error", reject); });
+ assert.equal(code, 1, name);
+ assert.equal(stdout, "");
+ assert.match(stderr, new RegExp(`${name} must be an absolute path`));
+ }
+});
+
+test("tool names retain path segments after the service name", async (t) => {
+ const { client, calls, peerId } = await fixture(t);
+ await client.callTool({ name: "call_remote_tool", arguments: { peer_id: peerId, tool_name: "mcp://calc/math/add" } });
+ assert.equal(calls[0]?.service, "mcp://calc");
+ assert.equal(calls[0]?.name, "math/add");
+});
+
+test("tool names may contain query and fragment characters", async (t) => {
+ const { client, calls, peerId } = await fixture(t);
+ await client.callTool({ name: "call_remote_tool", arguments: { peer_id: peerId, tool_name: "mcp://calc/add?x#y" } });
+ assert.equal(calls[0]?.service, "mcp://calc");
+ assert.equal(calls[0]?.name, "add?x#y");
+});
+
+test("a stalled provider costs only its own row in mesh-wide discovery", { timeout: 15_000 }, async (t) => {
+ const { client, peerId, stalled } = await fixture(t, "stalled");
+ const rows = payload(await client.callTool({ name: "find_remote_tools", arguments: {} })) as { peer_id: string; tool_name?: string; error?: string }[];
+ assert.deepEqual(rows.filter((row) => !row.error).map((row) => [row.peer_id, row.tool_name]), [[peerId, "mcp://calc/add"], [peerId, "mcp://calc/first"]]);
+ assert.equal(rows.find((row) => row.peer_id === stalled)?.error !== undefined, true);
+ assert.deepEqual(payload(await client.callTool({ name: "discover_remote_services", arguments: { type: "mcp" } })), [
+ { peer_id: peerId, srv_name: "mcp://calc", srv_description: "calculator" },
+ { peer_id: peerId, srv_name: "mcp://denied", srv_description: "" },
+ ]);
+});
+
+test("cancelling a remote call closes its mesh session", { timeout: 2000 }, async (t) => {
+ const { client, peerId, started, finished } = await fixture(t, "hang");
+ const abort = new AbortController();
+ const result = client.callTool({ name: "call_remote_tool", arguments: { peer_id: peerId, tool_name: "mcp://calc/add" } }, undefined, { signal: abort.signal });
+ const rejected = assert.rejects(result);
+ await started;
+ abort.abort();
+ await rejected;
+ await finished;
+});
+
+test("EOF and SIGTERM abort enrollment without leaving a process running", { timeout: 5000 }, async (t) => {
+ const directory = await mkdtemp(join(tmpdir(), "agentmesh-stdio-test-"));
+ t.after(() => rm(directory, { recursive: true, force: true }));
+ const token = join(directory, "token");
+ await writeFile(token, "test-bootstrap-token", { mode: 0o600 });
+ for (const stop of ["eof", "signal"]) {
+ let markRequested!: () => void;
+ const requested = new Promise<void>((resolve) => { markRequested = resolve; });
+ const controlPlane = createServer((_req, _res) => { markRequested(); });
+ controlPlane.listen(0, "127.0.0.1");
+ await once(controlPlane, "listening");
+ t.after(() => { controlPlane.closeAllConnections(); controlPlane.close(); });
+ const address = controlPlane.address();
+ assert.ok(address && typeof address !== "string");
+ const env = { ...process.env };
+ for (const key of Object.keys(env)) if (key.startsWith("AGENTMESH_")) delete env[key];
+ Object.assign(env, {
+ AGENTMESH_CONTROL_PLANE_URL: `http://127.0.0.1:${address.port}`,
+ AGENTMESH_STATE_DIR: join(directory, stop), AGENTMESH_BOOTSTRAP_TOKEN_PATH: token,
+ });
+ const child = spawn(process.execPath, [new URL("./cli.js", import.meta.url).pathname], { env });
+ t.after(() => { if (child.exitCode === null) child.kill("SIGKILL"); });
+ let stdout = "", stderr = "";
+ child.stdout.on("data", (data) => { stdout += String(data); });
+ child.stderr.on("data", (data) => { stderr += String(data); });
+ const closed = once(child, "close");
+ await requested;
+ if (stop === "eof") child.stdin.end();
+ else child.kill("SIGTERM");
+ const [code, signal] = await closed;
+ assert.equal(code, 0, stderr);
+ assert.equal(signal, null);
+ assert.equal(stdout, "");
+ }
+});
diff --git a/sdk/js/src/mcp-server.ts b/sdk/js/src/mcp-server.ts
new file mode 100644
index 00000000..b4e540ee
--- /dev/null
+++ b/sdk/js/src/mcp-server.ts
@@ -0,0 +1,306 @@
+// 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.
+
+// The local MCP surface for SDK members. All remote operations use the
+// session's authenticated streams and the member's own credential.
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import type { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
+import { CallToolResultSchema, type CallToolResult, type Tool } from "@modelcontextprotocol/sdk/types.js";
+import { z } from "zod";
+import { BASELINE_DATALOG } from "./gen/datalog.ts";
+import { AuthRejectedError } from "./auth.ts";
+import { canonicalPeerId } from "./identity.ts";
+import type { MeshSession, Peer } from "./session.ts";
+import type { MCPSessionOptions } from "./mcp.ts";
+
+type Session = Pick<MeshSession, "peerId" | "routers" | "isHeldRouter" | "discover" | "openMCP"> & {
+ node: Pick<MeshSession["node"], "getPeers">;
+};
+
+const MAX_PROVIDERS = 64;
+const MAX_SERVICES = 256;
+const MAX_TOOLS = 256;
+const MAX_RESULTS = 1024;
+// Bounds enrollment, directory lookups and single-peer queries.
+const REQUEST_TIMEOUT_MS = 10_000;
+// Match agentmesh-node: each provider in a mesh-wide fan-out gets its own
+// deadline, at most 8 at a time, and a slow one only costs its own row.
+const PEER_TIMEOUT_MS = 5_000;
+const FANOUT = 8;
+// Opening a call stream is bounded like the node's dial; the call itself is
+// bounded by the MCP client's cancellation, as tools may run for minutes.
+const OPEN_TIMEOUT_MS = 15_000;
+const CALL_TIMEOUT_MS = 30 * 60_000;
+const serviceSchema = z.object({
+ type: z.number().int(), name: z.string().min(1), description: z.string().optional(),
+});
+type Service = z.infer<typeof serviceSchema>;
+type ToolRow = { peer_id: string; tool_name?: string; description?: string; error?: string };
+const types: Record<string, number> = { mcp: 1, inference: 2, a2a: 3 };
+
+function text(value: unknown): CallToolResult {
+ return { content: [{ type: "text", text: JSON.stringify(value) }] };
+}
+
+function serviceTarget(name: string, type = "mcp"): string {
+ const target = name.includes("://") ? name : `${type}://${name}`;
+ if (!target.startsWith(`${type}://`) || target.slice(type.length + 3).length === 0) {
+ throw new Error(`expected a ${type} service name`);
+ }
+ return target;
+}
+
+function toolTarget(name: string): { service: string; tool: string } {
+ // Split at the first path slash: MCP tool names themselves can contain '/',
+ // '?' or '#'. Only the service name is a path segment on the wire.
+ const match = /^mcp:\/\/([^/?#]+)\/(.+)$/s.exec(name);
+ if (!match) throw new Error("tool_name must be mcp://<service>/<tool>");
+ return { service: `mcp://${match[1]}`, tool: match[2]! };
+}
+
+function requiredLabels(value: string): Record<string, string> {
+ const labels: Record<string, string> = Object.create(null) as Record<string, string>;
+ if (value.trim() === "") return labels;
+ for (const pair of value.split(",")) {
+ if (pair.trim() === "") continue;
+ const parts = pair.trim().split("=");
+ if (parts.length !== 2 || !parts[0]?.trim() || !parts[1]?.trim()) {
+ throw new Error("required_labels must contain comma-separated key=value pairs");
+ }
+ const key = parts[0].trim(), val = parts[1].trim();
+ // Match api.ValidateLabelKey / ValidateLabelValue and the node parser.
+ if (!/^[a-zA-Z0-9_.-]{1,63}$/.test(key) || new TextEncoder().encode(val).length > 255 || /[\p{Cc}"\\]/u.test(val)) {
+ throw new Error("invalid required label key or value");
+ }
+ if (Object.hasOwn(labels, key)) throw new Error(`duplicate required label: ${key}`);
+ labels[key] = val;
+ }
+ if (Object.keys(labels).length === 0) throw new Error("expected at least one required label");
+ return labels;
+}
+
+async function call(session: Session, peer: Peer, service: string, name: string, args: Record<string, unknown>, options: MCPSessionOptions & { signal: AbortSignal }, request: RequestOptions = { signal: options.signal }): Promise<CallToolResult> {
+ const remote = await session.openMCP(peer, service, options);
+ try {
+ return CallToolResultSchema.parse(await remote.client.callTool({ name, arguments: args }, undefined, request));
+ } finally {
+ await remote.close();
+ }
+}
+
+async function catalog(session: Session, peer: Peer, type: string, signal: AbortSignal): Promise<Service[]> {
+ const result = await call(session, peer, `system://${BASELINE_DATALOG.catalog_target}`, "list_local_services", { type }, { signal });
+ const content = result.content[0];
+ if (result.isError || content?.type !== "text") throw new Error("provider refused its service catalog");
+ return z.array(serviceSchema).max(MAX_SERVICES).parse(JSON.parse(content.text)).filter((s) => s.type === types[type]);
+}
+
+// Follow MCP cursors, but never accept an unbounded or looping catalog.
+async function tools(session: Session, peer: Peer, service: string, signal: AbortSignal): Promise<Tool[]> {
+ const remote = await session.openMCP(peer, service, { signal });
+ try {
+ const result: Tool[] = [];
+ const cursors = new Set<string>();
+ let cursor: string | undefined;
+ do {
+ signal.throwIfAborted();
+ const page = await remote.client.listTools(cursor === undefined ? {} : { cursor }, { signal });
+ result.push(...page.tools);
+ if (result.length > MAX_TOOLS) throw new Error(`provider exceeds ${MAX_TOOLS} tools per service`);
+ cursor = page.nextCursor;
+ if (cursor !== undefined) {
+ if (cursors.has(cursor) || cursors.size >= MAX_TOOLS) throw new Error("provider returned an unbounded tool catalog");
+ cursors.add(cursor);
+ }
+ } while (cursor !== undefined);
+ return result;
+ } finally {
+ await remote.close();
+ }
+}
+
+// Do not keep a cancelled MCP request waiting for enrollment or directory lookup.
+async function withSignal<T>(value: T | Promise<T>, signal: AbortSignal): Promise<T> {
+ signal.throwIfAborted();
+ return new Promise<T>((resolve, reject) => {
+ const abort = () => { reject(signal.reason); };
+ signal.addEventListener("abort", abort, { once: true });
+ Promise.resolve(value).then(resolve, reject).finally(() => { signal.removeEventListener("abort", abort); });
+ });
+}
+
+class ResultLimitError extends Error {
+ constructor() { super("too many tools; narrow the search by peer or service"); }
+}
+
+// Runs fn for each peer, FANOUT at a time, each under its own deadline. Only
+// the caller's cancellation aborts the whole fan-out.
+async function fanOut<P extends Peer, R>(peers: P[], signal: AbortSignal, fn: (peer: P, signal: AbortSignal) => Promise<R>): Promise<PromiseSettledResult<R>[]> {
+ const results: PromiseSettledResult<R>[] = [];
+ let next = 0;
+ const worker = async () => {
+ for (let i = next++; i < peers.length; i = next++) {
+ signal.throwIfAborted();
+ try {
+ results[i] = { status: "fulfilled", value: await fn(peers[i]!, AbortSignal.any([signal, AbortSignal.timeout(PEER_TIMEOUT_MS)])) };
+ } catch (reason) {
+ results[i] = { status: "rejected", reason };
+ }
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(FANOUT, peers.length) }, worker));
+ signal.throwIfAborted();
+ return results;
+}
+
+/** The same five caller tools as agentmesh-node; an SDK member hosts no services. */
+export function createMeshMCPServer(ready: Session | Promise<Session>, version: string): McpServer {
+ const server = new McpServer({ name: "agentmesh", version }, { instructions:
+ "Use find_remote_tools, then describe_remote_tool to learn the input schema, then call_remote_tool. " +
+ "Calls use this SDK member's identity and mesh policy. This stdio server exposes no local HTTP proxy, inference endpoint or hosted services.",
+ });
+
+ server.registerTool("get_mesh_info", { description: "Get information about the mesh network", inputSchema: {} }, async (_args, extra) => {
+ const signal = AbortSignal.any([extra.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
+ const s = await withSignal(ready, signal);
+ const routers = s.routers.filter((r) => s.isHeldRouter(r.peerId)).map((r) => r.peerId).sort();
+ return text({ peer_id: s.peerId, connected_peers: s.node.getPeers().map((p) => p.toString()).sort(), attached_routers: routers, router_peer_id: routers[0] ?? "" });
+ });
+
+ server.registerTool("discover_remote_services", {
+ description: "Discover remote services by type and optional name. Returns peer_id, srv_name and srv_description. This SDK member has no local_proxy_url; inference and A2A services require an SDK client or an agentmesh-node HTTP proxy.",
+ inputSchema: {
+ type: z.string().describe("Required. One of: mcp, inference, a2a."),
+ name: z.string().optional().describe("Optional service name. Omit to list all services of the given type."),
+ limit: z.number().int().optional().describe("Optional limit for pagination. Defaults to 20."),
+ offset: z.number().int().optional().describe("Optional offset for pagination. Defaults to 0."),
+ },
+ }, async (args, extra) => {
+ const setup = AbortSignal.any([extra.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
+ const s = await withSignal(ready, setup);
+ const type = args.type.toLowerCase();
+ if (types[type] === undefined) throw new Error("type must be mcp, inference or a2a");
+ const name = args.name ? serviceTarget(args.name, type).slice(type.length + 3) : undefined;
+ const peers = await withSignal(s.discover(type, name, { limit: MAX_PROVIDERS }), setup);
+ const rows: { peer_id: string; srv_name: string; srv_description: string }[] = [];
+ if (name !== undefined) {
+ // As in agentmesh-node, a named lookup is answered by the directory
+ // alone; no provider is contacted, so none can fail or stall it.
+ for (const peer of peers) rows.push({ peer_id: peer.peerId, srv_name: `${type}://${name}`, srv_description: "" });
+ } else {
+ // A provider that fails or stalls is dropped, as in agentmesh-node.
+ const catalogs = await fanOut(peers, extra.signal, (peer, signal) => catalog(s, peer, type, signal));
+ catalogs.forEach((result, i) => {
+ if (result.status === "rejected") {
+ console.error(`agentmesh: catalog from ${peers[i]!.peerId} failed: ${JSON.stringify(String(result.reason))}`);
+ return;
+ }
+ for (const svc of result.value) {
+ rows.push({ peer_id: peers[i]!.peerId, srv_name: serviceTarget(svc.name, type), srv_description: svc.description ?? "" });
+ if (rows.length > MAX_RESULTS) throw new Error("too many services; narrow the discovery by name");
+ }
+ });
+ }
+ rows.sort((a, b) => a.peer_id.localeCompare(b.peer_id) || a.srv_name.localeCompare(b.srv_name));
+ const offset = Math.max(0, args.offset ?? 0), limit = (args.limit ?? 0) > 0 ? args.limit! : 20;
+ return text(rows.slice(offset, offset + limit));
+ });
+
+ server.registerTool("find_remote_tools", {
+ description: "Discover MCP tools available on hosted services across the mesh. Optionally narrow by peer_id, service_name, or exact tool_name. intent is accepted but ignored, as in agentmesh-node.",
+ inputSchema: {
+ intent: z.string().optional().describe("Natural-language description of what the caller is looking for. Reserved for future semantic ranking; currently accepted but ignored."),
+ peer_id: z.string().optional().describe("Restrict the search to a single peer. Empty means search the whole mesh."),
+ service_name: z.string().optional().describe("Restrict results to tools whose name starts with this service prefix (e.g. 'code-reviewer'). Empty means no service filter."),
+ tool_name: z.string().optional().describe("Exact (non-namespaced) tool name to locate across the mesh, e.g. 'review_pr'. Empty means list all tools."),
+ },
+ }, async (args, extra) => {
+ const setup = AbortSignal.any([extra.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
+ const s = await withSignal(ready, setup);
+ const filter = args.service_name ? serviceTarget(args.service_name) : undefined;
+ const peerId = args.peer_id ? canonicalPeerId(args.peer_id) : undefined;
+ if (peerId === s.peerId) throw new Error("cross-mesh discovery cannot target self");
+ const peers = peerId ? [{ peerId, addrs: [] }] : await withSignal(s.discover("mcp", undefined, { limit: MAX_PROVIDERS }), setup);
+ const rows: ToolRow[] = [];
+ const append = (row: ToolRow) => {
+ if (rows.length >= MAX_RESULTS) throw new ResultLimitError();
+ rows.push(row);
+ };
+ const results = await fanOut(peers, extra.signal, async (peer, signal) => {
+ const found: ToolRow[] = [];
+ for (const svc of await catalog(s, peer, "mcp", signal)) {
+ const target = serviceTarget(svc.name);
+ if (filter !== undefined && target !== filter) continue;
+ try {
+ for (const tool of await tools(s, peer, target, signal)) {
+ if (!args.tool_name || tool.name === args.tool_name) {
+ found.push({ peer_id: peer.peerId, tool_name: `${target}/${tool.name}`, description: tool.description ?? "" });
+ if (found.length > MAX_RESULTS) throw new ResultLimitError();
+ }
+ }
+ } catch (err) {
+ // The peer's deadline ends the peer, not just this service.
+ signal.throwIfAborted();
+ if (err instanceof ResultLimitError) throw err;
+ if (err instanceof AuthRejectedError) console.error(`agentmesh: discovery refused: ${JSON.stringify(err.message)}`);
+ else found.push({ peer_id: peer.peerId, tool_name: target, error: String(err) });
+ }
+ }
+ return found;
+ });
+ results.forEach((result, i) => {
+ if (result.status === "fulfilled") {
+ result.value.forEach(append);
+ return;
+ }
+ const err: unknown = result.reason;
+ if (err instanceof ResultLimitError) throw err;
+ if (peerId !== undefined) throw err;
+ if (err instanceof AuthRejectedError) console.error(`agentmesh: discovery refused: ${JSON.stringify(err.message)}`);
+ else append({ peer_id: peers[i]!.peerId, error: String(err) });
+ });
+ return text(rows.filter((row) => !args.tool_name || !row.error).sort((a, b) => a.peer_id.localeCompare(b.peer_id) || (a.tool_name ?? "").localeCompare(b.tool_name ?? "")));
+ });
+
+ server.registerTool("describe_remote_tool", {
+ description: "Return the description, input schema, and output schema for a specific MCP tool on a specific peer.",
+ inputSchema: {
+ peer_id: z.string().describe("Peer ID of the node hosting the server. Required."),
+ tool_name: z.string().describe("Namespaced server name as returned by find_remote_tools (e.g. 'mcp://code-reviewer/review_pr'). Required."),
+ },
+ }, async (args, extra) => {
+ const signal = AbortSignal.any([extra.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
+ const s = await withSignal(ready, signal), peer = canonicalPeerId(args.peer_id), target = toolTarget(args.tool_name);
+ const tool = (await tools(s, peer, target.service, signal)).find((t) => t.name === target.tool);
+ if (tool === undefined) throw new Error("tool not found on peer");
+ return text({ peer_id: peer, tool_name: args.tool_name, description: tool.description ?? "", input_schema: tool.inputSchema, ...(tool.outputSchema ? { output_schema: tool.outputSchema } : {}) });
+ });
+
+ server.registerTool("call_remote_tool", {
+ description: "Call an MCP tool on a remote agent",
+ inputSchema: {
+ peer_id: z.string().describe("The Peer ID of the target agent"),
+ tool_name: z.string().describe("The name of the server to call"),
+ arguments: z.record(z.string(), z.unknown()).optional().describe("Server arguments as a JSON object whose keys match the target server's input_schema. Call describe_remote_tool first to learn the schema."),
+ required_labels: z.string().optional().describe("Comma-separated key=value pairs (e.g. 'region=us-east-1,team=platform'). Fails closed: the call is rejected unless the peer attests every one of them. Empty means no requirement."),
+ },
+ }, async (args, extra) => {
+ const s = await withSignal(ready, AbortSignal.any([extra.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]));
+ const peer = canonicalPeerId(args.peer_id), target = toolTarget(args.tool_name);
+ const open = AbortSignal.any([extra.signal, AbortSignal.timeout(OPEN_TIMEOUT_MS)]);
+ return call(s, peer, target.service, target.tool, args.arguments ?? {}, { signal: open, requiredLabels: requiredLabels(args.required_labels ?? "") },
+ { signal: extra.signal, timeout: CALL_TIMEOUT_MS, resetTimeoutOnProgress: true });
+ });
+ return server;
+}
diff --git a/site/content/docs/guides/connecting-agents.md b/site/content/docs/guides/connecting-agents.md
index 3687b8b3..82b7e1f5 100644
--- a/site/content/docs/guides/connecting-agents.md
+++ b/site/content/docs/guides/connecting-agents.md
@@ -12,239 +12,152 @@ aliases:
- /docs/integrations/vscode-copilot/
---
-An agent uses the mesh through the `agentmesh-node` that runs on its own machine.
-The node is an MCP server, so you can point any MCP client at it. This guide
-gives the configuration for the common clients and explains what the agent
-gets.
+An MCP client can join Agent Mesh as its own member and call remote MCP tools
+through the published **`dev.sam-mesh/mesh`** server. The server runs locally
+over stdio. It enrolls directly with your mesh control plane, so it does not
+need an `agentmesh-node` process beside it.
-## What every client needs
+## Install from the MCP registry
-Three values, all printed by `agentmesh-node run --daemonize`:
-
-- **The endpoint**: `http://127.0.0.1:8080/mcp` (Streamable HTTP).
-- **The token**: the contents of `~/.config/agentmesh/api-token`, or the
- `AGENTMESH_API_TOKEN` you started the node with. It goes in the header
- `X-Mesh-Authentication: Bearer <token>`.
-- **The socket**: `~/.config/agentmesh/agentmesh.sock`. Anything the agent runs in a
- shell can use the socket without a token. This is the easier way to reach
- the node's `/v1` inference endpoint from scripts.
-
-The node must be running before the client starts. MCP clients start and
-manage stdio servers themselves, but `agentmesh-node` is an HTTP server that they
-connect to. You can run `agentmesh-node run --daemonize` as often as you like, so it
-is safe to put it in a shell profile or to let the agent run it.
-
-## What the agent gets
-
-Six tools:
-
-| Tool | Purpose |
-|---|---|
-| `get_mesh_info` | The routers the node holds, its connected peers, the local socket path. A quick health check. |
-| `list_local_services` | The services this node publishes. |
-| `discover_remote_services` | The services other nodes publish, by type (`mcp`, `inference`, `a2a`) and optionally by name. Returns the hosting peer ID for each. |
-| `find_remote_tools` | The tools behind MCP services, across the mesh or limited to a peer, a service, or a tool name. |
-| `describe_remote_tool` | The input schema of one tool on one peer. Call this before `call_remote_tool`, because the provider chooses the argument names. |
-| `call_remote_tool` | Run a tool on a peer. Takes `peer_id`, the namespaced `tool_name` (`mcp://service/tool`) and `arguments`. |
-
-Inference is not an MCP tool. `discover_remote_services` with
-`{"type":"inference"}` lists providers, but to use a model you send an
-ordinary OpenAI request to the node's `/v1` endpoint, with `base_url`
-`http://127.0.0.1:8080/v1` and the token as the API key. `/v1/models` lists
-the available models.
-
-A2A agents are not MCP tools either. `discover_remote_services` with
-`{"type":"a2a"}` lists them with a `local_proxy_url`, and any stock A2A
-client works through that URL, for example the official
-[`a2a` CLI](https://github.com/a2aproject/a2a-cli), whose own skill teaches
-an agent the protocol. The
-[node API reference](../../reference/node-api/#talking-a2a-through-the-proxy)
-shows the call.
-
-Two things an agent should know (the skill below tells it): service names
-are not unique across the mesh, so the peer ID identifies a provider, and
-discovery is best-effort per peer, so on a partly reachable mesh some entries
-come back with an `error` field next to the good ones.
-
-## The skill
-
-Tools tell an agent what it can do. A skill tells it when and how to use
-them. `agentmesh-node` ships one:
-
-```bash
-agentmesh-node skill install # ~/.claude/skills/agentmesh/ and ~/.gemini/config/skills/agentmesh/
-agentmesh-node skill install --project # ./.claude/skills/ and ./.agents/skills/ in the current repository
-agentmesh-node skill install --dir DIR # anywhere else
-agentmesh-node skill list # where it is installed and whether it is current
-agentmesh-node skill show # print it, for a harness with its own layout
-```
-
-Reinstall the skill after you upgrade `agentmesh-node`. `list` says `outdated` when
-the installed copy differs from the one in the binary. Restart the client
-afterwards so that it loads both the skill and the tools.
-
-## Claude Code
-
-```bash
-claude mcp add --transport http agentmesh http://127.0.0.1:8080/mcp \
- --header "X-Mesh-Authentication: Bearer <token>"
-```
-
-The default scope is the current project. `--scope user` makes the server
-available everywhere, and `--scope project` writes a shareable `.mcp.json`.
-The equivalent file entry, where `type` is required:
+The official registry server entry is **`dev.sam-mesh/mesh`**. Its npm package
+is **`@agentmesh-p2p/sdk`**; the registry name and npm package name serve
+different purposes. After the first registry release is available, configure
+your client to run the published package version:
```json
{
- "mcpServers": {
- "agentmesh": {
- "type": "http",
- "url": "http://127.0.0.1:8080/mcp",
- "headers": { "X-Mesh-Authentication": "Bearer <token>" }
- }
+ "command": "npx",
+ "args": ["--yes", "@agentmesh-p2p/sdk@<published-version>"],
+ "env": {
+ "AGENTMESH_CONTROL_PLANE_URL": "https://mesh.example.com",
+ "AGENTMESH_BOOTSTRAP_TOKEN_PATH": "/absolute/path/to/join-token",
+ "AGENTMESH_STATE_DIR": "/absolute/path/to/this-client-identity"
}
}
```
-`claude mcp list` should report the server as connected. Tools load at
-session start. `/mcp` inside a session shows them, and `/skills` shows
-`agentmesh-p2p` once the skill is installed.
+Replace `<published-version>` with the version shown for `dev.sam-mesh/mesh`
+in the MCP registry. The first registry release must include the package's
+`agentmesh` command, so use a version published after that release. Node.js
+22.18 or later is required. Use absolute paths: MCP clients do not expand `~`
+in environment-variable values.
+
+Ask your mesh operator for the HTTPS control-plane URL and a bootstrap-token
+file that only your account can read. The executable reads the credential from
+that file; do not put token contents into client configuration, command-line
+arguments or shell history. Alternatively, use
+`AGENTMESH_JWT_PATH` for a workload/OIDC token file. Set exactly one credential
+path for first enrollment. The client saves its member identity and resumes
+from `AGENTMESH_STATE_DIR` on later launches, so it can omit the credential
+path after enrollment. JWT enrollment rereads the token file when refreshing.
+
+Each client identity and mesh needs its own state directory. Do not launch two
+copies against one directory. If you omit `AGENTMESH_STATE_DIR`, the executable
+uses `~/.config/agentmesh/mcp`.
-## Google Antigravity
+Plain HTTP is accepted only for a loopback control plane. To permit plaintext
+HTTP to another address, set `AGENTMESH_INSECURE_CONTROL_PLANE=true`; this
+disables TLS protection for the control-plane connection and should only be
+used on a network you trust. Its default is `false`.
-Add to `~/.gemini/config/mcp_config.json`:
+## Configure a client
+
+The registry entry declares a stdio transport and the environment variables
+above. Most MCP clients accept this `mcpServers` shape:
```json
{
"mcpServers": {
"agentmesh": {
- "serverUrl": "http://127.0.0.1:8080/mcp",
- "headers": { "X-Mesh-Authentication": "Bearer <token>" }
+ "command": "npx",
+ "args": ["--yes", "@agentmesh-p2p/sdk@<published-version>"],
+ "env": {
+ "AGENTMESH_CONTROL_PLANE_URL": "https://mesh.example.com",
+ "AGENTMESH_BOOTSTRAP_TOKEN_PATH": "/absolute/path/to/join-token",
+ "AGENTMESH_STATE_DIR": "/absolute/path/to/this-client-identity"
+ }
}
}
}
```
-Antigravity picks up the change without a restart. `agentmesh-node skill install`
-writes the skill to Antigravity's global skills directory. `--project` writes
-it to `.agents/skills/` in the workspace instead.
-
-## VS Code and GitHub Copilot
-
-Create `.vscode/mcp.json` in the workspace. VS Code asks for the token once
-and keeps it in its secret store, so the file is safe to commit:
+VS Code uses a `servers` object in `.vscode/mcp.json` instead:
```json
{
- "inputs": [
- { "type": "promptString", "id": "agentmesh-api-token",
- "description": "Agent Mesh node API token", "password": true }
- ],
"servers": {
"agentmesh": {
- "type": "http",
- "url": "http://127.0.0.1:8080/mcp",
- "headers": { "X-Mesh-Authentication": "Bearer ${input:agentmesh-api-token}" }
+ "type": "stdio",
+ "command": "npx",
+ "args": ["--yes", "@agentmesh-p2p/sdk@<published-version>"],
+ "env": {
+ "AGENTMESH_CONTROL_PLANE_URL": "https://mesh.example.com",
+ "AGENTMESH_BOOTSTRAP_TOKEN_PATH": "/absolute/path/to/join-token",
+ "AGENTMESH_STATE_DIR": "/absolute/path/to/this-client-identity"
+ }
}
}
}
```
-VS Code does not start a newly declared server on its own. Open the file and
-use the **Start** action shown above the entry, or run **MCP: List Servers**
-from the command palette. A server listed as stopped was read correctly and
-is waiting to be started. If you entered a wrong token, clear it with
-**MCP: Reset Cached Tokens**. New tools may not appear in a chat that is
-already in progress. Start a new chat and check that `agentmesh-p2p` is ticked in
-the tools picker. To use the server in all workspaces, put the same JSON in
-the user-level configuration (**MCP: Open User Configuration**). Copilot
-reads `~/.claude/skills/`, so the default skill install applies.
+The process writes MCP messages only to stdout and diagnostics to stderr.
+Closing stdin or stopping the client shuts down the mesh session.
-## Claude Desktop
+## What the server provides
-Claude Desktop launches stdio servers only, so it needs a bridge.
-[`mcp-remote`](https://www.npmjs.com/package/mcp-remote) is a small
-stdio-to-HTTP proxy that Claude Desktop can launch. Add it to
-`claude_desktop_config.json` (`~/Library/Application Support/Claude/` on
-macOS, `%APPDATA%\Claude\` on Windows):
+The stdio server exposes five caller tools:
-```json
-{
- "mcpServers": {
- "agentmesh": {
- "command": "npx",
- "args": [
- "mcp-remote", "http://127.0.0.1:8080/mcp", "--allow-http",
- "--header", "X-Mesh-Authentication: Bearer <token>"
- ]
- }
- }
-}
-```
+| Tool | Purpose |
+|---|---|
+| `get_mesh_info` | Return this member's peer ID, connected peers and attached routers. |
+| `discover_remote_services` | Find services published by other mesh members. |
+| `find_remote_tools` | Find tools offered by remote MCP services. |
+| `describe_remote_tool` | Read the input schema for a remote tool. |
+| `call_remote_tool` | Call a remote tool using the member's authenticated mesh session. |
-`--allow-http` is needed because the node serves plain HTTP on loopback. Quit
-and reopen Claude Desktop. The tools appear under the connectors icon. On
-Windows the command may need to be `npx.cmd`. Claude's cloud-hosted "custom
-connectors" cannot reach a node on your machine, so use the bridge.
+The server is a caller, not a service host, so it does not expose
+`list_local_services`. Calls follow the member's mesh identity and policy.
+Discovery is bounded and follows tool pagination. Inference and A2A discovery
+return service metadata, but this stdio executable does not create an HTTP
+proxy, `/v1` endpoint, local socket or `local_proxy_url`. To publish a local
+service, share a node identity, or invoke inference and A2A over HTTP, use
+[the agentmesh-node setup](../deploying-node-mcp/).
-## OpenClaw
+## Try the source checkout before registry release
+
+Until the first package version with its executable is published, you can run
+the same server from a checkout:
```bash
-openclaw mcp set agentmesh '{
- "url": "http://127.0.0.1:8080/mcp",
- "headers": { "X-Mesh-Authentication": "Bearer <token>" }
-}'
-openclaw mcp list
+git clone https://github.com/google/agentmesh.git
+cd agentmesh/sdk/js
+npm ci
+npm run build
```
-Restart the OpenClaw gateway after adding it.
-
-## Your own code
+Use `node` and the absolute path to `dist/cli.js` in place of `npx` in the
+client configuration:
-Any MCP SDK works. In Python, with the official `mcp` package (2.x):
+```json
+{
+ "command": "node",
+ "args": ["/absolute/path/to/agentmesh/sdk/js/dist/cli.js"],
+ "env": {
+ "AGENTMESH_CONTROL_PLANE_URL": "https://mesh.example.com",
+ "AGENTMESH_BOOTSTRAP_TOKEN_PATH": "/absolute/path/to/join-token",
+ "AGENTMESH_STATE_DIR": "/absolute/path/to/this-client-identity"
+ }
+}
+```
-```python
-import httpx
-from mcp import ClientSession
-from mcp.client.streamable_http import streamable_http_client
+The source checkout needs Node.js 22.18 or later and the same mesh settings
+described above. See the
+[JavaScript SDK README](https://github.com/google/agentmesh/tree/main/sdk/js#mcp-client-over-stdio)
+for implementation limits and troubleshooting.
-http = httpx.AsyncClient(headers={"X-Mesh-Authentication": "Bearer <token>"})
-async with streamable_http_client("http://127.0.0.1:8080/mcp", http_client=http) as (read, write):
- async with ClientSession(read, write) as session:
- await session.initialize()
- tools = await session.list_tools()
-```
+## The node HTTP server
-`site/content/docs/snippets/agent_demo.py` in the repository is a complete
-version of this example. For inference, point any OpenAI SDK at
-`http://127.0.0.1:8080/v1` with the token as `api_key`, or at the socket with
-no key.
-
-Native SDKs that join the mesh from inside the agent process, without a
-`agentmesh-node` sidecar, are being built under `sdk/` in the repository; see
-`sdk/README.md` for their status.
-
-## A note on trust
-
-A client configured this way is a client of your node. It holds the node's
-token and gets everything that the node's credential grants. That is the
-right arrangement for an assistant on your own machine. Code that you do not
-trust should not be able to reach the node's API at all. The
-[sandboxed agents preview](../../preview/sandboxed-agents/) covers that case.
-
-## When it does not work
-
-- **401**: the header value does not match the node's token. Over the
- socket no token is needed. Over TCP it is required.
-- **Connection refused**: the node is not running, or it is bound to another
- address. If
- `curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/mcp`
- answers `401`, the endpoint is up.
-- **Node in WSL or in a container**: the client runs on the host, so bind
- the node to an address the host can reach (`--bind-addr 0.0.0.0:8080`) or
- forward the port.
-- **No remote tools**: check `get_mesh_info` first. An empty
- `attached_routers` means the node has not been admitted by a router yet,
- and it has nobody to ask.
-- **A tool is listed with an `error`**: the provider's backend is not
- answering. Another peer that offers the same service name may work.
+The `agentmesh-node` also exposes an MCP server over authenticated HTTP. Use it
+when you want a node to publish services or several clients to share one
+member identity. Its HTTP setup and client-specific configuration live in
+[Connect through an agentmesh-node](../deploying-node-mcp/).
diff --git a/site/content/docs/guides/deploying-node-mcp.md b/site/content/docs/guides/deploying-node-mcp.md
new file mode 100644
index 00000000..3a65fdbd
--- /dev/null
+++ b/site/content/docs/guides/deploying-node-mcp.md
@@ -0,0 +1,243 @@
+---
+title: "Connect through an agentmesh-node"
+linkTitle: "Connect through a node"
+weight: 3
+---
+
+An `agentmesh-node` publishes local MCP, inference and A2A services to the mesh
+and exposes them through authenticated HTTP endpoints on your machine. Use this
+setup when you need to publish a service, share one node identity across
+clients, or call inference and A2A endpoints. For an MCP client that joins as
+its own member and calls remote tools, see [Connecting agents](../connecting-agents/).
+
+## What every client needs
+
+Three values, all printed by `agentmesh-node run --daemonize`:
+
+- **The endpoint**: `http://127.0.0.1:8080/mcp` (Streamable HTTP).
+- **The token**: the contents of `~/.config/agentmesh/api-token`, or the
+ `AGENTMESH_API_TOKEN` you started the node with. It goes in the header
+ `X-Mesh-Authentication: Bearer <token>`.
+- **The socket**: `~/.config/agentmesh/agentmesh.sock`. Anything the agent runs in a
+ shell can use the socket without a token. This is the easier way to reach
+ the node's `/v1` inference endpoint from scripts.
+
+The node must be running before the client starts. MCP clients start and
+manage stdio servers themselves, but `agentmesh-node` is an HTTP server that they
+connect to. You can run `agentmesh-node run --daemonize` as often as you like, so it
+is safe to put it in a shell profile or to let the agent run it.
+
+## What the agent gets
+
+Six tools:
+
+| Tool | Purpose |
+|---|---|
+| `get_mesh_info` | The routers the node holds, its connected peers, the local socket path. A quick health check. |
+| `list_local_services` | The services this node publishes. |
+| `discover_remote_services` | The services other nodes publish, by type (`mcp`, `inference`, `a2a`) and optionally by name. Returns the hosting peer ID for each. |
+| `find_remote_tools` | The tools behind MCP services, across the mesh or limited to a peer, a service, or a tool name. |
+| `describe_remote_tool` | The input schema of one tool on one peer. Call this before `call_remote_tool`, because the provider chooses the argument names. |
+| `call_remote_tool` | Run a tool on a peer. Takes `peer_id`, the namespaced `tool_name` (`mcp://service/tool`) and `arguments`. |
+
+Inference is not an MCP tool. `discover_remote_services` with
+`{"type":"inference"}` lists providers, but to use a model you send an
+ordinary OpenAI request to the node's `/v1` endpoint, with `base_url`
+`http://127.0.0.1:8080/v1` and the token as the API key. `/v1/models` lists
+the available models.
+
+A2A agents are not MCP tools either. `discover_remote_services` with
+`{"type":"a2a"}` lists them with a `local_proxy_url`, and any stock A2A
+client works through that URL, for example the official
+[`a2a` CLI](https://github.com/a2aproject/a2a-cli), whose own skill teaches
+an agent the protocol. The
+[node API reference](../../reference/node-api/#talking-a2a-through-the-proxy)
+shows the call.
+
+Two things an agent should know (the skill below tells it): service names
+are not unique across the mesh, so the peer ID identifies a provider, and
+discovery is best-effort per peer, so on a partly reachable mesh some entries
+come back with an `error` field next to the good ones.
+
+## The skill
+
+Tools tell an agent what it can do. A skill tells it when and how to use
+them. `agentmesh-node` ships one:
+
+```bash
+agentmesh-node skill install # ~/.claude/skills/agentmesh/ and ~/.gemini/config/skills/agentmesh/
+agentmesh-node skill install --project # ./.claude/skills/ and ./.agents/skills/ in the current repository
+agentmesh-node skill install --dir DIR # anywhere else
+agentmesh-node skill list # where it is installed and whether it is current
+agentmesh-node skill show # print it, for a harness with its own layout
+```
+
+Reinstall the skill after you upgrade `agentmesh-node`. `list` says `outdated` when
+the installed copy differs from the one in the binary. Restart the client
+afterwards so that it loads both the skill and the tools.
+
+## Claude Code
+
+```bash
+claude mcp add --transport http agentmesh http://127.0.0.1:8080/mcp \
+ --header "X-Mesh-Authentication: Bearer <token>"
+```
+
+The default scope is the current project. `--scope user` makes the server
+available everywhere, and `--scope project` writes a shareable `.mcp.json`.
+The equivalent file entry, where `type` is required:
+
+```json
+{
+ "mcpServers": {
+ "agentmesh": {
+ "type": "http",
+ "url": "http://127.0.0.1:8080/mcp",
+ "headers": { "X-Mesh-Authentication": "Bearer <token>" }
+ }
+ }
+}
+```
+
+`claude mcp list` should report the server as connected. Tools load at
+session start. `/mcp` inside a session shows them, and `/skills` shows
+`agentmesh-p2p` once the skill is installed.
+
+## Google Antigravity
+
+Add to `~/.gemini/config/mcp_config.json`:
+
+```json
+{
+ "mcpServers": {
+ "agentmesh": {
+ "serverUrl": "http://127.0.0.1:8080/mcp",
+ "headers": { "X-Mesh-Authentication": "Bearer <token>" }
+ }
+ }
+}
+```
+
+Antigravity picks up the change without a restart. `agentmesh-node skill install`
+writes the skill to Antigravity's global skills directory. `--project` writes
+it to `.agents/skills/` in the workspace instead.
+
+## VS Code and GitHub Copilot
+
+Create `.vscode/mcp.json` in the workspace. VS Code asks for the token once
+and keeps it in its secret store, so the file is safe to commit:
+
+```json
+{
+ "inputs": [
+ { "type": "promptString", "id": "agentmesh-api-token",
+ "description": "Agent Mesh node API token", "password": true }
+ ],
+ "servers": {
+ "agentmesh": {
+ "type": "http",
+ "url": "http://127.0.0.1:8080/mcp",
+ "headers": { "X-Mesh-Authentication": "Bearer ${input:agentmesh-api-token}" }
+ }
+ }
+}
+```
+
+VS Code does not start a newly declared server on its own. Open the file and
+use the **Start** action shown above the entry, or run **MCP: List Servers**
+from the command palette. A server listed as stopped was read correctly and
+is waiting to be started. If you entered a wrong token, clear it with
+**MCP: Reset Cached Tokens**. New tools may not appear in a chat that is
+already in progress. Start a new chat and check that `agentmesh-p2p` is ticked in
+the tools picker. To use the server in all workspaces, put the same JSON in
+the user-level configuration (**MCP: Open User Configuration**). Copilot
+reads `~/.claude/skills/`, so the default skill install applies.
+
+## Claude Desktop
+
+Claude Desktop launches stdio servers only, so it needs a bridge.
+[`mcp-remote`](https://www.npmjs.com/package/mcp-remote) is a small
+stdio-to-HTTP proxy that Claude Desktop can launch. Add it to
+`claude_desktop_config.json` (`~/Library/Application Support/Claude/` on
+macOS, `%APPDATA%\Claude\` on Windows):
+
+```json
+{
+ "mcpServers": {
+ "agentmesh": {
+ "command": "npx",
+ "args": [
+ "mcp-remote", "http://127.0.0.1:8080/mcp", "--allow-http",
+ "--header", "X-Mesh-Authentication: Bearer <token>"
+ ]
+ }
+ }
+}
+```
+
+`--allow-http` is needed because the node serves plain HTTP on loopback. Quit
+and reopen Claude Desktop. The tools appear under the connectors icon. On
+Windows the command may need to be `npx.cmd`. Claude's cloud-hosted "custom
+connectors" cannot reach a node on your machine, so use the bridge.
+
+## OpenClaw
+
+```bash
+openclaw mcp set agentmesh '{
+ "url": "http://127.0.0.1:8080/mcp",
+ "headers": { "X-Mesh-Authentication": "Bearer <token>" }
+}'
+openclaw mcp list
+```
+
+Restart the OpenClaw gateway after adding it.
+
+## Your own code
+
+Any MCP SDK works. In Python, with the official `mcp` package (2.x):
+
+```python
+import httpx
+from mcp import ClientSession
+from mcp.client.streamable_http import streamable_http_client
+
+http = httpx.AsyncClient(headers={"X-Mesh-Authentication": "Bearer <token>"})
+async with streamable_http_client("http://127.0.0.1:8080/mcp", http_client=http) as (read, write):
+ async with ClientSession(read, write) as session:
+ await session.initialize()
+ tools = await session.list_tools()
+```
+
+`site/content/docs/snippets/agent_demo.py` in the repository is a complete
+version of this example. For inference, point any OpenAI SDK at
+`http://127.0.0.1:8080/v1` with the token as `api_key`, or at the socket with
+no key.
+
+Native SDKs that join the mesh from inside the agent process, without a
+`agentmesh-node` sidecar, are being built under `sdk/` in the repository; see
+`sdk/README.md` for their status.
+
+## A note on trust
+
+A client configured this way is a client of your node. It holds the node's
+token and gets everything that the node's credential grants. That is the
+right arrangement for an assistant on your own machine. Code that you do not
+trust should not be able to reach the node's API at all. The
+[sandboxed agents preview](../../preview/sandboxed-agents/) covers that case.
+
+## When it does not work
+
+- **401**: the header value does not match the node's token. Over the
+ socket no token is needed. Over TCP it is required.
+- **Connection refused**: the node is not running, or it is bound to another
+ address. If
+ `curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/mcp`
+ answers `401`, the endpoint is up.
+- **Node in WSL or in a container**: the client runs on the host, so bind
+ the node to an address the host can reach (`--bind-addr 0.0.0.0:8080`) or
+ forward the port.
+- **No remote tools**: check `get_mesh_info` first. An empty
+ `attached_routers` means the node has not been admitted by a router yet,
+ and it has nobody to ask.
+- **A tool is listed with an `error`**: the provider's backend is not
+ answering. Another peer that offers the same service name may work.
diff --git a/tests/integration/sdk_mcp_stdio_test.go b/tests/integration/sdk_mcp_stdio_test.go
new file mode 100644
index 00000000..10f8881c
--- /dev/null
+++ b/tests/integration/sdk_mcp_stdio_test.go
@@ -0,0 +1,221 @@
+// 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"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "sort"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/google/agentmesh/api"
+ "github.com/google/agentmesh/internal/node"
+ "github.com/google/agentmesh/internal/standalone"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+// TestNativeSDKMCPStdio drives the built entrypoint with a stock MCP
+// client, over stdio, against agentmesh-one and a real Go provider. Both
+// services exist and the provider may publish both; the caller may use only
+// calc. The second process must resume its saved identity without a token.
+func TestNativeSDKMCPStdio(t *testing.T) {
+ root := repoRoot(t)
+ entry := filepath.Join(root, "sdk", "js", "dist", "cli.js")
+ if _, err := exec.LookPath("node"); err != nil {
+ t.Skip("node is not installed")
+ }
+ if _, err := os.Stat(entry); err != nil {
+ t.Skip("SDK executable not built: cd sdk/js && npm ci && npm run build")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ policyPath := filepath.Join(t.TempDir(), "policy.json")
+ policy := `{"roles":[
+ {"name":"mesh:role:router","allowed_services":["*"],"allowed_targets":["*"]},
+ {"name":"mesh:role:node","allowed_services":["system://*","mcp://calc"],"allowed_publish":["*"],"allowed_targets":["*"]}
+ ]}`
+ if err := os.WriteFile(policyPath, []byte(policy), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ srv := startStandalone(t, ctx, standalone.Options{BindAddress: "127.0.0.1:0", DataDir: t.TempDir(), PolicyFile: policyPath})
+ provider := newStandaloneTestNode(t, ctx)
+ if err := provider.EnrollBootstrap(ctx, srv.PublicURL(), srv.JoinToken()); err != nil {
+ t.Fatal(err)
+ }
+ var calls atomic.Int32
+ backend := mcp.NewServer(&mcp.Implementation{Name: "calc", Version: "1"}, nil)
+ backend.AddTool(&mcp.Tool{Name: "add", Description: "add numbers", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ calls.Add(1)
+ return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "3"}}}, nil
+ })
+ httpBackend := httptest.NewServer(mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return backend }, nil))
+ t.Cleanup(httpBackend.Close)
+ for _, name := range []string{"calc", "denied"} {
+ if err := provider.RegisterService(ctx, &api.RegisterServiceRequest{
+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: name},
+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: httpBackend.URL},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ tokenPath := filepath.Join(t.TempDir(), "join-token")
+ if err := os.WriteFile(tokenPath, []byte(srv.JoinToken()), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ stateDir := filepath.Join(t.TempDir(), "state")
+ // Compare the executable's caller parameter contracts with the Go node,
+ // using the node's real MCP registration rather than a copied schema fixture.
+ nodeServer := node.NewMCPServer(provider)
+ serverTransport, clientTransport := mcp.NewInMemoryTransports()
+ nodeSession, err := nodeServer.Connect(ctx, serverTransport, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = nodeSession.Close() })
+ nodeClient, err := mcp.NewClient(&mcp.Implementation{Name: "schema-check", Version: "1"}, nil).Connect(ctx, clientTransport, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = nodeClient.Close() })
+ nodeTools, err := nodeClient.ListTools(ctx, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Descriptions and generator-specific JSON Schema keywords may differ;
+ // field names, JSON types and required parameters must match.
+ contract := func(schema any) any {
+ data, err := json.Marshal(schema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var parsed struct {
+ Properties map[string]struct {
+ Type any `json:"type"`
+ } `json:"properties"`
+ Required []string `json:"required"`
+ }
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ t.Fatal(err)
+ }
+ if len(parsed.Properties) == 0 {
+ parsed.Properties = nil
+ }
+ if len(parsed.Required) == 0 {
+ parsed.Required = nil
+ }
+ sort.Strings(parsed.Required)
+ return parsed
+ }
+ contracts := map[string]any{}
+ for _, tool := range nodeTools.Tools {
+ contracts[tool.Name] = contract(tool.InputSchema)
+ }
+ var firstPeer string
+ for launch := range 2 {
+ cmd := exec.CommandContext(ctx, "node", entry)
+ for _, value := range os.Environ() {
+ if !strings.HasPrefix(value, "AGENTMESH_") {
+ cmd.Env = append(cmd.Env, value)
+ }
+ }
+ cmd.Env = append(cmd.Env, "AGENTMESH_CONTROL_PLANE_URL="+srv.PublicURL(), "AGENTMESH_STATE_DIR="+stateDir)
+ if launch == 0 {
+ cmd.Env = append(cmd.Env, "AGENTMESH_BOOTSTRAP_TOKEN_PATH="+tokenPath)
+ }
+ cmd.Stderr = os.Stderr
+ client := mcp.NewClient(&mcp.Implementation{Name: "stdio-integration", Version: "1"}, nil)
+ session, err := client.Connect(ctx, &mcp.CommandTransport{Command: cmd}, nil)
+ if err != nil {
+ t.Fatalf("launch %d: %v", launch, err)
+ }
+ t.Cleanup(func() { _ = session.Close() })
+ invoke := func(name string, args map[string]any, wantError bool) *mcp.CallToolResult {
+ t.Helper()
+ result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
+ if err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ if result.IsError != wantError {
+ content, _ := json.Marshal(result.Content)
+ t.Fatalf("%s: isError=%v, want %v; content=%s", name, result.IsError, wantError, content)
+ }
+ return result
+ }
+ info := invoke("get_mesh_info", map[string]any{}, false)
+ var details struct {
+ PeerID string `json:"peer_id"`
+ }
+ if err := json.Unmarshal([]byte(info.Content[0].(*mcp.TextContent).Text), &details); err != nil || details.PeerID == "" {
+ t.Fatalf("invalid mesh info: %v", err)
+ }
+ if launch == 0 {
+ firstPeer = details.PeerID
+ } else if details.PeerID != firstPeer {
+ t.Fatalf("restart changed identity: %s -> %s", firstPeer, details.PeerID)
+ }
+ tools, err := session.ListTools(ctx, nil)
+ if err != nil || len(tools.Tools) != 5 {
+ t.Fatalf("tools/list: %v, want five tools", err)
+ }
+ for _, tool := range tools.Tools {
+ if got, want := contract(tool.InputSchema), contracts[tool.Name]; !reflect.DeepEqual(got, want) {
+ t.Fatalf("%s parameter contract differs: got %+v, want %+v", tool.Name, got, want)
+ }
+ }
+ peer := provider.Host.ID().String()
+ invoke("describe_remote_tool", map[string]any{"peer_id": peer, "tool_name": "mcp://calc/add"}, false)
+ result := invoke("call_remote_tool", map[string]any{"peer_id": peer, "tool_name": "mcp://calc/add", "arguments": map[string]any{"a": 1, "b": 2}}, false)
+ if text, ok := result.Content[0].(*mcp.TextContent); !ok || text.Text != "3" {
+ t.Fatalf("unexpected tool result: %v", result.Content)
+ }
+ before := calls.Load()
+ invoke("call_remote_tool", map[string]any{"peer_id": peer, "tool_name": "mcp://denied/add"}, true)
+ invoke("call_remote_tool", map[string]any{"peer_id": peer, "tool_name": "mcp://calc/add", "required_labels": "region=unattested"}, true)
+ if calls.Load() != before {
+ t.Fatal("a refused call reached the backend")
+ }
+ found := invoke("find_remote_tools", map[string]any{}, false)
+ var rows []struct {
+ ToolName string `json:"tool_name"`
+ }
+ if err := json.Unmarshal([]byte(found.Content[0].(*mcp.TextContent).Text), &rows); err != nil || len(rows) != 1 || rows[0].ToolName != "mcp://calc/add" {
+ t.Fatalf("find_remote_tools must expose only calc/add: %v, %v", rows, err)
+ }
+ discovered := invoke("discover_remote_services", map[string]any{"type": "mcp", "name": "calc"}, false)
+ var services []struct {
+ PeerID string `json:"peer_id"`
+ Name string `json:"srv_name"`
+ ProxyURL string `json:"local_proxy_url"`
+ }
+ if err := json.Unmarshal([]byte(discovered.Content[0].(*mcp.TextContent).Text), &services); err != nil || len(services) != 1 || services[0].PeerID != peer || services[0].Name != "mcp://calc" || services[0].ProxyURL != "" {
+ t.Fatalf("discovery must return the real provider without an HTTP proxy: %+v, %v", services, err)
+ }
+ if err := session.Close(); err != nil {
+ t.Fatalf("stdin close did not stop the executable: %v", err)
+ }
+ if cmd.ProcessState == nil || !cmd.ProcessState.Success() {
+ t.Fatalf("executable did not exit cleanly: %v", cmd.ProcessState)
+ }
+ }
+}