Guide build/

Build an MCP server in TypeScript with the official SDK

Install @modelcontextprotocol/server, register a tool with a Zod schema, and serve the same factory over stdio or Streamable HTTP.

Published
Read
6 min
Source
Markdown

Short answer

To build an MCP server in TypeScript, install the official SDK's server package, @modelcontextprotocol/server (version 2.4.0 on npm as of December 6, 2026), plus zod and tsx. Create an McpServer, call registerTool with a name, a description and a Zod inputSchema, and pass a factory that builds the server to serveStdio for a local server or to createMcpHandler for Streamable HTTP. Test it with npx @modelcontextprotocol/inspector npx tsx src/index.ts.

Checked against: the MCP TypeScript SDK README, its first-server tutorial, HTTP guide, Express recipe and the npm registry, December 6, 2026.

Run by us: no. Commands are copied from the MCP TypeScript SDK’s docs.

Which package do I install, and which version is current?

As of December 6, 2026, the package for building an MCP server in TypeScript is @modelcontextprotocol/server 2.4.0, part of the official SDK’s v2 line.

Package Version on npm Used for
@modelcontextprotocol/server 2.4.0, published October 23, 2026 McpServer, registerTool, createMcpHandler; serveStdio at the /stdio subpath
@modelcontextprotocol/node 2.1.2 toNodeHandler, to mount the HTTP handler in Node frameworks
@modelcontextprotocol/express 2.0.2 createMcpExpressApp and requireBearerAuth
@modelcontextprotocol/sdk 1.32.2 The v1 package

The SDK’s main branch is v2, which implements the 2026-07-28 MCP specification, per the README. The README says v1 lives on the v1.x branch and gets bug fixes and security updates for at least six months after the v2 release on July 27, 2026. The v2 packages require Node.js 20 or later and ship ES modules only. The SDK also runs on Bun and Deno. Tool schemas accept any Standard Schema library; the docs use Zod v4.

How do I set up the project?

Create an ES module project and install the server package, Zod and tsx.

mkdir weather && cd weather
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server zod tsx
mkdir src

These commands are from the SDK’s first-server tutorial. type=module is required because the SDK ships only ES modules. tsx runs TypeScript directly, so the project has no build step.

How do I register a tool?

Call registerTool with a name, a config that holds a description and a Zod inputSchema, and an async handler that returns content blocks.

import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';

const NWS_API = 'https://api.weather.gov';

interface AlertsResponse {
    features: { properties: { event?: string; headline?: string } }[];
}

function createServer(): McpServer {
    const server = new McpServer({ name: 'weather', version: '1.0.0' });

    server.registerTool(
        'get-alerts',
        {
            description: 'Get the active weather alerts for a US state',
            inputSchema: z.object({
                state: z.string().length(2).describe('Two-letter US state code, e.g. CA')
            })
        },
        async ({ state }) => {
            const code = state.toUpperCase();
            const url = `${NWS_API}/alerts/active?area=${code}`;
            const res = await fetch(url, { headers: { 'User-Agent': 'mcp-weather-tutorial/1.0' } });
            if (!res.ok) {
                return { content: [{ type: 'text', text: `NWS API error: HTTP ${res.status}` }], isError: true };
            }
            const { features } = (await res.json()) as AlertsResponse;
            if (features.length === 0) {
                return { content: [{ type: 'text', text: `No active alerts for ${code}.` }] };
            }
            const lines = features.map(f => f.properties.headline ?? f.properties.event ?? 'Unnamed alert');
            return { content: [{ type: 'text', text: lines.join('\n') }] };
        }
    );

    return server;
}

This is src/index.ts from the tutorial. The Zod inputSchema is the only schema you write. The SDK derives the JSON Schema the model sees from it, validates arguments before the handler runs, and infers the handler’s argument types. The handler returns content, a list of typed blocks. Setting isError: true marks a failed result that the model can read and react to.

Bad arguments never reach the handler. Per the tutorial, a call with { "state": "California" } returns this result to the model:

Input validation error: Invalid arguments for tool get-alerts: state: Too big: expected string to have <=2 characters

How do I serve it over stdio?

Append a serveStdio call that takes the factory, then start the file with tsx.

void serveStdio(createServer);
console.error('weather MCP server running on stdio');
npx tsx src/index.ts

