wiki-formant
Provides optional integration for uploads via @vercel/blob, allowing the wiki server to store and retrieve blobs using Vercel Blob storage.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
wiki-formant
The portable half of a wiki: a page store, derived taxonomy, a spec-correct MCP transport, markdown twins, block rendering and editing, and the conditional-GET plumbing an agent surface needs.
The editor, history, sanitiser, chart and passkey modules bring their libraries as dependencies (@tiptap/*, fast-diff, sanitize-html, lightweight-charts, @simplewebauthn/*). What only some apps use is an optional peer: pg, react, jose and @radixdlt/rola for ROLA, sharp and @vercel/blob for uploads. Web-standard Request/Response throughout, so it runs on Next route handlers, Hono, Bun, Deno and workers.
npm install wiki-formantAn agent can start a wiki for you, hosted on miow.me or in your own app, with the skill in skills/wiki-formant: npx skills add tutmoses/wiki-formant.
What stays the app's: its design system, its block types beyond the core, its connection, cache and auth. Everything else here is shared.
API
Every module has a subpath (wiki-formant/taxonomy, wiki-formant/mcp, …) and there is no root export: a barrel loads every module for the one symbol a route wanted. The emitted .d.ts files are the reference; this README shows one use of each subpath and the rules a signature cannot say. A function a module uses only itself is marked @internal and left out of the .d.ts.
wiki-formant/tsconfig.base.json is the compiler floor: an app's tsconfig.json extends it and keeps only paths, include, exclude and any licensed extra, since tsconfig resolves those against the file that declares them.
{ "extends": "wiki-formant/tsconfig.base.json", "compilerOptions": { "paths": { "@/*": ["./src/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "src/app/.well-known/**/*.ts", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"], "exclude": ["node_modules"] }Related MCP server: census-mcp
Store
wiki-formant/store: wikiStore reads and writes WikiPage and WikiRevision through one Sql function the app binds to its own client, scoped to one site.
import { wikiStore } from 'wiki-formant/store';
const store = wikiStore({
sql: (query, ...values) => prisma.$queryRawUnsafe(query, ...values),
siteId: '', // a multi-tenant app passes the site's key
hidden: tree.hiddenPaths, // back office: never listed unasked
});
const page = await store.get('contents/tech', 'radix-engine');
const { items, total } = await store.search('validators', { take: 20 });
await store.save({ tagPath, slug, content, authorId, message, baseVersion: page.version });A save is one statement: the page update and its revision in a CTE guarded on the version read. A lost race, a stale
baseVersion, a page deleted since or a rename onto a taken slug writes nothing and throws a 409HttpErrorwhose body names the reason asconflict:staleanddeletedmean reload,takenmeans another slug (ConflictReason).The bump is the diff's: added, removed or moved blocks are
major, changed prose or titleminor;changeoverrides it. A metadata-only save moves no version and writes no revision.History is diffed on read. A revision stores the page as saved.
history(pageId, { limit })reads one row more than it returns, so the oldest entry shown has its real predecessor.Listings carry a snippet, not the article:
list,recentandbyIdsdropcontent, and carrybanner, the page's picture for its card (metadata.banner, or thebanneroption's reading).Search is four tiers: title prefix, title, literal prose, then full text on
search_tsvwith Postgres' headline as the snippet. Hidden paths, and paths under them, are left out unless named.branchis an agent's walk of a path and everything under it;countsis pages per tag path.Copy the models with
npx prisma-models wiki(--tenantfor a tenant-keyed copy), then build the full-text column withnpx fts-ddl '"WikiPage"'.
Tree
wiki-formant/tree: the category tree a wiki declares, and its walks.
import { createTree, parseWikiPath } from 'wiki-formant/tree';
const tree = createTree(NODES, { globalKeys: [QUALITY] });
tree.resolve('contents/tech'); // { node, trail, valid, hidden, sort, mainArticle, metadataKeys }
parseWikiPath(tree, ['contents', 'tech', 'radix-engine', 'history']);
// { type: 'page', tagPath: 'contents/tech', slug: 'radix-engine', mode: 'history' }Metadata keys accumulate down the trail;
sort,mainArticleandhiddeninherit, the nearest declaration winning. A field only one wiki reads rides on the node.A path that is itself a category wins over a mode suffix. The empty slug is a category's hub article.
crumbsmakes one crumb per URL segment, linked only where the tree knows it.
Category view
wiki-formant/category: a category page from the tree, the taxonomy and anything that reads like the store.
import { categoryView } from 'wiki-formant/category';
const view = await categoryView({ tree, taxonomy, pages: store }, 'ecosystem', searchParams);
// { sort, total, pages, all, filters, letter, facets, letters, sortable, clearHref, sortHref, sections }A link carries sort only when it is not the category's default, so the bare category and its default are one address.
Wiki read tools
wiki-formant/wiki-tools: the read half of a wiki's MCP server: search_wiki, get_page, get_pages, list_pages, get_categories, get_recent_changes, get_full_corpus and get_page_history. searchWiki is the same rows for a plain-GET ?q= and a search page.
import { wikiReadTools, searchWiki, type CorpusSection } from 'wiki-formant/wiki-tools';
const reading = { store, tree, url: (tagPath, slug) => `${SITE}/${tagPath}/${slug}`, text: extractText, noun: 'the Radix Wiki', corpusTitle: 'Radix Wiki' };
const tools = [...wikiReadTools(reading), ...myOwnTools];
const { items, total } = await searchWiki(reading, 'validators', { page: 1, size: 20 });Every row carries
path, which every read tool takes back, itsid(what apageListblock takes), andcharswhere the text was read. A pasted URL resolves, withpathPrefixstripped; a miss names the nearest pages.get_pagewithblocks: truereturns the stored blocks,id, metadata andversion: what an edit starts from.forEditadds the app's own edit fields;authorsnames revision authors.textshould be the twin's serializer andresolvethe page's live resolver, so a page reads the same over MCP as at its twin.get_full_corpusis asizeOnlypreflight, then page-aligned slices undermaxChars(CORPUS_BUDGET) withtruncated,nextSkipandclippedPage.corpusreturns the app's ownCorpusSections.privateHiddencloses the back office to every tool.metadata,label,noMatchandskillsare the app's.onSearchhears each first-pagesearch_wikiquery, except one narrowed bytagPaththat found nothing; pass the tracker'strackSearchunderMCP_SURFACEand the stats page lists what agents searched for.Writes stay with each app.
Taxonomy
wiki-formant/taxonomy: the cross-cutting browsing axis derived from the select metadata pages already carry. The tree is yours; supply getMetadataKeys and one href builder.
import { createTaxonomy } from 'wiki-formant/taxonomy';
const taxonomy = createTaxonomy({
getMetadataKeys: tagPath => TAGS[tagPath]?.metadataKeys ?? [],
href: (tagPath, { sort, filters, letter }) => /* your URL contract */,
});
const state = { sort, filters, letter: taxonomy.resolveLetter(all, filters, query.letter) };
const groups = taxonomy.facetControls('ecosystem', all, state); // [{ key, label, options }]
const letters = taxonomy.alphaControls('ecosystem', all, state); // [] below the thresholdEach facet is counted over the set narrowed by every other filter, so its options stay switchable.
Values come from the data, not the declared
options. A single-valued facet hides unless it is active.Every control is
{ value, label, count, href, active }with every other axis carried inhref. The reset control leads the row, flaggedreset.alphaControlsis[]belowneedsAlphaIndex(40 pages unlessalphaIndexMinPages);resolveLetterdrops a letter no page starts with.metadataRowsreturns a page's populated keys as rows withhrefon the facet ones;rankRelatedranks by shared facet values and returns the shared axis for the See also heading.
Headings
wiki-formant/headings: heading ids, permalink anchors, and the list an "on this page" rail renders.
import { articleHtml, headingsFrom } from 'wiki-formant/headings';
const used = new Set([slug(page.title)]);
const blocks = page.blocks.map(b => ({ ...b, text: articleHtml(b.text, { used, links: { selfHost: 'radix.wiki' } }) }));
const toc = headingsFrom(blocks.map(b => b.text).join('')); // [{ id, text, level }]injectHeadingIdsis idempotent;slugis a parameter, since a heading id is a published URL.Pass one
usedset across a page's blocks, seeded with ids the template renders, or a repeated heading mints a duplicate id.articleHtmlis the render-path chain: heading ids,scrollTables, and withlinksthe link pass: an internal link losestargetandrel, an external one gets them, and a bare-URL anchor gets readable text.
MCP
wiki-formant/mcp: a Model Context Protocol server over Streamable HTTP.
import { mcpResponse, mcpGet, mcpOptions, McpToolError } from 'wiki-formant/mcp';
import { MCP_RATE_LIMIT } from 'wiki-formant/rate-limit';
const config = {
serverInfo: { name: 'my-wiki', version: '1.4.0' },
instructions: 'Call search_pages first; get_page needs a full path.',
docsUrl: 'https://example.com/llms.txt',
tools: [{
name: 'search_pages',
description: 'Full-text search across the wiki.',
inputSchema: { type: 'object', properties: { q: { type: 'string', description: 'query' } }, required: ['q'] },
annotations: { readOnlyHint: true },
handler: async ({ q }) => search(String(q)),
}],
rateLimit: MCP_RATE_LIMIT,
onCall: (req, body) => track(req, body),
};
export const POST = (req: Request) => mcpResponse(req, config);
export const GET = () => mcpGet(config.docsUrl);
export const OPTIONS = () => mcpOptions();A caller-fixable mistake is a tool result with
isError, never-32603: bad arguments name every bad field, quote legal values and append the schema. ThrowMcpToolError(message, details)from a handler for the same.Capabilities, and the
-32601method list, advertise only what the config populates.A notification-only POST is a bare
202; malformed JSON is-32700with a400;GETis an explicit 405 with CORS; the preflight allow-list andAccess-Control-Expose-Headerscover what MCP clients send and read.Batches are capped (
DEFAULT_MAX_BATCH, 20) and refused from 2025-06-18 on.Both protocol eras on one endpoint: a request with
io.modelcontextprotocol/protocolVersioninparams._metais served as2026-07-28(server/discover, per-request version checks,resultTypeand cache hints); everything else is the legacy era, which echoes a supported client version. Every response carriesMCP-Protocol-Version.The A2A call an agent card invites (
message/send,SendMessage) is answered from the toolanswernames.rateLimit: { capacity, refillPerSec }is enforced before the body is parsed, withRateLimit-*headers on every answer;mcpRateLimited(sec)is the JSON-RPC 429.Every object a handler returns comes back as
structuredContentbeside the text;outputSchemais the stronger contract when declared.inputSchema.requireOneOfnames a set of which one must be present.A handler's second argument is its context:
ctx.meta(the request'sparams._meta) andctx.setMeta(key, value)(ontoresult._meta).config.gateis envelope-level middleware, for a payment gate whose demand replaces the call.readArgsreads raw arguments as typed, clamped values and records every override;withAdjustmentsputs them on the result asadjustments.feedbackTool(record, noun)issend_feedback. Listed,initializeappendsFEEDBACK_INVITEand an emptylistEnvelopepage or anMcpToolErrorcarries a one-line pointer to it.
Markdown twins
wiki-formant/markdown: htmlToMarkdown keeps the structure an agent cites by (headings, lists, tables, code, emphasis); markdownDocument adds the frontmatter.
import { htmlToMarkdown, markdownDocument } from 'wiki-formant/markdown';
import { markdownHeaders, cacheTagHeaders, VARY_ACCEPT } from 'wiki-formant/http';
return notModified(request, etag, lastModified) ?? new Response(
markdownDocument(
{ title: page.title, url, updated: page.updatedAt, lastVerified: page.lastVerifiedAt, license },
blocksToMarkdown(page.content),
),
{ headers: markdownHeaders(lastModified, { etag, noindex: true, extra: { ...VARY_ACCEPT, ...cacheTagHeaders(pageTag(path)) } }) },
);Tables convert first, ordered lists number per list, cell pipes are escaped, and a headerless table gets a header.
noindexis for a twin of an HTML page; a document with no HTML page (AGENTS.md) leaves it off.cacheTagHeaders(tags)with the tags the save path revalidates, or the CDN holds a route handler's twin past every save. The same goes forllms.txt, a search index and a sitemap.Next drops a rewrite destination's query string, so a twin rewrite carries the
.mdextension through to its destination.
Conditional GET and route errors
wiki-formant/http: validators, the headers of every text surface, and the answers a route gives when it is not answering with data.
import { corpusValidatorsFrom, corpusRoute, errors, handleRoute, HttpError } from 'wiki-formant/http';
export const GET = corpusRoute(async () => {
const agg = await prisma.page.aggregate({ _count: true, _max: { updatedAt: true } });
return corpusValidatorsFrom([agg._count], [agg._max.updatedAt]);
}, buildCorpus);
export const POST = (req: Request) => handleRoute(async () => {
const q = new URL(req.url).searchParams.get('q');
if (!q) return errors.badRequest('q is required');
if (q.length > 200) throw new HttpError(400, 'q is too long', { code: 'INVALID_PARAMS' });
return Response.json(await search(q));
}, 'Search failed');corpusEtag,notModifiedandtextHeadersare the parts;corpusRouteskips the build on a 304.A URL answering JSON or markdown by
AcceptaskswantsMarkdown(request)and sendsVARY_ACCEPTon both branches.descriptorResponseserves a JSON descriptor with its own ETag andAccess-Control-Allow-Origin: *.Every error body is
{ error, ...extra }. A thrownHttpErroranswers with its status, a thrownResponse(errors.tooManyRequests(sec), say) is the answer as built; anything else is logged and answered with a 500 carrying only the handler's message ('Search failed'), so no exception text reaches a caller.errors.tooManyRequests(sec)statesRetry-After.
Response headers and the Next config
wiki-formant/headers: the headers every route sends, the shared CSP, and the Next config defaults. It imports nothing, so next.config.ts pays for nothing it does not use.
import type { NextConfig } from 'next';
import { contentSecurityPolicy, withWikiDefaults } from 'wiki-formant/headers';
const csp = contentSecurityPolicy({ 'connect-src': ["'self'", 'https://*.radixdlt.com'] });
export default withWikiDefaults({ async redirects() { /* … */ } } satisfies NextConfig, { csp });withWikiDefaults(config, { csp }) adds:
The security headers on every route,
cspenforced in production only (Next's dev runtime is inline andeval); an origin with a per-request nonce passes none./openapi.jsonrewritten to/.well-known/openapi.jsonfirst inbeforeFiles, merged with the app's ownrewrites()in either form.AVIF before WebP,
turbopackFileSystemCacheForBuild: false(Vercel restores a stale build cache), anddistDirfromSTUDIO_DIST_DIRfor radix-studio's second dev server.
What the app sets wins, and its headers() follow these. contentSecurityPolicy starts from the shared base and each directive passed replaces its default; an empty list drops one. The default frame-src is DEFAULT_IFRAME_HOSTS, the sanitiser's default iframeHosts, so an embed that clears one clears the other; a site with its own hosts passes the same list to both.
Pagination, versioning and rate limits
import { parsePagination, paginatedResponse, listEnvelope } from 'wiki-formant/pagination';
import { bump, parseVersion } from 'wiki-formant/versioning';
import { limitClient, rateLimitedResponse } from 'wiki-formant/rate-limit';
const { page, pageSize } = parsePagination(searchParams); // page ≥ 1, pageSize 1–100
return Response.json(paginatedResponse(items, total, page, pageSize)); // always carries totalPages
bump(page.version, 'minor'); // tolerant of null or junk
const limit = limitClient('search', request.headers, { capacity: 30, refillPerSec: 0.5 });
if (!limit.ok) return rateLimitedResponse(limit.retryAfterSec);listEnvelopeis the shape every list tool answers with, itsnoteon an empty page.rateLimitis an in-memory token bucket;blockMsblocks an abusive key outright across every bucket naming it.costspends more than one token on a call, which is howmcpResponsecharges a batch for each call it carries.clientIpreadsx-real-ipfirst, then the leftmostx-forwarded-for.MCP_RATE_LIMITis the MCP servers' budget.
React
wiki-formant/react carries 'use client'. What is shared is behaviour; class names and icons are passed in.
// A Next layout passes the rail its data: `wiki-formant/next`'s `Rail` brings the router's link and pathname.
import { Rail } from 'wiki-formant/next';
<RailFrame rail={<Rail label="Wiki" nav={[{ href: '/', label: 'Home' }]} groups={[{ label: 'Sections', links: sections }]} />}>
// The page hands up its headings.
<RailHeadings headings={article.headings} />wiki-formant/next ('use client', next an optional peer) is Rail bound to next/link and usePathname(), /index read as /; a pathname prop overrides the router's. Off Next, wiki-formant/react's Rail takes pathname and link itself.
SidebarProvider/useSidebarhold the rail's collapse state, remembered across loads and defaulted from the viewport only when the reader never chose. Pair it withsidebarBootScript(wiki-formant/sidebar) in<head>, or a remembered-closed rail paints open first.Railis every rail, in one order: atitle(.wiki-rail__title), asearchbox, the unlabellednavlinks, "On this page", then the labelledgroups, an empty one left out. "On this page" lists theheadingspassed, or else those a page handed up withRailHeadings, whichSidebarProviderholds; a heading a view draws rather than the stored HTML is added withreferencesHeading(id?, title?)orseeAlsoHeading(text, id?)(wiki-formant/headings, callable on the server), the idsReferencesViewandRelatedPagesuse;tocsets its label, indent and offset.RailShellrenders the rail's landmark, scroll wrapper and collapse states, and closes a mobile drawer on a followed link; mark the active link withisRailLinkActive. With its defaultprefix,"wiki-sidebar", in a.wiki-layoutbeside.wiki-layout__main,base.csslays it out: a sticky column from 1024px, a drawer above the article below it. The site supplies--rail-top,--rail-borderand--rail-bg.RailToggleis the button that opens and closes the rail, a menu glyph and a cross while open, drawn bybase.cssas every header button,.header-btn(--header-btn,--header-btn-radius,--header-ink,--header-ink-hover,--header-btn-hover). It goes at the leading edge of the header, inside theSidebarProvider, on the pages that have a rail.Menu({ label, trigger, children })is a panel that opens from a button and hangs from it, on the browser'spopover: a click outside, Escape and another menu shut it, as does a link or button inside unless it carriesdata-keep-open. Its contents render the first time it opens, and its button is lit while it is open.base.cssdraws it as.menu, its rows.menu__item(--dangerfor one that signs out or deletes), a heading.menu__labeland a rule.menu__rule; the button is a.header-btnunlesstriggerClassNamesays otherwise.AccountSlot({ status, avatar, children, signIn, pending })is the header's account corner:pending(a.account-slot__pendingdisc by default) whilestatusisunknown,signInwhensignedOut, and aMenuonavatarholdingchildrenwhensignedIn.HeaderNav({ links, label, pathname, link, prefetch })is the header's links innav.header-nav, one row that scrolls sideways rather than wrapping, each.header-nav__link(a link's ownclassNameadded) and the one being readaria-current(page, ortruebeneath atreelink) byisRailLinkActive; a link to another origin is an<a>. It reads the header tokens and--header-nav-gap,--header-nav-pad,--header-nav-weight.wiki-formant/next'sHeaderNavis it on Next's link and pathname.The breakpoint is known twice, in
matchMediaand in CSS.base.csssets--rail-floating: 1inside its media query and the hook warns in development when the two disagree; a rail laid out by its own CSS sets the property the same way.railBreakpointMismatchandreadRailFloating(wiki-formant/sidebar) are the mechanism.treeRailLinks(nodes, base, glyph?)(wiki-formant/react-server, so a server layout can call it) walks a category tree (WikiNode[]) into rail links underbase: each node a section titled by its description, its children opening on its trail, a hidden node left out with its subtree.RailGroupis a labelled group of rail links (RailLink:href,label,icon,glyph,title,tree,children; aglyphis drawn in.wiki-rail__glyph, hidden from a screen reader) in thewiki-rail__*classesbase.cssdraws. The link being read is lit witharia-current="page", a section witharia-current="true"while the reader is beneath it, and a link'schildrenopen while the reader is on its trail, the deepest link on it the one lit.TableOfContentsis the "on this page" list with scroll-spy over theheadingsit is given, read from the article's source with the ids the server gave them, never scanned from the DOM; each entry is a#sectionlink, so a section is in the URL to share. Unless given, its classes are the rail's (wiki-rail__toc-*), its icon a chevron and its offset--rail-top.WikiLinkPreviewis the hover card over the internal links inscope, each asked ofGET <endpoint>?path=, which answersLinkPreviewData(title,excerpt,bannerImage) or 404. Its props are data, so a server layout mounts it;containernames a query container the card is drawn inside.useLinkPreviewis the hover card: one delegated listener, an intent delay, a grace period into the card, viewport clamping and a per-href cache of answers; afetchthat throws is asked again on the next hover, a null is cached as no card.LinkPreviewCardis its markup (link-preview-card,-banner,-body,-title,-excerpt); a caller that must move the card passes its ownstyle.useTypeaheadis the search field's state machine: a request-id guard, keyboard navigation, abort and a per-mount cache.resultsisidle,searching,foundorfailed, so "no results" isfoundwith none and a failed search is never cached;itemsis the rows on screen.clearItemsdismisses the list and keeps the query;reopenasks for that query again (from the cache where it can), so a refocused field shows its list without a keystroke.fetchmust be referentially stable. Itscombobox(listKey)hands outinputProps,listPropsandoptionProps(i), witharia-activedescendantomitted rather than emptied;listKeykeeps two rendered lists' ids apart. The arithmetic iswiki-formant/combobox, which imports nothing.SearchFieldis the search box every wiki shares, onuseTypeahead: a GET<form>toactionwithname="q", the first few rows under it as links (hrefOf,renderRow), a last row toaction?q=, and a note for a failed or empty search. Enter opens the results page unless the arrows chose a row; Escape and a click outside shut the list; "/" reaches it, callingrevealfirst for a field hidden in a closed rail. Aniconfolds it to a magnifier until opened, and again when left empty or a row is followed: that isSearchFold({ label, icon, href, at, className, toggleClassName, children }), which wraps any search form of a site's own the same way (<search data-folded>> the toggle while folded; "/" opens it and focuses its input; Escape or a blur with the input empty folds it, as does a change ofat, the page it was opened on). Its classes are alwayssearch-field>__form>__input,__toggle,__list>__item(--active; the last row also__all),__note, whichbase.cssdraws as a dropdown on the--ui-*tokens;classNamesadds a site's own to each.navigate(the router's push) and the words (all,empty,failed) are the site's.useSnapRowis a carousel as a scroll-snapped row:step,go(i)andat, no markup.useClickOutsideignores a container hidden at the current breakpoint (offsetParent).useUnsavedChanges(dirty)asks before leaving and returnsconfirmLeave()for a client-side navigation;useSaveShortcut(save)binds ⌘S / Ctrl+S;useSearchShortcut(open)is "/" to search, withfocusShown(input).SortHeaderrendersuseTableSort'sheaderProps(key)as a<th aria-sort>holding a<button>, the markupsortTableswrites.useBlockOperations(blocks, setBlocks, { duplicate })andBlockActionsare a block list's five edits and their buttons;useRevisionRestore(restore, { onRestored })confirms and restores,restoreViaPost(endpoint)being the usualrestore.useArticlePasses(ref, [blocks])runswiki-formant/dom's passes and renders math with KaTeX (an optional peer, loaded only when a page has$$…$$,\[…\]or\(…\)).<Beacon />sends page views and outbound clicks towiki-formant/analytics.toast.success(message)andtoast.error(message), with an optionalactionlink andduration, raise a toast from any code;toast.carry(message)shows one on the page a full load reaches.Toaster, whichSiteShellmounts, stacks them above the dock,.toast-stack>.toast.toast--success|error>.toast__message,.toast__action,.toast__close, drawn bybase.csson the--ui-*tokens.RouteErroris whaterror.tsxdraws: anEmptyStatewith the heading, an optionaldescription, Try again (Next'sretry, neverreset) and Home (orhome); the button is.btn-primary, the class every site gives its primary button, unlessbuttonClassNamenames another.GlobalRouteErrorisglobal-error.tsx: the document,.app-shellandmain#main.app-main.page-framearound aRouteError, withhtmlClassNamefor the font variables the root layout sets on<html>; the file imports the site's stylesheet and fonts itself.
useClickOutside, useSnapRow and the editor hooks ship no class names.
Server components
wiki-formant/react-server: the same React without the directive, for parts that are pure functions of their props. Each takes the router's link component, since a bare <a> turns every press into a full load.
import Link from 'next/link';
import { Breadcrumbs, FacetBar, FacetSummary, InfoboxFacts, JsonLd, Pager } from 'wiki-formant/react-server';
<Breadcrumbs link={Link} items={tree.crumbs(path)} base={SITE_URL} />
<FacetBar link={Link} facets={groups} letters={letters} alphaFirst />
<Pager href={p => `?page=${p}`} page={page} total={totalPages} noun="Page" />Highlight({ text, query, lead })marks where a search's words fall in a result's title or snippet, in<mark class="search-mark">(base.csssets it in bold), matched as the search matched: case and accents ignored, a hyphenated word as its parts, each word anywhere and its stem at the start of a word, no stop words or excluded-words.leadstarts a snippet at most that many characters before its first mark, after an ellipsis, so a line-clamped snippet keeps its mark in sight.wiki-formant/highlight'shighlightRanges(text, query)is the same answer as ranges, for a caller that must know whether a text is marked at all.EmptyState({ title, description, action, as, className })is "there is nothing here": a 404 (as="h1"), an empty table, a filtered-out grid..empty-state> the title (h1, orp.empty-state-title),.empty-state-desc,.empty-state-action;base.cssstacks and centres it, the site sets its look on the--empty-*tokens.NotFound({ site, link, buttonClassName })is whatnot-found.tsxdraws: anEmptyStatein.not-foundtitled "Page not found",site.notFound'sdescriptionunder it, and itshome(the front page, Home, unless given) as a.btn-primarylink.FacetBarrendersfacetControlsandalphaControls;letterRow,letterControl,textandletterCounts="title"separate the A–Z row and let a label truncate while its count stays.Breadcrumbsrenders the trail and itsBreadcrumbListJSON-LD together;basemakes the URLs absolute.JsonLdescapes every<, so an authored</script>cannot close the tag.SiteDocumentis the root layout's<html>: the rail's boot script and thesite'sSiteLinksin the head, itsJsonLdgraph andBeacon(beacon, on by default) in the body,suppressHydrationWarningfor the attribute the script stamps. Other props go on<html>;bodyClassNameon the body.SiteShellisbase.css's shell underSidebarProvider:.app-shell> skip link,header.app-header(aroundheader, which is its contents),main#main.app-main.page-frame, the footer (aSiteFooterofsite'sfooterwithlink, unlessfootergives another): the main is the column, so no page frames itself, bar a full-width.page-bleedband that draws its own.page-frame(frame={false}for a site that draws its own column).RailFrameis a section layout's rail beside its column,.wiki-layout>rail+.wiki-layout__main>.page-frame, insidemain, where the main's frame gives way to it; it mountsWikiLinkPreviewover the column from/api/wiki/previewunlesspreviewnames anotherendpointor isfalse. Given a site with alogo(defineSite's), the shell leads the header withRailToggleand the mark as a link home,.header-logo, named forsite.name, ahead ofheader; a header drawn without one putsRailTogglefirst itself.base.csshides the toggle on a page with no rail. Adockis pinned to the window's foot in.dock, a click-through strip whose buttons are.dock-button(--dock-button,--dock-inset, and the look--dock-bg,--dock-ink,--dock-border,--dock-shadow,--dock-hover);DockLink({ href, label, link })is a disc that is a link, its glyph the children. The shell mounts theToaster. With noheaderit draws none; other attributes go on the shell's box;prefixrenames the boxes (<prefix>-shell,-header,-main) for a host that styles a shell of its own and keeps the skip link and landmarks.SiteFooterisfooter.app-footer: the site's own matter (children), a row oflinksending on thexfollow link, and© <year> <owner>,Content licensed under <license>and anote(a disclaimer, a credit). Givensite, each comes fromdefineSite'sfooter(links,owner, which defaults to the site's name,license,note) andx, a prop overriding its own.
// @/lib/site
export const site = defineSite({ name, url, description, x: X, image, feeds, agentsMd: true, themeColor, graph: { logo }, logo: <Mark />, notFound: { description } });
// src/app/layout.tsx
export const { metadata, viewport } = site;
<SiteDocument className={fontVariables} site={site}>
<SiteShell site={site} link={Link} header={<Header />} dock={<SearchButton />}>{children}</SiteShell>
</SiteDocument>
// src/app/not-found.tsx
export default function NotFoundPage() {
return <NotFound site={site} link={Link} />;
}SiteLinksis the root layout's agent-surface<link>s:/llms.txtashelp, the RSSfeeds, the OpenAPI document asservice-descand the agent card asservice-meta(described, on by default),/AGENTS.mdasservice-doc(agentsMd). React hoists them into<head>from anywhere.service-descis never the MCP endpoint, which is POST-only.Pagersteps by links (href) or buttons (onPage,wrap); a step with nowhere to go stays in place, inert.SnapDotsare a snap row's dots.FacetSummaryis the count and Clear line under the facets;RelatedPagesthe see-also aside;InfoboxAsidethe facts landmark with its series line;InfoboxFactsrendersmetadataRowswithformatFactValueas its default cell.RevisionChangesrenderswithChangesrows;MaintenanceQueuesrendersmaintenanceQueues;Citeis an article's citation in a<details>.ArticleMetais an article's provenance line,ul.article-meta:children(who wrote it), Updated (updated, orupdatedLabel),version,revisions(linked tohistoryHref),verified, thelicenseandcite.PageWithInfoboxsets a body beside itsinfoboxin.page-with-infobox>.page-main-content, and is the body alone without one.SectionIndexis a front page's or a section page's listing (STRUCTURE.md S12):groupsof{ title, href, blurb, glyph, count, sections, pages, more }, each.wiki-catheaded by a link to its section (.wiki-cat__head, its heading atlevel) and itsblurb(.wiki-cat__blurb), its sections asIndexCards(.wiki-grid--sectionsofIndexCardLink,.wiki-card--sectionwith a glyph, status, count, blurb and an optional bannerthumb) and its pages as title tiles in.wiki-grid, the blurb a tooltip.base.cssdraws them on the--ui-*tokens;--index-glyphinks the marks and--index-edgea section card's leading edge.
Block trees
wiki-formant/blocks: the two core containers (columns[i].blocks, an infobox's blocks), the walks over them, and the core leaves' text, markdown and defaults.
import { coreBlockShape, mapBlockTree, coreAtomicToMarkdown, coreBlockDefaults } from 'wiki-formant/blocks';
export const BLOCK_SHAPE = coreBlockShape<Block>();
mapBlockTree(blocks, processLeaf, BLOCK_SHAPE);
switch (block.type) {
case 'content': case 'codeTabs': case 'banner': case 'references':
case 'stats': case 'linkGrid': case 'recentPages': case 'pageList':
return coreAtomicToMarkdown(block, { siteUrl: SITE_URL, referencesTitle: 'Sources' });
case 'corpusStats':
return block.resolvedHtml ? htmlToMarkdown(block.resolvedHtml) : '';
}The dispatch over a repo's own union stays in that repo, so a new type is a compile error there; the core bodies come from here (
coreAtomicText,coreAtomicToMarkdown,coreBlockDefaults).The core leaves are
content,codeTabs,banner,references,stats,linkGrid,testimonial,events,locations,recentPages,pageListandlist.CoreLeafBlockis their union (less the list and containers) andCoreLeafTypeits types; a wiki's atomic union isCoreLeafBlock | ListBlock | its native types, and a leaf added here fails to compile in every wiki until wired.coreAtomicToMarkdownmakes a resolved page'shrefabsolute withsiteUrl, since a twin is read off-site.A
codeTabstab'scodeis source text: escaped by its view, fenced verbatim by the twin. Passhighlightedto the view for server-highlighted markup.CODE_LANGSandDEFAULT_LANGare the language list.recentPages,pageListandlistresolve toResolvedPageRefs built withpageRef(page, now).ListBlockis the pages under a section (source: 'under'), the newest ('newest',count) or chosen ones ('chosen',pages), shown as links or cards.An
eventsitem is{ id, date, end?, text }, dated to the year, month or day (EVENT_DATE);splitEvents,eventWhen,eventBegunandeventEndedsplit upcoming from past by aday, which the browser re-splits by the visitor's own.A
testimonialis{ quote, author, role?, avatarUrl? }. Alocationsitem carries an address,hoursrows of{ days, opens, closes }and atimeZone.
Validation
wiki-formant/validation: the block model in one declaration, and the checks under it.
import { defineBlocks, describeBlockIssues } from 'wiki-formant/validation';
import { coreBlockDefaults } from 'wiki-formant/blocks';
const model = defineBlocks<Block>({
defaults: { ...coreBlockDefaults(), corpusStats: () => ({ type: 'corpusStats', view: 'sourceTiers' }) },
checks: { corpusStats: b => isCorpusView(b.view), list: (b, core) => core(b) && isSection(b.under) },
});
export const { shape: BLOCK_SHAPE, createBlock, duplicateBlock, validateBlocks, blockIssues } = model;
const issues = blockIssues(body.content);
if (issues.length) return errors.badRequest(`Invalid content: ${describeBlockIssues(issues)}`);
// Invalid content: [2].columns[0].blocks[1]: malformed linkGrid blockA check for a core type narrows the package's (
coreis passed in).MAX_BLOCK_ROWScapsrecentPages.limitandpageIds, since both end in a databasetake:;blockLimitis the read side.safeLinkHrefis the link check the views rely on.
Block views
wiki-formant/block-views: the views of the core leaves, as client components that render server-side.
import { CodeTabsView, ColumnsView, LinkGridView, PageRefsView, StatsView, EventsView, LocationsView, BannerView } from 'wiki-formant/block-views';
case 'codeTabs': return <CodeTabsView tabs={block.tabs} />;
case 'columns': return <ColumnsView columns={block.columns} gap={block.gap} render={renderBlock} />;
case 'pageList': return <PageRefsView refs={block.items} link={Link} renderItem={row} />;ColumnsViewstates its gap and alignment as data attributes and an inactive code tab ishidden, so no view needs Tailwind to scan the package.TestimonialViewisfigure.testimonial; passphotofor sized images.EventsViewsets upcoming soonest first and past latest first, with "Now on" beside one begun;dayfills the server's split.LocationsViewdraws each place's address, week (PlaceHours), note and map; the browser adds whether it is open by the place's clock, once a minute.wiki-formant/hoursholds those rules (hoursRows,openState,clock,hoursLd,mapHref,mapEmbed) for a twin or structured data; a closing time at or before the opening one is the next morning, andDEFAULT_ZONEisEurope/London.BannerViewshowsBANNER_MESSAGES(wiki-formant/text) unlessmessageoverrides it.
Text
wiki-formant/text: a block tree as plain prose, for an LLM export or a description.
import { openingText, plainText, stripHtml } from 'wiki-formant/text';
import { describe } from 'wiki-formant/metadata';
const description = describe(page.metadata?.excerpt || openingText(page.content));openingText is the first top-level content block with prose once headings are out, so a page opening on an infobox is not described by its table. matchSnippet is a search hit's line.
Page metadata
wiki-formant/metadata: a page's canonical, markdown alternate, Open Graph and Twitter card from one input, and the schema.org nodes beside them.
export const generateMetadata = () => ({
title,
...pageMetadata({ title, description, url, type: 'article', image: ogImageUrl(title), siteName, handle, markdownTwin: true }),
});
<JsonLd data={articleLd({ headline: title, url, image, published, modified, publisher: SITE.publisher, citation: citationsFromReferences(refs) })} />defineSite({ ...rootMetadata's options, x, feeds, agentsMd, themeColor, graph, footer, logo, notFound })is a site's identity stated once in@/lib/site(a.tsxmodule where itslogois markup): it returns the facts (name,url,description,x) and what each surface takes,metadataandviewportfor the root layout,linksandgraphfor<SiteDocument site>,footerandlogofor<SiteShell site>,notFoundfor<NotFound site>. The handle and the graph'ssameAscome fromx;graphadds tositeGraphLd's options or overrides them.rootMetadata({ name, url, description, title, image, handle, keywords, icons })is the root layout'smetadata: title template, robots, and an inherited card with no title, description or URL, which Next fills from each page's own; the site's name as author, creator and publisher; and Search Console and Bing verification fromGOOGLE_SITE_VERIFICATIONandBING_SITE_VERIFICATIONwhere set.Next replaces
openGraphandtwitterper segment rather than merging, sopageMetadatasets both;sitePageMetadata({ siteName, handle })binds the fields every page's card needs.sitePageMetadata({ ..., card:${SITE_URL}/og})binds the site's card route, and a page then passescard: { title, eyebrow, description, banner }in place ofimage.cardUrl(base, fields)is the same address for JSON-LD: empty fields left out, the order fixed, so one card has one URL.articleLdrequiresimage.collectionLdis an index over anItemList.siteGraphLdis the Organization, WebSite andWebAPI@graphfor the root layout (search defaults to/search?q=on the origin, the API's documentation to itsllms.txt), andsiteRefs(url)hands out the same@ids for a page'spublisherandisPartOf.questionPairs(html)reads a FAQ from headings ending in?;faqPageLd(pairs, url)is null under two pairs.describe(text)is a meta description from any prose within 160 characters: whole sentences where they fill half, else cut at a word with an ellipsis.
Social cards
wiki-formant/og: the /og card, as the element next/og's ImageResponse takes.
import { SocialCard, bannerField, bubbles, cardRandom, OG_SIZE, OG_HEADERS } from 'wiki-formant/og';
const field = (await bannerField(searchParams.get('banner'), /\.public\.blob\.vercel-storage\.com$/))
?? bubbles(cardRandom(title), { field: [BG, NAVY], colors: [GREEN, ORANGE] });
return new ImageResponse(<SocialCard {...{ title, eyebrow, description }} {...field} mark="example.org" colors={colors} fontFamily="Inter" />, { ...OG_SIZE, headers: OG_HEADERS, fonts });A page's banner is its card; the generated field is for a page without one.
bannerFieldfetches only from the hosts named, crops, inlines PNG and turns the scrim on, or returns null. It loadssharp.Fonts stay with the site: Next traces a font file only from a literal path in the app, and satori reads TTF or OTF.
wiki-formant/seeded'shashStrandseededRandomare the deterministic randomness the art draws from, identical on server and browser.
Page banners
wiki-formant/banner: the banner a page is headed with, its own picture or art seeded by the page.
import { PageBanner, CardBanner } from 'wiki-formant/banner';
<PageBanner seed={page.title + page.tagPath} picture={banner && <Image src={banner} alt="" fill preload sizes="100vw" />}>
<Breadcrumbs items={crumbs} />
<h1>{page.title}</h1>
</PageBanner>
<CardBanner seed={page.title + page.tagPath} picture={card.banner && <Image src={card.banner} alt="" fill sizes="33vw" />} />Every page has a banner: a page without a picture gets art seeded by
seed, the same on every render, server and browser.CardBanneris the same picture or art at the top of the page's card, cropped to 4:1; seed both alike, so a card and its page match.A listing carries
banner, the picture both show:metadata.bannerunless the store'sbanneroption reads it elsewhere, such as the article's first picture.The art is inline SVG with a class per role, coloured by custom properties:
--banner-fromand--banner-tothe gradient (transparent unset),--banner-midthe blobs and half the shapes (--ui-mutedunset),--banner-inkthe rest and the dots (--ui-accentunset), over--banner-field(--ui-surfaceunset). A category's palette or a section's band is a style on the frame.markreplaces the triangle with a wiki's own shape, as a path from its anchor, size and generator.fill-opacityon a role's class dims it under a title.The frame's 4:1 is a floor, not a height (
base.css): the trail and title grow it rather than being cropped.
Revisions and history
wiki-formant/revisions: what changed between two versions of a page, and which bump to ask for. wiki-formant/history: what each revision changed, as a history view shows it.
import { computeRevisionDiff } from 'wiki-formant/revisions';
import { withChanges } from 'wiki-formant/history';
const diff = computeRevisionDiff({ currentVersion: page.version, oldContent, newContent, oldTitle, newTitle });
const rows = withChanges(revisionsNewestFirst); // each row needs its `content`; it leaves without it
<RevisionChanges changes={rows[0].changes} label={type => BLOCK_LABELS[type]} />Blocks match by id, so a moved block is one
moved. Container keys are walked as their own entries, never diffed as attributes. A path likeroot.1.columns.0.blocks.2is part of the contract; passcontainersbeyond the core two.withChangesdiffs on the server, by words, leaves only. The oldest row is diffed against an empty page, so fetch one more than you show.
Feeds and sitemaps
import { feedResponse } from 'wiki-formant/feed';
import { treeSitemap, tagPrefixes } from 'wiki-formant/sitemap';
export const GET = async (request: Request) => feedResponse(request, channel, await items());
...treeSitemap(pages, {
sections: tagPrefixes(pages.map(p => p.tagPath)),
sectionRow: path => ({ url: `${SITE_URL}/wiki/${path}`, changeFrequency: 'weekly', priority: 0.6 }),
pageRow: p => ({ url: pageUrl(p), changeFrequency: 'weekly', priority: 0.7 }),
}),feedResponseanswers a conditional GET;lastBuildDateis the newest item's date, and an empty feed carries none.A section is dated by the newest page at or beneath it, or not at all. Every URL appears once: an empty-slug page dates its section and gets no row.
Licences and the X account
import { ccBy40, licenseBlock, openApiLicense } from 'wiki-formant/license';
import { xAccount, followLines, followNote, followLinkProps } from 'wiki-formant/social';
const license = ccBy40({ siteName: 'AcuiQ', siteUrl: SITE_URL });
const block = licenseBlock({ license, scope: 'The protocol compilation and prose', excludes });
export const X = xAccount({ siteName: 'AcuiQ', handle: '@acu_iq', posts: "a named trial's prescription with its citation" });One
Licensegoes tolicenseBlock,agentCard({ license, licenseScope })andopenApiDocument, which setsinfo.licensefrom it.X.urlis thesameAs,X.handlethe card's,followLines(X)goes into llms.txt and AGENTS.md,followNote(X)into the MCP instructions, and<a {...followLinkProps(X)}>is the footer link withrel="me".
Agent descriptors
wiki-formant/well-known: the A2A agent card, the MCP manifest and server card, and the registry's domain proof.
import { agentCard, mcpManifest, skillsFromTools, wellKnownHandler, serverCardHandler } from 'wiki-formant/well-known';
const AGENT_CARD = agentCard({ name, description, url: `${SITE_URL}/api/mcp`, version, skills: skillsFromTools(TOOLS), license });
// src/app/.well-known/[doc]/route.ts
export const GET = wellKnownHandler({ agentCard: AGENT_CARD, mcpManifest: mcpManifest({ … }), openapi: SPEC });The card is served at agent-card.json, and its url is the MCP endpoint, which answers A2A. The well-known routes serve MCP_REGISTRY_PUBLIC_KEY at /.well-known/mcp-registry-auth, 404 when unset.
OpenAPI
wiki-formant/openapi: the frame of the spec wellKnownHandler serves, and the paths every site shares. A spec writes only its own paths.
import { openApiDocument, jsonBody, jsonResponse, toolBody, llmsTxtPath, mcpPath } from 'wiki-formant/openapi';
export const SPEC = openApiDocument({ title, version, description, license, siteUrl: SITE_URL }, {
'/api/wiki/{path}': { put: { requestBody: toolBody(toolInput('edit_page'), { inPath: ['tagPath', 'slug'], refs: { Block: BLOCK_SCHEMA } }), … } },
'/llms.txt': llmsTxtPath('Index of every page (plain text)'),
'/api/mcp': mcpPath(TOOLS.map(t => t.name)),
}, { schemas: { Block: BLOCK_SCHEMA } });toolBody is a write tool's input schema as the REST body, so openapiWriteParity holds by construction. mcpPath states the protocol versions, the batch cap and MCP_RATE_LIMIT_TEXT; llmsTxtPath the If-None-Match and its 304.
AI crawlers
wiki-formant/crawlers: one roster of AI crawlers, for the proxy that counts them and the robots.txt that addresses them.
import { trackAiBot, crawlerRules } from 'wiki-formant/crawlers';
trackAiBot(request, event, () => import('@/lib/track')); // in proxy.ts
const rules = crawlerRules({ allow: '/', disallow, aiAllow });Every agent group allows the agent surface (
/api/mcp,/llms.txt,/openapi.json,/.well-known/);aiAllowadds the origin's own.Search engines get the HTML site and no twins (
/*.md$, plussearchDisallow). The?_rsc=prefetch payload is refused in every group.trackAiBotcounts a rostered crawler anywhere, and anything but a search engine asking for what only agents read.loadis a dynamic import so the proxy does not load a database client.
Rendered-article passes
wiki-formant/dom: what runs against an article element once it is in the document.
import { addCopyButtons, sortTables, activateTabGroups, hydrateTweetEmbeds, onTweetResize, sizeTweetEmbed } from 'wiki-formant/dom';
addCopyButtons(el);
sortTables(el);
activateTabGroups(el);
hydrateTweetEmbeds(el);
const off = onTweetResize((h, source) => sizeTweetEmbed(el, h, source));Each pass is idempotent.
sortTablessorts a column as dates, numbers or text (one stray value makes it text), restores the author's order on a third press, and leaves label/value and merged-cell tables alone.activateTabGroupsmakes stored[data-tabs]markup a working tab group; without script every tab shows in order.onTweetResizebelieves only the embed host and hands over the posting window, sosizeTweetEmbedsizes that iframe alone.scrollTables(html)(wiki-formant/headings) wraps each table in a.table-scrollbox on the string, before layout.track(name, props)sends a browser event to the analytics beacon.
Search
wiki-formant/search: what a literal tier and a full-text tier must agree on: proseSql, HEADLINE_OPTIONS, FTS_RANK_NORMALIZATION, and searchTsvDdl(table), the statements that drop and re-add the generated search_tsv column and its index in one transaction. fullTextQuery is a query as the full-text tier reads it, a hyphen or underscore inside a word a space; correctQuery(query, vocabulary) corrects a query's misspelt words against a site's own, which the store's search retries with when its first page is empty, returning the query that found the rows as corrected.
const { column, index } = searchTsvDdl('"WikiPage"');Dates, freshness and the maintenance queues
wiki-formant/freshness and wiki-formant/queues.
import { relativeTime, formatDay, freshnessBanner } from 'wiki-formant/freshness';
import { maintenanceQueues } from 'wiki-formant/queues';
relativeTime(then, now, { style: 'short' }); // '3h ago'; `now` is always passed in
formatDay(day, { locale: 'en-GB', month: 'long' }); // '19 September 2026', always UTC
const banner = freshnessBanner(page, Date.now(), { against: 'current sources and the live ledger' });
const queues = maintenanceQueues(pages, { href, required, nowMs, verify, listedIds });freshnessBanneris theoutdatedbanner once a page goes unchecked formaxAgeDays(180), or null.freshnessAgeis the days since a page was verified, or edited if never, and null when it carries neither, whichisStalecounts as stale.maintenanceQueuesreturns the outdated, orphaned, unsourced and missing-facts queues, empty ones dropped. Pass every page but the home page and the back office.MaintenanceQueuesdraws them on anoindexpage.
Sanitising stored HTML
wiki-formant/sanitize: the allowlist between saved HTML and a reader's browser. Run it server-side on the render path.
import { createHtmlSanitizer, sanitizeCoreLeaf } from 'wiki-formant/sanitize';
const clean = createHtmlSanitizer({ iframeHosts: FRAME_HOSTS }); // the same hosts in the CSP's frame-src
const safe = mapBlockTree(blocks, b => sanitizeCoreLeaf(b, clean), BLOCK_SHAPE);The default list is what
wiki-formant/tiptap's nodes store plus a presentational SVG subset. Extendtags,attributes,classesandschemesByTagfrom your stored HTML, never from memory.A YouTube iframe comes out as the YouTube node's markup, whoever wrote it, and
base.cssdraws it as a 16:9 player.Classes pass by name only, since a site's own utilities can draw over the chrome.
sanitizeLine(html, { links })cleans what aWikiLinestores: its marks andwikiTextStyle's spans.sanitizeCoreLeafruns it over the core leaves' one-line fields (a figure, a quote and who said it, the events' and places' headings, a place's name), whichblock-viewsdraws as HTML.
Image uploads
wiki-formant/upload: the route an editor's image upload posts to.
// src/app/api/upload/route.ts
export const runtime = 'nodejs';
export const POST = uploadHandler({
authorize: async () => (await currentUser())?.id ?? errors.unauthorized('Sign in to upload.'),
prefix: 'wiki/',
});The file's own bytes say what it is; SVG is refused. Every image is re-encoded upright, so no source metadata (GPS included) is kept. Defaults: 4 MB, 40 megapixels.
Each uploader has a budget on
authorize's id and address, and each address its own.encode,maxBytes,maxPixels,rateLimitandstore(Vercel Blob by default) are options.normalizeImage(bytes, opts)is the sniff, cap and re-encode without the route.
Maps
wiki-formant/maps: a pasted Google or Apple Maps URL as one an <iframe> accepts.
import { toMapEmbedUrl, resolveMapHandler } from 'wiki-formant/maps';
toMapEmbedUrl('https://maps.apple.com/?ll=51.5,-0.12');
export const GET = resolveMapHandler({ authorize: async () => !!(await currentUser()) }); // /api/resolve-mapA short link resolves through the wiki's own route (resolveMapUrl is the client half): exact shortener hosts, one hop, an allowlisted landing host, a timeout and your sign-in check. A pasted short link inserts as a placeholder at once and settleMapEmbed settles it: the embed, or, when the link cannot be resolved, the link itself as text, never a blank frame.
Editor nodes
wiki-formant/tiptap: the custom nodes: embedNodes (an iframe, YouTube with its paste rule, an X post and a map), createCodeBlock, createTabs and createHeadingIds.
import { embedNodes, createCodeBlock, createTabs, createHeadingIds } from 'wiki-formant/tiptap';
const { TabGroup, TabItem } = createTabs();
const nodes = [...embedNodes({ resolveMapUrl }), createCodeBlock({ classNames, icons }), TabGroup, TabItem, createHeadingIds({ slug })];embedNodesturns a pasted YouTube, X or map link into its player. The iframe and map nodes draw only an https src onDEFAULT_IFRAME_HOSTS, since the editor draws stored HTML where its author is signed in; a site whose sanitiser takes its owniframeHostspassesembedNodesthe same list, or the editor draws those frames empty and a save strips them.The node views draw in default classes
base.cssstyles;classNamesandiconsreplace them.createTabsreturns both nodes, since one is unsatisfiable without the other. A short map link inserts at once and swaps itssrcwhen it resolves.createHeadingIdsgives each heading the id its published copy will carry.
Editor
wiki-formant/editor: the rich-text editor's engine, minus its chrome.
import { useWikiEditor, useUrlPrompt, WikiToolbar, UrlPromptField, WikiLine, uploadImageTo } from 'wiki-formant/editor';
const url = useUrlPrompt(editor, { resolveMapUrl });
<WikiToolbar editor={editor} prompt={url} onUpload={triggerUpload}
icons={{ ...ICONS, unlink: <Unlink />, upload: <Upload />, embed: <Globe /> }}
classNames={{ toolbar: 'toolbar', button: 'toolbar-btn', pressed: 'toolbar-btn-on', divider: 'toolbar-divider' }} />
<UrlPromptField prompt={url} classNames={{ row: 'row', input: 'input', apply: 'btn', cancel: 'btn-quiet' }} />
<WikiLine as="h1" value={title} onChange={setTitle} placeholder="The page's title" />WikiToolbarshows each command the editor's extensions support (supports) and nothing else, in fixed groups, with the table controls while the cursor is in a table.useUrlPromptis the link and embed field: it opens on the current link, unlinks on an emptied one, and closes when its editor changes.WikiLineis a one-line field with its ownmarks, undo andonFocus, so one toolbar can drive the field last touched. Itsstylemark iswikiTextStyle: a font, colour and size on a run of words, which an article editor takes throughnodesand an app's own controls set withsetTextStyle.A link is stored as its
hrefand thelinkclass only; whether it is external is decided at render byarticleHtml'slinkspass.uploadImageTo('/api/upload')is theuploadImagean editor passes: it resolves the URL or throws the route's reason, anduseWikiEditor'suploadisidle,uploadingorfailedwith that reason for the editor to show.
Block editor
wiki-formant/block-editor: the block list an author edits and the fields of the core types. The look arrives as a kit.
const KIT: BlockEditorKit = {
classNames: { action: 'icon-btn', input: 'input', row: 'row', stack: 'stack-sm' },
icons: { add: <Plus />, up: <ChevronUp />, down: <ChevronDown />, duplicate: <Copy />, remove: <Trash2 /> },
};
const SCHEMA: BlockSchema<Block> = {
meta: type => BLOCK_META[type], create: createBlock, duplicate: duplicateBlock,
types: PAGE_TYPES, nestedTypes: ATOMIC_TYPES, single: ['infobox'],
renderBody: (block, onUpdate) => {
switch (block.type) {
case 'codeTabs': return <CodeTabsFields block={block} onUpdate={onUpdate} />;
case 'columns': return <ColumnsFields block={block} onUpdate={onUpdate} />;
case 'daoTimeline': return <DaoTimelineEdit block={block} onUpdate={onUpdate} />;
}
},
};
<BlockEditor blocks={blocks} onChange={setBlocks} schema={SCHEMA} kit={KIT} />Each block is a card with a toolbar (name, add below, move, duplicate, delete); an add menu of more than eight types opens on a filter box. An option's
groupheads it.The core fields are
CodeTabsFields,StatsFields,TestimonialFields,EventsFields,LocationsFields,ReferencesFields,LinkGridFields,BannerFields,PageListFields,ListFields,ColumnsFieldsandInfoboxFields.Field,ChoiceandLimitFieldare for a wiki's own types.A type the build does not know is shown by its raw type and carried through untouched.
Keep the kit and schema stable (a module constant or
useMemo): both reach every card through context.An editor that draws blocks in place hosts the fields in
<BlockFieldsKit kit={KIT}>.
Analytics
wiki-formant/analytics: page views and events in the site's own Postgres. No cookie and no stored address: a visitor is a hash of address and browser under a salt replaced every UTC day. Rows are kept 400 days. A view is marked engaged once its reader has had the page visible fifteen seconds or given it input, so engaged counts people where agents counts crawlers. Its time on page is the seconds its page was in a visible tab, capped at an hour, sent as the reader hides the tab or moves on. The tables ship in prisma/analytics.prisma; ViewDay holds days a site counted elsewhere first, and AgentDay one row for each agent on each day, so an agent's requests are counted and not kept.
// src/lib/track.ts
const sql: Sql = (query, ...values) => prisma.$queryRawUnsafe(query, ...values);
export const { trackEvent, trackMcpCall, trackFeedback, trackSearch, viewRoute } = createTracker({ sql, defer: after, siteUrl: SITE_URL });
// src/app/api/view/route.ts
export const POST = viewRoute();createTrackerrecords only on a Vercel production deployment unlessenabledsays otherwise. A beacon naming an event the server records is dropped: the tracker's own, and those an app records withtrackEvent, which it lists aseventsand whichtrackEventis then typed to.trackMcpCallfitsMcpServerConfig.onCall;trackSearchnormalises a query and drops an empty one;recordEventis the undeferred write.A proxy reaches the tracker through a dynamic
import()insideevent.waitUntil, since it imports the database client.digest(sql, { days })is the site as one JSON object: people, engaged people, agents, views, visits, bounce rate, median time on page, sources, pages, countries, devices, by day, agents by name, MCP calls, every search people made, everysearch_wikiquery agents made, the searches of either that found nothing, and agents'send_feedbackreports. A search its visitor went on typing within five minutes is left out, as is any of one character. A visit is a run of views with no gap over 30 minutes; a bounce is a one-view visit its reader never engaged with. Agents are counted beside people, never among them: the ranked lists are people's.ownAgentsleaves the site's own out. A multi-tenant app passessite.A browser under automation (
navigator.webdriver) sends no beacon.
Passkeys and the stats page
wiki-formant/passkey: the door to a site's own admin pages, a passkey and nothing else. wiki-formant/stats: the stats page behind it.
// src/lib/admin.ts
export const gate = createPasskeyGate({ sql, rpName: 'Caper' });
// src/app/api/passkey/route.ts
export const POST = gate.route;
export const DELETE = gate.signOut;
// src/app/stats/page.tsx
const q = statsQuery(params);
return (
<StatsGate gate={gate} session={(await cookies()).get(gate.cookie)?.value} invite={params.invite} host="caper.network">
{async () => <Stats digest={await digest(sql, q)} {...q} link={Link} />}
</StatsGate>
);There is no sign-up: every passkey is saved from a single-use link
npx passkey-inviteprints. A passkey is bound to its host. Deleting aPasskeyrow signs out every session it opened. Tokens are kept only as hashes (prisma/passkey.prisma).A challenge store that does not answer is a 503 (
SIGN_IN_UNAVAILABLE,wiki-formant/http), never a refused passkey.gate.signedIn(cookie)is a page's check andgate.allows(request)a write route's.statsQueryreads?days=(1, 7, 30, 90, 365 or all) and the narrowings?segment=,?page=,?entry=,?source=,?country=,?device=, which stack and recount every figure from the visits that pass.?segment=engagedis the visitors who engaged, with every visit of theirs;?segment=agentsis the agents, each one's day a visit and its requests that visit's views, andvisitorsthe agents;?segment=allis people and agents together, each counted as its own segment counts it. The page switches between people, engaged, agents and all beside the windows, so its one Visitors figure and every other reads for each: the bounce rate of engaged visitors, an agent's views per visit. The segment is the switch, never a chip.Each headline figure shows its change from the window before (
.stats-delta[data-better]) and charts on press. A narrowed page overViewDaytotals starts atcounted_fromand says so.
ROLA sign-in
wiki-formant/rola: a Radix wallet sign-in up to the token: a single-use challenge, the wallet's proof, the HS256 session, and the two MCP tools that sign an agent in. How a site keeps the session stays with it.
import { createRola, sessionSecret, signSession, verifySession, bearerToken, rolaLoginTools } from 'wiki-formant/rola';
const rola = createRola({ expectedOrigin, dAppDefinitionAddress, networkId, applicationName, challenges: prisma.challenge });
const v = await rola.verifySignedChallenge(signed); // { isValid, error? }; an outage throws a 503 HttpError
const secret = sessionSecret(process.env.JWT_SECRET); // throws under 32 characters
const token = await signSession({ id: signed.address }, secret, 7 * 86400);
const claims = await verifySession<{ id: string }>(bearerToken(request.headers) ?? cookie, secret);
const tools = rolaLoginTools({
site: 'the wiki', dAppDefinitionAddress, origin: SITE_URL, tokenTtlSec: 7 * 86400, writeTools: 'create_page / edit_page',
generateChallenge: rola.generateChallenge,
login: async signed => issueToken(signed), // { token, expiresAt, ...shown }; throw McpToolError to refuse
notes: { sign: { address: 'your virtual account; its key must be an on-ledger owner_keys entry' } },
});A challenge is spent by one conditional delete whatever the outcome, so one signature cannot pass twice; making one purges the expired. Only an account proof signs in. Verification pins HS256.
rolaLoginToolsgivesget_challenge(the exact message to sign, naming the dApp definition address and the originrolaOriginChecklooks for) andlogin, whose refusal says to fetch a new challenge.notes.challenge,notes.signandnotes.addressadd a surface's own lines.
wiki-formant/rola-client is the browser's half: loadRadixWallet imports @radixdlt/radix-dapp-toolkit (an optional peer) on first use, hands it the challenge, asks for accounts ('one', the default, or 'some') with a proof, and calls onProof(signedChallenge, response) with a fresh answer's first account, never on the replay of a cached wallet; what onProof throws goes to onError, so the wallet's request still settles. It returns the toolkit for the site to mirror walletData$ and send transactions.
const rdt = await loadRadixWallet({
dAppDefinitionAddress, networkId, applicationName: 'Caper',
challenge: async () => (await generateChallenge()).challenge,
onProof: async proof => signIn(await loginWithProof(proof)),
onError: error => toast.error(errorMessage(error)),
});Charts
wiki-formant/chart: TimeChart, every time-series chart: one area series in the box's color, range buttons (24H to All) and day, week and month steps.
<TimeChart series={days} label="Transactions" aggregate="sum" fromZero
markers={[{ time: haltAt, label: 'Network halt' }]} step="month" onView={v => keep(v)} />
<TimeChart series={load} label="Price" format={formatPrice} range="30d" candles />seriesis the points or a loader asked for'hour'(24H),'4h'(7D) or'day', once each.The default step is the finest that makes 200 points or fewer; no step is finer than the points.
aggregateislastfor a price,sumfor a count,meanfor a rate. A stepped range starts on a whole week or month.Points with
open,highandlowget a candles switch; withvolume, a volume pane. A zero-volume point leaves its slot empty.formatgets the tick spacing too;stepDecimalsandformatChartValuekeep ticks at one precision.markersare tooltips on the last point at or before each event.
Base stylesheet
wiki-formant/base.css: the layout the package's markup needs and the package's components drawn on the --ui-* tokens (--ui-surface, --ui-surface-2, --ui-stripe, --ui-border, --ui-radius, --ui-pad, --ui-small, --ui-muted, --ui-accent, --ui-accent-soft, --ui-on-accent, --ui-up, --ui-down, --ui-shadow). Each defaults to the house colour vocabulary (--color-surface-1, --color-text-muted, --color-accent and the rest, listed in base.css), so a site whose @theme uses it maps only what it names otherwise, in its own :root.
The classes on its @dressed line take their look from tokens listed beside their rules: the shell (--shell-*, --footer-*, --header-*, --layout-bg), the rail (--rail-*), the dock (--dock-*), and EmptyState (--empty-*), breadcrumbs (--crumb-*), ArticleMeta (--meta-*), the stats figures (--figure-*), the infobox (--infobox-*), ColumnsView (--columns-*, --column-flex), code blocks (--code-*), SearchField (--search-*) and SectionIndex (--index-*). A site sets the tokens and never restates the class; check-classes --restated enforces it, bar a rule licensed by a /* licensed: <why> */ comment above it.
@import "wiki-formant/base.css" layer(components);It declares the page frame (--content-width 120rem for every page, --sidebar-width 18rem, --infobox-width, --page-pad 16/24/64px) in the components layer, so a site never restates them in @theme; the shell every root layout draws (.app-shell, .app-main, .page-frame, .skip-link), whose header sticks at every width on --header-bg, --header-border and --header-filter and lays out its row on --header-gap, --header-pad, --header-wrap, --header-justify and --header-z, and whose column beside a rail is a flex column --frame-gap apart; the primitives .spinner, .skeleton, .empty-state; and the reduced-motion guard. The rail's rows are tokens a site sets in :root rather than restating wiki-rail__*: --rail-pad-block, --rail-section, --rail-gap, --rail-row, --rail-inline, --rail-size, --rail-ink, --rail-weight, and its title, labels, glyphs, subtrees and "On this page" the same way (--rail-title-*, --rail-label-*, --rail-glyph-*, --rail-subtree-*, --rail-toc-*; the list and defaults are base.css's comment), so no site restates a wiki-rail__* class. It also splits a page beside its infobox at 768px of its column, where the infobox sticks (--infobox-top, --infobox-position), and a ColumnsView row at 40rem of its column: .page-frame is a container, so both read the width they have rather than the window's. The rail's surface is --rail-bg.
Database and scripts
wiki-formant/db: pgPoolConfig(url), ten clients on the 6543 transaction pooler and three on the 5432 session pooler, and prismaConfig(root, schema?), which prefers DIRECT_URL, since the Prisma CLI hangs on the transaction pooler.
// prisma.config.ts
import { defineConfig } from 'prisma/config';
import { prismaConfig } from 'wiki-formant/db';
export default defineConfig(prismaConfig(import.meta.dirname));wiki-formant/scripts: what a seed or sweep script shares: withClient (a pg client that rolls back on a throw and expires the cache tag after a write), readPage, writeRevision (refused if the page moved on), upsertWikiPage (created, updated or unchanged), the block builders content, banner and infobox, and assertLinkShapes.
import { withClient, readPage, writeRevision } from 'wiki-formant/scripts';
await withClient(async client => {
const page = await readPage(client, 'contents/tech', 'radix-engine');
await writeRevision(client, page!, blocks, { change: 'minor', message: 'Why, with the source.' });
}, { tag: 'wiki' });wiki-formant/link-check: auditLinks, each link once with the pages that carry it, probed with probeExternal or the checker's own, and printLinkAudit. verdictOf reads a probe as alive, dead, walled, tls or unreachable; only dead lands in brokenExternal, the rest in unverifiableExternal, which a sweep confirms by hand and never strips.
wiki-formant/knip: the shared knip configuration, spread into each app's knip.ts.
Bins
Run each from the app's root, where .env holds DATABASE_URL.
npx check-classes [--warn] [--compositions] [--unused] [--restated] # a className token no stylesheet defines; 3+ inline utilities; dead selectors; a dressed class restated
npx check-pages https://radix.wiki # the served HTML of every sitemap page
npx analytics-digest --days 7 [--gap "Symptom Miss:term"]
npx passkey-invite https://caper.network/stats [--days n]
npx prisma-models [analytics|passkey|wiki] [--check] [--in prisma/schema.prisma --tenant]
npx fts-ddl '"WikiPage"' # rebuild search_tsv and its index over DIRECT_URL
npx indexnow https://radix.wiki [--hours 6 | --all]
npx mark-verified <tagPath> <slug> | --all <tagPath> [--invalidate wiki]
npx maintenance-log read|write|compact|backlog-add --at <path> --routine <name> [--author <id>]prisma-modelscopies the shipped models intoprisma/schema/(Prisma reads a folder of files; a generatoroutputgains a../), and--checkfails on a missing or drifted copy.--incompares models in one file, and--tenantletssiteIddrop its default and gain a relation.fts-ddlruns before the column is declared inschema.prisma; a PascalCase table goes in quoted.indexnowposts the sitemap rows modified in the window to IndexNow, after checking the origin serves the key file inpublic/. The sitemap must render per request.mark-verifiedstampslastVerifiedAtsofreshnessBannerstops calling a page outdated.maintenance-logis the state of a sweep routine kept in one page'smetadata.state: every mode holds the row lock from read to write,backlog-addfiles an item another routine raised and a stalewritemerges it back, and awritewhosetotalRunsis below the stored one is refused.--sitenames the wiki in a multi-tenant app.
A reusable workflow
.github/workflows/publish-mcp-registry.yml republishes an origin's server to the MCP registry when its server.json version moves.
on:
push: { branches: [main], paths: ['server.json'] }
workflow_dispatch:
jobs:
publish:
uses: tutmoses/wiki-formant/.github/workflows/publish-mcp-registry.yml@main
with:
domain: example.com
secrets:
MCP_REGISTRY_PRIVATE_KEY: ${{ secrets.MCP_REGISTRY_PRIVATE_KEY }}Licence
MIT.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Remote MCP server exposing SMI Aware tools, resources, and skills over Streamable HTTP.
Query, browse, and automate OmegaAI workspaces from any MCP client. Streamable HTTP with OAuth 2.0.
Streamable HTTP MCP gateway for NV oOS fleets — one API key, namespaced tools, quotas and policy.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceExposes LLM Wiki desktop capabilities via Streamable HTTP transport for MCP clients, enabling project listing, file reading, search, and knowledge graph queries through a secure API.MIT
- AlicenseNot gradedqualityBmaintenanceEnables MCP clients to connect, list tools, and invoke the echo tool over HTTP.MIT
- AlicenseNot gradedqualityCmaintenanceEnables MCP clients to connect over stateless Streamable HTTP and authenticate through an existing OAuth 2.1 / OpenID Connect authorization server, with JWT validation, per-tool scope enforcement, and step-up challenges. It ships example scoped tools for reading and creating per-user notes that developers replace with their own.MIT
- AlicenseNot gradedqualityAmaintenanceEnables LLM clients to read, search, create, edit, manage, and upload content across any MediaWiki wiki, including extension-backed querying and OAuth-authenticated writes.8 npmMIT