Skip to content

Commit 1807d89

Browse files
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>
1 parent 3116282 commit 1807d89

15 files changed

Lines changed: 727 additions & 5 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ Start with these foundational examples to learn the SDK:
5050
- [`examples/basic-server-vanillajs`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-vanillajs) — MCP server + MCP App using vanilla JS
5151
- [`examples/basic-server-react`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-react) — MCP server + MCP App using React
5252
- [`examples/basic-server-vue`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-vue) — MCP server + MCP App using Vue
53+
- [`examples/basic-server-svelte`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-svelte) — MCP server + MCP App using Svelte
5354
- [`examples/basic-host`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-host) — MCP host application supporting MCP Apps
5455

5556
The [`examples/`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples) directory contains additional demo apps showcasing real-world use cases.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Example: Basic Server (Svelte)
2+
3+
An MCP App example with a Svelte 5 UI using runes for reactivity.
4+
5+
> [!TIP]
6+
> Looking for a vanilla JavaScript example? See [`basic-server-vanillajs`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-server-vanillajs)!
7+
8+
## Overview
9+
10+
- Tool registration with a linked UI resource
11+
- Svelte 5 UI using the [`App`](https://modelcontextprotocol.github.io/ext-apps/api/classes/app.App.html) class
12+
- 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)
13+
14+
## Key Files
15+
16+
- [`server.ts`](server.ts) - MCP server with tool and resource registration
17+
- [`mcp-app.html`](mcp-app.html) / [`src/App.svelte`](src/App.svelte) - Svelte 5 UI using `App` class
18+
19+
## Getting Started
20+
21+
```bash
22+
npm install
23+
npm run dev
24+
```
25+
26+
## How It Works
27+
28+
1. The server registers a `get-time` tool with metadata linking it to a UI HTML resource (`ui://get-time/mcp-app.html`).
29+
2. When the tool is invoked, the Host renders the UI from the resource.
30+
3. The UI uses the MCP App SDK API to communicate with the host and call server tools.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<meta name="color-scheme" content="light dark">
7+
<title>Get Time App</title>
8+
<link rel="stylesheet" href="/src/global.css">
9+
</head>
10+
<body>
11+
<div id="app"></div>
12+
<script type="module" src="/src/mcp-app.ts"></script>
13+
</body>
14+
</html>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
{
2+
"name": "basic-server-svelte",
3+
"version": "1.0.0",
4+
"private": true,
5+
"type": "module",
6+
"scripts": {
7+
"build": "tsc --noEmit && cross-env INPUT=mcp-app.html vite build",
8+
"watch": "cross-env INPUT=mcp-app.html vite build --watch",
9+
"serve": "bun server.ts",
10+
"start": "cross-env NODE_ENV=development npm run build && npm run serve",
11+
"dev": "cross-env NODE_ENV=development concurrently 'npm run watch' 'npm run serve'"
12+
},
13+
"dependencies": {
14+
"@modelcontextprotocol/ext-apps": "../..",
15+
"@modelcontextprotocol/sdk": "^1.24.0",
16+
"svelte": "^5.0.0",
17+
"zod": "^4.1.13"
18+
},
19+
"devDependencies": {
20+
"@sveltejs/vite-plugin-svelte": "^5.0.0",
21+
"@types/cors": "^2.8.19",
22+
"@types/express": "^5.0.0",
23+
"@types/node": "^22.0.0",
24+
"concurrently": "^9.2.1",
25+
"cors": "^2.8.5",
26+
"express": "^5.1.0",
27+
"typescript": "^5.9.3",
28+
"vite": "^6.0.0",
29+
"vite-plugin-singlefile": "^2.3.0"
30+
}
31+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2+
import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js";
3+
import fs from "node:fs/promises";
4+
import path from "node:path";
5+
import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE, RESOURCE_URI_META_KEY } from "@modelcontextprotocol/ext-apps/server";
6+
import { startServer } from "./src/server-utils.js";
7+
8+
const DIST_DIR = path.join(import.meta.dirname, "dist");
9+
10+
/**
11+
* Creates a new MCP server instance with tools and resources registered.
12+
*/
13+
function createServer(): McpServer {
14+
const server = new McpServer({
15+
name: "Basic MCP App Server (Svelte)",
16+
version: "1.0.0",
17+
});
18+
19+
// Two-part registration: tool + resource, tied together by the resource URI.
20+
const resourceUri = "ui://get-time/mcp-app.html";
21+
22+
// Register a tool with UI metadata. When the host calls this tool, it reads
23+
// `_meta[RESOURCE_URI_META_KEY]` to know which resource to fetch and render
24+
// as an interactive UI.
25+
registerAppTool(server,
26+
"get-time",
27+
{
28+
title: "Get Time",
29+
description: "Returns the current server time as an ISO 8601 string.",
30+
inputSchema: {},
31+
_meta: { [RESOURCE_URI_META_KEY]: resourceUri },
32+
},
33+
async (): Promise<CallToolResult> => {
34+
const time = new Date().toISOString();
35+
return { content: [{ type: "text", text: time }] };
36+
},
37+
);
38+
39+
// Register the resource, which returns the bundled HTML/JavaScript for the UI.
40+
registerAppResource(server,
41+
resourceUri,
42+
resourceUri,
43+
{ mimeType: RESOURCE_MIME_TYPE },
44+
async (): Promise<ReadResourceResult> => {
45+
const html = await fs.readFile(path.join(DIST_DIR, "mcp-app.html"), "utf-8");
46+
47+
return {
48+
contents: [
49+
{ uri: resourceUri, mimeType: RESOURCE_MIME_TYPE, text: html },
50+
],
51+
};
52+
},
53+
);
54+
55+
return server;
56+
}
57+
58+
startServer(createServer);
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
<script lang="ts">
2+
import { onMount } from "svelte";
3+
import { App, PostMessageTransport } from "@modelcontextprotocol/ext-apps";
4+
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
5+
6+
const log = {
7+
info: console.log.bind(console, "[APP]"),
8+
warn: console.warn.bind(console, "[APP]"),
9+
error: console.error.bind(console, "[APP]"),
10+
};
11+
12+
function extractTime(result: CallToolResult): string {
13+
const { text } = result.content?.find((c) => c.type === "text")!;
14+
return text;
15+
}
16+
17+
let app = $state<App | null>(null);
18+
let serverTime = $state("Loading...");
19+
let messageText = $state("This is message text.");
20+
let logText = $state("This is log text.");
21+
let linkUrl = $state("https://modelcontextprotocol.io/");
22+
23+
onMount(async () => {
24+
const instance = new App({ name: "Get Time App", version: "1.0.0" });
25+
26+
instance.ontoolinput = (params) => {
27+
log.info("Received tool call input:", params);
28+
};
29+
30+
instance.ontoolresult = (result) => {
31+
log.info("Received tool call result:", result);
32+
serverTime = extractTime(result);
33+
};
34+
35+
instance.onerror = log.error;
36+
37+
await instance.connect(new PostMessageTransport(window.parent));
38+
app = instance;
39+
});
40+
41+
async function handleGetTime() {
42+
if (!app) return;
43+
try {
44+
log.info("Calling get-time tool...");
45+
const result = await app.callServerTool({ name: "get-time", arguments: {} });
46+
log.info("get-time result:", result);
47+
serverTime = extractTime(result);
48+
} catch (e) {
49+
log.error(e);
50+
serverTime = "[ERROR]";
51+
}
52+
}
53+
54+
async function handleSendMessage() {
55+
if (!app) return;
56+
const signal = AbortSignal.timeout(5000);
57+
try {
58+
log.info("Sending message text to Host:", messageText);
59+
const { isError } = await app.sendMessage(
60+
{ role: "user", content: [{ type: "text", text: messageText }] },
61+
{ signal },
62+
);
63+
log.info("Message", isError ? "rejected" : "accepted");
64+
} catch (e) {
65+
log.error("Message send error:", signal.aborted ? "timed out" : e);
66+
}
67+
}
68+
69+
async function handleSendLog() {
70+
if (!app) return;
71+
log.info("Sending log text to Host:", logText);
72+
await app.sendLog({ level: "info", data: logText });
73+
}
74+
75+
async function handleOpenLink() {
76+
if (!app) return;
77+
log.info("Sending open link request to Host:", linkUrl);
78+
const { isError } = await app.openLink({ url: linkUrl });
79+
log.info("Open link request", isError ? "rejected" : "accepted");
80+
}
81+
</script>
82+
83+
<main class="main">
84+
<p class="notice">Watch activity in the DevTools console!</p>
85+
86+
<div class="action">
87+
<p><strong>Server Time:</strong> <code id="server-time">{serverTime}</code></p>
88+
<button onclick={handleGetTime}>Get Server Time</button>
89+
</div>
90+
91+
<div class="action">
92+
<textarea bind:value={messageText}></textarea>
93+
<button onclick={handleSendMessage}>Send Message</button>
94+
</div>
95+
96+
<div class="action">
97+
<input type="text" bind:value={logText}>
98+
<button onclick={handleSendLog}>Send Log</button>
99+
</div>
100+
101+
<div class="action">
102+
<input type="url" bind:value={linkUrl}>
103+
<button onclick={handleOpenLink}>Open Link</button>
104+
</div>
105+
</main>
106+
107+
<style>
108+
.main {
109+
--color-primary: #2563eb;
110+
--color-primary-hover: #1d4ed8;
111+
--color-notice-bg: #eff6ff;
112+
113+
width: 100%;
114+
max-width: 425px;
115+
box-sizing: border-box;
116+
117+
> * {
118+
margin-top: 0;
119+
margin-bottom: 0;
120+
}
121+
122+
> * + * {
123+
margin-top: 1.5rem;
124+
}
125+
}
126+
127+
.action {
128+
> * {
129+
margin-top: 0;
130+
margin-bottom: 0;
131+
width: 100%;
132+
}
133+
134+
> * + * {
135+
margin-top: 0.5rem;
136+
}
137+
138+
textarea,
139+
input {
140+
font-family: inherit;
141+
font-size: inherit;
142+
}
143+
144+
button {
145+
padding: 0.5rem 1rem;
146+
border: none;
147+
border-radius: 6px;
148+
color: white;
149+
font-weight: bold;
150+
background-color: var(--color-primary);
151+
cursor: pointer;
152+
153+
&:hover,
154+
&:focus-visible {
155+
background-color: var(--color-primary-hover);
156+
}
157+
}
158+
}
159+
160+
.notice {
161+
padding: 0.5rem 0.75rem;
162+
color: var(--color-primary);
163+
text-align: center;
164+
font-style: italic;
165+
background-color: var(--color-notice-bg);
166+
167+
&::before {
168+
content: "ℹ️ ";
169+
font-style: normal;
170+
}
171+
}
172+
</style>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
* {
2+
box-sizing: border-box;
3+
}
4+
5+
html, body {
6+
font-family: system-ui, -apple-system, sans-serif;
7+
font-size: 1rem;
8+
}
9+
10+
code {
11+
font-size: 1em;
12+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { mount } from "svelte";
2+
import App from "./App.svelte";
3+
import "./global.css";
4+
5+
mount(App, { target: document.getElementById("app")! });

0 commit comments

Comments
 (0)