SuperLab Posts

How to Build an MCP Server: Step-by-Step With Working Code

Developer writing server code on a laptop

What Is an MCP Server and Why Would You Build One?

Every AI assistant needs data it doesn't have.

An MCP server is a lightweight program that exposes tools, data, or prompts to an AI client through the Model Context Protocol, an open standard Anthropic released in November 2024 and that OpenAI and Google DeepMind have since adopted. Instead of pasting context into a chat window by hand, the client calls your server's tools directly and gets structured JSON back. No manual copy-paste, no stale context.

You build one whenever an AI assistant needs to reach something it can't see on its own: your internal API, a database, a SaaS product, a file system, a build pipeline. The server sits between the client (Claude Code, Claude Desktop, or any other MCP-compatible app) and whatever you're exposing. It doesn't run the model. It just answers tool calls.

The pattern is deliberately narrow. A tool has a name, a description, an input schema, and a handler function. That's it. But narrow is what makes it composable. SuperLab's own MCP server, for example, registers 32 tools this way across two source files, most of them under 40 lines each.


What Do You Need Before You Start Building an MCP Server?

Four things. No exceptions.

You need Node.js 20+ (or Python 3.10+ for the Python SDK), the official @modelcontextprotocol/sdk package, a schema validation library like Zod, and an MCP client to test against. Claude Code is the fastest option since registration takes one command. You do not need an Anthropic API key for local testing; Claude Code's Pro or Team subscription covers tool calls made during a session.

Check your setup:

node --version   # must be v20.0.0 or higher
claude --version

This guide uses the TypeScript SDK because it's what most production MCP servers ship with today, including SuperLab's. The Python SDK follows the same concepts (server instance, tool registration, transport) with different syntax.


How Do You Set Up the MCP Server Project Structure?

Start from an empty folder. Five commands get you a working skeleton.

A minimal MCP server needs a package.json with "type": "module", TypeScript configured to compile to dist/, the SDK and Zod as dependencies, and a single entry file that creates a server instance and connects a transport. Total setup time is under ten minutes, including the first successful build.

mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
npx tsc --init

Set "type": "module" in package.json. The SDK ships as ES modules, and Node.js below v20 or a missing "type": "module" field will fail import resolution with an unhelpful error. Add a build script:

{
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js"
  }
}

Close-up of hands typing on a keyboard while writing an MCP server entry file

Create src/index.ts:

#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

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

const transport = new StdioServerTransport();
await server.connect(transport);

That's a complete, connectable server with zero tools. Run npm run build and confirm dist/index.js exists before moving on.


How Do You Define and Register Tools in an MCP Server?

A tool is a name, a description, a schema, and a function. Nothing more.

server.tool(name, description, inputSchema, handler) is the core registration call in the TypeScript SDK. The inputSchema is a Zod shape: a plain object of Zod types that the SDK validates automatically before your handler ever runs. Malformed input never reaches your business logic; the client gets a validation error back instead.

import { z } from "zod";

server.tool(
  "get_weather",
  "Get current weather for a city",
  { city: z.string().describe("City name, e.g. 'Kuala Lumpur'") },
  async ({ city }) => {
    const data = await fetchWeather(city);
    return {
      content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
    };
  }
);

Two details matter here. First, the return shape: every tool response is { content: [...] }, an array of content blocks: text, image, or resource. Returning a bare object instead of this shape breaks the client silently in some hosts and loudly in others. Second, errors: set isError: true on the returned object rather than throwing. SuperLab's server wraps this in a shared reg() helper so every one of its 32 tools gets the same try/catch behavior without repeating it:

function reg(name, description, shape, handler) {
  server.tool(name, description, shape, async (args) => {
    try {
      const result = await handler(args);
      return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
    }
  });
}

If you want to see this pattern running in production against a real 25-tool surface, How to Set Up Claude Code MCP with SuperLab walks through the client side of the same server.


How Do You Connect an MCP Server to a Real API?

Your tool handlers are just functions. They can call anything.

A tool handler is an async function. It can call a REST API, query a database, read a file, or shell out to another process. The common pattern is a thin client class that wraps your target API's authentication and endpoints, so tool handlers stay one line each: call the client method, return the result.

class ApiClient {
  constructor(private baseUrl: string, private token: string) {}

  async get(path: string) {
    const res = await fetch(`${this.baseUrl}${path}`, {
      headers: { Authorization: `Bearer ${this.token}` },
    });
    if (!res.ok) throw new Error(`API returned ${res.status}`);
    return res.json();
  }
}

Read credentials from environment variables, never hardcode them:

const client = new ApiClient(
  process.env.API_URL!,
  process.env.API_TOKEN!
);

Fail loudly at startup if a required variable is missing. A server that starts successfully but throws 401s on every tool call is harder to debug than one that refuses to boot.

Want a working reference before you write a single tool definition? SuperLab's production MCP server ships 32 tools built exactly this way. See the client-side setup in the Claude Code MCP guide. Five minutes to read.


