Skip to content

Agent Mesh

sdk: serve MCP, inference and A2A, milestone 4

Antonio Ojeab00feed1c931
diff --git a/sdk/README.md b/sdk/README.md
index 71f4287a..f6202914 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -21,7 +21,7 @@ node and to the control plane, a `sam-node`.
## What exists today
-Milestones 1 to 3 are implemented and tested in both languages:
+Milestones 1 to 4 are implemented and tested in both languages:
| Capability | JS | Python |
| --- | --- | --- |
@@ -38,10 +38,17 @@ Milestones 1 to 3 are implemented and tested in both languages:
| Service discovery in the mesh DHT (`/sam/kad/1.0.0`) | yes | yes |
| `/sam/mcp/1.0.0` client: list and call a provider's tools, or its catalog | yes | yes |
| Caller-side label requirements on the provider's credential | yes | yes |
-
-A member built this way is on the mesh and uses it: it finds a service in
-the DHT and calls its tools through the router, verifying the provider on
-every call. It cannot yet serve tools of its own.
+| Provider authorizer: the baseline Datalog and the mesh policy (`GET /policies`), evaluated as `sam-node` does | yes | yes |
+| `/sam/mcp/1.0.0` server: publish MCP services with an in-process MCP server; the member's own catalog | yes | yes |
+| `/libp2p-http` server: publish inference and A2A services, forwarded to a local URL or an in-process handler | yes | yes |
+| `/libp2p-http` client: call inference and A2A services on the mesh | yes | yes |
+| DHT provide with reprovide, `POST /nodes/catalog` self-report | yes | yes |
+
+A member built this way is on the mesh and uses it in both directions: it
+finds a service in the DHT and calls it through the router, verifying the
+provider on every call, and it publishes services of its own that a
+`sam-node` or another SDK member discovers and calls, authorizing every
+caller with the same Datalog the Go node evaluates.
Facts about the libp2p implementations that the SDKs work around, each
pinned by a test:
@@ -75,6 +82,15 @@ pinned by a test:
- go-libp2p-kad-dht keys provider records by the multihash, not the CID.
`sdk/testdata/service_keys.json` pins the keys both SDKs derive against
`internal/node/service.go`.
+- go-libp2p-kad-dht stores an ADD_PROVIDER record only when the sender is
+ the provider it names and lists at least one address, and it answers
+ nothing. The Python SDK sends the record itself to the routers and to the
+ closer peers they name (`agent_mesh/discovery.py`); js-libp2p's
+ `contentRouting.provide` does the same in client mode.
+- go-libp2p-http is plain HTTP/1.1 on a stream, one request per stream,
+ with `Host` set to the peer ID. The JS SDK bridges the stream to a Node
+ duplex and runs Node's HTTP server and client on it; the Python SDK
+ drives `h11` over the stream.
## Wire contract
@@ -282,30 +298,52 @@ holds against the control plane's records.
service the node does not have. The runners took `discover`, `tools` and
`call` commands for it.
-### Milestone 4 — serve tools
-
-- Datalog as the contract (done, Go side): the baseline moved into a
- generated artifact both SDKs embed, the control plane renders the mesh
- policy as `datalog_rules`, and `sam-node` consumes that text like any
- other member. See the authorization section above.
-- Provider authorizer in each SDK, built from the artifact and
- `datalog_rules`, evaluated on every inbound `AuthFrame`.
-- `/sam/mcp/1.0.0` server: read the `AuthFrame`, run the authorizer, answer,
- then hand the stream to an in-process MCP server.
-- `/libp2p-http` ingress for inference and A2A backends, forwarding
- authorized requests to a local URL, and the client side to call them.
-- DHT provide for each registered service, reprovided on the node's
- interval; `POST /nodes/catalog` self-report.
-- Test: a `sam-node` calls a tool and an inference endpoint served by each
- SDK member, the SDK members call each other, and a caller whose role
- grants nothing is refused at the `AuthResponse`.
+### Milestone 4 — serve tools (done)
+
+- Datalog as the contract, Go side: the baseline moved into a generated
+ artifact both SDKs embed, the control plane renders the mesh policy as
+ `datalog_rules`, and `sam-node` consumes that text like any other member.
+ See the authorization section above.
+- Provider authorizer in each SDK (`authorizer.ts`, `authorizer.py`), built
+ from the artifact and `datalog_rules`, evaluated on every inbound
+ `AuthFrame` and every `/libp2p-http` request in the order
+ `internal/node/middleware.go` uses.
+- `/sam/mcp/1.0.0` server: read the `AuthFrame`, authorize, answer with the
+ member's credential, then hand the stream to the service's MCP server
+ (`@modelcontextprotocol/sdk` `McpServer`; `mcp.server.mcpserver.MCPServer`
+ run over pumped streams). A denied caller gets `AuthResponse{success:
+ false}` with the reason; a granted service the member does not publish
+ closes the stream after the answer, as `sam-node` does. The empty target is
+ the member's catalog (`list_local_services`).
+- `/libp2p-http` server for inference and A2A: the path is
+ `/<type>/<name>/<upstream>`, the biscuit is `X-Sam-Biscuit`; after
+ authorization the request goes to a local URL or an in-process handler
+ with the biscuit and agent headers stripped and `X-Peer-Id` set to the
+ verified caller. `session.request(addr, "inference://<name>", path)` is
+ the client side.
+- `session.serve(spec)` registers the service, fetches the mesh policy on
+ the first call and re-reads it on `sam-node`'s sync interval, announces
+ the service in the DHT (type and name, reprovided periodically) and
+ reports it to `POST /nodes/catalog`.
+- Tests. Unit: each SDK's handlers behind an in-process host, called with
+ its own clients: an MCP tool, the catalog, a proxied backend that sees
+ `X-Peer-Id` and never the biscuit, an in-process handler, and refusals for
+ a role that grants nothing, an ungranted service, a missing service, a
+ missing biscuit and a dotted path; plus the authorizer alone against the
+ decisions `internal/node/middleware_test.go` pins. Integration: in the
+ mesh of `sdk_mesh_test.go` each SDK member publishes `mcp://echo-<sdk>`
+ and `inference://llm-<sdk>`; the `sam-node` calls the tool with
+ `call_remote_tool` and the inference endpoint through its egress proxy,
+ the other SDK member discovers both in the DHT and calls them through the
+ router, and a Go peer the control plane vouches for but whose role the
+ policy grants nothing is refused at the `AuthResponse` and with 403 on
+ the HTTP path, then served once it presents a node-role token. About 9
+ seconds for the whole mesh.
### Milestone 5 — parity and release
-- Control plane sync loop (`/keys`, bans, router addresses, policy) and
- gossip event handling for bans and key rotation.
-- Inference and A2A egress over libp2p HTTP (`libp2phttp`), following the
- sidecar's `/sam/<peer>/<type>/<name>/` proxy.
+- Control plane sync loop (`/keys`, bans, router addresses) and gossip
+ event handling for bans, key rotation and policy updates.
- Publishing: `@agent-mesh/sdk` to npm and `agent-mesh` to PyPI from the
release workflow, versioned with the repository.
- Docs: a guide under `site/content/docs/guides/` and the connector
@@ -344,8 +382,8 @@ both so nothing skips there. The SDK members in the mesh test are the
runners `sdk/js/src/conformance-join.ts` and
`sdk/python/src/agent_mesh/conformance_join.py`: each joins, prints what it
holds, then takes JSON commands on stdin (`auth`, `discover`, `tools`,
-`call`, `peers`, `quit`) so the Go test can drive both languages through the
-same script.
+`call`, `serve`, `http`, `peers`, `quit`) so the Go test can drive both
+languages through the same script.
Interoperability facts that the tests pin: `sdk/testdata/identity_vectors.json`
holds key encodings, peer IDs and challenge signatures produced with
diff --git a/sdk/js/README.md b/sdk/js/README.md
index dfba1b95..43c55104 100644
--- a/sdk/js/README.md
+++ b/sdk/js/README.md
@@ -24,6 +24,8 @@ and the js-libp2p packages (`libp2p`, `@libp2p/tcp`, `@libp2p/tls`,
```ts
import { AgentMesh } from "@agent-mesh/sdk";
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { z } from "zod";
const mesh = await AgentMesh.enroll({
controlPlaneUrl: "https://hub.sam-mesh.dev",
@@ -47,6 +49,24 @@ const addr = `${session.routers[0].addr}/p2p-circuit/p2p/${provider.peerId}`;
console.log(await session.listTools(addr, "mcp://calc"));
const result = await session.callTool(addr, "mcp://calc", "add", { a: 1, b: 2 }, { requiredLabels: { region: "eu" } });
console.log(result.text);
+
+// Publish services of your own. Callers are authorized with the mesh policy
+// before anything reaches your code or your backend.
+await session.serve({
+ type: "mcp",
+ name: "echo",
+ createServer: () => {
+ const server = new McpServer({ name: "echo", version: "1.0.0" });
+ server.tool("echo", { text: z.string() }, async ({ text }) => ({ content: [{ type: "text", text }] }));
+ return server;
+ },
+});
+await session.serve({ type: "inference", name: "llm", target: "http://127.0.0.1:8000" });
+await session.serve({ type: "a2a", name: "reviewer", target: (request, caller) => new Response(`hello ${caller.peerId}`) });
+
+// Call an inference or A2A service on another member.
+const models = await session.request(addr, "inference://llm", "/v1/models");
+console.log(models.status, models.text());
await session.close();
// Later, in a new process:
@@ -76,7 +96,13 @@ A plaintext `http://` control plane is accepted only on loopback. Pass
reservation and the refresh loop.
- `src/discovery.ts`, `src/mcp.ts`: service keys for the mesh DHT, and MCP
over `/sam/mcp/1.0.0` (a `Transport` for the official MCP client).
-- `src/gen/`: generated from `api/sam.proto` by `hack/gen-sdk-proto.sh`.
+- `src/authorizer.ts`: the provider authorizer, as
+ `internal/node.(*SamNode).Authorize`, over the generated baseline Datalog
+ and the mesh policy rules from `GET /policies`.
+- `src/serve.ts`: the `/sam/mcp/1.0.0` server, the `/libp2p-http` server
+ and client, and the service registry behind `session.serve()`.
+- `src/gen/`: generated from `api/sam.proto` and `api/datalog.go` by
+ `hack/gen-sdk-proto.sh`.
## Test
diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.json
index 24f5bb97..1f18ed00 100644
--- a/sdk/js/package-lock.json
+++ b/sdk/js/package-lock.json
@@ -24,13 +24,13 @@
"@modelcontextprotocol/sdk": "^1.30.1",
"@multiformats/multiaddr": "^13.0.3",
"libp2p": "^3.3.11",
- "multiformats": "^14.0.5"
+ "multiformats": "^14.0.5",
+ "zod": "^4.6.5"
},
"devDependencies": {
"@bufbuild/protoc-gen-es": "^2.15.0",
"@types/node": "^22.19.0",
- "typescript": "^5.9.3",
- "zod": "^4.6.5"
+ "typescript": "^5.9.3"
},
"engines": {
"node": ">=22.18"
diff --git a/sdk/js/package.json b/sdk/js/package.json
index 4e768aa5..ccf8834d 100644
--- a/sdk/js/package.json
+++ b/sdk/js/package.json
@@ -44,12 +44,12 @@
"@modelcontextprotocol/sdk": "^1.30.1",
"@multiformats/multiaddr": "^13.0.3",
"libp2p": "^3.3.11",
- "multiformats": "^14.0.5"
+ "multiformats": "^14.0.5",
+ "zod": "^4.6.5"
},
"devDependencies": {
"@bufbuild/protoc-gen-es": "^2.15.0",
"@types/node": "^22.19.0",
- "typescript": "^5.9.3",
- "zod": "^4.6.5"
+ "typescript": "^5.9.3"
}
}
diff --git a/sdk/js/src/authorizer.test.ts b/sdk/js/src/authorizer.test.ts
new file mode 100644
index 00000000..039b7891
--- /dev/null
+++ b/sdk/js/src/authorizer.test.ts
@@ -0,0 +1,165 @@
+// 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 authorizer against tokens minted the way the control plane
+// mints them and policy rules rendered the way it renders them. The
+// decisions here are the ones internal/node/middleware_test.go pins.
+
+import assert from "node:assert/strict";
+import { before, test } from "node:test";
+import { AuthorizationError, authorizeCaller, type AuthorizeRequest } from "./authorizer.ts";
+import { loadBiscuit } from "./biscuit.ts";
+import { BASELINE_DATALOG } from "./gen/datalog.ts";
+
+type Wasm = Awaited<ReturnType<typeof loadBiscuit>>;
+
+let wasm: Wasm;
+let cpKeyPair: InstanceType<Wasm["KeyPair"]>;
+let otherKeyPair: InstanceType<Wasm["KeyPair"]>;
+let cpKey: Uint8Array;
+
+const PROVIDER = "12D3KooWProvider00000000000000000000000000000000000";
+const CALLER = "12D3KooWCaller0000000000000000000000000000000000000";
+
+function mint(facts: string[], keyPair = cpKeyPair, expiration = "2035-01-01T00:00:00Z"): Uint8Array {
+ const b = wasm.Biscuit.builder();
+ b.addFact(wasm.Fact.fromString(`expiration(${expiration})`));
+ for (const f of facts) {
+ b.addFact(wasm.Fact.fromString(f));
+ }
+ return b.build(keyPair.getPrivateKey()).toBytes();
+}
+
+/** A token as the control plane mints it for a node bound to peerId. */
+function nodeToken(peerId: string, extra: string[] = [], keyPair = cpKeyPair): Uint8Array {
+ return mint([`node(${JSON.stringify(peerId)})`, `client_peer_id(${JSON.stringify(peerId)})`, `role("sam:role:node")`, ...extra], keyPair);
+}
+
+before(async () => {
+ wasm = await loadBiscuit();
+ cpKeyPair = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
+ otherKeyPair = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
+ cpKey = new Uint8Array(Buffer.from(cpKeyPair.getPublicKey().toString().replace(/^ed25519\//, ""), "hex"));
+});
+
+function options(policyRules: string[], ownBiscuit?: Uint8Array) {
+ return {
+ trustedKeys: () => [cpKey],
+ ownBiscuit: () => ownBiscuit ?? nodeToken(PROVIDER, [`granted_service_all_types(true)`, `target_unrestricted(true)`]),
+ policyRules: () => policyRules,
+ };
+}
+
+function request(biscuit: Uint8Array, targetService = "mcp://calc", agent?: string): AuthorizeRequest {
+ const req: AuthorizeRequest = { biscuit, peerId: CALLER, targetService, protocol: "/sam/mcp/1.0.0" };
+ if (agent !== undefined) {
+ req.agent = agent;
+ }
+ return req;
+}
+
+// The role grants the service through the mesh policy rules, exactly as the
+// control plane renders them; the token itself carries only the role.
+const NODE_ROLE_GRANTS = [
+ `granted_service_set("mcp", ["calc"]) <- role("sam:role:node")`,
+ `target_unrestricted(true) <- role("sam:role:node")`,
+];
+
+test("a role granted the service by the mesh policy is allowed", async () => {
+ const verified = await authorizeCaller(request(nodeToken(CALLER)), options(NODE_ROLE_GRANTS));
+ assert.equal(verified.peerId, CALLER);
+ assert.deepEqual(verified.roles, ["sam:role:node"]);
+});
+
+test("grants minted into the token are enough on their own", async () => {
+ const token = nodeToken(CALLER, [`granted_service_exact("mcp", "calc")`, `target_unrestricted(true)`]);
+ await authorizeCaller(request(token), options([]));
+});
+
+test("the empty target is the protocol in the system namespace", async () => {
+ const token = nodeToken(CALLER, [`granted_service_all("sam:system")`, `target_unrestricted(true)`]);
+ await authorizeCaller(request(token, ""), options([]));
+ await assert.rejects(authorizeCaller(request(token, "mcp://calc"), options([])), AuthorizationError);
+});
+
+test("a service the role was not granted is denied", async () => {
+ await assert.rejects(authorizeCaller(request(nodeToken(CALLER), "mcp://other"), options(NODE_ROLE_GRANTS)), AuthorizationError);
+});
+
+test("a role with no grants at all is denied", async () => {
+ const guest = mint([`node(${JSON.stringify(CALLER)})`, `client_peer_id(${JSON.stringify(CALLER)})`, `role("sam:role:guest")`]);
+ await assert.rejects(authorizeCaller(request(guest), options(NODE_ROLE_GRANTS)), AuthorizationError);
+});
+
+test("a token presented by a peer it is not bound to is denied", async () => {
+ // Minted for someone else, replayed by CALLER over CALLER's connection.
+ const stolen = nodeToken("12D3KooWVictim000000000000000000000000000000000000", [`granted_service_all_types(true)`, `target_unrestricted(true)`]);
+ await assert.rejects(authorizeCaller(request(stolen), options([])), AuthorizationError);
+});
+
+test("client_peer_id must match the connection peer", async () => {
+ // node() binds to CALLER but client_peer_id names another peer: the replay check fails.
+ const token = mint([
+ `node(${JSON.stringify(CALLER)})`,
+ `client_peer_id("12D3KooWSomeoneElse000000000000000000000000000000")`,
+ `granted_service_all_types(true)`,
+ `target_unrestricted(true)`,
+ ]);
+ await assert.rejects(authorizeCaller(request(token), options([])), AuthorizationError);
+});
+
+test("an expired token is denied", async () => {
+ const token = mint([`node(${JSON.stringify(CALLER)})`, `client_peer_id(${JSON.stringify(CALLER)})`, `granted_service_all_types(true)`, `target_unrestricted(true)`], cpKeyPair, "2020-01-01T00:00:00Z");
+ await assert.rejects(authorizeCaller(request(token), options([])), AuthorizationError);
+});
+
+test("a token under an untrusted key is denied", async () => {
+ const token = nodeToken(CALLER, [`granted_service_all_types(true)`, `target_unrestricted(true)`], otherKeyPair);
+ await assert.rejects(authorizeCaller(request(token), options([])), AuthorizationError);
+});
+
+test("target grants are matched against the provider's own identity", async () => {
+ const provider = nodeToken(PROVIDER, [`group("backend")`]);
+ const rules = [`granted_service_all_types(true) <- role("sam:role:node")`, `target_restricted(true) <- role("sam:role:node")`];
+ // Granted group:backend, which the provider carries: allowed.
+ await authorizeCaller(request(nodeToken(CALLER, [`granted_target_set("group", ["backend"])`])), options(rules, provider));
+ // Granted group:frontend only: the provider is not an intended target.
+ await assert.rejects(
+ authorizeCaller(request(nodeToken(CALLER, [`granted_target_set("group", ["frontend"])`])), options(rules, provider)),
+ AuthorizationError,
+ );
+ // No target grant and no target_unrestricted: denied.
+ await assert.rejects(authorizeCaller(request(nodeToken(CALLER)), options(rules, provider)), AuthorizationError);
+});
+
+test("an agent claim is accepted only inside a granted namespace", async () => {
+ const rules = [...NODE_ROLE_GRANTS, `granted_agent_suffix(".acme.example") <- role("sam:role:node")`];
+ await authorizeCaller(request(nodeToken(CALLER), "mcp://calc", "reviewer.acme.example"), options(rules));
+ await assert.rejects(authorizeCaller(request(nodeToken(CALLER), "mcp://calc", "reviewer.evil.example"), options(rules)), AuthorizationError);
+ // No agent grant at all: any claim is refused, no claim is fine.
+ await assert.rejects(authorizeCaller(request(nodeToken(CALLER), "mcp://calc", "reviewer.acme.example"), options(NODE_ROLE_GRANTS)), AuthorizationError);
+ await authorizeCaller(request(nodeToken(CALLER)), options(NODE_ROLE_GRANTS));
+});
+
+test("every baseline item parses in biscuit-wasm", () => {
+ for (const c of [BASELINE_DATALOG.time_check, BASELINE_DATALOG.replay_check, BASELINE_DATALOG.target_check, BASELINE_DATALOG.agent_check]) {
+ wasm.Check.fromString(c);
+ }
+ for (const r of [...BASELINE_DATALOG.rules, ...BASELINE_DATALOG.agent_rules, ...BASELINE_DATALOG.target_fact_rules]) {
+ wasm.Rule.fromString(r);
+ }
+ for (const p of [...BASELINE_DATALOG.policies, BASELINE_DATALOG.allow_if_true]) {
+ wasm.Policy.fromString(p);
+ }
+});
diff --git a/sdk/js/src/authorizer.ts b/sdk/js/src/authorizer.ts
new file mode 100644
index 00000000..d5bf4a36
--- /dev/null
+++ b/sdk/js/src/authorizer.ts
@@ -0,0 +1,208 @@
+// 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 authorizer, mirroring internal/node.(*SamNode).Authorize.
+// Every piece of Datalog it evaluates is text: the baseline generated from
+// api/datalog.go (gen/datalog.ts) and the mesh policy rules the control
+// plane renders (GET /policies). Nothing here derives rules from roles.
+
+import { AUTHORIZER_LIMITS, BiscuitVerificationError, loadBiscuit, verifyPeerBiscuit, type VerifiedBiscuit } from "./biscuit.ts";
+import { parseServiceTarget } from "./discovery.ts";
+import { BASELINE_DATALOG } from "./gen/datalog.ts";
+
+/** What a caller asks for, as sam-node's RequestContext. */
+export interface AuthorizeRequest {
+ /** The caller's biscuit, as it arrived in the AuthFrame or X-Sam-Biscuit. */
+ biscuit: Uint8Array;
+ /** The peer at the other end of the authenticated connection. */
+ peerId: string;
+ /** "mcp://<name>", or "" for the protocol itself (the provider's own catalog). */
+ targetService: string;
+ /** The stream protocol; names the service when targetService is "". */
+ protocol: string;
+ /** The agent the caller says it acts for; its own claim, checked against its grants. */
+ agent?: string;
+}
+
+export interface ProviderAuthorizerOptions {
+ /** Control plane keys, read per request so a rotation takes effect. */
+ trustedKeys(): Uint8Array[];
+ /** This provider's own biscuit; its identity facts are what target grants match. */
+ ownBiscuit(): Uint8Array;
+ /** The mesh policy as PolicyConfigGetResponse.datalog_rules. */
+ policyRules(): string[];
+ now?(): Date;
+}
+
+export class AuthorizationError extends Error {
+ constructor(peerId: string, reason: string) {
+ super(`caller ${peerId} is not authorized: ${reason}`);
+ this.name = "AuthorizationError";
+ }
+}
+
+function describe(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+function timeFact(now: Date): string {
+ return `${BASELINE_DATALOG.fact_time}(${now.toISOString().replace(/\.\d{3}Z$/, "Z")})`;
+}
+
+/**
+ * Authorizes one request from a caller. Returns the caller's verified
+ * credential when every check holds and a policy allows; throws
+ * AuthorizationError otherwise. Every trusted key is tried, as
+ * VerifyBiscuitToken does.
+ */
+export async function authorizeCaller(req: AuthorizeRequest, options: ProviderAuthorizerOptions): Promise<VerifiedBiscuit> {
+ const wasm = await loadBiscuit();
+ const now = options.now?.() ?? new Date();
+ const keys = options.trustedKeys();
+ if (keys.length === 0) {
+ throw new AuthorizationError(req.peerId, "no trusted control plane key");
+ }
+
+ // Signature under a trusted key, authority block only, expiry and binding
+ // to the connection peer: RequireAuthorityBinding and EnforceExpiration.
+ let caller: VerifiedBiscuit;
+ try {
+ caller = await verifyPeerBiscuit(req.biscuit, req.peerId, keys, now);
+ } catch (err) {
+ throw new AuthorizationError(req.peerId, describe(err));
+ }
+ const token = wasm.Biscuit.fromBytes(req.biscuit, wasm.PublicKey.fromBytes(caller.verifyingKey, wasm.SignatureAlgorithm.Ed25519));
+
+ const b = new wasm.AuthorizerBuilder();
+ const fact = (source: string, params: Record<string, unknown> = {}) => {
+ const f = wasm.Fact.fromString(source);
+ for (const [k, v] of Object.entries(params)) {
+ f.set(k, v);
+ }
+ b.addFact(f);
+ };
+
+ // The action: service(type, name). An empty target is the protocol itself
+ // in the system namespace, as sam-node scopes its own catalog.
+ let svcType: string;
+ let svcName: string;
+ if (req.targetService === "") {
+ svcType = BASELINE_DATALOG.system_namespace;
+ svcName = req.protocol;
+ } else {
+ let parsed: { type: string; name: string };
+ try {
+ parsed = parseServiceTarget(req.targetService);
+ } catch (err) {
+ throw new AuthorizationError(req.peerId, describe(err));
+ }
+ svcType = parsed.type;
+ svcName = parsed.name;
+ }
+ fact(`${BASELINE_DATALOG.fact_service}({t}, {n})`, { t: svcType, n: svcName });
+ fact(`${BASELINE_DATALOG.fact_connection_peer_id}({p})`, { p: req.peerId });
+ fact(timeFact(now));
+
+ // The caller's word about which agent it acts for, limited to the agent
+ // namespaces its own token grants.
+ if (req.agent) {
+ fact(`${BASELINE_DATALOG.fact_agent}({a})`, { a: req.agent });
+ for (const r of BASELINE_DATALOG.agent_rules) {
+ b.addRule(wasm.Rule.fromString(r));
+ }
+ b.addCheck(wasm.Check.fromString(BASELINE_DATALOG.agent_check));
+ }
+
+ b.addCheck(wasm.Check.fromString(BASELINE_DATALOG.replay_check));
+ b.addCheck(wasm.Check.fromString(BASELINE_DATALOG.time_check));
+
+ // This provider's identity as target_fact facts, so the caller's target
+ // grants have something to match (injectIdentityFacts).
+ for (const f of await identityTargetFacts(options.ownBiscuit(), keys, now)) {
+ b.addFact(f);
+ }
+
+ b.addCheck(wasm.Check.fromString(BASELINE_DATALOG.target_check));
+ for (const p of BASELINE_DATALOG.policies) {
+ b.addPolicy(wasm.Policy.fromString(p));
+ }
+ for (const r of BASELINE_DATALOG.rules) {
+ b.addRule(wasm.Rule.fromString(r));
+ }
+ for (const r of options.policyRules()) {
+ b.addRule(wasm.Rule.fromString(r));
+ }
+
+ const authorizer = b.buildAuthenticated(token);
+ try {
+ authorizer.authorizeWithLimits(AUTHORIZER_LIMITS);
+ } catch (err) {
+ throw new AuthorizationError(req.peerId, describe(err));
+ }
+ return caller;
+}
+
+type WasmFact = ReturnType<Awaited<ReturnType<typeof loadBiscuit>>["Fact"]["fromString"]>;
+
+/**
+ * Evaluates this provider's own biscuit and returns its identity as
+ * target_fact facts, one per target_fact rule of the baseline.
+ */
+async function identityTargetFacts(ownBiscuit: Uint8Array, keys: Uint8Array[], now: Date): Promise<WasmFact[]> {
+ const wasm = await loadBiscuit();
+ if (ownBiscuit.length === 0) {
+ return [];
+ }
+ let own: VerifiedBiscuit;
+ try {
+ own = await verifyPeerBiscuit(ownBiscuit, await boundPeer(ownBiscuit, keys), keys, now);
+ } catch (err) {
+ throw new BiscuitVerificationError(`own credential does not verify: ${describe(err)}`, { cause: err });
+ }
+ const token = wasm.Biscuit.fromBytes(ownBiscuit, wasm.PublicKey.fromBytes(own.verifyingKey, wasm.SignatureAlgorithm.Ed25519));
+ const b = new wasm.AuthorizerBuilder();
+ b.addFact(wasm.Fact.fromString(timeFact(now)));
+ b.addPolicy(wasm.Policy.fromString(BASELINE_DATALOG.allow_if_true));
+ const authorizer = b.buildAuthenticated(token);
+ authorizer.authorizeWithLimits(AUTHORIZER_LIMITS);
+ const facts: WasmFact[] = [];
+ for (const r of BASELINE_DATALOG.target_fact_rules) {
+ facts.push(...(authorizer.queryWithLimits(wasm.Rule.fromString(r), AUTHORIZER_LIMITS) as WasmFact[]));
+ }
+ return facts;
+}
+
+/** The peer a biscuit binds itself to: its node() fact. */
+async function boundPeer(biscuit: Uint8Array, keys: Uint8Array[]): Promise<string> {
+ const wasm = await loadBiscuit();
+ let lastErr: unknown;
+ for (const key of keys) {
+ try {
+ const token = wasm.Biscuit.fromBytes(biscuit, wasm.PublicKey.fromBytes(key, wasm.SignatureAlgorithm.Ed25519));
+ const b = new wasm.AuthorizerBuilder();
+ b.addPolicy(wasm.Policy.fromString(BASELINE_DATALOG.allow_if_true));
+ const authorizer = b.buildAuthenticated(token);
+ const bound = (authorizer.queryWithLimits(wasm.Rule.fromString("p($p) <- node($p)"), AUTHORIZER_LIMITS) as WasmFact[])
+ .map((f) => f.terms()[0])
+ .find((t): t is string => typeof t === "string");
+ if (bound === undefined) {
+ throw new Error("biscuit carries no node() fact");
+ }
+ return bound;
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw new BiscuitVerificationError(`biscuit is not signed by a trusted control plane key: ${describe(lastErr)}`);
+}
diff --git a/sdk/js/src/conformance-join.ts b/sdk/js/src/conformance-join.ts
index b725f3f2..4a8e793e 100644
--- a/sdk/js/src/conformance-join.ts
+++ b/sdk/js/src/conformance-join.ts
@@ -26,13 +26,24 @@
// 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": "..."}
+// call an HTTP service over the mesh
// {"cmd": "peers"} peers that authenticated to us
// {"cmd": "quit"} leave the mesh and exit
//
// 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 { AgentMesh } from "./mesh.ts";
import type { MeshSession } from "./session.ts";
@@ -45,6 +56,11 @@ interface Command {
service?: string;
tool?: string;
args?: Record<string, unknown>;
+ target?: string;
+ path?: string;
+ method?: string;
+ body?: string;
+ headers?: Record<string, string>;
}
function requireEnv(name: string): string {
@@ -91,6 +107,45 @@ async function handle(session: MeshSession, command: Command): Promise<unknown>
}
case "peers":
return { cmd: "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 "http": {
+ const res = await session.request(command.addr ?? "", command.service ?? "", command.path ?? "/", {
+ method: command.method ?? "GET",
+ ...(command.headers !== undefined ? { headers: command.headers } : {}),
+ ...(command.body !== undefined ? { body: command.body } : {}),
+ signal: AbortSignal.timeout(15_000),
+ });
+ return { cmd: "http", ok: true, status: res.status, headers: res.headers, body: res.text() };
+ }
default:
return failure(command.cmd, new Error(`unknown command ${JSON.stringify(command.cmd)}`));
}
diff --git a/sdk/js/src/controlplane.ts b/sdk/js/src/controlplane.ts
index 14dffc10..93066e33 100644
--- a/sdk/js/src/controlplane.ts
+++ b/sdk/js/src/controlplane.ts
@@ -25,6 +25,10 @@ import {
EnrollResponseSchema,
EnrollmentStatus,
KeysResponseSchema,
+ NodeCatalogReportSchema,
+ PolicyConfigGetResponseSchema,
+ ServiceInfoSchema,
+ ServiceType,
TokenRefreshRequestSchema,
TokenRefreshResponseSchema,
type BootstrapEnrollResponse,
@@ -330,6 +334,36 @@ export class ControlPlaneClient {
return { biscuit: resp.biscuitToken, expiration: Number(resp.expiresAt) };
}
+ /**
+ * GET /policies: the mesh policy as the Datalog rules a provider adds to
+ * its authorizer, one per entry, rendered by the control plane. The text
+ * is the contract; nothing here derives rules from roles and bindings.
+ */
+ async policyRules(biscuit: Uint8Array): Promise<string[]> {
+ const body = await this.#request("GET", "/policies", undefined, {
+ Authorization: `Bearer ${Buffer.from(biscuit).toString("base64")}`,
+ });
+ const resp = fromBinary(PolicyConfigGetResponseSchema, body);
+ if (resp.$unknown !== undefined && resp.$unknown.length > 0) {
+ throw new Error("control plane predates datalog_rules in its policy response; upgrade the control plane");
+ }
+ 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 d5987082..0fa7eacc 100644
--- a/sdk/js/src/index.ts
+++ b/sdk/js/src/index.ts
@@ -44,3 +44,22 @@ export { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, MCP_PROTOCOL, AuthRejectedError, a
export { createMeshHost, type MeshHostOptions } from "./host.ts";
export { DHT_PROTOCOL, parseServiceTarget, serviceCID, type ServiceType } from "./discovery.ts";
export { LabelsNotSatisfiedError, StreamTransport, openMCPSession, requireLabels, type MCPSession, type MCPSessionOptions } from "./mcp.ts";
+export { AuthorizationError, authorizeCaller, type AuthorizeRequest, type ProviderAuthorizerOptions } from "./authorizer.ts";
+export {
+ HTTP_PROTOCOL,
+ ServiceRegistry,
+ httpIngressHandler,
+ httpRequestOverStream,
+ mcpStreamHandler,
+ streamToNodeDuplex,
+ type HTTPHandler,
+ type HTTPRequestOptions,
+ type HTTPResponse,
+ type HTTPServiceSpec,
+ type MCPServerLike,
+ type MCPServiceSpec,
+ type ProviderOptions,
+ type ServedService,
+ type ServiceSpec,
+} from "./serve.ts";
+export { BASELINE_DATALOG } from "./gen/datalog.ts";
diff --git a/sdk/js/src/serve.test.ts b/sdk/js/src/serve.test.ts
new file mode 100644
index 00000000..c7430681
--- /dev/null
+++ b/sdk/js/src/serve.test.ts
@@ -0,0 +1,240 @@
+// 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
new file mode 100644
index 00000000..dddcb8ce
--- /dev/null
+++ b/sdk/js/src/serve.ts
@@ -0,0 +1,485 @@
+// 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;
+ /** 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());
+ 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}`;
+ 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 dc5fc2e5..631af062 100644
--- a/sdk/js/src/session.ts
+++ b/sdk/js/src/session.ts
@@ -14,12 +14,25 @@
import type { Connection, Libp2p } from "@libp2p/interface";
import { multiaddr, type Multiaddr } from "@multiformats/multiaddr";
-import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, authenticateWithPeer, authStreamHandler } from "./auth.ts";
+import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, MCP_PROTOCOL, authenticateWithPeer, authStreamHandler } from "./auth.ts";
import { ROLE_ROUTER, requireRole, type VerifiedBiscuit } from "./biscuit.ts";
import { serviceCID, type ServiceType } from "./discovery.ts";
import { createMeshHost, listenThroughRelay, type MeshHostOptions } from "./host.ts";
import { openMCPSession, type MCPSession, type MCPSessionOptions } from "./mcp.ts";
import type { AgentMesh } from "./mesh.ts";
+import {
+ HTTP_PROTOCOL,
+ SERVE_HANDLER_OPTIONS,
+ ServiceRegistry,
+ httpIngressHandler,
+ httpRequestOverStream,
+ mcpStreamHandler,
+ type HTTPRequestOptions,
+ type HTTPResponse,
+ type ProviderOptions,
+ type ServedService,
+ type ServiceSpec,
+} from "./serve.ts";
export interface JoinOptions extends MeshHostOptions {
/**
@@ -32,6 +45,10 @@ 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. */
+ policySyncIntervalMs?: number;
+ /** How often published services are re-announced in the DHT. */
+ provideIntervalMs?: number;
/** Bounds the whole join. */
signal?: AbortSignal;
}
@@ -63,6 +80,10 @@ const DISCOVERY_TIMEOUT_MS = 5_000;
const DEFAULT_REFRESH_LEAD_MS = 60 * 60 * 1000;
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;
/**
* A member that is on the mesh: a libp2p host authenticated with at least
@@ -75,9 +96,17 @@ export class MeshSession {
readonly routers: AdmittedRouter[];
/** Peers that passed the inbound auth handshake, with their credential's expiration. */
readonly authenticatedPeers: Map<string, Date>;
+ /** The services this member publishes. */
+ readonly services = new ServiceRegistry();
#refreshTimer: ReturnType<typeof setTimeout> | undefined;
+ #policyTimer: ReturnType<typeof setInterval> | undefined;
+ #provideTimer: ReturnType<typeof setInterval> | undefined;
readonly #refreshLeadMs: number;
readonly #refreshRetryMs: number;
+ readonly #policySyncMs: number;
+ readonly #provideIntervalMs: number;
+ #policyRules: string[] | undefined;
+ #serving = false;
#closed = false;
constructor(mesh: AgentMesh, node: Libp2p, routers: AdmittedRouter[], authenticatedPeers: Map<string, Date>, options: JoinOptions) {
@@ -87,6 +116,8 @@ export class MeshSession {
this.authenticatedPeers = authenticatedPeers;
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.#scheduleRefresh();
}
@@ -197,6 +228,90 @@ export class MeshSession {
this.#scheduleRefresh();
}
+ /**
+ * 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().
+ */
+ get policyRules(): string[] {
+ return this.#policyRules ?? [];
+ }
+
+ /** Re-reads the mesh policy from the control plane. */
+ async syncPolicy(): Promise<void> {
+ this.#policyRules = await this.mesh.controlPlane.policyRules(this.mesh.credential.biscuit);
+ }
+
+ /**
+ * Calls an inference or A2A service on a provider over /libp2p-http, the
+ * way sam-node's egress proxy does for /sam/<peer>/<type>/<name>/<path>.
+ */
+ async request(addr: string | Multiaddr, targetService: string, path: string, options: HTTPRequestOptions = {}): Promise<HTTPResponse> {
+ const conn = await this.connect(addr, options.signal);
+ return httpRequestOverStream(conn, this.mesh.credential.biscuit, targetService, path, options);
+ }
+
+ /**
+ * 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.
+ */
+ 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,
+ 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;
+ }
+ }
+ }
+ }
+
+ /** 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());
+ }
+
+ /** The services this member publishes. */
+ get servedServices(): ServedService[] {
+ return this.services.list();
+ }
+
#scheduleRefresh(): void {
if (this.#closed) {
return;
@@ -222,6 +337,8 @@ export class MeshSession {
async close(): Promise<void> {
this.#closed = true;
clearTimeout(this.#refreshTimer);
+ clearInterval(this.#policyTimer);
+ clearInterval(this.#provideTimer);
await this.node.stop();
}
}
diff --git a/sdk/python/README.md b/sdk/python/README.md
index 2b7f0b04..95988c3d 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -24,7 +24,8 @@ Runtime dependencies are `cryptography`, `protobuf`, `biscuit-python`,
```python
import trio
-from agent_mesh import AgentMesh
+from agent_mesh import AgentMesh, HTTPRequest, HTTPResponse, HTTPService, MCPService, VerifiedBiscuit
+from mcp.server.mcpserver import MCPServer
mesh = AgentMesh.enroll(
"https://hub.sam-mesh.dev",
@@ -50,6 +51,29 @@ async def main():
result = await session.call_tool(addr, "mcp://calc", "add", {"a": 1, "b": 2}, required_labels={"region": "eu"})
print(result.text)
+ # Publish services of your own. Callers are authorized with the mesh
+ # policy before anything reaches your code or your backend.
+ def create_server() -> MCPServer:
+ server = MCPServer("echo")
+
+ @server.tool()
+ def echo(text: str) -> str:
+ return text
+
+ return server
+
+ await session.serve(MCPService(name="echo", create_server=create_server))
+ await session.serve(HTTPService(type="inference", name="llm", target="http://127.0.0.1:8000"))
+
+ async def card(request: HTTPRequest, caller: VerifiedBiscuit) -> HTTPResponse:
+ return HTTPResponse(status=200, body=f"hello {caller.peer_id}".encode())
+
+ await session.serve(HTTPService(type="a2a", name="reviewer", target=card))
+
+ # Call an inference or A2A service on another member.
+ models = await session.request(addr, "inference://llm", "/v1/models")
+ print(models.status, models.text)
+
trio.run(main)
@@ -83,10 +107,17 @@ A plaintext `http://` control plane is accepted only on loopback. Pass
both sides, the circuit relay v2 client (reservation, dial, accept) and
`MeshSession` with the refresh loop.
- `agent_mesh.discovery`, `agent_mesh.mcp_client`: the bounded
- GET_PROVIDERS walk on the mesh DHT, and MCP over `/sam/mcp/1.0.0` for
- `mcp.ClientSession`.
-- `agent_mesh._proto`: generated from `api/sam.proto` and
- `sdk/python/proto/circuit.proto` by `hack/gen-sdk-proto.sh`.
+ GET_PROVIDERS walk and ADD_PROVIDER on the mesh DHT, and MCP over
+ `/sam/mcp/1.0.0` for `mcp.ClientSession`.
+- `agent_mesh.authorizer`: the provider authorizer, as
+ `internal/node.(*SamNode).Authorize`, over the generated baseline Datalog
+ and the mesh policy rules from `GET /policies`.
+- `agent_mesh.serve`: the `/sam/mcp/1.0.0` server, the `/libp2p-http`
+ server and client (`h11` on the stream), and the service registry behind
+ `session.serve()`.
+- `agent_mesh._proto`, `agent_mesh._gen`: generated from `api/sam.proto`,
+ `sdk/python/proto/circuit.proto` and `api/datalog.go` by
+ `hack/gen-sdk-proto.sh`.
## Test
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index 6c1f9769..08f6e2c4 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -13,6 +13,9 @@ dependencies = [
"anyio>=4",
"biscuit-python>=0.4",
"cryptography>=42",
+ # HTTP/1.1 on a libp2p stream (/libp2p-http) and forwarding to a backend.
+ "h11>=0.14",
+ "httpx>=0.27",
"libp2p>=0.7,<0.8",
"mcp>=2,<3",
"multiaddr>=0.2",
diff --git a/sdk/python/src/agent_mesh/__init__.py b/sdk/python/src/agent_mesh/__init__.py
index 37c079b8..eb8f766b 100644
--- a/sdk/python/src/agent_mesh/__init__.py
+++ b/sdk/python/src/agent_mesh/__init__.py
@@ -15,6 +15,7 @@
"""Native SDK for joining a SAM agent mesh from inside a Python process."""
from .auth import AUTH_PROTOCOL, MCP_PROTOCOL, AuthRejectedError, auth_stream_handler, authenticate_with_peer
+from .authorizer import BASELINE_DATALOG, AuthorizationError, AuthorizeRequest, ProviderAuthorizerOptions, authorize_caller
from .biscuit import ROLE_ROUTER, BiscuitVerificationError, VerifiedBiscuit, require_role, verify_peer_biscuit
from .challenges import enroll_challenge, enroll_status_challenge, refresh_challenge, register_challenge
from .controlplane import (
@@ -29,11 +30,24 @@ from .controlplane import (
verify_keys_response,
)
from .credential import MeshCredential, decode_auth_response, encode_auth_frame
-from .discovery import DHT_PROTOCOL, DiscoveredProvider, find_providers, parse_service_target, service_key
+from .discovery import DHT_PROTOCOL, DiscoveredProvider, find_providers, parse_service_target, provide, service_key
from .identity import Identity, libp2p_public_key, peer_id_from_public_key, verify_ed25519
from .mcp_client import LabelsNotSatisfiedError, ToolCallResult, open_mcp_session, require_labels
from .mesh import AgentMesh
from .relay import dial_through_relay, reserve_relay
+from .serve import (
+ HTTP_PROTOCOL,
+ HTTPHandler,
+ HTTPRequest,
+ HTTPResponse,
+ HTTPService,
+ MCPService,
+ ProviderOptions,
+ ServiceRegistry,
+ http_ingress_handler,
+ http_request_over_stream,
+ mcp_stream_handler,
+)
from .session import AdmittedRouter, MeshSession
__version__ = "0.1.0"
@@ -43,6 +57,9 @@ __all__ = [
"AdmittedRouter",
"AgentMesh",
"AuthRejectedError",
+ "AuthorizationError",
+ "AuthorizeRequest",
+ "BASELINE_DATALOG",
"BiscuitVerificationError",
"ControlPlaneClient",
"ControlPlaneError",
@@ -50,29 +67,43 @@ __all__ = [
"DiscoveredProvider",
"Enrollment",
"EnrollmentRejectedError",
+ "HTTP_PROTOCOL",
+ "HTTPHandler",
+ "HTTPRequest",
+ "HTTPResponse",
+ "HTTPService",
"Identity",
"InsecureControlPlaneURLError",
"LabelsNotSatisfiedError",
"MCP_PROTOCOL",
+ "MCPService",
"MeshCredential",
"MeshSession",
+ "ProviderAuthorizerOptions",
+ "ProviderOptions",
"ROLE_NODE",
"ROLE_ROUTER",
"RefreshResult",
+ "ServiceRegistry",
"ToolCallResult",
"VerifiedBiscuit",
"auth_stream_handler",
"authenticate_with_peer",
+ "authorize_caller",
"decode_auth_response",
"dial_through_relay",
"encode_auth_frame",
"enroll_challenge",
"enroll_status_challenge",
"find_providers",
+ "http_ingress_handler",
+ "http_request_over_stream",
"libp2p_public_key",
+ "mcp_stream_handler",
"open_mcp_session",
"parse_service_target",
"peer_id_from_public_key",
+ "provide",
"refresh_challenge",
"register_challenge",
"require_labels",
diff --git a/sdk/python/src/agent_mesh/authorizer.py b/sdk/python/src/agent_mesh/authorizer.py
new file mode 100644
index 00000000..33575815
--- /dev/null
+++ b/sdk/python/src/agent_mesh/authorizer.py
@@ -0,0 +1,168 @@
+# 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 authorizer, mirroring internal/node.(*SamNode).Authorize.
+Every piece of Datalog it evaluates is text: the baseline generated from
+api/datalog.go (_gen/datalog.json) and the mesh policy rules the control
+plane renders (GET /policies). Nothing here derives rules from roles."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from importlib import resources
+from typing import Callable, Optional, Sequence
+
+import biscuit_auth as ba
+
+from .biscuit import BiscuitVerificationError, VerifiedBiscuit, _limits, verify_peer_biscuit
+from .discovery import parse_service_target
+
+BASELINE_DATALOG: dict = json.loads(resources.files("agent_mesh._gen").joinpath("datalog.json").read_text())
+
+
+class AuthorizationError(Exception):
+ def __init__(self, peer_id: str, reason: str):
+ super().__init__(f"caller {peer_id} is not authorized: {reason}")
+ self.peer_id = peer_id
+ self.reason = reason
+
+
+@dataclass(frozen=True)
+class AuthorizeRequest:
+ """What a caller asks for, as sam-node's RequestContext."""
+
+ # The caller's biscuit, as it arrived in the AuthFrame or X-Sam-Biscuit.
+ biscuit: bytes
+ # The peer at the other end of the authenticated connection.
+ peer_id: str
+ # "mcp://<name>", or "" for the protocol itself (the provider's own catalog).
+ target_service: str
+ # The stream protocol; names the service when target_service is "".
+ protocol: str
+ # The agent the caller says it acts for; its own claim, checked against its grants.
+ agent: str = ""
+
+
+@dataclass(frozen=True)
+class ProviderAuthorizerOptions:
+ # Control plane keys, read per request so a rotation takes effect.
+ trusted_keys: Callable[[], Sequence[bytes]]
+ # This provider's own biscuit; its identity facts are what target grants match.
+ own_biscuit: Callable[[], bytes]
+ # The mesh policy as PolicyConfigGetResponse.datalog_rules.
+ policy_rules: Callable[[], Sequence[str]]
+ now: Optional[Callable[[], datetime]] = None
+
+
+def _token(biscuit: bytes, key: bytes) -> ba.Biscuit:
+ return ba.Biscuit.from_bytes(biscuit, ba.PublicKey.from_bytes(bytes(key), ba.Algorithm.Ed25519))
+
+
+def authorize_caller(req: AuthorizeRequest, options: ProviderAuthorizerOptions) -> VerifiedBiscuit:
+ """Authorizes one request from a caller. Returns the caller's verified
+ credential when every check holds and a policy allows; raises
+ AuthorizationError otherwise. Every trusted key is tried, as
+ VerifyBiscuitToken does."""
+ now = options.now() if options.now else datetime.now(timezone.utc)
+ keys = list(options.trusted_keys())
+ if not keys:
+ raise AuthorizationError(req.peer_id, "no trusted control plane key")
+
+ # Signature under a trusted key, authority block only, expiry and binding
+ # to the connection peer: RequireAuthorityBinding and EnforceExpiration.
+ try:
+ caller = verify_peer_biscuit(req.biscuit, req.peer_id, keys, now)
+ except BiscuitVerificationError as err:
+ raise AuthorizationError(req.peer_id, str(err)) from err
+ token = _token(req.biscuit, caller.verifying_key)
+
+ b = ba.AuthorizerBuilder()
+ b.set_limits(_limits())
+
+ # The action: service(type, name). An empty target is the protocol itself
+ # in the system namespace, as sam-node scopes its own catalog.
+ if req.target_service == "":
+ svc_type, svc_name = BASELINE_DATALOG["system_namespace"], req.protocol
+ else:
+ try:
+ svc_type, svc_name = parse_service_target(req.target_service)
+ except ValueError as err:
+ raise AuthorizationError(req.peer_id, str(err)) from err
+ b.add_fact(ba.Fact(BASELINE_DATALOG["fact_service"] + "({t}, {n})", {"t": svc_type, "n": svc_name}))
+ b.add_fact(ba.Fact(BASELINE_DATALOG["fact_connection_peer_id"] + "({p})", {"p": req.peer_id}))
+ b.add_fact(ba.Fact(BASELINE_DATALOG["fact_time"] + "({now})", {"now": now}))
+
+ # The caller's word about which agent it acts for, limited to the agent
+ # namespaces its own token grants.
+ if req.agent:
+ b.add_fact(ba.Fact(BASELINE_DATALOG["fact_agent"] + "({a})", {"a": req.agent}))
+ for r in BASELINE_DATALOG["agent_rules"]:
+ b.add_rule(ba.Rule(r))
+ b.add_check(ba.Check(BASELINE_DATALOG["agent_check"]))
+
+ b.add_check(ba.Check(BASELINE_DATALOG["replay_check"]))
+ b.add_check(ba.Check(BASELINE_DATALOG["time_check"]))
+
+ # This provider's identity as target_fact facts, so the caller's target
+ # grants have something to match (injectIdentityFacts).
+ for f in _identity_target_facts(options.own_biscuit(), keys, now):
+ b.add_fact(f)
+
+ b.add_check(ba.Check(BASELINE_DATALOG["target_check"]))
+ for p in BASELINE_DATALOG["policies"]:
+ b.add_policy(ba.Policy(p))
+ for r in BASELINE_DATALOG["rules"]:
+ b.add_rule(ba.Rule(r))
+ for r in options.policy_rules():
+ b.add_rule(ba.Rule(r))
+
+ try:
+ b.build(token).authorize()
+ except Exception as err: # noqa: BLE001 - biscuit-python raises several types for a denial
+ raise AuthorizationError(req.peer_id, str(err)) from err
+ return caller
+
+
+def _identity_target_facts(own_biscuit: bytes, keys: Sequence[bytes], now: datetime) -> list[ba.Fact]:
+ """Evaluates this provider's own biscuit and returns its identity as
+ target_fact facts, one per target_fact rule of the baseline."""
+ if not own_biscuit:
+ return []
+ verifying_key = None
+ last_err: Exception | None = None
+ for key in keys:
+ try:
+ _token(own_biscuit, key)
+ verifying_key = key
+ break
+ except Exception as err: # noqa: BLE001
+ last_err = err
+ if verifying_key is None:
+ raise BiscuitVerificationError(f"own credential is not signed by a trusted control plane key: {last_err}")
+ b = ba.AuthorizerBuilder()
+ b.set_limits(_limits())
+ b.add_fact(ba.Fact(BASELINE_DATALOG["fact_time"] + "({now})", {"now": now}))
+ b.add_check(ba.Check(BASELINE_DATALOG["time_check"]))
+ b.add_policy(ba.Policy(BASELINE_DATALOG["allow_if_true"]))
+ authorizer = b.build(_token(own_biscuit, verifying_key))
+ try:
+ authorizer.authorize()
+ except Exception as err: # noqa: BLE001
+ raise BiscuitVerificationError(f"own credential does not verify: {err}") from err
+ facts: list[ba.Fact] = []
+ for r in BASELINE_DATALOG["target_fact_rules"]:
+ facts.extend(authorizer.query(ba.Rule(r)))
+ return facts
diff --git a/sdk/python/src/agent_mesh/conformance_join.py b/sdk/python/src/agent_mesh/conformance_join.py
index 721165af..521b10b9 100644
--- a/sdk/python/src/agent_mesh/conformance_join.py
+++ b/sdk/python/src/agent_mesh/conformance_join.py
@@ -25,6 +25,15 @@ then takes JSON commands on stdin, one per line, until stdin closes:
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": "..."}
+ call an HTTP service over the mesh
{"cmd": "peers"} peers that authenticated to us
{"cmd": "quit"} leave the mesh and exit
@@ -40,8 +49,10 @@ import sys
import traceback
import trio
+from mcp.server.mcpserver import MCPServer
from .mesh import AgentMesh
+from .serve import HTTPRequest, HTTPResponse, HTTPService, MCPService
from .session import MeshSession
@@ -89,6 +100,45 @@ async def _handle(session: MeshSession, command: dict) -> dict:
return {"cmd": cmd, "ok": True, "is_error": result.is_error, "text": result.text}
if cmd == "peers":
return {"cmd": cmd, "authenticated_peers": sorted(session.authenticated_peers)}
+ if cmd == "serve":
+ name = command.get("name", "")
+ service_type = command.get("type")
+ if service_type == "mcp":
+
+ def create_server() -> MCPServer:
+ server = MCPServer(name)
+
+ @server.tool()
+ def echo(text: str) -> str:
+ return f"python:{text}"
+
+ return server
+
+ await session.serve(MCPService(name=name, create_server=create_server, description="echo served by the python SDK"))
+ elif service_type in ("inference", "a2a"):
+ target = command.get("target")
+ if not target:
+
+ async def fake(request: HTTPRequest, caller) -> HTTPResponse: # type: ignore[no-untyped-def]
+ body = json.dumps({"sdk": "python", "peer": caller.peer_id, "method": request.method, "path": request.path.split("?")[0]})
+ return HTTPResponse(status=200, headers={"content-type": "application/json"}, body=body.encode())
+
+ target = fake
+ await session.serve(HTTPService(type=service_type, name=name, target=target, description=f"{service_type} served by the python SDK"))
+ else:
+ return {"cmd": cmd, "ok": False, "error": f"unknown service type {service_type!r}"}
+ return {"cmd": cmd, "ok": True, "services": [f"{t}://{n}" for t, n, _ in session.services.list()]}
+ if cmd == "http":
+ with trio.fail_after(15):
+ res = await session.request(
+ command["addr"],
+ command.get("service", ""),
+ command.get("path", "/"),
+ method=command.get("method", "GET"),
+ headers=command.get("headers"),
+ body=command.get("body"),
+ )
+ return {"cmd": cmd, "ok": True, "status": res.status, "headers": res.headers, "body": res.text}
return {"cmd": cmd, "ok": False, "error": f"unknown command {cmd!r}"}
except BaseException as err: # noqa: BLE001 - the driver wants the failure, not a dead runner
if isinstance(err, (KeyboardInterrupt, SystemExit, trio.Cancelled)):
diff --git a/sdk/python/src/agent_mesh/controlplane.py b/sdk/python/src/agent_mesh/controlplane.py
index 931ee93e..4c504cdb 100644
--- a/sdk/python/src/agent_mesh/controlplane.py
+++ b/sdk/python/src/agent_mesh/controlplane.py
@@ -27,6 +27,8 @@ import urllib.request
from dataclasses import dataclass, field
from typing import Callable, Mapping, Optional, Sequence
+from google.protobuf.unknown_fields import UnknownFieldSet
+
from . import challenges
from ._proto import sam_pb2 as pb
from .identity import PUBLIC_KEY_SIZE, Identity, verify_ed25519
@@ -272,6 +274,29 @@ class ControlPlaneClient:
raise ValueError("refresh returned an empty biscuit")
return RefreshResult(biscuit=resp.biscuit_token, expiration=resp.expires_at)
+ def policy_rules(self, biscuit: bytes) -> list[str]:
+ """GET /policies: the mesh policy as the Datalog rules a provider adds
+ to its authorizer, one per entry, rendered by the control plane. The
+ text is the contract; nothing here derives rules from roles and bindings."""
+ body = self._request("GET", "/policies", headers={"Authorization": "Bearer " + base64.b64encode(biscuit).decode()})
+ resp = pb.PolicyConfigGetResponse.FromString(body)
+ if len(UnknownFieldSet(resp)) > 0:
+ raise ValueError("control plane predates datalog_rules in its policy response; upgrade the control plane")
+ return list(resp.datalog_rules)
+
+ def report_catalog(self, biscuit: bytes, services: Sequence[tuple[str, str, str]]) -> None:
+ """POST /nodes/catalog: this member's published services as (type, name,
+ description), for the console. Display only; the control plane takes
+ the reporting peer from the biscuit."""
+ types = {"mcp": pb.SERVICE_TYPE_MCP, "inference": pb.SERVICE_TYPE_INFERENCE, "a2a": pb.SERVICE_TYPE_A2A}
+ report = pb.NodeCatalogReport(services=[pb.ServiceInfo(type=types[t], name=n, description=d) for t, n, d in services])
+ self._request(
+ "POST",
+ "/nodes/catalog",
+ report.SerializeToString(),
+ headers={"Authorization": "Bearer " + base64.b64encode(biscuit).decode()},
+ )
+
def _request(self, method: str, path: str, body: Optional[bytes] = None, headers: Optional[Mapping[str, str]] = None) -> bytes:
all_headers = {"Accept": PROTOBUF_CONTENT_TYPE, **(headers or {})}
if body is not None:
diff --git a/sdk/python/src/agent_mesh/discovery.py b/sdk/python/src/agent_mesh/discovery.py
index 70c654c3..302d752e 100644
--- a/sdk/python/src/agent_mesh/discovery.py
+++ b/sdk/python/src/agent_mesh/discovery.py
@@ -23,7 +23,7 @@ from __future__ import annotations
import hashlib
import logging
from dataclasses import dataclass, field
-from typing import Iterable, Literal
+from typing import Iterable, Literal, Sequence
import multiaddr
import trio
@@ -141,3 +141,56 @@ async def find_providers(host: IHost, key: bytes, seeds: Iterable[ID], limit: in
if found:
break
return list(found.values())
+
+
+async def _add_provider(host: IHost, peer_id: ID, key: bytes, addrs: Sequence[multiaddr.Multiaddr]) -> bool:
+ """Sends one ADD_PROVIDER for key naming ourselves. go-libp2p-kad-dht
+ stores the record only when the sender is the provider and lists at
+ least one address, and answers nothing."""
+ try:
+ stream = await host.new_stream(peer_id, [DHT_PROTOCOL])
+ except Exception as err: # noqa: BLE001 - a peer that does not serve the DHT is skipped
+ logger.debug("dht: %s does not answer %s: %s", peer_id, DHT_PROTOCOL, err)
+ return False
+ try:
+ with trio.fail_after(_QUERY_TIMEOUT):
+ msg = kad.Message(type=kad.Message.ADD_PROVIDER, key=key)
+ provider = msg.providerPeers.add()
+ provider.id = host.get_id().to_bytes()
+ provider.addrs.extend(ma.to_bytes() for ma in addrs)
+ await stream.write(encode_varint_prefixed(msg.SerializeToString()))
+ except Exception as err: # noqa: BLE001
+ logger.debug("dht: add_provider to %s failed: %s", peer_id, err)
+ return False
+ finally:
+ await stream.close()
+ return True
+
+
+async def provide(host: IHost, key: bytes, seeds: Iterable[ID], addrs: Sequence[multiaddr.Multiaddr]) -> int:
+ """Announces this host as a provider of key, as sam-node's DHT provide:
+ the record goes to the seed peers (the routers, which serve the DHT) and
+ to the closer peers they name for the key. Returns how many accepted a
+ stream; the DHT does not acknowledge the record itself."""
+ self_id = host.get_id()
+ targets: list[ID] = [p for p in seeds if p != self_id]
+ for seed in list(targets):
+ resp = await _get_providers(host, seed, key)
+ if resp is None:
+ continue
+ for info in _peer_infos(resp.closerPeers):
+ if info.peer_id == self_id or info.peer_id in targets:
+ continue
+ if info.peer_id not in host.get_connected_peers():
+ try:
+ await host.connect(info)
+ except Exception: # noqa: BLE001 - unreachable closer peers are skipped
+ continue
+ targets.append(info.peer_id)
+ if len(targets) >= _MAX_PEERS_PER_ROUND:
+ break
+ sent = 0
+ for peer_id in targets[:_MAX_PEERS_PER_ROUND]:
+ if await _add_provider(host, peer_id, key, addrs):
+ sent += 1
+ return sent
diff --git a/sdk/python/src/agent_mesh/serve.py b/sdk/python/src/agent_mesh/serve.py
new file mode 100644
index 00000000..6ad66c46
--- /dev/null
+++ b/sdk/python/src/agent_mesh/serve.py
@@ -0,0 +1,495 @@
+# 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)."""
+
+from __future__ import annotations
+
+import base64
+import json
+import logging
+from dataclasses import dataclass, field
+from typing import Awaitable, Callable, Literal, Mapping, Optional, Sequence, Union
+
+import anyio
+import h11
+import httpx
+import mcp_types
+import trio
+from libp2p.abc import IHost, INetStream
+from libp2p.custom_types import TProtocol
+from libp2p.peer.id import ID
+from libp2p.utils.varint import encode_varint_prefixed, read_varint_prefixed_bytes
+from mcp.server.mcpserver import MCPServer
+from mcp.shared.message import SessionMessage
+
+from ._proto import sam_pb2 as pb
+from .auth import AUTH_HANDSHAKE_TIMEOUT, MAX_AUTH_FRAME_BYTES
+from .authorizer import AuthorizationError, AuthorizeRequest, ProviderAuthorizerOptions, authorize_caller
+from .biscuit import VerifiedBiscuit
+from .discovery import ServiceType
+from .mcp_client import MAX_MCP_MESSAGE_BYTES
+
+logger = logging.getLogger("agent_mesh")
+
+# go-libp2p-http's protocol: plain HTTP/1.1 on a stream, one request per stream.
+HTTP_PROTOCOL = TProtocol("/libp2p-http")
+
+# Headers of the mesh HTTP datapath (api/network.go).
+HEADER_SAM_BISCUIT = "x-sam-biscuit"
+HEADER_SAM_AGENT = "x-sam-agent"
+HEADER_PEER_ID = "x-peer-id"
+HEADER_SAM_NO_TRAILING_SLASH = "x-sam-no-trailing-slash"
+
+_MAX_INGRESS_BODY_BYTES = 8 * 1024 * 1024
+_READ_CHUNK = 64 * 1024
+_REQUEST_TIMEOUT = 60.0
+
+
+@dataclass(frozen=True)
+class HTTPRequest:
+ """What an in-process HTTP handler receives: the request as it reached
+ the service, path relative to /<type>/<name>."""
+
+ method: str
+ path: str
+ headers: dict[str, str]
+ body: bytes
+
+ @property
+ def text(self) -> str:
+ return self.body.decode("utf-8", "replace")
+
+
+@dataclass(frozen=True)
+class HTTPResponse:
+ status: int
+ headers: dict[str, str] = field(default_factory=dict)
+ body: bytes = b""
+
+ @property
+ def text(self) -> str:
+ return self.body.decode("utf-8", "replace")
+
+ def json(self): # type: ignore[no-untyped-def]
+ return json.loads(self.body)
+
+
+HTTPHandler = Callable[[HTTPRequest, VerifiedBiscuit], Awaitable[HTTPResponse]]
+
+
+@dataclass(frozen=True)
+class MCPService:
+ """An MCP service: one server per session, since an MCP server run holds one transport."""
+
+ name: str
+ create_server: Callable[[], MCPServer]
+ description: str = ""
+ type: Literal["mcp"] = "mcp"
+
+
+@dataclass(frozen=True)
+class HTTPService:
+ """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
+ biscuit and agent headers are stripped and X-Peer-Id names the verified
+ caller, as sam-node does."""
+
+ type: Literal["inference", "a2a"]
+ name: str
+ target: Union[str, HTTPHandler]
+ description: str = ""
+
+
+ServiceSpec = Union[MCPService, HTTPService]
+
+
+@dataclass(frozen=True)
+class ProviderOptions:
+ authorizer: ProviderAuthorizerOptions
+ # This provider's current biscuit, for the mutual AuthResponse.
+ own_biscuit: Callable[[], bytes]
+ # Called after a caller is authorized for a service, e.g. for the session's admitted set.
+ on_authorized: Optional[Callable[[str, VerifiedBiscuit, str], None]] = None
+
+
+class ServiceRegistry:
+ """Services registered on a member, keyed by type and name."""
+
+ def __init__(self) -> None:
+ self._services: dict[str, ServiceSpec] = {}
+
+ @staticmethod
+ def key(service_type: str, name: str) -> str:
+ return f"{service_type}://{name}"
+
+ def add(self, spec: ServiceSpec) -> None:
+ key = self.key(spec.type, spec.name)
+ if key in self._services:
+ raise ValueError(f"service {key} is already registered")
+ self._services[key] = spec
+
+ def remove(self, service_type: ServiceType, name: str) -> bool:
+ return self._services.pop(self.key(service_type, name), None) is not None
+
+ def get(self, service_type: str, name: str) -> Optional[ServiceSpec]:
+ return self._services.get(self.key(service_type, name))
+
+ def list(self) -> list[tuple[str, str, str]]:
+ """(type, name, description) of every registered service."""
+ return [(s.type, s.name, s.description) for s in self._services.values()]
+
+
+def _catalog_server(registry: ServiceRegistry) -> MCPServer:
+ """The member's own catalog over MCP, as sam-node's list_local_services."""
+ server = MCPServer("agent-mesh-sdk")
+
+ @server.tool(description="List the services this member publishes on the mesh")
+ def list_local_services() -> str:
+ return json.dumps([{"type": t, "name": n, "description": d} for t, n, d in registry.list()])
+
+ return server
+
+
+async def _refuse(stream: INetStream, peer_id: str, reason: str) -> None:
+ logger.info("refusing %s: %s", peer_id, reason)
+ try:
+ with trio.fail_after(AUTH_HANDSHAKE_TIMEOUT):
+ await stream.write(encode_varint_prefixed(pb.AuthResponse(success=False, error=reason).SerializeToString()))
+ except Exception: # noqa: BLE001 - the caller may already be gone
+ pass
+
+
+def mcp_stream_handler(registry: ServiceRegistry, options: ProviderOptions, protocol: str): # type: ignore[no-untyped-def]
+ """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."""
+
+ async def handle(stream: INetStream) -> None:
+ peer_id = str(stream.muxed_conn.peer_id)
+ try:
+ with trio.fail_after(AUTH_HANDSHAKE_TIMEOUT):
+ data = await read_varint_prefixed_bytes(stream)
+ if len(data) > MAX_AUTH_FRAME_BYTES:
+ await stream.close()
+ return
+ frame = pb.AuthFrame.FromString(data)
+ try:
+ verified = await trio.to_thread.run_sync(
+ authorize_caller,
+ AuthorizeRequest(biscuit=frame.biscuit, peer_id=peer_id, target_service=frame.target_service, protocol=protocol, agent=frame.agent),
+ options.authorizer,
+ )
+ except AuthorizationError as err:
+ await _refuse(stream, peer_id, str(err))
+ await stream.close()
+ return
+ if options.on_authorized:
+ options.on_authorized(peer_id, verified, frame.target_service)
+ with trio.fail_after(AUTH_HANDSHAKE_TIMEOUT):
+ await stream.write(encode_varint_prefixed(pb.AuthResponse(success=True, biscuit=options.own_biscuit()).SerializeToString()))
+
+ if frame.target_service == "":
+ server = _catalog_server(registry)
+ else:
+ spec = registry.get("mcp", frame.target_service.removeprefix("mcp://")) if frame.target_service.startswith("mcp://") else None
+ if not isinstance(spec, MCPService):
+ logger.info("no MCP service %s for %s", frame.target_service, peer_id)
+ await stream.close()
+ return
+ server = spec.create_server()
+ await _serve_mcp(stream, server)
+ except Exception as err: # noqa: BLE001 - one caller's failure must not take the handler down
+ logger.debug("mcp stream from %s ended: %s", peer_id, err)
+ await stream.close()
+
+ return handle
+
+
+async def _serve_mcp(stream: INetStream, server: MCPServer) -> None:
+ """Runs one MCP server over the stream until the caller goes away."""
+ low = server._lowlevel_server # noqa: SLF001 - the only way to run it over custom streams
+ read_writer, read_stream = anyio.create_memory_object_stream[SessionMessage | Exception](0)
+ write_stream, write_reader = anyio.create_memory_object_stream[SessionMessage](0)
+
+ async def pump_in() -> None:
+ try:
+ async with read_writer:
+ while True:
+ data = await read_varint_prefixed_bytes(stream)
+ if len(data) > MAX_MCP_MESSAGE_BYTES:
+ raise ValueError("oversized MCP frame")
+ try:
+ message = mcp_types.jsonrpc_message_adapter.validate_json(data, by_name=False)
+ except ValueError as exc:
+ await read_writer.send(exc)
+ continue
+ await read_writer.send(SessionMessage(message))
+ except Exception: # noqa: BLE001 - the caller went away
+ pass
+
+ async def pump_out() -> None:
+ try:
+ async with write_reader:
+ async for message in write_reader:
+ await stream.write(encode_varint_prefixed(message.message.model_dump_json(by_alias=True, exclude_unset=True).encode()))
+ except Exception: # noqa: BLE001
+ pass
+
+ async with trio.open_nursery() as nursery:
+ nursery.start_soon(pump_in)
+ nursery.start_soon(pump_out)
+ try:
+ await low.run(read_stream, write_stream, low.create_initialization_options())
+ except Exception: # noqa: BLE001 - the session ended with the stream
+ pass
+ finally:
+ await stream.close()
+ nursery.cancel_scope.cancel()
+
+
+def _has_dot_segment(path: str) -> bool:
+ return any(seg in (".", "..") for seg in path.split("/"))
+
+
+async def _read_http_request(stream: INetStream, conn: h11.Connection, limit: int) -> tuple[h11.Request, bytes]:
+ request: Optional[h11.Request] = None
+ body = bytearray()
+ while True:
+ event = conn.next_event()
+ if event is h11.NEED_DATA:
+ try:
+ data = await stream.read(_READ_CHUNK)
+ except Exception: # noqa: BLE001 - EOF or reset: the parser sees end of input
+ data = b""
+ conn.receive_data(data)
+ continue
+ if isinstance(event, h11.Request):
+ request = event
+ elif isinstance(event, h11.Data):
+ body.extend(event.data)
+ if len(body) > limit:
+ raise ValueError(f"body exceeds {limit} bytes")
+ elif isinstance(event, h11.EndOfMessage):
+ if request is None:
+ raise ValueError("end of message before request")
+ return request, bytes(body)
+ elif isinstance(event, (h11.ConnectionClosed, h11.PAUSED)):
+ raise ValueError("connection closed before a request")
+
+
+async def _write_http_response(stream: INetStream, conn: h11.Connection, status: int, headers: Mapping[str, str], body: bytes) -> None:
+ out = [(k.encode(), v.encode()) for k, v in headers.items() if k.lower() not in ("content-length", "transfer-encoding", "connection")]
+ out.append((b"content-length", str(len(body)).encode()))
+ out.append((b"connection", b"close"))
+ data = conn.send(h11.Response(status_code=status, headers=out)) or b""
+ data += conn.send(h11.Data(data=body)) or b""
+ data += conn.send(h11.EndOfMessage()) or b""
+ await stream.write(data)
+
+
+def http_ingress_handler(registry: ServiceRegistry, options: ProviderOptions): # type: ignore[no-untyped-def]
+ """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."""
+
+ async def handle(stream: INetStream) -> None:
+ peer_id = str(stream.muxed_conn.peer_id)
+ conn = h11.Connection(h11.SERVER)
+
+ async def reply(status: int, text: str) -> None:
+ await _write_http_response(stream, conn, status, {"content-type": "text/plain; charset=utf-8"}, (text + "\n").encode())
+
+ try:
+ try:
+ with trio.fail_after(AUTH_HANDSHAKE_TIMEOUT):
+ request, body = await _read_http_request(stream, conn, _MAX_INGRESS_BODY_BYTES)
+ except (ValueError, h11.RemoteProtocolError, trio.TooSlowError) as err:
+ logger.debug("http ingress from %s: %s", peer_id, err)
+ return
+ status, headers, out = await _handle_ingress(request, body, peer_id, registry, options)
+ await _write_http_response(stream, conn, status, headers, out)
+ except Exception as err: # noqa: BLE001 - one caller's failure must not take the handler down
+ logger.debug("http ingress from %s failed: %s", peer_id, err)
+ try:
+ await reply(500, f"ingress error: {err}")
+ except Exception: # noqa: BLE001
+ pass
+ finally:
+ await stream.close()
+
+ return handle
+
+
+async def _handle_ingress(
+ request: h11.Request, body: bytes, peer_id: str, registry: ServiceRegistry, options: ProviderOptions
+) -> tuple[int, dict[str, str], bytes]:
+ def plain(status: int, text: str) -> tuple[int, dict[str, str], bytes]:
+ return status, {"content-type": "text/plain; charset=utf-8"}, (text + "\n").encode()
+
+ target = request.target.decode("latin-1")
+ raw_path, _, query = target.partition("?")
+ # Policy is decided on the /<type>/<name> prefix; a dot segment in what
+ # follows could resolve to a sibling service on a shared backend.
+ if _has_dot_segment(raw_path):
+ return plain(400, "Invalid path")
+ parts = raw_path.lstrip("/").split("/")
+ if len(parts) < 2 or not parts[0] or not parts[1]:
+ return plain(400, "Invalid path")
+ service_type, service_name, rest = parts[0], parts[1], parts[2:]
+ if service_type not in ("inference", "a2a", "mcp"):
+ return plain(400, "Invalid service type")
+ upstream_path = "/".join(rest)
+
+ headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in request.headers}
+ biscuit_b64 = headers.get(HEADER_SAM_BISCUIT, "")
+ if not biscuit_b64:
+ return plain(401, "Missing X-Sam-Biscuit header")
+ try:
+ biscuit = base64.b64decode(biscuit_b64, validate=True)
+ if not biscuit:
+ raise ValueError("empty")
+ except (ValueError, TypeError):
+ return plain(400, "Invalid X-Sam-Biscuit encoding")
+
+ target_service = f"{service_type}://{service_name}"
+ try:
+ verified = await trio.to_thread.run_sync(
+ authorize_caller,
+ AuthorizeRequest(
+ biscuit=biscuit,
+ peer_id=peer_id,
+ target_service=target_service,
+ protocol=str(HTTP_PROTOCOL),
+ agent=headers.get(HEADER_SAM_AGENT, ""),
+ ),
+ options.authorizer,
+ )
+ except AuthorizationError as err:
+ logger.info("http ingress denied %s: %s", peer_id, err)
+ return plain(403, "Authorization failed")
+ if options.on_authorized:
+ options.on_authorized(peer_id, verified, target_service)
+
+ # Under the type the policy was evaluated on.
+ spec = registry.get(service_type, service_name)
+ if not isinstance(spec, HTTPService):
+ return plain(404, "Service not found")
+
+ # 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.
+ forwarded = {
+ k: v
+ for k, v in headers.items()
+ if k not in (HEADER_SAM_BISCUIT, HEADER_SAM_AGENT, HEADER_SAM_NO_TRAILING_SLASH, HEADER_PEER_ID, "host", "connection", "transfer-encoding", "content-length")
+ }
+ forwarded[HEADER_PEER_ID] = peer_id
+ if upstream_path == "" and not rest:
+ forwarded[HEADER_SAM_NO_TRAILING_SLASH] = "true"
+ method = request.method.decode()
+ path = "/" + upstream_path + (f"?{query}" if query else "")
+
+ if callable(spec.target):
+ response = await spec.target(HTTPRequest(method=method, path=path, headers=forwarded, body=body), verified)
+ return response.status, dict(response.headers), response.body
+
+ async with httpx.AsyncClient(timeout=_REQUEST_TIMEOUT, follow_redirects=False) as client:
+ upstream = await client.request(method, spec.target.rstrip("/") + path, headers=forwarded, content=body or None)
+ out_headers = {k: v for k, v in upstream.headers.items() if k.lower() not in ("content-length", "transfer-encoding", "connection")}
+ return upstream.status_code, out_headers, upstream.content
+
+
+async def http_request_over_stream(
+ host: IHost,
+ peer_id: ID,
+ biscuit: bytes,
+ target_service: str,
+ path: str,
+ *,
+ method: str = "GET",
+ headers: Optional[Mapping[str, str]] = None,
+ body: Union[bytes, str, None] = None,
+ agent: str = "",
+ timeout: float = _REQUEST_TIMEOUT,
+) -> HTTPResponse:
+ """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>."""
+ scheme, sep, name = target_service.partition("://")
+ if not sep or scheme not in ("inference", "a2a", "mcp") or not name:
+ raise ValueError(f"service target must look like inference://<name>, got {target_service!r}")
+ payload = body.encode() if isinstance(body, str) else (body or b"")
+ out = [(k.lower(), v) for k, v in (headers or {}).items() if k.lower() not in ("host", "content-length")]
+ out.append(("host", str(peer_id)))
+ out.append((HEADER_SAM_BISCUIT, base64.b64encode(biscuit).decode()))
+ if agent:
+ out.append((HEADER_SAM_AGENT, agent))
+ out.append(("content-length", str(len(payload))))
+
+ conn = h11.Connection(h11.CLIENT)
+ stream = await host.new_stream(peer_id, [HTTP_PROTOCOL])
+ try:
+ with trio.fail_after(timeout):
+ data = conn.send(h11.Request(method=method, target=f"/{scheme}/{name}" + (path if path.startswith("/") else "/" + path), headers=out)) or b""
+ data += conn.send(h11.Data(data=payload)) or b""
+ data += conn.send(h11.EndOfMessage()) or b""
+ await stream.write(data)
+
+ status = 0
+ resp_headers: dict[str, str] = {}
+ resp_body = bytearray()
+ while True:
+ event = conn.next_event()
+ if event is h11.NEED_DATA:
+ try:
+ chunk = await stream.read(_READ_CHUNK)
+ except Exception: # noqa: BLE001 - EOF ends the response
+ chunk = b""
+ conn.receive_data(chunk)
+ continue
+ if isinstance(event, (h11.Response, h11.InformationalResponse)):
+ if isinstance(event, h11.Response):
+ status = event.status_code
+ resp_headers = {k.decode("latin-1"): v.decode("latin-1") for k, v in event.headers}
+ elif isinstance(event, h11.Data):
+ resp_body.extend(event.data)
+ if len(resp_body) > _MAX_INGRESS_BODY_BYTES:
+ raise ValueError("response body too large")
+ elif isinstance(event, h11.EndOfMessage):
+ return HTTPResponse(status=status, headers=resp_headers, body=bytes(resp_body))
+ elif isinstance(event, (h11.ConnectionClosed, h11.PAUSED)):
+ if status:
+ return HTTPResponse(status=status, headers=resp_headers, body=bytes(resp_body))
+ raise ConnectionError(f"peer {peer_id} closed the stream before answering")
+ finally:
+ await stream.close()
+
+
+__all__: Sequence[str] = (
+ "HTTP_PROTOCOL",
+ "HTTPHandler",
+ "HTTPRequest",
+ "HTTPResponse",
+ "HTTPService",
+ "MCPService",
+ "ProviderOptions",
+ "ServiceRegistry",
+ "http_ingress_handler",
+ "http_request_over_stream",
+ "mcp_stream_handler",
+)
diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.py
index 1fa9b74b..fb8cfceb 100644
--- a/sdk/python/src/agent_mesh/session.py
+++ b/sdk/python/src/agent_mesh/session.py
@@ -29,12 +29,23 @@ from libp2p.peer.peerinfo import info_from_p2p_addr
from mcp import ClientSession
from ._proto import circuit_pb2 as circuit
-from .auth import AUTH_PROTOCOL, auth_stream_handler, authenticate_with_peer
+from .auth import AUTH_PROTOCOL, MCP_PROTOCOL, auth_stream_handler, authenticate_with_peer
+from .authorizer import ProviderAuthorizerOptions
from .biscuit import ROLE_ROUTER, VerifiedBiscuit, require_role
-from .discovery import DiscoveredProvider, ServiceType, find_providers, service_key
+from .discovery import DiscoveredProvider, ServiceType, find_providers, provide, service_key
from .host import create_mesh_host
from .mcp_client import ToolCallResult, open_mcp_session, tool_call_result
from .relay import STOP_PROTOCOL, dial_through_relay, reserve_relay, split_circuit_address, stop_stream_handler
+from .serve import (
+ HTTP_PROTOCOL,
+ HTTPResponse,
+ ProviderOptions,
+ ServiceRegistry,
+ ServiceSpec,
+ http_ingress_handler,
+ http_request_over_stream,
+ mcp_stream_handler,
+)
if TYPE_CHECKING:
from .mesh import AgentMesh
@@ -44,6 +55,10 @@ logger = logging.getLogger("agent_mesh")
DEFAULT_REFRESH_LEAD = 60 * 60.0
DEFAULT_REFRESH_RETRY = 30.0
MIN_REFRESH_DELAY = 2.0
+# sam-node's --control-plane-sync-interval default.
+DEFAULT_POLICY_SYNC = 15 * 60.0
+# How often provider records are refreshed; go-libp2p-kad-dht expires them after 48h.
+DEFAULT_PROVIDE_INTERVAL = 10 * 60.0
@dataclass(frozen=True)
@@ -65,6 +80,13 @@ class MeshSession:
routers: list[AdmittedRouter]
# Peers that passed the inbound auth handshake, with their credential's expiration.
authenticated_peers: dict[str, datetime] = field(default_factory=dict)
+ # The services this member publishes.
+ services: ServiceRegistry = field(default_factory=ServiceRegistry)
+ policy_sync_interval: float = DEFAULT_POLICY_SYNC
+ provide_interval: float = DEFAULT_PROVIDE_INTERVAL
+ _nursery: Optional[trio.Nursery] = field(default=None, repr=False)
+ _policy_rules: Optional[list[str]] = field(default=None, repr=False)
+ _serving: bool = field(default=False, repr=False)
@property
def peer_id(self) -> str:
@@ -154,6 +176,98 @@ class MeshSession:
raise RuntimeError(f"tool {tool} answered with {type(result).__name__}, not a result")
return tool_call_result(result) # type: ignore[arg-type]
+ @property
+ def policy_rules(self) -> list[str]:
+ """The mesh policy rules this member evaluates for callers, as the
+ control plane rendered them (PolicyConfigGetResponse.datalog_rules).
+ Empty until the first serve() or sync_policy()."""
+ return list(self._policy_rules or [])
+
+ async def sync_policy(self) -> None:
+ """Re-reads the mesh policy from the control plane."""
+ self._policy_rules = await trio.to_thread.run_sync(self.mesh.control_plane.policy_rules, self.mesh.credential.biscuit)
+
+ async def request(
+ self,
+ addr: str | multiaddr.Multiaddr,
+ target_service: str,
+ path: str,
+ *,
+ method: str = "GET",
+ headers: Optional[Mapping[str, str]] = None,
+ body: bytes | str | None = None,
+ agent: str = "",
+ ) -> HTTPResponse:
+ """Calls an inference or A2A service on a provider over /libp2p-http,
+ the way sam-node's egress proxy does for /sam/<peer>/<type>/<name>/<path>."""
+ peer_id = await self.connect(addr)
+ return await http_request_over_stream(
+ self.host, peer_id, self.mesh.credential.biscuit, target_service, path, method=method, headers=headers, body=body, agent=agent
+ )
+
+ async def serve(self, spec: ServiceSpec) -> None:
+ """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."""
+ if not self._serving:
+ await self.sync_policy()
+ options = ProviderOptions(
+ authorizer=ProviderAuthorizerOptions(
+ trusted_keys=lambda: self.mesh.credential.control_plane_keys,
+ own_biscuit=lambda: self.mesh.credential.biscuit,
+ policy_rules=lambda: self._policy_rules or [],
+ ),
+ own_biscuit=lambda: self.mesh.credential.biscuit,
+ on_authorized=lambda peer, verified, _target: self.authenticated_peers.__setitem__(peer, verified.expiration),
+ )
+ self.host.set_stream_handler(MCP_PROTOCOL, mcp_stream_handler(self.services, options, str(MCP_PROTOCOL)))
+ self.host.set_stream_handler(HTTP_PROTOCOL, http_ingress_handler(self.services, options))
+ if self._nursery is not None:
+ self._nursery.start_soon(self._policy_loop)
+ self._nursery.start_soon(self._provide_loop)
+ self._serving = True
+ self.services.add(spec)
+ await self._provide(spec.type, spec.name)
+ try:
+ await self.report_catalog()
+ except Exception as err: # noqa: BLE001 - the catalog is display only
+ logger.warning("catalog report failed: %s", err)
+
+ async def provide_all(self) -> None:
+ """Announces every registered service in the DHT again."""
+ for service_type, name, _ in self.services.list():
+ await self._provide(service_type, name) # type: ignore[arg-type]
+
+ async def _provide(self, service_type: ServiceType, name: str) -> None:
+ # Once for the type and once for the name, as sam-node announces.
+ seeds = [ID.from_base58(r.peer_id) for r in self.routers]
+ addrs = [multiaddr.Multiaddr(a) for a in self.relay_addresses] + list(self.host.get_addrs())
+ for key in (service_key(service_type), service_key(service_type, name)):
+ await provide(self.host, key, seeds, addrs)
+
+ async def report_catalog(self) -> None:
+ """Reports the published services to the control plane's catalog (display only)."""
+ await trio.to_thread.run_sync(self.mesh.control_plane.report_catalog, self.mesh.credential.biscuit, self.services.list())
+
+ async def _policy_loop(self) -> None:
+ while True:
+ await trio.sleep(self.policy_sync_interval)
+ try:
+ await self.sync_policy()
+ except Exception as err: # noqa: BLE001 - the last good policy stays in force
+ logger.warning("mesh policy sync failed: %s", err)
+
+ async def _provide_loop(self) -> None:
+ while True:
+ await trio.sleep(self.provide_interval)
+ try:
+ await self.provide_all()
+ except Exception as err: # noqa: BLE001
+ logger.warning("dht reprovide failed: %s", err)
+
async def _refresh_loop(mesh: "AgentMesh", lead: float, retry: float) -> None:
while True:
@@ -183,6 +297,8 @@ async def join_mesh(
reserve: bool = True,
refresh_lead: float = DEFAULT_REFRESH_LEAD,
refresh_retry: float = DEFAULT_REFRESH_RETRY,
+ policy_sync_interval: float = DEFAULT_POLICY_SYNC,
+ provide_interval: float = DEFAULT_PROVIDE_INTERVAL,
) -> AsyncIterator[MeshSession]:
"""Implements AgentMesh.join(); lives here to keep mesh.py free of libp2p."""
router_addrs = [multiaddr.Multiaddr(a) for a in mesh.credential.router_addresses]
@@ -207,7 +323,15 @@ async def join_mesh(
async with trio.open_nursery() as nursery:
nursery.start_soon(_refresh_loop, mesh, refresh_lead, refresh_retry)
try:
- yield MeshSession(mesh=mesh, host=host, routers=admitted, authenticated_peers=authenticated)
+ yield MeshSession(
+ mesh=mesh,
+ host=host,
+ routers=admitted,
+ authenticated_peers=authenticated,
+ policy_sync_interval=policy_sync_interval,
+ provide_interval=provide_interval,
+ _nursery=nursery,
+ )
finally:
nursery.cancel_scope.cancel()
except BaseExceptionGroup as group:
diff --git a/sdk/python/tests/test_authorizer.py b/sdk/python/tests/test_authorizer.py
new file mode 100644
index 00000000..bbd988dd
--- /dev/null
+++ b/sdk/python/tests/test_authorizer.py
@@ -0,0 +1,145 @@
+# 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 authorizer against tokens minted the way the control plane
+mints them and policy rules rendered the way it renders them. The decisions
+here are the ones internal/node/middleware_test.go pins."""
+
+import biscuit_auth as ba
+import pytest
+
+from agent_mesh.authorizer import BASELINE_DATALOG, AuthorizationError, AuthorizeRequest, ProviderAuthorizerOptions, authorize_caller
+
+from .test_session import CP, CP_KEY
+
+OTHER = ba.KeyPair()
+PROVIDER = "12D3KooWProvider00000000000000000000000000000000000"
+CALLER = "12D3KooWCaller0000000000000000000000000000000000000"
+
+# The role grants the service through the mesh policy rules, exactly as the
+# control plane renders them; the token itself carries only the role.
+NODE_ROLE_GRANTS = [
+ 'granted_service_set("mcp", ["calc"]) <- role("sam:role:node")',
+ 'target_unrestricted(true) <- role("sam:role:node")',
+]
+
+
+def mint(facts: list[str], key: ba.KeyPair = CP, expiration: str = "2035-01-01T00:00:00Z") -> bytes:
+ return ba.BiscuitBuilder(f"expiration({expiration}); " + " ".join(f + ";" for f in facts)).build(key.private_key).to_bytes()
+
+
+def node_token(peer_id: str, extra: list[str] | None = None, key: ba.KeyPair = CP) -> bytes:
+ """A token as the control plane mints it for a node bound to peer_id."""
+ return mint([f'node("{peer_id}")', f'client_peer_id("{peer_id}")', 'role("sam:role:node")', *(extra or [])], key)
+
+
+def options(policy_rules: list[str], own_biscuit: bytes | None = None) -> ProviderAuthorizerOptions:
+ own = own_biscuit or node_token(PROVIDER, ["granted_service_all_types(true)", "target_unrestricted(true)"])
+ return ProviderAuthorizerOptions(trusted_keys=lambda: [CP_KEY], own_biscuit=lambda: own, policy_rules=lambda: policy_rules)
+
+
+def request(biscuit: bytes, target_service: str = "mcp://calc", agent: str = "") -> AuthorizeRequest:
+ return AuthorizeRequest(biscuit=biscuit, peer_id=CALLER, target_service=target_service, protocol="/sam/mcp/1.0.0", agent=agent)
+
+
+def test_role_granted_by_mesh_policy_is_allowed():
+ verified = authorize_caller(request(node_token(CALLER)), options(NODE_ROLE_GRANTS))
+ assert verified.peer_id == CALLER
+ assert verified.roles == ["sam:role:node"]
+
+
+def test_grants_minted_into_the_token_are_enough():
+ token = node_token(CALLER, ['granted_service_exact("mcp", "calc")', "target_unrestricted(true)"])
+ authorize_caller(request(token), options([]))
+
+
+def test_empty_target_is_the_protocol_in_the_system_namespace():
+ token = node_token(CALLER, ['granted_service_all("sam:system")', "target_unrestricted(true)"])
+ authorize_caller(request(token, ""), options([]))
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(token, "mcp://calc"), options([]))
+
+
+def test_ungranted_service_is_denied():
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(node_token(CALLER), "mcp://other"), options(NODE_ROLE_GRANTS))
+
+
+def test_role_with_no_grants_is_denied():
+ guest = mint([f'node("{CALLER}")', f'client_peer_id("{CALLER}")', 'role("sam:role:guest")'])
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(guest), options(NODE_ROLE_GRANTS))
+
+
+def test_token_presented_by_another_peer_is_denied():
+ stolen = node_token("12D3KooWVictim000000000000000000000000000000000000", ["granted_service_all_types(true)", "target_unrestricted(true)"])
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(stolen), options([]))
+
+
+def test_client_peer_id_must_match_the_connection_peer():
+ token = mint(
+ [
+ f'node("{CALLER}")',
+ 'client_peer_id("12D3KooWSomeoneElse000000000000000000000000000000")',
+ "granted_service_all_types(true)",
+ "target_unrestricted(true)",
+ ]
+ )
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(token), options([]))
+
+
+def test_expired_token_is_denied():
+ token = mint(
+ [f'node("{CALLER}")', f'client_peer_id("{CALLER}")', "granted_service_all_types(true)", "target_unrestricted(true)"],
+ expiration="2020-01-01T00:00:00Z",
+ )
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(token), options([]))
+
+
+def test_untrusted_key_is_denied():
+ token = node_token(CALLER, ["granted_service_all_types(true)", "target_unrestricted(true)"], key=OTHER)
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(token), options([]))
+
+
+def test_target_grants_match_the_providers_own_identity():
+ provider = node_token(PROVIDER, ['group("backend")'])
+ rules = ['granted_service_all_types(true) <- role("sam:role:node")', 'target_restricted(true) <- role("sam:role:node")']
+ authorize_caller(request(node_token(CALLER, ['granted_target_set("group", ["backend"])'])), options(rules, provider))
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(node_token(CALLER, ['granted_target_set("group", ["frontend"])'])), options(rules, provider))
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(node_token(CALLER)), options(rules, provider))
+
+
+def test_agent_claim_only_inside_a_granted_namespace():
+ rules = [*NODE_ROLE_GRANTS, 'granted_agent_suffix(".acme.example") <- role("sam:role:node")']
+ authorize_caller(request(node_token(CALLER), agent="reviewer.acme.example"), options(rules))
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(node_token(CALLER), agent="reviewer.evil.example"), options(rules))
+ with pytest.raises(AuthorizationError):
+ authorize_caller(request(node_token(CALLER), agent="reviewer.acme.example"), options(NODE_ROLE_GRANTS))
+ authorize_caller(request(node_token(CALLER)), options(NODE_ROLE_GRANTS))
+
+
+def test_every_baseline_item_parses_in_biscuit_python():
+ for c in (BASELINE_DATALOG["time_check"], BASELINE_DATALOG["replay_check"], BASELINE_DATALOG["target_check"], BASELINE_DATALOG["agent_check"]):
+ ba.Check(c)
+ for r in BASELINE_DATALOG["rules"] + BASELINE_DATALOG["agent_rules"] + BASELINE_DATALOG["target_fact_rules"]:
+ ba.Rule(r)
+ for p in BASELINE_DATALOG["policies"] + [BASELINE_DATALOG["allow_if_true"]]:
+ ba.Policy(p)
diff --git a/sdk/python/tests/test_serve.py b/sdk/python/tests/test_serve.py
new file mode 100644
index 00000000..ddbbadce
--- /dev/null
+++ b/sdk/python/tests/test_serve.py
@@ -0,0 +1,212 @@
+# 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 py-libp2p host, called with this SDK's clients.
+The real sam-node as a caller is exercised by tests/integration."""
+
+import json
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import biscuit_auth as ba
+import multiaddr
+import pytest
+import trio
+from libp2p.peer.peerinfo import info_from_p2p_addr
+from mcp.server.mcpserver import MCPServer
+
+from agent_mesh._proto import sam_pb2 as pb
+from agent_mesh.auth import MCP_PROTOCOL, AuthRejectedError
+from agent_mesh.authorizer import ProviderAuthorizerOptions
+from agent_mesh.controlplane import ROLE_NODE
+from agent_mesh.identity import Identity
+from agent_mesh.mcp_client import open_mcp_session, tool_call_result
+from agent_mesh.serve import (
+ HTTP_PROTOCOL,
+ HTTPRequest,
+ HTTPResponse,
+ HTTPService,
+ MCPService,
+ ProviderOptions,
+ ServiceRegistry,
+ http_ingress_handler,
+ http_request_over_stream,
+ mcp_stream_handler,
+)
+
+from .test_session import CP, CP_KEY, libp2p_host
+
+# What the control plane renders for a policy granting the node role calc,
+# echo and every inference service on any target.
+POLICY_RULES = [
+ 'granted_service_set("mcp", ["calc", "echo"]) <- 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")',
+]
+
+
+def mint(peer_id: str, role: str) -> bytes:
+ return ba.BiscuitBuilder(
+ "node({p}); client_peer_id({p}); expiration(2035-01-01T00:00:00Z); role({r});", {"p": peer_id, "r": role}
+ ).build(CP.private_key).to_bytes()
+
+
+def calc_server() -> MCPServer:
+ server = MCPServer("calc")
+
+ @server.tool()
+ def add(a: int, b: int) -> str:
+ return str(a + b)
+
+ return server
+
+
+class FakeBackend(BaseHTTPRequestHandler):
+ seen: list[dict] = []
+
+ def _answer(self) -> None:
+ length = int(self.headers.get("content-length") or 0)
+ body = self.rfile.read(length) if length else b""
+ FakeBackend.seen.append({"method": self.command, "path": self.path, "peer": self.headers.get("x-peer-id"), "body": body.decode(), "biscuit": self.headers.get("x-sam-biscuit")})
+ payload = json.dumps({"path": self.path, "echo": body.decode()}).encode()
+ self.send_response(200)
+ self.send_header("content-type", "application/json")
+ self.send_header("x-backend", "fake")
+ self.send_header("content-length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ do_GET = _answer
+ do_POST = _answer
+
+ def log_message(self, *_args) -> None: # noqa: D102 - quiet
+ pass
+
+
[email protected](scope="module")
+def backend_url():
+ server = ThreadingHTTPServer(("127.0.0.1", 0), FakeBackend)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ yield f"http://127.0.0.1:{server.server_port}"
+ server.shutdown()
+
+
+async def start_provider(nursery, backend_url: str, authorized: list[str]):
+ identity = Identity.generate()
+ host = libp2p_host(identity)
+ biscuit = mint(identity.peer_id, ROLE_NODE)
+ registry = ServiceRegistry()
+ registry.add(MCPService(name="calc", create_server=calc_server))
+ registry.add(HTTPService(type="inference", name="llm", target=backend_url))
+
+ async def inproc(request: HTTPRequest, caller) -> HTTPResponse:
+ return HTTPResponse(status=201, body=f"hello {caller.peer_id} {request.method} {request.path}".encode())
+
+ registry.add(HTTPService(type="inference", name="inproc", target=inproc))
+ options = ProviderOptions(
+ authorizer=ProviderAuthorizerOptions(trusted_keys=lambda: [CP_KEY], own_biscuit=lambda: biscuit, policy_rules=lambda: POLICY_RULES),
+ own_biscuit=lambda: biscuit,
+ on_authorized=lambda peer, _v, target: authorized.append(f"{peer} {target}"),
+ )
+ host.set_stream_handler(MCP_PROTOCOL, mcp_stream_handler(registry, options, str(MCP_PROTOCOL)))
+ host.set_stream_handler(HTTP_PROTOCOL, http_ingress_handler(registry, options))
+ started = trio.Event()
+ addr_box = []
+
+ async def run():
+ async with host.run(listen_addrs=[multiaddr.Multiaddr("/ip4/127.0.0.1/tcp/0")]):
+ addr_box.append(multiaddr.Multiaddr(f"{host.get_addrs()[0]}"))
+ started.set()
+ await trio.sleep_forever()
+
+ nursery.start_soon(run)
+ await started.wait()
+ return host, addr_box[0]
+
+
+def frame(biscuit: bytes, target: str) -> bytes:
+ return pb.AuthFrame(biscuit=biscuit, target_service=target).SerializeToString()
+
+
+def test_services_are_served_to_authorized_callers(backend_url):
+ authorized: list[str] = []
+
+ async def main():
+ async with trio.open_nursery() as nursery:
+ provider, addr = await start_provider(nursery, backend_url, authorized)
+ caller_identity = Identity.generate()
+ caller = libp2p_host(caller_identity)
+ caller_biscuit = mint(caller_identity.peer_id, ROLE_NODE)
+ guest_biscuit = mint(caller_identity.peer_id, "sam:role:guest")
+ async with caller.run(listen_addrs=[]):
+ await caller.connect(info_from_p2p_addr(addr))
+ pid = provider.get_id()
+
+ # An MCP service, then the member's own catalog.
+ async with open_mcp_session(caller, pid, frame(caller_biscuit, "mcp://calc"), [CP_KEY]) as (mcp, verified):
+ assert verified.peer_id == str(pid)
+ assert [t.name for t in (await mcp.list_tools()).tools] == ["add"]
+ assert tool_call_result(await mcp.call_tool("add", {"a": 2, "b": 3})).text == ["5"]
+ assert f"{caller_identity.peer_id} mcp://calc" in authorized
+ async with open_mcp_session(caller, pid, frame(caller_biscuit, ""), [CP_KEY]) as (mcp, _):
+ listed = json.loads(tool_call_result(await mcp.call_tool("list_local_services", {})).text[0])
+ assert sorted(f"{s['type']}://{s['name']}" for s in listed) == ["inference://inproc", "inference://llm", "mcp://calc"]
+
+ # A role that grants nothing is refused at the AuthResponse.
+ with pytest.raises(AuthRejectedError, match="not authorized"):
+ async with open_mcp_session(caller, pid, frame(guest_biscuit, "mcp://calc"), [CP_KEY]):
+ pass
+ # A service the role was not granted, likewise.
+ with pytest.raises(AuthRejectedError):
+ async with open_mcp_session(caller, pid, frame(caller_biscuit, "mcp://secret"), [CP_KEY]):
+ pass
+ # Granted but not registered: success, then the stream closes.
+ with pytest.raises(Exception): # noqa: B017 - the MCP initialize fails on the closed stream
+ async with open_mcp_session(caller, pid, frame(caller_biscuit, "mcp://echo"), [CP_KEY]):
+ pass
+
+ # An inference service is proxied with the caller's identity and without its biscuit.
+ res = await http_request_over_stream(caller, pid, caller_biscuit, "inference://llm", "/v1/models?x=1", headers={"x-sam-biscuit": "spoof"})
+ assert res.status == 200
+ assert res.headers.get("x-backend") == "fake"
+ assert res.json() == {"path": "/v1/models?x=1", "echo": ""}
+ assert FakeBackend.seen[-1]["peer"] == caller_identity.peer_id
+ assert FakeBackend.seen[-1]["biscuit"] is None
+ post = await http_request_over_stream(
+ caller, pid, caller_biscuit, "inference://llm", "/v1/chat/completions", method="POST", headers={"content-type": "application/json"}, body='{"model": "m"}'
+ )
+ assert post.status == 200 and post.json()["echo"] == '{"model": "m"}'
+
+ # An in-process handler sees the verified caller.
+ res = await http_request_over_stream(caller, pid, caller_biscuit, "inference://inproc", "/agent/card")
+ assert res.status == 201 and res.text == f"hello {caller_identity.peer_id} GET /agent/card"
+
+ # What the policy does not grant is refused before the backend is reached.
+ before = len(FakeBackend.seen)
+ assert (await http_request_over_stream(caller, pid, guest_biscuit, "inference://llm", "/v1/models")).status == 403
+ assert (await http_request_over_stream(caller, pid, caller_biscuit, "a2a://llm", "/")).status == 403
+ assert len(FakeBackend.seen) == before
+ assert (await http_request_over_stream(caller, pid, caller_biscuit, "inference://nope", "/")).status == 404
+ assert (await http_request_over_stream(caller, pid, b"", "inference://llm", "/v1/models")).status == 401
+ assert (await http_request_over_stream(caller, pid, caller_biscuit, "inference://llm", "/../other/x")).status == 400
+ nursery.cancel_scope.cancel()
+
+ async def with_timeout():
+ with trio.fail_after(30):
+ await main()
+
+ trio.run(with_timeout)
diff --git a/tests/integration/sdk_mesh_test.go b/tests/integration/sdk_mesh_test.go
index 7dcc2f17..8615336d 100644
--- a/tests/integration/sdk_mesh_test.go
+++ b/tests/integration/sdk_mesh_test.go
@@ -24,6 +24,7 @@ import (
"fmt"
"io"
"net"
+ "net/http"
"net/http/httptest"
"os"
"os/exec"
@@ -38,6 +39,7 @@ import (
"github.com/google/sam/internal/identity"
"github.com/google/sam/internal/storage"
"github.com/libp2p/go-libp2p"
+ libp2phttp "github.com/libp2p/go-libp2p-http"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
@@ -128,8 +130,13 @@ var sdkMemberLaunchers = []sdkRunner{
// credential gets no answer. Then each SDK member discovers the sam-node's
// service in the DHT, lists and calls its tools over /sam/mcp/1.0.0 through
// the router, reads the node's own catalog, and is refused a service the
-// node does not have. Any SDK whose toolchain is missing is skipped, and
-// the matrix shrinks to the members present.
+// node does not have. Then each SDK member publishes an MCP service and an
+// inference service of its own: the sam-node discovers and calls both
+// (call_remote_tool, and the egress proxy for /sam/<peer>/inference/...),
+// the other SDK member does the same over the mesh, and a Go peer holding a
+// role the policy grants nothing is refused at the AuthResponse. Any SDK
+// whose toolchain is missing is skipped, and the matrix shrinks to the
+// members present.
func TestNativeSDKsMesh(t *testing.T) {
root := repoRoot(t)
oidcURL, mintToken := startCustomMockOIDC(t)
@@ -323,6 +330,102 @@ bindings:
})
}
+ // Every SDK member becomes a provider: an MCP service with an echo tool
+ // and an inference service, both served in the runner's process. The
+ // policy rules it evaluates are the ones the control plane renders.
+ for _, m := range members {
+ m.serve(t, "mcp", "echo-"+m.name)
+ m.serve(t, "inference", "llm-"+m.name)
+ }
+ guest := newGuestGoPeer(t, ctx, cpPriv, routerAddr)
+ for _, m := range members {
+ m := m
+ t.Run(m.name+"-serves", func(t *testing.T) {
+ mcpService := "mcp://echo-" + m.name
+ inferenceService := "inference://llm-" + m.name
+ sdkPeer, _ := peer.Decode(m.report.PeerID)
+
+ // sam-node -> SDK tool, through the router, as an agent behind the
+ // node would with call_remote_tool.
+ answer, err := callMCPAllowError(t, nodeAPI, "node-token", "call_remote_tool", map[string]any{
+ "peer_id": m.report.PeerID,
+ "tool_name": mcpService + "/echo",
+ "arguments": map[string]any{"text": "from-node"},
+ })
+ if err != nil || !strings.Contains(answer, m.name+":from-node") {
+ t.Fatalf("sam-node calling echo on %s: answer %q, err %v", m.name, answer, err)
+ }
+
+ // sam-node -> SDK inference, through the egress proxy: the node
+ // verifies the member's credential, then the member authorizes the
+ // node's and answers with who called.
+ status, body := egressGet(t, nodeAPI, "node-token", "/sam/"+m.report.PeerID+"/inference/llm-"+m.name+"/v1/models")
+ if status != 200 {
+ t.Fatalf("sam-node egress to %s inference: status %d, body %s", m.name, status, body)
+ }
+ var seen struct {
+ SDK string `json:"sdk"`
+ Peer string `json:"peer"`
+ Path string `json:"path"`
+ }
+ if json.Unmarshal([]byte(body), &seen) != nil || seen.SDK != m.name || seen.Peer != samNode.peerID.String() || seen.Path != "/v1/models" {
+ t.Fatalf("sam-node egress to %s inference answered %s", m.name, body)
+ }
+
+ // SDK -> SDK: the other member finds the service in the DHT and
+ // calls both the tool and the inference endpoint through the router.
+ for _, other := range members {
+ if other == m {
+ continue
+ }
+ other.discoverUntil(t, "mcp", "echo-"+m.name, m.report.PeerID, 20*time.Second)
+ if tools := other.tools(t, m.report.RelayAddresses[0], mcpService); !contains(tools, "echo") {
+ t.Fatalf("%s listed %v on %s of %s, want echo", other.name, tools, mcpService, m.name)
+ }
+ if res := other.call(t, m.report.RelayAddresses[0], mcpService, "echo", map[string]any{"text": "from-" + other.name}); res.IsError || !contains(res.Text, m.name+":from-"+other.name) {
+ t.Fatalf("%s calling echo on %s: %+v", other.name, m.name, res)
+ }
+ res := other.http(t, m.report.RelayAddresses[0], inferenceService, "/v1/models")
+ if res.Status != 200 || !strings.Contains(res.Body, other.report.PeerID) {
+ t.Fatalf("%s calling %s on %s: %+v", other.name, inferenceService, m.name, res)
+ }
+ // The member's catalog lists what it publishes.
+ if r := other.call(t, m.report.RelayAddresses[0], "", "list_local_services", nil); r.IsError || !strings.Contains(strings.Join(r.Text, "\n"), "echo-"+m.name) {
+ t.Fatalf("%s reading %s's catalog: %+v", other.name, m.name, r)
+ }
+ // A service the member does not publish, but the policy grants:
+ // authorized, then the stream is closed, as sam-node does.
+ if r := other.callRaw(t, m.report.RelayAddresses[0], "mcp://not-served", "echo", nil); r.OK {
+ t.Fatalf("%s called a service %s does not serve: %+v", other.name, m.name, r)
+ }
+ if r := other.http(t, m.report.RelayAddresses[0], "inference://not-served", "/"); r.Status != 404 {
+ t.Fatalf("%s calling an inference service %s does not serve: %+v", other.name, m.name, r)
+ }
+ }
+
+ // A peer the control plane vouches for, but whose role the policy
+ // grants nothing, is refused at the AuthResponse with a reason, and
+ // with 403 on the HTTP path.
+ dialCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ if err := guest.Connect(dialCtx, peer.AddrInfo{ID: sdkPeer, Addrs: []multiaddr.Multiaddr{multiaddr.StringCast(m.report.RelayAddresses[0])}}); err != nil {
+ t.Fatalf("guest peer could not reach %s: %v", m.name, err)
+ }
+ guestBiscuit := guestHostBiscuit(t, cpPriv, guest.ID())
+ resp := mcpHandshake(t, ctx, guest, sdkPeer, guestBiscuit, mcpService)
+ if resp.Success || !strings.Contains(resp.Error, "not authorized") {
+ t.Fatalf("%s answered a guest's request for %s with %+v, want a refusal", m.name, mcpService, resp)
+ }
+ if status, _ := libp2pHTTPGet(t, ctx, guest, sdkPeer, guestBiscuit, "/inference/llm-"+m.name+"/v1/models"); status != 403 {
+ t.Fatalf("%s answered a guest's HTTP request with %d, want 403", m.name, status)
+ }
+ // The same peer with a node-role token is served: the refusal was the policy, not the peer.
+ if status, body := libp2pHTTPGet(t, ctx, guest, sdkPeer, goHostBiscuit(t, cpPriv, guest.ID()), "/inference/llm-"+m.name+"/v1/models"); status != 200 || !strings.Contains(body, guest.ID().String()) {
+ t.Fatalf("%s answered a node-role HTTP request with %d %s", m.name, status, body)
+ }
+ })
+ }
+
// Everyone who ran the handshake against a member is in its admitted set.
for _, m := range members {
peers := m.peers(t)
@@ -532,6 +635,46 @@ func (m *sdkMember) call(t *testing.T, addr, service, tool string, args map[stri
return res
}
+// serve asks the member to publish a service served in its own process.
+func (m *sdkMember) serve(t *testing.T, serviceType, name string) {
+ t.Helper()
+ var res struct {
+ OK bool `json:"ok"`
+ Error string `json:"error"`
+ Services []string `json:"services"`
+ }
+ if line := m.send(t, map[string]string{"cmd": "serve", "type": serviceType, "name": name}); json.Unmarshal(line, &res) != nil {
+ t.Fatalf("%s member: serve answered %q", m.name, line)
+ }
+ if !res.OK {
+ t.Fatalf("%s member could not serve %s://%s: %s", m.name, serviceType, name, res.Error)
+ }
+ if !contains(res.Services, serviceType+"://"+name) {
+ t.Fatalf("%s member serves %v after publishing %s://%s", m.name, res.Services, serviceType, name)
+ }
+}
+
+// sdkHTTPResult answers an {"cmd":"http"} command.
+type sdkHTTPResult struct {
+ OK bool `json:"ok"`
+ Error string `json:"error"`
+ Status int `json:"status"`
+ Body string `json:"body"`
+}
+
+// http asks the member to call an inference or A2A service over /libp2p-http.
+func (m *sdkMember) http(t *testing.T, addr, service, path string) sdkHTTPResult {
+ t.Helper()
+ var res sdkHTTPResult
+ if line := m.send(t, map[string]string{"cmd": "http", "addr": addr, "service": service, "path": path}); json.Unmarshal(line, &res) != nil {
+ t.Fatalf("%s member: http answered %q", m.name, line)
+ }
+ if !res.OK {
+ t.Fatalf("%s member could not call %s%s at %s: %s", m.name, service, path, addr, res.Error)
+ }
+ return res
+}
+
func (m *sdkMember) quit(t *testing.T) {
t.Helper()
m.send(t, map[string]string{"cmd": "quit"})
@@ -620,6 +763,87 @@ func goHostBiscuit(t *testing.T, cpPriv ed25519.PrivateKey, id peer.ID) []byte {
return b
}
+// guestHostBiscuit is a valid control plane credential for a role the mesh
+// policy does not know, so it grants nothing anywhere.
+func guestHostBiscuit(t *testing.T, cpPriv ed25519.PrivateKey, id peer.ID) []byte {
+ t.Helper()
+ b, err := identity.MintBootstrapBiscuitToken(cpPriv, id, "sam:role:guest", time.Now().Add(time.Hour), nil, nil)
+ if err != nil {
+ t.Fatalf("failed to mint guest biscuit for %s: %v", id, err)
+ }
+ return b
+}
+
+// newGuestGoPeer is a Go peer admitted by the router with a node-role token;
+// what it presents to providers is chosen per request.
+func newGuestGoPeer(t *testing.T, ctx context.Context, cpPriv ed25519.PrivateKey, routerAddr string) host.Host {
+ t.Helper()
+ return newAdmittedGoPeer(t, ctx, cpPriv, routerAddr)
+}
+
+// mcpHandshake opens /sam/mcp/1.0.0 to target for targetService and returns
+// the provider's answer, as sam-node's ConnectMCPSession reads it.
+func mcpHandshake(t *testing.T, ctx context.Context, h host.Host, target peer.ID, biscuit []byte, targetService string) *api.AuthResponse {
+ t.Helper()
+ streamCtx, cancel := context.WithTimeout(network.WithAllowLimitedConn(ctx, "mcp"), 10*time.Second)
+ defer cancel()
+ s, err := h.NewStream(streamCtx, target, api.MCPProtocolID)
+ if err != nil {
+ t.Fatalf("open mcp stream to %s: %v", target, err)
+ }
+ defer func() { _ = s.Close() }()
+ _ = s.SetDeadline(time.Now().Add(10 * time.Second))
+ frame, _ := proto.Marshal(&api.AuthFrame{Biscuit: biscuit, TargetService: targetService})
+ if err := msgio.NewVarintWriter(s).WriteMsg(frame); err != nil {
+ t.Fatalf("write mcp auth frame to %s: %v", target, err)
+ }
+ msg, err := msgio.NewVarintReaderSize(s, 64*1024).ReadMsg()
+ if err != nil {
+ t.Fatalf("read mcp auth response from %s: %v", target, err)
+ }
+ var resp api.AuthResponse
+ if err := proto.Unmarshal(msg, &resp); err != nil {
+ t.Fatalf("mcp auth response from %s: %v", target, err)
+ }
+ return &resp
+}
+
+// libp2pHTTPGet is one GET over /libp2p-http with the biscuit in
+// X-Sam-Biscuit, the way sam-node's egress proxy sends it.
+func libp2pHTTPGet(t *testing.T, ctx context.Context, h host.Host, target peer.ID, biscuit []byte, path string) (int, string) {
+ t.Helper()
+ client := &http.Client{Transport: libp2phttp.NewTransport(h), Timeout: 15 * time.Second}
+ req, err := http.NewRequestWithContext(network.WithAllowLimitedConn(ctx, "http"), http.MethodGet, "libp2p://"+target.String()+path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set(api.HeaderSamBiscuit, base64.StdEncoding.EncodeToString(biscuit))
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("GET %s on %s: %v", path, target, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, string(body)
+}
+
+// egressGet is a GET through sam-node's egress proxy with the node API token.
+func egressGet(t *testing.T, apiAddr, token, path string) (int, string) {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodGet, "http://"+apiAddr+path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)
+ resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
+ if err != nil {
+ t.Fatalf("GET %s through the sidecar: %v", path, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, string(body)
+}
+
// authHandshake runs the client side of /sam/auth/1.0.0 against target and
// returns the credential target answers with.
func authHandshake(t *testing.T, ctx context.Context, h host.Host, target peer.ID, biscuit []byte) []byte {