askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
15 hours, 56 minutes ago
History
mcp.mjs · 12.1 KB · 139 lines
| 1 | // Connecting to an MCP server with OAuth, end to end: discovery, registration, PKCE through the loopback redirect, |
| 2 | // tools in the chat, refresh, revocation. The server is a stand-in on the demo server (see /mcp and /o/* there). |
| 3 | export default async function (ctx) { |
| 4 | const { call: T, check, base, sleep } = ctx; |
| 5 | const rejects = (p) => p.then(() => null, (e) => e); |
| 6 | const demo = async () => (await T("mcp.state")).find((x) => x.id === "demo"); |
| 7 | const stats = async () => (await fetch(base + "/o/_stats")).json(); |
| 8 | const ev = async (since) => T("chat.events", { since }); |
| 9 | async function waitFor(fn, what) { |
| 10 | for (let i = 0; i < 200; i++) { const v = await fn(); if (v) return v; await sleep(50); } |
| 11 | throw new Error(`timed out waiting for ${what}`); |
| 12 | } |
| 13 | |
| 14 | // before signing in |
| 15 | let st = await T("mcp.state"); |
| 16 | check(st.some((x) => x.id === "askrobots") && st.find((x) => x.id === "demo")?.signedIn === false, "the built-in askrobots entry and the server from the servers file are listed, and not signed in", JSON.stringify(st.map((x) => x.id))); |
| 17 | check((await T("mcp.tools")).length === 0, "a server you are not signed in to adds no tools"); |
| 18 | const none = await T("chat.send", { text: "lookup cats" }); |
| 19 | check(none.reply === "Result: no such tool", "so the assistant cannot use it"); |
| 20 | |
| 21 | // a sign-in that is cancelled, and one with the wrong state |
| 22 | const c0 = await T("mcp.connect", { id: "demo", open: false }); |
| 23 | const u0 = new URL(c0.authorizeUrl); |
| 24 | const redirect0 = u0.searchParams.get("redirect_uri"); |
| 25 | check((await demo()).connecting === true, "starting a sign-in shows it as waiting"); |
| 26 | check((await fetch(`${redirect0}?code=x&state=not-the-state`)).status === 400 && (await demo()).connecting === true, "a redirect with the wrong state is refused and does not end the sign-in"); |
| 27 | await T("mcp.cancel", { id: "demo" }); |
| 28 | await waitFor(async () => (await demo()).connecting === false, "the cancelled sign-in to end"); |
| 29 | check((await demo()).error === "sign-in was cancelled" && !(await demo()).signedIn, "cancelling ends it, says so, and signs nobody in"); |
| 30 | |
| 31 | // the real thing: registration, PKCE, the loopback redirect |
| 32 | const c = await T("mcp.connect", { id: "demo", open: false }); |
| 33 | const u = new URL(c.authorizeUrl); |
| 34 | check(u.origin + u.pathname === base + "/o/authorize/" && u.searchParams.get("code_challenge_method") === "S256" && u.searchParams.get("response_type") === "code" && u.searchParams.get("scope") === "mcp" && u.searchParams.get("state").length > 20, "the consent address is built from the server's own discovery documents, with PKCE and a state", c.authorizeUrl); |
| 35 | const redirect = u.searchParams.get("redirect_uri"); |
| 36 | check(/^http:\/\/127\.0\.0\.1:5368\d\/callback$/.test(redirect), "the redirect is a loopback address on a registered port", redirect); |
| 37 | const reg = (await stats()).lastRegistration; |
| 38 | check(reg.token_endpoint_auth_method === "none" && reg.redirect_uris.length === 5 && !("client_secret" in reg), "the client registered itself as public, with all five loopback redirects and no secret", JSON.stringify(reg)); |
| 39 | const approve = await fetch(c.authorizeUrl, { redirect: "manual" }); // what the person's browser does after they click Approve |
| 40 | const back = approve.headers.get("location"); |
| 41 | check(approve.status === 302 && back.startsWith(redirect), "the server sends the browser back to the loopback address", back); |
| 42 | check((await fetch(back)).status === 200, "the browser's own redirect is accepted"); |
| 43 | await waitFor(async () => (await demo()).signedIn, "the sign-in to finish"); |
| 44 | st = await T("mcp.state"); |
| 45 | check((await demo()).signedIn && !(await demo()).connecting && !JSON.stringify(st).match(/AT-|RT-|code-/), "signed in, and nothing secret is in the state"); |
| 46 | check((await demo()).persistent === false, "and with DBB_MCP_STORE=memory the sign-in is reported as lasting only until the browser closes"); |
| 47 | const s1 = await stats(); |
| 48 | check(s1.registered === 1 && s1.issued === 1, "the code was traded for a token, and the second try reused the first one's registration", JSON.stringify({ registered: s1.registered, issued: s1.issued })); |
| 49 | check(!JSON.stringify(await T("status")).match(/AT-|RT-/), "tokens do not appear in the browser's status either"); |
| 50 | |
| 51 | // the tools |
| 52 | const tools = await T("mcp.tools"); |
| 53 | check(JSON.stringify(tools.map((t) => [t.name, t.risk])) === JSON.stringify([["demo__lookup", "read"], ["demo__save", "act"], ["demo__person", "read"]]), "only the tools the entry allows are offered, reads as reads and the write as an action (the server's 'wipe' is not offered)", JSON.stringify(tools.map((t) => t.name))); |
| 54 | |
| 55 | // using them from the chat |
| 56 | const lookup = await T("chat.send", { text: "lookup cats" }); |
| 57 | check(lookup.reply.startsWith("Result: Found 2 notes about cats.") && !lookup.events.some((e) => e.kind === "confirm"), "the assistant can use a read tool, with no question asked"); |
| 58 | const log = await (await fetch(base + "/v1/_log")).json(); |
| 59 | const toolMsg = log.at(-1).messages.at(-1); |
| 60 | check(toolMsg.role === "tool" && /^\[Content from the person's own account/.test(toolMsg.content) && /<untrusted-[0-9a-f]{12}>/.test(toolMsg.content) && toolMsg.content.includes("IGNORE ALL PREVIOUS INSTRUCTIONS"), "what the server returned reaches the model marked as from the person's account, not from the person, inside the untrusted tags (its text is there, as data)"); |
| 61 | check(!log.at(-1).tools.some((t) => /wipe/.test(t.function.name)) && !/delete everything/i.test(JSON.stringify(log.at(-1).tools)), "the model is never offered a tool the entry did not allow"); |
| 62 | const who = await T("chat.send", { text: "whois" }); |
| 63 | check(/Ada/.test(who.reply) && !/private notes|interactions/.test(who.reply) && !/private notes/.test(JSON.stringify(await (await fetch(base + "/v1/_log")).json())), "fields the entry drops (notes, interactions) never reach the model"); |
| 64 | |
| 65 | // a tool that writes: always asked about, even in Auto mode; fixed arguments are forced |
| 66 | await T("chat.mode", { mode: "auto" }); |
| 67 | let since = (await ev(0)).next; |
| 68 | const run = T("chat.send", { text: "keep this page" }); |
| 69 | const ask = await waitFor(async () => (await ev(since)).events.find((e) => e.kind === "confirm"), "the approval for the write"); |
| 70 | check(ask.danger === true && /^Ask Demo notes to save:\n/.test(ask.summary) && /\nproject_id: P-1(\n|$)/.test(ask.summary), "a write is asked about even in Auto mode, and the question shows the forced project, not the model's", ask.summary); |
| 71 | await T("chat.confirm", { id: ask.id, ok: false }); |
| 72 | check((await run).reply === "Result: declined" && (await stats()).lastArgs?.title !== "A good page", "a no means nothing was sent to the server"); |
| 73 | await T("chat.mode", { mode: "ask" }); |
| 74 | since = (await ev(0)).next; |
| 75 | const run2 = T("chat.send", { text: "keep this page" }); |
| 76 | const ask2 = await waitFor(async () => (await ev(since)).events.find((e) => e.kind === "confirm"), "the second approval"); |
| 77 | await T("chat.confirm", { id: ask2.id, ok: true }); |
| 78 | check((await run2).reply === "Result: saved", "a yes sends it"); |
| 79 | check((await stats()).lastArgs.project_id === "P-1" && (await stats()).lastArgs.title === "A good page", "the server received the fixed project, whatever the model asked for", JSON.stringify((await stats()).lastArgs)); |
| 80 | |
| 81 | // After private data was read from the account, typing asks even in Auto mode (a page could have talked the assistant into copying it) |
| 82 | await T("page.goto", { url: base + "/forms" }); |
| 83 | await T("chat.mode", { mode: "auto" }); |
| 84 | since = (await ev(0)).next; |
| 85 | const run3 = T("chat.send", { text: "exfil the notes" }); |
| 86 | const ask3 = await waitFor(async () => (await ev(since)).events.find((e) => e.kind === "confirm"), "the approval for typing after a private read"); |
| 87 | check(/Type “COPIED-FROM-NOTES”/.test(ask3.summary) && ask3.danger === true, "in Auto mode, typing right after a private read asks, and is marked risky", ask3.summary); |
| 88 | check((await T("page.eval", { js: "document.querySelector('[name=first]').value" })).value === "Ada", "and nothing has been typed yet"); |
| 89 | await T("chat.confirm", { id: ask3.id, ok: false }); |
| 90 | check((await run3).reply === "Result: declined" && (await T("page.eval", { js: "document.querySelector('[name=first]').value" })).value === "Ada", "a no leaves the page untouched"); |
| 91 | await T("chat.mode", { mode: "ask" }); |
| 92 | |
| 93 | // refresh: with very short-lived access tokens every call has to refresh first, and keeps working |
| 94 | await T("mcp.disconnect", { id: "demo" }); |
| 95 | await fetch(base + "/o/_short?on=1"); |
| 96 | const c2 = await T("mcp.connect", { id: "demo", open: false }); |
| 97 | const a2 = await fetch(c2.authorizeUrl, { redirect: "manual" }); |
| 98 | await fetch(a2.headers.get("location")); |
| 99 | await waitFor(async () => (await demo()).signedIn, "the second sign-in"); |
| 100 | const r0 = (await stats()).refreshed; |
| 101 | const again = await T("chat.send", { text: "lookup dogs" }); |
| 102 | check(again.reply.startsWith("Result: Found 2 notes about cats.") && (await stats()).refreshed > r0, "when the access token is about to expire it is refreshed quietly and the call works", `refreshes ${(await stats()).refreshed - r0}`); |
| 103 | await fetch(base + "/o/_short?on=0"); |
| 104 | |
| 105 | // signing in inside the browser's own tab: no system browser, no listener, the redirect is caught inside the browser |
| 106 | await T("mcp.disconnect", { id: "demo" }); |
| 107 | const tabsBefore = (await T("tabs.list")).length; |
| 108 | const issuedBefore = (await stats()).issued; |
| 109 | const net = await import("node:net"); |
| 110 | const portOpen = (port) => new Promise((resolve) => { const sk = net.connect({ host: "127.0.0.1", port }, () => (sk.destroy(), resolve(true))); sk.on("error", () => resolve(false)); }); |
| 111 | const viaTab = await T("mcp.connect", { id: "demo", wait: true }); // the default: a tab of this browser (the stand-in server approves at once) |
| 112 | check(new URL(viaTab.authorizeUrl).searchParams.get("redirect_uri") === "http://127.0.0.1:53682/callback", "by default the consent page opens in a tab of this browser, with the first registered loopback address as the redirect", viaTab.authorizeUrl); |
| 113 | check((await demo()).signedIn && (await stats()).issued === issuedBefore + 1, "the redirect was caught inside the browser and the code traded for a token"); |
| 114 | check(!(await portOpen(53682)) && !(await portOpen(53683)), "and nothing is listening on a port, so there is nothing to be down when you click"); |
| 115 | check((await T("tabs.list")).length === tabsBefore, "the consent tab closes itself afterwards (the number of tabs is what it was)", `${tabsBefore} → ${(await T("tabs.list")).length}`); |
| 116 | check((await T("chat.send", { text: "lookup cats" })).reply.startsWith("Result: Found 2 notes about cats."), "and the new sign-in works for the assistant"); |
| 117 | |
| 118 | // the panel |
| 119 | const cdp = await ctx.chrome(); |
| 120 | const q = (js) => cdp.ev(`(() => { ${js} })()`); |
| 121 | const row = `[...document.querySelectorAll('#chatConn .cn')].find((r) => /Demo notes/.test(r.textContent))`; |
| 122 | await cdp.ev(`setChat(false)`); |
| 123 | await cdp.ev(`toggleChat()`); |
| 124 | await waitFor(async () => q(`return /Demo notes/.test(document.getElementById('chatConn').textContent)`), "the panel to list the connection"); |
| 125 | check(await q(`const t = ${row}.textContent; return /connected/.test(t) && /until you close the browser/.test(t) && /Disconnect/.test(t)`), "the panel shows the connection, says it lasts until the browser closes, and offers Disconnect"); |
| 126 | await q(`${row}.querySelector('button').click()`); |
| 127 | await waitFor(async () => (await demo()).signedIn === false, "the panel's Disconnect"); |
| 128 | const revokedBy = (await stats()).revoked; |
| 129 | check(revokedBy >= 2, "Disconnect asks the server to revoke the token", String(revokedBy)); |
| 130 | await waitFor(async () => q(`const b = ${row}.querySelector('button').textContent; return b === 'Connect'`), "the panel to offer Connect again"); |
| 131 | check(true, "and then offers Connect again"); |
| 132 | check((await T("mcp.tools")).length === 0 && (await T("chat.send", { text: "lookup cats" })).reply === "Result: no such tool", "after disconnecting the tools are gone"); |
| 133 | |
| 134 | // off while the caller network is on |
| 135 | await T("net.provider", { enabled: true, userAgent: "E2E-Mcp/1.0 (+https://example.invalid/about)" }); |
| 136 | const refused = await rejects(T("mcp.connect", { id: "demo", open: false })); |
| 137 | await T("net.provider", { enabled: false }); |
| 138 | check(refused && /caller network/.test(refused.message), "signing in is refused while the caller network is on", refused?.message); |
| 139 | } |