~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
380 lines · 15.6 KB Raw History
// The dev host: a page that plays an MCP Apps host for the built view, so
// it can be seen without Claude or ChatGPT. It calls a running hud server's
// tools at POST /mcp (Vite proxies it to HUD_URL) in the 2025-11-25 era,
// initialize first; shows the view (/view.html, web/dist/index.html under
// the CSP it builds from the UI resource's metadata, as a host does) in a
// sandboxed iframe, talking to it through AppBridge; passes it the call's
// input and result, and forwards the tool calls the view makes the same
// way. The theme, width and display toggles change the host context as a
// host would; pip is drawn as a frame floating in the corner. It signs in
// as an MCP client does (oauth.ts): signed in, its calls carry the bearer
// token; a call the server answers 401 offers Sign in.

import { AppBridge, PostMessageTransport, type McpUiHostContext } from '@modelcontextprotocol/ext-apps/app-bridge';
import type { CallToolResult, Tool } from '@modelcontextprotocol/client';
import * as oauth from './oauth';

const PROTOCOL = '2025-11-25';

/** Arguments to start from, per tool. Any may also take a `view`, typed in
 * the arguments or in the view box, which goes in as `view`. */
const EXAMPLES: Record<string, Record<string, unknown>> = {
	describe_repo: { actor: 'chadtmiller.com' },
	describe_collection: { actor: 'chadtmiller.com', collection: 'app.bsky.feed.post' },
	describe_method: { method: 'app.bsky.feed.getFeed' },
	list_records: { actor: 'chadtmiller.com', collection: 'social.grain.gallery' },
	get_record: { uri: 'at://chadtmiller.com/app.bsky.actor.profile/self' },
	query: {
		method: 'app.bsky.feed.getFeed',
		params: { feed: 'at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/whats-hot', limit: 10 }
	}
};

const element = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
const form = element<HTMLFormElement>('call');
const select = element<HTMLSelectElement>('tool');
const argsInput = element<HTMLTextAreaElement>('args');
const viewInput = element<HTMLTextAreaElement>('view');
const status = element<HTMLParagraphElement>('status');
const box = element<HTMLDivElement>('frame-box');
const textOut = element<HTMLPreElement>('text');
const log = element<HTMLOListElement>('log');
const who = element<HTMLSpanElement>('who');
const signInButton = element<HTMLButtonElement>('sign-in');
const signOutButton = element<HTMLButtonElement>('sign-out');
const prompt = element<HTMLParagraphElement>('auth-prompt');

let tools: Tool[] = [];
let bridge: AppBridge | null = null;
/** The tool whose call the view on show is drawing. */
let shownTool: Tool | undefined;
let theme: 'light' | 'dark' = 'light';
let nextId = 1;
let session: Promise<string | null> | null = null;
/** Whether a sign-in popup is out. */
let signingIn = false;

type Message = { id?: number; result?: unknown; error?: { code: number; message: string } };

/** The server answered 401: the call needs a sign-in, or a fresh one. */
class SignInNeeded extends Error {}

/** The headers every request to /mcp carries: the bearer token when signed in. */
async function headersFor(sessionId: string | null, initialize: boolean): Promise<Record<string, string>> {
	const headers: Record<string, string> = {
		'Content-Type': 'application/json',
		Accept: 'application/json, text/event-stream'
	};
	if (!initialize) headers['MCP-Protocol-Version'] = PROTOCOL;
	if (sessionId) headers['Mcp-Session-Id'] = sessionId;
	const token = await oauth.bearer();
	if (token) headers.Authorization = `Bearer ${token}`;
	return headers;
}

/** One JSON-RPC request to /mcp, answered as JSON or as an event stream. A
 * 401 for a token the server calls invalid refreshes it and tries once
 * more; any other 401 is SignInNeeded. */
