Your First MCP Server

Building Your First MCP Server

Let's build a working MCP server from scratch. We'll create a simple calculator server that gives Claude the ability to perform math operations. This is the "Hello World" of MCP.

The Complete Server Code

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

// Create the server
const server = new McpServer({
  name: "calculator",
  version: "1.0.0",
});

// Tool: Add two numbers
server.tool(
  "add",
  "Add two numbers together",
  { a: z.number(), b: z.number() },
  async ({ a, b }) => ({
    content: [{ type: "text", text: String(a + b) }],
  })
);

// Tool: Multiply two numbers
server.tool(
  "multiply",
  "Multiply two numbers",
  { a: z.number(), b: z.number() },
  async ({ a, b }) => ({
    content: [{ type: "text", text: String(a * b) }],
  })
);

// Connect to stdio transport
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Calculator MCP server running!");

Breaking It Down

Let's understand each part of the server:
typescript
// 1. McpServer - The main server class
//    Takes a name and version for identification
const server = new McpServer({ name: "calculator", version: "1.0.0" });

// 2. server.tool() - Register a tool
//    Arguments: name, description, input schema, handler
//    - name: unique identifier the AI uses to call this tool
//    - description: helps the AI understand WHEN to use it
//    - schema: zod schema validating the input
//    - handler: async function that does the work

// 3. StdioServerTransport - Communication channel
//    Reads from stdin, writes to stdout
//    This is how Claude Desktop talks to your server

// 4. server.connect() - Start listening
//    Your server is now ready to receive requests!

Configure in Claude Desktop

Add your server to Claude Desktop's config file at ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):
typescript
{
  "mcpServers": {
    "calculator": {
      "command": "npx",
      "args": ["tsx", "/path/to/my-mcp-server/src/index.ts"]
    }
  }
}

Tip:After saving the config, restart Claude Desktop. You should see a hammer icon indicating your tools are available. Try asking: "What is 42 multiplied by 17?"

PreviewTypeScriptRead Only
Copy this code and run it locally with npx tsx server.ts

💬 Got questions? Ask me anything!