Merge pull request #9 from modelcontextprotocol/ochafik/update-packages

update simple-examples (add "raw" no-sdk example)
This commit is contained in:
Olivier Chafik 2025-11-24 14:34:10 +00:00 • committed by GitHub
commit 0f31e0a5db
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 424 additions and 5041 deletions

3
.gitignore vendored
View file

@ -1,3 +1,6 @@
.DS_Store .DS_Store
dist/ dist/
node_modules/ node_modules/
package-lock.json
yarn.lock
.vscode/

View file

@ -5,15 +5,16 @@ This repo contains the SDK and [specification](./specification/draft/apps.mdx) f
MCP Apps are proposed standard inspired by [MCP-UI](https://mcpui.dev/) and [OpenAI's Apps SDK](https://developers.openai.com/apps-sdk/) to allow MCP Servers to display interactive UI elements in conversational MCP clients / chatbots. MCP Apps are proposed standard inspired by [MCP-UI](https://mcpui.dev/) and [OpenAI's Apps SDK](https://developers.openai.com/apps-sdk/) to allow MCP Servers to display interactive UI elements in conversational MCP clients / chatbots.
This repo provides: This repo provides:
- [specification/draft/apps.mdx](./specification/draft/apps.mdx): The Draft Extension Specification. It's still... in flux! Feedback welcome! (also see discussions in [SEP-1865](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/1865)).
- [types.ts](./src/types.ts): Types of JSON-RPC messages used to communicate between Apps & their host - [types.ts](./src/types.ts): Types of JSON-RPC messages used to communicate between Apps & their host
- Note that MCP Apps also use some standard MCP messages (e.g. `tools/call` for the App to trigger actions on its originating Server - these calls are proxied through the Host), but these types are the additional messages defined by the extension - Note that MCP Apps also use some standard MCP messages (e.g. `tools/call` for the App to trigger actions on its originating Server - these calls are proxied through the Host), but these types are the additional messages defined by the extension
- [examples/simple-example](./examples/simple-example): Example Server + Apps - [examples/simple-example](./examples/simple-example): Example Server + Apps
- [server.ts](./examples/simple-server/server.ts): MCP server with two tools that declare UI resources of Apps to be show in the chat when called - [server.ts](./examples/simple-server/server.ts): MCP server with three tools that declare UI resources of Apps to be show in the chat when called
- [ui-react.tsx](./examples/simple-server/src/ui-react.tsx): React App returned by the `create-ui-react` tool shows how to use the `useApp` hook to register MCP callbacks - [ui-react.tsx](./examples/simple-server/src/ui-react.tsx): React App returned by the `create-ui-react` tool shows how to use the `useApp` hook to register MCP callbacks
- [ui-vanilla.tsx](./examples/simple-server/src/ui-vanilla.ts): vanilla App returned by the `create-ui-vanilla` - [ui-vanilla.tsx](./examples/simple-server/src/ui-vanilla.ts): vanilla App returned by the `create-ui-vanilla`
- [ui-raw.tsx](./examples/simple-server/src/ui-raw.ts): same as vanilla App but doesn't use the SDK runtime (just its types)
- [specification/draft/apps.mdx](./specification/draft/apps.mdx): The Draft Extension Specification. It's still... in flux! Feedback welcome! (also see discussions in [SEP-1865](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/1865)).
- [message-transport](./src/message-transport.ts): `PostMessageTransport` class that uses `postMessage` to exchange JSON-RPC messages between windows / iframes - [message-transport](./src/message-transport.ts): `PostMessageTransport` class that uses `postMessage` to exchange JSON-RPC messages between windows / iframes

View file

@ -8,20 +8,28 @@ const isDevelopment = Bun.env.NODE_ENV === "development";
// Build all JavaScript/TypeScript files // Build all JavaScript/TypeScript files
function buildJs(entrypoint: string, opts: Record<string, any> = {}) { function buildJs(entrypoint: string, opts: Record<string, any> = {}) {
return Bun.build({ return Bun.build({
entrypoints: [entrypoint], entrypoints: [entrypoint],
outdir: "dist", outdir: "dist",
target: "browser", target: "browser",
minify: !isDevelopment, minify: !isDevelopment,
...(isDevelopment ? { ...(isDevelopment
sourcemap: "inline", ? {
} : {}), sourcemap: "inline",
...opts }
}) : {}),
...opts,
});
} }
await Promise.all([ await Promise.all([
buildJs("src/app.ts", { outdir: "dist/src" }), buildJs("src/app.ts", { outdir: "dist/src" }),
buildJs("src/app-bridge.ts", { outdir: "dist/src", external: ["@modelcontextprotocol/sdk"] }), buildJs("src/app-bridge.ts", {
buildJs("src/react/index.tsx", { outdir: "dist/src/react", external: ["react", "react-dom"]}), outdir: "dist/src",
]) external: ["@modelcontextprotocol/sdk"],
}),
buildJs("src/react/index.tsx", {
outdir: "dist/src/react",
external: ["react", "react-dom"],
}),
]);

File diff suppressed because it is too large Load diff

View file

@ -4,15 +4,13 @@
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "build:uis": "rm -rf dist && concurrently 'UI=ui-raw.html vite build' 'UI=ui-vanilla.html vite build' 'UI=ui-react.html vite build'",
"build": "rm -rf dist && VITE_ENTRY=ui-vanilla vite build && VITE_ENTRY=ui-react vite build",
"preview": "vite preview",
"server": "bun server.ts", "server": "bun server.ts",
"start": "npm run build && npm run server" "start": "npm run build:uis && npm run server"
}, },
"dependencies": { "dependencies": {
"@modelcontextprotocol/ext-apps": "git+https://github.com/modelcontextprotocol/ext-apps.git", "@modelcontextprotocol/ext-apps": "../..",
"@modelcontextprotocol/sdk": "^1.20.1", "@modelcontextprotocol/sdk": "^1.22.0",
"react": "^19.2.0", "react": "^19.2.0",
"react-dom": "^19.2.0", "react-dom": "^19.2.0",
"zod": "^3.25.0" "zod": "^3.25.0"
@ -23,6 +21,7 @@
"@types/react": "^19.2.2", "@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2", "@types/react-dom": "^19.2.2",
"@vitejs/plugin-react": "^4.3.4", "@vitejs/plugin-react": "^4.3.4",
"concurrently": "^9.2.1",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^5.1.0", "express": "^5.1.0",
"typescript": "^5.7.2", "typescript": "^5.7.2",

View file

@ -36,94 +36,122 @@ const getServer = async () => {
); );
// Load HTML for both UIs // 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-vanilla"),
loadHtml("ui-react"), loadHtml("ui-react"),
]); ]);
// --- Vanilla UI Resource & Tool --- const registerResource = (resource: Resource, htmlContent: string) => {
const vanillaResource: Resource = { server.registerResource(
name: "ui-vanilla-template", resource.name,
uri: "ui://vanilla", resource.uri,
title: "Vanilla UI Template", resource,
description: "A simple vanilla JS UI", async (): Promise<ReadResourceResult> => ({
mimeType: "text/html+mcp", contents: [
{
uri: resource.uri,
mimeType: resource.mimeType,
text: htmlContent,
},
],
}),
);
return resource;
}; };
server.registerResource( {
vanillaResource.name, const rawResource = registerResource(
vanillaResource.uri, {
vanillaResource, name: "ui-raw-template",
async (): Promise<ReadResourceResult> => ({ uri: "ui://raw",
contents: [ title: "Raw UI Template",
{ description: "A simple raw HTML UI",
uri: vanillaResource.uri, mimeType: "text/html+mcp",
mimeType: vanillaResource.mimeType, },
text: vanillaHtml, 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"),
}, },
], _meta: {
}), "ui/resourceUri": rawResource.uri,
);
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,
}, },
], },
}), async ({ message }): Promise<CallToolResult> => ({
); content: [{ type: "text", text: JSON.stringify({ message }) }],
structuredContent: { message },
}),
);
}
server.registerTool( {
"create-ui-react", const vanillaResource = registerResource(
{ {
title: "React UI", name: "ui-vanilla-template",
description: "A tool that returns a React-based UI", uri: "ui://vanilla",
inputSchema: { title: "Vanilla UI Template",
message: z.string().describe("Message to display"), description: "A simple vanilla JS UI",
mimeType: "text/html+mcp",
}, },
_meta: { vanillaHtml,
"ui/resourceUri": reactResource.uri, );
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,
},
}, },
}, async ({ message }): Promise<CallToolResult> => ({
async ({ message }): Promise<CallToolResult> => ({ content: [{ type: "text", text: JSON.stringify({ message }) }],
content: [{ type: "text", text: JSON.stringify({ message }) }], structuredContent: { 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 },
}),
);
}
// --- Common tool: get-weather --- // --- Common tool: get-weather ---
server.registerTool( server.registerTool(
@ -252,7 +280,6 @@ app.delete("/mcp", async (req: Request, res: Response) => {
app.listen(MCP_PORT, () => { app.listen(MCP_PORT, () => {
console.log(`MCP Server listening on http://localhost:${MCP_PORT}/mcp`); console.log(`MCP Server listening on http://localhost:${MCP_PORT}/mcp`);
console.log(` Tools: create-ui-vanilla, create-ui-react, get-weather`);
}); });
process.on("SIGINT", async () => { process.on("SIGINT", async () => {

View file

@ -0,0 +1,243 @@
/**
* @file App that does NOT depend on Apps SDK runtime.
*
* The Raw UI example has no runtime dependency to the Apps SDK
* but still imports its types for static type safety.
* Types can be just stripped, e.g. w/ the command line:
*
* <code>
* npx esbuild src/ui-raw.ts --bundle --outfile=dist/ui-raw.js --minify --sourcemap --platform=browser
* </code>
*
* We implement a barebones JSON-RPC message sender/receiver (see `app` object below),
* but without timeouts or runtime type validation of any kind
* (for that, use the Apps SDK / see ui-vanilla.ts or ui-react.ts).
*/
import type {
McpUiInitializeRequest,
McpUiInitializeResult,
McpUiInitializedNotification,
McpUiToolResultNotification,
McpUiHostContextChangedNotification,
McpUiToolInputNotification,
McpUiSizeChangeNotification,
McpUiMessageRequest,
McpUiMessageResult,
McpUiOpenLinkRequest,
McpUiOpenLinkResult,
} from "@modelcontextprotocol/ext-apps";
import type {
CallToolRequest,
CallToolResult,
JSONRPCMessage,
LoggingMessageNotification,
} from "@modelcontextprotocol/sdk/types.js";
const app = (() => {
type Sendable = { method: string; params: any };
let nextId = 1;
return {
sendRequest<T extends Sendable, Result>({ method, params }: T) {
const id = nextId++;
window.parent.postMessage({ jsonrpc: "2.0", id, method, params }, "*");
return new Promise<Result>((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(event.data.result as Result);
} else if (event.data?.error) {
reject(new Error(event.data.error));
}
} else {
reject(new Error(`Unsupported message: ${JSON.stringify(data)}`));
}
});
});
},
sendNotification<T extends Sendable>({ method, params }: T) {
window.parent.postMessage({ jsonrpc: "2.0", method, params }, "*");
},
onNotification<T extends Sendable>(
method: T["method"],
handler: (params: T["params"]) => 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<McpUiToolInputNotification>(
"ui/notifications/tool-input",
async (params) => {
appendText(`Tool call input: ${JSON.stringify(params)}`);
},
);
app.onNotification<McpUiToolResultNotification>(
"ui/notifications/tool-result",
async (params) => {
appendText(`Tool call result: ${JSON.stringify(params)}`);
},
);
app.onNotification<McpUiHostContextChangedNotification>(
"ui/notifications/host-context-changed",
async (params) => {
appendText(`Host context changed: ${JSON.stringify(params)}`);
},
);
const initializeResult = await app.sendRequest<
McpUiInitializeRequest,
McpUiInitializeResult
>({
method: "ui/initialize",
params: {
appCapabilities: {},
appInfo: { name: "My UI", version: "1.0.0" },
protocolVersion: "2025-06-18",
},
});
appendText(`Initialize result: ${JSON.stringify(initializeResult)}`);
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, CallToolResult>(
{
method: "tools/call",
params: {
name: "get-weather",
arguments: { location: "Tokyo" },
},
},
);
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,
McpUiMessageResult
>({
method: "ui/message",
params: {
role: "user",
content: [
{
type: "text",
text: "What is the weather in Tokyo?",
},
],
},
});
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,
McpUiOpenLinkResult
>({
method: "ui/open-link",
params: {
url: "https://www.google.com",
},
});
appendText(`Link result: ${isError ? "error" : "success"}`);
} catch (e) {
appendError(e);
}
},
}),
);
console.log("Initialized with host info:", initializeResult.hostInfo);
});

View file

@ -1,3 +1,6 @@
/**
* @file App that demonstrates a few features using React + the Apps SDK.
*/
import { useState, useCallback } from "react"; import { useState, useCallback } from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { import {
@ -13,8 +16,8 @@ import type {
const APP_INFO: Implementation = { const APP_INFO: Implementation = {
name: "MCP UI React Example Client", name: "MCP UI React Example Client",
version: "1.0.0", version: "1.0.0",
protocolVersion: "2025-06-18",
}; };
export function McpClientApp() { export function McpClientApp() {
const [toolResults, setToolResults] = useState<CallToolResult[]>([]); const [toolResults, setToolResults] = useState<CallToolResult[]>([]);
const [messages, setMessages] = useState<string[]>([]); const [messages, setMessages] = useState<string[]>([]);

View file

@ -1,9 +1,18 @@
/**
* @file Demonstrate a few Apps SDK features.
*
* The vanilla (no React) UI uses the Apps SDK.
*
* The Apps SDK offers advantages over the Raw UI example,
* such as ability to set timeouts, strong runtime type validation
* and simpler methods for each request/response interaction.
*/
import { import {
App, App,
PostMessageTransport, PostMessageTransport,
McpUiToolInputNotificationSchema, McpUiToolInputNotificationSchema,
McpUiSizeChangeNotificationSchema,
McpUiToolResultNotificationSchema, McpUiToolResultNotificationSchema,
McpUiHostContextChangedNotificationSchema,
} from "@modelcontextprotocol/ext-apps"; } from "@modelcontextprotocol/ext-apps";
window.addEventListener("load", async () => { window.addEventListener("load", async () => {
@ -27,6 +36,14 @@ window.addEventListener("load", async () => {
version: "1.0.0", version: "1.0.0",
}); });
app.setNotificationHandler(
McpUiToolInputNotificationSchema,
async ({ params }) => {
appendText(
`Tool call input received: ${JSON.stringify(params.arguments)}`,
);
},
);
app.setNotificationHandler( app.setNotificationHandler(
McpUiToolResultNotificationSchema, McpUiToolResultNotificationSchema,
async ({ params: { content, structuredContent, isError } }) => { async ({ params: { content, structuredContent, isError } }) => {
@ -36,19 +53,9 @@ window.addEventListener("load", async () => {
}, },
); );
app.setNotificationHandler( app.setNotificationHandler(
McpUiSizeChangeNotificationSchema, McpUiHostContextChangedNotificationSchema,
async ({ params: { width, height } }) => { async (params) => {
appendText( appendText(`Host context changed: ${JSON.stringify(params)}`);
`Size change notification received: width=${width}, height=${height}`,
);
},
);
app.setNotificationHandler(
McpUiToolInputNotificationSchema,
async ({ params }) => {
appendText(
`Tool call input received: ${JSON.stringify(params.arguments)}`,
);
}, },
); );

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 (Raw)</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/ui-raw.ts"></script>
</body>
</html>

View file

@ -4,13 +4,13 @@ import { viteSingleFile } from "vite-plugin-singlefile";
import { resolve } from "path"; import { resolve } from "path";
// Get the entry from environment variable, default to ui-react // Get the entry from environment variable, default to ui-react
const entry = process.env.VITE_ENTRY || "ui-react"; const uiPath = process.env.UI;
export default defineConfig({ export default defineConfig({
plugins: [react(), viteSingleFile()], plugins: [react(), viteSingleFile()],
build: { build: {
rollupOptions: { rollupOptions: {
input: resolve(__dirname, `${entry}.html`), input: uiPath,
}, },
outDir: `dist`, outDir: `dist`,
emptyOutDir: false, emptyOutDir: false,

1659
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -7,16 +7,16 @@
"main": "./dist/src/app.js", "main": "./dist/src/app.js",
"exports": { "exports": {
".": { ".": {
"default": "./dist/src/app.js", "types": "./dist/src/app.d.ts",
"types": "./dist/src/app.d.ts" "default": "./dist/src/app.js"
}, },
"./react": { "./react": {
"default": "./dist/src/react/index.js", "types": "./dist/src/react/index.d.ts",
"types": "./dist/src/react/index.d.ts" "default": "./dist/src/react/index.js"
}, },
"./app-bridge": { "./app-bridge": {
"default": "./dist/src/app-bridge.js", "types": "./dist/src/app-bridge.d.ts",
"types": "./dist/src/app-bridge.d.ts" "default": "./dist/src/app-bridge.js"
} }
}, },
"files": [ "files": [
@ -44,7 +44,7 @@
"prettier": "^3.6.2" "prettier": "^3.6.2"
}, },
"dependencies": { "dependencies": {
"@modelcontextprotocol/sdk": "^1.20.1", "@modelcontextprotocol/sdk": "^1.22.0",
"bun": "^1.3.2", "bun": "^1.3.2",
"react": "^19.2.0", "react": "^19.2.0",
"react-dom": "^19.2.0", "react-dom": "^19.2.0",

View file

@ -1,2 +1,2 @@
export * from "./useApp"; export * from "./useApp";
export * from "./useAutoResize"; export * from "./useAutoResize";