Yes, you can make your product available to Claude, ChatGPT, Cursor, and VS Code without building a separate connector for each client. An MCP server exposes your data and actions in a format those agents already know how to call. The current MCP specification is the 2026-07-28 revision, and the official TypeScript SDK is published as version 2.4.0 on npm as of November 6, 2026. A first local server fits in one file with two tools; production adds HTTP transport, authentication, and publishing.
The protocol uses JSON-RPC 2.0. A host — Claude, ChatGPT, Cursor, VS Code — starts a client that connects to your server. The server exposes three families of objects: tools, which the model can call; resources, which the client can read and attach to context; and prompts, which the user invokes explicitly. Your server does not decide when a tool runs. It describes what it can do, and the model chooses.
What MCP changes for your product#
A plain REST API expects the model to know your routes, parameters, and error codes. MCP moves that knowledge into the server: each tool carries a name, a description, an input schema, and, if you provide one, an output schema. The client shows the call, asks the user for approval, and passes the result back to the model.
The point is not to replace your API. It is to add a discovery and safety layer between the model and your product. An agent searching for a note does not need to know whether your backend uses PostgreSQL, Stripe, or a full-text index. It calls search_notes with a query, and your server translates.
MCP has also become a common entry point. Claude, ChatGPT, Cursor, and VS Code accept remote MCP servers over Streamable HTTP. A local stdio server remains useful for tools that read files or a local database. That split is reflected in the TypeScript SDK's two surfaces: @modelcontextprotocol/server for the server and @modelcontextprotocol/client for the client, as separate packages since version 2.
Scope it down: two tools, not twenty#
The temptation is to expose everything. A server with twenty generic tools tires the model, lengthens the prompt, and multiplies bad choices. Start with the workflow that justifies the integration: find an object, then read its detail. The example product in this article is a notes service with search_notes and get_note.
A few rules make those tools usable by an agent. The name describes the action and the domain: search_notes, not search. The description says when to use it, not only what it does. Every schema field carries a .describe(): the SDK turns that description into JSON Schema, and it is the only documentation the model gets for the argument. Results are bounded: at most twenty notes, a 160-character snippet, and a canonical URL so the client can cite the source.
Annotations help the client decide what to show. readOnlyHint: true marks a tool that changes nothing. destructiveHint: true asks for confirmation before deleting. idempotentHint: true says a repeated call produces the same result. These annotations are hints, not access controls: a client can ignore them, and your server must enforce its own rules.
For any tool that writes, add explicit confirmation and an idempotency key. A create_note tool that receives the same request twice must not create two notes. The model can be wrong, retry, or be interrupted; your server has to stay predictable.
Set up the TypeScript project#
SDK 2.4.0 declares Node.js 20 or newer in its engines. Create an empty project, install the server package and Zod, then add TypeScript:
mkdir notes-mcp
cd notes-mcp
npm init -y
npm install @modelcontextprotocol/server zod
npm install -D typescript @types/node
mkdir srcEnable ES modules and build scripts in package.json:
{
"name": "notes-mcp",
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/stdio.js"
}
}Create a minimal tsconfig.json. ES2022 is enough for Node.js 20, and module: Node16 keeps imports explicit:
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"types": ["node"],
"skipLibCheck": true
},
"include": ["src"]
}Keep server construction separate from transport. src/create-server.ts exports a function that builds a fresh server; src/stdio.ts uses it for the local transport. That split lets you reuse the exact same tools behind HTTP without duplicating code.
Write the tools with Zod#
The file below defines two tools, one resource, and one prompt. The in-memory store is deliberately simple: replace the notes array with your API calls or database. The shape of the server matters, not the data source.
import { McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";
type Note = { id: string; title: string; body: string; url: string };
const notes: Note[] = [
{
id: "n_1042",
title: "Restart a Coolify deployment",
body: "Open the project, then Deploy. The health check waits 30 seconds.",
url: "https://app.example.com/notes/n_1042"
}
];
export function createServer() {
const server = new McpServer({ name: "notes", version: "1.0.0" });
server.registerTool(
"search_notes",
{
title: "Search notes",
description:
"Search notes by keyword and return up to 20 results with their canonical URL.",
inputSchema: z.object({
query: z.string().min(2).describe("Keywords to match in the title and body"),
limit: z.number().int().min(1).max(20).default(10)
}),
outputSchema: z.object({
results: z.array(
z.object({
id: z.string(),
title: z.string(),
url: z.string(),
snippet: z.string()
})
)
}),
annotations: { readOnlyHint: true, idempotentHint: true }
},
async ({ query, limit }) => {
const needle = query.toLowerCase();
const results = notes
.filter((note) => `${note.title} ${note.body}`.toLowerCase().includes(needle))
.slice(0, limit)
.map((note) => ({
id: note.id,
title: note.title,
url: note.url,
snippet: note.body.slice(0, 160)
}));
const output = { results };
return {
content: [{ type: "text", text: JSON.stringify(output) }],
structuredContent: output
};
}
);
server.registerTool(
"get_note",
{
title: "Read a note",
description: "Return the full content of one note by its identifier.",
inputSchema: z.object({
id: z.string().describe("Identifier returned by search_notes")
}),
outputSchema: z.object({
id: z.string(),
title: z.string(),
text: z.string(),
url: z.string()
}),
annotations: { readOnlyHint: true }
},
async ({ id }) => {
const note = notes.find((candidate) => candidate.id === id);
if (!note) {
return {
content: [{ type: "text", text: `No note with identifier ${id}.` }],
isError: true
};
}
const output = { id: note.id, title: note.title, text: note.body, url: note.url };
return {
content: [{ type: "text", text: JSON.stringify(output) }],
structuredContent: output
};
}
);
server.registerResource(
"guide",
"notes://guide",
{
title: "Notes guide",
description: "Title, tag, and internal-link conventions.",
mimeType: "text/markdown"
},
async (uri) => ({
contents: [
{
uri: uri.href,
mimeType: "text/markdown",
text: "# Guide\n\nOne title per note, short tags, one canonical URL."
}
]
})
);
server.registerPrompt(
"summarize-note",
{
title: "Summarize a note",
description: "Prepare a three-point summary of one note.",
argsSchema: z.object({
id: z.string().describe("Note identifier")
})
},
({ id }) => ({
messages: [
{
role: "user" as const,
content: {
type: "text" as const,
text: `Summarize note ${id} in three points, then cite its URL.`
}
}
]
})
);
return server;
}Three details matter in this file. The Zod schema is the single source of truth: the SDK derives the advertised JSON Schema, validates arguments before the call, and types the handler argument. An argument outside the schema comes back to the model as an isError: true result with a message it can read and correct. Finally, structuredContent mirrors the JSON text: newer clients can validate the structure, older ones read the text.
The local transport takes a few lines:
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { createServer } from "./create-server.js";
serveStdio(createServer, {
onerror: (error) => console.error("notes-mcp:", error)
});serveStdio picks the protocol era at open, then pins one instance built by createServer for the life of the connection. It serves 2026-07-28 clients and, by default, 2025 clients that still open with initialize; { legacy: "reject" } turns those away. A server/discover probe can build one extra instance, discarded if the client falls back to initialize, so createServer must return a fresh server on every call with no shared state.
Add a resource and a prompt#
Resources are application-controlled, not model-controlled. notes://guide gives the client a stable document it can read and attach to the conversation. A client such as VS Code exposes resources in a context menu; Claude and Cursor list them too. Use them for conventions, data schemas, or catalogs that change rarely.
Prompts are user-invoked, often as a command or a menu entry. summarize-note prepares a message with the supplied identifier. The client can show the arguments, the user fills them in, and the model receives the message. A prompt executes nothing: it frames the request.
Neither surface is mandatory. A server with only tools works. But a resource avoids repeating the same explanations in every tool description, and a prompt gives a visible entry point to a user who does not know which tool to call.
Test with the Inspector before connecting an agent#
The official Inspector runs through npx. The CLI mode connects, runs one request, prints the result, and exits. It is the fastest way to check a server before adding it to a host.
npm run build
npx @modelcontextprotocol/inspector --cli node dist/stdio.js \
--protocol-era modern --method tools/listThe Inspector defaults to the legacy era, which only exercises the 2025 handshake. Pass --protocol-era modern to check 2026-07-28 behavior, then run it again without the flag to check compatibility with older clients. Both runs must list search_notes and get_note.
Call a tool with its arguments:
npx @modelcontextprotocol/inspector --cli node dist/stdio.js \
--method tools/call --tool-name search_notes \
--tool-arg query=coolify --tool-arg limit=3For a pipeline, request JSON and filter it with jq:
npx @modelcontextprotocol/inspector --cli node dist/stdio.js \
--method tools/list --format json | jq '.result.tools[].name'A tools/call that returns isError: true exits with code 5. An unreachable server exits with code 4, and a server that requires authentication exits with code 3. Those codes separate a broken connection from a tool that failed cleanly.
Move from stdio to Streamable HTTP#
stdio works for a server that the client launches on the same machine. A product used by several people needs a public URL and Streamable HTTP. The table below isolates the four differences that matter:
| Need | stdio | Streamable HTTP |
|---|---|---|
| Users | One, on the same machine | Many, remotely |
| Deployment | Local command launched by the client | Worker, VPS, or container |
| Authentication | Environment variables | OAuth 2.0 or bearer token |
| State | The process can hold memory | A fresh instance per request |
SDK v2 provides createMcpHandler, which turns a server factory into a standard HTTP handler. With Hono, createMcpHonoApp adds JSON body parsing and Host/Origin validation:
import { createMcpHonoApp } from "@modelcontextprotocol/hono";
import { createMcpHandler } from "@modelcontextprotocol/server";
import type { Context } from "hono";
import { createServer } from "./create-server.js";
const handler = createMcpHandler(createServer);
const app = createMcpHonoApp({
host: "0.0.0.0",
allowedHosts: ["mcp.example.com", "127.0.0.1", "localhost"]
});
app.all("/mcp", (c: Context) =>
handler.fetch(c.req.raw, { parsedBody: c.get("parsedBody") })
);
export default app;createMcpHandler calls the factory on every request and holds nothing between calls. A v2 server is therefore stateless and scales horizontally without sticky sessions. If you need a cart, a long-running job, or a conversation identifier, store it in your database and pass it as a tool argument. Do not keep it in a module variable: the next request may land on another instance.
On Cloudflare Workers, export default app is enough. Add Wrangler and a configuration file:
npm install hono @modelcontextprotocol/hono
npm install -D wrangler{
"name": "notes-mcp",
"main": "src/http.ts",
"compatibility_date": "2026-11-01"
}npx wrangler dev
npx wrangler deployTest the endpoint with a JSON-RPC request. The response can arrive as JSON or as an SSE event, depending on whether the handler emits a notification during the call:
curl -s -X POST http://127.0.0.1:8787/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'createMcpHonoApp validates Host and Origin headers to prevent DNS rebinding: a malicious page can resolve its own domain to 127.0.0.1 and reach a local server as if it were same-origin. In production, replace mcp.example.com with your real domain and keep localhost only for local testing. If you never want to stream events, createMcpHandler(createServer, { responseMode: "json" }) forces a single JSON response.
For a regular Node server, Hono runs with @hono/node-server. On a VPS, a Docker container works too. Our Next.js deployment tutorial with Coolify shows how a Node service sits behind a proxy and a certificate; the same mechanics apply to an MCP server.
Authenticate calls#
A public MCP server is an OAuth resource server. It does not issue tokens: it verifies tokens that an identity provider issued for it. The SDK provides requireBearerAuth for that gate. You write one function, verifyAccessToken, which takes the raw token and returns AuthInfo or throws.
import { requireBearerAuth } from "@modelcontextprotocol/server";
import type { AuthInfo } from "@modelcontextprotocol/server";
const resource = new URL("https://mcp.example.com/mcp");
async function verifyAccessToken(token: string): Promise<AuthInfo> {
const payload = await verifyJwt(token);
const audience = [payload.aud ?? []]
.flat()
.find((value) => URL.canParse(value) && new URL(value).origin === resource.origin);
return {
token,
clientId: payload.sub,
scopes: payload.scopes,
expiresAt: payload.exp,
resource: audience ? new URL(audience) : undefined
};
}
const gate = requireBearerAuth({
verifier: { verifyAccessToken },
requiredScopes: ["notes:read"],
expectedResource: resource,
resourceMetadataUrl: new URL("/.well-known/oauth-protected-resource/mcp", resource)
});Mount the gate in front of the MCP route. A missing, expired, or malformed token gets a 401 with a WWW-Authenticate challenge; a valid token without the required scope gets a 403. The client follows the challenge, discovers the OAuth metadata, and retries with a token. The resourceMetadataUrl option puts the protected resource metadata URL into the challenge; serve that document with oauthMetadataResponse on a web-standard host, or mcpAuthMetadataRouter with Express.
app.all("/mcp", async (c: Context) => {
const auth = await gate(c.req.raw);
if (auth instanceof Response) return auth;
return handler.fetch(c.req.raw, {
authInfo: auth,
parsedBody: c.get("parsedBody")
});
});Three rules prevent incidents. Never forward a token received from a client to your API without checking that it was issued for your server; that reuse, or token passthrough, is forbidden by the specification. Bind every state handle to the authenticated user, not only to the identifier supplied by the client. And keep scopes narrow: notes:read for reading, notes:write for writing, with a step-up request at the moment of the action.
On the client side, Claude supports OAuth with dynamic client registration and the callback https://claude.ai/api/mcp/auth_callback. Cursor expects https://www.cursor.com/agents/mcp/oauth/callback and http://localhost:8787/callback. On the ChatGPT side, you add a custom MCP server on the web from the plugins interface, with the URL and the authentication you choose (OAuth, none, or both); full access depends on a Business, Enterprise, or Edu plan. Claude and Cursor also accept a static bearer token in a header; for a multi-user product, keep OAuth.
Connect Claude, ChatGPT, and Cursor#
For a local server, Claude Code adds the command that launches the process. The path must be absolute:
claude mcp add notes -- node /absolute/path/to/notes-mcp/dist/stdio.js
claude mcp listClaude Desktop reads a claude_desktop_config.json file with the same shape:
{
"mcpServers": {
"notes": {
"command": "node",
"args": ["/absolute/path/to/notes-mcp/dist/stdio.js"]
}
}
}For a remote server, add it by URL. Claude Code:
claude mcp add --transport http notes https://mcp.example.com/mcpCursor reads mcp.json, either at ~/.cursor/mcp.json for a global setup or .cursor/mcp.json for a project:
{
"mcpServers": {
"notes": {
"url": "https://mcp.example.com/mcp"
}
}
}ChatGPT adds a custom MCP server from its plugin interface, on the web, with the URL and authentication. The OpenAI guide specifies the expected schemas: to make the server work in deep research and company knowledge too, expose two read-only tools, search and fetch, with a structuredContent object containing id, title, url, and the text, plus the same object serialized as JSON in content. A non-empty url makes the result citable; without a URL, ChatGPT keeps the output as ordinary tool data.
A public example of a remote server: Logoforge exposes its own at https://logoforge.terravidhal.me/mcp and connects it with claude mcp add --transport http logoforge https://logoforge.terravidhal.me/mcp. The Logoforge MCP documentation lists the commands for other editors.
Client limits change the design. Claude accepts about 150,000 characters per tool result on web and desktop, with a 240-second timeout per call. Claude Code accepts 25,000 tokens, configurable with MAX_MCP_OUTPUT_TOKENS. A tool that returns a whole repository or a whole catalog will be truncated or rejected: paginate, summarize, and return a URL for the detail.
Publish to the MCP Registry and directories#
The MCP Registry is in preview as of November 6, 2026. It hosts metadata, not your code. For an npm server, add mcpName to package.json, publish the package, then create a server.json with mcp-publisher.
{
"name": "@your-org/notes-mcp",
"version": "1.0.0",
"mcpName": "io.github.your-org/notes"
}npm publish --access public
mcp-publisher initEdit the generated server.json. For a remote server, the remotes section replaces packages:
{
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
"name": "io.github.your-org/notes",
"title": "Notes",
"description": "Search and read notes from your Notes workspace.",
"version": "1.0.0",
"remotes": [
{
"type": "streamable-http",
"url": "https://mcp.example.com/mcp"
}
]
}mcp-publisher login github
mcp-publisher publishThe remote server must be publicly reachable at the declared URL. The registry verifies that the npm package matches the metadata; the mcpName field must equal the name in server.json. For a custom domain, the registry also supports DNS authentication, which avoids the io.github prefix.
The registry does not replace client directories. Anthropic reviews connectors for the Claude directory; anyone on a paid Claude plan can submit, and a Team or Enterprise owner submits for an organization. OpenAI requires a remote MCP server for a ChatGPT plugin. Cursor lists servers in its marketplace and in cursor.directory. Publishing to the registry helps clients that search by name, but each directory remains a separate process.
Mistakes that cost a day#
- The server writes to stdout over
stdio. Aconsole.logcorrupts the JSON-RPC stream. Useconsole.erroror a logger that writes to stderr. Over HTTP, stdout is harmless. - The results are too large. A full catalog exceeds Claude's limit or floods the context. Paginate, summarize, and return a canonical URL.
- The client sees no tools. Check
tools/listwith the Inspector, then the server name and transport. An HTTP server returning404on/mcpis not mounted at the right path. - The local server is unreachable from another process.
stdiois meant to be launched by the client, not to listen on a port. For a manual test, use the Inspector or an MCP client. - The certificate or domain fails. DNS must point to the host, and ports 80 and 443 must reach the proxy. A broken
AAAArecord blocks validation even when IPv4 works. - The token is rejected. Check audience, expiry, and scopes. A
401without OAuth metadata leaves the client with no path forward: serve the protected resource document. - The schema breaks after an update. A renamed field or a reduced
enumchanges the contract. Version your tools and keep the old names during the transition. - The registry rejects the publication.
mcpNameand theserver.jsonnamemust match, and the npm package must be published before the server.
What it costs and when it pays off#
A stateless MCP server deploys well on Cloudflare Workers. The free plan includes 100,000 requests per day and 10 milliseconds of CPU per invocation. The paid plan starts at $5 per month, with 10 million requests included, $0.30 per additional million, 30 million CPU milliseconds included, and $0.02 per additional million. Cloudflare's own example — 15 million requests at 7 ms of CPU — costs $8 per month: $5 for the subscription, $1.50 for requests, and $1.50 for CPU. Prices checked in November 2026.
A VPS becomes simpler if your server must keep a long-running process, start background jobs, or talk to a database on the same network. Our Vercel vs Cloudflare vs Coolify comparison puts numbers on those options, and our developer hosting comparison covers plans with SSH and Git.
The real cost is yours: writing two good tools, testing error cases, handling authentication, and watching calls. A poorly described MCP server will not be called; a server that returns too much data costs tokens. One well-described, bounded tool beats ten generic ones.
Frequently asked questions#
Frequently asked questions
Do I need an MCP server if I already have a REST API?
Not necessarily. If one client needs one route, a direct integration can be enough. MCP becomes useful when several agents must discover the same actions, when you want schemas and annotations, or when you want to connect Claude, ChatGPT, Cursor, and VS Code without writing four connectors.
Which transport should I use: stdio or Streamable HTTP?
stdio or Streamable HTTP?stdio is the simplest choice for a local tool that reads files or a database on the user's machine. Streamable HTTP is the default for a product used by several people: one URL, OAuth, and a stateless deployment. You can serve both from the same server factory.
How do I stop an agent from taking a destructive action?
Start with read-only tools and mark them with readOnlyHint. For writes, ask for confirmation, use an idempotency key, and require a dedicated scope. A tool that deletes should be explicitly destructiveHint: true, and the client must be able to reject the call.
Why does my server not appear in Claude or ChatGPT?
First check tools/list with the Inspector, then the exact endpoint URL, transport, and authentication. An HTTP server must answer on the declared path with accepted Host and Origin headers. The client logs and the WWW-Authenticate challenge usually point to the cause.
What does an MCP server cost in production?
A Cloudflare Worker can stay free up to 100,000 requests per day; the paid plan starts at $5 per month. A small VPS adds the server cost and your time. The main cost is writing and maintaining the tools, not hosting.
Should I publish to the MCP Registry?
It is not required to connect a server in Claude, ChatGPT, or Cursor. The registry helps clients discover a server by name and install it, but it is still in preview. The Claude, ChatGPT, and Cursor directories remain separate processes.
Sources#
Official pages consulted on November 6, 2026. Prices checked in November 2026.
- Model Context Protocol — introduction
- Model Context Protocol — 2026-07-28 specification
- Model Context Protocol — 2026-07-28 release notes
- Model Context Protocol — build a server
- Model Context Protocol — security best practices
- Model Context Protocol — Inspector CLI
- MCP TypeScript SDK — GitHub repository
- MCP TypeScript SDK — server package on npm
- MCP TypeScript SDK — serve over HTTP
- MCP TypeScript SDK — serve over
stdio - MCP TypeScript SDK — serve with Hono
- MCP TypeScript SDK — legacy clients
- MCP TypeScript SDK — tools
- MCP TypeScript SDK — resources
- MCP TypeScript SDK — prompts
- MCP TypeScript SDK — authorization
- MCP Registry — publish a server
- MCP Registry — remote servers
- MCP Registry — DNS authentication
- Claude — build an MCP server
- Claude Code — connect MCP servers
- OpenAI — build MCP servers for ChatGPT
- OpenAI — connect a custom MCP server in ChatGPT
- Cursor — MCP
- VS Code — add MCP servers
- Cloudflare Workers — pricing



Comments
Loading comments…