@frontmcp/uipack

中文文档
1.12.2发布于 2026/11/15Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 1.4万

React-free core that builds FrontMCP widget pages: HTML shell with CSP and bridge, template rendering, CDN import resolution

原始使用文档
文档目录19 节
  1. Install
  2. Usage
  3. Building a page around your own markup
  4. Resolving imports to CDN URLs
  5. Rendering a component from npm
  6. Generating the bridge script
  7. Fetching TypeScript definitions
  8. Entry points
  9. Adapters
  10. Shell
  11. Resolver
  12. Component
  13. Bridge runtime
  14. Typings
  15. Utils
  16. Docs
  17. Related packages
  18. Contributing
  19. License

@frontmcp/uipack

@frontmcp/uipack is the React-free core FrontMCP builds widget pages with, on the server. It renders a tool's template into a full HTML page with a Content Security Policy, the call's data and the bridge script that talks to the host; resolves a widget's imports to CDN URLs; and bundles React widget files. @frontmcp/sdk depends on it, so a FrontMCP server already has it. Import it yourself to split a template into functions with html, to test a template without a server with renderToolTemplate(), or to build widget pages for a host of your own.

npm License

Install

npm install @frontmcp/uipack
  • No React dependency. The runtime dependencies are zod and entities (the HTML character reference decoder sanitizeHtml() uses); npm 7 and later also install the peer @frontmcp/lazy-zod, at the same version.
  • esbuild is an optional peer, needed only to bundle .tsx and .jsx widget files. Install it as a dependency, not a dev dependency, since it's loaded when a widget is rendered.
  • highlight.js is an optional peer, needed only for markdown.highlightTheme (ui.runtimeOptions.markdown.highlightTheme). It's loaded from your project when a template uses it.
  • @mdx-js/mdx, react and react-dom are optional peers, needed only to render an MDX template (mdxComponents) on the server, and remark-gfm for one with markdown.gfm. react and react-dom also render a component on the server (uiType: 'react') and a widget to hydrate (hydrate). They're loaded from your project, so the template's components and the renderer share one React.
  • It runs on Node.js 24 or later.

Usage

Render a template the way a tool call does, without a server:

import { html, renderToolTemplate, type TemplateContext } from '@frontmcp/uipack';

type Weather = { city: string; tempC: number };

const badge = (text: string) => html`<span class="badge">${text}</span>`;

const result = renderToolTemplate({
  toolName: 'get_weather',
  input: { city: 'Oslo' },
  output: { city: 'Oslo', tempC: 21 },
  template: (ctx: TemplateContext<{ city: string }, Weather>) =>
    html`<h2>${ctx.output.city} ${badge(`${ctx.output.tempC}°C`)}</h2>`,
});

result.html is a whole HTML document whose body is <h2>Oslo <span class="badge">21°C</span></h2>, result.uiType is "html", and result.meta["ui/mimeType"] is "text/html;profile=mcp-app". Values interpolated into html are escaped, so a city of <script> renders as &lt;script&gt;; markup built with html or trustedHtml() isn't escaped twice. html is the same builder as a tool template's ctx.helpers.html, so pieces of a widget can live in their own file and be tested on their own (Splitting a template into functions).

Building a page around your own markup

import { buildShell } from '@frontmcp/uipack/shell';

const { html, hash, size } = buildShell('<div id="root"></div>', {
  toolName: 'get_weather',
  input: { city: 'London' },
  output: { temp: 18 },
  includeBridge: true,
  csp: { connectDomains: ['https://api.weather.com'] },
});

hash is a short, non-cryptographic hash of the page, for cache keys, and size its length in bytes. The page looks like this, with the bridge script shortened:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta
      http-equiv="Content-Security-Policy"
      content="default-src 'none'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net ... https://esm.sh; ... connect-src https://cdn.jsdelivr.net ... https://esm.sh https://api.weather.com; ..."
    />
    <script>
      window.__mcpAppsEnabled = true;
      window.__mcpToolName = 'get_weather';
      window.__mcpToolInput = { city: 'London' };
      window.__mcpToolOutput = { temp: 18 };
      window.__mcpStructuredContent = null;
    </script>
    <script>
      /* the bridge: picks an adapter for the host and sets window.FrontMcpBridge */
    </script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Resolving imports to CDN URLs