serveStdio owns the stdio transport: it reads requests on stdin, writes responses on stdout, and calls createServer to build the instance for the connection. The banner goes to stderr because stdout carries JSON-RPC, and one console.log corrupts that stream. After the banner, the process waits for a client to speak first. The README’s shorter greet example uses new StdioServerTransport() with server.connect(transport); the SDK’s stdio guide describes serveStdio as the replacement for that wiring.

How do I serve the same server over Streamable HTTP?

Pass a factory to createMcpHandler and mount the handler on one route; the Express recipe does this in one file.

npm install @modelcontextprotocol/server @modelcontextprotocol/express @modelcontextprotocol/node express
import { createMcpExpressApp } from '@modelcontextprotocol/express';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';

const handler = createMcpHandler(() => {
    const server = new McpServer({ name: 'notes', version: '1.0.0' });
    server.registerTool('add-note', { description: 'Append a note', inputSchema: z.object({ text: z.string() }) }, async ({ text }) => ({
        content: [{ type: 'text', text: `Saved: ${text}` }]
    }));
    return server;
});

const app = createMcpExpressApp();
const node = toNodeHandler(handler);
app.all('/mcp', (req, res) => void node(req, res, req.body));

The recipe then adds app.listen(3000); and starts the file with npx tsx server.ts. The HTTP guide says the factory runs once per request, so the handler holds nothing between requests and scales horizontally as-is. createMcpExpressApp is express() with express.json() and DNS-rebinding protection applied. On the default 127.0.0.1 bind, a request with a non-localhost Host or Origin header gets 403.

The handler itself validates no Host header, no Origin header and no token. A public Streamable HTTP deployment needs those checks in front of it, which Run a remote MCP server covers.

How do I check it works before adding it to a host?

Launch the stdio server under MCP Inspector, or POST a tools/list request to the HTTP endpoint.

npx @modelcontextprotocol/inspector npx tsx src/index.ts
curl -s -X POST http://127.0.0.1:3000/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

In the Inspector, click Connect, open Tools, select get-alerts and run it with a two-letter state code such as TX. The Express recipe documents the curl response as a single SSE message event that carries the tool list. Debug an MCP server with MCP Inspector covers the other tabs and the CLI mode.

How do I connect it to Claude Code, VS Code or Cursor?

Give the host the launch command npx tsx src/index.ts; only the place you put it changes.

claude mcp add weather -- npx tsx src/index.ts
{
  "servers": {
    "weather": {
      "type": "stdio",
      "command": "npx",
      "args": ["tsx", "src/index.ts"]
    }
  }
}

The SDK’s real-host guide runs claude mcp add from the project root; everything after -- is the launch command. Run /mcp in a Claude Code session to confirm weather is connected. The JSON goes in .vscode/mcp.json. Cursor takes the same command and args under an mcpServers key in .cursor/mcp.json. See Claude Code MCP config and VS Code MCP config for scopes and approvals.

What breaks, and how do I fix it?

Most failures match an exact error string on the SDK’s troubleshooting page.

Error Cause Fix
SyntaxError: Unexpected token ... is not valid JSON A console.log, yours or a dependency’s, wrote to stdout on a stdio server Log with console.error
TS2589: Type instantiation is excessively deep and possibly infinite Two copies of zod in the dependency tree Run npm ls zod and align on one Zod 4 version
ReferenceError: crypto is not defined The process runs on Node.js 18 or earlier Upgrade to Node.js 20 or later
Module '"@modelcontextprotocol/server"' has no exported member 'SSEServerTransport' The server-side SSE transport moved to a frozen legacy package Serve Streamable HTTP, or import from @modelcontextprotocol/server-legacy/sse

If a host shows no tools, run npx tsx src/index.ts by hand from the project root. It should print one line to stderr and wait. A crash, an early exit or extra output on stdout is the bug.

Sources

  1. MCP TypeScript SDK READMEModel Context Protocol github.com
  2. Build your first serverModel Context Protocol github.com
  3. Plug into a real hostModel Context Protocol github.com
  4. Serve over stdioModel Context Protocol github.com
  5. Serve over HTTPModel Context Protocol github.com
  6. Serve with ExpressModel Context Protocol github.com
  7. TroubleshootingModel Context Protocol github.com
  8. @modelcontextprotocol/servernpm npmjs.com

Changelog

  • First published.

Cite this page

Agents for Devs. "Build an MCP server in TypeScript with the official SDK." Published Dec 6, 2026. https://agentsfordevs.com/guides/build-mcp-server-typescript
Cite one section