Learn › MCP: Model Context Protocol — Complete Developer Guide › Building Your First MCP Server (TypeScript)

Building Your First MCP Server (TypeScript)

Intermediate 🕐 35 min Lesson 8 of 11
What you'll learn
  • Explain why serveStdio takes a factory function rather than a server instance
  • Define MCP tool input schemas using Zod and describe how they differ from Python type hints
  • Build, test with the MCP Inspector, and connect a TypeScript server to Claude Desktop

Why TypeScript for MCP?

The Python SDK is excellent for data-heavy tools and Python-native integrations. TypeScript is the right choice when you are building tools that integrate with the Node.js ecosystem — npm packages, JavaScript APIs, web services that have TypeScript clients, or anything that runs in a browser-adjacent environment. TypeScript also provides stronger static type checking than Python type hints, catching tool schema mismatches at compile time rather than at runtime.

The two SDKs are semantically equivalent — they expose the same MCP primitives — but they differ in idiom. The most important difference is the factory pattern used by serveStdio in TypeScript, which we will cover in depth.

Prerequisites

  • Node.js 20 or higher
  • npm (included with Node.js)
  • Claude Desktop installed and running

Setting Up the Project

Create a directory and initialize a Node.js project:

mkdir weather && cd weather
npm init -y

Install the runtime dependencies:

npm install @modelcontextprotocol/server zod

Install the development dependencies:

npm install -D @types/node typescript

Edit package.json to add the module type, a build script, a bin entry, and a files list:

{
  "name": "weather",
  "version": "1.0.0",
  "type": "module",
  "bin": { "weather": "./build/index.js" },
  "scripts": { "build": "tsc && chmod +x build/index.js" },
  "files": ["build"]
}

Create tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "rootDir": "./src",
    "outDir": "./build",
    "strict": true
  }
}

Create the source directory and entry file:

mkdir src && touch src/index.ts

Your project structure:

weather/
├── package.json
├── tsconfig.json
├── node_modules/
└── src/
    └── index.ts

Writing the Server

Open src/index.ts:

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";

const NWS_API_BASE = "https://api.weather.gov";
const USER_AGENT = "weather-mcp-server/1.0";