import { createEsmShResolver, rewriteImports } from '@frontmcp/uipack/resolver';

const resolver = createEsmShResolver({ providerOrder: ['cloudflare', 'jsdelivr'] });

resolver.resolve('chart.js');
// { value: 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.1/chart.umd.min.js', type: 'url' }

rewriteImports("import { format } from 'date-fns';", { resolver }).code;
// "import { format } from 'https://esm.sh/date-fns';"

A package in the CDN registry (react, react-dom, chart.js, d3, lodash) resolves to its registered URL, trying the providers in providerOrder; any other package resolves to https://esm.sh/<specifier>.

Rendering a component from npm

import { renderComponent } from '@frontmcp/uipack/component';

const { html } = renderComponent(
  { source: { npm: 'my-weather-widget', exportName: 'WeatherCard' } },
  { toolName: 'get_weather', output: { temp: 18 } },
);

renderComponent() is synchronous. The page imports the component from https://esm.sh/my-weather-widget, loads React from esm.sh through an import map, and renders the component into #root with the tool's output as its props. The source can be any of these:

SourceShapeWhat happens
npm{ npm: 'my-chart', exportName?, version? }Loaded from its CDN registry entry, or from esm.sh.
file{ file: '/abs/path/widget.tsx', exportName?, inline? }A local file. .tsx and .jsx files are bundled with esbuild; a relative path resolves from the working directory.
import{ import: 'https://cdn.example.com/widget.js', exportName? }A module URL, used as it is.
function(input, output) => '<div>…</div>'Returns the HTML.

Generating the bridge script

import { BRIDGE_SCRIPT_TAGS, generateBridgeIIFE } from '@frontmcp/uipack/bridge-runtime';

const everyHost = BRIDGE_SCRIPT_TAGS.universal;
const openAiOnly = `<script>${generateBridgeIIFE({ adapters: ['openai', 'generic'], minify: true })}</script>`;

The script detects the host and sets window.FrontMcpBridge:

MemberDescription
adapterId, initialized, capabilitiesThe adapter picked for the host, whether it's ready, and what it can do.
getToolInput(), getToolOutput(), getStructuredContent()The call's data, from the page and then from each result the host sends.
callTool(name, args)Calls a tool through the host and returns the host's result.
onToolResult(callback), onContextChange(callback)Subscribe to results and to host changes. Each returns an unsubscribe function.
getTheme(), getDisplayMode(), getHostContext(), hasCapability(name)What the host said about itself.
sendMessage(text), openLink(url)Add a message to the conversation, open a link, through the host.
requestDisplayMode(mode), setSize({ width?, height? }), requestClose()Ask for inline, fullscreen or pip, report the widget's size, ask to remove the widget.
updateModelContext(data, merge?)Tell the host what the model should know, where the host supports it.
getWidgetState(), setWidgetState(state)State kept in localStorage.

Fetching TypeScript definitions

import { createTypeFetcher } from '@frontmcp/uipack/typings';

const fetcher = createTypeFetcher({ allowedPackages: ['@myorg/*'], maxDepth: 3 });
const { results, errors } = await fetcher.fetchBatch({ imports: ["import { z } from 'zod'"] });
// results[0].files: the .d.ts files, at virtual node_modules/ paths

