Add basic-host and basic-server-react examples

Introduce new example implementations to replace simple-host and
simple-server:

- basic-host: Reference host implementation with double-iframe sandbox
  pattern for secure UI isolation (outer iframe validates and relays
  messages, inner iframe renders untrusted tool UI via srcdoc)

- basic-server-react: MCP server example demonstrating tool registration
  with linked UI resources and React UI using the useApp() hook

Build infrastructure updates:
- Add build:all script and simplify CI/pre-commit to use it
- Add examples:dev for watch-mode development workflow

Also change PostMessageTransport logging from info to debug level.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Jonathan Hefner 2025-12-02 13:11:17 -06:00
commit 97310d50c5
10 changed files with 1808 additions and 25 deletions

View file

@ -0,0 +1,27 @@
# Example: Basic Server (React)
An MCP App example with a React UI.
## Overview
- Tool registration with a linked UI resource
- React UI using the [`useApp()`](https://modelcontextprotocol.github.io/ext-apps/api/functions/_modelcontextprotocol_ext-apps_react.useApp.html) hook
- App communication APIs: [`callServerTool`](https://modelcontextprotocol.github.io/ext-apps/api/classes/app.App.html#callservertool), [`sendMessage`](https://modelcontextprotocol.github.io/ext-apps/api/classes/app.App.html#sendmessage), [`sendLog`](https://modelcontextprotocol.github.io/ext-apps/api/classes/app.App.html#sendlog), [`sendOpenLink`](https://modelcontextprotocol.github.io/ext-apps/api/classes/app.App.html#sendopenlink)
## Key Files
- [`server.ts`](server.ts) - MCP server with tool and resource registration
- [`mcp-app.html`](mcp-app.html) / [`src/mcp-app.tsx`](src/mcp-app.tsx) - React UI using `useApp()` hook
## Getting Started
```bash
npm install
npm run dev
```
## How It Works
1. The server registers a `get-time` tool with metadata linking it to a UI HTML resource (`ui://get-time/mcp-app.html`).
2. When the tool is invoked, the Host renders the UI from the resource.
3. The UI uses the MCP App SDK API to communicate with the host and call server tools.

View file

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Time App</title>
<link rel="stylesheet" href="/src/global.css">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/mcp-app.tsx"></script>
</body>
</html>

View file

@ -0,0 +1,34 @@
{
"name": "basic-server-react",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "INPUT=mcp-app.html vite build",
"watch": "INPUT=mcp-app.html vite build --watch",
"serve": "bun server.ts",
"start": "NODE_ENV=development npm run build && npm run serve",
"dev": "NODE_ENV=development concurrently 'npm run watch' 'npm run serve'"
},
"dependencies": {
"@modelcontextprotocol/ext-apps": "../..",
"@modelcontextprotocol/sdk": "^1.22.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"zod": "^3.25.0"
},
"devDependencies": {
"@types/cors": "^2.8.19",
"@types/express": "^5.0.0",
"@types/node": "^22.0.0",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"@vitejs/plugin-react": "^4.3.4",
"concurrently": "^9.2.1",
"cors": "^2.8.5",
"express": "^5.1.0",
"typescript": "^5.9.3",
"vite": "^6.0.0",
"vite-plugin-singlefile": "^2.3.0"
}
}

View file

@ -0,0 +1,104 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js";
import cors from "cors";
import express, { type Request, type Response } from "express";
import fs from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import { RESOURCE_URI_META_KEY } from "../../dist/src/app";
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3001;
const DIST_DIR = path.join(import.meta.dirname, "dist");
const server = new McpServer({
name: "MCP App Server",
version: "1.0.0",
});
// MCP Apps require two-part registration: a tool (what the LLM calls) and a
// resource (the UI it renders). The `_meta` field on the tool links to the
// resource URI, telling hosts which UI to display when the tool executes.
{
const resourceUri = "ui://get-time/mcp-app.html";
server.registerTool(
"get-time",
{
title: "Get Time",
description: "Returns the current server time as an ISO 8601 string.",
inputSchema: {},
outputSchema: { time: z.string() },
_meta: { [RESOURCE_URI_META_KEY]: resourceUri },
},
async (): Promise<CallToolResult> => {
const time = new Date().toISOString();
return {
content: [{ type: "text", text: time }],
structuredContent: { time },
};
},
);
server.registerResource(
resourceUri,
resourceUri,
{},
async (): Promise<ReadResourceResult> => {
const html = await fs.readFile(path.join(DIST_DIR, "mcp-app.html"), "utf-8");
return {
contents: [
// Per the MCP App specification, "text/html+mcp" signals to the Host
// that this resource is indeed for an MCP App UI.
{ uri: resourceUri, mimeType: "text/html+mcp", text: html },
],
};
},
);
}
const app = express();
app.use(cors());
app.use(express.json());
app.post("/mcp", async (req: Request, res: Response) => {
try {
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: true,
});
res.on("close", () => { transport.close(); });
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
} catch (error) {
console.error("Error handling MCP request:", error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: "2.0",
error: { code: -32603, message: "Internal server error" },
id: null,
});
}
}
});
const httpServer = app.listen(PORT, () => {
console.log(`Server listening on http://localhost:${PORT}/mcp`);
});
function shutdown() {
console.log("\nShutting down...");
httpServer.close(() => {
console.log("Server closed");
process.exit(0);
});
}
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);

