Create an MCP server in TypeScript: step-by-step guide

Tutorials By 6 min read

Learn how to create an MCP server in TypeScript, expose tools and resources with the official SDK, and test it with a compatible client.

Create an MCP server in TypeScript sounds fancy, but it’s pretty straightforward. In this tutorial I’ll spin up an MCP server with the official SDK, expose a couple of tools and a resource, and test everything with a compatible client that also runs on Node. Copy, paste, run. No prayers required.

Requirements

  • Node.js 18 or newer (I recommend the current LTS)
  • npm (bundled with Node) or pnpm/yarn if you prefer; I’ll use npm here
  • Windows, Linux, or macOS
  • Permissions to install npm packages

Step 1: scaffold the project

Initialize a clean project, enable ES modules, add TypeScript, the MCP SDK, and schema helpers.

Bash
mkdir mcp-ts-server
cd mcp-ts-server
npm init -y
npm pkg set type=module
npm i @modelcontextprotocol/sdk zod zod-to-json-schema
npm i -D typescript ts-node @types/node

Create tsconfig.json with ESM support and sane targets:

JSON
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "outDir": "dist",
    "resolveJsonModule": true
  },
  "include": ["src"]
}

Add some helpful package.json scripts:

JSON
{
  "name": "mcp-ts-server",
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "ts-node --loader ts-node/esm src/server.ts",
    "build": "tsc -p tsconfig.json",
    "start": "node dist/server.js",
    "test:client": "ts-node --loader ts-node/esm src/client.ts"
  }
}

Step 2: build a minimal MCP server

Here’s the core. I define a server, two tools, and one resource. Zod describes input, converted to JSON Schema. Transport is stdio, which many clients expect.

Create src/server.ts with the following:

TypeScript
import { Server } from "@modelcontextprotocol/sdk/server";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";

// Server identity
const server = new Server(
  { name: "mcp-ts-demo", version: "0.1.0" },
  {
    capabilities: {
      tools: {},
      resources: {}
    }
  }
);

// Tool: add two numbers
const SumInput = z.object({
  a: z.number().describe("First addend"),
  b: z.number().describe("Second addend")
});

server.tool(
  "sum",
  "Adds two numbers and returns the result as text",
  zodToJsonSchema(SumInput, "SumInput"),
  async ({ a, b }: { a: number; b: number }) => {
    const result = a + b;
    return {
      content: [
        { type: "text", text: String(result) }
      ]
    };
  }
);

// Tool: current time in ISO
server.tool(
  "time",
  "Returns current time in ISO 8601 format",
  zodToJsonSchema(z.object({}), "TimeInput"),
  async () => {
    return {
      content: [
        { type: "text", text: new Date().toISOString() }
      ]
    };
  }
);

// Resource: Node version, accessible as env:node
server.resource(
  "env:node",
  {
    name: "Node.js version",
    mimeType: "text/plain"
  },
  async () => ({
    contents: [
      { type: "text", text: process.version }
    ]
  })
);

// Start over stdio (for clients that launch the process)
const transport = new StdioServerTransport();
await server.connect(transport);

What each piece does and why:

  • Server declares identity and capabilities (tools/resources). Clients discover what they can call.
  • tool publishes an invokable function with validated input. If you change params later, clients fail fast instead of wasting your time.
  • resource exposes readable context (manuals, configs, small datasets). Great to ground the model.
  • StdioServerTransport lets a client spawn your process and talk via stdin/stdout. Portable and simple, no ports to open.

Step 3: add a simple Node test client

To avoid depending on any other app, I’ll use the SDK’s client too and spawn your server as a child process over stdio. Self-contained, CI-friendly.

Create src/client.ts with:

TypeScript
import { Client } from "@modelcontextprotocol/sdk/client";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio";

// Launch server as a child process using ts-node (dev)
const transport = new StdioClientTransport({
  command: "node",
  args: ["--loader", "ts-node/esm", "src/server.ts"],
  env: process.env
});

const client = new Client({ name: "mcp-ts-smoke", version: "0.1.0" });

await client.connect(transport);

// List tools
const tools = await client.listTools();
console.log("Tools:");
console.log(JSON.stringify(tools, null, 2));

// Call sum
const sum = await client.callTool("sum", { a: 2, b: 40 });
console.log("sum(2, 40):");
console.log(JSON.stringify(sum, null, 2));

// Call time
const time = await client.callTool("time", {});
console.log("time():");
console.log(JSON.stringify(time, null, 2));

// List resources and read env:node
const resources = await client.listResources();
console.log("Resources:");
console.log(JSON.stringify(resources, null, 2));

const nodeVersion = await client.readResource("env:node");
console.log("env:node:");
console.log(JSON.stringify(nodeVersion, null, 2));

await client.close();

Note: in production you’d build to dist and run the compiled server. The sample client uses ts-node for convenience.

Step 4: run server and client

Linux/macOS:

Bash
npm run dev

This keeps the server waiting on stdio. Open another terminal and run the client:

Bash
npm run test:client

Windows (PowerShell):

PowerShell
npm run dev

In another window:

PowerShell
npm run test:client

Verify it works

The client should list tools, execute sum/time, and read the resource. A typical output looks like this:

Texto
Tools:
{
  "tools": [
    { "name": "sum", "description": "Adds two numbers and returns the result as text" },
    { "name": "time", "description": "Returns current time in ISO 8601 format" }
  ]
}
sum(2, 40):
{
  "content": [ { "type": "text", "text": "42" } ]
}
time():
{
  "content": [ { "type": "text", "text": "2026-01-01T12:34:56.789Z" } ]
}
Resources:
{
  "resources": [ { "uri": "env:node", "name": "Node.js version", "mimeType": "text/plain" } ]
}
env:node:
{
  "contents": [ { "type": "text", "text": "v20.11.0" } ]
}

Common errors and fixes

  • Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'ts-node'
    • Install dev deps or check the ESM loader. Fix:
    Bash
    npm i -D ts-node @types/node
    npm run test:client
  • SyntaxError: Cannot use import statement outside a module
    • You’re missing "type": "module" in package.json or running under CJS. Ensure it’s set and use the ESM loader:
    Bash
    npm pkg set type=module
    npm run test:client
  • TypeError: server.tool is not a function
    • You’re on an SDK version with a different API. Check your installed version (npm ls @modelcontextprotocol/sdk) and adapt. If your SDK exposes addTool, switch to that method name.
  • spawn node ENOENT
    • Windows without Node on PATH. Add it to PATH or use the absolute path to node.exe in the client’s command field.

FAQ

How to create an MCP server in TypeScript and expose tools/resources

Use the SDK: instantiate Server, register tool and resource with schemas, and connect over StdioServerTransport. This guide gives you the boilerplate to copy.

Can I use WebSocket instead of stdio

Yes, if your client supports it and the SDK exposes a WS transport. To start, stdio is simpler: no ports, fewer surprises.

How do I version tools without breaking clients

Adding new tools is safe. Changing an existing tool’s signature can break clients. Prefer adding sum_v2 and deprecating the old one. Treat it like a public API.

How to serve large files as resources

Serve them as resources in chunks if your client supports streaming/fragmentation. Otherwise, expose a tool that returns a time-limited signed URL to your own storage.

Closing

The nice thing about MCP is it brings order to integrations: the model requests tools and context via a protocol anyone can implement. My production tip: keep tools small, idempotent, and strictly validated; otherwise, when things fail at 3 am you’ll hate future-you. PS: before going to prod, add structured logs and per-tool metrics; intuition doesn’t scale.

Related posts

More categories