async function post(method: string, params: object, sessionId: string | null, retried = false): Promise<{ message: Message; response: Response }> {
	const id = nextId++;
	const headers = await headersFor(sessionId, method === 'initialize');
	const response = await fetch('/mcp', { method: 'POST', headers, body: JSON.stringify({ jsonrpc: '2.0', id, method, params }) });
	if (response.status === 401) {
		const asked = oauth.challenge(response);
		if (!retried && headers.Authorization && asked?.error === 'invalid_token' && (await oauth.refresh())) return post(method, params, sessionId, true);
		showAccount();
		// What the server asks of the person, as the challenge's body says it.
		const said = await response.json().then(
			(body: { error_description?: unknown }) => (typeof body.error_description === 'string' && body.error_description ? body.error_description : null),
			() => null
		);
		throw new SignInNeeded(`${said ?? 'Sign in to HUD to do this'}: the server answered ${method} with 401${asked?.scope ? ` (scope ${asked.scope})` : ''}.`);
	}
	const body = await response.text();
	if (!response.ok) throw new Error(`${method}: HTTP ${response.status} ${body}`);
	const message = (response.headers.get('content-type') ?? '').includes('text/event-stream') ? fromStream(body, id) : (JSON.parse(body) as Message);
	if (message.error) throw new Error(`${method}: ${message.error.message} (${message.error.code})`);
	return { message, response };
}

/** The response with this id among an event stream's `data:` lines. */
function fromStream(body: string, id: number): Message {
	for (const event of body.split(/\r?\n\r?\n/)) {
		const data = event
			.split(/\r?\n/)
			.filter((line) => line.startsWith('data:'))
			.map((line) => line.slice(5).trimStart())
			.join('\n');
		if (!data) continue;
		const message = JSON.parse(data) as Message;
		if (message.id === id) return message;
	}
	throw new Error('no response in the event stream');
}

/** The session: initialize, then notifications/initialized, once. */
function connect(): Promise<string | null> {
	session ??= (async () => {
		const { response } = await post(
			'initialize',
			{ protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: 'hud-dev-host', version: '0.1.0' } },
			null
		);
		const sessionId = response.headers.get('mcp-session-id');
		await fetch('/mcp', {
			method: 'POST',
			headers: await headersFor(sessionId, false),
			body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })
		});
		return sessionId;
	})().catch((error: unknown) => {
		session = null;
		throw error;
	});
	return session;
}

async function rpc(method: string, params: object): Promise<unknown> {
	const { message } = await post(method, params, await connect());
	return message.result;
}

/** A tool call; a failure to reach the server comes back as a tool error,
 * as a host would show it. One the server answers 401 offers Sign in. */
async function callTool(name: string, args: Record<string, unknown>): Promise<CallToolResult> {
	try {
		return (await rpc('tools/call', { name, arguments: args })) as CallToolResult;
	} catch (error) {
		if (error instanceof SignInNeeded) prompt.hidden = false;
		return { content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }], isError: true };
	}
}

const resultText = (result: CallToolResult) =>
	result.content.map((block) => (block.type === 'text' ? block.text : `[${block.type}]`)).join('\n');

/** Whether the view shows inline or picture-in-picture: the dev host draws
 * pip as a frame floating in the corner. */
let displayMode: 'inline' | 'pip' = 'inline';

function hostContext(tool: Tool | undefined): McpUiHostContext {
	const wide = !box.classList.contains('narrow');
	return {
		theme,
		platform: 'web',
		displayMode,
		availableDisplayModes: ['inline', 'pip'],
		locale: navigator.language,
		timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
		containerDimensions: { width: wide && displayMode === 'inline' ? box.clientWidth : 360, maxHeight: 6000 },
		...(tool ? { toolInfo: { tool } } : {})
	};
}

function setDisplayMode(mode: 'inline' | 'pip') {
	displayMode = mode;
	box.classList.toggle('pip', mode === 'pip');
	const radio = document.querySelector<HTMLInputElement>(`input[name=display][value=${mode}]`);
	if (radio) radio.checked = true;
	bridge?.setHostContext(hostContext(shownTool));
}

/** The view resource's CSP metadata, as `resources/read` gives it. */
type UiCsp = { connectDomains?: string[]; resourceDomains?: string[]; frameDomains?: string[]; baseUriDomains?: string[] };