View file

@ -0,0 +1,12 @@
* {
box-sizing: border-box;
}
html, body {
font-family: system-ui, -apple-system, sans-serif;
font-size: 1rem;
}
code {
font-size: 1em;
}

View file

@ -0,0 +1,63 @@
.main {
--color-primary: #2563eb;
--color-primary-hover: #1d4ed8;
--color-notice-bg: #eff6ff;
min-width: 425px;
> * {
margin-top: 0;
margin-bottom: 0;
}
> * + * {
margin-top: 1.5rem;
}
}
.action {
> * {
margin-top: 0;
margin-bottom: 0;
width: 100%;
}
> * + * {
margin-top: 0.5rem;
}
/* Consistent font for form inputs (inherits from global.css) */
textarea,
input {
font-family: inherit;
font-size: inherit;
}
button {
padding: 0.5rem 1rem;
border: none;
border-radius: 6px;
color: white;
font-weight: bold;
background-color: var(--color-primary);
cursor: pointer;
&:hover,
&:focus-visible {
background-color: var(--color-primary-hover);
}
}
}
.notice {
padding: 0.5rem 0.75rem;
color: var(--color-primary);
text-align: center;
font-style: italic;
background-color: var(--color-notice-bg);
&::before {
content: "ℹ️ ";
font-style: normal;
}
}

View file

