By Shakil Ahmed, Android developer & software engineer
Build Your First MCP Server in TypeScript (Step by Step)
Step-by-step: build a notes MCP server in TypeScript with the v2 SDK, test it in the MCP Inspector, connect Claude, then serve it over HTTP with a bearer token.
The best way to understand MCP is to build an MCP server yourself. In this step-by-step guide, you will build an MCP server in TypeScript with two tools and one resource, test it, connect it to Claude, and then turn it into a secure remote endpoint.
I run my own MCP server for this portfolio site, and my AI assistant uses it to manage blog posts. The example here is smaller, a simple notes server, but the patterns are the same ones I use in production.
If you are new to MCP, read What Is MCP (Model Context Protocol)? A Simple Guide for Developers first. It explains hosts, clients, servers, tools and resources.
Before You Start: Which TypeScript SDK Version?
This matters, because many tutorials online are now out of date.
As of November 2026, the official TypeScript SDK is at v2. Version 2 was released in July 2026 and implements the current MCP spec, 2026-07-28. It is split into separate packages:
| Package | Use it for |
|---|---|
@modelcontextprotocol/server | Building servers (this guide) |
@modelcontextprotocol/client | Building clients |
@modelcontextprotocol/express | Mounting a server in Express, plus bearer auth |
@modelcontextprotocol/node | Adapting the handler to Node's req/res |
The old single package, @modelcontextprotocol/sdk (v1.x), still gets bug fixes and security updates for a while, but new projects should use v2. If you see code with new StdioServerTransport() and server.connect(transport), that is the v1 style. In v2 you use serveStdio() for local servers and createMcpHandler() for HTTP. The SDK repository has a migration guide and a codemod.
Tip: You need Node.js 20 or later. Check with
node --version.
Step 1: Set Up the Project
Create a folder and install the packages:
mkdir notes-mcp && cd notes-mcp
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server zod
npm install -D typescript tsx @types/node
mkdir src
Let's understand it:
type=moduleis required. The SDK ships ES modules only.zodis used to describe and validate tool inputs.tsxruns TypeScript directly during development.typescriptbuilds the final JavaScript.
Now add scripts to package.json:
{
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"start": "node build/index.js"
}
}
And create tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "build",
"rootDir": "src",
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}
NodeNext makes TypeScript understand the SDK's package exports, like @modelcontextprotocol/server/stdio. It also means local imports need a .js extension, as you will see below.
Step 2: Write the Server with Two Tools and One Resource
We will put the server logic in its own file, src/server.ts. Later, both the local (stdio) and remote (HTTP) versions will reuse it.
// src/server.ts
import { randomUUID } from 'node:crypto';
import { McpServer } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';
interface Note {
id: string;
title: string;
body: string;
createdAt: string;
}
// In-memory store. Real servers should use a database.
const notes: Note[] = [];
const MAX_NOTES = 500;
export function createServer(): McpServer {
const server = new McpServer({ name: 'notes', version: '1.0.0' });
// Tool 1: add a note
server.registerTool(
'add_note',
{
title: 'Add a note',
description: 'Save a short text note. Returns the id of the new note.',
inputSchema: z.object({
title: z.string().min(1).max(100).describe('Short title, 1-100 characters'),
body: z.string().max(5000).describe('Note text, up to 5000 characters')
}),
annotations: { readOnlyHint: false, destructiveHint: false }
},
async ({ title, body }) => {
if (notes.length >= MAX_NOTES) {
return {
content: [{ type: 'text', text: `The notes store is full (${MAX_NOTES} notes). No note was saved.` }],
isError: true
};
}
const note: Note = { id: randomUUID(), title, body, createdAt: new Date().toISOString() };
notes.push(note);
console.error(`[notes] added ${note.id}`);
return { content: [{ type: 'text', text: `Saved note "${title}" with id ${note.id}` }] };
}
);
// Tool 2: list notes
server.registerTool(
'list_notes',
{
title: 'List notes',
description: 'List saved notes, newest first. Optionally filter by text in the title.',
inputSchema: z.object({
query: z.string().optional().describe('Only return notes whose title contains this text'),
limit: z.number().int().min(1).max(50).optional().describe('Maximum notes to return, default 10')
}),
annotations: { readOnlyHint: true }
},
async ({ query, limit }) => {
const q = query?.toLowerCase();
const found = [...notes]
.reverse()
.filter(note => !q || note.title.toLowerCase().includes(q))
.slice(0, limit ?? 10);
if (found.length === 0) {
return { content: [{ type: 'text', text: 'No notes found.' }] };
}
const lines = found.map(note => `- ${note.title} (id: ${note.id}, ${note.createdAt})`);
return { content: [{ type: 'text', text: lines.join('\n') }] };
}
);
// Resource: all notes as JSON
server.registerResource(
'all-notes',
'notes://all',
{
title: 'All notes',
description: 'Every saved note as a JSON array',
mimeType: 'application/json'
},
async uri => ({
contents: [{ uri: uri.href, mimeType: 'application/json', text: JSON.stringify(notes, null, 2) }]
})
);
return server;
}
Let's understand it:
registerTool(name, config, handler)registers a tool. TheinputSchemais a Zod object. From this one schema, the SDK creates the JSON Schema the model sees, validates every call, and gives your handler typed arguments..describe()text goes into the JSON Schema. It is the only help the model gets for each argument, so write it clearly.annotationsare hints for the host. A host may auto-approve a read-only tool and ask the user before other tools. They are hints only, not security.- The handler returns
content, a list of blocks. Here we use onetextblock. isError: truemeans "the tool ran but failed". The model reads the message and can react.registerResource(name, uri, metadata, readCallback)exposes read-only data at a fixed URI. The host decides when to read it.console.errorwrites to stderr. This is on purpose (more on that soon).
Tip: Name tools with simple verbs like
add_noteandlist_notes. The spec recommends only letters, digits,_,-and.in tool names.
Step 3: Run It Locally over stdio
Now create the entry point for local use, src/index.ts:
// src/index.ts
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { createServer } from './server.js';
void serveStdio(createServer);
console.error('notes MCP server running on stdio');
Let's understand it:
serveStdioreads JSON-RPC requests from stdin and writes responses to stdout. It calls yourcreateServerfactory to build the server.- The import says
./server.js, not./server.ts. WithNodeNext, you write the extension of the compiled file.
Run it:
npm run dev
You should see only notes MCP server running on stdio. Then nothing happens. That is correct: a stdio server waits for a client to talk to it. Press Ctrl+C to stop.
Warning: In a stdio server, stdout is the protocol channel. One
console.log("debug")puts a non-JSON line into the stream, and the host drops the connection. Always useconsole.error(stderr) for logs. This is the most common beginner bug.
Step 4: Test with the MCP Inspector
The MCP Inspector is an official web tool to call your server's tools by hand, without any AI. It launches your command and connects over stdio:
npx @modelcontextprotocol/inspector npx tsx src/index.ts
In the browser tab that opens:
- Click Connect.
- Open the Tools tab. You should see
add_noteandlist_notes. - Run
add_notewith a title and body. You get back a success message with an id. - Run
list_notes. Your note is there. - Open the Resources tab and read
notes://all.
Now try to break it. Call add_note with an empty title. The SDK rejects the input before your handler runs and returns an isError: true result with a message like "Input validation error". This is exactly what the model would see, so it can fix its input and try again.
Tip: Always test with the Inspector before you connect a real AI app. If a tool fails in the Inspector, it will fail in Claude too, but with less helpful error messages. I explain this habit in Debug an MCP Connection with One Read-Only Tool.
Step 5: Connect Your Server to Claude Desktop and Claude Code
First, build the JavaScript:
npm run build
Claude Desktop
In Claude Desktop, open Settings → Developer → Edit Config. This opens claude_desktop_config.json. Add your server:
{
"mcpServers": {
"notes": {
"command": "node",
"args": ["/absolute/path/to/notes-mcp/build/index.js"]
}
}
}
Let's understand it:
commandandargsare what the host runs to start your server.- Use an absolute path. On Windows, escape backslashes:
"C:\\Users\\you\\notes-mcp\\build\\index.js". - Fully quit and restart Claude Desktop after editing the file.
Then ask: "Save a note called Groceries with rice, eggs and tea, then list my notes." Claude should ask for permission and call your tools.
Claude Code
From the project folder, run:
claude mcp add notes -- node build/index.js
Everything after -- is the launch command. Inside Claude Code, type /mcp to check that notes is connected.
If the host does not see your tools
Run the launch command by hand first. It should print one line to stderr and wait. If it crashes, fix the error there. If it prints anything to stdout, find the console.log and change it.
Step 6: Error Handling and Input Validation
Good error handling makes your server feel smart. There are two kinds of errors in MCP:
| Error type | What it means | Who sees it |
|---|---|---|
Tool error (isError: true) | The tool ran but something went wrong | The model, so it can recover |
| Protocol error (JSON-RPC error) | The request itself is broken, e.g. unknown tool | The client, usually not the model |
Some practical rules:
- Return
isError: truewith a helpful message. Say what went wrong and how to fix it, like "No note with id X. Call list_notes to see valid ids." - Thrown errors are caught too. If your handler throws, the SDK turns it into an
isError: trueresult with the error message. That is fine for unexpected errors, but don't leak secrets or stack traces in messages. - Let Zod do the validation. Limits like
.max(5000)and.int().min(1).max(50)protect you from huge or strange input. - Validate business rules in the handler. Zod checks the shape. Your code checks the meaning, like "this note belongs to this user".
Here is a safe pattern for code that calls something external:
async ({ id }) => {
try {
const note = await db.findNote(id);
if (!note) {
return {
content: [{ type: 'text', text: `No note with id ${id}. Call list_notes to see valid ids.` }],
isError: true
};
}
return { content: [{ type: 'text', text: note.body }] };
} catch (err) {
console.error('[notes] database error', err); // full details go to your logs only
return {
content: [{ type: 'text', text: 'The notes database is not available right now. Try again later.' }],
isError: true
};
}
}
Let's understand it: the full error goes to stderr for you, and a short, safe message goes to the model. (Here db stands for your own database code.)
Step 7: Turn It into a Remote Streamable HTTP Server with a Bearer Token
A stdio server only works on your machine. To use your server from another computer or from web apps like ChatGPT, serve it over Streamable HTTP.
Install the HTTP packages:
npm install @modelcontextprotocol/express @modelcontextprotocol/node express
npm install -D @types/express
Create src/http.ts:
// src/http.ts
import { timingSafeEqual } from 'node:crypto';
import type { OAuthTokenVerifier } from '@modelcontextprotocol/express';
import { createMcpExpressApp, requireBearerAuth } from '@modelcontextprotocol/express';
import { toNodeHandler } from '@modelcontextprotocol/node';
import type { AuthInfo } from '@modelcontextprotocol/server';
import { createMcpHandler, OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server';
import { createServer } from './server.js';
const TOKEN: string = process.env.MCP_TOKEN ?? '';
if (TOKEN.length < 32) {
console.error('Set MCP_TOKEN to a random secret of at least 32 characters.');
process.exit(1);
}
const PORT = Number(process.env.PORT ?? 3000);
const PUBLIC_HOST = process.env.PUBLIC_HOST; // e.g. notes.example.com
function sameToken(a: string, b: string): boolean {
const left = Buffer.from(a);
const right = Buffer.from(b);
return left.length === right.length && timingSafeEqual(left, right);
}
const verifier: OAuthTokenVerifier = {
async verifyAccessToken(token): Promise<AuthInfo> {
if (!sameToken(token, TOKEN)) {
throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid token');
}
// expiresAt must be set, or the token is rejected
return { token, clientId: 'owner', scopes: ['mcp'], expiresAt: Math.floor(Date.now() / 1000) + 3600 };
}
};
const handler = createMcpHandler(createServer);
const app = PUBLIC_HOST
? createMcpExpressApp({ host: '0.0.0.0', allowedHosts: [PUBLIC_HOST] })
: createMcpExpressApp();
const auth = requireBearerAuth({ verifier, requiredScopes: ['mcp'] });
const node = toNodeHandler(handler);
app.all('/mcp', auth, (req, res) => void node(req, res, req.body));
app.listen(PORT, PUBLIC_HOST ? '0.0.0.0' : '127.0.0.1', () => {
console.error(`notes MCP server listening on port ${PORT}`);
});
Let's understand it:
createMcpHandler(createServer)reuses the same factory as the stdio version. The factory runs once per HTTP request, so the endpoint is stateless and easy to scale. That fits the 2026-07-28 spec, which removed protocol sessions.createMcpExpressApp()is Express with JSON parsing and DNS rebinding protection. On localhost it checks theHostandOriginheaders. When you bind to0.0.0.0, you must list your public hostname inallowedHosts.requireBearerAuthreads theAuthorization: Bearer ...header, calls your verifier and returns401for a bad or missing token.timingSafeEqualcompares tokens in constant time, so attackers can't guess the token from response times.- The verifier must set
expiresAt. The SDK rejects tokens without it.
Run it locally:
npm run build
MCP_TOKEN="paste-a-long-random-secret-here" node build/http.js
Generate a good secret with openssl rand -hex 32. On Windows PowerShell, set the variable first with $env:MCP_TOKEN = "...".
Connect Claude Code to the remote server:
claude mcp add --transport http notes https://notes.example.com/mcp \
--header "Authorization: Bearer YOUR_TOKEN"
Warning: Put the token in a header, never in the URL query string. URLs end up in server logs, browser history and screenshots. A static bearer token is fine for a personal server. For a multi-user product, use OAuth; the SDK docs cover it. I wrote about why this matters in MCP Integrations: Why Authentication Makes or Breaks Them.
Deployment Tips for a Remote MCP Server
These tips come from running my own portfolio MCP server:
- Use HTTPS. Put the Node app behind a reverse proxy like Nginx or Caddy that handles TLS. Never send bearer tokens over plain HTTP.
- Keep secrets in environment variables, not in code or Git. Rotate the token if it ever leaks.
- Use a real database. Our notes live in memory, so a restart deletes them, and two server instances would each have different notes. SQLite or PostgreSQL fixes both problems.
- Run it with a process manager like systemd or PM2, so it restarts after a crash.
- Add rate limits. The spec says servers must rate limit tool calls. A simple Express rate limiter in front of
/mcpis enough to start. - Make write tools safe to retry. Networks fail and AI clients retry. Use an idempotency key or check before you write, as I explain in Retry an MCP Write Without Creating Two Blog Posts.
- Log to stderr or files, and include the tool name in every log line. It makes debugging much faster.
Frequently Asked Questions
Can I build an MCP server with the old @modelcontextprotocol/sdk package?
Yes, v1.x still works and gets fixes for a while. But as of November 2026, v2 (@modelcontextprotocol/server) is the stable line and implements the newest spec, so start new projects with v2.
Why does my server work in the terminal but not in Claude Desktop?
Usually it's a relative path in the config, a console.log writing to stdout, or Claude Desktop was not fully restarted. Run the exact command from the config by hand to see the real error.
Do I need TypeScript to build an MCP server? No. There are official SDKs for Python, Kotlin, C#, Go and more. TypeScript is a good choice if you already know JavaScript and want strong types with Zod.
Should I use stdio or Streamable HTTP? Use stdio for personal, local tools on your own machine. Use Streamable HTTP when other people, other devices or web apps like ChatGPT need to reach the server. With the factory pattern in this guide, you can support both.
Key Takeaways
- To build an MCP server in TypeScript today, use the v2 SDK:
@modelcontextprotocol/serverwithMcpServer,registerTooland a ZodinputSchema. - Put your tools and resources in one
createServerfactory and reuse it forserveStdio(local) andcreateMcpHandler(HTTP). - In stdio servers, log only to stderr. stdout is the protocol channel.
- Test every tool in the MCP Inspector before connecting Claude Desktop or Claude Code.
- Return
isError: truewith clear, safe messages so the model can recover. - For remote servers: HTTPS, a bearer token in a header (or OAuth), allowed hosts, rate limits and a real database.
- Next, learn how agents decide which tools to call in AI Agents Explained, and how to write better tool instructions in Prompt Engineering for Developers.
Related articles
MCP explained simply: the N×M problem, hosts, clients and servers, tools, resources and prompts, stdio vs Streamable HTTP, the 2026 spec and security tips.
What AI agents really are: the observe-think-act loop, tool calling, memory, MCP, common failures like looping and prompt injection, and practical guardrails.
How Retrieval-Augmented Generation lets AI answer from your own documents: the pipeline, embeddings, a small Python example, common failures and how to evaluate.
A timeout can hide a successful write. Design an idempotent scheduling tool and test what happens when its first response is lost.