~ 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
64 lines · 2.5 KB Raw History
// People's faces and names, for the avatars of who is here, of a tile's
// author and of a canvas's members: their Bluesky profiles, read through
// HUD's `query` tool (app.bsky.actor.getProfiles, from the AppView), asked
// for once per DID, in batches, and kept for the page's life. Someone with
// no profile there shows as their handle's first letter.

import { SvelteMap } from 'svelte/reactivity';
import { callTool } from './tools';

export type Profile = { did: string; handle: string | null; name: string | null; avatar: string | null };

/** The most actors getProfiles takes at once. */
const BATCH = 25;
/** Bluesky's AppView, which answers getProfiles (no bundled view names it). */
const APPVIEW = 'did:web:api.bsky.app#bsky_appview';

const known = new SvelteMap<string, Profile>();
const asked = new Set<string>();
let queued: string[] = [];
let scheduled = false;

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

async function fetchBatch(dids: string[]) {
	try {
		const result = await callTool('query', { method: 'app.bsky.actor.getProfiles', params: { actors: dids }, service: APPVIEW });
		const data = result.structuredContent;
		const response = isObject(data) && isObject(data.response) ? data.response : {};
		for (const found of Array.isArray(response.profiles) ? response.profiles : []) {
			if (!isObject(found) || typeof found.did !== 'string') continue;
			const handle = typeof found.handle === 'string' && found.handle !== 'handle.invalid' ? found.handle : null;
			const profile: Profile = {
				did: found.did,
				handle,
				name: typeof found.displayName === 'string' && found.displayName.trim() ? found.displayName : null,
				avatar: typeof found.avatar === 'string' ? found.avatar : null
			};
			known.set(found.did, profile);
			// Asked for by handle (a profile tile's actor), it is found by it.
			if (handle && asked.has(handle)) known.set(handle, profile);
		}
	} catch {
		// No faces: the letters stand in.
	}
}

/** The profile known for a DID (or a handle), asking for it the first
 * time; undefined until it comes, or when there is none. Reactive. */
export function profile(did: string): Profile | undefined {
	if (!asked.has(did)) {
		asked.add(did);
		queued.push(did);
		if (!scheduled) {
			scheduled = true;
			queueMicrotask(() => {
				scheduled = false;
				const all = queued;
				queued = [];
				for (let i = 0; i < all.length; i += BATCH) void fetchBatch(all.slice(i, i + BATCH));
			});
		}
	}
	return known.get(did);
}