Add basic-server-* examples for Vue, Svelte, Preact, and Solid (#141)
* Add basic-server-vue example Demonstrates MCP App SDK usage with Vue 3, providing framework parity alongside the existing React and vanilla JS examples. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add basic-server-svelte example Demonstrates MCP App SDK usage with Svelte, providing parity with the existing basic-server-react and basic-server-vue examples. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add basic-server-preact example Demonstrates MCP App SDK usage with Preact, providing another lightweight framework option alongside the existing React, Vue, and Svelte examples. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add basic-server-solid example Demonstrates MCP App SDK usage with Solid.js, providing another reactive framework option alongside the existing React, Vue, Svelte, and Preact examples. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add framework GitHub links to README Link each framework name to its official GitHub repo in basic examples list. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
79670b4dcd
commit
8acec0eaad
52 changed files with 3115 additions and 963 deletions
|
|
@ -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
|
||||
|
|
|
|||
10
README.md
10
README.md
|
|
@ -47,9 +47,13 @@ Or edit your `package.json` manually:
|
|||
|
||||
Start with these foundational examples to learn the SDK:
|
||||
|
||||
- [`examples/basic-server-vanillajs`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-vanillajs) — Example MCP server with tools that return UI Apps (vanilla JS)
|
||||
- [`examples/basic-server-react`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-react) — Example MCP server with tools that return UI Apps (React)
|
||||
- [`examples/basic-host`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-host) — Bare-bones example of hosting MCP Apps
|
||||
- [`examples/basic-server-vanillajs`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-vanillajs) — MCP server + MCP App using vanilla JS
|
||||
- [`examples/basic-server-react`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-react) — MCP server + MCP App using [React](https://github.com/facebook/react)
|
||||
- [`examples/basic-server-vue`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-vue) — MCP server + MCP App using [Vue](https://github.com/vuejs/vue)
|
||||
- [`examples/basic-server-svelte`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-svelte) — MCP server + MCP App using [Svelte](https://github.com/sveltejs/svelte)
|
||||
- [`examples/basic-server-preact`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-preact) — MCP server + MCP App using [Preact](https://github.com/preactjs/preact)
|
||||
- [`examples/basic-server-solid`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-solid) — MCP server + MCP App using [Solid](https://github.com/solidjs/solid)
|
||||
- [`examples/basic-host`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-host) — MCP host application supporting MCP Apps
|
||||
|
||||
The [`examples/`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples) directory contains additional demo apps showcasing real-world use cases.
|
||||
|
||||
|
|
|
|||
30
examples/basic-server-preact/README.md
Normal file
30
examples/basic-server-preact/README.md
Normal file
|
|
@ -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.
|
||||
14
examples/basic-server-preact/mcp-app.html
Normal file
14
examples/basic-server-preact/mcp-app.html
Normal file
|
|
@ -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>
|
||||
32
examples/basic-server-preact/package.json
Normal file
32
examples/basic-server-preact/package.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
58
examples/basic-server-preact/server.ts
Normal file
58
examples/basic-server-preact/server.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
|
||||
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 { 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.ui.resourceUri` 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: { ui: { 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);
|
||||
12
examples/basic-server-preact/src/global.css
Normal file
12
examples/basic-server-preact/src/global.css
Normal 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;
|
||||
}
|
||||
65
examples/basic-server-preact/src/mcp-app.module.css
Normal file
65
examples/basic-server-preact/src/mcp-app.module.css
Normal file
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
159
examples/basic-server-preact/src/mcp-app.tsx
Normal file
159
examples/basic-server-preact/src/mcp-app.tsx
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
/**
|
||||
* @file App that demonstrates a few features using MCP Apps SDK + Preact.
|
||||
*/
|
||||
import { App, type McpUiHostContext } 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);
|
||||
const [hostContext, setHostContext] = useState<McpUiHostContext | undefined>();
|
||||
|
||||
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.onhostcontextchanged = (params) => {
|
||||
setHostContext((prev) => ({ ...prev, ...params }));
|
||||
};
|
||||
|
||||
instance
|
||||
.connect()
|
||||
.then(() => {
|
||||
setApp(instance);
|
||||
setHostContext(instance.getHostContext());
|
||||
})
|
||||
.catch(setError);
|
||||
}, []);
|
||||
|
||||
if (error) return <div><strong>ERROR:</strong> {error.message}</div>;
|
||||
if (!app) return <div>Connecting...</div>;
|
||||
|
||||
return <GetTimeAppInner app={app} toolResult={toolResult} hostContext={hostContext} />;
|
||||
}
|
||||
|
||||
|
||||
interface GetTimeAppInnerProps {
|
||||
app: App;
|
||||
toolResult: CallToolResult | null;
|
||||
hostContext?: McpUiHostContext;
|
||||
}
|
||||
function GetTimeAppInner({ app, toolResult, hostContext }: 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}
|
||||
style={{
|
||||
paddingTop: hostContext?.safeAreaInsets?.top,
|
||||
paddingRight: hostContext?.safeAreaInsets?.right,
|
||||
paddingBottom: hostContext?.safeAreaInsets?.bottom,
|
||||
paddingLeft: hostContext?.safeAreaInsets?.left,
|
||||
}}
|
||||
>
|
||||
<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")!);
|
||||
110
examples/basic-server-preact/src/server-utils.ts
Normal file
110
examples/basic-server-preact/src/server-utils.ts
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
/**
|
||||
* Shared utilities for running MCP servers with various transports.
|
||||
*/
|
||||
|
||||
import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import cors from "cors";
|
||||
import type { Request, Response } from "express";
|
||||
|
||||
/**
|
||||
* Starts an MCP server using the appropriate transport based on command-line arguments.
|
||||
*
|
||||
* If `--stdio` is passed, uses stdio transport. Otherwise, uses Streamable HTTP transport.
|
||||
*
|
||||
* @param createServer - Factory function that creates a new McpServer instance.
|
||||
*/
|
||||
export async function startServer(
|
||||
createServer: () => McpServer,
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (process.argv.includes("--stdio")) {
|
||||
await startStdioServer(createServer);
|
||||
} else {
|
||||
await startStreamableHttpServer(createServer);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts an MCP server with stdio transport.
|
||||
*
|
||||
* @param createServer - Factory function that creates a new McpServer instance.
|
||||
*/
|
||||
export async function startStdioServer(
|
||||
createServer: () => McpServer,
|
||||
): Promise<void> {
|
||||
await createServer().connect(new StdioServerTransport());
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts an MCP server with Streamable HTTP transport in stateless mode.
|
||||
*
|
||||
* Each request creates a fresh server and transport instance, which are
|
||||
* closed when the response ends (no session tracking).
|
||||
*
|
||||
* The server listens on the port specified by the PORT environment variable,
|
||||
* defaulting to 3001 if not set.
|
||||
*
|
||||
* @param createServer - Factory function that creates a new McpServer instance per request.
|
||||
*/
|
||||
export async function startStreamableHttpServer(
|
||||
createServer: () => McpServer,
|
||||
): Promise<void> {
|
||||
const port = parseInt(process.env.PORT ?? "3001", 10);
|
||||
|
||||
// Express app - bind to all interfaces for development/testing
|
||||
const expressApp = createMcpExpressApp({ host: "0.0.0.0" });
|
||||
expressApp.use(cors());
|
||||
|
||||
expressApp.all("/mcp", async (req: Request, res: Response) => {
|
||||
// Create fresh server and transport for each request (stateless mode)
|
||||
const server = createServer();
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
});
|
||||
|
||||
// Clean up when response ends
|
||||
res.on("close", () => {
|
||||
transport.close().catch(() => {});
|
||||
server.close().catch(() => {});
|
||||
});
|
||||
|
||||
try {
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
} catch (error) {
|
||||
console.error("MCP error:", error);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32603, message: "Internal server error" },
|
||||
id: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const { promise, resolve, reject } = Promise.withResolvers<void>();
|
||||
|
||||
const httpServer = expressApp.listen(port, (err?: Error) => {
|
||||
if (err) return reject(err);
|
||||
console.log(`Server listening on http://localhost:${port}/mcp`);
|
||||
resolve();
|
||||
});
|
||||
|
||||
const shutdown = () => {
|
||||
console.log("\nShutting down...");
|
||||
httpServer.close(() => process.exit(0));
|
||||
};
|
||||
|
||||
process.on("SIGINT", shutdown);
|
||||
process.on("SIGTERM", shutdown);
|
||||
|
||||
return promise;
|
||||
}
|
||||
1
examples/basic-server-preact/src/vite-env.d.ts
vendored
Normal file
1
examples/basic-server-preact/src/vite-env.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
/// <reference types="vite/client" />
|
||||
21
examples/basic-server-preact/tsconfig.json
Normal file
21
examples/basic-server-preact/tsconfig.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"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",
|
||||
"jsxImportSource": "preact",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src", "server.ts"]
|
||||
}
|
||||
25
examples/basic-server-preact/vite.config.ts
Normal file
25
examples/basic-server-preact/vite.config.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { defineConfig } from "vite";
|
||||
import preact from "@preact/preset-vite";
|
||||
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: [preact(), viteSingleFile()],
|
||||
build: {
|
||||
sourcemap: isDevelopment ? "inline" : undefined,
|
||||
cssMinify: !isDevelopment,
|
||||
minify: !isDevelopment,
|
||||
|
||||
rollupOptions: {
|
||||
input: INPUT,
|
||||
},
|
||||
outDir: "dist",
|
||||
emptyOutDir: false,
|
||||
},
|
||||
});
|
||||
30
examples/basic-server-solid/README.md
Normal file
30
examples/basic-server-solid/README.md
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Example: Basic Server (Solid)
|
||||
|
||||
An MCP App example with a Solid 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
|
||||
- Solid 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) - Solid 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.
|
||||
14
examples/basic-server-solid/mcp-app.html
Normal file
14
examples/basic-server-solid/mcp-app.html
Normal file
|
|
@ -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>
|
||||
32
examples/basic-server-solid/package.json
Normal file
32
examples/basic-server-solid/package.json
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"name": "basic-server-solid",
|
||||
"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",
|
||||
"solid-js": "^1.9.0",
|
||||
"zod": "^4.1.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@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",
|
||||
"vite-plugin-solid": "^2.0.0"
|
||||
}
|
||||
}
|
||||
58
examples/basic-server-solid/server.ts
Normal file
58
examples/basic-server-solid/server.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
|
||||
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 { 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 (Solid)",
|
||||
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.ui.resourceUri` 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: { ui: { 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);
|
||||
12
examples/basic-server-solid/src/global.css
Normal file
12
examples/basic-server-solid/src/global.css
Normal 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;
|
||||
}
|
||||
65
examples/basic-server-solid/src/mcp-app.module.css
Normal file
65
examples/basic-server-solid/src/mcp-app.module.css
Normal file
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
163
examples/basic-server-solid/src/mcp-app.tsx
Normal file
163
examples/basic-server-solid/src/mcp-app.tsx
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
/**
|
||||
* @file App that demonstrates a few features using MCP Apps SDK + Solid.
|
||||
*/
|
||||
import { App, type McpUiHostContext } from "@modelcontextprotocol/ext-apps";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { createEffect, createSignal, onMount, Show } from "solid-js";
|
||||
import { render } from "solid-js/web";
|
||||
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] = createSignal<App | null>(null);
|
||||
const [error, setError] = createSignal<Error | null>(null);
|
||||
const [toolResult, setToolResult] = createSignal<CallToolResult | null>(null);
|
||||
const [hostContext, setHostContext] = createSignal<McpUiHostContext | undefined>();
|
||||
|
||||
onMount(async () => {
|
||||
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.onhostcontextchanged = (params) => {
|
||||
setHostContext((prev) => ({ ...prev, ...params }));
|
||||
};
|
||||
|
||||
try {
|
||||
await instance.connect();
|
||||
setApp(instance);
|
||||
setHostContext(instance.getHostContext());
|
||||
} catch (e) {
|
||||
setError(e as Error);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Show when={!error()} fallback={<div><strong>ERROR:</strong> {error()!.message}</div>}>
|
||||
<Show when={app()} fallback={<div>Connecting...</div>}>
|
||||
<GetTimeAppInner app={app()!} toolResult={toolResult()} hostContext={hostContext()} />
|
||||
</Show>
|
||||
</Show>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
interface GetTimeAppInnerProps {
|
||||
app: App;
|
||||
toolResult: CallToolResult | null;
|
||||
hostContext?: McpUiHostContext;
|
||||
}
|
||||
function GetTimeAppInner(props: GetTimeAppInnerProps) {
|
||||
const [serverTime, setServerTime] = createSignal("Loading...");
|
||||
const [messageText, setMessageText] = createSignal("This is message text.");
|
||||
const [logText, setLogText] = createSignal("This is log text.");
|
||||
const [linkUrl, setLinkUrl] = createSignal("https://modelcontextprotocol.io/");
|
||||
|
||||
// Update serverTime when toolResult changes
|
||||
createEffect(() => {
|
||||
if (props.toolResult) {
|
||||
setServerTime(extractTime(props.toolResult));
|
||||
}
|
||||
});
|
||||
|
||||
async function handleGetTime() {
|
||||
try {
|
||||
log.info("Calling get-time tool...");
|
||||
const result = await props.app.callServerTool({ name: "get-time", arguments: {} });
|
||||
log.info("get-time result:", result);
|
||||
setServerTime(extractTime(result));
|
||||
} catch (e) {
|
||||
log.error(e);
|
||||
setServerTime("[ERROR]");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendMessage() {
|
||||
const signal = AbortSignal.timeout(5000);
|
||||
try {
|
||||
log.info("Sending message text to Host:", messageText());
|
||||
const { isError } = await props.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);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendLog() {
|
||||
log.info("Sending log text to Host:", logText());
|
||||
await props.app.sendLog({ level: "info", data: logText() });
|
||||
}
|
||||
|
||||
async function handleOpenLink() {
|
||||
log.info("Sending open link request to Host:", linkUrl());
|
||||
const { isError } = await props.app.openLink({ url: linkUrl() });
|
||||
log.info("Open link request", isError ? "rejected" : "accepted");
|
||||
}
|
||||
|
||||
return (
|
||||
<main
|
||||
class={styles.main}
|
||||
style={props.hostContext?.safeAreaInsets ? {
|
||||
"padding-top": `${props.hostContext.safeAreaInsets.top}px`,
|
||||
"padding-right": `${props.hostContext.safeAreaInsets.right}px`,
|
||||
"padding-bottom": `${props.hostContext.safeAreaInsets.bottom}px`,
|
||||
"padding-left": `${props.hostContext.safeAreaInsets.left}px`,
|
||||
} : undefined}
|
||||
>
|
||||
<p class={styles.notice}>Watch activity in the DevTools console!</p>
|
||||
|
||||
<div class={styles.action}>
|
||||
<p>
|
||||
<strong>Server Time:</strong> <code id="server-time">{serverTime()}</code>
|
||||
</p>
|
||||
<button onClick={handleGetTime}>Get Server Time</button>
|
||||
</div>
|
||||
|
||||
<div class={styles.action}>
|
||||
<textarea value={messageText()} onInput={(e) => setMessageText(e.currentTarget.value)} />
|
||||
<button onClick={handleSendMessage}>Send Message</button>
|
||||
</div>
|
||||
|
||||
<div class={styles.action}>
|
||||
<input type="text" value={logText()} onInput={(e) => setLogText(e.currentTarget.value)} />
|
||||
<button onClick={handleSendLog}>Send Log</button>
|
||||
</div>
|
||||
|
||||
<div class={styles.action}>
|
||||
<input type="url" value={linkUrl()} onInput={(e) => setLinkUrl(e.currentTarget.value)} />
|
||||
<button onClick={handleOpenLink}>Open Link</button>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
render(() => <GetTimeApp />, document.getElementById("root")!);
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue