惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
T
Threatpost
P
Palo Alto Networks Blog
NISL@THU
NISL@THU
O
OpenAI News
Project Zero
Project Zero
G
GRAHAM CLULEY
P
Privacy International News Feed
A
Arctic Wolf
Microsoft Azure Blog
Microsoft Azure Blog
H
Help Net Security
M
MIT News - Artificial intelligence
T
Threat Research - Cisco Blogs
S
Security @ Cisco Blogs
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
D
Docker
aimingoo的专栏
aimingoo的专栏
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
W
WeLiveSecurity
P
Proofpoint News Feed
腾讯CDC
Cloudbric
Cloudbric
S
Secure Thoughts
C
Check Point Blog
博客园 - Franky
T
The Exploit Database - CXSecurity.com
T
Troy Hunt's Blog
GbyAI
GbyAI
Security Archives - TechRepublic
Security Archives - TechRepublic
Application and Cybersecurity Blog
Application and Cybersecurity Blog
月光博客
月光博客
C
Cyber Attacks, Cyber Crime and Cyber Security
I
Intezer
TaoSecurity Blog
TaoSecurity Blog
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
F
Fortinet All Blogs
博客园 - 叶小钗
C
CXSECURITY Database RSS Feed - CXSecurity.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recorded Future
Recorded Future
C
Cisco Blogs
博客园 - 司徒正美
Stack Overflow Blog
Stack Overflow Blog
Y
Y Combinator Blog
Apple Machine Learning Research
Apple Machine Learning Research

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building MCP Apps with Angular
Dale Nguyen · 2026-04-25 · via DEV Community

If you've been building MCP servers, you know the drill: your tool returns JSON, the host renders it as text, and the user squints at a timestamp string. MCP Apps change that — they let your server ship an interactive UI that the host renders in an iframe, right inside the conversation.

MCP Apps are built on the Model Context Protocol — an open standard. They're not tied to Claude or any specific AI provider. Any host that implements the MCP Apps specification (Claude Desktop, custom chat clients, or other AI assistants that adopt MCP) can render your UI. You build it once, and it works everywhere MCP is supported.

This post walks through building MCP Apps with Angular. We'll start with a single tool, add a second tool with its own UI, and then show how to share code between them without bloating either bundle.

How MCP Apps Work (Quick Recap)

View (Angular App) <--PostMessageTransport--> Host (AppBridge) <--MCP Client--> MCP Server

Enter fullscreen mode Exit fullscreen mode

  • Server registers tools and resources. Each tool can point to a resource URI containing the UI.
  • Host (the chat client) fetches that resource and renders it in a sandboxed iframe.
  • View is your Angular app running inside that iframe. It uses the App class from @modelcontextprotocol/ext-apps to communicate with the host.

The key insight: your UI is bundled into a single self-contained HTML file using Vite and vite-plugin-singlefile. The host doesn't need to know it's Angular — it just loads HTML.

Project Structure

basic-server-angular/
├── mcp-app.html              # HTML entry point for UI #1
├── greeting-app.html         # HTML entry point for UI #2
├── src/
│   ├── main.ts               # Angular bootstrap for UI #1
│   ├── app.component.ts      # Get Time component
│   ├── greeting-main.ts      # Angular bootstrap for UI #2
│   ├── greeting.component.ts # Greeting component
│   ├── shared/
│   │   └── mcp-app-setup.ts  # Shared App + theming setup
│   └── global.css            # Host-aware CSS variables
├── server.ts                 # MCP server (registers tools + resources)
├── main.ts                   # Server entry point (HTTP + stdio)
└── vite.config.ts            # Builds each HTML into a single file

Enter fullscreen mode Exit fullscreen mode

Step 1: The Server

Every MCP App starts on the server side. You register a tool (what the LLM calls) and a resource (the HTML that gets rendered). They're linked by a resource URI.

// server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js";
import fs from "node:fs/promises";
import path from "node:path";
import {
  registerAppTool,
  registerAppResource,
  RESOURCE_MIME_TYPE,
} from "@modelcontextprotocol/ext-apps/server";

const DIST_DIR = import.meta.filename.endsWith(".ts")
  ? path.join(import.meta.dirname, "dist")
  : import.meta.dirname;

