How to Build a Connector and Plugin for ChatGPT and Claude, Part 2: Build the MCP Server, Tools and Widget
Create an MCP server, add tools the AI uses correctly, return structured results and show an interactive widget inside ChatGPT and Claude.
Where we are
This is Part 2 of a three-part series:
- Plan before you code
- Build the MCP server, tools and widget (this post)
- Secure, test and publish on ChatGPT and Claude
If connectors and plugins are new to you, start with What Are Connectors and Plugins in ChatGPT and Claude?
In Part 1 we planned a restaurant booking connector. Now let’s build it. The examples use TypeScript and the official MCP SDK, but SDKs exist for Python, C#, Java and more, and the ideas are the same everywhere. If you work in .NET, see our guide on building an MCP server with the C# SDK and Semantic Kernel.
Step 1: Create the MCP server
npm init -y
npm install @modelcontextprotocol/sdk zod express
A minimal server with one tool, over Streamable HTTP, the transport remote clients like ChatGPT and Claude use:
import express from "express";
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
function createServer() {
const server = new McpServer({ name: "table-booking", version: "1.0.0" });
server.registerTool(
"search_restaurants",
{
title: "Search restaurants",
description:
"Find restaurants with free tables. Use when the user wants to eat out or book a table. " +
"Ask for the city, date, time and party size if they are missing. " +
"Next: let the user pick a time, then call book_table.",
inputSchema: {
city: z.string().describe("City or area, as the user said it"),
date: z.string().describe("Date in YYYY-MM-DD"),
time: z.string().describe("Preferred time in 24-hour HH:mm, for example 20:00"),
partySize: z.number().int().min(1).max(20),
cuisine: z.string().optional()
},
annotations: { readOnlyHint: true }
},
async ({ city, date, time, partySize, cuisine }) => {
const restaurants = await bookingApi.search({ city, date, time, partySize, cuisine });
return {
structuredContent: { restaurants },
content: [{ type: "text", text: `Found ${restaurants.length} restaurants. Ask the user which time they prefer.` }]
};
}
);
return server;
}
const app = express();
app.use(express.json());
app.post("/mcp", async (req, res) => {
const server = createServer();
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on("close", () => {
transport.close();
server.close();
});
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});
app.listen(3000);
This is a stateless server: each request stands alone, so you can run several copies behind a load balancer. Keep any state (bookings, sessions) in your own database.
Step 2: Write tool descriptions the AI follows
As we saw in Part 1, a tool description is the label on a button. The model decides which tool to call and what to pass using only the tool’s name, its description and the descriptions of its inputs. It never sees your code.
There are two levels:
- The tool description (
descriptionabove) explains what the tool does and when to use it. - Input descriptions (
.describe(...)on each field) explain what each value means and its format, for example “Date in YYYY-MM-DD”.
A good tool description says:
- When to use it, in the words users actually type (“eat out”, “book a table”).
- What to ask first, if inputs are missing.
- What to do next, after the call.
- The rules: “Never say the table is booked unless get_booking shows it as confirmed.”
A weak description vs. a strong one:
| Weak | Strong |
|---|---|
| “Searches restaurants.” | “Find restaurants with free tables. Use when the user wants to eat out or book a table. Ask for the city, date, time and party size if they are missing. Next: let the user pick a time, then call book_table.” |
Keep each description about one tool. The step-by-step flow across several tools belongs in the server instructions (Step 4) and, in more detail, in a skill (Part 3).
Also set annotations honestly: readOnlyHint for tools that only read, destructiveHint for tools that delete or cancel. Clients use them to decide when to ask the user for permission.
Step 3: Return results the AI can act on
Every tool result should include:
structuredContent: clean JSON for the widget and the model.content: a short sentence the model can repeat, ideally with the next step.- Friendly errors: return
isError: truewith a clear message such as “That time is no longer available. Offer the other slots.” Never return a stack trace.
Step 4: Add server instructions
Most SDKs let you give the client a short description of the whole server. Use it for the overall flow and hard rules:
Table Booking finds restaurants and books tables.
Flow: search_restaurants -> the user picks a time -> book_table -> the user pays the deposit
on the payment page -> get_booking -> share the confirmation.
Only get_booking confirms a booking. Never ask for card details in the chat.
Short and factual works best. Server instructions are a map of how the tools fit together; a skill (Part 3) is the full step-by-step guide.
Step 5: Show an interactive widget
A widget is an HTML page that your server provides as a resource. The client shows it in a sandboxed frame inside the chat, right where the tool result appears.
5a. Register the widget as a resource
const WIDGET_URI = "ui://widget/booking.html";
server.registerResource("booking-widget", WIDGET_URI, {}, async () => ({
contents: [
{
uri: WIDGET_URI,
mimeType: "text/html;profile=mcp-app",
text: bookingWidgetHtml,
_meta: {
ui: {
csp: {
connectDomains: ["https://api.example.com"],
resourceDomains: []
}
}
}
}
]
}));
The CSP (Content Security Policy) lists the only domains the widget may contact. Keep it as small as possible.
5b. Link the widget to a tool
Add metadata to the tool so the client knows which widget to show with its result:
_meta: {
ui: { resourceUri: WIDGET_URI },
"openai/outputTemplate": WIDGET_URI
}
ui.resourceUri is the open MCP Apps standard. openai/outputTemplate is the matching key for ChatGPT’s Apps SDK. Adding both keeps you compatible with both clients.
5c. Talk to the chat from the widget
Inside the widget, communication happens through postMessage with small JSON-RPC messages. The ones you’ll use most:
| Message | What it does |
|---|---|
ui/initialize |
Handshake; returns theme (light or dark) and language |
ui/notifications/tool-result |
The host sends the tool’s result to the widget |
tools/call |
The widget calls one of your tools, for example when “Book” is clicked |
ui/open-link |
Opens a page, such as your payment page, in a new tab |
ui/update-model-context |
Tells the AI what the user did in the widget |
ui/notifications/size-changed |
Tells the host how tall the widget is |
ChatGPT also offers a window.openai helper with similar functions (callTool, openExternal, setWidgetState). A small wrapper lets one widget work in both:
function callTool(name, args) {
if (window.openai && window.openai.callTool) {
return window.openai.callTool(name, args);
}
return request("tools/call", { name: name, arguments: args });
}
Here request is a tiny helper that posts a JSON-RPC message to window.parent and waits for the matching reply.
5d. Widget tips that make a big difference
- Keep it one self-contained HTML file, with inline CSS and JS and no external scripts. It’s simpler and safer.
- Match the chat’s theme and language using the values from
ui/initialize. - Design for mobile first. A 320 px wide layout with big tap targets also looks good on desktop.
- Drive the screen from a status. Render from the latest server status, and check it again while waiting, so the widget never gets out of sync.
- One loader per screen. A spinner and a progress bar together look broken.
- Always offer a manual “check again” button when waiting on something outside the chat.
- Tell the AI what happened. After a click, update the model context, so “Is my table booked?” gets the right answer.
Step 6: Handle files and long tasks
Files: clients pass files to tools in different ways, and some can’t pass them at all. Support at least one universal path: an upload inside the widget, or a short-lived upload link to your website.
Long tasks: a tool should answer in seconds. For slow work (AI processing, reports, conversions), start a background job, return a status such as processing, and let the widget or the AI check progress with a status tool.
Payments: open your own payment page in a new tab from a button click, and confirm the payment only on your server. The AI should never decide by itself that a payment succeeded.
Step 7: Test locally
npx @modelcontextprotocol/inspector
Connect the MCP Inspector to http://localhost:3000/mcp and:
- Check that every tool appears with the right inputs and description.
- Call each tool by hand and read exactly what the AI will see.
- Try bad inputs and confirm the errors are friendly.
For the widget, open the HTML in a browser with a fake callTool that returns sample data, and click through every screen at phone and desktop widths.
Next up
In Part 3: Secure, Test and Publish we make it safe for real users, test it inside ChatGPT and Claude, package it as a plugin and publish it.