async function makeNwsRequest(url: string): Promise | null> {
  try {
    const response = await fetch(url, {
      headers: { "User-Agent": USER_AGENT, Accept: "application/geo+json" },
      signal: AbortSignal.timeout(30_000),
    });
    if (!response.ok) return null;
    return response.json() as Promise>;
  } catch {
    return null;
  }
}

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

  server.registerTool(
    "get_alerts",
    {
      description: "Get active weather alerts for a US state.",
      inputSchema: z.object({
        state: z.string().length(2).describe("Two-letter US state code (e.g. CA, NY)"),
      }),
    },
    async ({ state }) => {
      const data = await makeNwsRequest(`${NWS_API_BASE}/alerts/active?area=${state}`);
      if (!data || !Array.isArray((data as any).features)) {
        return { content: [{ type: "text", text: `Could not retrieve alerts for ${state}.` }], isError: true };
      }
      const features = ((data as any).features as any[]).slice(0, 5);
      if (features.length === 0) {
        return { content: [{ type: "text", text: `No active alerts for ${state}.` }] };
      }
      const alerts = features.map((f: any) => {
        const p = f.properties ?? {};
        return `**${p.event ?? "Alert"}** in ${p.areaDesc ?? "unknown area"}
${p.headline ?? ""}`;
      });
      return { content: [{ type: "text", text: alerts.join("

") }] };
    }
  );

  server.registerTool(
    "get_forecast",
    {
      description: "Get the weather forecast for a location by latitude and longitude.",
      inputSchema: z.object({
        latitude: z.number().min(-90).max(90).describe("Latitude of the location"),
        longitude: z.number().min(-180).max(180).describe("Longitude of the location"),
      }),
    },
    async ({ latitude, longitude }) => {
      const points = await makeNwsRequest(`${NWS_API_BASE}/points/${latitude},${longitude}`);
      if (!points) {
        return { content: [{ type: "text", text: `Could not resolve ${latitude}, ${longitude}.` }], isError: true };
      }
      const forecastUrl = (points as any)?.properties?.forecast as string | undefined;
      if (!forecastUrl) {
        return { content: [{ type: "text", text: "No forecast URL found." }], isError: true };
      }
      const forecast = await makeNwsRequest(forecastUrl);
      if (!forecast) {
        return { content: [{ type: "text", text: "Could not retrieve forecast." }], isError: true };
      }
      const periods = ((forecast as any)?.properties?.periods as any[] ?? []).slice(0, 3);
      const result = periods.map((p: any) => `**${p.name}**: ${p.detailedForecast}`);
      return { content: [{ type: "text", text: result.join("

") }] };
    }
  );

  return server;
}

serveStdio(createServer, {
  onerror: (error) => console.error("Server error:", error),
});
console.error("Weather MCP Server running on stdio");

The Factory Pattern Explained

The most important thing to understand about the TypeScript server is that createServer is a factory function — a function that returns a new McpServer instance each time it is called. You pass the factory to serveStdio, not an already-created server instance.

Why? serveStdio calls the factory multiple times. When a client connects and sends a server/discover probe, serveStdio creates a fresh server instance to respond to it. When an actual client session starts (a 2026-era client) or an initialize handshake arrives (a 2025-era client), it creates another instance to handle that session. This factory model is what allows the same server code to serve both protocol eras simultaneously.

If you had instead written:

const server = new McpServer({ name: "weather", version: "1.0.0" });
server.connect(new StdioServerTransport()); // Do NOT do this

You would have a server that only handles one era of clients. The connection would work for the 2025-era initialize handshake, but not for the 2026-era stateless model. Using serveStdio with a factory is the correct pattern for new servers.

Zod Schemas for Tool Definitions

TypeScript uses Zod to define tool schemas instead of raw JSON Schema. Zod provides type-safe schema construction with built-in validation. The SDK converts Zod schemas to JSON Schema automatically when building the protocol response.

Zod schemas compose well with TypeScript's type system. When you use z.object({...}) as the inputSchema, TypeScript infers the argument types in the tool handler automatically. The { state }: { state: string } destructuring in the handler is typed without any manual annotation.

Useful Zod validators for MCP tool schemas:

  • z.string(), z.number(), z.boolean() — primitive types
  • z.string().length(2) — fixed-length string
  • z.number().min(-90).max(90) — bounded number
  • z.string().describe("...") — adds a description to the JSON Schema property
  • z.array(z.string()) — array of strings
  • z.enum(["a", "b", "c"]) — string literal union
  • z.optional(z.string()) — optional parameter

Returning Errors Correctly

In TypeScript, you return execution errors as a result with isError: true, not by throwing. The TypeScript SDK does not have a ToolError class — instead, you return the error as content:

return {
  content: [{ type: "text", text: "Something went wrong: reason" }],
  isError: true,
};

This is the same execution error pattern from Lesson 4, expressed in TypeScript. The model receives the message and can reason about it. Protocol-level errors (bad arguments, unknown tool) are handled by the SDK and do not require any special code from you.

Building and Testing

Compile the TypeScript:

npm run build

This produces build/index.js. Test it with the Inspector:

npx @modelcontextprotocol/inspector --cli node build/index.js --protocol-era modern --method tools/list

Then test with the legacy era to confirm both work:

npx @modelcontextprotocol/inspector --cli node build/index.js --protocol-era legacy --method tools/list

Connecting to Claude Desktop

Add the server to claude_desktop_config.json:

{
  "mcpServers": {
    "weather": {
      "command": "node",
      "args": ["/absolute/path/to/weather/build/index.js"]
    }
  }
}

Fully restart Claude Desktop and test with a weather question. Note that you need to run npm run build after any change to the TypeScript source — the running server uses the compiled JavaScript, not the source.

Python vs TypeScript: Key Differences

Feature
Python
TypeScript
Schema definition
Type hints + docstrings (automatic)
Zod schemas (explicit)
Error handling
raise ToolError("...")
return { content: [...], isError: true }
Server start
mcp.run(transport="stdio")
serveStdio(createServer, options)
Multi-era support
Built in to MCPServer
Requires factory pattern with serveStdio
Build step
None (runs directly)
tsc compile required
Key takeaways
  • The TypeScript SDK uses a factory function pattern with serveStdio to serve both 2026 and 2025 protocol eras from the same code
  • Zod schemas give TypeScript compile-time type checking for tool arguments — the SDK converts them to JSON Schema automatically
  • Execution errors in TypeScript are returned as content with isError: true, not thrown as exceptions
Learn more every week Get 5 hand-picked prompts + new AI tools every Monday. Free.