From c90ca5fae0a0dfcc5d87f670bde510868ccbaa95 Mon Sep 17 00:00:00 2001 From: Tomas Tormo Date: Thu, 26 Nov 2026 22:34:19 +0000 Subject: [PATCH] sdk/js, webapp: a browser lists tools that declare an output schema, and a failed dial names every path On a testnet, find_remote_tools from agentmesh-webapp failed in two ways, and its dashboard counted routers as peers: - A provider whose tools declare an outputSchema (server-everything) failed with "EvalError: ... 'unsafe-eval' is not an allowed source of script". The MCP SDK's client compiles each output schema with ajv, which builds validators with new Function, and the page's CSP allows no eval. - Offline providers were reported as "NoValidAddressesError: The dial request has no valid addresses". connect() kept only the error of its last path, a directory address the browser has no transport for, and dropped the relay's NO_RESERVATION. With two held routers libp2p also folds the relays' answers into one "All multiaddr dials failed". - "Connected Peers" counted every connection, so a page that talked to no member showed one peer per router, next to a Routers count of the same routers. Now: - The SDK's MCP client checks schemas with the MCP SDK's eval-free CfWorkerJsonSchemaValidator (@cfworker/json-schema, the MCP SDK's optional peer), in Node and in the browser. - connect() throws "cannot reach :" with each path it tried and why it failed, as the Python SDK does. Errors libp2p aggregates are expanded, and a router that refuses the member or a failed directory lookup is reported instead of skipped. - The dashboard groups its counts under Connections. Peers leaves the routers out. Routers is unchanged, the SDK's admitted routers, because the lost-session timer is timed on that count. Tests: - npm test runs the SDK suite with eval switched off (--disallow-code-generation-from-strings). The MCP test tool declares an output schema; without the validator change it fails with EvalError. - Two session tests: one holds two routers, a directory address with no transport and a router that refuses the member; one gets an error from the directory. On the parent commit both get only the last path's error. - The UI journey expects 0 peers after join; on the parent commit it shows 1. --- internal/webapp/public/app.js | 10 +++- internal/webapp/public/index.html | 3 +- internal/webapp/public/style.css | 2 + sdk/js/package-lock.json | 6 ++ sdk/js/package.json | 3 +- sdk/js/src/mcp-server.test.ts | 5 +- sdk/js/src/mcp.test.ts | 7 ++- sdk/js/src/mcp.ts | 4 +- sdk/js/src/session.test.ts | 88 +++++++++++++++++++++++++++++ sdk/js/src/session.ts | 26 ++++++--- site/content/docs/preview/webapp.md | 12 ++-- tests/ui/app.spec.js | 2 + 12 files changed, 146 insertions(+), 22 deletions(-) diff --git a/internal/webapp/public/app.js b/internal/webapp/public/app.js index 5cc7849e1..b0970ac48 100644 --- a/internal/webapp/public/app.js +++ b/internal/webapp/public/app.js @@ -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) { diff --git a/internal/webapp/public/index.html b/internal/webapp/public/index.html index 8ac3c4726..324b27e47 100644 --- a/internal/webapp/public/index.html +++ b/internal/webapp/public/index.html @@ -107,8 +107,9 @@

+

Connections

- Connected Peers + Peers –
diff --git a/internal/webapp/public/style.css b/internal/webapp/public/style.css index 4246a6d66..db1f77831 100644 --- a/internal/webapp/public/style.css +++ b/internal/webapp/public/style.css @@ -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; } @@ -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; } diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.json index 9f7292b6f..2f2151651 100644 --- a/sdk/js/package-lock.json +++ b/sdk/js/package-lock.json @@ -11,6 +11,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", @@ -165,6 +166,11 @@ "node": ">=14.17" } }, + "node_modules/@cfworker/json-schema": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.6.tgz", + "integrity": "sha512-YzVGTHXf4bzlyAL5KAvHYCdNbbt6zM5cYkAgxqxQPDQM6aZ4ShIIN5yJ+6q7YeonnevxT8k/LmD2tJi/jOiKkg==" + }, "node_modules/@chainsafe/as-chacha20poly1305": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/@chainsafe/as-chacha20poly1305/-/as-chacha20poly1305-0.1.0.tgz", diff --git a/sdk/js/package.json b/sdk/js/package.json index f36acac9e..1a01ea737 100644 --- a/sdk/js/package.json +++ b/sdk/js/package.json @@ -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", @@ -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", diff --git a/sdk/js/src/mcp-server.test.ts b/sdk/js/src/mcp-server.test.ts index e3f5414c2..165633cb4 100644 --- a/sdk/js/src/mcp-server.test.ts +++ b/sdk/js/src/mcp-server.test.ts @@ -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"; @@ -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 { @@ -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"); }); diff --git a/sdk/js/src/mcp.test.ts b/sdk/js/src/mcp.test.ts index 4300875ab..62cceb1ae 100644 --- a/sdk/js/src/mcp.test.ts +++ b/sdk/js/src/mcp.test.ts @@ -107,7 +107,11 @@ async function serveMCP(stream: Stream, connection: Connection): Promise { 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)); } @@ -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(); } diff --git a/sdk/js/src/mcp.ts b/sdk/js/src/mcp.ts index 92cede734..4bb90e438 100644 --- a/sdk/js/src/mcp.ts +++ b/sdk/js/src/mcp.ts @@ -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"; @@ -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, diff --git a/sdk/js/src/session.test.ts b/sdk/js/src/session.test.ts index ff1630bc6..4aadee736 100644 --- a/sdk/js/src/session.test.ts +++ b/sdk/js/src/session.test.ts @@ -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[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).toString(); + const strictAddr = (strict.getMultiaddrs()[0] as ReturnType).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 diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.ts index 9ee55abec..24e53b4a0 100644 --- a/sdk/js/src/session.ts +++ b/sdk/js/src/session.ts @@ -779,7 +779,9 @@ 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; @@ -787,10 +789,10 @@ export class MeshSession { 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 ")}`); } } @@ -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 { + async #unjoinedRouterAddresses(peerId: string, failures: string[], signal?: AbortSignal): Promise { const out: Multiaddr[] = []; for (const text of this.mesh.credential.routerAddresses) { let addr: Multiaddr; @@ -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; @@ -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 { + async #routedAddresses(peerId: string, failures: string[], signal?: AbortSignal): Promise { 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) { @@ -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; } } @@ -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); } diff --git a/site/content/docs/preview/webapp.md b/site/content/docs/preview/webapp.md index 806549a4c..f7e4bebae 100644 --- a/site/content/docs/preview/webapp.md +++ b/site/content/docs/preview/webapp.md @@ -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 `#server=&token=` joins the same way. The values travel after the `#`, which browsers never send to a @@ -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 diff --git a/tests/ui/app.spec.js b/tests/ui/app.spec.js index d53f9b9c5..744f3c574 100644 --- a/tests/ui/app.spec.js +++ b/tests/ui/app.spec.js @@ -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.