;
resource: UiResourceContent;
allowAttribute: string;
requireToolConsent: boolean;
cacheToolConsent: boolean;
hostContext?: UiHostContext;
appBridgeModuleUrl?: string;
}
export function buildHostHtmlTemplate(input: HostHtmlTemplateInput): string {
const cspContent = buildCspMetaContent(input.resource.meta.csp);
const resourceHtml = applyCspMetaContent(input.resource.html, cspContent);
const sessionToken = safeInlineJSON(input.sessionToken);
const toolArgs = safeInlineJSON(input.toolArgs);
const uiHtml = safeInlineJSON(resourceHtml);
const serverName = safeInlineJSON(input.serverName);
const toolName = safeInlineJSON(input.toolName);
const hostContextJson = safeInlineJSON(input.hostContext ?? {});
const allowAttribute = safeInlineJSON(input.allowAttribute);
const requireToolConsent = safeInlineJSON(input.requireToolConsent);
const cacheToolConsent = safeInlineJSON(input.cacheToolConsent);
const moduleUrl = safeInlineJSON(input.appBridgeModuleUrl ?? DEFAULT_APP_BRIDGE_MODULE_URL);
return `
MCP UI - ${escapeHtml(input.serverName)} / ${escapeHtml(input.toolName)}
`;
}
function buildCspMetaContent(csp: UiResourceCsp | undefined): string | undefined {
if (!csp) return undefined;
const directives: string[] = [];
const push = (key: string, domains?: string[]) => {
if (domains && domains.length > 0) directives.push(`${key} ${domains.join(" ")}`);
};
push("connect-src", csp.connectDomains);
push("script-src", csp.scriptDomains);
push("style-src", csp.styleDomains);
push("font-src", csp.fontDomains);
push("img-src", csp.imgDomains);
push("media-src", csp.mediaDomains);
push("frame-src", csp.frameDomains);
push("worker-src", csp.workerDomains);
push("base-uri", csp.baseUriDomains);
return directives.length > 0 ? directives.join("; ") : undefined;
}
function applyCspMetaContent(html: string, cspContent: string | undefined): string {
if (!cspContent) return html;
const meta = ``;
if (/]*>/i.test(html)) {
return html.replace(/]*)>/i, `${meta}`);
}
return `${meta}${html}`;
}
function safeInlineJSON(value: unknown): string {
// Escape `` and line separators so the value is safe to inline
// inside a