export function createServer(): McpServer {
  const server = new McpServer({
    name: "Basic MCP App Server (Angular)",
    version: "1.0.0",
  });

  const resourceUri = "ui://get-time/mcp-app.html";

  // Register the tool — this is what the LLM calls
  registerAppTool(server, "get-time", {
    title: "Get Time",
    description: "Returns the current server time as an ISO 8601 string.",
    inputSchema: {},
    _meta: { ui: { resourceUri } }, // Links this tool to its UI
  }, async (): Promise<CallToolResult> => {
    const time = new Date().toISOString();
    return { content: [{ type: "text", text: time }] };
  });

  // Register the resource — the bundled HTML for this tool's UI
  registerAppResource(server, resourceUri, resourceUri, {
    mimeType: RESOURCE_MIME_TYPE,
  }, async (): Promise<ReadResourceResult> => {
    const html = await fs.readFile(
      path.join(DIST_DIR, "mcp-app.html"),
      "utf-8",
    );
    return {
      contents: [{ uri: resourceUri, mimeType: RESOURCE_MIME_TYPE, text: html }],
    };
  });

  return server;
}

Enter fullscreen mode Exit fullscreen mode

The _meta.ui.resourceUri is the glue. When the host calls this tool, it reads that field to know which resource to fetch and render.

Step 2: The HTML Entry Point

Each UI needs an HTML file at the project root. This is the Vite entry point that gets bundled into a single self-contained file.

<!-- mcp-app.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="color-scheme" content="light dark">
  <title>Get Time App</title>
  <link rel="stylesheet" href="/src/global.css">
</head>
<body>
  <app-root></app-root>
  <script type="module" src="/src/main.ts"></script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Step 3: The Angular App

The bootstrap is minimal — Angular 19+ with zoneless change detection:

// src/main.ts
import "@angular/compiler";
import { bootstrapApplication } from "@angular/platform-browser";
import { provideZonelessChangeDetection } from "@angular/core";
import { AppComponent } from "./app.component";
import "./global.css";

bootstrapApplication(AppComponent, {
  providers: [provideZonelessChangeDetection()],
}).catch((err) => console.error(err));

Enter fullscreen mode Exit fullscreen mode

Now the component itself. The App class from @modelcontextprotocol/ext-apps is the bridge between your Angular code and the host:

// src/app.component.ts
import { Component, type OnInit, signal } from "@angular/core";
import {
  App,
  applyDocumentTheme,
  applyHostStyleVariables,
  applyHostFonts,
  type McpUiHostContext,
} from "@modelcontextprotocol/ext-apps";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";

function extractText(result: CallToolResult): string {
  return result.content?.find((c) => c.type === "text")!.text;
}

@Component({
  selector: "app-root",
  template: `
    <main
      [style.padding-top.px]="hostContext()?.safeAreaInsets?.top"
      [style.padding-right.px]="hostContext()?.safeAreaInsets?.right"
      [style.padding-bottom.px]="hostContext()?.safeAreaInsets?.bottom"
      [style.padding-left.px]="hostContext()?.safeAreaInsets?.left"
    >
      <p><strong>Server Time:</strong> <code>{{ serverTime() }}</code></p>
      <button (click)="handleGetTime()">Get Server Time</button>
    </main>
  `,
})
export class AppComponent implements OnInit {
  private app: App | null = null;
  hostContext = signal<McpUiHostContext | undefined>(undefined);
  serverTime = signal("Loading...");

  async ngOnInit() {
    const instance = new App({ name: "Get Time App", version: "1.0.0" });

    instance.ontoolresult = (result) => {
      this.serverTime.set(extractText(result));
    };

    instance.onhostcontextchanged = (params) => {
      const ctx = { ...this.hostContext(), ...params };
      this.hostContext.set(ctx);
      if (ctx.theme) applyDocumentTheme(ctx.theme);
      if (ctx.styles?.variables) applyHostStyleVariables(ctx.styles.variables);
      if (ctx.styles?.css?.fonts) applyHostFonts(ctx.styles.css.fonts);
    };

    await instance.connect();
    this.app = instance;

    const ctx = instance.getHostContext();
    this.hostContext.set(ctx);
    if (ctx?.theme) applyDocumentTheme(ctx.theme);
    if (ctx?.styles?.variables) applyHostStyleVariables(ctx.styles.variables);
    if (ctx?.styles?.css?.fonts) applyHostFonts(ctx.styles.css.fonts);
  }

