chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.5.0 Latest 5 packages
0
0
// What the flows share: the world they run in, the browser that trusts
// HUD's certificate alone, signing in through the PDS's own pages, and
// HUD's MCP as a client of it, with a token got as any client gets one.
import { test as base, expect } from '@playwright/test';
import { createHash, randomBytes } from 'node:crypto';
export const world = JSON.parse(process.env.E2E_WORLD);
export const who = Object.fromEntries(world.accounts.map((a) => [a.handle.split('.')[0], a]));
/// The flows' `test`: Chromium reaching HUD's hostname on loopback, and
/// trusting the certificate HUD is served with there, and no other.
export const test = base.extend({
launchOptions: [
async ({ launchOptions }, use) => {
await use({
...launchOptions,
args: [
...(launchOptions.args ?? []),
`--host-resolver-rules=MAP ${world.host} 127.0.0.1`,
`--ignore-certificate-errors-spki-list=${world.spki}`,
],
});
},
{ scope: 'worker' },
],
});
export { expect };
/// Signs in as `name` on the PDS's own pages `page` has come to, and
/// approves what HUD asks; back at HUD when it returns. A browser signed
/// in there already may be asked only to approve, or not even that.
export async function approve(page, name) {
const pds = new URL(world.pds).origin;
await page.waitForURL((u) => u.origin === pds);
const password = page.getByRole('textbox', { name: 'Password' });
const accept = page.getByRole('button', { name: /^(accept|authorize|allow)$/i });
const account = page.getByRole('button', { name: new RegExp(who[name].handle) }).first();
// Each step is tried briefly, as a page between steps holds its fields inert.
const tried = (step) => step().then(
() => true,
() => false,
);
for (let i = 0; i < 150 && new URL(page.url()).origin === pds; i++) {
if (await password.isVisible()) {
if (await tried(() => password.fill(who[name].password, { timeout: 1000 })))
await tried(() => page.getByRole('button', { name: 'Sign in' }).click({ timeout: 1000 }));
} else if (await accept.isVisible()) {
await tried(() => accept.click({ timeout: 1000 }));
} else if (await account.isVisible()) {
await tried(() => account.click({ timeout: 1000 }));
}
await page.waitForTimeout(200);
}
}
/// Signs `page` in to the workspace as `name`: the signed-out page's Sign
/// in (the header's), its sign-in dialog, the PDS's pages, then back at the
/// workspace, drawn. The account is named by its DID: a `.test` handle
/// resolves nowhere HUD looks.
export async function signIn(page, name) {
await page.goto(`${world.base}/workspace`);
await page.getByRole('banner').getByRole('button', { name: 'Sign in', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'Sign in with your Atmosphere account' });
await dialog.getByLabel('Handle').fill(who[name].did);
await dialog.getByRole('button', { name: 'Sign in', exact: true }).click();
await approve(page, name);
await page.waitForURL(`${world.base}/workspace`);
await expect(page.getByRole('tablist', { name: 'Canvases' })).toBeVisible();
}
const b64url = (bytes) => Buffer.from(bytes).toString('base64url');
/// An MCP access token of `name`'s, got as an MCP client gets one: a
/// client registered at HUD (RFC 7591), its authorization request with
/// PKCE answered by signing in on `page`'s context, the browser sent to
/// the client's loopback redirect URI, the code exchanged.
export async function mcpToken(context, name) {
const redirect = 'http://127.0.0.1/e2e-callback';
const registered = await fetch(`${world.hudUrl}/oauth/register`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
redirect_uris: [redirect],
client_name: 'HUD e2e',
grant_types: ['authorization_code', 'refresh_token'],
token_endpoint_auth_method: 'none',
}),
});
expect(registered.status, await registered.clone().text()).toBe(201);
const { client_id } = await registered.json();
const verifier = b64url(randomBytes(32));
const challenge = b64url(createHash('sha256').update(verifier).digest());
const state = b64url(randomBytes(8));
const resource = `${world.base}/mcp`;
const asked = new URLSearchParams({
client_id,
redirect_uri: redirect,
response_type: 'code',
code_challenge: challenge,
code_challenge_method: 'S256',
resource,
state,
login_hint: who[name].did,
});
const page = await context.newPage();
let back = null;
// Read off the request to where the client would be listening, which
// nothing answers: Chromium upgrades it to https, past any route.
const callback = new URL(redirect);
page.on('request', (request) => {
const u = new URL(request.url());
if (u.host === callback.host && u.pathname === callback.pathname) back = u;
});
await page.goto(`${world.base}/oauth/authorize?${asked}`);
// A client sent back to loopback, naming its account, goes straight on
// to the account's server where HUD_ALLOW_PRIVATE is on; else HUD's
// sign-in page names the client first.
const pds = new URL(world.pds).origin;
const proceed = page.getByRole('button', { name: 'Continue' });
await expect.poll(async () => new URL(page.url()).origin === pds || (await proceed.isVisible())).toBe(true);
if (new URL(page.url()).origin !== pds) await proceed.click();
await approve(page, name);
await expect.poll(() => back !== null).toBe(true);
await page.close();
expect(back.searchParams.get('state')).toBe(state);
const code = back.searchParams.get('code');
expect(code, back.toString()).toBeTruthy();
const res = await fetch(`${world.hudUrl}/oauth/token`, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: redirect,
client_id,
code_verifier: verifier,
resource,
}),
});
const answer = await res.json();
expect(res.status, JSON.stringify(answer)).toBe(200);
return answer.access_token;
}
/// Calls HUD's MCP tool `tool` with `args`, as the holder of `token`: its
/// result.
export async function mcpCall(token, tool, args) {
const res = await fetch(`${world.hudUrl}/mcp`, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json, text/event-stream',
authorization: `Bearer ${token}`,
'mcp-protocol-version': '2025-06-18',
},
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } }),
});
const answer = await res.json();
expect(res.status, JSON.stringify(answer)).toBe(200);
expect(answer.error, JSON.stringify(answer)).toBeUndefined();
return answer.result;
}