-
Notifications
You must be signed in to change notification settings - Fork 47
Add basic-server-* examples for Vue, Svelte, Preact, and Solid
#141
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jonathanhefner
wants to merge
9
commits into
modelcontextprotocol:main
Choose a base branch
from
jonathanhefner:basic-examples-multi-framework
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+4,759
−1,426
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e8f7ec1
Centralize example server transport logic in shared utils
jonathanhefner 9fa2c2a
Make example servers self-contained with local server-utils
jonathanhefner 2df8bb1
Add `integration-server` example for E2E testing
jonathanhefner bf23882
Simplify `basic-server-*` examples
jonathanhefner 3116282
Add basic-server-vue example
jonathanhefner 1807d89
Add basic-server-svelte example
jonathanhefner 4f75e91
Add basic-server-preact example
jonathanhefner b8832f0
Add basic-server-solid example
jonathanhefner 6eb0eaa
Add framework GitHub links to README
jonathanhefner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,4 @@ | ||
| examples/basic-host/**/*.ts | ||
| examples/basic-host/**/*.tsx | ||
| examples/basic-server-react/**/*.ts | ||
| examples/basic-server-react/**/*.tsx | ||
| examples/basic-server-vanillajs/**/*.ts | ||
| examples/basic-server-vanillajs/**/*.tsx | ||
| examples/basic-server-*/**/*.ts | ||
| examples/basic-server-*/**/*.tsx |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| # Example: Basic Server (Preact) | ||
|
|
||
| An MCP App example with a Preact UI. | ||
|
|
||
| > [!TIP] | ||
| > Looking for a vanilla JavaScript example? See [`basic-server-vanillajs`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-vanillajs)! | ||
|
|
||
| ## Overview | ||
|
|
||
| - Tool registration with a linked UI resource | ||
| - Preact UI using the [`App`](https://modelcontextprotocol.github.io/ext-apps/api/classes/app.App.html) class | ||
| - 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), [`openLink`](https://modelcontextprotocol.github.io/ext-apps/api/classes/app.App.html#openlink) | ||
|
|
||
| ## 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) - Preact UI using `App` class | ||
|
|
||
| ## 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| <!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> | ||
| <div id="root"></div> | ||
| <script type="module" src="/src/mcp-app.tsx"></script> | ||
| </body> | ||
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| { | ||
| "name": "basic-server-preact", | ||
| "version": "1.0.0", | ||
| "private": true, | ||
| "type": "module", | ||
| "scripts": { | ||
| "build": "tsc --noEmit && cross-env INPUT=mcp-app.html vite build", | ||
| "watch": "cross-env INPUT=mcp-app.html vite build --watch", | ||
| "serve": "bun server.ts", | ||
| "start": "cross-env NODE_ENV=development npm run build && npm run serve", | ||
| "dev": "cross-env NODE_ENV=development concurrently 'npm run watch' 'npm run serve'" | ||
| }, | ||
| "dependencies": { | ||
| "@modelcontextprotocol/ext-apps": "../..", | ||
| "@modelcontextprotocol/sdk": "^1.24.0", | ||
| "preact": "^10.0.0", | ||
| "zod": "^4.1.13" | ||
| }, | ||
| "devDependencies": { | ||
| "@preact/preset-vite": "^2.0.0", | ||
| "@types/cors": "^2.8.19", | ||
| "@types/express": "^5.0.0", | ||
| "@types/node": "^22.0.0", | ||
| "concurrently": "^9.2.1", | ||
| "cors": "^2.8.5", | ||
| "cross-env": "^7.0.3", | ||
| "express": "^5.1.0", | ||
| "typescript": "^5.9.3", | ||
| "vite": "^6.0.0", | ||
| "vite-plugin-singlefile": "^2.3.0" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| 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, RESOURCE_URI_META_KEY } from "@modelcontextprotocol/ext-apps/server"; | ||
| import { startServer } from "./src/server-utils.js"; | ||
|
|
||
| const DIST_DIR = path.join(import.meta.dirname, "dist"); | ||
|
|
||
| /** | ||
| * Creates a new MCP server instance with tools and resources registered. | ||
| */ | ||
| function createServer(): McpServer { | ||
| const server = new McpServer({ | ||
| name: "Basic MCP App Server (Preact)", | ||
| version: "1.0.0", | ||
| }); | ||
|
|
||
| // Two-part registration: tool + resource, tied together by the resource URI. | ||
| const resourceUri = "ui://get-time/mcp-app.html"; | ||
|
|
||
| // Register a tool with UI metadata. When the host calls this tool, it reads | ||
| // `_meta[RESOURCE_URI_META_KEY]` to know which resource to fetch and render | ||
| // as an interactive UI. | ||
| registerAppTool(server, | ||
| "get-time", | ||
| { | ||
| title: "Get Time", | ||
| description: "Returns the current server time as an ISO 8601 string.", | ||
| inputSchema: {}, | ||
| _meta: { [RESOURCE_URI_META_KEY]: resourceUri }, | ||
| }, | ||
| async (): Promise<CallToolResult> => { | ||
| const time = new Date().toISOString(); | ||
| return { content: [{ type: "text", text: time }] }; | ||
| }, | ||
| ); | ||
|
|
||
| // Register the resource, which returns the bundled HTML/JavaScript for the 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; | ||
| } | ||
|
|
||
| startServer(createServer); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| .main { | ||
| --color-primary: #2563eb; | ||
| --color-primary-hover: #1d4ed8; | ||
| --color-notice-bg: #eff6ff; | ||
|
|
||
| width: 100%; | ||
| max-width: 425px; | ||
| box-sizing: border-box; | ||
|
|
||
| > * { | ||
| 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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| /** | ||
| * @file App that demonstrates a few features using MCP Apps SDK + Preact. | ||
| */ | ||
| import { App, PostMessageTransport } from "@modelcontextprotocol/ext-apps"; | ||
| import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; | ||
| import { useCallback, useEffect, useState } from "preact/hooks"; | ||
| import { render } from "preact"; | ||
| 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 { text } = callToolResult.content?.find((c) => c.type === "text")!; | ||
| return text; | ||
| } | ||
|
|
||
|
|
||
| function GetTimeApp() { | ||
| const [app, setApp] = useState<App | null>(null); | ||
| const [error, setError] = useState<Error | null>(null); | ||
| const [toolResult, setToolResult] = useState<CallToolResult | null>(null); | ||
|
|
||
| useEffect(() => { | ||
| const instance = new App(IMPLEMENTATION); | ||
|
|
||
| instance.ontoolinput = async (input) => { | ||
| log.info("Received tool call input:", input); | ||
| }; | ||
|
|
||
| instance.ontoolresult = async (result) => { | ||
| log.info("Received tool call result:", result); | ||
| setToolResult(result); | ||
| }; | ||
|
|
||
| instance.onerror = log.error; | ||
|
|
||
| instance | ||
| .connect(new PostMessageTransport(window.parent)) | ||
| .then(() => setApp(instance)) | ||
| .catch(setError); | ||
| }, []); | ||
|
|
||
| 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.openLink({ 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 id="server-time">{serverTime}</code> | ||
| </p> | ||
| <button onClick={handleGetTime}>Get Server Time</button> | ||
| </div> | ||
|
|
||
| <div className={styles.action}> | ||
| <textarea value={messageText} onChange={(e) => setMessageText(e.currentTarget.value)} /> | ||
| <button onClick={handleSendMessage}>Send Message</button> | ||
| </div> | ||
|
|
||
| <div className={styles.action}> | ||
| <input type="text" value={logText} onChange={(e) => setLogText(e.currentTarget.value)} /> | ||
| <button onClick={handleSendLog}>Send Log</button> | ||
| </div> | ||
|
|
||
| <div className={styles.action}> | ||
| <input type="url" value={linkUrl} onChange={(e) => setLinkUrl(e.currentTarget.value)} /> | ||
| <button onClick={handleOpenLink}>Open Link</button> | ||
| </div> | ||
| </main> | ||
| ); | ||
| } | ||
|
|
||
|
|
||
| render(<GetTimeApp />, document.getElementById("root")!); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.