add a raw (no sdk) UI

This commit is contained in:
ochafik 2025-11-23 03:14:19 +00:00
commit ec306a8698
5 changed files with 318 additions and 4790 deletions

File diff suppressed because it is too large Load diff

View file

@ -5,14 +5,14 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "rm -rf dist && VITE_ENTRY=ui-vanilla vite build && VITE_ENTRY=ui-react vite build",
"build": "rm -rf dist && VITE_ENTRY=ui-raw vite build && VITE_ENTRY=ui-vanilla vite build && VITE_ENTRY=ui-react vite build",
"preview": "vite preview",
"server": "bun server.ts",
"start": "npm run build && npm run server"
},
"dependencies": {
"@modelcontextprotocol/ext-apps": "../..",
"@modelcontextprotocol/sdk": "^1.20.1",
"@modelcontextprotocol/sdk": "^1.22.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"zod": "^3.25.0"

View file

@ -36,94 +36,113 @@ const getServer = async () => {
);
// Load HTML for both UIs
const [vanillaHtml, reactHtml] = await Promise.all([
const [rawHtml, vanillaHtml, reactHtml] = await Promise.all([
loadHtml("ui-raw"),
loadHtml("ui-vanilla"),
loadHtml("ui-react"),
]);
// --- Vanilla UI Resource & Tool ---
const vanillaResource: Resource = {
name: "ui-vanilla-template",
uri: "ui://vanilla",
title: "Vanilla UI Template",
description: "A simple vanilla JS UI",
mimeType: "text/html+mcp",
const registerResource = (resource: Resource, htmlContent: string) => {
server.registerResource(
resource.name,
resource.uri,
resource,
async (): Promise<ReadResourceResult> => ({
contents: [
{
uri: resource.uri,
mimeType: resource.mimeType,
text: htmlContent,
},
],
}),
);
return resource;
};
server.registerResource(
vanillaResource.name,
vanillaResource.uri,
vanillaResource,
async (): Promise<ReadResourceResult> => ({
contents: [
{
uri: vanillaResource.uri,
mimeType: vanillaResource.mimeType,
text: vanillaHtml,
{
const rawResource = registerResource({
name: "ui-raw-template",
uri: "ui://raw",
title: "Raw UI Template",
description: "A simple raw HTML UI",
mimeType: "text/html+mcp",
}, rawHtml);
server.registerTool(
"create-ui-raw",
{
title: "Raw UI",
description: "A tool that returns a raw HTML UI (no Apps SDK runtime)",
inputSchema: {
message: z.string().describe("Message to display"),
},
],
}),
);
server.registerTool(
"create-ui-vanilla",
{
title: "Vanilla UI",
description: "A tool that returns a simple vanilla JS UI",
inputSchema: {
message: z.string().describe("Message to display"),
},
_meta: {
"ui/resourceUri": vanillaResource.uri,
},
},
async ({ message }): Promise<CallToolResult> => ({
content: [{ type: "text", text: JSON.stringify({ message }) }],
structuredContent: { message },
}),
);
// --- React UI Resource & Tool ---
const reactResource: Resource = {
name: "ui-react-template",
uri: "ui://react",
title: "React UI Template",
description: "A React-based UI",
mimeType: "text/html+mcp",
};
server.registerResource(
reactResource.name,
reactResource.uri,
reactResource,
async (): Promise<ReadResourceResult> => ({
contents: [
{
uri: reactResource.uri,
mimeType: reactResource.mimeType,
text: reactHtml,
_meta: {
"ui/resourceUri": rawResource.uri,
},
],
}),
);
},
async ({ message }): Promise<CallToolResult> => ({
content: [{ type: "text", text: JSON.stringify({ message }) }],
structuredContent: { message },
}),
);
}
server.registerTool(
"create-ui-react",
{
title: "React UI",
description: "A tool that returns a React-based UI",
inputSchema: {
message: z.string().describe("Message to display"),
{
const vanillaResource = registerResource({
name: "ui-vanilla-template",
uri: "ui://vanilla",
title: "Vanilla UI Template",
description: "A simple vanilla JS UI",
mimeType: "text/html+mcp",
}, vanillaHtml);
server.registerTool(
"create-ui-vanilla",
{
title: "Vanilla UI",
description: "A tool that returns a vanilla TS + Apps SDK UI",
inputSchema: {
message: z.string().describe("Message to display"),
},
_meta: {
"ui/resourceUri": vanillaResource.uri,
},
},
_meta: {
"ui/resourceUri": reactResource.uri,
async ({ message }): Promise<CallToolResult> => ({
content: [{ type: "text", text: JSON.stringify({ message }) }],
structuredContent: { message },
}),
);
}
{
const reactResource = registerResource({
name: "ui-react-template",
uri: "ui://react",
title: "React UI Template",
description: "A React-based UI",
mimeType: "text/html+mcp",
}, reactHtml);
server.registerTool(
"create-ui-react",
{
title: "React UI",
description: "A tool that returns a React-based UI",
inputSchema: {
message: z.string().describe("Message to display"),
},
_meta: {
"ui/resourceUri": reactResource.uri,
},
},
},
async ({ message }): Promise<CallToolResult> => ({
content: [{ type: "text", text: JSON.stringify({ message }) }],
structuredContent: { message },
}),
);
async ({ message }): Promise<CallToolResult> => ({
content: [{ type: "text", text: JSON.stringify({ message }) }],
structuredContent: { message },
}),
);
}
// --- Common tool: get-weather ---
server.registerTool(

View file

@ -0,0 +1,207 @@
import {
McpUiInitializeRequest,
McpUiInitializeResult,
McpUiInitializedNotification,
McpUiToolResultNotification,
McpUiHostContextChangedNotification,
McpUiToolInputNotification,
McpUiSizeChangeNotification,
McpUiMessageRequest,
McpUiMessageResult,
McpUiOpenLinkRequest,
McpUiOpenLinkResult,
} from "@modelcontextprotocol/ext-apps";
import {
CallToolRequest,
CallToolResult,
JSONRPCMessage,
LoggingMessageNotification,
} from "@modelcontextprotocol/sdk/types.js";
const app = (() => {
let nextId = 1;
return {
sendRequest({ method, params }: { method: string; params: any }) {
const id = nextId++;
window.parent.postMessage({ jsonrpc: "2.0", id, method, params }, "*");
return new Promise((resolve, reject) => {
window.addEventListener("message", function listener(event) {
const data: JSONRPCMessage = event.data;
if (event.data?.id === id) {
window.removeEventListener("message", listener);
if (event.data?.result) {
resolve(true);
} else if (event.data?.error) {
reject(new Error(event.data.error));
}
} else {
reject(new Error(`Unsupported message: ${JSON.stringify(data)}`));
}
});
});
},
sendNotification({ method, params }: { method: string; params: any }) {
window.parent.postMessage({ jsonrpc: "2.0", method, params }, "*");
},
onNotification(method: string, handler: (params: any) => void) {
window.addEventListener("message", function listener(event) {
if (event.data?.method === method) {
handler(event.data.params);
}
});
},
};
})();
window.addEventListener("load", async () => {
const root = document.getElementById("root")!;
const appendText = (textContent: string, opts = {}) => {
root.appendChild(
Object.assign(document.createElement("div"), {
textContent,
...opts,
}),
);
};
const appendError = (error: unknown) =>
appendText(
`Error: ${error instanceof Error ? error.message : String(error)}`,
{ style: "color: red;" },
);
app.onNotification(
"ui/notifications/tool-result" as McpUiToolResultNotification["method"],
async (params: McpUiToolResultNotification["params"]) => {
appendText(`Tool call result: ${JSON.stringify(params)}`);
},
);
app.onNotification(
"ui/notifications/host-context-changed" as McpUiHostContextChangedNotification["method"],
async (params: McpUiHostContextChangedNotification["params"]) => {
appendText(`Host context changed: ${JSON.stringify(params)}`);
},
);
app.onNotification(
"ui/notifications/tool-input" as McpUiToolInputNotification["method"],
async (params: McpUiToolInputNotification["params"]) => {
appendText(`Tool call input: ${JSON.stringify(params)}`);
},
);
const initializeResult = (await app.sendRequest(<McpUiInitializeRequest>{
method: "ui/initialize",
params: {
appCapabilities: {},
appInfo: { name: "My UI", version: "1.0.0" },
protocolVersion: "2025-06-18",
},
})) as McpUiInitializeResult;
app.sendNotification(<McpUiInitializedNotification>{
method: "ui/notifications/initialized",
params: {},
});
new ResizeObserver(() => {
const { body, documentElement: html } = document;
const bodyStyle = getComputedStyle(body);
const htmlStyle = getComputedStyle(html);
const width = body.scrollWidth;
const height =
body.scrollHeight +
(parseFloat(bodyStyle.borderTop) || 0) +
(parseFloat(bodyStyle.borderBottom) || 0) +
(parseFloat(htmlStyle.borderTop) || 0) +
(parseFloat(htmlStyle.borderBottom) || 0);
app.sendNotification(<McpUiSizeChangeNotification>{
method: "ui/notifications/size-change",
params: { width, height },
});
}).observe(document.body);
root.appendChild(
Object.assign(document.createElement("button"), {
textContent: "Get Weather (Tool)",
onclick: async () => {
try {
const result = (await app.sendRequest(<CallToolRequest>{
method: "tools/call",
params: {
name: "get-weather",
arguments: { location: "Tokyo" },
},
})) as CallToolResult;
appendText(`Weather tool result: ${JSON.stringify(result)}`);
} catch (e) {
appendError(e);
}
},
}),
);
root.appendChild(
Object.assign(document.createElement("button"), {
textContent: "Notify Cart Updated",
onclick: async () => {
app.sendNotification(<LoggingMessageNotification>{
method: "notifications/message",
params: {
level: "info",
data: "cart-updated",
},
});
},
}),
);
root.appendChild(
Object.assign(document.createElement("button"), {
textContent: "Prompt Weather in Tokyo",
onclick: async () => {
try {
const { isError } = (await app.sendRequest(<McpUiMessageRequest>{
method: "ui/message",
params: {
role: "user",
content: [
{
type: "text",
text: "What is the weather in Tokyo?",
},
],
},
})) as McpUiMessageResult;
appendText(`Message result: ${isError ? "error" : "success"}`);
} catch (e) {
appendError(e);
}
},
}),
);
root.appendChild(
Object.assign(document.createElement("button"), {
textContent: "Open Link to Google",
onclick: async () => {
try {
const { isError } = (await app.sendRequest(<McpUiOpenLinkRequest>{
method: "ui/open-link",
params: {
url: "https://www.google.com",
},
})) as McpUiOpenLinkResult;
appendText(`Link result: ${isError ? "error" : "success"}`);
} catch (e) {
appendError(e);
}
},
}),
);
console.log("Initialized with host info:", initializeResult.hostInfo);
});

View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MCP UI Client (Vanilla)</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/ui-raw.ts"></script>
</body>
</html>