/** The Content-Security-Policy a host builds from a view resource's
 * `_meta.ui.csp`, by the MCP Apps spec's rules ("Content Security Policy
 * Enforcement"): resource domains for scripts, styles, images, fonts and
 * media; connect domains for connections; nothing else. */
function viewCsp(csp: UiCsp | undefined): string {
	const resources = (csp?.resourceDomains ?? []).join(' ');
	const connects = (csp?.connectDomains ?? []).join(' ');
	return [
		"default-src 'none'",
		`script-src 'self' 'unsafe-inline' ${resources}`,
		`style-src 'self' 'unsafe-inline' ${resources}`,
		`connect-src 'self' ${connects}`,
		`img-src 'self' data: ${resources}`,
		`font-src 'self' ${resources}`,
		`media-src 'self' data: ${resources}`,
		`frame-src ${csp?.frameDomains?.join(' ') || "'none'"}`,
		"object-src 'none'",
		`base-uri ${csp?.baseUriDomains?.join(' ') || "'self'"}`
	]
		.map((directive) => directive.trim())
		.join('; ');
}

/** The CSP for the view the tool names: read its UI resource, as a host does
 * before it renders one. */
async function cspFor(tool: Tool | undefined): Promise<string> {
	const meta = tool?._meta as { ui?: { resourceUri?: string } } | undefined;
	const uri = meta?.ui?.resourceUri ?? 'ui://records/view';
	const { contents } = (await rpc('resources/read', { uri })) as { contents: { _meta?: { ui?: { csp?: UiCsp } } }[] };
	return viewCsp(contents[0]?._meta?.ui?.csp);
}

/** A fresh view for a call, as a host renders one per tool call. */
async function run(name: string, args: Record<string, unknown>) {
	const tool = tools.find((t) => t.name === name);
	shownTool = tool;
	const csp = await cspFor(tool);
	// The view on show is torn down as a host does, so it can send what it
	// holds (feed interactions); those calls head the log of the next.
	log.replaceChildren();
	await bridge?.teardownResource({}).catch(() => undefined);
	await bridge?.close();
	textOut.textContent = '';
	const iframe = document.createElement('iframe');
	iframe.title = 'HUD view';
	iframe.sandbox.add('allow-scripts');
	box.replaceChildren(iframe);
	const view = iframe.contentWindow;
	if (!view) throw new Error('the iframe has no window');

	const next = new AppBridge(null, { name: 'hud-dev-host', version: '0.1.0' }, { openLinks: {}, serverTools: {}, logging: {} }, { hostContext: hostContext(tool) });
	next.oncalltool = async (params) => {
		const item = document.createElement('li');
		const call = `${new Date().toLocaleTimeString()} ${params.name} ${JSON.stringify(params.arguments ?? {})}`;
		item.textContent = `${call} …`;
		log.append(item);
		const result = await callTool(params.name, params.arguments ?? {});
		item.textContent = `${call}${result.isError ? ' → error' : ''}: ${resultText(result)}`;
		return result;
	};
	next.onopenlink = async ({ url }) => {
		window.open(url, '_blank', 'noopener,noreferrer');
		return {};
	};
	next.onsizechange = ({ height }) => {
		if (height !== undefined) iframe.style.height = `${height}px`;
	};
	next.onrequestdisplaymode = async ({ mode }) => {
		if (mode === 'inline' || mode === 'pip') setDisplayMode(mode);
		return { mode: displayMode };
	};
	next.onloggingmessage = (params) => console.log('[view]', params.level, params.data);
	const initialized = Promise.withResolvers<void>();
	next.oninitialized = () => initialized.resolve();
	bridge = next;
	await next.connect(new PostMessageTransport(view, view));
	iframe.src = `/view.html?csp=${encodeURIComponent(csp)}`;
	await initialized.promise;

	status.textContent = `Calling ${name}…`;
	await next.sendToolInput({ arguments: args });
	const result = await callTool(name, args);
	status.textContent = `${name}: ${result.isError ? 'error' : 'done'}`;
	textOut.textContent = resultText(result);
	await next.sendToolResult(result);
}