@ -0,0 +1,141 @@
/**
* @file App that demonstrates a few features using MCP Apps SDK + React.
*/
import type { App } from "@modelcontextprotocol/ext-apps";
import { useApp } from "@modelcontextprotocol/ext-apps/react";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { StrictMode, useCallback, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import styles from "./mcp-app.module.css";
const IMPLEMENTATION = { name: "Get Time App", version: "1.0.0" };
const log = {
info: console.log.bind(console, "[APP]"),
warn: console.warn.bind(console, "[APP]"),
error: console.error.bind(console, "[APP]"),
};
function extractTime(callToolResult: CallToolResult): string {
const { time } = (callToolResult.structuredContent as { time?: string }) ?? {};
return time ?? "[ERROR]";
}
function GetTimeApp() {
const [toolResult, setToolResult] = useState<CallToolResult | null>(null);
const { app, error } = useApp({
appInfo: IMPLEMENTATION,
capabilities: {},
onAppCreated: (app) => {
app.ontoolinput = async (input) => {
log.info("Received tool call input:", input);
};
app.ontoolresult = async (result) => {
log.info("Received tool call result:", result);
setToolResult(result);
};
app.onerror = log.error;
},
});
if (error) return <div><strong>ERROR:</strong> {error.message}</div>;
if (!app) return <div>Connecting...</div>;
return <GetTimeAppInner app={app} toolResult={toolResult} />;
}
interface GetTimeAppInnerProps {
app: App;
toolResult: CallToolResult | null;
}
function GetTimeAppInner({ app, toolResult }: GetTimeAppInnerProps) {
const [serverTime, setServerTime] = useState("Loading...");
const [messageText, setMessageText] = useState("This is message text.");
const [logText, setLogText] = useState("This is log text.");
const [linkUrl, setLinkUrl] = useState("https://modelcontextprotocol.io/");
useEffect(() => {
if (toolResult) {
setServerTime(extractTime(toolResult));
}
}, [toolResult]);
const handleGetTime = useCallback(async () => {
try {
log.info("Calling get-time tool...");
const result = await app.callServerTool({ name: "get-time", arguments: {} });
log.info("get-time result:", result);
setServerTime(extractTime(result));
} catch (e) {
log.error(e);
setServerTime("[ERROR]");
}
}, [app]);
const handleSendMessage = useCallback(async () => {
const signal = AbortSignal.timeout(5000);
try {
log.info("Sending message text to Host:", messageText);
const { isError } = await app.sendMessage(
{ role: "user", content: [{ type: "text", text: messageText }] },
{ signal },
);
log.info("Message", isError ? "rejected" : "accepted");
} catch (e) {
log.error("Message send error:", signal.aborted ? "timed out" : e);
}
}, [app, messageText]);
const handleSendLog = useCallback(async () => {
log.info("Sending log text to Host:", logText);
await app.sendLog({ level: "info", data: logText });
}, [app, logText]);
const handleOpenLink = useCallback(async () => {
log.info("Sending open link request to Host:", linkUrl);
const { isError } = await app.sendOpenLink({ url: linkUrl });
log.info("Open link request", isError ? "rejected" : "accepted");
}, [app, linkUrl]);
return (
<main className={styles.main}>
<p className={styles.notice}>Watch activity in the DevTools console!</p>
<div className={styles.action}>
<p>
<strong>Server Time:</strong> <code>{serverTime}</code>
</p>
<button onClick={handleGetTime}>Get Server Time</button>
</div>
<div className={styles.action}>
<textarea value={messageText} onChange={(e) => setMessageText(e.target.value)} />
<button onClick={handleSendMessage}>Send Message</button>
</div>
<div className={styles.action}>
<input type="text" value={logText} onChange={(e) => setLogText(e.target.value)} />
<button onClick={handleSendLog}>Send Log</button>
</div>
<div className={styles.action}>
<input type="url" value={linkUrl} onChange={(e) => setLinkUrl(e.target.value)} />
<button onClick={handleOpenLink}>Open Link</button>
</div>
</main>
);
}
createRoot(document.getElementById("root")!).render(
<StrictMode>
<GetTimeApp />
</StrictMode>,
);

View file

@ -0,0 +1 @@
/// <reference types="vite/client" />

View file

@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ESNext",
"lib": ["ESNext", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src", "server.ts"]
}

View file

@ -0,0 +1,25 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { viteSingleFile } from "vite-plugin-singlefile";
const INPUT = process.env.INPUT;
if (!INPUT) {
throw new Error("INPUT environment variable is not set");
}
const isDevelopment = process.env.NODE_ENV === "development";
export default defineConfig({
plugins: [react(), viteSingleFile()],
build: {
sourcemap: isDevelopment ? "inline" : undefined,
cssMinify: !isDevelopment,
minify: !isDevelopment,
rollupOptions: {
input: INPUT,
},
outDir: "dist",
emptyOutDir: false,
},
});