Build Your First MCP Server: The Smallest Useful One, Step by Step
Originally published at https://meetblogging.tech/blog/build-your-first-mcp-server/ 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: Scaffold a Node project and install @modelcontextprotocol/server and zod. Register one tool with a Zod input schema and an async handler. Serve it over stdio; log to stderr, never stdout. Test the tool in the MCP Inspector before any client sees it.
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. Node.js 20 or later โ the current SDK requires it. Check with node --version.
npm, which ships with Node. A folder of Markdown drafts (or any text files) for the tool to count. Create an empty one if you have none. An MCP client for the final step โ Claude Code, Claude Desktop, Cursor or VS Code all read the same config shape.
About an hour, including the testing pass in Step 6. 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. 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: Read-only, so a bug cannot damage anything. Deterministic, so you can verify the answer yourself. Needed weekly, so the server earns its place.
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. 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.
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: Input is validated by schema, so the model cannot pass a shape you did not plan for.
The file path is constrained to one folder. basename strips directory tricks, and the startsWith check refuses anything that still escapes. This is the defensive habit from the MCP security checklist applied to your own code. Logging goes to stderr.
Stdout carries the MCP protocol over stdio; one stray console.log corrupts the JSON-RPC stream and produces the most confusing errors in this ecosystem. 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. 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.
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.
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.
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.
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. The server never appears in the client.
Almost always a relative path in args, or the config was saved in the wrong client's file. Absolute paths, then restart the client โ most clients read MCP config only at launch. The client connects, then reports garbled or closed-stream errors. Something wrote to stdout.
Search your code for console.log and move every diagnostic to console.error. The tool is listed but the agent never calls it. The description is doing too little. Say what the tool does and when to use it ("Count the words in a Markdown draft inside the drafts folder; use when asked whether a draft meets a length target"), then restart so the client reloads it.
Import errors mentioning @modelcontextprotocol/sdk. You installed (or copied code for) the v1 package. The v2 package is @modelcontextprotocol/server, registerTool replaces server.tool(), and imports come from @modelcontextprotocol/server/stdio. The Inspector will not start, or the SDK will not install.
Check node --version first: the current SDK requires Node.js 20 or later, and an older Node fails in ways that look like package problems. What language should my first MCP server use? 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?
What should my one tool be? Why test in the Inspector before connecting a client? When does a server need to be remote instead of stdio? the MCP registry guide covers what changes when you eventually publish one.
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: MCP servers actually worth installing โ the short list, for the jobs not worth building yourself Your second MCP server โ error shapes, versioning and validation done properly The MCP hub โ every MCP guide on this site, from first build to production Resources โ starter templates and configs to start from
Key Takeaways
- โขThis tutorial builds exactly that: a TypeScript MCP server exposing a single word_count tool for Markdown drafts inside one allowed folder.
- โขThis story was reported by Dev.to, covering developments in the dev space.
- โขAI advancements continue to reshape industries โ read the full article on Dev.to for complete coverage.
๐ Continue reading the full article:
Read Full Article on Dev.to โShare this article

![[Day 25/30] Content-Addressed SQLite WAL Caching for Deterministic Tool & Embedding Deduplication](https://media2.dev.to/dynamic/image/width=1200,height=627,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fnuwansaratharusha.github.io%2Fkofi-devto-autopilot%2Fart_plates%2Fday25.jpg)

