All writing

Building MCP Servers and Clients with Node.js and TypeScript

By Bronson Dunbar ·

Updated November 2026: rewritten against the official TypeScript SDK. The first version of this post used packages that don't exist (@mcp/server and @mcp/client). Every example below has been run.

The Model Context Protocol (MCP) is an open standard for giving AI applications access to tools and data. You write an MCP server once, and any MCP-capable app (Claude Desktop, Claude Code, Cursor, VS Code and many more) can use it. If you're new to the idea, start with MCP explained.

In this guide we'll build a small notes server in TypeScript, call it from our own client, test it with the MCP Inspector, plug it into Claude Desktop and Claude Code, and finally hand its tools to Claude from our own code.

How the pieces fit

  • Server: exposes capabilities. Ours will be a Node.js process.
  • Client: connects to one server and speaks the protocol. Apps like Claude Desktop create one client per server.
  • Transport: how they talk. stdio runs the server as a child process and is what you'll use locally. Streamable HTTP is for remote servers.

A server can offer three kinds of capability:

Capability What it is Who decides to use it
Tools Functions the model can call, like "search notes" The model
Resources Data the app can read, addressed by URI The app or user
Prompts Reusable prompt templates The user

Set up the project

You need Node.js 20 or newer.

mkdir mcp-notes && cd mcp-notes
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
mkdir src

Create tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "rootDir": "src",
    "outDir": "dist",
    "strict": true,
    "skipLibCheck": true
  }
}

Build the server

Create src/server.ts. It registers two tools, one resource template and one prompt, then listens on stdio:

import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({ name: "notes", version: "1.0.0" });

// A real server would use a database. A Map keeps the example focused on MCP.
const notes = new Map<number, string>();

server.registerTool(
  "add_note",
  {
    description: "Save a note and return its ID",
    inputSchema: { text: z.string().describe("The note to save") },
  },
  async ({ text }) => {
    const id = notes.size + 1;
    notes.set(id, text);
    return { content: [{ type: "text", text: `Saved note ${id}` }] };
  },
);

server.registerTool(
  "search_notes",
  {
    description: "Find notes containing the query (case-insensitive)",
    inputSchema: { query: z.string() },
    annotations: { readOnlyHint: true },
  },
  async ({ query }) => {
    const matches = [...notes.values()].filter((n) => n.toLowerCase().includes(query.toLowerCase()));
    return { content: [{ type: "text", text: matches.join("\n") || "No matches." }] };
  },
);

server.registerResource(
  "note",
  new ResourceTemplate("notes://{id}", { list: undefined }),
  { description: "A single note by ID" },
  async (uri, { id }) => ({
    contents: [{ uri: uri.href, text: notes.get(Number(id)) ?? "No note with that ID." }],
  }),
);

server.registerPrompt(
  "summarise_notes",
  { description: "Summarise everything saved so far" },
  () => ({
    messages: [
      {
        role: "user",
        content: {
          type: "text",
          text: `Summarise these notes in three bullet points:\n\n${[...notes.values()].map((n) => `- ${n}`).join("\n")}`,
        },
      },
    ],
  }),
);

// stdout carries the protocol, so log to stderr.
await server.connect(new StdioServerTransport());
console.error("notes MCP server running on stdio");

A few details worth knowing:

  • Input schemas are Zod shapes. The SDK turns them into JSON Schema for clients and validates arguments before your handler runs, so text is guaranteed to be a string.
  • Descriptions matter. The model decides which tool to call from the name and description, so write them for the model.
  • Annotations are hints. readOnlyHint: true tells clients the tool doesn't change anything, so they may skip asking the user for approval. There are also destructiveHint, idempotentHint and openWorldHint.
  • Never write to stdout in a stdio server. stdout carries the protocol, so a stray console.log corrupts it. Use console.error.

Build it:

npx tsc

Write a client

Create src/client.ts. It starts the server as a child process, then uses every capability:

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

const transport = new StdioClientTransport({ command: "node", args: ["dist/server.js"] });
const client = new Client({ name: "notes-client", version: "1.0.0" });
await client.connect(transport);

