MCP Servers & Security

Build Your First MCP Server: The Smallest Useful One, Step by Step

22 November 2026 · Updated 28 November 2026 · 12 min read · by Yang Kai

Build the smallest useful MCP server in TypeScript with the current SDK: one tool, a clean skeleton, an Inspector test, and a checklist to run before you connect it to any agent.

Starter code inside: Minimal TypeScript MCP Server Skeleton (SDK v2)

Contents
  1. What you need before you start
  2. Step 1: Decide the one job
  3. Step 2: Set up the project
  4. Step 3: Write the server
  5. Step 4: Test it in the MCP Inspector
  6. Step 5: Connect it to your client
  7. Step 6: Test like you mean it
  8. Step 7: Grow it by one tool at a time
  9. Troubleshooting: five common first-build failures
  10. What to build next

You can read about the Model Context Protocol for a week and still not know the one thing that matters: what a server actually does when a model calls it. Building the smallest useful server yourself answers that in about an hour — one tool, one file, nothing that can break anything you own.

This tutorial builds exactly that: a TypeScript MCP server exposing a single word_count tool for Markdown drafts inside one allowed folder. The code follows the official TypeScript SDK documentation as checked in November 2026 — which matters, because the SDK is now on v2 and most older tutorials install a v1 package whose API no longer matches. Step 2 flags the difference so you do not walk into it.

The whole build, in five lines:

  1. Scaffold a Node project and install @modelcontextprotocol/server and zod.
  2. Register one tool with a Zod input schema and an async handler.
  3. Serve it over stdio; log to stderr, never stdout.
  4. Test the tool in the MCP Inspector before any client sees it.
  5. Add it to your client’s config with absolute paths, then run the testing checklist.

When you are ready to choose third-party servers instead of building, pair this with MCP servers actually worth installing.

What you need before you start

No API key, no account, no external service. The tool runs entirely on your machine, on purpose: a first server should be incapable of surprising you.

Step 1: Decide the one job

A first server with five tools teaches you five half-lessons. One tool teaches you the whole lifecycle: definition, input validation, error handling, logging, and client configuration. Pick a job that is:

Word counting a draft, checking a file exists, or listing posts missing frontmatter all qualify. Sending email, moving money, or deleting files do not. The rest of this tutorial uses word_count; the shape is identical whatever read-only job you pick.

Step 2: Set up the project

Create the project and install the SDK. These commands follow the official TypeScript SDK quickstart:

mkdir draft-tools && cd draft-tools
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server zod
npm install -D typescript tsx @types/node
mkdir src

Two details in that block do real work. type=module matters because the SDK ships ES modules only. And the package name matters more: @modelcontextprotocol/server is the current v2 SDK. The older @modelcontextprotocol/sdk package is v1 — still published and patched, but its server.tool() API was replaced by registerTool in v2, and code written for one does not run on the other unchanged. Most tutorials published before 2026 install v1. This one does not.

tsx runs the TypeScript directly during development, so there is no build step while you iterate. You will still compile once in Step 5, because a client config should point at a stable file.

Step 3: Write the server

Save this as src/index.ts. It is the complete server — a working skeleton, not a fragment:

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";
import { readFile } from "node:fs/promises";
import { basename, resolve } from "node:path";

const ALLOWED_DIR = resolve(process.env.DRAFTS_DIR ?? "./drafts");

function createServer(): McpServer {
  const server = new McpServer({ name: "draft-tools", version: "0.1.0" });

  server.registerTool(
    "word_count",
    {
      description: "Count the words in a Markdown draft inside the drafts folder",
      inputSchema: z.object({
        filename: z.string().describe("File name only, e.g. my-post.md"),
      }),
    },
    async ({ filename }) => {
      const safeName = basename(filename); // strips any ../ tricks
      const path = resolve(ALLOWED_DIR, safeName);
      if (!path.startsWith(ALLOWED_DIR)) {
        return {
          isError: true,
          content: [{ type: "text", text: "Outside the allowed folder" }],
        };
      }
      const text = await readFile(path, "utf8");
      const words = text.split(/\s+/).filter(Boolean).length;
      return {
        content: [{ type: "text", text: `${safeName}: ${words} words` }],
      };
    }
  );

  return server;
}

void serveStdio(createServer);
console.error("draft-tools running on stdio"); // stderr only — stdout is the protocol

How it fits together: registerTool takes a name, a config (description plus one Zod inputSchema), and an async handler. From that single schema the SDK derives the JSON Schema the model sees, validates arguments before your handler runs, and types the handler’s arguments for you. The handler returns content — a list of typed blocks, one text block here. serveStdio owns the transport: it reads requests on stdin, writes responses on stdout, and calls your factory to build the server instance.

Three details matter more than everything else combined:

The tool description is user interface for a model. Write it like you would brief a careful assistant, because that is literally what it is — vague descriptions are the top reason a working tool never gets called.

What the model actually sees

When a client connects, it asks your server for its tool list (tools/list), and the model receives each tool’s name, description and input schema — not your code. When the model decides to call word_count, the client sends a tools/call request with arguments the SDK has already validated against your Zod schema. Everything else in this tutorial follows from that split: the schema is a contract, the description is a sales pitch, and the handler is the only part that touches your files.

