Skip to content

Step-by-step: build an MCP server in TypeScript

Each step has a Goal, what to Do, and how to Verify it. Track progress with the MCP checklist. The finished server is the TypeScript template: download it from the templates page.

Running example: a notes server that lets the agent search and add notes stored in a local JSON file.

These snippets use the v2 TypeScript SDK (@modelcontextprotocol/server, Zod 4). v2 is the stable line. Started with serveStdio(createServer) (Step 3), it serves both current 2026-07-28 clients and legacy 2025 clients (see Protocol versions). The old monolithic @modelcontextprotocol/sdk package is v1. If you’re maintaining v1 code, the differences are listed at the end of this guide.


  • Goal: A short list of task-shaped tools.
  • Do:
    1. List the user jobs, for example: “find notes about X” and “save this as a note”.
    2. Map one tool to each job, not one per API endpoint: search_notes, add_note.
    3. For each tool, decide its inputs, its output, and whether it’s read-only or destructive.
    4. Read Tool design before you finalise names and descriptions.
  • Verify: Every tool maps to a real request, and you have fewer than about 10 tools (this guide’s rule of thumb).
  • Goal: A buildable TypeScript project.

  • Do:

    Terminal window
    mkdir notes-server && cd notes-server
    npm init -y
    npm install @modelcontextprotocol/server zod
    npm install -D typescript@5 @types/node
    npx tsc --init

    Pin typescript@5: a plain npm install -D typescript now installs a newer major version that this template hasn’t been tested with. In package.json, set "type": "module", a "bin" entry, and "build": "tsc". In tsconfig.json, set "module": "Node16", "moduleResolution": "Node16", "target": "ES2022", "outDir": "build", "rootDir": "src", and "types": ["node"]. The template already has all of this done.

  • Verify: npm run build succeeds on an empty src/index.ts.

  • Goal: A server that connects over stdio and serves both protocol eras.

  • Do: In src/index.ts, put all registration inside a createServer() function, and start it with serveStdio:

    #!/usr/bin/env node
    import { realpathSync } from "node:fs";
    import { fileURLToPath } from "node:url";
    import { McpServer } from "@modelcontextprotocol/server";
    import { serveStdio } from "@modelcontextprotocol/server/stdio";
    export function createServer(): McpServer {
    const server = new McpServer({ name: "notes", version: "0.1.0" });
    // tools, resources, prompts go here (Steps 4–6)
    return server;
    }
    // Start only when run directly, so tests can import this file without starting a server.
    if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
    await serveStdio(createServer);
    console.error("notes MCP server running on stdio"); // stderr, never stdout
    }

    serveStdio(createServer) answers both 2026-07-28 clients (no handshake, server/discover) and legacy clients (initialize handshake). The older pattern, new StdioServerTransport() plus server.connect(), still compiles but serves only legacy clients.

  • Verify: npm run build, then npx @modelcontextprotocol/inspector node build/index.js (the Inspector needs Node 22.19 or later). The Inspector connects.

  • Goal: The model can call your first tool.

  • Do:

    1. Add the storage helpers near the top of src/index.ts. They read and write a JSON file, and searchNotes sorts matches newest first:

      import { readFile, writeFile } from "node:fs/promises";
      import { homedir } from "node:os";
      import { join } from "node:path";
      import { z } from "zod";
      const NOTES_FILE = process.env.NOTES_FILE ?? join(homedir(), ".notes-mcp.json");
      interface Note {
      title: string;
      body: string;
      created: string; // ISO 8601
      }
      async function loadNotes(): Promise<Note[]> {
      try {
      return JSON.parse(await readFile(NOTES_FILE, "utf8")) as Note[];
      } catch (err) {
      if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
      throw err;
      }
      }
      async function saveNotes(notes: Note[]): Promise<void> {
      await writeFile(NOTES_FILE, JSON.stringify(notes, null, 2), "utf8");
      }
      export function searchNotes(notes: Note[], query: string, limit: number): Note[] {
      const q = query.toLowerCase();
      return notes
      .filter((n) => `${n.title} ${n.body}`.toLowerCase().includes(q))
      .sort((a, b) => b.created.localeCompare(a.created)) // newest first
      .slice(0, limit);
      }
    2. Register the tool inside createServer(), before return server:

      server.registerTool(
      "search_notes",
      {
      title: "Search notes",
      description:
      "Search saved notes by keyword in title or body. Returns up to `limit` matches, newest first. Use before add_note to avoid duplicates.",
      inputSchema: z.object({
      query: z.string().min(1).describe("Keyword or phrase, case-insensitive"),
      limit: z.number().int().min(1).max(20).default(5).describe("Maximum results (1-20)"),
      }),
      annotations: { readOnlyHint: true, openWorldHint: false },
      },
      async ({ query, limit }) => {
      const hits = searchNotes(await loadNotes(), query, limit);
      return {
      content: [{
      type: "text",
      text: hits.length
      ? hits.map((n) => `- ${n.title} (${n.created}): ${n.body.slice(0, 200)}`).join("\n")
      : `No notes match "${query}". Try a broader keyword.`,
      }],
      };
      },
      );
  • Verify: In the Inspector, go to Tools → List, then run search_notes. You get a sensible result, including when nothing matches.

Step 5: Add a write tool, with validation and errors

