build-mcp-app
anthropics/claude-plugins-official
このスキルは、ユーザーが「MCPアプリ」を構築したい場合、MCPサーバーに「インタラクティブなUI」や「ウィジェット」を追加したい場合、「チャット内でコンポーネントをレンダリング」したい場合、あるいは「MCP UIリソース」を構築したい場合、会話内に「フォーム」、「ピッカー」、「ダッシュボード」、または「確認ダイアログ」をインラインで表示するツールを作成したい場合、あるいはMCPの文脈で「アプリSDK」に言及する場合に、このスキルを使用してください。 これは、build-mcp-serverスキルがデプロイメントモデルを確定した後、またはユーザーがUIウィジェットが必要であることをすでに把握している場合に使用してください。
...すべて拡張しますMCPアプリの構築(インタラクティブなUIウィジェット)
MCPアプリとは、UIリソース(チャット画面内にインラインでレンダリングされるインタラクティブなコンポーネント)も提供する標準的なMCPサーバーのことです。一度構築すれば、ClaudeやChatGPT、およびアプリのインターフェースを実装しているその他のホスト上で動作します。
UIレイヤーは追加的なものです。内部的には、依然としてツール、リソース、そして同じワイヤプロトコルが使用されています。これまで通常のMCPサーバーを構築したことがない場合は、 build-mcp-server このスキルでは基本レイヤーを解説しています。本スキルでは、その上にウィジェットを追加します。
Claudeでのテスト:claude.aiにサーバーをカスタムコネクタとして追加します(ローカル開発の場合はCloudflareトンネル経由)。これにより、実際のiframeサンドボックスが動作し、
hostContext。詳細は https://claude.com/docs/connectors/building/testing を参照してください。
Claudeホストの仕様
hostContext.safeAreaInsets: {top, right, bottom, left}(px) — ノッチやコンポーザーのオーバーレイについては、これらの値を厳守してください。- ディレクトリへの登録には、OAuth または認証不要(
none)が必要です — 静的ベアラー認証はプライベートデプロイ専用であり、リストへの掲載がブロックされます — さらに、ツールannotationsおよび3~5枚のPNGスクリーンショットが必要です。詳細はreferences/directory-checklist.md.
ウィジェットがプレーンテキストに勝る場合
UIを単なる装飾として追加しないでください — ほとんどのツールでは、テキストやJSONを返すだけで十分です。以下のいずれかに該当する場合にのみ、ウィジェットを追加してください:
該当するものがなければ、ウィジェットは省略してください。テキストの方が構築もユーザーにとっての処理も高速です。
ウィジェット対情報抽出 — 適切な判断を
ウィジェットを構築する前に、情報引き出しで対応できるかどうかを確認してください。情報引き出しは仕様そのものであり、UIコードを一切必要とせず、準拠したホストであればどこでも機能します。
エリシテーションで対応できる場合は、それを利用してください。詳細は ../build-mcp-server/references/elicitation.md.
アーキテクチャ:2つのデプロイ形態
リモートMCPアプリ(最も一般的)
ホスト型ストリーム対応HTTPサーバー。ウィジェットテンプレートはリソースとして提供され、ツールの結果がそれらを参照します。ホストはリソースを取得し、iframeサンドボックス内でレンダリングし、ウィジェットとClaude間のメッセージを仲介します。
┌──────────┐ tools/call ┌────────────┐
│ Claude │─────────────> │ MCP server │
│ host │<── result ────│ (remote) │
│ │ + widget ref │ │
│ │ │ │
│ │ resources/read│ │
│ │─────────────> │ widget │
│ ┌──────┐ │<── template ──│ HTML/JS │
│ │iframe│ │ └────────────┘
│ │widget│ │
│ └──────┘ │
└──────────┘
MCPBパッケージ化されたMCPアプリ(ローカル+UI)
ウィジェットの仕組みは同じですが、サーバーはMCPBバンドル内でローカルに実行されます。ウィジェットがローカルアプリケーションを制御する必要がある場合(例:実際のローカルディスクを閲覧するファイルピッカー、デスクトップアプリを制御するダイアログなど)にこれを使用します。
MCPBのパッケージ化の仕組みについては、「build-mcpb」スキルを参照してください。以下の内容は、両方のシェイプに適用されます。
ウィジェットのツールへのアタッチ方法
ウィジェット対応のツールには、2つの別々の登録があります:
- ツールは、
_meta.ui.resourceUriを通じて UI リソースを宣言します。そのハンドラはプレーンテキストまたは JSON を返します(HTML ではありません)。 - リソースは別途登録され、HTMLを提供します。
Claudeがツールを呼び出すと、ホストは _meta.ui.resourceUriを検知し、そのリソースを取得してiframe内でレンダリングし、 ontoolresult イベントを介してツールの戻り値をiframeに渡し込みます。
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE }
from "@modelcontextprotocol/ext-apps/server";
import { z } from "zod";const server = new McpServer({ name: "contacts", version: "1.0.0" });// 1. The tool — returns DATA, declares which UI to show
registerAppTool(server, "pick_contact", {
description: "Open an interactive contact picker",
annotations: { title: "Pick Contact", readOnlyHint: true },
inputSchema: { filter: z.string().optional() },
_meta: { ui: { resourceUri: "ui://widgets/contact-picker.html" } },
}, async ({ filter }) => {
const contacts = await db.contacts.search(filter);
// Plain JSON — the widget receives this via ontoolresult
return { content: [{ type: "text", text: JSON.stringify(contacts) }] };
});// 2. The resource — serves the HTML
registerAppResource(
server,
"Contact Picker",
"ui://widgets/contact-picker.html",
{},
async () => ({
contents: [{
uri: "ui://widgets/contact-picker.html",
mimeType: RESOURCE_MIME_TYPE,
text: pickerHtml, // your HTML string
}],
}),
);
URIスキーマ ui:// は慣例によるものです。MIMEタイプは RESOURCE_MIME_TYPE ("text/html;profile=mcp-app")でなければなりません。これにより、ホストは単にソースを表示するのではなく、対話型のiframeとしてレンダリングすべきであることを認識します。
ウィジェットランタイム — App クラス
iframe 内では、スクリプトは App クラスを通じてホストと通信します。これは永続的な双方向接続です。通信がアクティブな限り、ウィジェットは稼働し @modelcontextprotocol/ext-appsを介してホストと通信します。これは永続的な双方向接続であり、通信がアクティブな限りウィジェットは稼働し続け、新しいツールの結果を受信したり、ユーザーのアクションを送信したりします。
<script type="module">
/* ext-apps bundle inlined at build time → globalThis.ExtApps */
/*__EXT_APPS_BUNDLE__*/
const { App } = globalThis.ExtApps; const app = new App({ name: "ContactPicker", version: "1.0.0" }, {}); // Set handlers BEFORE connecting
app.ontoolresult = ({ content }) => {
const contacts = JSON.parse(content[0].text);
render(contacts);
}; await app.connect(); // Later, when the user clicks something:
function onPick(contact) {
app.sendMessage({
role: "user",
content: [{ type: "text", text: `Selected contact: ${contact.id}` }],
});
}
script>
/*__EXT_APPS_BUNDLE__*/ プレースホルダーは、起動時にサーバーによって @modelcontextprotocol/ext-apps/app-with-deps — これが必要な理由とリライトのスニペットについては references/iframe-sandbox.md を参照してください。これが必要な理由とリライトのスニペットが記載されています。 import { App } from "https://esm.sh/..."; iframeのCSPが推移的依存関係の取得をブロックし、ウィジェットが空白でレンダリングされてしまいます。
sendMessage は、「ユーザーが何かを選択したため、それをClaudeに通知する」という典型的な処理フローです。 updateModelContext は、Claudeが把握しておくべきだが、チャットを煩雑にしてはならない状態のためのものです。 openLink は、外部サイトへのナビゲーションを行う際に必須です — window.open また はsandbox属性によってブロックされます。
ウィジェットでできないこと:
- ホストページのDOM、クッキー、またはストレージへのアクセス
- 任意のオリジンへのネットワーク呼び出し(CSPにより制限されているため、
callServerTool) - ポップアップを開く、または直接ナビゲートする — 代わりに
app.openLink({url}) - リモート画像を確実に読み込むこと — サーバーサイドで
data:サーバーサイドでインライン化
ウィジェットは小さく、単一の目的のみに限定してください。ピッカーは選択を行い、チャートは表示を行います。iframe 内にサブアプリ全体を構築せず、特定の機能に特化したウィジェットを持つ複数のツールに分割してください。
スケルトン:最小限のピッカーウィジェット
インストール:
npm install @modelcontextprotocol/sdk @modelcontextprotocol/ext-apps zod express
サーバー(src/server.ts):
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE }
from "@modelcontextprotocol/ext-apps/server";
import express from "express";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { z } from "zod";const require = createRequire(import.meta.url);
const server = new McpServer({ name: "contact-picker", version: "1.0.0" });// Inline the ext-apps browser bundle into the widget HTML.
// The iframe CSP blocks CDN script fetches — bundling is mandatory.
const bundle = readFileSync(
require.resolve("@modelcontextprotocol/ext-apps/app-with-deps"), "utf8",
).replace(/export\{([^}]+)\};?\s*$/, (_, body) =>
"globalThis.ExtApps={" +
body.split(",").map((p) => {
const [local, exported] = p.split(" as ").map((s) => s.trim());
return `${exported ?? local}:${local}`;
}).join(",") + "};",
);
const pickerHtml = readFileSync("./widgets/picker.html", "utf8")
.replace("/*__EXT_APPS_BUNDLE__*/", () => bundle);registerAppTool(server, "pick_contact", {
description: "Open an interactive contact picker. User selects one contact.",
annotations: { title: "Pick Contact", readOnlyHint: true },
inputSchema: { filter: z.string().optional().describe("Name/email prefix filter") },
_meta: { ui: { resourceUri: "ui://widgets/picker.html" } },
}, async ({ filter }) => {
const contacts = await db.contacts.search(filter ?? "");
return { content: [{ type: "text", text: JSON.stringify(contacts) }] };
});registerAppResource(server, "Contact Picker", "ui://widgets/picker.html", {},
async () => ({
contents: [{ uri: "ui://widgets/picker.html", mimeType: RESOURCE_MIME_TYPE, text: pickerHtml }],
}),
);const app = express();
app.use(express.json());
app.post("/mcp", async (req, res) => {
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on("close", () => transport.close());
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});
app.listen(process.env.PORT ?? 3000);
ローカルのみで動作するウィジェットアプリ(デスクトップアプリの制御やローカルファイルの読み取りなど)の場合は、トランスポートを StdioServerTransport に変更し、 build-mcpb skill を使用してパッケージ化してください。
ウィジェット(widgets/picker.html):
html>
<meta charset="utf-8" />
<style>
body { font: 14px system-ui; margin: 0; }
ul { list-style: none; padding: 0; margin: 0; max-height: 300px; overflow-y: auto; }
li { padding: 10px 14px; cursor: pointer; border-bottom: 1px solid #eee; }
li:hover { background: #f5f5f5; }
.sub { color: #666; font-size: 12px; }
style>
<ul id="list">ul>
<script type="module">
/*__EXT_APPS_BUNDLE__*/
const { App } = globalThis.ExtApps;
(async () => {
const app = new App({ name: "ContactPicker", version: "1.0.0" }, {});
const ul = document.getElementById("list"); app.ontoolresult = ({ content }) => {
const contacts = JSON.parse(content[0].text);
ul.innerHTML = "";
for (const c of contacts) {
const li = document.createElement("li");
li.innerHTML = `${c.name}${c.email}`;
li.addEventListener("click", () => {
app.sendMessage({
role: "user",
content: [{ type: "text", text: `Selected contact: ${c.id} (${c.name})` }],
});
});
ul.append(li);
}
}; await app.connect();
})();
script>
その他のウィジェットの形状については、 references/widget-templates.md を参照してください。
書き直しを省くための設計上のポイント
ツールごとに1つのウィジェット。何でもできる巨大なウィジェットを1つ作りたくなる衝動に抵抗してください。1つのツール → 1つの特化したウィジェット → 1つの明確な結果の形状。Claudeはこれらについてはるかに的確に推論します。
ツールの説明文にはウィジェットを明記する必要があります。Claudeは呼び出す対象を決定する際、ツールの説明文しか参照しません。説明文に「インタラクティブなピッカーを開く」と記載されていれば、ClaudeはIDを推測する代わりにそのウィジェットを選択します。
ウィジェットは実行時にオプションです。アプリの表示をサポートしていないホストは、単に _meta.ui ツールのテキストコンテンツを通常通りレンダリングします。ツールハンドラはすでに意味のあるテキストやJSON(ウィジェットのデータ)を返しているため、機能低下時の処理は自動的に行われます。つまり、Claudeはウィジェットを経由せず、データを直接参照します。
読み取り専用ツールの場合、ウィジェットの結果を待たないでください。単にデータを表示するだけのウィジェット(チャート、プレビュー)は、完了するためにユーザーの操作を必要とすべきではありません。表示用ウィジェットとテキストによる要約を同じ結果として返すことで、Claudeは待機することなく推論を続行できます。
レイアウトの分岐は、ツール数ではなく項目数に基づいて行ってください。「1つの結果を詳細に表示する」というユースケースと、「複数の結果を並べて表示する」というユースケースがある場合、2つのツールを作成するのではなく、 items[]を受け入れ、ウィジェットにレイアウトを選択させるようにします: items.length === 1 → 詳細表示、 > 1 → カルーセル。これにより、サーバーのスキーマをシンプルに保ち、Claudeが自然に件数を決定できるようになります。
Claudeの推論結果をペイロードに含める。各アイテムの短い note 各アイテムに(Claudeがそれを選んだ理由を示す)短いフィールドを設け、カード上のコールアウトとして表示することで、ユーザーは選択内容に沿った推論をその場で確認できます。このフィールドをツールの説明に記載し、Claudeが自動的に値を設定するようにしましょう。
画像の形状はサーバー側で正規化します。データソースからアスペクト比が大きく異なる画像が返される場合は、インラインのデータURLを取得する前に、予測可能な形式(例:正方形にトリミング)に再変換します。その後、ウィジェットの画像コンテナに固定の aspect-ratio + object-fit: contain を指定し、すべての要素が中央に配置されるようにします。
ホストのテーマに従ってください。 app.getHostContext()?.theme ( connect())に加え、 app.onhostcontextchanged を使用してリアルタイム更新を実現します。 .dark クラスをオンにトグルし 、CSSのカスタムプロパティ内の色を :root.dark {} オーバーライドブロックで色を保持し、 color-scheme。ダークモードを mix-blend-mode: multiply を無効にしてください — 画像が表示されなくなります。
テスト
Claude Desktop — 現在のビルドでは、依然として command/args config shape が必要です(ネイティブ対応は "type": "http")が必要です。 mcp-remote で囲み、 http-only トランスポートを強制することで、SSEプローブがウィジェットの機能ネゴシエーションを妨げないようにします:
{
"mcpServers": {
"my-server": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:3000/mcp",
"--allow-http", "--transport", "http-only"]
}
}
}
DesktopはUIリソースを積極的にキャッシュします。ウィジェットのHTMLを編集した後は、完全に終了(⌘Q / Alt+F4、ウィンドウの閉じボタンではない)してから再起動し、リソースの完全な再取得を強制してください。
ヘッドレス JSON-RPC ループ — デスクトップを操作せずに高速に反復処理を行う:
# test.jsonl — one JSON-RPC message per line
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}
{"jsonrpc":"2.0","method":"notifications/initialized"}
{"jsonrpc":"2.0","id":2,"method":"tools/list"}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"your_tool","arguments":{...}}}(cat test.jsonl; sleep 10) | npx mcp-remote http://localhost:3000/mcp --allow-http
` sleep は、すべてのレスポンスを収集するのに十分な時間、標準入力(stdin)を開いたままにします。jsonlの出力を jq またはPythonのワンライナーで解析します。
ウィジェット開発ループ — インライン化されたウィジェットHTMLを、偽の ExtApps shim を使用して ontoolresult をトリガーする偽のshim を使用して、プレーンな GET ルートでインラインのウィジェット HTML を提供することで、⌘Q による再起動のループを完全に回避できます
app.get("/widget-preview", (_req, res) => {
const shim = `globalThis.ExtApps={applyHostStyleVariables:()=>{},App:class{
constructor(){this.h={}} ontoolresult;onhostcontextchanged;
async connect(){const p=new URLSearchParams(location.search).get("payload");
if(p)this.ontoolresult?.({content:[{type:"text",text:p}]});}
getHostContext(){return{theme:"light"}}
sendMessage(m){console.log("sendMessage",m)} updateModelContext(){}
callServerTool(){return Promise.resolve({content:[]})} openLink(){} downloadFile(){}
}};`;
res.type("html").send(widgetHtml.replace("/*__EXT_APPS_BUNDLE__*/", shim));
});
通常のブラウザタブで http://localhost:3000/widget-preview?payload={"rows":[...]} 通常のブラウザタブで開き、通常の開発者ツールを使って反復テストを行います。
ホストのフォールバック — apps インターフェース(または MCP Inspector)がないホストを使用し、ツールのテキストコンテンツが適切に表示されることを確認します。
CSP デバッグ — iframe 自身のデベロッパーツールコンソールを開きます。CSP 違反は、ウィジェットが何の前触れもなく失敗する(空白の矩形が表示され、メインコンソールにエラーが表示されない)最大の原因です。 references/iframe-sandbox.md.
参照ファイル
references/iframe-sandbox.md— CSP/サンドボックスの制約、バンドルのインライン化パターン、画像の処理、ホストのテーマ設定references/widget-templates.md— ピッカー/確認/進行状況/表示用の再利用可能な HTML スケルトンreferences/apps-sdk-messages.md—AppクラスAPI:ウィジェット ↔ ホスト ↔ サーバー間のメッセージング、ライフサイクルおよびスーパーセッションreferences/payload-budgeting.md— ホストのツール結果サイズ上限、プルーニング・アンド・トランケート、callServerToolreferences/abuse-protection.md— Anthropic 送信 CIDR、段階的なレート制限、trust proxy、レスポンスキャッシュreferences/directory-checklist.md— コネクタ・ディレクトリへの送信前の事前チェック
Build an MCP App (Interactive UI Widgets)
An MCP app is a standard MCP server that also serves UI resources — interactive components rendered inline in the chat surface. Build once, runs in Claude and ChatGPT and any other host that implements the apps surface.
The UI layer is additive. Under the hood it's still tools, resources, and the same wire protocol. If you haven't built a plain MCP server before, the build-mcp-server skill covers the base layer. This skill adds widgets on top.
Testing in Claude: Add the server as a custom connector in claude.ai (via a Cloudflare tunnel for local dev) — this exercises the real iframe sandbox and
hostContext. See https://claude.com/docs/connectors/building/testing.
Claude host specifics
hostContext.safeAreaInsets: {top, right, bottom, left}(px) — honor these for notches and the composer overlay.- Directory submission requires OAuth or authless (
none) — static bearer is private-deploy only and blocks listing — plus toolannotationsand 3–5 PNG screenshots; seereferences/directory-checklist.md.
When a widget beats plain text
Don't add UI for its own sake — most tools are fine returning text or JSON. Add a widget when one of these is true:
If none apply, skip the widget. Text is faster to build and faster for the user.
Widgets vs Elicitation — route correctly
Before building a widget, check if elicitation covers it. Elicitation is spec-native, zero UI code, works in any compliant host.
If elicitation covers it, use it. See ../build-mcp-server/references/elicitation.md.
Architecture: two deployment shapes
Remote MCP app (most common)
Hosted streamable-HTTP server. Widget templates are served as resources; tool results reference them. The host fetches the resource, renders it in an iframe sandbox, and brokers messages between the widget and Claude.
┌──────────┐ tools/call ┌────────────┐
│ Claude │─────────────> │ MCP server │
│ host │<── result ────│ (remote) │
│ │ + widget ref │ │
│ │ │ │
│ │ resources/read│ │
│ │─────────────> │ widget │
│ ┌──────┐ │<── template ──│ HTML/JS │
│ │iframe│ │ └────────────┘
│ │widget│ │
│ └──────┘ │
└──────────┘
MCPB-packaged MCP app (local + UI)
Same widget mechanism, but the server runs locally inside an MCPB bundle. Use this when the widget needs to drive a local application — e.g., a file picker that browses the actual local disk, a dialog that controls a desktop app.
For MCPB packaging mechanics, defer to the build-mcpb skill. Everything below applies to both shapes.
How widgets attach to tools
A widget-enabled tool has two separate registrations:
- The tool declares a UI resource via
_meta.ui.resourceUri. Its handler returns plain text/JSON — NOT the HTML. - The resource is registered separately and serves the HTML.
When Claude calls the tool, the host sees _meta.ui.resourceUri, fetches that resource, renders it in an iframe, and pipes the tool's return value into the iframe via the ontoolresult event.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE }
from "@modelcontextprotocol/ext-apps/server";
import { z } from "zod";const server = new McpServer({ name: "contacts", version: "1.0.0" });// 1. The tool — returns DATA, declares which UI to show
registerAppTool(server, "pick_contact", {
description: "Open an interactive contact picker",
annotations: { title: "Pick Contact", readOnlyHint: true },
inputSchema: { filter: z.string().optional() },
_meta: { ui: { resourceUri: "ui://widgets/contact-picker.html" } },
}, async ({ filter }) => {
const contacts = await db.contacts.search(filter);
// Plain JSON — the widget receives this via ontoolresult
return { content: [{ type: "text", text: JSON.stringify(contacts) }] };
});// 2. The resource — serves the HTML
registerAppResource(
server,
"Contact Picker",
"ui://widgets/contact-picker.html",
{},
async () => ({
contents: [{
uri: "ui://widgets/contact-picker.html",
mimeType: RESOURCE_MIME_TYPE,
text: pickerHtml, // your HTML string
}],
}),
);
The URI scheme ui:// is convention. The mime type MUST be RESOURCE_MIME_TYPE ("text/html;profile=mcp-app") — this is how the host knows to render it as an interactive iframe, not just display the source.
Widget runtime — the App class
Inside the iframe, your script talks to the host via the App class from @modelcontextprotocol/ext-apps. This is a persistent bidirectional connection — the widget stays alive as long as the conversation is active, receiving new tool results and sending user actions.
<script type="module">
/* ext-apps bundle inlined at build time → globalThis.ExtApps */
/*__EXT_APPS_BUNDLE__*/
const { App } = globalThis.ExtApps; const app = new App({ name: "ContactPicker", version: "1.0.0" }, {}); // Set handlers BEFORE connecting
app.ontoolresult = ({ content }) => {
const contacts = JSON.parse(content[0].text);
render(contacts);
}; await app.connect(); // Later, when the user clicks something:
function onPick(contact) {
app.sendMessage({
role: "user",
content: [{ type: "text", text: `Selected contact: ${contact.id}` }],
});
}
</script>
The /*__EXT_APPS_BUNDLE__*/ placeholder gets replaced by the server at startup with the contents of @modelcontextprotocol/ext-apps/app-with-deps — see references/iframe-sandbox.md for why this is necessary and the rewrite snippet. Do not import { App } from "https://esm.sh/..."; the iframe's CSP blocks the transitive dependency fetches and the widget renders blank.
sendMessage is the typical "user picked something, tell Claude" path. updateModelContext is for state that Claude should know about but shouldn't clutter the chat. openLink is required for any outbound navigation — window.open and <a target="_blank"> are blocked by the sandbox attribute.
What widgets cannot do:
- Access the host page's DOM, cookies, or storage
- Make network calls to arbitrary origins (CSP-restricted — route through
callServerTool) - Open popups or navigate directly — use
app.openLink({url}) - Load remote images reliably — inline as
data:URLs server-side
Keep widgets small and single-purpose. A picker picks. A chart displays. Don't build a whole sub-app inside the iframe — split it into multiple tools with focused widgets.
Scaffold: minimal picker widget
Install:
npm install @modelcontextprotocol/sdk @modelcontextprotocol/ext-apps zod express
Server (src/server.ts):
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE }
from "@modelcontextprotocol/ext-apps/server";
import express from "express";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { z } from "zod";const require = createRequire(import.meta.url);
const server = new McpServer({ name: "contact-picker", version: "1.0.0" });// Inline the ext-apps browser bundle into the widget HTML.
// The iframe CSP blocks CDN script fetches — bundling is mandatory.
const bundle = readFileSync(
require.resolve("@modelcontextprotocol/ext-apps/app-with-deps"), "utf8",
).replace(/export\{([^}]+)\};?\s*$/, (_, body) =>
"globalThis.ExtApps={" +
body.split(",").map((p) => {
const [local, exported] = p.split(" as ").map((s) => s.trim());
return `${exported ?? local}:${local}`;
}).join(",") + "};",
);
const pickerHtml = readFileSync("./widgets/picker.html", "utf8")
.replace("/*__EXT_APPS_BUNDLE__*/", () => bundle);registerAppTool(server, "pick_contact", {
description: "Open an interactive contact picker. User selects one contact.",
annotations: { title: "Pick Contact", readOnlyHint: true },
inputSchema: { filter: z.string().optional().describe("Name/email prefix filter") },
_meta: { ui: { resourceUri: "ui://widgets/picker.html" } },
}, async ({ filter }) => {
const contacts = await db.contacts.search(filter ?? "");
return { content: [{ type: "text", text: JSON.stringify(contacts) }] };
});registerAppResource(server, "Contact Picker", "ui://widgets/picker.html", {},
async () => ({
contents: [{ uri: "ui://widgets/picker.html", mimeType: RESOURCE_MIME_TYPE, text: pickerHtml }],
}),
);const app = express();
app.use(express.json());
app.post("/mcp", async (req, res) => {
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on("close", () => transport.close());
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});
app.listen(process.env.PORT ?? 3000);
For local-only widget apps (driving a desktop app, reading local files), swap the transport to StdioServerTransport and package via the build-mcpb skill.
Widget (widgets/picker.html):
<!doctype html>
<meta charset="utf-8" />
<style>
body { font: 14px system-ui; margin: 0; }
ul { list-style: none; padding: 0; margin: 0; max-height: 300px; overflow-y: auto; }
li { padding: 10px 14px; cursor: pointer; border-bottom: 1px solid #eee; }
li:hover { background: #f5f5f5; }
.sub { color: #666; font-size: 12px; }
</style>
<ul id="list"></ul>
<script type="module">
/*__EXT_APPS_BUNDLE__*/
const { App } = globalThis.ExtApps;
(async () => {
const app = new App({ name: "ContactPicker", version: "1.0.0" }, {});
const ul = document.getElementById("list"); app.ontoolresult = ({ content }) => {
const contacts = JSON.parse(content[0].text);
ul.innerHTML = "";
for (const c of contacts) {
const li = document.createElement("li");
li.innerHTML = `<div>${c.name}</div><div class="sub">${c.email}</div>`;
li.addEventListener("click", () => {
app.sendMessage({
role: "user",
content: [{ type: "text", text: `Selected contact: ${c.id} (${c.name})` }],
});
});
ul.append(li);
}
}; await app.connect();
})();
</script>
See references/widget-templates.md for more widget shapes.
Design notes that save you a rewrite
One widget per tool. Resist the urge to build one mega-widget that does everything. One tool → one focused widget → one clear result shape. Claude reasons about these far better.
Tool description must mention the widget. Claude only sees the tool description when deciding what to call. "Opens an interactive picker" in the description is what makes Claude reach for it instead of guessing an ID.
Widgets are optional at runtime. Hosts that don't support the apps surface simply ignore _meta.ui and render the tool's text content normally. Since your tool handler already returns meaningful text/JSON (the widget's data), degradation is automatic — Claude sees the data directly instead of via the widget.
Don't block on widget results for read-only tools. A widget that just displays data (chart, preview) shouldn't require a user action to complete. Return the display widget and a text summary in the same result so Claude can continue reasoning without waiting.
Layout-fork by item count, not by tool count. If one use case is "show one result in detail" and another is "show many results side-by-side", don't make two tools — make one tool that accepts items[], and let the widget pick a layout: items.length === 1 → detail view, > 1 → carousel. Keeps the server schema simple and lets Claude decide count naturally.
Put Claude's reasoning in the payload. A short note field on each item (why Claude picked it) rendered as a callout on the card gives users the reasoning inline with the choice. Mention this field in the tool description so Claude populates it.
Normalize image shapes server-side. If your data source returns images with wildly varying aspect ratios, rewrite to a predictable variant (e.g. square-bounded) before fetching for the data-URL inline. Then give the widget's image container a fixed aspect-ratio + object-fit: contain so everything sits centered.
Follow host theme. app.getHostContext()?.theme (after connect()) plus app.onhostcontextchanged for live updates. Toggle a .dark class on <html>, keep colors in CSS custom props with a :root.dark {} override block, set color-scheme. Disable mix-blend-mode: multiply in dark — it makes images vanish.
Testing
Claude Desktop — current builds still require the command/args config shape (no native "type": "http"). Wrap with mcp-remote and force http-only transport so the SSE probe doesn't swallow widget-capability negotiation:
{
"mcpServers": {
"my-server": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:3000/mcp",
"--allow-http", "--transport", "http-only"]
}
}
}
Desktop caches UI resources aggressively. After editing widget HTML, fully quit (⌘Q / Alt+F4, not window-close) and relaunch to force a cold resource re-fetch.
Headless JSON-RPC loop — fast iteration without clicking through Desktop:
# test.jsonl — one JSON-RPC message per line
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}
{"jsonrpc":"2.0","method":"notifications/initialized"}
{"jsonrpc":"2.0","id":2,"method":"tools/list"}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"your_tool","arguments":{...}}}(cat test.jsonl; sleep 10) | npx mcp-remote http://localhost:3000/mcp --allow-http
The sleep keeps stdin open long enough to collect all responses. Parse the jsonl output with jq or a Python one-liner.
Widget dev loop — avoid the ⌘Q-relaunch cycle entirely by serving the inlined widget HTML at a plain GET route with a fake ExtApps shim that fires ontoolresult from a query param:
app.get("/widget-preview", (_req, res) => {
const shim = `globalThis.ExtApps={applyHostStyleVariables:()=>{},App:class{
constructor(){this.h={}} ontoolresult;onhostcontextchanged;
async connect(){const p=new URLSearchParams(location.search).get("payload");
if(p)this.ontoolresult?.({content:[{type:"text",text:p}]});}
getHostContext(){return{theme:"light"}}
sendMessage(m){console.log("sendMessage",m)} updateModelContext(){}
callServerTool(){return Promise.resolve({content:[]})} openLink(){} downloadFile(){}
}};`;
res.type("html").send(widgetHtml.replace("/*__EXT_APPS_BUNDLE__*/", shim));
});
Open http://localhost:3000/widget-preview?payload={"rows":[...]} in a normal browser tab and iterate with ordinary devtools.
Host fallback — use a host without the apps surface (or MCP Inspector) and confirm the tool's text content degrades gracefully.
CSP debugging — open the iframe's own devtools console. CSP violations are the #1 reason widgets silently fail (blank rectangle, no error in the main console). See references/iframe-sandbox.md.
Reference files
references/iframe-sandbox.md— CSP/sandbox constraints, the bundle-inlining pattern, image handling, host themingreferences/widget-templates.md— reusable HTML scaffolds for picker / confirm / progress / displayreferences/apps-sdk-messages.md— theAppclass API: widget ↔ host ↔ server messaging, lifecycle & supersessionreferences/payload-budgeting.md— host tool-result size caps, prune-then-truncate, heavy assets viacallServerToolreferences/abuse-protection.md— Anthropic egress CIDRs, tiered rate limiting,trust proxy, response cachingreferences/directory-checklist.md— pre-flight for connector-directory submission
すべてのファイル
7件のファイルbuild-mcp-appをインストール
スキルファイルをダウンロードし、.claude/skills/ ディレクトリに解凍してください。
ZIPをダウンロードリポジトリをクローンし、スキルファイルをプロジェクトにコピーしてください。
git clone https://github.com/anthropics/claude-plugins-official/tree/main/plugins/mcp-server-dev/skills/build-mcp-app # Copy the skill folder to .claude/skills/ or .codex/skills/
コピー





家