function setTool(name: string) {
	select.value = name;
	argsInput.value = JSON.stringify(EXAMPLES[name] ?? {}, null, 2);
}

form.addEventListener('submit', (event) => {
	event.preventDefault();
	let args: Record<string, unknown>;
	try {
		args = JSON.parse(argsInput.value || '{}') as Record<string, unknown>;
	} catch (error) {
		status.textContent = `Arguments are not JSON: ${error instanceof Error ? error.message : String(error)}`;
		return;
	}
	if (viewInput.value.trim()) {
		try {
			args.view = JSON.parse(viewInput.value) as unknown;
		} catch (error) {
			status.textContent = `The view is not JSON: ${error instanceof Error ? error.message : String(error)}`;
			return;
		}
	}
	run(select.value, args).catch((error: unknown) => (status.textContent = String(error)));
});

select.addEventListener('change', () => setTool(select.value));

for (const input of document.querySelectorAll<HTMLInputElement>('input[name=theme]')) {
	input.addEventListener('change', () => {
		theme = input.value === 'dark' ? 'dark' : 'light';
		document.documentElement.dataset.theme = theme;
		bridge?.setHostContext(hostContext(shownTool));
	});
}

for (const input of document.querySelectorAll<HTMLInputElement>('input[name=width]')) {
	input.addEventListener('change', () => {
		box.classList.toggle('narrow', input.value === 'narrow');
		bridge?.setHostContext(hostContext(shownTool));
	});
}

for (const input of document.querySelectorAll<HTMLInputElement>('input[name=display]')) {
	input.addEventListener('change', () => setDisplayMode(input.value === 'pip' ? 'pip' : 'inline'));
}

/** The server's tools, for the menu; the read tools by name when it is down. */
async function loadTools() {
	try {
		const { tools: listed } = (await rpc('tools/list', {})) as { tools: Tool[] };
		tools = listed;
		status.textContent = `Connected to ${location.origin}/mcp: ${tools.length} tools.`;
	} catch (error) {
		status.textContent = `No hud server answered at /mcp (${error instanceof Error ? error.message : String(error)}). Start one, or set HUD_URL for npm run dev.`;
	}
	const names = tools.length > 0 ? tools.map((t) => t.name) : Object.keys(EXAMPLES);
	select.replaceChildren(...names.map((name) => new Option(name, name)));
	setTool(names.includes('list_records') ? 'list_records' : names[0]);
}

/** The account line: who is signed in (the token response's `sub`), and
 * Sign in, Cancel or Sign out. */
function showAccount(message?: string) {
	const current = oauth.session();
	who.textContent = message ?? (signingIn ? 'Signing in: finish in the window that opened.' : current ? `Signed in as ${current.sub ?? 'an account'}` : 'Signed out');
	signInButton.hidden = current !== null && !signingIn;
	signInButton.textContent = signingIn ? 'Cancel' : 'Sign in';
	signOutButton.hidden = current === null || signingIn;
	if (current) prompt.hidden = true;
}

/** Sign in, from a click: the popup opens now, before any await, so no
 * popup blocker stops it. A new token starts a new MCP session. */
async function signIn() {
	if (signingIn) {
		oauth.cancelSignIn();
		return;
	}
	const popup = window.open('about:blank', 'hud-sign-in', 'popup,width=520,height=760');
	if (!popup) {
		showAccount('The browser blocked the sign-in window.');
		return;
	}
	signingIn = true;
	showAccount();
	try {
		await oauth.signIn(popup);
		session = null;
		signingIn = false;
		showAccount();
	} catch (error) {
		signingIn = false;
		showAccount(error instanceof Error ? error.message : String(error));
	}
}

async function signOut() {
	await oauth.signOut();
	session = null;
	showAccount();
}

for (const button of [signInButton, element<HTMLButtonElement>('prompt-sign-in')]) {
	button.addEventListener('click', () => void signIn());
}
signOutButton.addEventListener('click', () => void signOut());

showAccount();
void loadTools();