Tutorial
Build an MCP App: an interactive UI inside the chat
Add an interactive UI to a TypeScript MCP server with the MCP Apps SDK: a ui:// resource, a view that calls tools, a test in MCP Inspector and a text fallback.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
An MCP App is an MCP tool that comes with its own small web interface. When a host that supports the MCP Apps extension calls the tool, it fetches an HTML page from your server through a ui:// resource and shows it inside the conversation, in a sandboxed iframe. The page can receive the tool’s result and call your server’s tools again when the user clicks something. Hosts without MCP Apps support ignore the interface and show the tool’s text result, so one server works everywhere.
In this tutorial you build a colour-contrast checker as an MCP App. The model calls check_contrast with two colours; the user sees a live preview with colour pickers, and changing a colour re-runs the check without another prompt. You will test the interface in MCP Inspector and see the text fallback from the command line. It was written and run on 25 November 2026 against @modelcontextprotocol/server 2.4.0, @modelcontextprotocol/ext-apps 2.0.4 and MCP Inspector 2.16.0.
How an MCP App fits together
MCP Apps is an official MCP extension with the identifier io.modelcontextprotocol/ui, defined in the ext-apps repository and marked Stable in the extensions overview on 25 November 2026. What changed in MCP 2026-07-28 explains how extensions are negotiated. It combines two things the core protocol already has:
| Piece | What it is | In this tutorial |
|---|---|---|
A tool with _meta.ui.resourceUri |
An ordinary tool whose metadata points at an interface | check_contrast |
A ui:// resource |
An HTML document with MIME type text/html;profile=mcp-app |
ui://contrast/checker.html |
| The view | Your HTML and JavaScript, running in a sandboxed iframe in the host | colour pickers and a preview |
| The bridge | postMessage between the view and the host, wrapped by the SDK’s App class |
ontoolresult, callServerTool |
The host can fetch the resource before the tool is even called. When the call completes, it pushes the result to the view. The view never talks to your server directly: when it calls a tool, the host forwards the call, so the host stays in control of what the app can do.
According to the MCP Apps overview, hosts supporting it on 25 November 2026 include Claude, Claude Desktop, VS Code GitHub Copilot, Microsoft 365 Copilot, Goose, Postman, MCPJam and Archestra.AI, and MCP Inspector has partial support.
1. Set up the project
Create a folder and install the server SDK, the MCP Apps SDK and the build tools:
mkdir contrast-app && cd contrast-app
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server@2.4.0 @modelcontextprotocol/ext-apps@2.0.4 zod@4
npm install -D typescript tsx @types/node vite vite-plugin-singlefile
mkdir src
ext-apps has subpath exports for each side: @modelcontextprotocol/ext-apps/server registers the tool and resource, and the package root gives the browser-side App class. npm installs its peer dependencies, including the v2 client and core packages, for you.
Create tsconfig.json. The DOM library is there because the same project holds the browser code:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"lib": ["ES2022", "DOM"],
"types": ["node"]
},
"include": ["*.ts", "src/**/*.ts"]
}
Create vite.config.ts. Hosts render the view with a strict Content Security Policy that blocks outside scripts and styles unless you declare them, so the simplest approach is to bundle everything into one HTML file:
import { defineConfig } from "vite";
import { viteSingleFile } from "vite-plugin-singlefile";
export default defineConfig({
plugins: [viteSingleFile()],
build: { outDir: "dist", rollupOptions: { input: "contrast.html" } },
});
2. Write the tool logic
Keep the logic in its own file so it is easy to test. Create contrast.ts, which computes the WCAG contrast ratio between two hex colours:
// WCAG 2.2 contrast ratio between two hex colours.
export function parseHex(hex: string): [number, number, number] {
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
if (!m) throw new Error(`${hex} is not a six-digit hex colour such as #1a1a1a`);
const n = parseInt(m[1], 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function luminance([r, g, b]: [number, number, number]): number {
const lin = (c: number) => {
const s = c / 255;
return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
};
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
}
export function contrast(foreground: string, background: string) {
const [hi, lo] = [luminance(parseHex(foreground)), luminance(parseHex(background))].sort((a, b) => b - a);
const ratio = Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100;
return {
foreground,
background,
ratio,
normalTextAA: ratio >= 4.5,
largeTextAA: ratio >= 3,
normalTextAAA: ratio >= 7,
};
}
The thresholds are the WCAG ones: 4.5:1 for body text at level AA, 3:1 for large text, 7:1 for AAA.
3. Register the tool and the UI resource
Create server.ts:
import { readFile } from "node:fs/promises";
import path from "node:path";
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import {
registerAppTool,
registerAppResource,
RESOURCE_MIME_TYPE,
} from "@modelcontextprotocol/ext-apps/server";
import * as z from "zod/v4";
import { contrast } from "./contrast.ts";
const UI_URI = "ui://contrast/checker.html";
const HTML_PATH = path.join(import.meta.dirname, "dist", "contrast.html");
function createServer(): McpServer {
const server = new McpServer({ name: "contrast", version: "0.1.0" });
registerAppTool(
server,
"check_contrast",
{
title: "Check colour contrast",
description:
"Check the WCAG contrast ratio between a text colour and a background colour, both six-digit hex such as #1a1a1a. Reports whether the pair passes AA and AAA.",
inputSchema: z.object({
foreground: z.string().describe("Text colour, for example #333333"),
background: z.string().describe("Background colour, for example #ffffff"),
}),
annotations: { readOnlyHint: true },
_meta: { ui: { resourceUri: UI_URI } },
},
async ({ foreground, background }) => {
try {
const r = contrast(foreground, background);
const verdict = r.normalTextAA
? "passes AA for body text"
: r.largeTextAA
? "passes AA for large text only"
: "fails AA";
return {
// Every host shows this text, including hosts without MCP Apps support.
content: [{ type: "text", text: `${foreground} on ${background}: ${r.ratio}:1, ${verdict}.` }],
// The view (and the model) read the numbers without parsing prose.
structuredContent: r,
};
} catch (err) {
return { content: [{ type: "text", text: (err as Error).message }], isError: true };
}
},
);
registerAppResource(server, "Contrast checker", UI_URI, { mimeType: RESOURCE_MIME_TYPE }, async () => ({
contents: [{ uri: UI_URI, mimeType: RESOURCE_MIME_TYPE, text: await readFile(HTML_PATH, "utf8") }],
}));
return server;
}
serveStdio(createServer);
console.error("contrast MCP App server ready");
What each part does:
registerAppToolisregisterToolplus the UI link. The_meta.ui.resourceUrifield is the only thing that makes this tool an app; the SDK also writes the older flatui/resourceUrikey so older hosts find it.contentandstructuredContentdo different jobs.contentis the fallback every host shows and the model reads.structuredContentis the data the view renders. Write the text as if no interface exists, because for some users it will not.registerAppResourceserves the bundled HTML at theui://address withRESOURCE_MIME_TYPE, which istext/html;profile=mcp-app. The specification requires that MIME type and theui://scheme.serveStdiois the same v2 stdio helper as in Build an MCP server in TypeScript. Logs go to stderr, never stdout.
4. Build the view
Create contrast.html. It is an ordinary page; the CSS variable fallback lets a host pass its own text colour:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Contrast checker</title>
<style>
body { font: 15px/1.5 system-ui, sans-serif; margin: 0; padding: 12px; color: var(--color-text-primary, #1a1a1a); }
.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
#sample { padding: 16px; border-radius: 8px; margin: 12px 0; font-size: 18px; }
output { font-weight: 600; }
</style>
</head>
<body>
<div class="row">
<label>Text <input id="fg" type="color" value="#333333" /></label>
<label>Background <input id="bg" type="color" value="#ffffff" /></label>
</div>
<p id="sample">The quick brown fox jumps over the lazy dog.</p>
<p>Contrast: <output id="ratio" aria-live="polite">waiting for the tool result</output></p>
<script type="module" src="./src/app.ts"></script>
</body>
</html>
Create src/app.ts, the code that talks to the host:
import { App } from "@modelcontextprotocol/ext-apps";
type Result = { foreground: string; background: string; ratio: number; normalTextAA: boolean; largeTextAA: boolean };
const fg = document.getElementById("fg") as HTMLInputElement;
const bg = document.getElementById("bg") as HTMLInputElement;
const sample = document.getElementById("sample")!;
const out = document.getElementById("ratio")!;
function render(r: Result) {
fg.value = r.foreground;
bg.value = r.background;
sample.style.color = r.foreground;
sample.style.background = r.background;
const verdict = r.normalTextAA ? "passes AA" : r.largeTextAA ? "large text only" : "fails AA";
out.textContent = `${r.ratio}:1, ${verdict}`;
}
const app = new App({ name: "Contrast checker", version: "0.1.0" });
// The host pushes the result of the tool call that opened this view.
app.ontoolresult = (result) => {
if (result.structuredContent) render(result.structuredContent as Result);
};
// When the user picks a colour, the view calls the server tool itself.
async function recheck() {
const result = await app.callServerTool({
name: "check_contrast",
arguments: { foreground: fg.value, background: bg.value },
});
if (result.structuredContent) render(result.structuredContent as Result);
}
fg.addEventListener("change", recheck);
bg.addEventListener("change", recheck);
await app.connect();
Set the handlers before app.connect(), so the view is ready when the host sends the first result. callServerTool goes through the host, which forwards it to your server; the MCP Apps documentation notes that hosts may restrict which tools an app can call. The App class is a convenience: you could speak the postMessage protocol yourself, but there is little reason to.
Type-check and build:
npx tsc
npx vite build
dist/contrast.html 235.34 kB │ gzip: 61.22 kB
Most of those 235 kB are the SDK and its schema validation. That is fine for a local tool. If size matters, see the SDK’s patterns guide for loading assets from declared origins instead.
5. Check the server from the command line
MCP Inspector’s CLI mode starts your server, sends one request and prints the response. List the tools first:
npx @modelcontextprotocol/inspector --cli npx tsx server.ts --method tools/list
The tool’s metadata carries the link to the interface:
"_meta": {
"ui": {
"resourceUri": "ui://contrast/checker.html"
},
"ui/resourceUri": "ui://contrast/checker.html"
}
Call the tool:
npx @modelcontextprotocol/inspector --cli npx tsx server.ts \
--method tools/call --tool-name check_contrast \
--tool-arg foreground=#767676 --tool-arg background=#ffffff
{
"content": [
{
"type": "text",
"text": "#767676 on #ffffff: 4.54:1, passes AA for body text."
}
],
"structuredContent": {
"foreground": "#767676",
"background": "#ffffff",
"ratio": 4.54,
"normalTextAA": true,
"largeTextAA": true,
"normalTextAAA": false
}
}
This is also the fallback in action. A command-line client has no way to show HTML, so it gets the text, which still answers the question. Try --tool-arg foreground=grey as well and check you get the “is not a six-digit hex colour” message with isError: true. Then read the resource to confirm the host will get the right MIME type:
npx @modelcontextprotocol/inspector --cli npx tsx server.ts --method resources/list
{
"resources": [
{
"name": "Contrast checker",
"uri": "ui://contrast/checker.html",
"mimeType": "text/html;profile=mcp-app"
}
]
}
6. Render it in MCP Inspector
Run Inspector without --cli to get the web interface:
npx @modelcontextprotocol/inspector npx tsx server.ts
Open the URL it prints (by default http://127.0.0.1:6274), switch the server on with its toggle, then:
- Open the Apps tab. It lists tools that have an interface; you should see “Check colour contrast”.
- Select it and fill in
foreground(#767676) andbackground(#ffffff). - Click Open App.
The view loads in a sandboxed frame showing the sample text and “Contrast: 4.54:1, passes AA”. In the protocol log on the right you can watch the sequence: resources/read for the ui:// resource, then tools/call. Now change the text colour to a lighter grey with the picker. The view calls the tool again through the host and updates, for example to “2.85:1, fails AA” for #999999, with a new tools/call in the log and no new prompt to the model.
7. Try it in a chat host
For hosts that start local servers, register the server with absolute paths. For Claude Desktop, for example, add an entry to claude_desktop_config.json:
{
"mcpServers": {
"contrast": {
"command": "npx",
"args": ["tsx", "/absolute/path/to/contrast-app/server.ts"]
}
}
}
Restart the app and ask something like “Is dark grey #555555 on #f0f0f0 readable for body text?”. A host with MCP Apps support shows the interface with the tool result; others show the sentence from content. Web hosts such as Claude in the browser reach servers over HTTP rather than stdio, which means serving the same createServer function over Streamable HTTP and adding authorisation, as in Secure a remote MCP server with OAuth.
Design the fallback on purpose
The specification says that if a host does not support MCP Apps, “tool behaves as standard tool (text-only fallback)”. So design the text result as carefully as the interface:
- Answer the question in
content. “4.54:1, passes AA for body text” is useful on its own. “See the interface” is not. - Keep data and display separate. Put numbers in
structuredContentand let the view format them. The model readscontent, so it never has to parse HTML. - Do not hide actions in the view. If the only way to do something is a button in the interface, users of other hosts cannot do it. Expose it as a tool too.
- Check the capability if you must. The SDK exports
getUiCapability(clientCapabilities)for servers that want to register a different tool when the client does not support apps. For most servers, a good text result is simpler.
Pitfalls
Loading scripts from a CDN. The host’s default Content Security Policy blocks outside origins, so the view loads blank. Bundle into one file, as here, or declare the origins in the resource’s _meta.ui.csp.
Forgetting to rebuild. The server reads dist/contrast.html on each request. Edit src/app.ts, forget npx vite build, and the host keeps showing the old view.
Setting handlers after connect(). The first tool result can arrive straight after the handshake. Register ontoolresult first.
Using a different MIME type. text/html alone is not an MCP App. Use RESOURCE_MIME_TYPE rather than typing the string.
Trusting input from the view. callServerTool arguments come from code running in a browser frame and can be anything. Validate them on the server exactly as you would model input; the Zod schema and the try block here do that.
Copying v1 examples. Many examples use @modelcontextprotocol/sdk/server/mcp.js with Express and session transports. They still work, but new servers should use the v2 packages, which follow the 2026-07-28 specification.
Next steps
- Read what MCP Apps and other extensions mean for the protocol in what changed in MCP 2026-07-28.
- Review the security basics before you share a server in MCP security risks.
- Put the server on the network with Secure a remote MCP server with OAuth.
- Revisit the core server pattern in Build an MCP server in TypeScript.
Covers
Check your understanding
Build an MCP App quiz
How an MCP App fits together, the ui:// resource and its MIME type, content versus structuredContent, the view bridge, testing in Inspector and designing the text fallback.
8 questions · pass mark 70%
Review
Related
- Build an MCP server in TypeScript
Build a small MCP server with the official TypeScript SDK v2, test it from the command line and in MCP Inspector, then connect it to Claude Code or Cursor.
- What changed in MCP 2026-07-28: a stateless protocol
The July 2026 MCP specification removes the handshake and sessions, adds server discovery and deprecates roots and sampling. What it means for you.
- MCP explained: hosts, clients, servers and transports
What MCP is and how the Model Context Protocol connects AI apps to tools and data: hosts, clients, servers, transports and what the 2026-07-28 spec changed.
- MCP resource
Data that an MCP server makes available by URI, such as a file, a database record or an API response, for the host to read into context.
- MCP security: tool poisoning, token scope and the lethal trifecta
The real attacks on MCP setups, from tool poisoning and rug pulls to token passthrough and the lethal trifecta, what hosts do about them, and a checklist.