chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.4.0 Latest 5 packages
0
0
// The gallery's answers (answers.json beside this): each public entry of
// entries.mjs as a HUD server answers it at /mcp with no one signed in,
// and each `made` one made up by made.mjs, as the signed-in `me`, held to
// its lexicon; with the profiles of the people the tiles show, what was
// picked from one answer for another call, the lexicons the made-up ones
// were held to that lexicons/ lacks, and the apps' icons (icons/). Each
// answer is kept as `hud resolve` reads one (`_meta.view`, and
// `_meta.lexicon` and `_meta.handles` for records no view draws), the
// server's own origin as HUD's default, http://localhost:8787. Recorded
// once, and again only to change what the gallery shows; `just
// gallery-data` asks no server.
//
// node harness/gallery/record.mjs [<HUD url>] all of it (http://127.0.0.1:8797)
// node harness/gallery/record.mjs --made the made-up answers again, from what is recorded
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { answersFile, filled, iconsDir, lexiconsOf, root, shown, viewOf } from './common.mjs';
import { entries, me as meHandle, people } from './entries.mjs';
import { check, made } from './made.mjs';
const argv = process.argv.slice(2);
const remake = argv.includes('--made');
const base = argv.find((a) => !a.startsWith('--')) ?? 'http://127.0.0.1:8797';
const say = (line) => console.log(`==> ${line}`);
const HUD = 'http://localhost:8787';
let id = 0;
/** A tool's result, as /mcp answers it to no one; a failure of the service it asked tried again, twice. */
async function call(name, args) {
for (let attempt = 1; ; attempt++) {
const res = await fetch(new URL('/mcp', base), {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': '2026-07-28', 'mcp-method': 'tools/call', 'mcp-name': name },
body: JSON.stringify({
jsonrpc: '2.0',
id: ++id,
method: 'tools/call',
params: { name, arguments: args, _meta: { 'io.modelcontextprotocol/protocolVersion': '2026-07-28', 'io.modelcontextprotocol/clientCapabilities': {} } }
})
});
const body = await res.json();
if (!body.result) throw new Error(`${name} ${JSON.stringify(args)}: ${body.error?.message ?? body.error_description ?? JSON.stringify(body)}`);
if (!body.result.isError) return body.result;
const why = body.result.content?.[0]?.text ?? '';
if (attempt === 3 || !/request failed|timed out|unavailable/i.test(why)) throw new Error(`${name} ${JSON.stringify(args)}: ${why}`);
}
}
const json = (file) => JSON.parse(readFileSync(file, 'utf8'));
const domains = new Set(['bsky.app', 'bsky.chat']);
const appOf = (nsid) => nsid?.split('.').slice(0, 2).reverse().join('.');
let book;
if (remake) {
if (!existsSync(answersFile)) throw new Error('nothing recorded yet: run record.mjs without --made first');
book = json(answersFile);
} else {
// The server's own origin, in its blob and icon URLs: an app's page names its icon by it.
const app = await call('describe_app', { domain: 'bsky.app' });
const origin = new URL(app.structuredContent.icon).origin;
/** A recorded answer as `hud resolve` reads one, the server's origin as HUD's default. */
const kept = (name, args, result) => {
const { content, structuredContent, isError } = JSON.parse(JSON.stringify(result).replaceAll(origin, HUD));
const meta = {};
const doc = viewOf(name, args);
if (doc) meta.view = shown(name, doc);
else if (name === 'list_records' || name === 'get_record') {
// Records no view draws: their fields by their collection's lexicon, where lexicons/ has it, and their account's handle.
const nsid = structuredContent.collection;
const file = join(root, 'lexicons', `${nsid}.json`);
meta.lexicon = existsSync(file) ? { nsid, doc: json(file) } : null;
meta.handles = structuredContent.handle ? { [structuredContent.did]: structuredContent.handle } : {};
}
return { content, structuredContent, isError, _meta: meta };
};
const profiles = (await call('query', { method: 'app.bsky.actor.getProfiles', params: { actors: people }, service: 'did:web:api.bsky.app#bsky_appview' })).structuredContent.response.profiles;
const did = (handle) => profiles.find((p) => p.handle === handle)?.did ?? (() => { throw new Error(`no profile for ${handle}`); })();
const picked = { me: did(meHandle), dan: did('danabra.mov') };
const answers = {};
for (const entry of entries) {
const nsid = entry.call.name === 'describe_app' ? null : (entry.call.args.method ?? entry.call.args.collection ?? entry.call.args.uri?.split('/')[3]);
if (entry.call.name === 'describe_app') domains.add(entry.call.args.domain);
else if (nsid) domains.add(appOf(nsid));
if (entry.made) continue;
if (entry.pick) {
const from = answers[entry.pick.from]?.structuredContent ?? (() => { throw new Error(`${entry.id} picks from ${entry.pick.from}, not recorded before it`); })();
if ('record' in entry.pick) picked[entry.id] = (from.records[entry.pick.record] ?? from.records[0]).uri;
else {
// A post of the account's own with a few replies and a picture or a link, for its thread.
const posts = from.response.feed.filter((i) => !i.reason && !i.reply).map((i) => i.post);
picked[entry.id] = (posts.find((p) => p.replyCount >= 2 && p.replyCount <= 8 && p.embed) ?? posts.find((p) => p.replyCount > 0) ?? posts[0]).uri;
}
}
const args = filled(entry.call.args, picked);
answers[entry.id] = kept(entry.call.name, args, await call(entry.call.name, args));
console.log(`recorded ${entry.id}`);
}
// What lexicons/ lacks of the methods made-up answers are of: as describe_method gives each, made documents again.
const lexicons = [];
for (const method of new Set(entries.filter((e) => e.made).map((e) => e.call.args.method))) {
if (existsSync(join(root, 'lexicons', `${method}.json`))) continue;
const d = (await call('describe_method', { method })).structuredContent;
const docs = { [method]: { lexicon: 1, id: method, defs: { main: { type: 'query', parameters: d.parameters, output: d.output } } } };
for (const [ref, def] of Object.entries(d.defs ?? {})) {
const [nsid, name = 'main'] = ref.split('#');
(docs[nsid] ??= { lexicon: 1, id: nsid, defs: {} }).defs[name] = def;
}
lexicons.push(...Object.values(docs));
}
book = {
about: 'Recorded by harness/gallery/record.mjs: the answers the gallery draws, public ones as a HUD server answered them to no one, the rest made up by made.mjs. Do not edit.',
me: { did: picked.me, handle: meHandle },
picked,
profiles,
lexicons,
answers
};
// The apps' icons, as the server has them: the tiles' apps', and every one an answer names (a profile's apps); none where it has none.
for (const [, domain] of JSON.stringify(answers).matchAll(/http:\/\/localhost:8787\/icon\/([a-z0-9.-]+)/g)) domains.add(domain);
rmSync(iconsDir, { recursive: true, force: true });
mkdirSync(iconsDir, { recursive: true });
const none = [];
for (const domain of [...domains].sort()) {
const res = await fetch(new URL(`/icon/${domain}`, base));
if (res.ok) writeFileSync(join(iconsDir, `${domain}.png`), Buffer.from(await res.arrayBuffer()));
else none.push(domain);
}
say(`${domains.size - none.length} apps' icons in ${iconsDir}; none for ${none.join(', ') || 'none'}`);
}
// The made-up answers, held to their lexicons.
const args = Object.fromEntries(entries.map((e) => [e.id, filled(e.call.args, book.picked)]));
const byHandle = Object.fromEntries(book.profiles.map((p) => [p.handle, p]));
const mine = made({ me: book.me, people: byHandle, recorded: book.answers, args });
for (const [entryId, result] of Object.entries(mine)) {
const entry = entries.find((e) => e.id === entryId);
result._meta.view = shown(entry.call.name, viewOf(entry.call.name, args[entryId]));
}
const problems = check(lexiconsOf(book.lexicons), mine);
for (const p of problems) say(p);
if (problems.length) process.exit(1);
const missing = entries.filter((e) => e.made && !mine[e.id]).map((e) => e.id);
if (missing.length) throw new Error(`made.mjs makes no answer for ${missing.join(', ')}`);
const answers = Object.fromEntries(entries.map((e) => [e.id, mine[e.id] ?? book.answers[e.id]]));
writeFileSync(answersFile, `${JSON.stringify({ ...book, answers }, null, '\t')}\n`);
say(`${Object.keys(answers).length} answers (${Object.keys(mine).length} made up, each as its lexicon says) in ${answersFile}`);