Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions internal/webapp/public/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -377,9 +377,15 @@ async function forget(keepIdentity, send) {
}
}

/** @returns {import("./model.js").Stats} */
/**
* Peers are the members this page has a connection open to, the routers left out. Routers stays the SDK's
* admitted set, which drops a router only after its redials: ROUTER_LOSS_GRACE_MS is timed on that.
* @returns {import("./model.js").Stats}
*/
function statsOf(joined) {
return { peers: joined.node.getPeers().length, routers: joined.routers.length, expires: joined.mesh.credential.expiration };
const routerIds = new Set(joined.routers.map((r) => r.peerId));
const members = joined.node.getPeers().filter((id) => !routerIds.has(id.toString())).length;
return { peers: members, routers: joined.routers.length, expires: joined.mesh.credential.expiration };
}

function wait(ms, signal) {
Expand Down
3 changes: 2 additions & 1 deletion internal/webapp/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,9 @@ <h2 id="node-title" class="node-title" aria-live="polite"></h2>
</div>
<div class="details">
<div class="card stats">
<h3>Connections</h3>
<div class="stat">
<span class="stat-head"><svg class="icon"><use href="#i-people"/></svg>Connected Peers</span>
<span class="stat-head"><svg class="icon"><use href="#i-people"/></svg>Peers</span>
<span id="stat-peers" class="stat-value">–</span>
</div>
<div class="stat">
Expand Down
2 changes: 2 additions & 0 deletions internal/webapp/public/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ section:not([hidden]) { animation: rise 0.28s cubic-bezier(0.2, 0.8, 0.2, 1); }

/* Stats, Node ID and the danger zone */
.stats { display: grid; grid-template-columns: 1fr 1fr; padding: 0; }
.stats h3 { grid-column: 1 / -1; padding: 16px 18px 0; font-size: 13px; font-weight: 500; color: var(--text-2); letter-spacing: 0; }
.stat { display: flex; flex-direction: column; gap: 6px; padding: 16px 18px 18px; }
.stat + .stat { border-left: 1px solid var(--hairline); }
.stat-head { display: flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 13px; font-weight: 500; }
Expand Down Expand Up @@ -428,6 +429,7 @@ dialog .note { margin-top: 14px; font-size: 13px; color: var(--text-3); }
.node-title { font-size: 32px; }
.details { gap: 16px; }
.stat { padding: 22px 24px 24px; gap: 10px; }
.stats h3 { padding: 22px 24px 0; }
.stat-value { font-size: 36px; }
.node-id, .danger-zone { padding: 22px 24px; }
#node-id { font-size: 15px; }
Expand Down
6 changes: 6 additions & 0 deletions sdk/js/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion sdk/js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"examples": "tsc -p tsconfig.examples.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"pretest": "tsc -p tsconfig.test.json && tsc -p tsconfig.webapp-test.json",
"test": "node --test 'build/**/*.test.js'",
"test": "node --disallow-code-generation-from-strings --test 'build/**/*.test.js'",
"bundle:browser": "node scripts/bundle-browser.mjs",
"bundle:app": "node scripts/bundle-browser.mjs webapp/index.mjs ../../internal/webapp/public/sdk --minify --no-sourcemap && npm run bundle:app-agent",
"bundle:app-agent": "esbuild @w3c/webmcp-polyfill/auto --bundle --format=esm --minify --outfile=../../internal/webapp/public/sdk/webmcp-polyfill.js && cp node_modules/@mcp-b/webmcp-local-relay/dist/browser/widget.js ../../internal/webapp/public/sdk/webmcp-relay.js && npm run bundle:app-relay",
Expand All @@ -49,6 +49,7 @@
"dependencies": {
"@biscuit-auth/biscuit-wasm": "^0.6.0",
"@bufbuild/protobuf": "^2.16.0",
"@cfworker/json-schema": "^4.1.6",
"@chainsafe/libp2p-noise": "^17.0.0",
"@chainsafe/libp2p-yamux": "^8.0.1",
"@libp2p/circuit-relay-v2": "^4.2.13",
Expand Down
5 changes: 3 additions & 2 deletions sdk/js/src/mcp-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { fileURLToPath } from "node:url";
import { spawn } from "node:child_process";
import { peerIdFromString } from "@libp2p/peer-id";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { CallToolRequestSchema, CallToolResultSchema, ListToolsRequestSchema, type Tool } from "@modelcontextprotocol/sdk/types.js";
Expand Down Expand Up @@ -71,7 +72,7 @@ async function fixture(t: TestContext, mode = "normal") {
return { content: [{ type: "text", text: "3" }, { type: "image", data: "AA==", mimeType: "image/png" }], structuredContent: { answer: 3 }, isError: mode === "error" };
});
const [a, b] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: "fixture-client", version: "1" });
const client = new Client({ name: "fixture-client", version: "1" }, { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() });
await remote.connect(a);
await client.connect(b);
return {
Expand All @@ -82,7 +83,7 @@ async function fixture(t: TestContext, mode = "normal") {
};
const server = createMeshMCPServer(session, "1");
const [a, b] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: "test", version: "1" });
const client = new Client({ name: "test", version: "1" }, { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() });
await server.connect(a);
await client.connect(b);
t.after(async () => { await client.close(); await server.close(); assert.equal(closed, opened, "every remote session closes"); });
Expand Down
7 changes: 6 additions & 1 deletion sdk/js/src/mcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,11 @@ async function serveMCP(stream: Stream, connection: Connection): Promise<void> {
if (type === "") {
server.tool("list_local_services", async () => ({ content: [{ type: "text", text: JSON.stringify([{ type: "mcp", name: "calc" }]) }] }));
} else {
server.tool("add", { a: z.number(), b: z.number() }, async ({ a, b }) => ({ content: [{ type: "text", text: String(a + b) }] }));
// An output schema makes the client compile a validator, which must not need eval (the web app's CSP has no unsafe-eval).
server.registerTool("add", { inputSchema: { a: z.number(), b: z.number() }, outputSchema: { sum: z.number() } }, async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }],
structuredContent: { sum: a + b },
}));
}
await server.connect(new StreamTransport(stream));
}
Expand Down Expand Up @@ -155,6 +159,7 @@ test("a tool is listed and called over the mesh stream, and the provider is veri
assert.deepEqual(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" }]);
assert.deepEqual(result.structuredContent, { sum: 5 });
} finally {
await mcp.close();
}
Expand Down
4 changes: 3 additions & 1 deletion sdk/js/src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import type { Connection, Stream } from "@libp2p/interface";
import { lpStream } from "@libp2p/utils";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker";
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { JSONRPCMessageSchema, type JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js";
import { AUTH_HANDSHAKE_TIMEOUT_MS, AuthRejectedError, MAX_AUTH_FRAME_BYTES, MCP_PROTOCOL } from "./auth.ts";
Expand Down Expand Up @@ -188,7 +189,8 @@ export async function openMCPSession(
}

const transport = new StreamTransport(stream);
const client = new Client(MCP_CLIENT_INFO);
// The default validator, ajv, compiles schemas with new Function, which a page without unsafe-eval in its CSP refuses.
const client = new Client(MCP_CLIENT_INFO, { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() });
await client.connect(transport, { signal });
return {
client,
Expand Down
88 changes: 88 additions & 0 deletions sdk/js/src/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,94 @@ test("a member on one router reaches a member on another", async () => {
}
});

test("a peer no path reaches is reported with the reason each path failed", async () => {
// The member holds two routers, as by default, and neither relays to the
// offline peer. The directory then lists only an address this member has
// no transport for, and a third listed router refuses the member. Each
// reason must reach the caller, not only the last one.
const offline = "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB";
const routerB = await createLibp2p({
addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },
transports: [tcp()],
connectionEncrypters: [tls()],
streamMuxers: [yamux()],
services: { identify: identify(), relay: circuitRelayServer() },
});
const strict = await createLibp2p({
addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },
transports: [tcp()],
connectionEncrypters: [tls()],
streamMuxers: [yamux()],
services: { identify: identify() },
});
const directory = (stream: Parameters<Parameters<Libp2p["handle"]>[1]>[0]) => {
void (async () => {
const lp = lpStream(stream, { maxDataLength: 64 * 1024 });
const req = fromBinary(DirectoryRequestSchema, (await lp.read()).subarray());
const resp = create(DirectoryResponseSchema, {});
if (req.request.case === "findPeer") {
resp.peer = create(PeerRecordSchema, { peerId: offline, addrs: [`/ip4/127.0.0.1/udp/9/quic-v1/p2p/${offline}`] });
}
await lp.write(toBinary(DirectoryResponseSchema, resp));
await stream.close();
})();
};
try {
const routerBBiscuit = mint(routerB.peerId.toString(), ROLE_ROUTER);
await routerB.handle(AUTH_PROTOCOL, authStreamHandler({ ownBiscuit: () => routerBBiscuit, trustedKeys: () => [cpKey] }));
const otherKey = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
const other = new Uint8Array(Buffer.from(otherKey.getPublicKey().toString().replace(/^ed25519\//, ""), "hex"));
await strict.handle(AUTH_PROTOCOL, authStreamHandler({ ownBiscuit: () => routerBiscuit, trustedKeys: () => [other] }));
await router.handle(DIRECTORY_PROTOCOL, directory);
await routerB.handle(DIRECTORY_PROTOCOL, directory);
const routerBAddr = (routerB.getMultiaddrs()[0] as ReturnType<typeof multiaddr>).toString();
const strictAddr = (strict.getMultiaddrs()[0] as ReturnType<typeof multiaddr>).toString();

const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: fakeControlPlane([routerAddr, routerBAddr, strictAddr]) });
const session = await mesh.join({ refreshLeadMs: 0, routerAddresses: [routerAddr, routerBAddr], reserveRelay: false });
try {
assert.equal(session.routers.length, 2);
await assert.rejects(session.connect(offline, AbortSignal.timeout(10_000)), (err: Error) => {
assert.match(err.message, new RegExp(`cannot reach ${offline}`));
assert.equal(err.message.match(/NO_RESERVATION/g)?.length, 2, `each held router's answer is kept: ${err.message}`);
assert.match(err.message, /no valid addresses/, "the directory path's failure is reported too");
assert.match(err.message, new RegExp(`${strictAddr}: admit: `), "the router that refused the member is reported too");
return true;
});
} finally {
await session.close();
}
} finally {
await router.unhandle(DIRECTORY_PROTOCOL);
await strict.stop();
await routerB.stop();
}
});

test("a directory that fails the lookup is reported with the relay's answer", async () => {
const offline = "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB";
await router.handle(DIRECTORY_PROTOCOL, (stream) => {
void (async () => {
const lp = lpStream(stream, { maxDataLength: 64 * 1024 });
await lp.read();
await lp.write(toBinary(DirectoryResponseSchema, create(DirectoryResponseSchema, { error: "directory unavailable" })));
await stream.close();
})();
});
const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: fakeControlPlane([routerAddr]) });
const session = await mesh.join({ refreshLeadMs: 0, routerAddresses: [routerAddr], reserveRelay: false });
try {
await assert.rejects(session.connect(offline, AbortSignal.timeout(10_000)), (err: Error) => {
assert.match(err.message, /NO_RESERVATION/);
assert.match(err.message, /directory lookup: .*directory unavailable/);
return true;
});
} finally {
await session.close();
await router.unhandle(DIRECTORY_PROTOCOL);
}
});

