Node.js MCP Server Tutorial for Complete Beginners

Node.js MCP Server Tutorial for Complete Beginners

Introduction

Ever wished your AI assistant could do more than just answer questions? That’s what an MCP server makes possible. MCP stands for Model Context Protocol — it’s a way for your AI tools and your own code to talk to each other in a standard, predictable way.

Think of it like giving your AI a new set of tools: a hammer, a screwdriver, maybe even a coffee machine. But instead of hardware, these tools could be a “math solver,” a “translate text” feature, or a “fetch API data” helper.

In this tutorial, we’ll use Node.js to build an MCP server from scratch. You’ll see real code examples, tips to avoid common mistakes, and how to test your work so you know it’s working before connecting it to an AI client.

Once you finish, you’ll have a working MCP server that can be plugged into an AI-powered IDE like Cursor, letting your AI run your custom tools whenever it needs them — automatically.

TL;DR: An MCP server is like a bridge between your code and AI tools. In this guide, you’ll learn how to create one in Node.js, step by step, using simple examples like adding numbers or fetching stored data. By the end, your AI will be able to call your tools automatically.


What is MCP and Why Use It with Node.js

MCP stands for Model Context Protocol. It’s basically a standard way for your AI tools and your code to talk to each other — without confusion or guesswork.

Think of it like this: If you wanted to order a pizza, you wouldn’t just say “food, please” to the restaurant. You’d tell them exactly what type, size, and toppings you want. MCP is the “menu” and “order form” for your AI, so it always knows how to call your code correctly.

With MCP, you can:

  • Create tools that do specific things, like fetch weather data, check stock prices, or solve math problems.
  • Plug those tools into AI-friendly environments like Cursor or Claude Desktop, so the AI can run them automatically when your prompt needs it.
  • Keep your code clean and easy to expand later — adding a new tool is as simple as adding a new function.

Why Node.js for MCP? Node.js is beginner-friendly, runs almost everywhere, and has a huge library of ready-made packages you can use. Plus, if you’ve ever written a bit of JavaScript, you’re already halfway there.

Example: Let’s say you write a tool in MCP that takes two numbers and adds them together. Later, you can also create a tool that fetches the latest football scores. Both tools can live in the same MCP server, and your AI will know exactly when to use each.

Tip: Start small — build one or two very simple tools first. Once you see them working, it’s much easier to add more complex ones without feeling lost.


What You Need Before Starting

Before diving into MCP server code, let’s make sure you’ve got the basics covered.

1. Node.js installed: You’ll need Node.js v20 or later. Check your version by running:

node -v        

If you don’t have it, grab it from nodejs.org.

2. A code editor VS Code is a great choice — it’s free, beginner-friendly, and has extensions to make coding easier.

3. Basic terminal/command prompt skills: You don’t have to be a pro. Just know how to:

  • Navigate folders (cd foldername)
  • Create files (touch file.js or use the editor)
  • Install packages (npm install packagename)

4. A place to test your server: We’ll use the MCP Inspector tool to test our work later, so you can see exactly what your server is doing.

Example: Think of this like cooking: you can’t start making a cake until you have the oven, ingredients, and baking tools ready. Node.js is your oven, the packages are your ingredients, and your editor is your kitchen counter.

Tip: Set up a dedicated folder for this project so all your files and settings stay organized. It makes coming back to your code later way easier.


Create a New Node.js Project

Now that you have Node.js ready, let’s create a fresh project just for your MCP server.

Step 1 – Make a project folder

Open your terminal and run:

mkdir my-mcp-server
cd my-mcp-server        

This creates a new folder named my-mcp-server and moves you into it.

Step 2 – Initialize the project

npm init -y        

This creates a file called package.json — think of it as your project’s ID card, keeping track of your dependencies and settings.

Step 3 – Organize your files

Inside the folder, you’ll eventually have:

my-mcp-server/
  ├── index.js        # main server code
  ├── package.json    # project settings
  └── node_modules/   # installed packages        

Example: This is like setting up an empty workshop. You’ve got the walls and a clean bench — now we can start bringing in the tools and materials.

Tip: Give your project a clear, descriptive name (e.g., weather-mcp-server) if you plan to build more than one. It helps when you come back later and can’t remember which folder is which.


Install the Right Packages

For our MCP server, we need just two main packages:

  1. @modelcontextprotocol/sdk – This is the official MCP toolkit. It lets your code talk in MCP’s “language.”
  2. zod – A helper library that checks and validates inputs, so your server doesn’t break if the wrong type of data comes in.

Step 1 – Install them

Run this inside your project folder:

npm install @modelcontextprotocol/sdk zod        

Step 2 – Why these packages matter

  • @modelcontextprotocol/sdk: Think of it as the instruction manual for building MCP tools.
  • zod: Imagine having a gatekeeper who checks everyone’s ID before they enter — Zod makes sure the inputs to your tools are correct.

Example: If your tool expects two numbers but gets “apple” and “banana” instead, Zod will politely refuse them before your server crashes.

Tip: Install only what you need. Fewer packages mean faster installs and fewer chances for version conflicts later.


Write Your First MCP Server Code

Now it’s time to bring our MCP server to life. We’ll start with a super simple tool that adds two numbers.

Step 1 – Create the file