The factory shape is there for the same reason. serveStdio calls createServer to build the instance that serves a connection, so the same factory can later serve HTTP connections without restructuring — each connection gets its own server instance rather than sharing state by accident.

Step 4: Test it in the MCP Inspector

Before any client config enters the picture, test the server with the MCP Inspector, the official debugging UI. It launches your server, connects over stdio, and lets you call tools by hand:

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

You should see the Inspector open in your browser with word_count in its tools list. Before calling anything, read what the Inspector shows for the tool: the description and the JSON Schema it derived from your Zod object. That is exactly what a model’s client will present to the model, so if the schema looks wrong here — a missing description on filename, a field that should be required but is not — fix it in the code now rather than after a client has cached the old version.

Expected result: a text response in the form my-post.md: 842 words, and a count you can verify by opening the file yourself. Also try a file that does not exist: the Inspector should show an error result, and the server should stay alive. If both hold, the server works — anything that goes wrong after this point is client configuration, not server code. The deeper testing approach, including protocol-level checks, is in testing MCP servers.

Step 5: Connect it to your client

Compile the server once, so the client points at a stable JavaScript file:

npm pkg set scripts.build="tsc"

Add a minimal tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "build",
    "rootDir": "src",
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}

Run npm run build, then add the server to your client’s MCP configuration. Use absolute paths — clients launch servers from unpredictable working directories, and a relative path is the most common reason a working server “does not exist”:

{
  "mcpServers": {
    "draft-tools": {
      "command": "node",
      "args": ["/absolute/path/to/draft-tools/build/index.js"],
      "env": { "DRAFTS_DIR": "/absolute/path/to/drafts" }
    }
  }
}

Restart the client and ask the agent to list its tools. You should see word_count with your description. If it is missing, the troubleshooting section below is ordered by how often each cause occurs.

Step 6: Test like you mean it

Most first servers “work” in the demo and misbehave in real sessions. Run this checklist before you rely on yours:

Test Try this Expected result
Happy path Count a real draft Correct count, file name echoed
Missing file Ask for nope.md Clear error, server stays alive
Path escape Ask for ../../secret.txt Refused, nothing read
Weird input Empty string, spaces, a .png name Handled error, no crash
Big file A 500 KB Markdown file Completes without hanging
Restart Kill and reconnect the client Tool reappears, no stale state
Log check Review stderr after all tests One readable line per event, no secrets printed

The path-escape test is not paranoia. Your model will eventually generate a strange argument — not from malice, just from a messy prompt — and your server should fail closed. Note that in this skeleton the escape attempt is refused twice over: basename reduces ../../secret.txt to secret.txt inside the allowed folder (where it does not exist, so the read fails), and the prefix check would refuse a path that still landed outside.

Step 7: Grow it by one tool at a time

When word_count has survived a week of real use, add the next tool — a natural second is missing_frontmatter, which lists drafts lacking a title or description. Add one, re-run the full Step 6 checklist, bump the version in the McpServer constructor. Resist the bundle instinct: a server that does three related things for one folder is a tool; a server that does fifteen unrelated things is a liability you now maintain.

Two growth paths branch off here. Your second MCP server covers what demos skip — error shapes an agent can act on, versioning, and input validation done properly. And when you want the server to expose data and reusable prompts, not just tools, MCP server resources and prompts is the next read. At the point your server needs to run while your laptop is closed, or be shared with a collaborator, you have outgrown stdio — that step is covered in hosting MCP servers and MCP in production.

Troubleshooting: five common first-build failures

FAQ

What language should my first MCP server use? TypeScript, if you have no strong preference — the official SDK is the most documented, and most example servers you will read are written in it. Python is a close second; building an MCP server in Python follows the same smallest-useful shape in that ecosystem, where SDK v2 renamed the high-level class from FastMCP to MCPServer.

How long does a first server take? An hour or two for the one-tool skeleton in this article, including the testing pass. If it takes a weekend, the tool you chose is too big for a first build.

What should my one tool be? Something read-only, local, and useful to you weekly: listing notes, searching your own docs, checking a folder of drafts. Read-only matters — your first server should be incapable of breaking anything.

Why test in the Inspector before connecting a client? Because it separates the two failure families. If the tool works in the Inspector, the server is right and any remaining problem is client configuration. If it fails there too, you debug one small program instead of guessing which layer broke.

When does a server need to be remote instead of stdio? When it must run while your laptop is closed, serve several people, or sit next to the data it reads. Until one of those is true, stdio is simpler, safer, and easier to debug — and the MCP registry guide covers what changes when you eventually publish one.

What to build next

Build the skeleton above today, point it at a harmless drafts folder, and pass all seven tests in the checklist. You will understand MCP better after that hour than after a week of reading about it — and you will own a tool shaped exactly like your workflow, which no registry listing can offer.

Learn more:

Category: MCP Servers & Security · Tags: #mcp #typescript #tutorial #ai-agents #checklist

Next step: this article is part of MCP guides, which covers the full topic from first setup to advanced use.

Related guides