簡介
外掛程式透過模型上下文協定(MCP),讓 ChatGPT 和 Codex 能使用伺服器提供的功能。本教學使用下列兩個元件:
- MCP 伺服器,用來定義工具並提供給 ChatGPT 和 Codex 呼叫。
- 選用的網頁元件,會顯示在 ChatGPT 內的 iframe 中。
ChatGPT 支援 MCP Apps 開放式使用者介面標準,因此只需開發一次介面,就能在相容於 MCP Apps 的主機上執行。
在本快速入門中,我們會建立一套簡單的待辦事項管理流程。介面的 HTML 標記、CSS 和 JavaScript 都放在同一個 HTML 檔案中。
如需使用 React 的進階範例,請參閱 GitHub 上的範例程式碼庫。
建立網頁元件
這個步驟可省略。如果只需要工具,無須在 ChatGPT 中顯示介面,請直接前往建立 MCP 伺服器,並略過 UI 資源的註冊步驟。
首先,在新的目錄中建立 public/todo-widget.html 檔案。這個檔案會包含網頁元件。當對應的 MCP 工具傳回這個元件時,ChatGPT 就會在介面中顯示它。
將以下內容加入檔案:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Todo list</title>
<style>
:root {
color: #0b0b0f;
font-family:
"Inter",
system-ui,
-apple-system,
sans-serif;
}
html,
body {
width: 100%;
min-height: 100%;
box-sizing: border-box;
}
body {
margin: 0;
padding: 16px;
background: #f6f8fb;
}
main {
width: 100%;
max-width: 360px;
min-height: 260px;
margin: 0 auto;
background: #fff;
border-radius: 16px;
padding: 20px;
box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
}
h2 {
margin: 0 0 16px;
font-size: 1.25rem;
}
form {
display: flex;
gap: 8px;
margin-bottom: 16px;
}
form input {
flex: 1;
padding: 10px 12px;
border-radius: 10px;
border: 1px solid #cad3e0;
font-size: 0.95rem;
}
form button {
border: none;
border-radius: 10px;
background: #111bf5;
color: white;
font-weight: 600;
padding: 0 16px;
cursor: pointer;
}
form button:disabled {
opacity: 0.7;
cursor: not-allowed;
}
input[type="checkbox"] {
accent-color: #111bf5;
}
ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
li {
background: #f2f4fb;
border-radius: 12px;
padding: 10px 14px;
display: flex;
align-items: center;
gap: 10px;
}
li span {
flex: 1;
}
li[data-completed="true"] span {
text-decoration: line-through;
color: #6c768a;
}
li[data-busy="true"] {
opacity: 0.7;
}
</style>
</head>
<body>
<main>
<h2>Todo list</h2>
<form id="add-form" autocomplete="off">
<input id="todo-input" name="title" placeholder="Add a task" />
<button type="submit">Add</button>
</form>
<ul id="todo-list"></ul>
</main>
<script type="module">
const listEl = document.querySelector("#todo-list");
const formEl = document.querySelector("#add-form");
const inputEl = document.querySelector("#todo-input");
const addButtonEl = formEl.querySelector('button[type="submit"]');
const addButtonText = addButtonEl.textContent;
let tasks = [];
let isAdding = false;
const busyTodoIds = new Set();
const render = () => {
listEl.innerHTML = "";
tasks.forEach((task) => {
const li = document.createElement("li");
li.dataset.id = task.id;
li.dataset.completed = String(Boolean(task.completed));
li.dataset.busy = String(busyTodoIds.has(task.id));
const label = document.createElement("label");
label.style.display = "flex";
label.style.alignItems = "center";
label.style.gap = "10px";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = Boolean(task.completed);
checkbox.disabled = busyTodoIds.has(task.id);
const span = document.createElement("span");
span.textContent = task.title;
label.appendChild(checkbox);
label.appendChild(span);
li.appendChild(label);
listEl.appendChild(li);
});
};
const updateFromResponse = (response) => {
if (response?.structuredContent?.tasks) {
tasks = response.structuredContent.tasks;
render();
}
};
// MCP Apps standard bridge: JSON-RPC messages over postMessage.
//
// - Initialize the bridge with `ui/initialize`.
// - Confirm readiness with `ui/notifications/initialized`.
// - Call tools with `tools/call`.
// - Listen for `ui/notifications/tool-result` to react to model-initiated tool calls.
let rpcId = 0;
const pendingRequests = new Map();
const rpcNotify = (method, params) => {
window.parent.postMessage({ jsonrpc: "2.0", method, params }, "*");
};
const rpcRequest = (method, params) =>
new Promise((resolve, reject) => {
const id = ++rpcId;
pendingRequests.set(id, { resolve, reject });
window.parent.postMessage(
{ jsonrpc: "2.0", id, method, params },
"*"
);
});
window.addEventListener(
"message",
(event) => {
if (event.source !== window.parent) return;
const message = event.data;
if (!message || message.jsonrpc !== "2.0") return;
// Responses
if (typeof message.id === "number") {
const pending = pendingRequests.get(message.id);
if (!pending) return;
pendingRequests.delete(message.id);
if (message.error) {
pending.reject(message.error);
return;
}
pending.resolve(message.result);
return;
}
// Notifications
if (typeof message.method !== "string") return;
if (message.method === "ui/notifications/tool-result") {
updateFromResponse(message.params);
}
},
{ passive: true }
);
const initializeBridge = async () => {
const appInfo = { name: "todo-widget", version: "0.1.0" };
const appCapabilities = {};
const protocolVersion = "2026-01-26";
try {
await rpcRequest("ui/initialize", {
appInfo,
appCapabilities,
protocolVersion,
});
rpcNotify("ui/notifications/initialized", {});
} catch (error) {
console.error("Failed to initialize the MCP Apps bridge:", error);
throw error;
}
};
const bridgeReady = initializeBridge();
const callTodoTool = async (name, payload) => {
await bridgeReady;
const response = await rpcRequest("tools/call", {
name,
arguments: payload,
});
updateFromResponse(response);
};
formEl.addEventListener("submit", async (event) => {
event.preventDefault();
const title = inputEl.value.trim();
if (!title || isAdding) return;
isAdding = true;
addButtonEl.disabled = true;
addButtonEl.textContent = "Adding…";
try {
await callTodoTool("add_todo", { title });
inputEl.value = "";
} catch (error) {
console.error("Failed to add todo:", error);
} finally {
isAdding = false;
addButtonEl.disabled = false;
addButtonEl.textContent = addButtonText;
}
});
listEl.addEventListener("change", async (event) => {
const checkbox = event.target;
if (!checkbox.matches('input[type="checkbox"]')) return;
const id = checkbox.closest("li")?.dataset.id;
if (!id) return;
if (!checkbox.checked) {
checkbox.checked = true;
return;
}
if (busyTodoIds.has(id)) return;
busyTodoIds.add(id);
checkbox.disabled = true;
const rowEl = checkbox.closest("li");
if (rowEl) rowEl.dataset.busy = "true";
try {
await callTodoTool("complete_todo", { id });
} catch (error) {
console.error("Failed to complete todo:", error);
} finally {
busyTodoIds.delete(id);
render();
}
});
render();
</script>
</body>
</html>在網頁元件中使用 MCP Apps
開發新的介面時,請使用 MCP Apps 的主機橋接機制。它透過 postMessage 傳送 JSON-RPC 訊息,支援 ui/* 通知以及 tools/call 等方法。
先確認各主機共用的 MCP Apps 流程能正常運作。只有在需要標準未涵蓋的功能時,才透過 window.openai 加入選用的 ChatGPT 擴充功能。詳情請參閱為 MCP 伺服器加入使用者介面。
建立 MCP 伺服器
安裝官方的 Python 或 TypeScript 版 MCP SDK,即可建立伺服器並提供 /mcp 端點。
本快速入門使用 TypeScript SDK。
如果你使用 Python,可以在 GitHub 上的範例程式碼庫中查看使用 Python SDK 建立 MCP 伺服器的範例。
請使用 Node.js 22.6 或更新版本。執行以下指令,安裝 TypeScript SDK、MCP Apps 輔助工具和 zod 套件:
npm install @modelcontextprotocol/sdk @modelcontextprotocol/ext-apps zod
提供 UI 資源的 MCP 伺服器
為打包好的元件註冊一項資源,並註冊模型可呼叫的工具(例如 add_todo 和 complete_todo),讓 ChatGPT 能透過這些工具更新介面。
建立名為 server.ts 的檔案,並貼上以下使用 TypeScript SDK 的範例程式碼:
import { createServer } from "node:http";
import { readFileSync } from "node:fs";
import {
registerAppResource,
registerAppTool,
RESOURCE_MIME_TYPE,
} from "@modelcontextprotocol/ext-apps/server";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";
const todoHtml = readFileSync("public/todo-widget.html", "utf8");
const addTodoInputSchema = {
title: z.string().min(1),
};
const completeTodoInputSchema = {
id: z.string().min(1),
};
const todoOutputSchema = {
tasks: z.array(
z.object({
id: z.string(),
title: z.string(),
completed: z.boolean(),
})
),
};
let todos: { id: string; title: string; completed: boolean }[] = [];
let nextId = 1;
const replyWithTodos = (message: string) => ({
content: message ? [{ type: "text" as const, text: message }] : [],
structuredContent: { tasks: todos },
});
function createTodoServer() {
const server = new McpServer({
name: "todo-plugin-server",
version: "0.1.0",
});
registerAppResource(
server,
"todo-widget",
"ui://widget/todo.html",
{},
async () => ({
contents: [
{
uri: "ui://widget/todo.html",
mimeType: RESOURCE_MIME_TYPE,
text: todoHtml,
},
],
})
);
registerAppTool(
server,
"add_todo",
{
title: "Add todo",
description: "Creates a todo item with the given title.",
inputSchema: addTodoInputSchema,
outputSchema: todoOutputSchema,
_meta: {
ui: { resourceUri: "ui://widget/todo.html" },
},
},
async (args) => {
const title = args?.title?.trim?.() ?? "";
if (!title) return replyWithTodos("Missing title.");
const todo = { id: `todo-${nextId++}`, title, completed: false };
todos = [...todos, todo];
return replyWithTodos(`Added "${todo.title}".`);
}
);
registerAppTool(
server,
"complete_todo",
{
title: "Complete todo",
description: "Marks a todo as done by id.",
inputSchema: completeTodoInputSchema,
outputSchema: todoOutputSchema,
_meta: {
ui: { resourceUri: "ui://widget/todo.html" },
},
},
async (args) => {
const id = args?.id;
if (!id) return replyWithTodos("Missing todo id.");
const todo = todos.find((task) => task.id === id);
if (!todo) {
return replyWithTodos(`Todo ${id} was not found.`);
}
todos = todos.map((task) =>
task.id === id ? { ...task, completed: true } : task
);
return replyWithTodos(`Completed "${todo.title}".`);
}
);
return server;
}
const port = Number(process.env.PORT ?? 8787);
const MCP_PATH = "/mcp";
const httpServer = createServer(async (req, res) => {
if (!req.url) {
res.writeHead(400).end("Missing URL");
return;
}
const url = new URL(req.url, `http://${req.headers.host ?? "localhost"}`);
if (req.method === "OPTIONS" && url.pathname === MCP_PATH) {
res.writeHead(204, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "content-type, mcp-session-id",
"Access-Control-Expose-Headers": "Mcp-Session-Id",
});
res.end();
return;
}
if (req.method === "GET" && url.pathname === "/") {
res.writeHead(200, { "content-type": "text/plain" }).end("Todo MCP server");
return;
}
const MCP_METHODS = new Set(["POST", "GET", "DELETE"]);
if (url.pathname === MCP_PATH && req.method && MCP_METHODS.has(req.method)) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
const server = createTodoServer();
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined, // stateless mode
enableJsonResponse: true,
});
res.on("close", () => {
transport.close();
server.close();
});
try {
await server.connect(transport);
await transport.handleRequest(req, res);
} catch (error) {
console.error("Error handling MCP request:", error);
if (!res.headersSent) {
res.writeHead(500).end("Internal server error");
}
}
return;
}
res.writeHead(404).end("Not Found");
});
httpServer.listen(port, () => {
console.log(
`Todo MCP server listening on http://localhost:${port}${MCP_PATH}`
);
});這段程式碼也會回應健康檢查使用的 GET / 請求、處理 /mcp 的 CORS 預檢請求,並針對尚未使用的 OAuth 探索路由傳回 404 Not Found。這樣一來,在尚未設定驗證的開發階段,ChatGPT 就不會因此顯示 502 錯誤。
在本機執行
如果使用 React 等網頁框架,請將元件建置為靜態資源,讓 HTML 範本能直接嵌入這些資源。通常可以執行 npm run build 等建置指令,產生 dist 目錄,裡面會包含編譯好的資源。
本快速入門使用純 HTML,因此可以省略建置步驟。
若要在 http://localhost:<port>/mcp 啟動 MCP 伺服器,請先切換到 server.ts 所在的目錄。
請確認 "type": "module" 已加入 package.json 檔案:
{
"type": "module",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.20.2",
"@modelcontextprotocol/ext-apps": "^1.0.1",
"zod": "^3.25.76"
}
}
接著執行以下指令啟動伺服器:
node --experimental-strip-types server.ts
伺服器就緒後,應會顯示 Todo MCP server listening on http://localhost:8787/mcp。
使用 MCP Inspector 測試
你可以使用 MCP Inspector 在本機測試伺服器。
npx @modelcontextprotocol/inspector@latest
這個指令會開啟 MCP Inspector 介面。選取 Streamable HTTP,輸入 http://localhost:8787/mcp,然後連線,即可測試伺服器並檢查工具的回應。

讓公用網際網路能存取伺服器
若要讓 ChatGPT 在開發期間存取伺服器,你必須讓伺服器可從公用網際網路連入。你可以使用 ngrok 等工具,建立通往本機伺服器的通道。
ngrok http <port>
執行後會取得類似 https://<subdomain>.ngrok.app 的公開網址。ChatGPT 可以透過這個網址存取你的伺服器。
在 ChatGPT 中連線至 MCP 伺服器時,請提供包含 /mcp 路徑的公開網址(例如 https://<subdomain>.ngrok.app/mcp)。
在 ChatGPT 中連線至 MCP 伺服器
確認 MCP 伺服器和網頁元件都能在本機正常運作後,即可在 ChatGPT 中連線至伺服器:
- 前往 ChatGPT 外掛程式,選取加號按鈕,再選取新增自訂 MCP 伺服器。
- 貼上通道或部署環境提供的 HTTPS 網址,並確認網址包含
/mcp路徑(例如https://<subdomain>.ngrok.app/mcp)。接著為連線命名,並設定驗證方式。 - 閱讀風險警告,選取我瞭解並想繼續,再選取建立為外掛程式。
- 安裝剛建立的外掛程式,開啟新對話,在提示詞輸入框中輸入
@並選取該外掛程式。接著輸入提示詞,例如「幫我把讀手邊這本書加入待辦事項」。ChatGPT 會以串流方式傳送工具呼叫的資料,讓你確認輸入和輸出。
後續步驟
接下來,你可以持續調整使用者介面與使用者體驗、提示詞及工具中繼資料,改善整體使用體驗。
每次變更 MCP 伺服器的工具、中繼資料或相關設定後,請重新整理外掛程式連線。你可以前往 chatgpt.com/plugins,在外掛程式的詳細資料頁面重新整理連線。
準備公開發布時,請參閱提交外掛程式、外掛程式指南和構思外掛程式的使用情境。如果你正在開發使用者介面,也可以參閱使用者介面指南。
熟悉基本概念後,你可以建立功能更豐富的使用者介面、視需要驗證使用者身分,以及管理狀態。