Skip to content

Agent Mesh

sdk/js: accept A2A for the agent, stop publishing services

Antonio Ojead013c00926ab
diff --git a/sdk/js/examples/agent.ts b/sdk/js/examples/agent.ts
new file mode 100644
index 00000000..64e0d9b3
--- /dev/null
+++ b/sdk/js/examples/agent.ts
@@ -0,0 +1,42 @@
+// An agent on the mesh: joins, then answers A2A requests from other members
+// until stopped. It publishes nothing. There is no service name to look up; a
+// caller reaches the agent by its peer ID, through a router, as a2a://agent.
+// The mesh policy decides which members may call; the SDK turns the others
+// away before anything reaches this code.
+//
+// node agent.js # answered by the handler below
+// node agent.js http://127.0.0.1:9999 # forwarded to an A2A server beside it
+//
+// SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
+// SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or
+// SAM_JWT_PATH (a workload identity token your platform issues, such as a
+// Kubernetes projected service account token), and keeps the identity and
+// credential in SAM_STATE_DIR; later runs resume from there, as the same
+// peer, without it.
+import { homedir } from "node:os";
+import { AgentMesh } from "@sam-mesh/sdk";
+
+const [backendURL] = 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,
+ jwtPath: process.env.SAM_JWT_PATH,
+ stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/agent`,
+ // A plaintext http:// control plane is otherwise accepted only on loopback.
+ allowInsecure: process.env.SAM_INSECURE_CONTROL_PLANE === "true",
+});
+const session = await mesh.join();
+
+// Answers every path with who was asked and who asked; a real agent runs an
+// A2A server here, or beside this process at backendURL.
+const target = await session.acceptA2A(
+ backendURL !== undefined
+ ? { url: backendURL }
+ : { handler: (request, caller) => Response.json({ name: "agent", path: new URL(request.url).pathname, caller: caller.peerId }) },
+);
+console.log(`accepting ${target} 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/examples/call.ts b/sdk/js/examples/call.ts
index 392ccb32..28ba1522 100644
--- a/sdk/js/examples/call.ts
+++ b/sdk/js/examples/call.ts
@@ -1,9 +1,10 @@
-// Finds a service on the mesh and calls it: a tool of an MCP service, or a
-// path of an inference or A2A service.
+// Calls something on the mesh: a tool of an MCP service or a path of an
+// inference or A2A service someone published, found by name, or an agent that
+// published nothing, reached by its peer ID.
//
// node call.js mcp://greeter greet '{"name": "Ada"}'
-// node call.js a2a://greeter /card
// node call.js inference://ollama /v1/models
+// node call.js 12D3KooW... a2a://agent /card
//
// SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
// SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or
@@ -11,9 +12,15 @@
// Kubernetes projected service account token), and keeps the identity and
// credential in SAM_STATE_DIR; later runs resume from there without it.
import { homedir } from "node:os";
-import { AgentMesh, type DiscoveredProvider } from "@sam-mesh/sdk";
+import { AgentMesh, type Peer } from "@sam-mesh/sdk";
-const [service = "mcp://greeter", toolOrPath = "greet", args = '{"name": "world"}'] = process.argv.slice(2);
+let argv = process.argv.slice(2);
+// A first argument that is not a service target is the peer ID of an agent.
+let peerId: string | undefined;
+if (argv[0] !== undefined && !argv[0].includes("://")) {
+ [peerId, ...argv] = argv as [string, ...string[]];
+}
+const [service = peerId !== undefined ? "a2a://agent" : "mcp://greeter", toolOrPath = peerId !== undefined ? "/card" : "greet", args = '{"name": "world"}'] = argv;
const mesh = await AgentMesh.enroll({
controlPlaneUrl: process.env.SAM_CONTROL_PLANE_URL ?? "https://mesh.example.com",
@@ -26,25 +33,32 @@ const mesh = await AgentMesh.enroll({
const session = await mesh.join();
console.log(`on the mesh as ${session.peerId}`);
-const providers = await session.discover(service);
-if (providers.length === 0) {
- throw new Error(`no member of the mesh serves ${service}`);
-}
-// A provider record can outlive its member; the first that answers is used.
-let provider: DiscoveredProvider | undefined;
-for (const candidate of providers) {
- try {
- await session.connect(candidate);
- provider = candidate;
- break;
- } catch (err) {
- console.error(`${candidate.peerId}: ${(err as Error).message}`);
+let provider: Peer | undefined;
+if (peerId !== undefined) {
+ // An agent is not in the discovery table; the SDK finds the path to its
+ // peer ID through the routers.
+ await session.connect(peerId);
+ provider = peerId;
+} else {
+ const providers = await session.discover(service);
+ if (providers.length === 0) {
+ throw new Error(`no member of the mesh serves ${service}`);
+ }
+ // A provider record can outlive its member; the first that answers is used.
+ for (const candidate of providers) {
+ try {
+ await session.connect(candidate);
+ provider = candidate;
+ break;
+ } catch (err) {
+ console.error(`${candidate.peerId}: ${(err as Error).message}`);
+ }
+ }
+ if (provider === undefined) {
+ throw new Error(`no provider of ${service} is reachable`);
}
}
-if (provider === undefined) {
- throw new Error(`no provider of ${service} is reachable`);
-}
-console.log(`${service} is served by ${provider.peerId}`);
+console.log(`${service} is served by ${typeof provider === "string" ? provider : (provider as { peerId: string }).peerId}`);
if (service.startsWith("mcp://")) {
const tools = await session.listTools(provider, service);
diff --git a/sdk/js/examples/serve.ts b/sdk/js/examples/serve.ts
deleted file mode 100644
index 18a75a69..00000000
--- a/sdk/js/examples/serve.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// 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 # publishes mcp://greeter and a2a://greeter
-// node serve.js greeter-2 # the same under another name
-//
-// SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
-// SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or
-// SAM_JWT_PATH (a workload identity token your platform issues, such as a
-// Kubernetes projected service account token), and keeps the identity and
-// credential in SAM_STATE_DIR; later runs resume from there without it.
-import { homedir } from "node:os";
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import { AgentMesh } from "@sam-mesh/sdk";
-import { z } from "zod";
-
-const [name = "greeter"] = 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,
- jwtPath: process.env.SAM_JWT_PATH,
- stateDir: process.env.SAM_STATE_DIR ?? `${homedir()}/.config/sam-mesh/${name}`,
- // A plaintext http:// control plane is otherwise accepted only on loopback.
- allowInsecure: process.env.SAM_INSECURE_CONTROL_PLANE === "true",
-});
-const session = await mesh.join();
-
-await session.serve({
- type: "mcp",
- name,
- createServer: () => {
- const server = new McpServer({ name, version: "1.0.0" });
- server.registerTool("greet", { description: "Greets someone by name", inputSchema: { name: z.string() } }, async ({ name: who }) => ({
- content: [{ type: "text", text: `hello ${who}` }],
- }));
- return server;
- },
-});
-
-await session.serve({
- type: "a2a",
- name,
- target: (request, caller) => Response.json({ name, 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/src/conformance-join.ts b/sdk/js/src/conformance-join.ts
index df1f5fc9..e143b698 100644
--- a/sdk/js/src/conformance-join.ts
+++ b/sdk/js/src/conformance-join.ts
@@ -26,14 +26,12 @@
// list a provider's tools
// {"cmd": "call", "addr": "<multiaddr>", "service": "mcp://calc",
// "tool": "add", "args": {...}} call one tool
-// {"cmd": "serve", "type": "mcp", "name": "echo"}
-// publish an MCP service with an
-// echo tool served in this process
-// {"cmd": "serve", "type": "inference", "name": "llm", "target": "<url>"}
-// publish an HTTP service; without
-// target, a fake in this process
-// {"cmd": "http", "addr": "<multiaddr>", "service": "inference://llm",
-// "path": "/v1/models", "method": "GET", "body": "..."}
+// {"cmd": "accept", "name": "agent", "target": "<url>"}
+// accept A2A requests for this
+// member's agent; without target,
+// a handler in this process answers
+// {"cmd": "http", "addr": "<multiaddr>", "service": "a2a://agent",
+// "path": "/card", "method": "GET", "body": "..."}
// call an HTTP service over the mesh
// {"cmd": "peers"} peers that authenticated to us
// {"cmd": "sync"} pull keys, bans and routers from
@@ -44,10 +42,9 @@
// Each command gets one JSON line back. Same environment as conformance.ts;
// the Python SDK ships the same runner (python -m agent_mesh.conformance_join).
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { createInterface } from "node:readline";
-import { z } from "zod";
import type { ServiceType } from "./discovery.ts";
+import { DEFAULT_A2A_NAME, type A2AEndpointSpec } from "./libp2p-http.ts";
import { AgentMesh } from "./mesh.ts";
import type { MeshSession } from "./session.ts";
@@ -126,35 +123,19 @@ async function handle(session: MeshSession, command: Command): Promise<unknown>
}
case "banned":
return { cmd: "banned", ok: true, banned: session.banned.peers(), authenticated_peers: [...session.authenticatedPeers.keys()].sort() };
- case "serve": {
- const name = command.name ?? "";
- if (command.type === "mcp") {
- await session.serve({
- type: "mcp",
- name,
- description: "echo served by the js SDK",
- createServer: () => {
- const server = new McpServer({ name, version: "0.0.1" });
- server.tool("echo", { text: z.string() }, async ({ text }) => ({ content: [{ type: "text", text: `js:${text}` }] }));
- return server;
- },
- });
- } else if (command.type === "inference" || command.type === "a2a") {
- await session.serve({
- type: command.type,
- name,
- description: `${command.type} served by the js SDK`,
- target:
- command.target ??
- ((request, caller) =>
- new Response(JSON.stringify({ sdk: "js", peer: caller.peerId, method: request.method, path: new URL(request.url).pathname }), {
- headers: { "content-type": "application/json" },
- })),
- });
- } else {
- return failure("serve", new Error(`unknown service type ${JSON.stringify(command.type)}`));
- }
- return { cmd: "serve", ok: true, services: session.servedServices.map((s) => `${s.type}://${s.name}`) };
+ case "accept": {
+ const spec: A2AEndpointSpec =
+ command.target !== undefined
+ ? { url: command.target }
+ : {
+ handler: (request, caller) =>
+ new Response(JSON.stringify({ sdk: "js", peer: caller.peerId, method: request.method, path: new URL(request.url).pathname }), {
+ headers: { "content-type": "application/json" },
+ }),
+ };
+ spec.name = command.name ?? DEFAULT_A2A_NAME;
+ const service = await session.acceptA2A(spec);
+ return { cmd: "accept", ok: true, service };
}
case "http": {
const res = await session.request(command.addr ?? "", command.service ?? "", command.path ?? "/", {
diff --git a/sdk/js/src/controlplane.ts b/sdk/js/src/controlplane.ts
index cc7c90ce..ee77c80e 100644
--- a/sdk/js/src/controlplane.ts
+++ b/sdk/js/src/controlplane.ts
@@ -26,10 +26,7 @@ import {
EnrollResponseSchema,
EnrollmentStatus,
KeysResponseSchema,
- NodeCatalogReportSchema,
PolicyConfigGetResponseSchema,
- ServiceInfoSchema,
- ServiceType,
TokenRefreshRequestSchema,
TokenRefreshResponseSchema,
type BootstrapEnrollResponse,
@@ -353,20 +350,6 @@ export class ControlPlaneClient {
return resp.datalogRules;
}
- /**
- * POST /nodes/catalog: this member's published services, for the console.
- * Display only; the control plane takes the reporting peer from the biscuit.
- */
- async reportCatalog(biscuit: Uint8Array, services: { type: "mcp" | "inference" | "a2a"; name: string; description: string }[]): Promise<void> {
- const types = { mcp: ServiceType.MCP, inference: ServiceType.INFERENCE, a2a: ServiceType.A2A };
- const report = create(NodeCatalogReportSchema, {
- services: services.map((s) => create(ServiceInfoSchema, { type: types[s.type], name: s.name, description: s.description })),
- });
- await this.#request("POST", "/nodes/catalog", toBinary(NodeCatalogReportSchema, report), {
- Authorization: `Bearer ${Buffer.from(biscuit).toString("base64")}`,
- });
- }
-
async #request(method: "GET" | "POST", path: string, body?: Uint8Array, headers: Record<string, string> = {}): Promise<Uint8Array> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(new Error(`control plane ${path}: timed out after ${this.#timeoutMs}ms`)), this.#timeoutMs);
diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.ts
index 2713def9..91bbaa8a 100644
--- a/sdk/js/src/index.ts
+++ b/sdk/js/src/index.ts
@@ -46,21 +46,26 @@ export { DHT_PROTOCOL, isServiceType, parseServiceTarget, serviceCID, type Servi
export { LabelsNotSatisfiedError, StreamTransport, openMCPSession, requireLabels, type MCPSession, type MCPSessionOptions } from "./mcp.ts";
export { AuthorizationError, authorizeCaller, type AuthorizeRequest, type ProviderAuthorizerOptions } from "./authorizer.ts";
export {
+ DEFAULT_A2A_NAME,
+ HTTP_HANDLER_OPTIONS,
HTTP_PROTOCOL,
- ServiceRegistry,
+ MESH_PATH_PREFIX,
+ a2aEndpoint,
+ fetchOverStream,
httpIngressHandler,
httpRequestOverStream,
- mcpStreamHandler,
+ meshHTTPTarget,
+ meshURL,
+ splitMeshURL,
streamToNodeDuplex,
+ type A2AEndpoint,
+ type A2AEndpointSpec,
type HTTPHandler,
type HTTPRequestOptions,
type HTTPResponse,
- type HTTPServiceSpec,
- type MCPServerLike,
- type MCPServiceSpec,
+ type HTTPStreamOptions,
+ type NodeRequestListener,
type ProviderOptions,
- type ServedService,
- type ServiceSpec,
-} from "./serve.ts";
+} from "./libp2p-http.ts";
export { BASELINE_DATALOG } from "./gen/datalog.ts";
export { BanSet, EVENT_FRESHNESS_MS, GOSSIP_EVENTS_TOPIC, verifyMeshEvent, type VerifiedMeshEvent } from "./sync.ts";
diff --git a/sdk/js/src/libp2p-http.test.ts b/sdk/js/src/libp2p-http.test.ts
new file mode 100644
index 00000000..3e11af9f
--- /dev/null
+++ b/sdk/js/src/libp2p-http.test.ts
@@ -0,0 +1,268 @@
+// 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 A2A ingress in one process: this SDK's /libp2p-http handler for one
+// agent behind a js-libp2p host, called with this SDK's clients, including
+// the fetch a session hands to clients built on fetch. The real sam-node as
+// a caller is exercised by tests/integration.
+
+import { yamux } from "@chainsafe/libp2p-yamux";
+import { identify } from "@libp2p/identify";
+import type { Connection, Libp2p } from "@libp2p/interface";
+import { tcp } from "@libp2p/tcp";
+import { tls } from "@libp2p/tls";
+import { createLibp2p } from "libp2p";
+import assert from "node:assert/strict";
+import http from "node:http";
+import { after, before, test } from "node:test";
+import { loadBiscuit } from "./biscuit.ts";
+import { ROLE_NODE } from "./controlplane.ts";
+import {
+ HTTP_PROTOCOL,
+ a2aEndpoint,
+ fetchOverStream,
+ httpIngressHandler,
+ httpRequestOverStream,
+ meshHTTPTarget,
+ meshURL,
+ splitMeshURL,
+ streamToNodeDuplex,
+ type ProviderOptions,
+} from "./libp2p-http.ts";
+
+type Wasm = Awaited<ReturnType<typeof loadBiscuit>>;
+
+let wasm: Wasm;
+let cpKeyPair: InstanceType<Wasm["KeyPair"]>;
+let cpKey: Uint8Array;
+let agent: Libp2p;
+let listenerAgent: Libp2p;
+let caller: Libp2p;
+let callerBiscuit: Uint8Array;
+let guestBiscuit: Uint8Array;
+let backend: http.Server;
+let backendURL: string;
+const backendSeen: { method: string; url: string; peer: string | undefined; body: string }[] = [];
+const listenerSeen: { url: string; peer: string | undefined; biscuit: string | undefined }[] = [];
+const authorized: string[] = [];
+
+function mint(peerId: string, role: string, extra: string[] = []): Uint8Array {
+ const b = wasm.Biscuit.builder();
+ b.addFact(wasm.Fact.fromString(`node(${JSON.stringify(peerId)})`));
+ b.addFact(wasm.Fact.fromString(`client_peer_id(${JSON.stringify(peerId)})`));
+ b.addFact(wasm.Fact.fromString("expiration(2035-01-01T00:00:00Z)"));
+ b.addFact(wasm.Fact.fromString(`role(${JSON.stringify(role)})`));
+ for (const f of extra) {
+ b.addFact(wasm.Fact.fromString(f));
+ }
+ return b.build(cpKeyPair.getPrivateKey()).toBytes();
+}
+
+function newHost(): Promise<Libp2p> {
+ return createLibp2p({
+ addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },
+ transports: [tcp()],
+ connectionEncrypters: [tls()],
+ streamMuxers: [yamux()],
+ services: { identify: identify() },
+ });
+}
+
+// What the control plane renders for a policy granting the node role every
+// A2A service on any target, and nothing else.
+const POLICY_RULES = [
+ `granted_service_all("a2a") <- role("sam:role:node")`,
+ `granted_service_all("sam:system") <- role("sam:role:node")`,
+ `target_unrestricted(true) <- role("sam:role:node")`,
+];
+
+function providerOptions(biscuit: Uint8Array): ProviderOptions {
+ return {
+ trustedKeys: () => [cpKey],
+ ownBiscuit: () => biscuit,
+ policyRules: () => POLICY_RULES,
+ onAuthorized: (peerId, _v, service) => authorized.push(`${peerId} ${service}`),
+ };
+}
+
+// Stands in for an A2A server beside the agent: echoes the request and, on
+// /stream, answers with three SSE events as message/stream would.
+function fakeA2AServer(req: http.IncomingMessage, res: http.ServerResponse): void {
+ let body = "";
+ req.on("data", (c: Buffer) => (body += c.toString()));
+ req.on("end", () => {
+ backendSeen.push({ method: req.method ?? "", url: req.url ?? "", peer: req.headers["x-peer-id"] as string | undefined, body });
+ assert.equal(req.headers["x-sam-biscuit"], undefined, "biscuit leaked to the backend");
+ if (req.url === "/stream") {
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ let i = 0;
+ const tick = () => {
+ res.write(`data: ${JSON.stringify({ event: i })}\n\n`);
+ if (++i < 3) {
+ setTimeout(tick, 10);
+ } else {
+ res.end();
+ }
+ };
+ tick();
+ return;
+ }
+ res.writeHead(200, { "content-type": "application/json", "x-backend": "fake" });
+ res.end(JSON.stringify({ path: req.url, echo: body }));
+ });
+}
+
+before(async () => {
+ wasm = await loadBiscuit();
+ cpKeyPair = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
+ cpKey = new Uint8Array(Buffer.from(cpKeyPair.getPublicKey().toString().replace(/^ed25519\//, ""), "hex"));
+
+ backend = http.createServer(fakeA2AServer);
+ await new Promise<void>((resolve) => backend.listen(0, "127.0.0.1", resolve));
+ backendURL = `http://127.0.0.1:${(backend.address() as { port: number }).port}`;
+
+ // An agent forwarding to a server beside it.
+ agent = await newHost();
+ await agent.handle(HTTP_PROTOCOL, httpIngressHandler(a2aEndpoint({ url: backendURL }), providerOptions(mint(agent.peerId.toString(), ROLE_NODE))), {
+ runOnLimitedConnection: true,
+ });
+
+ // An agent answering with a Node request listener in the process, as an
+ // Express app carrying the A2A SDK's handlers would.
+ listenerAgent = await newHost();
+ const listener = (req: http.IncomingMessage, res: http.ServerResponse) => {
+ listenerSeen.push({ url: req.url ?? "", peer: req.headers["x-peer-id"] as string | undefined, biscuit: req.headers["x-sam-biscuit"] as string | undefined });
+ res.writeHead(202, { "content-type": "text/plain" });
+ res.end(`listener ${req.method} ${req.url}`);
+ };
+ await listenerAgent.handle(
+ HTTP_PROTOCOL,
+ httpIngressHandler(a2aEndpoint({ name: "worker", listener }), providerOptions(mint(listenerAgent.peerId.toString(), ROLE_NODE))),
+ { runOnLimitedConnection: true },
+ );
+
+ caller = await newHost();
+ callerBiscuit = mint(caller.peerId.toString(), ROLE_NODE);
+ guestBiscuit = mint(caller.peerId.toString(), "sam:role:guest");
+});
+
+after(async () => {
+ await caller.stop();
+ await agent.stop();
+ await listenerAgent.stop();
+ await new Promise<void>((resolve) => backend.close(() => resolve()));
+});
+
+async function dial(to: Libp2p = agent): Promise<Connection> {
+ return caller.dial(to.getMultiaddrs()[0] as Parameters<typeof caller.dial>[0]);
+}
+
+test("the agent is forwarded the request with the caller's identity and without its biscuit", async () => {
+ const conn = await dial();
+ const res = await httpRequestOverStream(conn, callerBiscuit, "a2a://agent", "/card?x=1", { headers: { "x-sam-biscuit": "spoof" } });
+ assert.equal(res.status, 200);
+ assert.equal(res.headers["x-backend"], "fake");
+ assert.deepEqual(JSON.parse(res.text()), { path: "/card?x=1", echo: "" });
+ assert.equal(backendSeen.at(-1)?.peer, caller.peerId.toString());
+ assert.ok(authorized.includes(`${caller.peerId.toString()} a2a://agent`));
+
+ const post = await httpRequestOverStream(conn, callerBiscuit, "a2a://agent", "/", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ jsonrpc: "2.0" }),
+ });
+ assert.equal(post.status, 200);
+ assert.equal(JSON.parse(post.text()).echo, JSON.stringify({ jsonrpc: "2.0" }));
+});
+
+test("a fetch over the stream delivers an SSE body event by event", async () => {
+ const conn = await dial();
+ const url = meshURL(agent.peerId.toString(), "a2a://agent", "/stream");
+ assert.equal(url, `http://mesh/sam/${agent.peerId.toString()}/a2a/agent/stream`);
+ const response = await fetchOverStream(conn, callerBiscuit, new Request(url));
+ assert.equal(response.status, 200);
+ assert.equal(response.headers.get("content-type"), "text/event-stream");
+ const chunks: string[] = [];
+ const reader = (response.body as ReadableStream<Uint8Array>).getReader();
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
+ chunks.push(new TextDecoder().decode(next.value));
+ }
+ // Three events, each flushed by the server before the next one was written.
+ assert.ok(chunks.length >= 3, `want at least three chunks, got ${JSON.stringify(chunks)}`);
+ assert.deepEqual(
+ chunks
+ .join("")
+ .split("\n")
+ .filter((l) => l.startsWith("data:")),
+ ['data: {"event":0}', 'data: {"event":1}', 'data: {"event":2}'],
+ );
+});
+
+test("a Node request listener sees the path relative to the agent and the verified caller", async () => {
+ const conn = await dial(listenerAgent);
+ const res = await httpRequestOverStream(conn, callerBiscuit, "a2a://worker", "/tasks/1?q=1", { method: "POST", headers: { "x-sam-biscuit": "spoof" }, body: "{}" });
+ assert.equal(res.status, 202);
+ assert.equal(res.text(), "listener POST /tasks/1?q=1");
+ assert.deepEqual(listenerSeen.at(-1), { url: "/tasks/1?q=1", peer: caller.peerId.toString(), biscuit: undefined });
+ // The listener answers only its own name.
+ assert.equal((await httpRequestOverStream(conn, callerBiscuit, "a2a://agent", "/")).status, 404);
+});
+
+test("what the policy does not grant is refused before the agent is reached", async () => {
+ const conn = await dial();
+ const before = backendSeen.length;
+ assert.equal((await httpRequestOverStream(conn, guestBiscuit, "a2a://agent", "/card")).status, 403);
+ // The node role is granted a2a only.
+ assert.equal((await httpRequestOverStream(conn, callerBiscuit, "inference://agent", "/")).status, 403);
+ assert.equal(backendSeen.length, before);
+ // Granted, but not this agent: 404 after authorization.
+ assert.equal((await httpRequestOverStream(conn, callerBiscuit, "a2a://other", "/card")).status, 404);
+});
+
+test("the ingress rejects a request without a biscuit and a dotted path", async () => {
+ const conn = await dial();
+ // An empty biscuit encodes to an empty header, which the server treats as missing.
+ assert.equal((await httpRequestOverStream(conn, new Uint8Array(), "a2a://agent", "/card")).status, 401);
+ // The fetch client normalizes a dot segment away before it leaves, so the
+ // server's own check is reached with a raw request.
+ const stream = await conn.newStream(HTTP_PROTOCOL, { runOnLimitedConnection: true });
+ const socket = streamToNodeDuplex(stream, agent.peerId.toString());
+ const status = await new Promise<number>((resolve, reject) => {
+ const req = http.request(
+ { method: "GET", path: "/a2a/agent/../other/x", headers: { host: agent.peerId.toString(), "x-sam-biscuit": Buffer.from(callerBiscuit).toString("base64") }, createConnection: () => socket },
+ (res) => {
+ res.resume();
+ resolve(res.statusCode ?? 0);
+ },
+ );
+ req.on("error", reject);
+ req.end();
+ });
+ socket.destroy();
+ assert.equal(status, 400);
+});
+
+test("mesh URLs name a peer and a service", () => {
+ const peer = "12D3KooWJ2Yhy3CKwVPDw7AnkxN5HbZbb65xDoRif54hdXXUzh1U";
+ assert.deepEqual(splitMeshURL(new URL(`http://mesh/sam/${peer}/a2a/agent`)), { peerId: peer, target: "/a2a/agent" });
+ assert.deepEqual(splitMeshURL(new URL(`http://anything:1/sam/${peer}/inference/llm/v1/models?x=1`)), { peerId: peer, target: "/inference/llm/v1/models?x=1" });
+ for (const bad of ["http://mesh/a2a/agent", `http://mesh/sam/${peer}`, `http://mesh/sam/${peer}/a2a`, "http://mesh/sam//a2a/agent"]) {
+ assert.throws(() => splitMeshURL(new URL(bad)), TypeError);
+ }
+ assert.equal(meshHTTPTarget("a2a://agent"), "/a2a/agent");
+ assert.equal(meshHTTPTarget("a2a://agent", "card"), "/a2a/agent/card");
+ assert.throws(() => meshHTTPTarget("ftp://agent", "/"));
+ assert.throws(() => a2aEndpoint({}), /exactly one/);
+ assert.throws(() => a2aEndpoint({ url: "http://x", handler: () => new Response() }), /exactly one/);
+});
diff --git a/sdk/js/src/libp2p-http.ts b/sdk/js/src/libp2p-http.ts
new file mode 100644
index 00000000..0b4871f9
--- /dev/null
+++ b/sdk/js/src/libp2p-http.ts
@@ -0,0 +1,486 @@
+// 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 /libp2p-http protocol (go-libp2p-http): the client that calls inference
+// and A2A services on the mesh, and the ingress that accepts A2A requests for
+// this member's own agent, gated by the authorizer the way sam-node gates its
+// ingress (StartIngressServer in internal/node). Node's own HTTP server and
+// client run over the libp2p stream, so bodies stream in both directions and
+// an A2A message/stream (SSE) works.
+
+import type { Connection, Stream, StreamHandler } from "@libp2p/interface";
+import http from "node:http";
+import { Duplex, Readable } from "node:stream";
+import { AUTH_HANDSHAKE_TIMEOUT_MS } from "./auth.ts";
+import { AuthorizationError, authorizeCaller, type ProviderAuthorizerOptions } from "./authorizer.ts";
+import type { VerifiedBiscuit } from "./biscuit.ts";
+import { canonicalPeerId } from "./identity.ts";
+
+/** go-libp2p-http's protocol: plain HTTP/1.1 on a stream, one request per stream. */
+export const HTTP_PROTOCOL = "/libp2p-http";
+
+/** Headers of the mesh HTTP datapath (api/network.go). */
+export const HEADER_SAM_BISCUIT = "x-sam-biscuit";
+export const HEADER_SAM_AGENT = "x-sam-agent";
+export const HEADER_PEER_ID = "x-peer-id";
+export const HEADER_SAM_NO_TRAILING_SLASH = "x-sam-no-trailing-slash";
+
+/** Options for libp2p.handle() so the agent is reachable over relayed connections. */
+export const HTTP_HANDLER_OPTIONS = { runOnLimitedConnection: true };
+
+/** The service name an agent answers under unless it picks another. */
+export const DEFAULT_A2A_NAME = "agent";
+
+/**
+ * The path prefix of a mesh URL, http://mesh/sam/<peer-id>/<type>/<name>/<path>:
+ * the shape of sam-node's egress proxy and of an agent card it rewrote. The
+ * host is ignored; the peer ID is in the path because URL parsers lowercase
+ * the host and a peer ID is case-sensitive.
+ */
+export const MESH_PATH_PREFIX = "/sam/";
+
+const MAX_INGRESS_BODY_BYTES = 8 * 1024 * 1024;
+const REQUEST_TIMEOUT_MS = 60_000;
+
+/** A fetch-style handler in this process. */
+export type HTTPHandler = (request: Request, caller: VerifiedBiscuit) => Promise<Response> | Response;
+
+/** A Node request listener in this process, such as an Express app with the A2A SDK's handlers mounted. */
+export type NodeRequestListener = (req: http.IncomingMessage, res: http.ServerResponse) => void;
+
+/**
+ * This member's agent as other members reach it: `a2a://<name>`, answered by
+ * exactly one of url (an A2A server beside this process), handler or
+ * listener (in this process). Authorized requests arrive with the biscuit and
+ * agent headers stripped, X-Peer-Id naming the verified caller and the path
+ * relative to /a2a/<name>, as sam-node forwards them. The endpoint is not
+ * announced anywhere; a caller reaches it by peer ID.
+ */
+export interface A2AEndpointSpec {
+ name?: string;
+ url?: string;
+ handler?: HTTPHandler;
+ listener?: NodeRequestListener;
+}
+
+export interface A2AEndpoint {
+ name: string;
+ service: string;
+ target: { url: string } | { handler: HTTPHandler } | { listener: NodeRequestListener };
+}
+
+export function a2aEndpoint(spec: A2AEndpointSpec): A2AEndpoint {
+ const name = spec.name ?? DEFAULT_A2A_NAME;
+ const given = [spec.url, spec.handler, spec.listener].filter((t) => t !== undefined).length;
+ if (given !== 1) {
+ throw new Error("an A2A endpoint is exactly one of url, handler or listener");
+ }
+ const target = spec.url !== undefined ? { url: spec.url } : spec.handler !== undefined ? { handler: spec.handler } : { listener: spec.listener as NodeRequestListener };
+ return { name, service: `a2a://${name}`, target };
+}
+
+export interface ProviderOptions extends ProviderAuthorizerOptions {
+ /** Peers the control plane has banned; refused before their token is looked at. */
+ isBanned?(peerId: string): boolean;
+ /** Called after a caller is authorized, e.g. for the session's admitted set. */
+ onAuthorized?(peerId: string, verified: VerifiedBiscuit, targetService: string): void;
+}
+
+interface StreamSocket extends Duplex {
+ remotePeer: string;
+}
+
+/**
+ * Bridges a libp2p stream to a Node Duplex so Node's own HTTP parser and
+ * client can run over it.
+ */
+export function streamToNodeDuplex(stream: Stream, remotePeer: string): StreamSocket {
+ const duplex = new Duplex({
+ read() {
+ stream.resume();
+ },
+ write(chunk: Uint8Array, _encoding, callback) {
+ if (stream.send(chunk)) {
+ callback();
+ } else {
+ stream.addEventListener("drain", () => callback(), { once: true });
+ }
+ },
+ final(callback) {
+ stream.close().then(
+ () => callback(),
+ (err: Error) => callback(err),
+ );
+ },
+ destroy(err, callback) {
+ if (err !== null) {
+ stream.abort(err);
+ } else {
+ void stream.close().catch(() => {});
+ }
+ callback(err);
+ },
+ }) as StreamSocket;
+ duplex.remotePeer = remotePeer;
+ stream.addEventListener("message", (evt) => {
+ if (!duplex.push(Buffer.from(evt.data.subarray()))) {
+ stream.pause();
+ }
+ });
+ const end = () => {
+ if (!duplex.readableEnded) {
+ duplex.push(null);
+ }
+ };
+ stream.addEventListener("remoteCloseWrite", end);
+ stream.addEventListener("close", end);
+ return duplex;
+}
+
+/** Reads a whole body, bounded. */
+async function readBody(readable: Readable, limit: number): Promise<Buffer> {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ for await (const chunk of readable) {
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
+ size += buf.length;
+ if (size > limit) {
+ throw new Error(`body exceeds ${limit} bytes`);
+ }
+ chunks.push(buf);
+ }
+ return Buffer.concat(chunks);
+}
+
+function hasDotSegment(path: string): boolean {
+ return path.split("/").some((seg) => seg === "." || seg === "..");
+}
+
+/**
+ * Server side of /libp2p-http, as sam-node's StartIngressServer: the path is
+ * /<type>/<name>[/<upstream>], the caller's biscuit is X-Sam-Biscuit, and the
+ * request is authorized for <type>://<name> before anything is forwarded. Only
+ * the agent's own endpoint is answered; anything else is 404 after
+ * authorization, so an unauthorized caller learns nothing about it.
+ */
+export function httpIngressHandler(endpoint: A2AEndpoint, options: ProviderOptions): StreamHandler {
+ const server = http.createServer({ keepAlive: false }, (req, res) => {
+ void handleIngress(req, res, endpoint, options).catch((err: unknown) => {
+ if (!res.headersSent) {
+ res.writeHead(500, { "content-type": "text/plain" });
+ }
+ res.end(`ingress error: ${err instanceof Error ? err.message : String(err)}\n`);
+ });
+ });
+ server.headersTimeout = AUTH_HANDSHAKE_TIMEOUT_MS;
+ return (stream: Stream, connection: Connection) => {
+ server.emit("connection", streamToNodeDuplex(stream, connection.remotePeer.toString()));
+ };
+}
+
+async function handleIngress(req: http.IncomingMessage, res: http.ServerResponse, endpoint: A2AEndpoint, options: ProviderOptions): Promise<void> {
+ const remotePeer = (req.socket as unknown as StreamSocket).remotePeer;
+ const reply = (status: number, text: string) => {
+ res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
+ res.end(text + "\n");
+ };
+
+ const rawURL = req.url ?? "/";
+ // Policy is decided on the /<type>/<name> prefix; a dot segment in what
+ // follows could resolve to a sibling path on the backend. Checked on the
+ // raw path, before URL parsing normalizes it away.
+ if (hasDotSegment(rawURL.split("?")[0] as string)) {
+ reply(400, "Invalid path");
+ return;
+ }
+ const url = new URL(rawURL, "http://mesh.invalid");
+ const parts = url.pathname.replace(/^\//, "").split("/");
+ if (parts.length < 2 || parts[0] === "" || parts[1] === "") {
+ reply(400, "Invalid path");
+ return;
+ }
+ const [serviceType, serviceName, ...rest] = parts as [string, string, ...string[]];
+ if (serviceType !== "inference" && serviceType !== "a2a" && serviceType !== "mcp") {
+ reply(400, "Invalid service type");
+ return;
+ }
+ const upstreamPath = rest.join("/");
+
+ const biscuitB64 = req.headers[HEADER_SAM_BISCUIT];
+ if (typeof biscuitB64 !== "string" || biscuitB64 === "") {
+ reply(401, "Missing X-Sam-Biscuit header");
+ return;
+ }
+ let biscuit: Uint8Array;
+ try {
+ biscuit = new Uint8Array(Buffer.from(biscuitB64, "base64"));
+ if (biscuit.length === 0) {
+ throw new Error("empty");
+ }
+ } catch {
+ reply(400, "Invalid X-Sam-Biscuit encoding");
+ return;
+ }
+
+ const targetService = `${serviceType}://${serviceName}`;
+ if (options.isBanned?.(remotePeer) === true) {
+ reply(403, "Authorization failed");
+ return;
+ }
+ const agentHeader = req.headers[HEADER_SAM_AGENT];
+ let verified: VerifiedBiscuit;
+ try {
+ verified = await authorizeCaller(
+ { biscuit, peerId: remotePeer, targetService, protocol: HTTP_PROTOCOL, agent: typeof agentHeader === "string" ? agentHeader : "" },
+ options,
+ );
+ } catch (err) {
+ if (err instanceof AuthorizationError) {
+ reply(403, "Authorization failed");
+ return;
+ }
+ throw err;
+ }
+ options.onAuthorized?.(remotePeer, verified, targetService);
+
+ // Under the type the policy was evaluated on.
+ if (targetService !== endpoint.service) {
+ reply(404, "Service not found");
+ return;
+ }
+
+ const path = "/" + upstreamPath + url.search;
+ const noTrailingSlash = upstreamPath === "" && rest.length === 0;
+
+ if ("listener" in endpoint.target) {
+ // The listener sees the request as a backend behind sam-node would: the
+ // path relative to the service, the verified caller, never the biscuit.
+ // X-Peer-Id is set, not added, so an inbound value cannot pose as the
+ // verified peer.
+ req.url = path;
+ delete req.headers[HEADER_SAM_BISCUIT];
+ delete req.headers[HEADER_SAM_AGENT];
+ req.headers[HEADER_PEER_ID] = remotePeer;
+ if (noTrailingSlash) {
+ req.headers[HEADER_SAM_NO_TRAILING_SLASH] = "true";
+ } else {
+ delete req.headers[HEADER_SAM_NO_TRAILING_SLASH];
+ }
+ endpoint.target.listener(req, res);
+ return;
+ }
+
+ const headers = new Headers();
+ for (const [k, v] of Object.entries(req.headers)) {
+ if (v === undefined || k === HEADER_SAM_BISCUIT || k === HEADER_SAM_AGENT || k === HEADER_SAM_NO_TRAILING_SLASH || k === HEADER_PEER_ID || k === "host" || k === "connection" || k === "transfer-encoding" || k === "content-length") {
+ continue;
+ }
+ for (const value of Array.isArray(v) ? v : [v]) {
+ headers.append(k, value);
+ }
+ }
+ headers.set(HEADER_PEER_ID, remotePeer);
+ if (noTrailingSlash) {
+ headers.set(HEADER_SAM_NO_TRAILING_SLASH, "true");
+ }
+
+ const method = req.method ?? "GET";
+ const body: Uint8Array<ArrayBuffer> | undefined =
+ method === "GET" || method === "HEAD" ? undefined : new Uint8Array(await readBody(req, MAX_INGRESS_BODY_BYTES));
+ const init: RequestInit = { method, headers };
+ if (body !== undefined) {
+ init.body = body;
+ }
+
+ let response: Response;
+ if ("url" in endpoint.target) {
+ const base = endpoint.target.url.replace(/\/$/, "");
+ response = await fetch(base + path, { ...init, redirect: "manual" });
+ } else {
+ response = await endpoint.target.handler(new Request("http://" + endpoint.name + path, init), verified);
+ }
+
+ const outHeaders: Record<string, string | string[]> = {};
+ response.headers.forEach((value, key) => {
+ if (key === "content-length" || key === "transfer-encoding" || key === "connection") {
+ return;
+ }
+ outHeaders[key] = value;
+ });
+ res.writeHead(response.status, outHeaders);
+ if (response.body === null) {
+ res.end();
+ return;
+ }
+ await new Promise<void>((resolve, reject) => {
+ Readable.fromWeb(response.body as import("node:stream/web").ReadableStream)
+ .on("error", reject)
+ .pipe(res)
+ .on("finish", resolve)
+ .on("error", reject);
+ });
+}
+
+/** The request target for a service on a peer: /<type>/<name>/<path>. */
+export function meshHTTPTarget(targetService: string, path = ""): string {
+ const m = /^(inference|a2a|mcp):\/\/(.+)$/.exec(targetService);
+ if (m === null) {
+ throw new Error(`service target must look like inference://<name>, got ${JSON.stringify(targetService)}`);
+ }
+ if (path === "") {
+ return `/${m[1]}/${m[2]}`;
+ }
+ return `/${m[1]}/${m[2]}${path.startsWith("/") ? path : "/" + path}`;
+}
+
+/**
+ * The URL a fetch bound to a session (session.fetch()) takes for a service
+ * on a peer: http://mesh/sam/<peer-id>/<type>/<name>/<path>.
+ */
+export function meshURL(peerId: string, targetService: string, path = ""): string {
+ return "http://mesh" + MESH_PATH_PREFIX + canonicalPeerId(peerId) + meshHTTPTarget(targetService, path);
+}
+
+/** (peer ID, request target) of a mesh URL; the target is what the peer's ingress takes. */
+export function splitMeshURL(url: URL): { peerId: string; target: string } {
+ if (!url.pathname.startsWith(MESH_PATH_PREFIX)) {
+ throw new TypeError(`a mesh URL looks like http://mesh${MESH_PATH_PREFIX}<peer-id>/<type>/<name>/..., got ${url.toString()}`);
+ }
+ const [peerId = "", ...rest] = url.pathname.slice(MESH_PATH_PREFIX.length).split("/");
+ if (peerId === "" || rest.length < 2 || rest[0] === "" || rest[1] === "") {
+ throw new TypeError(`a mesh URL names a peer, a service type and a name, got ${url.toString()}`);
+ }
+ return { peerId, target: "/" + rest.join("/") + url.search };
+}
+
+export interface HTTPStreamOptions {
+ /** The agent this request is made for. */
+ agent?: string;
+ /** Bounds the whole exchange; without one, the response headers must arrive within a minute and the body is unbounded. */
+ signal?: AbortSignal;
+}
+
+/**
+ * Client side of /libp2p-http, as go-libp2p-http's RoundTripper: one stream
+ * per request, plain HTTP/1.1 with Host set to the peer ID and the biscuit in
+ * X-Sam-Biscuit. Resolves once the response headers are in; the body streams
+ * after, so an SSE response is consumed as the peer sends it.
+ */
+export async function fetchOverStream(conn: Connection, biscuit: Uint8Array, request: Request, options: HTTPStreamOptions = {}): Promise<Response> {
+ const { target } = splitMeshURL(new URL(request.url));
+ const peerId = conn.remotePeer.toString();
+ // One controller ends the exchange: the caller's signal at any time, the
+ // headers timeout only until the response headers are in.
+ const ctl = new AbortController();
+ let headersIn = false;
+ const forward = (s: AbortSignal | undefined) => s?.addEventListener("abort", () => ctl.abort(s.reason), { once: true });
+ forward(options.signal);
+ forward(request.signal);
+ if (options.signal === undefined) {
+ const timer = setTimeout(() => {
+ if (!headersIn) {
+ ctl.abort(new DOMException(`no response headers from ${peerId} within ${REQUEST_TIMEOUT_MS}ms`, "TimeoutError"));
+ }
+ }, REQUEST_TIMEOUT_MS);
+ timer.unref?.();
+ }
+ const signal = ctl.signal;
+ const stream = await conn.newStream(HTTP_PROTOCOL, { signal, runOnLimitedConnection: true });
+ const socket = streamToNodeDuplex(stream, peerId);
+ const headers: Record<string, string> = {};
+ request.headers.forEach((value, key) => {
+ if (key !== "host" && key !== "content-length" && key !== HEADER_SAM_BISCUIT && key !== HEADER_PEER_ID) {
+ headers[key] = value;
+ }
+ });
+ headers.host = peerId;
+ headers[HEADER_SAM_BISCUIT] = Buffer.from(biscuit).toString("base64");
+ if (options.agent) {
+ headers[HEADER_SAM_AGENT] = options.agent;
+ }
+ const body = request.body === null ? undefined : Buffer.from(await request.arrayBuffer());
+ headers["content-length"] = String(body?.length ?? 0);
+
+ return new Promise<Response>((resolve, reject) => {
+ const req = http.request({ method: request.method, path: target, headers, createConnection: () => socket, signal }, (res) => {
+ headersIn = true;
+ const responseHeaders = new Headers();
+ for (const [k, v] of Object.entries(res.headers)) {
+ if (typeof v === "string") {
+ responseHeaders.set(k, v);
+ } else if (Array.isArray(v)) {
+ responseHeaders.set(k, v.join(", "));
+ }
+ }
+ res.on("close", () => socket.destroy());
+ const status = res.statusCode ?? 0;
+ const bodyStream = Readable.toWeb(res) as ReadableStream<Uint8Array>;
+ resolve(new Response(status === 204 || status === 304 || request.method === "HEAD" ? null : bodyStream, { status, statusText: res.statusMessage ?? "", headers: responseHeaders }));
+ });
+ req.on("error", (err) => {
+ socket.destroy();
+ reject(err);
+ });
+ if (body !== undefined) {
+ req.write(body);
+ }
+ req.end();
+ });
+}
+
+export interface HTTPRequestOptions {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: Uint8Array | string;
+ /** The agent this request is made for. */
+ agent?: string;
+ signal?: AbortSignal;
+}
+
+export interface HTTPResponse {
+ status: number;
+ headers: Record<string, string>;
+ body: Uint8Array;
+ text(): string;
+}
+
+/** One request to /<type>/<name>/<path> on a peer, body read whole. */
+export async function httpRequestOverStream(
+ conn: Connection,
+ biscuit: Uint8Array,
+ targetService: string,
+ path: string,
+ options: HTTPRequestOptions = {},
+): Promise<HTTPResponse> {
+ const signal = options.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS);
+ const init: RequestInit = { method: options.method ?? "GET", headers: options.headers ?? {}, signal };
+ if (options.body !== undefined) {
+ init.body = options.body as BodyInit;
+ }
+ const request = new Request(meshURL(conn.remotePeer.toString(), targetService, path), init);
+ const streamOptions: HTTPStreamOptions = { signal };
+ if (options.agent !== undefined) {
+ streamOptions.agent = options.agent;
+ }
+ const response = await fetchOverStream(conn, biscuit, request, streamOptions);
+ const buf = new Uint8Array(await response.arrayBuffer());
+ if (buf.length > MAX_INGRESS_BODY_BYTES) {
+ throw new Error("response body too large");
+ }
+ const flat: Record<string, string> = {};
+ response.headers.forEach((value, key) => {
+ flat[key] = value;
+ });
+ return { status: response.status, headers: flat, body: buf, text: () => new TextDecoder().decode(buf) };
+}
diff --git a/sdk/js/src/serve.test.ts b/sdk/js/src/serve.test.ts
deleted file mode 100644
index c7430681..00000000
--- a/sdk/js/src/serve.test.ts
+++ /dev/null
@@ -1,240 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// The provider side in one process: this SDK's handlers for /sam/mcp/1.0.0
-// and /libp2p-http behind a js-libp2p host, called with this SDK's clients.
-// The real sam-node as a caller is exercised by tests/integration.
-
-import { create, toBinary } from "@bufbuild/protobuf";
-import { yamux } from "@chainsafe/libp2p-yamux";
-import { identify } from "@libp2p/identify";
-import type { Connection, Libp2p } from "@libp2p/interface";
-import { tcp } from "@libp2p/tcp";
-import { tls } from "@libp2p/tls";
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import { createLibp2p } from "libp2p";
-import assert from "node:assert/strict";
-import http from "node:http";
-import { after, before, test } from "node:test";
-import { z } from "zod";
-import { AuthRejectedError, MCP_PROTOCOL } from "./auth.ts";
-import { loadBiscuit } from "./biscuit.ts";
-import { ROLE_NODE } from "./controlplane.ts";
-import { AuthFrameSchema } from "./gen/sam_pb.ts";
-import { openMCPSession } from "./mcp.ts";
-import { HTTP_PROTOCOL, ServiceRegistry, httpIngressHandler, httpRequestOverStream, mcpStreamHandler, type ProviderOptions } from "./serve.ts";
-
-type Wasm = Awaited<ReturnType<typeof loadBiscuit>>;
-
-let wasm: Wasm;
-let cpKeyPair: InstanceType<Wasm["KeyPair"]>;
-let cpKey: Uint8Array;
-let provider: Libp2p;
-let providerBiscuit: Uint8Array;
-let caller: Libp2p;
-let callerBiscuit: Uint8Array;
-let guestBiscuit: Uint8Array;
-let backend: http.Server;
-let backendURL: string;
-const backendSeen: { method: string; url: string; peer: string | undefined; body: string }[] = [];
-const authorized: string[] = [];
-
-function mint(peerId: string, role: string, extra: string[] = []): Uint8Array {
- const b = wasm.Biscuit.builder();
- b.addFact(wasm.Fact.fromString(`node(${JSON.stringify(peerId)})`));
- b.addFact(wasm.Fact.fromString(`client_peer_id(${JSON.stringify(peerId)})`));
- b.addFact(wasm.Fact.fromString("expiration(2035-01-01T00:00:00Z)"));
- b.addFact(wasm.Fact.fromString(`role(${JSON.stringify(role)})`));
- for (const f of extra) {
- b.addFact(wasm.Fact.fromString(f));
- }
- return b.build(cpKeyPair.getPrivateKey()).toBytes();
-}
-
-function newHost(): Promise<Libp2p> {
- return createLibp2p({
- addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },
- transports: [tcp()],
- connectionEncrypters: [tls()],
- streamMuxers: [yamux()],
- services: { identify: identify() },
- });
-}
-
-// What the control plane renders for a policy granting the node role calc,
-// echo and every inference service on any target.
-const POLICY_RULES = [
- `granted_service_set("mcp", ["calc"]) <- role("sam:role:node")`,
- `granted_service_all("inference") <- role("sam:role:node")`,
- `granted_service_all("sam:system") <- role("sam:role:node")`,
- `target_unrestricted(true) <- role("sam:role:node")`,
-];
-
-before(async () => {
- wasm = await loadBiscuit();
- cpKeyPair = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
- cpKey = new Uint8Array(Buffer.from(cpKeyPair.getPublicKey().toString().replace(/^ed25519\//, ""), "hex"));
-
- backend = http.createServer((req, res) => {
- let body = "";
- req.on("data", (c: Buffer) => (body += c.toString()));
- req.on("end", () => {
- backendSeen.push({ method: req.method ?? "", url: req.url ?? "", peer: req.headers["x-peer-id"] as string | undefined, body });
- assert.equal(req.headers["x-sam-biscuit"], undefined, "biscuit leaked to the backend");
- res.writeHead(200, { "content-type": "application/json", "x-backend": "fake" });
- res.end(JSON.stringify({ path: req.url, echo: body }));
- });
- });
- await new Promise<void>((resolve) => backend.listen(0, "127.0.0.1", resolve));
- const addr = backend.address() as { port: number };
- backendURL = `http://127.0.0.1:${addr.port}`;
-
- provider = await newHost();
- providerBiscuit = mint(provider.peerId.toString(), ROLE_NODE);
- const registry = new ServiceRegistry();
- registry.add({
- type: "mcp",
- name: "calc",
- createServer: () => {
- const server = new McpServer({ name: "calc", version: "0.0.1" });
- server.tool("add", { a: z.number(), b: z.number() }, async ({ a, b }) => ({ content: [{ type: "text", text: String(a + b) }] }));
- return server;
- },
- });
- registry.add({ type: "inference", name: "llm", target: backendURL });
- registry.add({
- type: "inference",
- name: "inproc",
- target: (request, verified) => new Response(`hello ${verified.peerId} ${request.method} ${new URL(request.url).pathname}`, { status: 201 }),
- });
- const options: ProviderOptions = {
- trustedKeys: () => [cpKey],
- ownBiscuit: () => providerBiscuit,
- policyRules: () => POLICY_RULES,
- onAuthorized: (peerId, _v, target) => authorized.push(`${peerId} ${target}`),
- };
- await provider.handle(MCP_PROTOCOL, mcpStreamHandler(registry, options, MCP_PROTOCOL), { runOnLimitedConnection: true });
- await provider.handle(HTTP_PROTOCOL, httpIngressHandler(registry, options), { runOnLimitedConnection: true });
-
- caller = await newHost();
- callerBiscuit = mint(caller.peerId.toString(), ROLE_NODE);
- guestBiscuit = mint(caller.peerId.toString(), "sam:role:guest");
-});
-
-after(async () => {
- await caller.stop();
- await provider.stop();
- await new Promise<void>((resolve) => backend.close(() => resolve()));
-});
-
-function frame(target: string, biscuit = callerBiscuit): Uint8Array {
- return toBinary(AuthFrameSchema, create(AuthFrameSchema, { biscuit, targetService: target }));
-}
-
-async function dial(): Promise<Connection> {
- return caller.dial(provider.getMultiaddrs()[0] as Parameters<typeof caller.dial>[0]);
-}
-
-test("an MCP service is served to an authorized caller", async () => {
- const mcp = await openMCPSession(await dial(), frame("mcp://calc"), [cpKey]);
- try {
- assert.equal(mcp.provider.peerId, provider.peerId.toString());
- assert.deepEqual((await mcp.client.listTools()).tools.map((t) => t.name), ["add"]);
- const result = await mcp.client.callTool({ name: "add", arguments: { a: 2, b: 3 } });
- assert.deepEqual(result.content, [{ type: "text", text: "5" }]);
- } finally {
- await mcp.close();
- }
- assert.ok(authorized.includes(`${caller.peerId.toString()} mcp://calc`));
-});
-
-test("the empty target is the member's own catalog", async () => {
- const mcp = await openMCPSession(await dial(), frame(""), [cpKey]);
- try {
- const result = await mcp.client.callTool({ name: "list_local_services", arguments: {} });
- const text = (result.content as Array<{ text: string }>)[0]?.text ?? "";
- const services = JSON.parse(text) as Array<{ type: string; name: string }>;
- assert.deepEqual(
- services.map((s) => `${s.type}://${s.name}`).sort(),
- ["inference://inproc", "inference://llm", "mcp://calc"],
- );
- } finally {
- await mcp.close();
- }
-});
-
-test("a caller whose role grants nothing gets AuthResponse{success: false}", async () => {
- await assert.rejects(openMCPSession(await dial(), frame("mcp://calc", guestBiscuit), [cpKey]), (err: unknown) => {
- assert.ok(err instanceof AuthRejectedError, String(err));
- assert.match(err.message, /not authorized/);
- return true;
- });
-});
-
-test("a service the role was not granted is denied before the service is looked up", async () => {
- await assert.rejects(openMCPSession(await dial(), frame("mcp://secret"), [cpKey]), AuthRejectedError);
-});
-
-test("a granted service the member does not have closes the stream after the answer", async () => {
- // echo is granted by the policy, not registered: the answer is success, then nothing.
- await assert.rejects(openMCPSession(await dial(), frame("mcp://echo"), [cpKey]));
-});
-
-test("an inference service is proxied to its backend with the caller's identity", async () => {
- const conn = await dial();
- const res = await httpRequestOverStream(conn, callerBiscuit, "inference://llm", "/v1/models?x=1", { headers: { "x-sam-biscuit": "spoof" } });
- assert.equal(res.status, 200);
- assert.equal(res.headers["x-backend"], "fake");
- assert.deepEqual(JSON.parse(res.text()), { path: "/v1/models?x=1", echo: "" });
- const seen = backendSeen.at(-1);
- assert.equal(seen?.peer, caller.peerId.toString());
-
- const post = await httpRequestOverStream(conn, callerBiscuit, "inference://llm", "/v1/chat/completions", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ model: "m" }),
- });
- assert.equal(post.status, 200);
- assert.equal(JSON.parse(post.text()).echo, JSON.stringify({ model: "m" }));
-});
-
-test("an in-process handler sees the verified caller", async () => {
- const res = await httpRequestOverStream(await dial(), callerBiscuit, "inference://inproc", "/agent/card");
- assert.equal(res.status, 201);
- assert.equal(res.text(), `hello ${caller.peerId.toString()} GET /agent/card`);
-});
-
-test("HTTP ingress refuses what the policy does not grant", async () => {
- const conn = await dial();
- // The guest role has no grants: 403 before anything reaches the backend.
- const before = backendSeen.length;
- const denied = await httpRequestOverStream(conn, guestBiscuit, "inference://llm", "/v1/models");
- assert.equal(denied.status, 403);
- assert.equal(backendSeen.length, before);
- // A2A is not granted to the node role either.
- const a2a = await httpRequestOverStream(conn, callerBiscuit, "a2a://llm", "/");
- assert.equal(a2a.status, 403);
- // Granted but not registered: 404 after authorization.
- const missing = await httpRequestOverStream(conn, callerBiscuit, "inference://nope", "/");
- assert.equal(missing.status, 404);
-});
-
-test("HTTP ingress rejects a request without a biscuit and a dotted path", async () => {
- const conn = await dial();
- const noBiscuit = await httpRequestOverStream(conn, new Uint8Array(), "inference://llm", "/v1/models").catch((err: Error) => err);
- // An empty biscuit encodes to an empty header, which the server treats as missing.
- assert.ok(!(noBiscuit instanceof Error) && noBiscuit.status === 401, String(noBiscuit instanceof Error ? noBiscuit : noBiscuit.status));
- const dotted = await httpRequestOverStream(conn, callerBiscuit, "inference://llm", "/../other/x");
- assert.equal(dotted.status, 400);
-});
diff --git a/sdk/js/src/serve.ts b/sdk/js/src/serve.ts
deleted file mode 100644
index fe017c69..00000000
--- a/sdk/js/src/serve.ts
+++ /dev/null
@@ -1,495 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// The provider side: /sam/mcp/1.0.0 for MCP services and /libp2p-http for
-// inference and A2A services, both gated by the authorizer the way sam-node
-// gates them (WithBiscuitAuth and StartIngressServer in internal/node).
-
-import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
-import type { Connection, Stream, StreamHandler } from "@libp2p/interface";
-import { lpStream } from "@libp2p/utils";
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
-import http from "node:http";
-import { Duplex, Readable } from "node:stream";
-import { AUTH_HANDSHAKE_TIMEOUT_MS, MAX_AUTH_FRAME_BYTES } from "./auth.ts";
-import { AuthorizationError, authorizeCaller, type ProviderAuthorizerOptions } from "./authorizer.ts";
-import type { VerifiedBiscuit } from "./biscuit.ts";
-import type { ServiceType } from "./discovery.ts";
-import { AuthFrameSchema, AuthResponseSchema } from "./gen/sam_pb.ts";
-import { StreamTransport } from "./mcp.ts";
-
-/** go-libp2p-http's protocol: plain HTTP/1.1 on a stream, one request per stream. */
-export const HTTP_PROTOCOL = "/libp2p-http";
-
-/** Headers of the mesh HTTP datapath (api/network.go). */
-export const HEADER_SAM_BISCUIT = "x-sam-biscuit";
-export const HEADER_SAM_AGENT = "x-sam-agent";
-export const HEADER_PEER_ID = "x-peer-id";
-export const HEADER_SAM_NO_TRAILING_SLASH = "x-sam-no-trailing-slash";
-
-/** Options for libp2p.handle() so services are reachable over relayed connections. */
-export const SERVE_HANDLER_OPTIONS = { runOnLimitedConnection: true };
-
-/** Anything with the MCP SDK's connect(): McpServer or the low-level Server. */
-export interface MCPServerLike {
- connect(transport: Transport): Promise<void>;
- close(): Promise<void>;
-}
-
-/** An MCP service: one server per session, since an MCP server holds one transport. */
-export interface MCPServiceSpec {
- type: "mcp";
- name: string;
- description?: string;
- createServer(): MCPServerLike;
-}
-
-/** A fetch-style handler for an HTTP service. */
-export type HTTPHandler = (request: Request, caller: VerifiedBiscuit) => Promise<Response> | Response;
-
-/**
- * An inference or A2A service: authorized requests are forwarded to target,
- * a base URL of a local backend or a handler in this process. The request
- * path is what followed /<type>/<name>/; the biscuit and agent headers are
- * stripped and X-Peer-Id names the verified caller, as sam-node does.
- */
-export interface HTTPServiceSpec {
- type: "inference" | "a2a";
- name: string;
- description?: string;
- target: string | HTTPHandler;
-}
-
-export type ServiceSpec = MCPServiceSpec | HTTPServiceSpec;
-
-export interface ServedService {
- type: ServiceType;
- name: string;
- description: string;
-}
-
-/** The request as seen by an HTTP handler; the Node http types are hidden. */
-interface StreamSocket extends Duplex {
- remotePeer: string;
-}
-
-/**
- * Bridges a libp2p stream to a Node Duplex so Node's own HTTP parser and
- * client can run over it.
- */
-export function streamToNodeDuplex(stream: Stream, remotePeer: string): StreamSocket {
- const duplex = new Duplex({
- read() {
- stream.resume();
- },
- write(chunk: Uint8Array, _encoding, callback) {
- if (stream.send(chunk)) {
- callback();
- } else {
- stream.addEventListener("drain", () => callback(), { once: true });
- }
- },
- final(callback) {
- stream.close().then(
- () => callback(),
- (err: Error) => callback(err),
- );
- },
- destroy(err, callback) {
- if (err !== null) {
- stream.abort(err);
- } else {
- void stream.close().catch(() => {});
- }
- callback(err);
- },
- }) as StreamSocket;
- duplex.remotePeer = remotePeer;
- stream.addEventListener("message", (evt) => {
- if (!duplex.push(Buffer.from(evt.data.subarray()))) {
- stream.pause();
- }
- });
- const end = () => {
- if (!duplex.readableEnded) {
- duplex.push(null);
- }
- };
- stream.addEventListener("remoteCloseWrite", end);
- stream.addEventListener("close", end);
- return duplex;
-}
-
-export interface ProviderOptions extends ProviderAuthorizerOptions {
- /** This provider's current biscuit, for the mutual AuthResponse. */
- ownBiscuit(): Uint8Array;
- /** Peers the control plane has banned; refused before their token is looked at. */
- isBanned?(peerId: string): boolean;
- /** Called after a caller is authorized for a service, e.g. for the session's admitted set. */
- onAuthorized?(peerId: string, verified: VerifiedBiscuit, targetService: string): void;
-}
-
-/** Services registered on a member, keyed by type and name. */
-export class ServiceRegistry {
- readonly #services = new Map<string, ServiceSpec>();
-
- static key(type: string, name: string): string {
- return `${type}://${name}`;
- }
-
- add(spec: ServiceSpec): void {
- const key = ServiceRegistry.key(spec.type, spec.name);
- if (this.#services.has(key)) {
- throw new Error(`service ${key} is already registered`);
- }
- this.#services.set(key, spec);
- }
-
- remove(type: ServiceType, name: string): boolean {
- return this.#services.delete(ServiceRegistry.key(type, name));
- }
-
- get(type: string, name: string): ServiceSpec | undefined {
- return this.#services.get(ServiceRegistry.key(type, name));
- }
-
- list(): ServedService[] {
- return [...this.#services.values()].map((s) => ({ type: s.type, name: s.name, description: s.description ?? "" }));
- }
-}
-
-async function refuse(stream: Stream, peerId: string, reason: string, signal: AbortSignal): Promise<void> {
- stream.log?.("refusing %s: %s", peerId, reason);
- const lp = lpStream(stream, { maxDataLength: MAX_AUTH_FRAME_BYTES });
- await lp.write(toBinary(AuthResponseSchema, create(AuthResponseSchema, { success: false, error: reason })), { signal }).catch(() => {});
-}
-
-/**
- * Server side of /sam/mcp/1.0.0, as sam-node's WithBiscuitAuth(HandleMCPStream):
- * read the AuthFrame, authorize the caller for the named service, answer with
- * our own credential, then hand the stream to that service's MCP server. A
- * denied caller gets AuthResponse{success: false}; an unknown service closes
- * the stream after a successful answer, which is what sam-node does.
- */
-export function mcpStreamHandler(registry: ServiceRegistry, options: ProviderOptions, protocol: string): StreamHandler {
- return async (stream: Stream, connection: Connection) => {
- const peerId = connection.remotePeer.toString();
- const signal = AbortSignal.timeout(AUTH_HANDSHAKE_TIMEOUT_MS);
- let handedOff = false;
- try {
- const lp = lpStream(stream, { maxDataLength: MAX_AUTH_FRAME_BYTES });
- const frame = fromBinary(AuthFrameSchema, (await lp.read({ signal })).subarray());
- if (options.isBanned?.(peerId) === true) {
- await refuse(stream, peerId, "peer is revoked", signal);
- return;
- }
- let verified: VerifiedBiscuit;
- try {
- verified = await authorizeCaller({ biscuit: frame.biscuit, peerId, targetService: frame.targetService, protocol, agent: frame.agent }, options);
- } catch (err) {
- if (err instanceof AuthorizationError) {
- await refuse(stream, peerId, err.message, signal);
- return;
- }
- throw err;
- }
- options.onAuthorized?.(peerId, verified, frame.targetService);
- await lp.write(toBinary(AuthResponseSchema, create(AuthResponseSchema, { success: true, biscuit: options.ownBiscuit() })), { signal });
-
- if (frame.targetService === "") {
- // The member's own catalog: what sam-node serves for an empty target.
- handedOff = true;
- await serveMCP(stream, catalogServer(registry));
- return;
- }
- const m = /^mcp:\/\/(.+)$/.exec(frame.targetService);
- const spec = m !== null ? registry.get("mcp", m[1] as string) : undefined;
- if (spec === undefined || spec.type !== "mcp") {
- stream.log?.("no MCP service %s for %s", frame.targetService, peerId);
- return;
- }
- handedOff = true;
- await serveMCP(stream, spec.createServer());
- } finally {
- if (!handedOff) {
- await stream.close().catch(() => stream.abort(new Error("mcp stream close failed")));
- }
- }
- };
-}
-
-/** Runs one MCP server over the stream until the caller goes away. */
-async function serveMCP(stream: Stream, server: MCPServerLike): Promise<void> {
- const transport = new StreamTransport(stream);
- const closed = new Promise<void>((resolve) => {
- // The MCP Protocol takes over transport.onclose; its own onclose fires after.
- const proto = ("server" in server ? (server as { server: { onclose?: () => void } }).server : server) as { onclose?: () => void };
- proto.onclose = () => resolve();
- });
- await server.connect(transport);
- await closed;
- await server.close().catch(() => {});
-}
-
-/**
- * The member's own catalog over MCP, as sam-node's list_local_services: the
- * services this member publishes. Built per session with the MCP SDK.
- */
-function catalogServer(registry: ServiceRegistry): MCPServerLike {
- const server = new McpServer({ name: "agent-mesh-sdk", version: "0.1.0" });
- server.registerTool("list_local_services", { description: "List the services this member publishes on the mesh" }, () => ({
- content: [{ type: "text", text: JSON.stringify(registry.list()) }],
- }));
- return server;
-}
-
-const MAX_INGRESS_BODY_BYTES = 8 * 1024 * 1024;
-
-/** Reads a whole body, bounded. */
-async function readBody(readable: Readable, limit: number): Promise<Buffer> {
- const chunks: Buffer[] = [];
- let size = 0;
- for await (const chunk of readable) {
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
- size += buf.length;
- if (size > limit) {
- throw new Error(`body exceeds ${limit} bytes`);
- }
- chunks.push(buf);
- }
- return Buffer.concat(chunks);
-}
-
-function hasDotSegment(path: string): boolean {
- return path.split("/").some((seg) => seg === "." || seg === "..");
-}
-
-/**
- * Server side of /libp2p-http, as sam-node's StartIngressServer: the path is
- * /<type>/<name>[/<upstream>], the caller's biscuit is X-Sam-Biscuit, and
- * the request is authorized for <type>://<name> before anything is forwarded.
- * Node's own HTTP server parses the stream.
- */
-export function httpIngressHandler(registry: ServiceRegistry, options: ProviderOptions): StreamHandler {
- const server = http.createServer({ keepAlive: false }, (req, res) => {
- void handleIngress(req, res, registry, options).catch((err: unknown) => {
- if (!res.headersSent) {
- res.writeHead(500, { "content-type": "text/plain" });
- }
- res.end(`ingress error: ${err instanceof Error ? err.message : String(err)}\n`);
- });
- });
- server.headersTimeout = AUTH_HANDSHAKE_TIMEOUT_MS;
- return (stream: Stream, connection: Connection) => {
- server.emit("connection", streamToNodeDuplex(stream, connection.remotePeer.toString()));
- };
-}
-
-async function handleIngress(req: http.IncomingMessage, res: http.ServerResponse, registry: ServiceRegistry, options: ProviderOptions): Promise<void> {
- const remotePeer = (req.socket as unknown as StreamSocket).remotePeer;
- const reply = (status: number, text: string) => {
- res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
- res.end(text + "\n");
- };
-
- const rawURL = req.url ?? "/";
- // Policy is decided on the /<type>/<name> prefix; a dot segment in what
- // follows could resolve to a sibling service on a shared backend. Checked
- // on the raw path, before URL parsing normalizes it away.
- if (hasDotSegment(rawURL.split("?")[0] as string)) {
- reply(400, "Invalid path");
- return;
- }
- const url = new URL(rawURL, "http://mesh.invalid");
- const parts = url.pathname.replace(/^\//, "").split("/");
- if (parts.length < 2 || parts[0] === "" || parts[1] === "") {
- reply(400, "Invalid path");
- return;
- }
- const [serviceType, serviceName, ...rest] = parts as [string, string, ...string[]];
- if (serviceType !== "inference" && serviceType !== "a2a" && serviceType !== "mcp") {
- reply(400, "Invalid service type");
- return;
- }
- const upstreamPath = rest.join("/");
-
- const biscuitB64 = req.headers[HEADER_SAM_BISCUIT];
- if (typeof biscuitB64 !== "string" || biscuitB64 === "") {
- reply(401, "Missing X-Sam-Biscuit header");
- return;
- }
- let biscuit: Uint8Array;
- try {
- biscuit = new Uint8Array(Buffer.from(biscuitB64, "base64"));
- if (biscuit.length === 0) {
- throw new Error("empty");
- }
- } catch {
- reply(400, "Invalid X-Sam-Biscuit encoding");
- return;
- }
-
- const targetService = `${serviceType}://${serviceName}`;
- if (options.isBanned?.(remotePeer) === true) {
- reply(403, "Authorization failed");
- return;
- }
- const agentHeader = req.headers[HEADER_SAM_AGENT];
- let verified: VerifiedBiscuit;
- try {
- verified = await authorizeCaller(
- { biscuit, peerId: remotePeer, targetService, protocol: HTTP_PROTOCOL, agent: typeof agentHeader === "string" ? agentHeader : "" },
- options,
- );
- } catch (err) {
- if (err instanceof AuthorizationError) {
- reply(403, "Authorization failed");
- return;
- }
- throw err;
- }
- options.onAuthorized?.(remotePeer, verified, targetService);
-
- // Under the type the policy was evaluated on.
- const spec = registry.get(serviceType, serviceName);
- if (spec === undefined || spec.type === "mcp") {
- reply(404, "Service not found");
- return;
- }
-
- // The biscuit and the agent are for policy, not for the backend; X-Peer-Id
- // is set, not added, so an inbound value cannot pose as the verified peer.
- const headers = new Headers();
- for (const [k, v] of Object.entries(req.headers)) {
- if (v === undefined || k === HEADER_SAM_BISCUIT || k === HEADER_SAM_AGENT || k === HEADER_SAM_NO_TRAILING_SLASH || k === HEADER_PEER_ID || k === "host" || k === "connection" || k === "transfer-encoding" || k === "content-length") {
- continue;
- }
- for (const value of Array.isArray(v) ? v : [v]) {
- headers.append(k, value);
- }
- }
- headers.set(HEADER_PEER_ID, remotePeer);
- if (upstreamPath === "" && rest.length === 0) {
- headers.set(HEADER_SAM_NO_TRAILING_SLASH, "true");
- }
-
- const method = req.method ?? "GET";
- const body: Uint8Array<ArrayBuffer> | undefined =
- method === "GET" || method === "HEAD" ? undefined : new Uint8Array(await readBody(req, MAX_INGRESS_BODY_BYTES));
- const path = "/" + upstreamPath + url.search;
- const init: RequestInit = { method, headers };
- if (body !== undefined) {
- init.body = body;
- }
-
- let response: Response;
- if (typeof spec.target === "string") {
- const base = spec.target.replace(/\/$/, "");
- response = await fetch(base + path, { ...init, redirect: "manual" });
- } else {
- response = await spec.target(new Request("http://" + serviceName + path, init), verified);
- }
-
- const outHeaders: Record<string, string | string[]> = {};
- response.headers.forEach((value, key) => {
- if (key === "content-length" || key === "transfer-encoding" || key === "connection") {
- return;
- }
- outHeaders[key] = value;
- });
- res.writeHead(response.status, outHeaders);
- if (response.body === null) {
- res.end();
- return;
- }
- await new Promise<void>((resolve, reject) => {
- Readable.fromWeb(response.body as import("node:stream/web").ReadableStream)
- .on("error", reject)
- .pipe(res)
- .on("finish", resolve)
- .on("error", reject);
- });
-}
-
-export interface HTTPRequestOptions {
- method?: string;
- headers?: Record<string, string>;
- body?: Uint8Array | string;
- /** The agent this request is made for. */
- agent?: string;
- signal?: AbortSignal;
-}
-
-export interface HTTPResponse {
- status: number;
- headers: Record<string, string>;
- body: Uint8Array;
- text(): string;
-}
-
-/**
- * Client side of /libp2p-http, as go-libp2p-http's RoundTripper: one stream
- * per request, plain HTTP/1.1 with Host set to the peer ID, the biscuit in
- * X-Sam-Biscuit and the path /<type>/<name>/<path>.
- */
-export async function httpRequestOverStream(
- conn: Connection,
- biscuit: Uint8Array,
- targetService: string,
- path: string,
- options: HTTPRequestOptions = {},
-): Promise<HTTPResponse> {
- const m = /^(inference|a2a|mcp):\/\/(.+)$/.exec(targetService);
- if (m === null) {
- throw new Error(`service target must look like inference://<name>, got ${JSON.stringify(targetService)}`);
- }
- const signal = options.signal ?? AbortSignal.timeout(60_000);
- const stream = await conn.newStream(HTTP_PROTOCOL, { signal, runOnLimitedConnection: true });
- const peerId = conn.remotePeer.toString();
- const socket = streamToNodeDuplex(stream, peerId);
- return new Promise<HTTPResponse>((resolve, reject) => {
- const headers: Record<string, string> = { ...(options.headers ?? {}), [HEADER_SAM_BISCUIT]: Buffer.from(biscuit).toString("base64"), host: peerId };
- if (options.agent) {
- headers[HEADER_SAM_AGENT] = options.agent;
- }
- const req = http.request({
- method: options.method ?? "GET",
- path: `/${m[1]}/${m[2]}${path.startsWith("/") ? path : "/" + path}`,
- headers,
- createConnection: () => socket,
- signal,
- });
- req.on("error", reject);
- req.on("response", (res) => {
- readBody(res, MAX_INGRESS_BODY_BYTES).then((buf) => {
- const flat: Record<string, string> = {};
- for (const [k, v] of Object.entries(res.headers)) {
- if (typeof v === "string") {
- flat[k] = v;
- } else if (Array.isArray(v)) {
- flat[k] = v.join(", ");
- }
- }
- resolve({ status: res.statusCode ?? 0, headers: flat, body: new Uint8Array(buf), text: () => new TextDecoder().decode(buf) });
- }, reject);
- });
- if (options.body !== undefined) {
- req.write(options.body);
- }
- req.end();
- }).finally(() => {
- socket.destroy();
- });
-}
diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.ts
index a24bcfb9..3286356c 100644
--- a/sdk/js/src/session.ts
+++ b/sdk/js/src/session.ts
@@ -17,26 +17,28 @@ import { timestampMs } from "@bufbuild/protobuf/wkt";
import { TopicValidatorResult } from "@libp2p/gossipsub";
import { peerIdFromString } from "@libp2p/peer-id";
import { isMultiaddr, multiaddr, type Multiaddr } from "@multiformats/multiaddr";
-import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, MCP_PROTOCOL, authenticateWithPeer, authStreamHandler } from "./auth.ts";
+import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, authenticateWithPeer, authStreamHandler } from "./auth.ts";
import { ROLE_ROUTER, requireRole, type VerifiedBiscuit } from "./biscuit.ts";
import { canonicalPeerId } from "./identity.ts";
-import { isServiceType, parseServiceTarget, serviceCID, type ServiceType } from "./discovery.ts";
+import { isServiceType, parseServiceTarget, serviceCID } from "./discovery.ts";
import { createMeshHost, listenThroughRelay, type MeshHost, type MeshHostOptions } from "./host.ts";
import { openMCPSession, type MCPSession, type MCPSessionOptions } from "./mcp.ts";
import type { AgentMesh, ControlPlaneSync } from "./mesh.ts";
import {
+ HTTP_HANDLER_OPTIONS,
HTTP_PROTOCOL,
- SERVE_HANDLER_OPTIONS,
- ServiceRegistry,
+ a2aEndpoint,
+ fetchOverStream,
httpIngressHandler,
httpRequestOverStream,
- mcpStreamHandler,
+ meshURL,
+ splitMeshURL,
+ type A2AEndpoint,
+ type A2AEndpointSpec,
type HTTPRequestOptions,
type HTTPResponse,
type ProviderOptions,
- type ServedService,
- type ServiceSpec,
-} from "./serve.ts";
+} from "./libp2p-http.ts";
import { BanSet, GOSSIP_EVENTS_TOPIC, MeshEvent_Type, verifyMeshEvent } from "./sync.ts";
export interface JoinOptions extends MeshHostOptions {
@@ -50,10 +52,8 @@ export interface JoinOptions extends MeshHostOptions {
refreshLeadMs?: number;
/** Retry a failed refresh after this long. */
refreshRetryMs?: number;
- /** How often the mesh policy is re-read from the control plane while serving. */
+ /** How often the mesh policy is re-read from the control plane while accepting callers. */
policySyncIntervalMs?: number;
- /** How often published services are re-announced in the DHT. */
- provideIntervalMs?: number;
/**
* How often keys, bans and router addresses are pulled from the control
* plane (sam-node's --control-plane-sync-interval). Gossip events bring a
@@ -104,8 +104,6 @@ const DEFAULT_REFRESH_RETRY_MS = 30 * 1000;
const MIN_REFRESH_DELAY_MS = 2_000;
/** sam-node's --control-plane-sync-interval default. */
const DEFAULT_POLICY_SYNC_MS = 15 * 60 * 1000;
-/** How often provider records are refreshed; go-libp2p-kad-dht expires them after 48h. */
-const DEFAULT_PROVIDE_INTERVAL_MS = 10 * 60 * 1000;
/** sam-node's --control-plane-sync-interval default, and its 2s first pull. */
const DEFAULT_CONTROL_PLANE_SYNC_MS = 15 * 60 * 1000;
const FIRST_CONTROL_PLANE_SYNC_MS = 2_000;
@@ -124,21 +122,18 @@ export class MeshSession {
readonly authenticatedPeers: Map<string, Date>;
/** Peers the control plane has banned; connections to and from them are refused. */
readonly banned: BanSet;
- /** The services this member publishes. */
- readonly services = new ServiceRegistry();
+ /** This member's agent, once acceptA2A was called. */
+ endpoint: A2AEndpoint | undefined;
#refreshTimer: ReturnType<typeof setTimeout> | undefined;
#policyTimer: ReturnType<typeof setInterval> | undefined;
- #provideTimer: ReturnType<typeof setInterval> | undefined;
#syncTimer: ReturnType<typeof setTimeout> | undefined;
#syncing: Promise<ControlPlaneSync> | undefined;
readonly #refreshLeadMs: number;
readonly #refreshRetryMs: number;
readonly #policySyncMs: number;
- readonly #provideIntervalMs: number;
readonly #syncIntervalMs: number;
readonly #syncJitterMs: number;
#policyRules: string[] | undefined;
- #serving = false;
#closed = false;
constructor(mesh: AgentMesh, node: MeshHost, routers: AdmittedRouter[], authenticatedPeers: Map<string, Date>, banned: BanSet, options: JoinOptions) {
@@ -150,7 +145,6 @@ export class MeshSession {
this.#refreshLeadMs = options.refreshLeadMs ?? DEFAULT_REFRESH_LEAD_MS;
this.#refreshRetryMs = options.refreshRetryMs ?? DEFAULT_REFRESH_RETRY_MS;
this.#policySyncMs = options.policySyncIntervalMs ?? DEFAULT_POLICY_SYNC_MS;
- this.#provideIntervalMs = options.provideIntervalMs ?? DEFAULT_PROVIDE_INTERVAL_MS;
this.#syncIntervalMs = options.controlPlaneSyncIntervalMs ?? DEFAULT_CONTROL_PLANE_SYNC_MS;
this.#syncJitterMs = options.controlPlaneSyncJitterMs ?? DEFAULT_CONTROL_PLANE_SYNC_JITTER_MS;
this.#scheduleRefresh();
@@ -164,6 +158,20 @@ export class MeshSession {
return this.node.peerId.toString();
}
+ /**
+ * The URL a fetch bound to this session (fetch()) takes for a service on a
+ * peer: http://mesh/sam/<peer-id>/<type>/<name>/<path>, the shape of
+ * sam-node's egress proxy and of an agent card it rewrote.
+ */
+ static meshURL(peerId: string, targetService: string, path = ""): string {
+ return meshURL(peerId, targetService, path);
+ }
+
+ /** The mesh URL of this member's own agent, once acceptA2A was called. */
+ get agentURL(): string | undefined {
+ return this.endpoint === undefined ? undefined : meshURL(this.peerId, this.endpoint.service);
+ }
+
/** Addresses peers can dial this member on, including relayed ones. */
get addresses(): Multiaddr[] {
return this.node.getMultiaddrs();
@@ -301,9 +309,10 @@ export class MeshSession {
/**
* Pulls keys, bans and router addresses from the control plane now, and
- * the mesh policy when serving, then applies them: a newly banned peer is
- * hung up on and dropped from the admitted set. Concurrent calls share
- * one pull. Errors of individual parts are in the result, not thrown.
+ * the mesh policy when accepting callers, then applies them: a newly
+ * banned peer is hung up on and dropped from the admitted set. Concurrent
+ * calls share one pull. Errors of individual parts are in the result, not
+ * thrown.
*/
sync(): Promise<ControlPlaneSync> {
this.#syncing ??= this.#syncOnce().finally(() => {
@@ -318,7 +327,7 @@ export class MeshSession {
const { banned } = this.banned.reconcile(canonicalPeerIds(result.bannedPeerIds), result.fetchedAt);
await Promise.all(banned.map((peerId) => this.#evict(peerId)));
}
- if (this.#serving) {
+ if (this.endpoint !== undefined) {
try {
await this.syncPolicy();
} catch (err) {
@@ -407,7 +416,7 @@ export class MeshSession {
/**
* The mesh policy rules this member evaluates for callers, as the control
* plane rendered them (PolicyConfigGetResponse.datalog_rules). Empty until
- * the first serve() or syncPolicy().
+ * acceptA2A() or syncPolicy().
*/
get policyRules(): string[] {
return this.#policyRules ?? [];
@@ -428,65 +437,57 @@ export class MeshSession {
}
/**
- * Publishes a service on the mesh: registers it, announces it in the DHT
- * and reports it to the control plane's catalog. The first call fetches
- * the mesh policy and starts answering /sam/mcp/1.0.0 and /libp2p-http;
- * a policy that cannot be read fails the call, since a provider without
- * it could only authorize what callers carry in their own tokens.
+ * A `fetch` bound to the mesh, for clients built on fetch such as the A2A
+ * SDK's (`fetchImpl`): a request to http://mesh/sam/<peer-id>/<type>/<name>/<path>
+ * is carried to that peer over /libp2p-http with this member's credential.
+ * Response bodies stream, so message/stream works. See MeshSession.meshURL.
*/
- async serve(spec: ServiceSpec): Promise<void> {
- if (!this.#serving) {
- await this.syncPolicy();
- const providerOptions: ProviderOptions = {
- trustedKeys: () => this.mesh.credential.controlPlaneKeys,
- ownBiscuit: () => this.mesh.credential.biscuit,
- policyRules: () => this.policyRules,
- isBanned: (peerId) => this.banned.has(peerId),
- onAuthorized: (peerId, verified) => this.authenticatedPeers.set(peerId, verified.expiration),
- };
- await this.node.handle(MCP_PROTOCOL, mcpStreamHandler(this.services, providerOptions, MCP_PROTOCOL), SERVE_HANDLER_OPTIONS);
- await this.node.handle(HTTP_PROTOCOL, httpIngressHandler(this.services, providerOptions), SERVE_HANDLER_OPTIONS);
- this.#policyTimer = setInterval(() => void this.syncPolicy().catch(() => {}), this.#policySyncMs);
- this.#policyTimer.unref?.();
- this.#provideTimer = setInterval(() => void this.provideAll().catch(() => {}), this.#provideIntervalMs);
- this.#provideTimer.unref?.();
- this.#serving = true;
- }
- this.services.add(spec);
- await this.#provide(spec.type, spec.name);
- await this.reportCatalog().catch(() => {});
- }
-
- /** Announces every registered service in the DHT again. */
- async provideAll(): Promise<void> {
- for (const s of this.services.list()) {
- await this.#provide(s.type, s.name);
- }
- }
-
- async #provide(type: ServiceType, name: string): Promise<void> {
- // Once for the type and once for the name, as sam-node announces.
- const signal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS);
- for (const cid of [await serviceCID(type), await serviceCID(type, name)]) {
- try {
- await this.node.contentRouting.provide(cid, { signal });
- } catch (err) {
- // A provide that timed out on some peers still landed on the ones that answered.
- if (!(err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"))) {
- throw err;
- }
+ fetch(options: { agent?: string } = {}): typeof fetch {
+ return async (input, init) => {
+ const request = new Request(input, init);
+ const { peerId } = splitMeshURL(new URL(request.url));
+ const conn = await this.connect(peerId, request.signal);
+ const streamOptions: { agent?: string; signal?: AbortSignal } = {};
+ if (options.agent !== undefined) {
+ streamOptions.agent = options.agent;
}
- }
- }
-
- /** Reports the published services to the control plane's catalog (display only). */
- async reportCatalog(): Promise<void> {
- await this.mesh.controlPlane.reportCatalog(this.mesh.credential.biscuit, this.services.list());
+ if (init?.signal !== undefined && init.signal !== null) {
+ streamOptions.signal = init.signal;
+ }
+ return fetchOverStream(conn, this.mesh.credential.biscuit, request, streamOptions);
+ };
}
- /** The services this member publishes. */
- get servedServices(): ServedService[] {
- return this.services.list();
+ /**
+ * Makes this member's agent reachable: other members call it as
+ * `a2a://<name>` by peer ID, through a router, and the SDK answers
+ * /libp2p-http with the spec's url (an A2A server beside this process),
+ * handler or listener (in this process; an Express app with the A2A SDK's
+ * handlers is a listener). Nothing is announced: no DHT record, no
+ * catalog entry. A tool, a model or a service others should find by name
+ * is published by a sam-node. Fetches the mesh policy first and keeps it
+ * current; a policy that cannot be read fails the call, since an agent
+ * without it could only authorize what callers carry in their own tokens.
+ * Returns the service target callers use. One agent per session.
+ */
+ async acceptA2A(spec: A2AEndpointSpec): Promise<string> {
+ if (this.endpoint !== undefined) {
+ throw new Error(`this session already accepts ${this.endpoint.service}`);
+ }
+ const endpoint = a2aEndpoint(spec);
+ await this.syncPolicy();
+ const providerOptions: ProviderOptions = {
+ trustedKeys: () => this.mesh.credential.controlPlaneKeys,
+ ownBiscuit: () => this.mesh.credential.biscuit,
+ policyRules: () => this.policyRules,
+ isBanned: (peerId) => this.banned.has(peerId),
+ onAuthorized: (peerId, verified) => this.authenticatedPeers.set(peerId, verified.expiration),
+ };
+ await this.node.handle(HTTP_PROTOCOL, httpIngressHandler(endpoint, providerOptions), HTTP_HANDLER_OPTIONS);
+ this.#policyTimer = setInterval(() => void this.syncPolicy().catch(() => {}), this.#policySyncMs);
+ this.#policyTimer.unref?.();
+ this.endpoint = endpoint;
+ return endpoint.service;
}
#scheduleRefresh(): void {
@@ -516,7 +517,6 @@ export class MeshSession {
clearTimeout(this.#refreshTimer);
clearTimeout(this.#syncTimer);
clearInterval(this.#policyTimer);
- clearInterval(this.#provideTimer);
await this.node.stop();
}
}