Inside your project folder, make a file called index.js.

Step 2 – Add this code

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

// Create the MCP server
const server = new McpServer({
  name: "My MCP Server",
  version: "1.0.0",
  tools: {}
});

// Add a simple "add" tool
server.tool(
  "add",
  { a: z.number(), b: z.number() },
  async ({ a, b }) => {
    return {
      content: [{ type: "text", text: `${a + b}` }]
    };
  }
);

// Set up server transport
const transport = new StdioServerTransport();
server.connect(transport);        

How it works:

  • McpServer sets up your server.
  • server.tool(...) creates a new tool called add that takes two numbers and returns their sum.
  • z.number() ensures the inputs are numbers, not text or something else.
  • StdioServerTransport is like the wire that connects your server to whoever’s calling it.

Example: If you send { a: 5, b: 7 } to the add tool, it will return 12.

Tip: Always start with one small tool to confirm everything’s working before adding more features. Debugging a single function is much easier than fixing five at once.


Add More Tools to Your Server

Now that your MCP server can add numbers, let’s give it another skill. We’ll make a tool that returns an API key stored in your environment variables.

Step 1 – Update your index.js file Right after the add tool code, add this:

// Tool to get API key from environment variables
server.tool(
  "getApiKey",
  {},
  async () => {
    return {
      content: [
        { type: "text", text: process.env.API_KEY || "No API key set" }
      ]
    };
  }
);        

Step 2 – Set an environment variable

In your terminal:

export API_KEY=my-secret-key   # Mac/Linux
set API_KEY=my-secret-key      # Windows (cmd)        

Step 3 – Why this is useful

Instead of hardcoding secrets like API keys in your code (which is risky), you store them outside your code and fetch them when needed.

Example: If you need an API key for a weather service, your AI could call getApiKey whenever it needs it, without exposing it in your source code.

Tip: Never commit .env files or secrets to GitHub. Treat them like passwords.


Test Your MCP Server

Before connecting your server to an AI tool, let’s make sure it works properly. We’ll use a handy tool called MCP Inspector — it lets you test your MCP server in a friendly interface.

Step 1 – Install MCP Inspector

In your terminal, run:

npm install -g @modelcontextprotocol/inspector        

The -g flag means it’s installed globally so you can use it from anywhere.

Step 2 – Run your MCP server with Inspector

From inside your project folder:

npx @modelcontextprotocol/inspector node index.js        

This starts your server and opens MCP Inspector in your browser (usually at http://localhost:6274).

Step 3 – Test your tools

  • In the Inspector, you’ll see your add and getApiKey tools listed.
  • Try calling add with { "a": 5, "b": 7 } — you should see 12 as the result.
  • Try calling getApiKey — you should see your secret key or the message "No API key set".

Example: This is like taking a car for a test drive before giving the keys to someone else. You want to know the brakes and steering work first.

Tip: If you get errors, check that your Node.js version is 20 or higher, your packages are installed, and your index.js file has no typos.


Connect Your MCP Server to an AI App

Once your MCP server works in MCP Inspector, it’s time to connect it to an AI client or IDE so your AI can use your tools automatically. A popular option is Cursor IDE (but you can also use Claude Desktop or other MCP-compatible apps).

Step 1 – Open your AI app’s settings

In Cursor, open settings.json (Command Palette → “Open Settings (JSON)”).

Step 2 – Add your MCP server config

Insert something like this:

"mcpServers": {
  "My MCP Server": {
    "command": "node",
    "args": ["path/to/index.js"],
    "env": {
      "API_KEY": "my-secret-key"
    }
  }
}        

Replace path/to/index.js with your actual file path.

Step 3 – Save and restart the AI app

When you restart Cursor (or your chosen client), it should detect the MCP server and list your tools.

Step 4 – Try it out

  • In a new prompt, type: “Add 5 and 8 using your tool”.
  • Your AI will automatically call the add tool in your server and give the result.
  • Try: “Get the API key” — it should use getApiKey.

Example: This is like connecting your new coffee machine to the kitchen power socket. Once plugged in, you can use it anytime without rewiring the house.

Tip: If your AI isn’t using the tools, double-check the config path, restart the app, and make sure your server is running.


Conclusion

Building an MCP server in Node.js isn’t just a coding exercise — it’s like giving your AI assistant a personal toolkit. With just a few steps, you learned how to:

  • Understand what MCP is and why it’s useful
  • Set up a Node.js project from scratch
  • Install the essential MCP and validation packages
  • Write simple, functional tools like add and getApiKey
  • Test everything with MCP Inspector
  • Connect your server to an AI-friendly IDE like Cursor

The real power of MCP comes when you start adding your own custom tools — anything from weather lookups to database queries. The best part? Once connected, your AI can use them without you having to explain how they work every time.

Key Takeaway: Start small, get it working, then grow your toolset one feature at a time.

References

  1. Model Context Protocol Documentationhttps://modelcontextprotocol.io
  2. Node.js Official Sitehttps://nodejs.org
  3. Zod Validation Libraryhttps://zod.dev
  4. MCP Inspector GitHubhttps://github.com/modelcontextprotocol/inspector
  5. Cursor IDEhttps://cursor.com


Created with the help of Chat GPT

To view or add a comment, sign in

Explore topics