This skill should be used when the user asks to "add MCP App support to my web app", "turn my web app into a hybrid MCP App", "make my web page work as an MCP App too", "wrap my existing UI as an MCP App", "convert iframe embed to MCP App", "turn my SPA into an MCP App", or needs to add MCP App support to an existing web application while keeping it working standalone. Provides guidance for analyzing existing web apps and creating a hybrid web + MCP App with server-side tool and resource registration.
Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
This skill should be used when the user asks to "add MCP App support to my web app", "turn my web app into a hybrid MCP App", "make my web page work as an MCP App too", "wrap my existing UI as an MCP App", "convert iframe embed to MCP App", "turn my SPA into an MCP App", or needs to add MCP App support to an existing web application while keeping it working standalone. Provides guidance for analyzing existing web apps and creating a hybrid web + MCP App with server-side tool and resource registration.
Add MCP App Support to a Web App
Add MCP App support to an existing web application so it works both as a standalone web app and as an MCP App that renders inline in MCP-enabled hosts like Claude Desktop — from a single codebase.
How It Works
The existing web app stays intact. A thin initialization layer detects whether the app is running inside an MCP host or as a regular web page, and fetches parameters from the appropriate source. A new MCP server wraps the app's bundled HTML as a resource and registers a tool to display it.
Build system — Current bundler (Webpack, Vite, Rollup, none), framework (React, Vue, vanilla), entry points
User interactions — Does the app have inputs/forms that should map to tool parameters?
Runtime detection — How to tell if the app is running inside an MCP host (e.g., check the current origin, a query param, or whether window.parent !== window)
Present findings to the user and confirm the approach.
Data Source Mapping
In hybrid mode, the app keeps its existing data sources for standalone use and adds MCP equivalents:
Standalone data source
MCP App equivalent
URL query parameters
ontoolinput / ontoolresultarguments or structuredContent
REST API calls
app.callServerTool() to server-side tools, or keep direct API calls with CSP connectDomains
Props / component inputs
ontoolinputarguments
localStorage / sessionStorage
Not available in sandboxed iframe — pass via structuredContent or server-side state
WebSocket connections
Keep with CSP connectDomains, or convert to polling via app-only tools
Hardcoded data
Move to tool structuredContent to make it dynamic
Step 2: Investigate CSP Requirements
MCP Apps HTML runs in a sandboxed iframe with no same-origin server. Every external origin must be declared in CSP — missing origins fail silently.
Before writing any code, build the app and investigate all origins it references:
Build the app using the existing build command
Search the resulting HTML, CSS, and JS for every origin (not just "external" origins — every network request will need CSP approval)
For each origin found, trace back to source:
If it comes from a constant → universal (same in dev and prod)
If it comes from an env var or conditional → note the mechanism and identify both dev and prod values
Check for third-party libraries that may make their own requests (analytics, error tracking, etc.)
Document your findings as three lists, and note for each origin whether it's universal, dev-only, or prod-only:
Use npm install to add dependencies rather than manually writing version numbers. This lets npm resolve the latest compatible versions. Never specify version numbers from memory.
Server Code
Create server.ts:
import { McpServer } from"@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from"@modelcontextprotocol/sdk/server/stdio.js";
import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE } from"@modelcontextprotocol/ext-apps/server";
import fs from"node:fs/promises";
import path from"node:path";
import { z } from"zod";
const server = newMcpServer({ name: "my-app", version: "1.0.0" });
const resourceUri = "ui://my-app/mcp-app.html";
// Register the tool — inputSchema maps to the app's data sourcesregisterAppTool(server, "show-app", {
description: "Displays the app with the given parameters",
inputSchema: { query: z.string().describe("The search query") },
_meta: { ui: { resourceUri } },
}, async (args) => {
// Process args server-side if neededreturn {
content: [{ type: "text", text: `Showing app for: ${args.query}` }],
structuredContent: { query: args.query },
};
});
// Register the HTML resourceregisterAppResource(server, {
uri: resourceUri,
name: "My App UI",
mimeType: RESOURCE_MIME_TYPE,
// Add CSP domains from Step 2 if needed:// _meta: { ui: { connectDomains: ["api.example.com"], resourceDomains: ["cdn.example.com"] } },
}, async () => {
const html = await fs.readFile(
path.resolve(import.meta.dirname, "dist", "mcp-app.html"),
"utf-8",
);
return { contents: [{ uri: resourceUri, mimeType: RESOURCE_MIME_TYPE, text: html }] };
});
// Start the serverconst transport = newStdioServerTransport();
await server.connect(transport);
Package Scripts
Add to package.json:
{"scripts":{"build:ui":"vite build","build:server":"tsc","build":"npm run build:ui && npm run build:server","serve":"tsx server.ts"}}
Step 4: Adapt the Build Pipeline
The MCP App build must produce a single HTML file using vite-plugin-singlefile. The standalone web app build stays unchanged.
Vite Configuration
Create or update vite.config.ts. If the app already uses Vite, add vite-plugin-singlefile and a separate entry point for the MCP App build. If it uses another bundler, add a Vite config alongside for the MCP App build only.
This is the core step. Instead of replacing the app's data sources, add an alternative initialization path for MCP mode. The app detects its environment at startup and reads parameters from the right source.
The Hybrid Pattern
import { App, PostMessageTransport } from"@modelcontextprotocol/ext-apps";
// Detect whether we're running inside an MCP host.// Choose a detection method that fits the app:// - Origin check: window.location.origin !== 'https://myhost.com'// - Null origin (sandboxed iframe): window.location.origin === 'null'// - Query param: new URL(location.href).searchParams.has('mcp')const isMcpApp = window.location.origin === "null";
asyncfunctiongetParameters(): Promise<Record<string, string>> {
if (isMcpApp) {
// Running as MCP App — get params from tool lifecycleconst app = newApp({ name: "My App", version: "1.0.0" });
// Register handlers BEFORE connect()const params = awaitnewPromise<Record<string, string>>((resolve) => {
app.ontoolresult = (result) =>resolve(result.structuredContent ?? {});
});
await app.connect(newPostMessageTransport());
return params;
} else {
// Running as standalone web app — get params from URLreturnObject.fromEntries(newURL(location.href).searchParams);
}
}
asyncfunctionmain() {
const params = awaitgetParameters();
renderApp(params); // Same rendering logic for both modes
}
main().catch(console.error);
// Before (standalone only):const data = awaitfetch("/api/data").then(r => r.json());
// After (hybrid):asyncfunctionfetchData(): Promise<any> {
if (isMcpApp) {
const result = await app.callServerTool("fetch-data", {});
return result.structuredContent;
}
returnfetch("/api/data").then(r => r.json());
}
Or keep direct API calls in both modes with CSP connectDomains:
// API calls can stay unchanged if the API is external and the CSP declares the domain// Declare connectDomains: ["api.example.com"] in the resource registration
localStorage / sessionStorage (Hybrid)
// Before (standalone only):const saved = localStorage.getItem("settings");
// After (hybrid) — localStorage isn't available in sandboxed iframes:functiongetSettings(): any {
if (isMcpApp) {
// Will be provided via tool resultreturnnull; // or a default
}
returnJSON.parse(localStorage.getItem("settings") ?? "null");
}
Key variable groups: --color-background-*, --color-text-*, --color-border-*, --font-sans, --font-mono, --font-text-*-size, --font-heading-*-size, --border-radius-*. See src/spec.types.ts for the full list.
Optional Enhancements
App-Only Helper Tools
For data the UI needs to poll or fetch that the model doesn't need to call directly:
registerAppTool(server, "refresh-data", {
description: "Fetches latest data for the UI",
_meta: { ui: { resourceUri, visibility: ["app"] } },
}, async () => {
const data = awaitgetLatestData();
return { content: [{ type: "text", text: JSON.stringify(data) }] };
});
The UI calls these via app.callServerTool("refresh-data", {}).
Streaming Partial Input
For large tool inputs, use ontoolinputpartial to show progress during LLM generation:
return {
content: [{ type: "text", text: "Fallback description of the result" }],
structuredContent: { /* data for the UI */ },
};
Common Mistakes to Avoid
Forgetting CSP declarations for external origins — fails silently in the sandboxed iframe
Using localStorage / sessionStorage in MCP mode — not available in sandboxed iframe; use fallbacks or pass via structuredContent
Missing vite-plugin-singlefile — external assets won't load in the iframe
Registering handlers after connect() — register ALL handlers BEFORE calling app.connect()
Hardcoding styles without fallbacks — use host CSS variables with var(..., fallback) so both modes look correct
Not handling safe area insets — always apply ctx.safeAreaInsets in onhostcontextchanged
Forgetting text content fallback — always provide content array for non-UI hosts
Forgetting resource registration — the tool references a resourceUri that must have a matching resource
Replacing standalone logic instead of branching — keep the original data sources intact; add the MCP path alongside them
Testing
Using basic-host
Test the MCP App mode with the basic-host example:
# Terminal 1: Build and run your server
npm run build && npm run serve
# Terminal 2: Run basic-host (from cloned repo)cd /tmp/mcp-ext-apps/examples/basic-host
npm install
SERVERS='["http://localhost:3001/mcp"]' npm run start
# Open http://localhost:8080
Configure SERVERS with a JSON array of your server URLs (default: http://localhost:3001/mcp).
Verify
MCP mode: App loads in basic-host without console errors