how-to-build-first-local-mcp-server-python-typescript

Build Your First Local MCP Server in Python or TypeScript

Step-by-step guide to building your first local Model Context Protocol (MCP) server in Python or TypeScript. Includes FastMCP, Zod schemas, and MCP Inspector.

Want to give your AI coding assistant access to local scripts or project notes, without copying and pasting context all day?

Setting up a Model Context Protocol (MCP) server can sound intimidating at first, especially if you are not sure whether to use Python or TypeScript.

The good news is that both official MCP SDKs let you build a working local server in under 40 lines of code. In this step-by-step tutorial, we will walk you through building, testing, and connecting your first local MCP server in either Python or TypeScript.

Executive Summary

  • Pick Your Language: Use Python (mcp / FastMCP) for quick scripts and data tasks, or TypeScript (@modelcontextprotocol/sdk) for Node.js and web tooling.
  • Automatic Schemas: Both SDKs generate JSON Schema tool definitions from Python type hints or TypeScript zod validators.
  • Safe Local Transport: Local servers communicate over stdio (standard input/output) with zero open network ports.
  • Instant Browser Testing: Test every tool in the official MCP Inspector before wiring it into Claude Desktop, Cursor, or another IDE.

Table of Contents

Python vs. TypeScript MCP SDKs Compared

Both official SDKs implement the same MCP specification, so your AI client cannot tell the difference. Pick the language that matches your team’s existing stack.

FeaturePython (mcp SDK)TypeScript (@modelcontextprotocol/sdk)
Primary Server ClassFastMCPMcpServer
Input ValidationPython type hints + Pydanticzod schemas
Build Step RequiredNo (runs directly with Python)Yes (compile .ts to .js via tsc)
Best Use CaseAI/ML scripts, SQLite, local data pipelinesWeb tooling, npm packages, Node.js APIs
Build Your First Local MCP Server in Python or TypeScript Data Chart

Method 1: Build a Local MCP Server in Python (Fastest Setup)

Python is the fastest way to get a local MCP server running. Its FastMCP wrapper turns regular typed functions into MCP tools automatically.

Step 1: Create a Virtual Environment and Install mcp

Open your terminal, create a new project folder, and install the official mcp package:

mkdir my-first-mcp && cd my-first-mcp
python -m venv .venv
source .venv/bin/activate
pip install "mcp[cli]"

Step 2: Write Your server.py File

Create a file named server.py with a simple tool that formats a clean project checklist or looks up a local status value. Notice how the docstring and type hints tell the AI model what the tool does.

import logging
from mcp.server.fastmcp import FastMCP

# Route logs to stderr so stdout stays clean for JSON-RPC
logging.basicConfig(level=logging.INFO)

mcp = FastMCP("dev-helper")


@mcp.tool()
def word_count(text: str) -> dict:
    """Count words, characters, and lines in a snippet of text."""
    lines = text.splitlines() if text else []
    words = text.split()
    return {
        "words": len(words),
        "characters": len(text),
        "lines": len(lines),
    }


if __name__ == "__main__":
    mcp.run(transport="stdio")

Step 3: Test with MCP Inspector and Connect Your Client

Run the MCP Inspector to verify your tool schema and test a sample input in your browser:

npx @modelcontextprotocol/inspector .venv/bin/python server.py

Once it works in the Inspector, add the absolute paths to your AI client’s mcp.json configuration:

{
  "mcpServers": {
    "dev-helper": {
      "command": "/absolute/path/to/my-first-mcp/.venv/bin/python",
      "args": ["/absolute/path/to/my-first-mcp/server.py"]
    }
  }
}

Pro Tip: Always point "command" directly to your virtual environment’s Python binary (.venv/bin/python), not global python, so your dependencies are always found.

Method 2: Build a Local MCP Server in TypeScript

If your team already works in Node.js, the official TypeScript SDK pairs cleanly with zod for strict runtime validation.

Step 1: Initialize Node.js and Install Dependencies

Create a folder, initialize package.json, and install the MCP SDK plus zod and TypeScript:

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

Make sure "type": "module" is set in package.json, and configure tsconfig.json with "module": "Node16" and "outDir": "./build".

Step 2: Write src/index.ts

Create src/index.ts using McpServer and StdioServerTransport:

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

const server = new McpServer({
  name: "dev-helper-ts",
  version: "1.0.0",
});

server.tool(
  "word_count",
  "Count words and characters in a text snippet",
  { text: z.string().describe("Input text to measure") },
  async ({ text }) => {
    const words = text.trim() ? text.trim().split(/\s+/).length : 0;
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({ words, characters: text.length }),
        },
      ],
    };
  }
);

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

Step 3: Build and Register the Compiled Script

Compile your TypeScript code into JavaScript (npx tsc), test it with npx @modelcontextprotocol/inspector node build/index.js, and register "command": "node" with "args": ["/absolute/path/to/my-ts-mcp/build/index.js"] in your client config.

Note: Use console.error() for debug messages in TypeScript stdio servers. Calling console.log() writes to stdout and breaks JSON-RPC framing.

Common Beginner Mistakes to Avoid

If your client fails to connect on the first try, check these three common issues:

  • Writing Debug Text to stdout: Both print() in Python and console.log() in Node.js write to stdout. Keep stdout 100% reserved for MCP protocol messages.
  • Using Relative Paths in mcp.json: GUI apps launch subprocesses from a root or home directory. Always use full absolute paths for both "command" and "args".
  • Missing Tool Descriptions: Without clear docstrings or .describe() notes, the AI model will guess parameter formats incorrectly.

Frequently Asked Questions

Do I need an API key to run a local MCP server?

No. A local stdio MCP server runs directly on your machine as a subprocess. You only need an API key if your tool itself calls an external cloud service.

Can I run both Python and TypeScript MCP servers at the same time?

Yes. Your AI client can connect to multiple MCP servers listed in mcp.json simultaneously, regardless of which language each server uses.

Why does my MCP client not see code changes I just saved?

AI clients spawn stdio servers at startup or session start. After editing your Python or compiled TypeScript file, reload or restart the MCP server inside your client.

How do I make my TypeScript MCP server executable without npx tsc every time?

During local development, you can run npx tsc --watch in a terminal tab so build/index.js recompiles automatically whenever you save src/index.ts.

You May Also Like

We hope this guide helped you build and test your first local MCP server. Written by the TeckScaler Editorial Engineering Team. Continue exploring our MCP and AI engineering series:

Primary Sources and References

Leave a Reply

Your email address will not be published. Required fields are marked *