|
| 1 | +import { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; |
| 2 | +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; |
| 3 | +import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js"; |
| 4 | +import fs from "node:fs/promises"; |
| 5 | +import path from "node:path"; |
| 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 (Preact)", |
| 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.ui.resourceUri` to know which resource to fetch and render as an |
| 24 | + // 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: { ui: { 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); |
0 commit comments