~ 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
238 lines · 10.7 KB Raw History
// What HUD's apps make of a tool result: its view, resolved by the server
// (`_meta.ui`), drawn by `Tree`; or a failure. With it, the signed-in
// account it was made for (`_meta.viewer`), the feed its tree reports to,
// and the calls that come next from it: a page more, a record opened.
// Nothing here knows how a call is made: the MCP App view (web/src) makes
// them through its host, the workspace (web/workspace) through HUD's
// appview, its callTool method.

import type { ActionArgs, ActionResult, UiLatest, UiNode, UiReport, UiTree } from '@hud/renderer';
import type { Interaction, Sent } from './interactions';

/** A tool result as the host passes it, of which the view reads only this. */
export type ToolResult = {
	content?: unknown[];
	structuredContent?: unknown;
	isError?: boolean;
	_meta?: Record<string, unknown>;
};

/** A tool call: its name and arguments. */
export type Call = { name: string; args: Record<string, unknown> };

/** What one result is drawn as: a tree, with the answer it was resolved
 * from (`structuredContent`, which the apps' chrome reads: a page's account
 * and collection, a query's method, an account's repository, a tile's label
 * and preview); or a failure. */
export type View = { renderer: 'tree'; ui: UiTree; data: unknown } | { renderer: 'error'; message: string };

/** A step of the back stack: what shows, and the call that brought it, when
 * the view knows it (the host's own call, it may not). */
export type Entry = { view: View; call: Call | null };

/** The account a result was made for, when the call was signed in. */
export type Viewer = { did: string; handle: string | null };

const isObject = (value: unknown): value is Record<string, unknown> =>
	typeof value === 'object' && value !== null && !Array.isArray(value);

/** The text blocks of a result's content, joined: its summary, or for a
 * failure, what went wrong. */
export function text(result: ToolResult): string {
	return (result.content ?? [])
		.flatMap((block) => (isObject(block) && block.type === 'text' && typeof block.text === 'string' ? [block.text] : []))
		.join('\n');
}

/** The signed-in account `_meta.viewer` names, or null: a result made with
 * no session carries none. */
export function viewer(result: ToolResult): Viewer | null {
	const found = result._meta?.viewer;
	if (!isObject(found) || typeof found.did !== 'string') return null;
	return { did: found.did, handle: typeof found.handle === 'string' && found.handle !== '' ? found.handle : null };
}

/** The view a result asks for. A failure, or a result the view cannot read,
 * is an error with the words the server sent. */
export function read(result: ToolResult): View {
	if (result.isError) return { renderer: 'error', message: text(result) || 'The tool call failed.' };
	const data = result.structuredContent;
	const meta = result._meta ?? {};
	if (isObject(meta.ui) && meta.ui.v === 1 && isObject(meta.ui.root)) return { renderer: 'tree', ui: { ...(meta.ui as UiTree), trusted: meta.ui.trusted === true }, data };
	const summary = text(result);
	return { renderer: 'error', message: `This result has no view HUD can draw.${summary ? `\n\n${summary}` : ''}` };
}

/** The page of records a tree was resolved from (`list_records`,
 * `get_record`): its account and collection; null for any other. */
export function pageOf(view: View): { did: string; handle: string | null; collection: string } | null {
	const data = view.renderer === 'tree' ? view.data : null;
	if (!isObject(data) || !Array.isArray(data.records) || typeof data.did !== 'string' || typeof data.collection !== 'string') return null;
	return { did: data.did, handle: typeof data.handle === 'string' ? data.handle : null, collection: data.collection };
}

/** The method of the query a tree was resolved from, or null. */
export function methodOf(view: View): string | null {
	const data = view.renderer === 'tree' ? view.data : null;
	return isObject(data) && typeof data.method === 'string' ? data.method : null;
}

/** An account's repository, as `describe_repo` answers it: who it is, where
 * it lives, the collections it holds records in, its Bluesky profile record
 * (`app.bsky.actor.profile/self`) when HUD could read one, and the
 * collections it holds that a bundled view draws, each with the view's
 * description. */
export type Account = {
	did: string;
	handle: string | null;
	pds: string;
	collections: string[];
	profile: { uri: string; cid: string; value: Record<string, unknown> } | null;
	views: { collection: string; description: string }[];
};

/** The account a tree was resolved from (`describe_repo`), or null. */
export function accountOf(view: View): Account | null {
	const data = view.renderer === 'tree' ? view.data : null;
	if (!isObject(data) || typeof data.did !== 'string' || typeof data.pds !== 'string' || !Array.isArray(data.collections)) return null;
	return {
		did: data.did,
		handle: typeof data.handle === 'string' ? data.handle : null,
		pds: data.pds,
		collections: data.collections.filter((nsid): nsid is string => typeof nsid === 'string'),
		profile: isObject(data.profile) && isObject(data.profile.value) ? (data.profile as Account['profile']) : null,
		views: Array.isArray(data.views) ? (data.views as Account['views']) : []
	};
}

/** The call for the page after an entry's: the tree's `next`. */
export function nextPage(entry: Entry): Call | null {
	return entry.view.renderer === 'tree' ? (entry.view.ui.next ?? null) : null;
}

/** How to tell something newer came than an entry's items: its tree's
 * `latest`, where its view names each item's key. */