It fetches the .d.ts files of each import from esm.sh, following their own imports up to maxDepth (default 2). Only allowed packages are fetched: react, react-dom, react/jsx-runtime, zod and @frontmcp/*, plus allowedPackages, or any package with allowedPackages: false.

Entry points

@frontmcp/uipack exports everything below. Each module is also its own entry point:

ImportWhat's in it
@frontmcp/uipack/adaptersrenderToolTemplate(), MCP_APPS_MIME_TYPE, and the helpers the SDK uses to build a tool's widget response.
@frontmcp/uipack/shellbuildShell(), html, trustedHtml(), template helpers, CSP, custom shells.
@frontmcp/uipack/resolverImport resolution, the CDN registry, import maps.
@frontmcp/uipack/componentrenderComponent() and the component sources.
@frontmcp/uipack/bridge-runtimeThe bridge script generator.
@frontmcp/uipack/typingsThe .d.ts fetcher and its cache.
@frontmcp/uipack/typesTypes for widget configuration, such as UITemplateConfig and TemplateContext.
@frontmcp/uipack/utilsEscaping helpers.

Adapters

ExportDescription
renderToolTemplate(options)Renders a template as a call does: { html, uiType, hash, size, meta }. Options: toolName, input, output, template, platformType?, resourceMode?, sizing?, csp?, escapeStringResults?, contentSecurity? (sanitize the template's markup with sanitizeHtml()), markdown? ({ gfm?, highlightTheme? } for a Markdown or MDX template), mdxComponents? (a string template is MDX, rendered on the server with these components), uiType? (force the renderer: 'html', 'markdown', 'mdx', 'react'), hydrate? (render a { file } widget on the server and hydrate it). Throws for an option the template can't take; under tsx, await prepareRenderOptions() before rendering MDX.
describeRenderOptionProblems(template, options)The rendering options set for a template that it can't take, one sentence each; [] when there are none.
MCP_APPS_MIME_TYPE"text/html;profile=mcp-app".

Shell

ExportDescription
buildShell(content, config)A page around content: { html, hash, size }. config: toolName (required), input, output, structuredContent, csp, includeBridge (default true), withShell (default true; false returns the data script and the content only), title, sizing, displayMode, customShell.
html`…`, trustedHtml(markup), isTrustedHtml(value)Build, mark and detect trusted markup. Values interpolated into html are escaped.
sanitizeHtml(markup, policy?)What ui.contentSecurity does. It reads markup as the browser's tokenizer does and writes every tag back out, each attribute value decoded once, checked and written back escaped. It removes <script>, on* handlers, srcdoc, <object>/<embed>/<applet>, <base>, <meta>, SVG animations, data-tool-call/data-tool-args, comments, URL attributes whose scheme isn't http:, https: or mailto:, @import in <style>, cross-origin <link rel=stylesheet>, and position: fixed/sticky in style attributes. policy: allowInlineScripts, allowUnsafeLinks, allowToolCallAttributes, bypassSanitization, maxMarkupLength (default DEFAULT_MAX_MARKUP_LENGTH, 2 Mi characters; longer markup throws). Linear time.
describeContentSecurityProblems(policy)Why a value can't be a ui.contentSecurity policy (not a plain object, a flag that isn't boolean, an unknown key), one sentence each.
createTemplateHelpers()A new set of template helpers: escapeHtml, formatDate, formatCurrency, uniqueId, jsonEmbed, html, trustedHtml.
buildCSPDirectives(csp?), buildCSPMetaTag(csp?)The page's policy: the default CDN origins plus connectDomains and resourceDomains.
buildDataInjectionScript({ toolName, input?, output?, structuredContent?, sizing?, displayMode? })The <script> that sets window.__mcpToolName, __mcpToolInput, __mcpToolOutput and __mcpStructuredContent.
resolveShellTemplate(source, options?)Async. Loads a custom shell from { inline }, { url, timeout? } or { npm, exportName?, version? }, and validates it.
validateShellTemplate(template), applyShellTemplate(template, values)Check and fill a custom shell's placeholders: {{CONTENT}} (required), {{CSP}}, {{DATA}}, {{BRIDGE}}, {{TITLE}}.
DEFAULT_CDN_DOMAINSThe origins every page allows: jsDelivr, cdnjs, Google Fonts and esm.sh.

Resolver

ExportDescription
createEsmShResolver({ registry?, providerOrder?, fallbackCdnBase? })The default resolver.
createResolverWithOverrides(overrides, options?)The default resolver, with fixed URLs for some packages.
DEFAULT_CDN_REGISTRY, mergeRegistries(custom)The registry (react, react-dom, chart.js, d3, lodash), and it merged with your entries.
lookupPackage(name, registry?), getPackageCDNUrl(name, providerOrder?, registry?)Query the registry.
parseImports(source), extractExternalPackages(source)The imports in source code, and the packages they name.
rewriteImports(source, { resolver?, skipPackages?, overrides? })Replaces bare specifiers with CDN URLs: { code, rewrittenCount, rewrites, fallbackPackages }.
createImportMap(dependencies), mergeImportMaps(...maps), generateImportMapScriptTag(map)Build, merge and write a browser import map.

Component

ExportDescription
renderComponent(config, shellConfig)Resolves config.source and builds the page around it: { html, hash, size }.
resolveUISource(source, options?)Resolves a source to a ResolvedComponent.
generateMountScript(resolved, propsMapping?)The module script that imports and mounts a module component.
bundleFileSource(), transpileReactSource()Bundle or transpile a .tsx or .jsx widget with esbuild.
isNpmSource, isFileSource, isImportSource, isFunctionSourceType guards for the sources.

Bridge runtime

ExportDescription
generateBridgeIIFE(options?)The bridge script. Options: adapters (from openai, ext-apps, claude, gemini, generic), debug, trustedOrigins, minify.
generatePlatformBundle(platform, options?)The script for chatgpt, claude, gemini or universal.
UNIVERSAL_BRIDGE_SCRIPTThe script with every adapter.
BRIDGE_SCRIPT_TAGS{ universal, chatgpt, claude, gemini }, each wrapped in <script>.

Typings

ExportDescription
createTypeFetcher(options?, cache?)A TypeFetcher. Options: allowedPackages, maxDepth, timeout (10 s per request), maxConcurrency (5), cdnBaseUrl, fetch.
TypeFetcherfetchBatch({ imports, maxDepth?, timeout? }): { results, errors, totalTimeMs, cacheHits }.
MemoryTypeCache, globalTypeCacheA least-recently-used cache with expiry; the shared one keeps up to 500 entries for an hour.
parseDtsImports(content), combineDtsContents(contents)Parse a .d.ts file's imports; join several files into one.

Utils

ExportDescription
escapeHtml(value)Escapes &, <, >, " and ', and U+2028 and U+2029. null and undefined give ''.
escapeHtmlAttr(value)Escapes & and ", for attribute values.
escapeJsString(value)Escapes a string for a JavaScript string literal.
escapeScriptClose(json)Replaces </ with <\/, so the text can't close a <script>.
safeJsonForScript(value)JSON safe to put in a <script>: <, > and & escaped, BigInt as a string, and {"error":"Value could not be serialized"} for a value JSON can't hold, such as a circular one.
safeStringify(value, space?)JSON.stringify that writes [Circular] for circular references.

Docs

  • @frontmcp/sdk: the server framework; it renders a tool's ui with this package.
  • @frontmcp/ui: the React components, hooks and renderers for widget files.
  • @frontmcp/testing: test helpers, with matchers for a tool's rendered widget.

Contributing

Source: libs/uipack. Issues and pull requests are welcome; see CONTRIBUTING.md.

The source has one folder per entry point under src/: adapters/, shell/, resolver/, component/, bridge-runtime/, typings/, types/ and utils/. utils and bridge-runtime depend on nothing else; resolver uses utils; shell uses utils, resolver and bridge-runtime; component builds on shell; adapters uses them all; typings stands alone, and types only imports types. Test escaping and Content Security Policy changes with hostile input. In the monorepo:

nx build uipack
nx test uipack
nx lint uipack

License

Apache-2.0. See LICENSE.

版本与发布记录

@frontmcp/uipack 共发布 113 个版本,首次发布于 2025/12/23;过去 12 个月发布了 113 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.12.2latest2026/11/151 天前
1.12.12026/11/132 天前
1.12.02026/11/114 天前
1.12.0-rc.1rc2026/11/114 天前
1.11.32026/11/106 天前
1.11.22026/11/096 天前

其他发布通道:beta → 1.1.2-beta.1,rc → 1.12.0-rc.1。

关于 @frontmcp/uipack 的常见问题

@frontmcp/uipack 是什么?

React-free core that builds FrontMCP widget pages: HTML shell with CSP and bridge, template rendering, CDN import resolution

如何安装 @frontmcp/uipack?

在项目目录运行 npm install @frontmcp/uipack,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@frontmcp/lazy-zod(1.12.2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@frontmcp/uipack 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@frontmcp/uipack 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@frontmcp/uipack 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@frontmcp/uipack 可以商用吗?

@frontmcp/uipack 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@frontmcp/uipack 的下载量有多少?

根据 npm 官方下载统计,@frontmcp/uipack 在 2026/10/16 – 2026/11/14 这 30 天内被下载 13,821 次,日均约 461 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@frontmcp/uipack 还在维护吗?

最新版本 1.12.2 发布于 2026/11/15(1 天前);至今共发布 113 个版本,其中过去 12 个月发布了 113 个;首次发布于 2025/12/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。