Improve consistency and organization of examples for AI learning
- Add `.gitignore` files to all 19 examples (`node_modules/`, `dist/`) - Replace custom `log` objects with standard `console` methods - Add `ontoolcancelled` handler to all `basic-server-*` examples - Add host styling integration (`applyDocumentTheme`, `applyHostFonts`, `applyHostStyleVariables`) to non-React `basic-server-*` examples - Add section headers for better code organization in feature examples - Update READMEs with Build System section explaining single-file bundling These changes make examples more consistent and easier to adapt. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
6166242136
commit
4140565b77
2 changed files with 449 additions and 363 deletions
|
|
@ -10,12 +10,10 @@ import { ReadResourceResultSchema } from "@modelcontextprotocol/sdk/types.js";
|
|||
import "./global.css";
|
||||
import "./mcp-app.css";
|
||||
|
||||
const log = {
|
||||
info: console.log.bind(console, "[VIDEO]"),
|
||||
error: console.error.bind(console, "[VIDEO]"),
|
||||
};
|
||||
// =============================================================================
|
||||
// DOM References
|
||||
// =============================================================================
|
||||
|
||||
// Get element references
|
||||
const mainEl = document.querySelector(".main") as HTMLElement;
|
||||
const loadingEl = document.getElementById("loading")!;
|
||||
const loadingTextEl = document.getElementById("loading-text")!;
|
||||
|
|
@ -25,7 +23,10 @@ const playerEl = document.getElementById("player")!;
|
|||
const videoEl = document.getElementById("video") as HTMLVideoElement;
|
||||
const videoInfoEl = document.getElementById("video-info")!;
|
||||
|
||||
// Parse tool result to get video URI
|
||||
// =============================================================================
|
||||
// UI State Helpers
|
||||
// =============================================================================
|
||||
|
||||
function parseToolResult(
|
||||
result: CallToolResult,
|
||||
): { videoUri: string; description: string } | null {
|
||||
|
|
@ -58,12 +59,16 @@ function showPlayer(dataUri: string, info: string) {
|
|||
playerEl.style.display = "block";
|
||||
}
|
||||
|
||||
// Create app instance
|
||||
// =============================================================================
|
||||
// MCP Apps SDK Integration
|
||||
// =============================================================================
|
||||
|
||||
const app = new App({ name: "Video Resource Player", version: "1.0.0" });
|
||||
|
||||
// Handle tool result - this is called when the tool execution completes
|
||||
// Handle tool result - Requests a resource via resources/read and converts the
|
||||
// base64 blob to a data URI for use in the browser.
|
||||
app.ontoolresult = async (result) => {
|
||||
log.info("Received tool result:", result);
|
||||
console.info("Received tool result:", result);
|
||||
|
||||
const parsed = parseToolResult(result);
|
||||
if (!parsed) {
|
||||
|
|
@ -72,12 +77,12 @@ app.ontoolresult = async (result) => {
|
|||
}
|
||||
|
||||
const { videoUri, description } = parsed;
|
||||
log.info("Video URI:", videoUri, "Description:", description);
|
||||
console.info("Video URI:", videoUri, "Description:", description);
|
||||
|
||||
showLoading("Fetching video from MCP resource...");
|
||||
|
||||
try {
|
||||
log.info("Requesting resource:", videoUri);
|
||||
console.info("Requesting resource:", videoUri);
|
||||
|
||||
const resourceResult = await app.request(
|
||||
{ method: "resources/read", params: { uri: videoUri } },
|
||||
|
|
@ -89,24 +94,24 @@ app.ontoolresult = async (result) => {
|
|||
throw new Error("Resource response did not contain blob data");
|
||||
}
|
||||
|
||||
log.info("Resource received, blob size:", content.blob.length);
|
||||
console.info("Resource received, blob size:", content.blob.length);
|
||||
|
||||
showLoading("Converting to data URI...");
|
||||
|
||||
const mimeType = content.mimeType || "video/mp4";
|
||||
const dataUri = `data:${mimeType};base64,${content.blob}`;
|
||||
|
||||
log.info("Data URI created, length:", dataUri.length);
|
||||
console.info("Data URI created, length:", dataUri.length);
|
||||
|
||||
showPlayer(dataUri, `Loaded via MCP resource (${description})`);
|
||||
} catch (err) {
|
||||
log.error("Error fetching resource:", err);
|
||||
console.error("Error fetching resource:", err);
|
||||
showError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
};
|
||||
|
||||
app.onerror = (err) => {
|
||||
log.error("App error:", err);
|
||||
console.error("App error:", err);
|
||||
showError(err instanceof Error ? err.message : String(err));
|
||||
};
|
||||
|
||||
|
|
@ -121,7 +126,6 @@ function handleHostContextChanged(ctx: McpUiHostContext) {
|
|||
|
||||
app.onhostcontextchanged = handleHostContextChanged;
|
||||
|
||||
// Connect to host
|
||||
app.connect().then(() => {
|
||||
const ctx = app.getHostContext();
|
||||
if (ctx) {
|
||||
|
|
|
|||
|
|
@ -1,110 +0,0 @@
|
|||
/**
|
||||
* 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;
|
||||
}
|
||||
Loading…
Reference in a new issue