test("discovery asks a held router over the directory protocol and connects to no other", async () => {
// A member keeps no DHT: a lookup is one request to a router it holds,
// which answers from the routers' directory. A second listed router is
Expand Down
26 changes: 17 additions & 9 deletions sdk/js/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -779,18 +779,20 @@ export class MeshSession {
if (peerId === undefined || (typeof peer === "string" && peer.startsWith("/")) || isMultiaddr(peer) || signal?.aborted === true) {
throw err;
}
for (const more of [() => this.#routedAddresses(peerId, signal), () => this.#unjoinedRouterAddresses(peerId, signal)]) {
// Each path's reason is kept, as in the Python SDK: a later path's error alone hides why the peer itself did not answer.
const failures = [`${addrs.join(" ")}: ${errorText(err)}`];
for (const more of [() => this.#routedAddresses(peerId, failures, signal), () => this.#unjoinedRouterAddresses(peerId, failures, signal)]) {
const routed = await more();
if (routed.length === 0) {
continue;
}
try {
return await this.node.dial(routed, options);
} catch (routedErr) {
err = routedErr;
failures.push(`${routed.join(" ")}: ${errorText(routedErr)}`);
}
}
throw err;
throw new Error(`cannot reach ${peerId}:\n ${failures.join("\n ")}`);
}
}

Expand All @@ -800,7 +802,7 @@ export class MeshSession {
* is the one the credential carries, refreshed by every control plane
* pull, so a router that came up after join is tried too.
*/
async #unjoinedRouterAddresses(peerId: string, signal?: AbortSignal): Promise<Multiaddr[]> {
async #unjoinedRouterAddresses(peerId: string, failures: string[], signal?: AbortSignal): Promise<Multiaddr[]> {
const out: Multiaddr[] = [];
for (const text of this.mesh.credential.routerAddresses) {
let addr: Multiaddr;
Expand All @@ -815,8 +817,8 @@ export class MeshSession {
}
try {
out.push((await this.#admitRouter(addr, signal)).addr.encapsulate(`/p2p-circuit/p2p/${peerId}`));
} catch {
continue;
} catch (err) {
failures.push(`${addr}: admit: ${errorText(err)}`);
}
}
return out;
Expand All @@ -828,12 +830,13 @@ export class MeshSession {
* for a source it authenticated, so a router met this way is dialed and
* passed the handshake first, and joins the admitted set.
*/
async #routedAddresses(peerId: string, signal?: AbortSignal): Promise<Multiaddr[]> {
async #routedAddresses(peerId: string, failures: string[], signal?: AbortSignal): Promise<Multiaddr[]> {
const lookup = signal ?? AbortSignal.timeout(PEER_ROUTING_TIMEOUT_MS);
let found: PeerRecord | undefined;
try {
found = await findPeer(this.#directoryRouters(), peerId, lookup);
} catch {
} catch (err) {
failures.push(`directory lookup: ${errorText(err)}`);
return [];
}
if (found === undefined) {
Expand All @@ -855,7 +858,8 @@ export class MeshSession {
if (!this.routers.some((r) => r.peerId === relay)) {
try {
await this.#admitRouter(relayAddr, signal);
} catch {
} catch (err) {
failures.push(`${relayAddr}: admit: ${errorText(err)}`);
continue;
}
}
Expand Down Expand Up @@ -1529,7 +1533,11 @@ export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}, timeo
}
}

// libp2p fails a dial to several addresses with one AggregateError whose message names none of the reasons.
function errorText(err: unknown): string {
if (err instanceof AggregateError) {
return err.errors.map(errorText).join("; ");
}
return err instanceof Error ? err.message : String(err);
}

Expand Down
12 changes: 7 additions & 5 deletions site/content/docs/preview/webapp.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ and cannot hold a key. On one computer, `http://127.0.0.1` works for both.

Expect: a dialog that names the mesh's address. Tap **Join**.

Expect: the dashboard shows **Node is Running**, the **Node ID** and the
number of **Routers** that hold a relay slot for the browser.
Expect: the dashboard shows **Node is Running**, the **Node ID** and, under
**Connections**, at least one router.

A link of the form `<page address>#server=<mesh address>&token=<token>` joins
the same way. The values travel after the `#`, which browsers never send to a
Expand All @@ -93,11 +93,13 @@ The tabs appear once the browser has enrolled.

| Tab | What it shows |
| --- | --- |
| **Dashboard** | **Node is Running** or **Node is Stopped**, the mesh's address, **Connected Peers**, **Routers**, the **Node ID**, and **Start** and **Stop**. **Unenroll / Clear Identity** is at the bottom. |
| **Dashboard** | **Node is Running** or **Node is Stopped**, the mesh's address, **Connections**, the **Node ID**, and **Start** and **Stop**. **Unenroll / Clear Identity** is at the bottom. |
| **Config** | **Device**: the labels this browser enrolled with, whether the browser keeps the storage, and until when the current credential is valid. On a computer, **Local agent** connects an agent on that computer. The version is at the bottom. |

**Routers** counts the routers that hold a relay slot for the browser,
because peers reach it through them.
**Connections** counts what the browser is connected to now: **Routers**,
the routers it joined through or passed through to reach a member, and
**Peers**, the other members it talks to. A member the browser has not talked to recently is not
counted, so **Peers** is often 0. The console shows every member of the mesh.

The node runs only while the page is open. The app remembers whether you left
it running. If you did, it rejoins on its own the next time it opens, with the
Expand Down
2 changes: 2 additions & 0 deletions tests/ui/app.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ for (const topology of topologies) {
await expect(page.locator('#copy-id')).toHaveAccessibleName('Copied');
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(peer);
await expect(page.locator('#stat-routers')).toHaveText('1');
// The router is counted once, under Routers, not again as a peer.
await expect(page.locator('#stat-peers')).toHaveText('0');
await expect(page.locator('#mesh-host')).toHaveText(new URL(samOne.publicUrl).host);

// The address follows the saved credential, even when the page never saved it.
Expand Down
Loading