  async handleGetTime() {
    if (!this.app) return;
    try {
      const result = await this.app.callServerTool({
        name: "get-time",
        arguments: {},
      });
      this.serverTime.set(extractText(result));
    } catch {
      this.serverTime.set("[ERROR]");
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

A few things to note:

  • App class — this is the SDK's main entry point. You create one, wire up callbacks, and call connect(). That's it.
  • ontoolresult — fires when the host sends a tool result. This is how data flows from the server to your UI.
  • callServerTool() — lets the UI call tools on the server. The host proxies this through the MCP client.
  • onhostcontextchanged — the host pushes theme and style updates. The helper functions (applyDocumentTheme, etc.) apply them as CSS variables on document, so your component styles just work.
  • safeAreaInsets — the host tells you how much padding to leave for its chrome. Use it on your root container.

Get Time MCP App running inside Claude Desktop

Step 4: Adding a Second UI

Here's where it gets interesting. Say you want a "Greet" tool with its own UI. Each tool gets its own HTML entry point, its own Angular app, and its own resource registration.

Server: Register Both Tools

// server.ts — inside createServer()

// Tool #1: Get Time
const timeResourceUri = "ui://get-time/mcp-app.html";
registerAppTool(server, "get-time", {
  title: "Get Time",
  description: "Returns the current server time.",
  inputSchema: {},
  _meta: { ui: { resourceUri: timeResourceUri } },
}, async (): Promise<CallToolResult> => {
  return { content: [{ type: "text", text: new Date().toISOString() }] };
});
registerAppResource(server, timeResourceUri, timeResourceUri, {
  mimeType: RESOURCE_MIME_TYPE,
}, async (): Promise<ReadResourceResult> => {
  const html = await fs.readFile(path.join(DIST_DIR, "mcp-app.html"), "utf-8");
  return { contents: [{ uri: timeResourceUri, mimeType: RESOURCE_MIME_TYPE, text: html }] };
});

// Tool #2: Greet
const greetResourceUri = "ui://greet/greeting-app.html";
registerAppTool(server, "greet", {
  title: "Greet",
  description: "Returns a personalised greeting.",
  inputSchema: {
    name: z.string().optional().default("World").describe("Name to greet"),
  },
  _meta: { ui: { resourceUri: greetResourceUri } },
}, async ({ name }: { name?: string }): Promise<CallToolResult> => {
  const greeting = `Hello, ${name || "World"}! Welcome to the MCP Apps SDK.`;
  return { content: [{ type: "text", text: greeting }] };
});
registerAppResource(server, greetResourceUri, greetResourceUri, {
  mimeType: RESOURCE_MIME_TYPE,
}, async (): Promise<ReadResourceResult> => {
  const html = await fs.readFile(path.join(DIST_DIR, "greeting-app.html"), "utf-8");
  return { contents: [{ uri: greetResourceUri, mimeType: RESOURCE_MIME_TYPE, text: html }] };
});

Enter fullscreen mode Exit fullscreen mode

Greeting Component

// src/greeting.component.ts
import { Component, type OnInit, signal } from "@angular/core";
import { FormsModule } from "@angular/forms";
import {
  App,
  applyDocumentTheme,
  applyHostStyleVariables,
  applyHostFonts,
  type McpUiHostContext,
} from "@modelcontextprotocol/ext-apps";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";

@Component({
  selector: "greeting-root",
  imports: [FormsModule],
  template: `
    <main
      [style.padding-top.px]="hostContext()?.safeAreaInsets?.top"
      [style.padding-right.px]="hostContext()?.safeAreaInsets?.right"
      [style.padding-bottom.px]="hostContext()?.safeAreaInsets?.bottom"
      [style.padding-left.px]="hostContext()?.safeAreaInsets?.left"
    >
      <div>
        <label><strong>Your name:</strong></label>
        <input type="text" [(ngModel)]="nameText" placeholder="Enter your name">
        <button (click)="handleGreet()">Get Greeting</button>
      </div>
      @if (greeting()) {
        <div class="greeting-display">{{ greeting() }}</div>
      }
    </main>
  `,
})
export class GreetingComponent implements OnInit {
  private app: App | null = null;
  hostContext = signal<McpUiHostContext | undefined>(undefined);
  greeting = signal("");
  nameText = "";

  async ngOnInit() {
    const instance = new App({ name: "Greeting App", version: "1.0.0" });
    instance.ontoolresult = (result) => {
      this.greeting.set(result.content?.find((c) => c.type === "text")!.text);
    };
    instance.onhostcontextchanged = (params) => {
      const ctx = { ...this.hostContext(), ...params };
      this.hostContext.set(ctx);
      if (ctx.theme) applyDocumentTheme(ctx.theme);
      if (ctx.styles?.variables) applyHostStyleVariables(ctx.styles.variables);
      if (ctx.styles?.css?.fonts) applyHostFonts(ctx.styles.css.fonts);
    };
    await instance.connect();
    this.app = instance;
    const ctx = instance.getHostContext();
    this.hostContext.set(ctx);
    if (ctx?.theme) applyDocumentTheme(ctx.theme);
    if (ctx?.styles?.variables) applyHostStyleVariables(ctx.styles.variables);
    if (ctx?.styles?.css?.fonts) applyHostFonts(ctx.styles.css.fonts);
  }

  async handleGreet() {
    if (!this.app) return;
    try {
      const name = this.nameText.trim() || "World";
      const result = await this.app.callServerTool({ name: "greet", arguments: { name } });
      this.greeting.set(result.content?.find((c) => c.type === "text")!.text);
    } catch {
      this.greeting.set("[ERROR]");
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Greeting MCP App running inside Claude Desktop

Step 5: Sharing Code Between UIs

You probably noticed that both components have identical App setup and theming boilerplate. That's a great candidate for extraction — and since each HTML is a separate Vite entry point, Vite's tree-shaking ensures each bundle only includes what it actually imports.

// src/shared/mcp-app-setup.ts
import {
  App,
  applyDocumentTheme,
  applyHostStyleVariables,
  applyHostFonts,
  type McpUiHostContext,
} from "@modelcontextprotocol/ext-apps";
import type { WritableSignal } from "@angular/core";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";

export function extractText(result: CallToolResult): string {
  return result.content?.find((c) => c.type === "text")!.text;
}

function applyContext(ctx: McpUiHostContext): void {
  if (ctx.theme) applyDocumentTheme(ctx.theme);
  if (ctx.styles?.variables) applyHostStyleVariables(ctx.styles.variables);
  if (ctx.styles?.css?.fonts) applyHostFonts(ctx.styles.css.fonts);
}

export async function createMcpApp(
  name: string,
  hostContext: WritableSignal<McpUiHostContext | undefined>,
  onToolResult?: (result: CallToolResult) => void,
): Promise<App> {
  const app = new App({ name, version: "1.0.0" });
  if (onToolResult) app.ontoolresult = onToolResult;
  app.onhostcontextchanged = (params) => {
    const ctx = { ...hostContext(), ...params } as McpUiHostContext;
    hostContext.set(ctx);
    applyContext(ctx);
  };
  await app.connect();
  const ctx = app.getHostContext();
  hostContext.set(ctx);
  if (ctx) applyContext(ctx);
  return app;
}

Enter fullscreen mode Exit fullscreen mode

Both components import createMcpApp and extractText from the shared module. Since they're in separate Vite builds, tree-shaking still applies — each bundle only pulls in what it calls.

Step 6: The Build

// vite.config.ts
import { defineConfig } from "vite";
import { viteSingleFile } from "vite-plugin-singlefile";

const INPUT = process.env.INPUT;
if (!INPUT) throw new Error("INPUT environment variable is not set");

export default defineConfig({
  plugins: [viteSingleFile()],
  build: {
    rollupOptions: { input: INPUT },
    outDir: "dist",
    emptyOutDir: false, // Key: don't wipe previous builds
  },
});

Enter fullscreen mode Exit fullscreen mode

{
  "scripts": {
    "build": "tsc --noEmit && cross-env INPUT=mcp-app.html vite build && cross-env INPUT=greeting-app.html vite build && tsc -p tsconfig.server.json && bun build server.ts --outdir dist --target node"
  }
}

Enter fullscreen mode Exit fullscreen mode

Each HTML file produces a fully self-contained output (all JS, CSS, and Angular runtime inlined). The two bundles are completely independent.

Theming: Looking Native in Any Host

:root {
  color-scheme: light dark;
  --color-text-primary: light-dark(#1f2937, #f3f4f6);
  --color-background-primary: light-dark(#ffffff, #1a1a1a);
  --color-accent: #2563eb;
  --border-radius-md: 6px;
  --spacing-unit: var(--font-text-md-size);
}

Enter fullscreen mode Exit fullscreen mode

When the host sends style updates via onhostcontextchanged, the helper functions overwrite these variables on the document root. Your Angular component styles reference the variables (var(--color-accent), var(--spacing-md)), so they adapt automatically — no theme prop drilling needed.

Recap

  1. Server: register a tool + resource pair per UI, linked by a resource URI
  2. HTML: one entry point per UI, each bootstrapping its own Angular app
  3. Component: create an App instance, wire up callbacks, call connect()
  4. Shared code: extract common setup into a shared module — Vite tree-shakes per entry point
  5. Build: run Vite once per HTML file into the same dist/ directory
  6. Theming: use host CSS variables with fallbacks, apply updates via onhostcontextchanged

The full source is available in the ext-apps examples.