---
title: Build an MCP server in TypeScript with the official SDK
type: guide
url: https://agentsfordevs.com/guides/build-mcp-server-typescript
markdown: https://agentsfordevs.com/guides/build-mcp-server-typescript.md
publisher: Agents for Devs
author: Agents for Devs desk
reviewed_by: Agents for Devs desk
published: 2026-12-06
updated: 2026-12-06
license: https://agentsfordevs.com/reuse
citation: 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
attribution: Credit Agents for Devs and link to https://agentsfordevs.com/guides/build-mcp-server-typescript
format: Guide
topics:
  - build
description: "Build an MCP server with the official TypeScript SDK v2: install @modelcontextprotocol/server, register a Zod-typed tool, serve it over stdio or HTTP."
---

# 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.

## 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](https://github.com/modelcontextprotocol/typescript-sdk), its [first-server tutorial](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/get-started/first-server.md), [HTTP guide](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/serving/http.md), [Express recipe](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/serving/express.md) and the [npm registry](https://www.npmjs.com/package/@modelcontextprotocol/server), 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](/glossary/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](https://github.com/modelcontextprotocol/typescript-sdk). 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`.

```sh
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](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/get-started/first-server.md). `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.

```ts
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:

```text
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`.

```ts
void serveStdio(createServer);
console.error('weather MCP server running on stdio');
```

```sh
npx tsx src/index.ts
```

`serveStdio` owns the [stdio transport](/glossary/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](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/serving/stdio.md) 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.

```sh
npm install @modelcontextprotocol/server @modelcontextprotocol/express @modelcontextprotocol/node express
```

```ts
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](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/serving/http.md) 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](/glossary/streamable-http) deployment needs those checks in front of it, which [Run a remote MCP server](/guides/deploy-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.

```sh
npx @modelcontextprotocol/inspector npx tsx src/index.ts
```

```sh
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](/guides/debug-mcp-server-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.

```sh
claude mcp add weather -- npx tsx src/index.ts
```

```json
{
  "servers": {
    "weather": {
      "type": "stdio",
      "command": "npx",
      "args": ["tsx", "src/index.ts"]
    }
  }
}
```

The SDK's [real-host guide](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/get-started/real-host.md) 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](/guides/claude-code-mcp) and [VS Code MCP config](/guides/vscode-mcp) 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](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/troubleshooting.md).

| 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.

## What to read next

- [Build an MCP server in Python with the official SDK](/guides/build-mcp-server-python)
- [Debug an MCP server with MCP Inspector](/guides/debug-mcp-server-inspector)
- [Run a remote MCP server: Streamable HTTP, sessions and auth](/guides/deploy-remote-mcp-server)
- [MCP transport](/glossary/mcp-transport)

## Sources

1. [MCP TypeScript SDK README, Model Context Protocol](https://github.com/modelcontextprotocol/typescript-sdk)
2. [Build your first server, Model Context Protocol](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/get-started/first-server.md)
3. [Plug into a real host, Model Context Protocol](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/get-started/real-host.md)
4. [Serve over stdio, Model Context Protocol](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/serving/stdio.md)
5. [Serve over HTTP, Model Context Protocol](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/serving/http.md)
6. [Serve with Express, Model Context Protocol](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/serving/express.md)
7. [Troubleshooting, Model Context Protocol](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/troubleshooting.md)
8. [@modelcontextprotocol/server, npm](https://www.npmjs.com/package/@modelcontextprotocol/server)

## Changelog

- 2026-12-06: 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

- Page: https://agentsfordevs.com/guides/build-mcp-server-typescript
- Markdown: https://agentsfordevs.com/guides/build-mcp-server-typescript.md
- Reuse: quote or summarize with a link to the page. Terms: https://agentsfordevs.com/reuse