How Do You Choose a Transport for Your MCP Server?

Two transports cover almost every use case.

MCP servers communicate over one of two transports: stdio (the process runs locally and exchanges JSON-RPC messages over stdin/stdout) or Streamable HTTP (the server runs as a network service and clients connect over HTTP, supporting remote and multi-client deployments). The older HTTP+SSE transport is deprecated in current SDK versions in favor of Streamable HTTP.

Transport Runs as Best for Auth model
stdio Local subprocess Single-user CLI tools, Claude Code, Claude Desktop Environment variables
Streamable HTTP Network service Remote/shared servers, multi-client access Bearer tokens, OAuth
HTTP+SSE (deprecated) Network service Legacy servers built before 2025 Bearer tokens

Network patch cables in a data center representing remote MCP server transport

Most first servers should start with stdio. It requires no networking, no TLS, and no session management. The client spawns your process and talks to it directly. Move to Streamable HTTP only when multiple clients or remote access are actual requirements, not hypothetical ones.

// stdio: what almost every local dev tool should use
const transport = new StdioServerTransport();
await server.connect(transport);

One gotcha that catches nearly everyone building their first stdio server: stdout is reserved for the JSON-RPC protocol. Any console.log() call in your handler corrupts the message stream and the client sees garbled or missing responses. Use console.error() for debug output instead. It goes to stderr, which the transport ignores.


How Do You Test an MCP Server Locally With Claude Code?

Register it, then call a tool.

Register a local MCP server with claude mcp add <name> -- node /absolute/path/to/dist/index.js, using an absolute path. Relative paths break when Claude Code changes its working directory. Open a new Claude Code session, run /mcp to confirm the server shows as connected, then call one of your tools directly to verify the full round trip.

npm run build
claude mcp add my-server -- node /absolute/path/to/my-mcp-server/dist/index.js

Programming code on a terminal screen representing MCP server testing

Start a fresh session and check:

claude

Then inside the session, run /mcp. Your server should appear in the connected list. Call a tool by name with the arguments your schema expects, and confirm the response matches what your handler returns. If the server shows as errored instead of connected, the two most common causes are: dist/index.js doesn't exist yet (you registered before building), or the entry file is missing the #!/usr/bin/env node shebang and isn't executable.


What Are Common Mistakes When Building an MCP Server?

Four mistakes account for most broken first servers.

The four most common MCP server mistakes are: logging to stdout instead of stderr on a stdio transport (corrupts the protocol stream), registering the server before building it (empty dist/), skipping input validation and letting malformed arguments reach business logic, and returning raw JavaScript objects instead of the { content: [...] } shape the protocol expects.

Mistake 1: console.log() on a stdio server. Covered above, but worth repeating because it's the single most common first-timer bug. It produces confusing, intermittent failures rather than a clear error.

Mistake 2: Registering before building. claude mcp add points at a file path. If that path doesn't exist yet, Claude Code registers it anyway and the server fails silently on first launch. Always npm run build first, confirm dist/index.js exists, then register.

Mistake 3: Skipping schema validation. A tool defined with {} as its shape accepts anything, including nothing. The SDK validates against whatever Zod shape you give it. An empty shape means no validation happens, and bad input reaches your handler as undefined fields that fail deep inside your business logic instead of at the boundary.

Mistake 4: Wrong return shape. Returning { result: data } instead of { content: [{ type: "text", text: ... }] } is a common port-over from building a plain REST endpoint. Some MCP clients tolerate this; others reject the response outright. Match the shape every time.


Keep Reading


Frequently Asked Questions

How do I build an MCP server from scratch?

Install @modelcontextprotocol/sdk and zod, create an entry file that instantiates McpServer, register tools with server.tool(name, description, schema, handler), and connect a StdioServerTransport. A minimal working server takes under ten minutes to write and build, and can be registered with Claude Code using claude mcp add.

Do I need Python or TypeScript to build an MCP server?

Either works. The TypeScript SDK is the most widely used in production servers today and pairs naturally with Zod for schema validation. The Python SDK offers the same server, tool, and transport concepts using Pydantic models instead of Zod. Pick whichever language your target API's client library already exists in.

Why does my MCP server show as "errored" in Claude Code?

Two causes cover most cases: the compiled dist/index.js doesn't exist because you registered before running npm run build, or the registration used a relative file path that breaks when Claude Code's working directory changes. Rebuild, confirm the compiled file exists, and re-register using an absolute path.

What is the difference between stdio and HTTP transport in MCP?

stdio runs your server as a local subprocess that exchanges JSON-RPC messages over stdin/stdout. No networking required, and it's the default choice for Claude Code and Claude Desktop. Streamable HTTP runs your server as a standalone network service reachable by multiple remote clients. Start with stdio; only move to HTTP when you have an actual multi-client or remote-access requirement.