const { tools } = await client.listTools();
console.log("Tools:", tools.map((t) => t.name));

await client.callTool({ name: "add_note", arguments: { text: "Ship the MCP post on Friday" } });
await client.callTool({ name: "add_note", arguments: { text: "Record the Friday devlog video" } });

const result = await client.callTool({ name: "search_notes", arguments: { query: "friday" } });
console.log("Search:", result.content);

const note = await client.readResource({ uri: "notes://1" });
console.log("Resource:", note.contents[0]);

const prompt = await client.getPrompt({ name: "summarise_notes" });
console.log("Prompt:", prompt.messages[0].content);

await client.close();
npx tsc && node dist/client.js

You should see the two tools, both Friday notes in the search results, note 1 from the resource, and the filled-in prompt.

Test with the MCP Inspector

The MCP Inspector is a browser UI for poking at a server by hand, and it's the fastest way to debug one:

npx @modelcontextprotocol/inspector node dist/server.js

Use it from Claude Desktop and Claude Code

To add the server to Claude Desktop, open Settings → Developer → Edit Config and add it to claude_desktop_config.json, using an absolute path:

{
  "mcpServers": {
    "notes": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-notes/dist/server.js"]
    }
  }
}

Restart Claude Desktop and the tools appear. In Claude Code it's one command:

claude mcp add notes -- node /absolute/path/to/mcp-notes/dist/server.js

Give the tools to Claude in your own app

This is the part most MCP tutorials skip. MCP tool definitions map almost one-to-one onto the Claude API's tool format, so connecting them takes a short loop: send the tools, run whatever Claude asks for through MCP, send the results back, and repeat until Claude answers.

npm install @anthropic-ai/sdk
export ANTHROPIC_API_KEY="sk-ant-..."

Create src/agent.ts:

import Anthropic from "@anthropic-ai/sdk";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

const anthropic = new Anthropic();
const mcp = new Client({ name: "notes-agent", version: "1.0.0" });
await mcp.connect(new StdioClientTransport({ command: "node", args: ["dist/server.js"] }));

// MCP tool definitions map almost one-to-one onto Claude's tool format.
const { tools } = await mcp.listTools();
const claudeTools: Anthropic.Tool[] = tools.map((tool) => ({
  name: tool.name,
  description: tool.description,
  input_schema: tool.inputSchema as Anthropic.Tool.InputSchema,
}));

await mcp.callTool({ name: "add_note", arguments: { text: "Ship the MCP post on Friday" } });

const messages: Anthropic.MessageParam[] = [
  { role: "user", content: "What have I got planned for Friday? Check my notes." },
];

// Keep going until Claude stops asking for tools.
while (true) {
  const response = await anthropic.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    tools: claudeTools,
    messages,
  });
  messages.push({ role: "assistant", content: response.content });

  if (response.stop_reason !== "tool_use") {
    for (const block of response.content) {
      if (block.type === "text") console.log(block.text);
    }
    break;
  }

  // Run every tool Claude asked for and send all the results back in one message.
  const results: Anthropic.ToolResultBlockParam[] = [];
  for (const block of response.content) {
    if (block.type !== "tool_use") continue;
    const result = await mcp.callTool({ name: block.name, arguments: block.input as Record<string, unknown> });
    results.push({
      type: "tool_result",
      tool_use_id: block.id,
      content: JSON.stringify(result.content),
      is_error: result.isError === true,
    });
  }
  messages.push({ role: "user", content: results });
}

await mcp.close();

Two rules to keep: return all the tool results from one turn in a single user message, and flag failures with is_error rather than dropping them, so Claude can recover. If the Claude API is new to you, read getting started with the Claude API in Node.js first.

Going further

  • Remote servers. Swap StdioServerTransport for the SDK's Streamable HTTP transport to run the server as a web service. Remote servers need authentication, and the spec uses OAuth 2.1 for that.
  • Security. Tools run with your server's permissions. Validate inputs, keep destructive tools behind user approval, and remember that text from tools (web pages, emails, files) can contain prompt injection.
  • Reuse before you build. Check the official MCP Registry and the reference servers first.

Resources