An MCP server describes your API as typed tools that any MCP host, such as Claude Code, Cursor or VS Code, can discover and call. As of November 2026, you write it with the v2 SDK (@modelcontextprotocol/server plus Zod 4), run it over stdio for local hosts, and check it in MCP Inspector. Once other people need to connect, you move to stateless Streamable HTTP with createMcpHandler.
Search "build MCP server TypeScript" and most results still show v1: @modelcontextprotocol/sdk and server.tool(). That package is now the maintenance line and won't get the 2026-07-28 spec. That's why the examples you've found disagree.
The running example is a small orders API with two endpoints: one searches orders, the other returns an order's status.
Which SDK package to install
Install @modelcontextprotocol/server. It's the v2 server package, published from the official TypeScript SDK repo's main branch alongside @modelcontextprotocol/client, and it implements the 2026-07-28 spec. v2 has been stable since its July 27 release in late July 2026, and the latest version is v2.4.0, from Oct 23. It needs Node 20+ and depends only on Zod 4 and the SDK's core package, so the install stays small. Bun and Deno work too. You won't touch @modelcontextprotocol/node or the Express, Fastify and Hono adapters until you add HTTP.
The v1 package, @modelcontextprotocol/sdk, sits at 1.32.2 on npm and covers the spec up to 2025-11-25. It will keep receiving security patches and bug fixes for no less than six months following v2's release, which runs to roughly late January 2027. It required Node 18+ and pulled in Express, Hono, ajv, jose and more. Imports and APIs differ between the two lines. If a tutorial imports from @modelcontextprotocol/sdk or calls server.tool(), it's v1 code, and it doesn't belong in a v2 project. FastMCP cuts boilerplate but hadn't migrated to v2, so stick with the official SDK for now.
Wrap one endpoint as a tool
You need Node 20+, TypeScript, and an API you can hit with a test key. The examples use a fictional orders API at https://api.example.com. Swap in your own base URL and fields.
mkdir orders-mcp && cd orders-mcpnpm init -ynpm pkg set type=modulenpm install @modelcontextprotocol/server zodnpm install -D typescript @types/nodenpx tsc --init --module nodenext --target es2022 --rootDir src --outDir buildSetting type: module keeps you on ESM. Release 2.2.0 fixed type-checking for CommonJS projects, but ESM is still the path of least resistance.
// src/index.tsimport { McpServer, StdioServerTransport } from '@modelcontextprotocol/server';import * as z from 'zod';
const API_BASE = 'https://api.example.com/v1';const API_KEY = process.env.ORDERS_API_KEY;
if (!API_KEY) { console.error('ORDERS_API_KEY is not set'); process.exit(1);}
const server = new McpServer({ name: 'orders', version: '0.1.0' });
server.registerTool( 'search_orders', { title: 'Search orders', description: 'Find orders by customer email or status. Use this when the user asks about ' + 'recent orders or needs an order ID. Returns up to `limit` orders, newest first.', inputSchema: z.object({ customerEmail: z.string().email().optional().describe('Exact customer email address'), status: z .enum(['pending', 'paid', 'shipped', 'refunded']) .optional() .describe('Filter by order status'), limit: z.number().int().min(1).max(20).default(10).describe('Max results, 1-20'), }), }, async ({ customerEmail, status, limit }) => { const params = new URLSearchParams({ limit: String(limit) }); if (customerEmail) params.set('customer_email', customerEmail); if (status) params.set('status', status);
const res = await fetch(`${API_BASE}/orders?${params}`, { headers: { Authorization: `Bearer ${API_KEY}` }, }); if (!res.ok) throw new Error(`Orders API returned ${res.status}`);
const { data } = await res.json(); const orders = data.map((o: any) => ({ id: o.id, status: o.status, total: `${o.total_cents / 100} ${o.currency}`, createdAt: o.created_at, }));
return { content: [{ type: 'text', text: JSON.stringify(orders) }] }; });
await server.connect(new StdioServerTransport());Build with npx tsc, which writes build/index.js.
McpServer holds the name and version that hosts display. When the host's model picks a tool and fills in arguments, it reads the tool description and the .describe() text on each parameter, so write those for the model. The handler trims each API record to four fields, which keeps the result readable and saves context. The thrown error is a placeholder; proper error handling comes later. The key comes from process.env so the host config can supply it.
StdioServerTransport uses stdout as the protocol channel. One stray console.log writes text into that stream and corrupts the JSON-RPC messages. Usually you'll see it as the host failing to connect or dropping the server. Log to console.error, as the startup check does.
This code targets @modelcontextprotocol/server 2.4.0. If a signature doesn't match on your version, trust the v2 SDK documentation over any tutorial, this one included.
Test it with MCP Inspector
MCP Inspector lets you call search_orders yourself before any AI host gets involved, which separates server bugs from host-config bugs.
-
Launch Inspector against the built file, passing the test key with
-e(use your env var name and build path):bashnpx @modelcontextprotocol/inspector -e ORDERS_API_KEY=your_test_key node build/index.jsSuccess is a browser UI that connects without errors. If it fails during discovery, check Inspector's version before your code. Its support for the 2026-07-28 spec may trail the SDK, and an older build can't talk to a v2 server.
-
Open the Tools tab and list tools.
search_ordersshould appear with the description you wrote and its parameters, types included. -
Call it with input that matches a known test order. The response should contain only your trimmed fields, not the raw API payload.
-
Call it again with bad input, such as a wrong type or a missing required field. Zod should reject it with a validation error, and your API should never receive the request.
Connect Claude, Cursor or VS Code
Every one of these hosts starts a stdio server the same way: it reads a config entry with a command, its args and an env block, then spawns the process itself. Your API key goes in that env block. Hard-code it in source and it ends up in git.
{ "mcpServers": { "orders": { "command": "/usr/local/bin/node", "args": ["/Users/you/orders-mcp/build/index.js"], "env": { "ORDERS_API_KEY": "replace-with-a-test-key" } } }}Use absolute paths for both Node and the built file. The host doesn't launch from your project directory, and a relative path is the most common reason a server silently never starts. which node gives you the first path; with a version manager, point at the binary it installed.
Claude Desktop, Claude Code, Cursor and VS Code all accept this command/args/env shape. Each keeps the config in a different file, though, and the top-level key isn't always mcpServers, so check your host's docs for both. Fully restart the host after every config change. If the server starts but no tools appear, update the host. Like Inspector, it can lag the SDK on 2026-07-28 support.
Design tools around tasks, not endpoints
The model picks a tool by reading every tool definition you expose, so your tool list matters more than your route table. Mirror 40 REST routes as 40 tools and you fill the context window with near-duplicates like get_order, list_order_items and get_order_shipments, and the model has to guess between them. Expose a few intent-level tools instead, such as search_orders and get_order_status, and let each one call whatever endpoints it needs internally. Generating tools from an OpenAPI spec is fast, but it reproduces the one-tool-per-endpoint problem, so cut the output down hard before you ship it.
Descriptions are the prompt. The name, the description and each parameter's description are all the model sees when it decides. "Gets orders" tells it nothing. Compare: "Find orders by customer email, status or date range. Use this when the user doesn't have an order ID. Dates are YYYY-MM-DD. Returns up to 20 orders with ID, status, total in cents and created date." That says when to use the tool, what format it expects and what comes back. Do the same for parameters, and spell out units, such as an integer amount in cents.
Results cost context too. A raw order object full of addresses, audit fields and line-item metadata might hold six fields the model needs, so map the response down to those. Add a limit and a cursor, and say in the result when more pages exist. Hosts may truncate large responses, and a cut-off JSON blob is worse than a short, complete one.
Keep read tools and write tools apart. cancel_order should be its own tool rather than a mode flag on update_order, so a host or user can let lookups run freely and still stop to confirm anything that changes data.
Return errors the model can act on
Expected failures like a missing order, a slow API or a rate limit should come back as tool results with isError: true. A thrown error leaves the model with nothing to act on.
// Same file as before: reuses server, z, API_BASE and API_KEY.const fail = (text: string) => ({ content: [{ type: "text" as const, text }], isError: true,});
server.registerTool( "get_order_status", { title: "Get order status", description: "Use when you have an exact order ID (ord_...). Returns status, carrier and last update. " + "If you only have a customer email or date, call search_orders first.", inputSchema: z.object({ orderId: z.string().regex(/^ord_[A-Za-z0-9]+$/).describe("Order ID, e.g. ord_8F2K"), }), }, async ({ orderId }) => { let res: Response; try { res = await fetch(`${API_BASE}/orders/${encodeURIComponent(orderId)}`, { headers: { Authorization: `Bearer ${API_KEY}` }, signal: AbortSignal.timeout(8_000), }); } catch (err) { if ((err as Error).name === "TimeoutError") { return fail("The orders API didn't answer within 8 seconds. Retry once, then tell the user it's slow."); } throw err; // Bad base URL or a bug in this server: let it surface. }
if (res.status === 404) { return fail(`Order ${orderId} not found. Check the ID, or call search_orders to find it.`); } if (res.status === 429) { const wait = res.headers.get("retry-after") ?? "30"; return fail( `Rate limited. Wait ${wait} seconds before retrying. Don't loop over many orders; ` + "use one search_orders call with a narrower filter instead.", ); } if (!res.ok) { return fail(`The orders API returned ${res.status}. Don't keep retrying; report the failure to the user.`); }
const o = await res.json(); return { content: [{ type: "text", text: JSON.stringify({ id: o.id, status: o.status, carrier: o.carrier, updatedAt: o.updated_at }) }], }; },);The model treats that text as its next instruction. "Error 404" invites a blind retry or a guessed answer, while naming the tool to call, or how long to wait, gives it a path to follow.
Lock it down before sharing
Every argument your tools receive comes from a model that may have just read a support ticket, email or web page an attacker wrote. Handle tool inputs the way you'd handle any untrusted request.
- Validate beyond the Zod shape. A schema that says
orderId: stringalso accepts../adminor a 5,000-character payload. Check IDs against your real format, caplimitat the 20 your API expects, and reject dates outside a sane window. - Use a read-only, least-privilege key wherever your API supports scopes. If injected text talks the model into a bad call, the key's permissions set the limit on the damage. The usual API security checklist items apply here too.
- Put destructive actions in their own tools. Give
cancel_orderorrefund_ordera name and description that say exactly what changes and that it can't be undone. The host's confirmation prompt only protects anyone if the user can tell what they're approving. - Keep secrets out of code. Read the key from
process.envand set it in the host config'senvblock. That keeps it out of your repo and lets each user supply their own key. - Check Host and Origin headers on any local HTTP server. Without those checks, DNS rebinding lets a malicious page open in the user's browser reach your server on localhost. The Express, Fastify and Hono middleware helpers include Host header validation. Confirm that Origin is checked too.
Move to Streamable HTTP when you share it
A stdio server is a local process serving one user, and the key in its env block belongs to that user. Once the server runs remotely for a team or for customers, you can't hand every caller the same key, so Streamable HTTP needs real per-user auth, which means OAuth. The 2026-07-28 spec also changes how clients register: Client ID Metadata Documents replace Dynamic Client Registration. Instead of registering with your authorization server at runtime, a client identifies itself with a metadata document at a URL it controls.
The bigger deployment change is that the spec removed protocol sessions and the Mcp-Session-Id header. Each request stands alone, so any instance can answer it. You can run the server on serverless functions or put several instances behind a load balancer without sticky sessions, and where serverless pricing stops paying off becomes the main hosting question.
In v1 you wrote the session plumbing yourself: tracking transports by session ID, routing follow-up requests to the right one, cleaning up afterward. v2's createMcpHandler absorbs all of it. Mount it with the Express or Hono adapter to get the Host header validation mentioned above, and copy the mounting code from the v2 SDK documentation for the version you installed.
If you already run a v1 server
Your v1 server keeps working through its support window, but it will never get 2026-07-28 support, so migration is a question of timing. The 2026-07-28 spec changelog lists what changes underneath you. The initialize handshake is gone: every request carries the protocol version and capabilities in _meta, and servers must implement server/discover. subscriptions/listen replaces the GET stream. Roots, Sampling, Logging and HTTP+SSE are deprecated. Read each item in the changelog itself, especially if your server depends on a deprecated feature.
Tooling handles much of the rewrite. The @modelcontextprotocol/codemod package converts v1 code to v2, and server-legacy keeps things compatible during the transition. Both ship as part of the v2 releases. The official migration guide covers whatever the codemod leaves behind. Some hosts and frameworks haven't moved to v2 yet, so test against the hosts you actually target before you cut over.
Frequently Asked Questions
Can I run an MCP server built with the v2 SDK on Bun or Deno?
Yes. Bun runs TypeScript directly, so you can skip the build step: set your host config's command to the bun binary and pass your .ts entry file as the argument. With Deno, put the permission flags your server needs, usually network and env access, in the args array. Leave them out and the server fails as soon as it calls your API or reads the key.
Should I use FastMCP instead of the official TypeScript SDK?
Not for a new server right now. FastMCP is built on the v1 line, so along with the convenience you'd inherit v1's spec ceiling and support window. v2 also needs less boilerplate than v1 did, now that createMcpHandler handles the session plumbing, so the official SDK doesn't cost you much extra code. If you already have a working FastMCP server, keep running it and check back once FastMCP ships v2 support.
Sources
- GitHub - ehtick/ModelContextProtocol-typescript-sdk: The official Typescript SDK for Model Context Protocol servers and clients · GitHub · github.com
- GitHub - modelcontextprotocol/typescript-sdk: The official TypeScript SDK for Model Context Protocol servers and clients · GitHub · github.com
- Releases · modelcontextprotocol/typescript-sdk · GitHub · github.com
- MCP TypeScript SDK · ts.sdk.modelcontextprotocol.io
Want more from ScriptHill in Google? Add us as a preferred source



