Tutorial
Build an MCP server in TypeScript
Build a small MCP server with the official TypeScript SDK v2, test it from the command line and in MCP Inspector, then connect it to Claude Code or Cursor.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
An MCP server is a program that exposes tools, and optionally resources and prompts, over the Model Context Protocol, so any MCP host can use them without a custom integration. Building one in TypeScript takes the official SDK, a few tool definitions with input schemas, and a transport: stdio for local use or Streamable HTTP for remote.
This tutorial builds a small MCP server with the official TypeScript SDK. The server gives any MCP host, such as Claude Code or Cursor, two read-only tools for searching and reading a folder of Markdown notes. You will test it from the command line and in MCP Inspector before connecting it to an agent, which is the order that saves the most debugging time.
1. Set up the project
mkdir notes-server && cd notes-server
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server zod
npm install -D typescript tsx @types/node
mkdir notes
printf "# Deploy checklist\nRun migrations before the release. Rollback with git revert.\n" > notes/deploy.md
printf "# Onboarding\nNew starters get laptop access on day one.\n" > notes/onboarding.md
Add a tsconfig.json so the type checker knows you are targeting Node:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"types": ["node"]
}
}
The types entry matters: recent TypeScript versions no longer include @types/* packages automatically, and the SDK’s type definitions refer to Node’s Buffer.
2. Write the server
Create server.ts:
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";
const NOTES_DIR = path.resolve(process.env.NOTES_DIR ?? "notes");
async function noteNames(): Promise<string[]> {
return (await readdir(NOTES_DIR)).filter((f) => f.endsWith(".md")).sort();
}
function safePath(name: string): string {
const full = path.resolve(NOTES_DIR, name);
if (path.dirname(full) !== NOTES_DIR || !full.endsWith(".md")) {
throw new Error(`${name} is not a note in ${NOTES_DIR}`);
}
return full;
}
function createServer(): McpServer {
const server = new McpServer({ name: "notes", version: "0.1.0" });
server.registerTool(
"search_notes",
{
title: "Search notes",
description: "Find Markdown notes whose text contains a word or phrase. Returns matching file names.",
inputSchema: z.object({
query: z.string().min(2).describe("Word or phrase to look for, case-insensitive"),
}),
annotations: { readOnlyHint: true },
},
async ({ query }) => {
const q = query.toLowerCase();
const hits: string[] = [];
for (const name of await noteNames()) {
const text = await readFile(path.join(NOTES_DIR, name), "utf8");
if (text.toLowerCase().includes(q)) hits.push(name);
}
return { content: [{ type: "text", text: hits.length ? hits.join("\n") : "No notes match." }] };
},
);
server.registerTool(
"read_note",
{
title: "Read a note",
description: "Return the full Markdown text of one note, by file name (for example deploy.md).",
inputSchema: z.object({ name: z.string().describe("File name of the note") }),
annotations: { readOnlyHint: true },
},
async ({ name }) => {
try {
return { content: [{ type: "text", text: await readFile(safePath(name), "utf8") }] };
} catch (err) {
return { content: [{ type: "text", text: `Could not read ${name}: ${(err as Error).message}` }], isError: true };
}
},
);
return server;
}
serveStdio(createServer);
console.error(`notes MCP server ready, serving ${NOTES_DIR}`);
Check that it type-checks:
npx tsc
How the pieces fit
McpServer holds the server’s name, version and registered capabilities.
registerTool(name, config, handler) adds a tool. The config carries a human-readable title, the description the model reads, the inputSchema as a Zod object, and optional annotations. The SDK converts the Zod schema to JSON Schema for clients and validates incoming arguments against it, so inside the handler query is already a checked string of at least two characters.
The handler returns a result with a content array. Text content is the common case; tools can also return images, embedded resources or structuredContent that matches an outputSchema.
isError: true marks a failed tool call as a result rather than a protocol error. The model sees the message and can recover, for example by searching for the right file name. Reserve thrown exceptions for genuinely broken states.
serveStdio(createServer) serves the stdio transport. It takes a factory function rather than a server instance, so the SDK can create the instance that serves each connection. The same factory also serves clients that still speak the 2025-era protocol, so older hosts keep working.
console.error is deliberate. On stdio, stdout carries JSON-RPC messages and any stray console.log breaks the connection. Logs go to stderr.
3. Call it from the command line
MCP Inspector has a CLI mode that starts your server, makes one request and prints the response. It is ideal for quick checks and for scripts:
npx @modelcontextprotocol/inspector --cli npx tsx server.ts --method tools/list
npx @modelcontextprotocol/inspector --cli npx tsx server.ts \
--method tools/call --tool-name search_notes --tool-arg query=rollback
The second command should print a result whose text is deploy.md. Try --tool-name read_note --tool-arg name=../package.json too and confirm you get the “Could not read” message with isError set.
4. Explore it in the Inspector UI
Run Inspector without --cli to get the web interface:
npx @modelcontextprotocol/inspector npx tsx server.ts
Open the URL it prints. In the Tools tab, list the tools, read their schemas and call them with different inputs. Look at the descriptions with fresh eyes: they are the only thing the model knows about your tools. If you would not know when to call a tool from its description alone, the model will not either.
5. Connect it to Claude Code
Register the server, using absolute paths because the host starts it from its own working directory:
claude mcp add notes \
-e NOTES_DIR=/absolute/path/to/notes-server/notes \
-- npx tsx /absolute/path/to/notes-server/server.ts
Start claude, run /mcp to check the server shows as connected, and ask a question your notes can answer. Approve the tool calls when asked.
For other hosts, the configuration has the same three parts. In Cursor, for example, add an entry to .cursor/mcp.json in your project:
{
"mcpServers": {
"notes": {
"command": "npx",
"args": ["tsx", "/absolute/path/to/notes-server/server.ts"],
"env": { "NOTES_DIR": "/absolute/path/to/notes-server/notes" }
}
}
}
For production use, compile to JavaScript (set outDir and remove noEmit in tsconfig.json) and run the output with node, so the host does not need tsx and starts the server faster.
6. Going remote
To serve over Streamable HTTP, the SDK has adapter packages for Express, Fastify, Hono and plain Node (@modelcontextprotocol/express and friends). The server code you wrote stays the same; only the serving part changes. Before you put an MCP server on a network, add authorisation. Remote MCP servers are expected to use OAuth, and the SDK’s serving guide covers how to wire it up.
Pitfalls
Copying v1 examples. Imports from @modelcontextprotocol/sdk/server/mcp.js and new StdioServerTransport() plus server.connect() are the v1 pattern. They still exist, but new code should use the v2 packages and serveStdio.
Raw shapes instead of Zod objects. v1 accepted inputSchema: { query: z.string() }. v2 expects z.object({ ... }); the raw-shape form is deprecated.
Logging to stdout. The most common reason a server “connects then immediately disconnects”. Use console.error.
Throwing for expected failures. A missing file is something the model can handle if you tell it. Return isError: true with a clear message.
One tool per API endpoint. Design tools around tasks the model will be asked to do, not around your REST routes. Fewer, better-described tools work better.
Next steps
- Compare with the Python and FastMCP version of the same server.
- Use the steps on a real system in Build an MCP server for an internal API.
- Review MCP explained for the security section before you share a server.
- Read what changed in MCP 2026-07-28 to see why the v2 SDK serves requests without sessions.
- Moving an older server off HTTP+SSE? Follow Migrate an MCP server from HTTP+SSE to Streamable HTTP.
- Add your server to other hosts with add an MCP server to Claude Code, Codex and Cursor.
- Before you expose it remotely, secure a remote MCP server with OAuth.
- Give a tool an interactive interface in the chat with Build an MCP App.
Covers
Check your understanding
Build an MCP server in TypeScript quiz
The v2 TypeScript SDK: registerTool, isError results, serveStdio, Inspector checks and avoiding v1 patterns.
7 questions · pass mark 70%
Review
Related
- MCP explained: hosts, clients, servers and transports
What MCP is and how the Model Context Protocol connects AI apps to tools and data: hosts, clients, servers, transports and what the 2026-07-28 spec changed.
- Build an MCP server in Python with FastMCP
Build a small MCP server in Python with FastMCP, test its tools in MCP Inspector without a model, then connect it to Claude Code, Cursor or another MCP host.
- Build an MCP server for an internal API
Two read-only tools, tested in MCP Inspector and called from Claude Code, Codex or Cursor.
- MCP server
A program that exposes tools, resources or prompts to MCP clients, running locally over stdio or remotely over HTTP, so any MCP host can use them.
- What changed in MCP 2026-07-28: a stateless protocol
The July 2026 MCP specification removes the handshake and sessions, adds server discovery and deprecates roots and sampling. What it means for you.