~ 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
113 lines · 4.9 KB Raw History
// HUD's tools as an app's pages call them: through the app's own server,
// at the host's `mcp` endpoint, which holds the account's tokens (the
// browser holds only a session cookie) and calls HUD's /mcp with them; and
// a picture uploaded through its `upload` endpoint, which it hands HUD's
// `place.hud.uploadBlob` the same way. Signed out, calls are made as no
// one: public data only, and a tool that needs an account throws
// `SignInNeeded`. A server's own calls send HUD the request `toolRequest`
// builds, and read its answer with `toolResult`.

import type { ToolResult } from '@hud/shared/result';
import pkg from '../package.json' with { type: 'json' };

/** The MCP protocol version every call names, as HUDKit's `HUDClient` does. */
const VERSION = '2026-07-28';

/** The HUD SDK's version this shell was built as: its package's, which HUD's release sets. */
const KIT = pkg.version;

/** Where the app's server takes its pages' calls: HUD's tools (`{name, args}` posted as JSON, the result answered; 401 to sign in) and uploads (the bytes posted, `{blob}` answered). */
export type Endpoints = { mcp: string; upload: string };

/** The call needs an account: sign in first. */
export class SignInNeeded extends Error {
	constructor() {
		super('Sign in to see this.');
	}
}

/** A `tools/call` to HUD's /mcp, statelessly: each request names its protocol version, method and tool in headers and `_meta`, so there is no session to open, and in `_meta` the kit and its version (`place.hud/kit`), so HUD draws for what it knows. */
export function toolRequest(name: string, args: Record<string, unknown>, token: string | null): RequestInit {
	const headers: Record<string, string> = {
		'Content-Type': 'application/json',
		Accept: 'application/json, text/event-stream',
		'MCP-Protocol-Version': VERSION,
		'Mcp-Method': 'tools/call',
		'Mcp-Name': name
	};
	if (token) headers.Authorization = `Bearer ${token}`;
	const body = JSON.stringify({
		jsonrpc: '2.0',
		id: 1,
		method: 'tools/call',
		params: {
			name,
			arguments: args,
			_meta: {
				'io.modelcontextprotocol/protocolVersion': VERSION,
				'io.modelcontextprotocol/clientInfo': { name: 'hud-web', version: KIT },
				'io.modelcontextprotocol/clientCapabilities': { extensions: { 'place.hud/kit': { platform: 'web', version: KIT } } }
			}
		}
	});
	return { method: 'POST', headers, body };
}

/** What HUD's /mcp answered a `tools/call`: its result, failures included (`isError`); throws `SignInNeeded` on a 401, and with why when there is no result at all. */
export async function toolResult(res: Response): Promise<ToolResult> {
	if (res.status === 401) throw new SignInNeeded();
	const answer = (await res.json().catch(() => null)) as { result?: ToolResult; error?: { message?: string } } | null;
	if (answer?.error) throw new Error(answer.error.message ?? 'HUD refused the call.');
	if (!answer?.result) throw new Error(`HUD answered ${res.status} with no result.`);
	return answer.result;
}

/** HUD's tools and uploads from the browser, through the app's server. */
export class Client {
	readonly #endpoints: Endpoints;

	constructor(endpoints: Endpoints) {
		this.#endpoints = endpoints;
	}

	/** One of HUD's tools. */
	async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {
		const res = await fetch(this.#endpoints.mcp, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ name, args })
		});
		if (res.status === 401) throw new SignInNeeded();
		const answer = (await res.json().catch(() => null)) as ToolResult | { message?: string } | null;
		if (!res.ok) throw new Error((answer as { message?: string } | null)?.message ?? `The call failed: HTTP ${res.status}.`);
		if (!answer) throw new Error('The server answered with no result.');
		return answer as ToolResult;
	}

	/** A picture's bytes uploaded as the account, telling `onprogress` how much has gone, from 0 to 1: the blob ref its PDS answered. */
	uploadBlob = (bytes: Blob, onprogress: (fraction: number) => void): Promise<unknown> => {
		const { promise, resolve, reject } = Promise.withResolvers<unknown>();
		const request = new XMLHttpRequest();
		request.open('POST', this.#endpoints.upload);
		request.setRequestHeader('Content-Type', bytes.type || 'application/octet-stream');
		request.upload.onprogress = (event) => {
			if (event.lengthComputable) onprogress(event.loaded / event.total);
		};
		request.onload = () => {
			const answer = (() => {
				try {
					return JSON.parse(request.responseText) as { blob?: unknown; message?: string };
				} catch {
					return null;
				}
			})();
			if (request.status === 401) reject(new SignInNeeded());
			else if (request.status !== 200) reject(new Error(answer?.message ?? `HUD answered ${request.status}.`));
			else if (!answer?.blob) reject(new Error('HUD answered the upload without its blob.'));
			else resolve(answer.blob);
		};
		request.onerror = () => reject(new Error('The upload could not reach the server.'));
		request.send(bytes);
		return promise;
	};
}