ext-apps/examples/basic-server-preact/src/mcp-app.tsx
Jonathan Hefner 8acec0eaad
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>
2026-01-08 18:44:36 +00:00

159 lines
5 KiB
TypeScript

/**
* @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")!);