export function latestOf(view: View): UiLatest | null {
	return view.renderer === 'tree' ? (view.ui.latest ?? null) : null;
}

/** Whether `peeked`, what `latest.call` answered, has an item whose key
 * none of `latest`'s items has: one newer than those drawn (not a pinned
 * post, which was drawn too). */
export function isNewer(peeked: View, latest: UiLatest): boolean {
	const drawn = new Set(latest.items.map((item) => item.key));
	return (latestOf(peeked)?.items ?? []).some((item) => !drawn.has(item.key));
}

/** Whether an entry's tree asks for its page more in its own place (a
 * conversation, `Messages`, its earlier messages at its top): the app
 * draws no "Load more" after it, but hands it the paging. */
export function ownsPaging(entry: Entry): boolean {
	return entry.view.renderer === 'tree' && entry.view.ui.root.c === 'Messages';
}

/** The feed a tree tells what is done with its items: its at-uri, whether
 * seen and opened items are told (a result made signed in), and an item's
 * interaction for an event (its item the report the server read). Null for
 * a view that tells no feed. */
export type Feed = { feed: string; signedIn: boolean; of: (event: string, item: unknown) => Interaction | null };

export function feedOf(view: View): Feed | null {
	if (view.renderer !== 'tree') return null;
	const to = view.ui.report;
	if (!to || typeof to.feed !== 'string') return null;
	return { feed: to.feed, signedIn: to.seen === true, of: (event, item) => (isObject(item) ? { ...(item as UiReport), event } : null) };
}

/** The tool each kind of a tree's action is: a record created or deleted,
 * or a procedure called. */
export const ACTION_TOOLS = { create: 'create_record', delete: 'delete_record', call: 'call_procedure' } as const satisfies Record<keyof ActionArgs, string>;

/** What an action's result is to the tree: the at-uri a `create_record`
 * made, a `call_procedure`'s answer (its `output`); a failure throws with
 * the server's words. */
export function acted(kind: keyof ActionArgs, result: ToolResult): ActionResult {
	if (result.isError) throw new Error(text(result) || 'The action failed.');
	const data = isObject(result.structuredContent) ? result.structuredContent : {};
	if (kind === 'call') return { uri: null, output: data.output };
	return { uri: kind === 'create' && typeof data.uri === 'string' ? data.uri : null };
}

/** What a tool a tree's form calls (`query`, `apply_writes`, `link_card`,
 * `find_place`) answers it: its `structuredContent`; a failure throws with
 * the server's words. */
export function answered(result: ToolResult): unknown {
	if (result.isError) throw new Error(text(result) || 'The tool failed.');
	return result.structuredContent ?? null;
}

/** What a `send_interactions` result says: how many went, or why none did. */
export function sent(result: ToolResult): Sent {
	const data = result.structuredContent;
	return {
		sent: isObject(data) && typeof data.sent === 'number' ? data.sent : 0,
		reason: isObject(data) && typeof data.reason === 'string' ? data.reason : null
	};
}

/** A tree with a next page's items added to its page list, and the next
 * page's `next`; null when the page is not of it. A new view, its page list
 * a new array holding the same items, so an app holding views as they are
 * read (never deeply reactive) draws it by replacing the old: the lists
 * drawn from it grow, what was drawn stays, and a player playing from it
 * goes on playing. */
export function append(view: View, next: View): View | null {
	if (view.renderer !== 'tree' || next.renderer !== 'tree') return null;
	const more = pageList(next.ui.root)?.items ?? null;
	const root = more && withPage(view.ui.root, more);
	if (!root) return null;
	return { ...view, ui: { ...view.ui, root, next: next.ui.next } };
}

/** Whether a node is a tree's page list: `p.page` and `items` (a `List`, or
 * one that lists a page's records as cards, pictures or tracks). */
const isPage = (node: UiNode) => node.p?.page === true && Array.isArray(node.items);

/** The page list of a tree, which a page more appends to, or null. */
function pageList(node: UiNode): UiNode | null {
	if (isPage(node)) return node;
	for (const child of node.k ?? []) {
		const found = pageList(child);
		if (found) return found;
	}
	return null;
}

/** A tree with its page list's items and `more` after them: a new node on
 * the way down to it, the rest as it was (drawn, it stays drawn); null when
 * it has no page list. */
function withPage(node: UiNode, more: NonNullable<UiNode['items']>): UiNode | null {
	if (isPage(node)) return { ...node, items: [...(node.items ?? []), ...more] };
	const k = node.k;
	if (!k) return null;
	for (const [i, child] of k.entries()) {
		const grown = withPage(child, more);
		if (grown) return { ...node, k: k.map((c, j) => (j === i ? grown : c)) };
	}
	return null;
}

/** What the loading state says while a tool runs. */
export function loadingLabel(name: string | undefined): string {
	switch (name) {
		case 'describe_repo':
			return 'Loading repository…';
		case 'describe_collection':
			return 'Loading collection…';
		case 'describe_method':
			return 'Loading method…';
		case 'query':
			return 'Asking the service…';
		case 'list_records':
			return 'Loading records…';
		case 'get_record':
			return 'Loading record…';
		default:
			return 'Loading…';
	}
}