Section titled “Step 5: Add a write tool, with validation and errors”
  • Goal: Safe state changes and helpful failures.

  • Do: Inside createServer():

    server.registerTool(
    "add_note",
    {
    title: "Add note",
    description:
    "Save a new note with a unique title and a Markdown body. Fails if a note with the same title already exists, so use search_notes first if unsure. Returns a confirmation with the saved title.",
    inputSchema: z.object({
    title: z.string().min(1).max(120).describe("Unique note title"),
    body: z.string().min(1).max(10_000).describe("Note content (Markdown allowed)"),
    }),
    annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    },
    async ({ title, body }) => {
    const notes = await loadNotes();
    if (notes.some((n) => n.title.toLowerCase() === title.toLowerCase())) {
    return {
    isError: true,
    content: [{ type: "text", text: `A note titled "${title}" already exists. Choose a different title or use search_notes to find it.` }],
    };
    }
    notes.push({ title, body, created: new Date().toISOString() });
    await saveNotes(notes);
    return { content: [{ type: "text", text: `Saved note "${title}".` }] };
    },
    );
    • Validation comes free from the Zod schema; invalid input is rejected before your handler runs.
    • Return isError: true for expected failures, with a message that tells the model what to do next.
    • Let unexpected exceptions throw; the SDK turns them into tool errors. The exception’s message reaches the model, so keep secrets and internal details out of it.
    • destructiveHint and openWorldHint default to true, so set them to false explicitly when they don’t apply (see Tool design).
  • Verify: Add a note, add the same note again (you get a clear error), then search for it.

Step 6: Add resources and prompts (optional)

Section titled “Step 6: Add resources and prompts (optional)”
  • Goal: Expose read-only context and user-invoked templates.

  • Do: Inside createServer():

    server.registerResource(
    "all-notes",
    "notes://all",
    { title: "All notes", description: "Every saved note as JSON", mimeType: "application/json" },
    async (uri) => ({ contents: [{ uri: uri.href, text: JSON.stringify(await loadNotes(), null, 2) }] }),
    );
    server.registerPrompt(
    "weekly-review",
    { title: "Weekly review", description: "Summarise this week's notes", argsSchema: z.object({ focus: z.string().optional() }) },
    ({ focus }) => ({
    messages: [{ role: "user", content: { type: "text", text: `Search my notes from this week and write a weekly review${focus ? ` focused on ${focus}` : ""}.` } }],
    }),
    );
  • Verify: They show up on the Inspector’s Resources and Prompts tabs.

  • Goal: No hard-coded paths or keys.

  • Do: Read configuration from environment variables with safe defaults, as NOTES_FILE does in Step 4. If a variable is required and has no safe default, fail fast with a clear stderr message. Put the check inside the start block from Step 3, so tests that import the file aren’t affected:

    if (!process.env.NOTES_API_TOKEN) {
    console.error("NOTES_API_TOKEN is not set. Add it to the env block of your client config.");
    process.exit(1);
    }
  • Verify: Run it with NOTES_FILE unset, set, and set to an invalid path. Each case behaves predictably.

  • Goal: Automated confidence.
  • Do:
    1. Test manually in the Inspector (every tool, including the error paths).
    2. Run the protocol smoke test that ships with the template: npm run smoke, or node scripts/mcp-smoke.mjs node build/index.js, from the project folder. If you built from scratch, copy scripts/mcp-smoke.mjs from the template download; it needs no other dependencies (Node 20 or later).
    3. Unit-test your handler logic separately from MCP. Import the pure functions, such as searchNotes, from src/index.ts; importing the file doesn’t start the server.
    4. See Testing & debugging.
  • Verify: The smoke test prints PASS, and the unit tests pass.
  • Goal: It works in real hosts.
  • Do: Follow Connect to clients. Use the absolute path to build/index.js.
  • Verify: Cursor shows the server as green with 2 tools (Claude Code shows “✔ Connected” in /mcp), and asking “search my notes for MCP” calls search_notes.
  • Goal: Others can install it.
  • Do:
    • npm: publish with a bin entry, so users can configure "command": "npx", "args": ["-y", "your-package"].
    • Claude Desktop: package it as an MCP Bundle (.mcpb) for one-click install. Run npx @anthropic-ai/mcpb init to create the manifest, then npx @anthropic-ai/mcpb pack to build the bundle.
    • Remote: switch to Streamable HTTP and deploy it (see Security & production).
    • Write a README covering its tools, required environment variables, and config snippets for each client.
  • Verify: A colleague installs it from the README alone.

Migrating from v1 (@modelcontextprotocol/sdk)

Section titled “Migrating from v1 (@modelcontextprotocol/sdk)”
v1 v2
npm i @modelcontextprotocol/sdk npm i @modelcontextprotocol/server (and @modelcontextprotocol/client for clients)
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { McpServer } from "@modelcontextprotocol/server"
new StdioServerTransport() + await server.connect(transport) serveStdio(createServer) from @modelcontextprotocol/server/stdio, which serves both eras. StdioServerTransport + connect() still exists in v2 but serves only legacy clients
inputSchema: { a: z.string() } (raw shape) inputSchema: z.object({ a: z.string() }) (raw shape still works but is deprecated)
Zod 3 Zod 4
HTTP: StreamableHTTPServerTransport wired by hand createMcpHandler (web-standard handler) from @modelcontextprotocol/server; NodeStreamableHTTPServerTransport or toNodeHandler (Node’s http module) from @modelcontextprotocol/node; or a framework adapter: @modelcontextprotocol/express, @modelcontextprotocol/hono, or @modelcontextprotocol/fastify

v2 still answers the initialize opening from legacy 2025 clients, so existing hosts keep working, as long as you start the server with serveStdio or the HTTP handlers above. The full migration guide is at https://ts.sdk.modelcontextprotocol.io/v2/migration/.