How to Build an MCP Server in Python & TypeScript (2026)

You copy a 30-line MCP server tutorial from last year, run python server.py, and hit an immediate ImportError: cannot import name 'FastMCP'. You switch to TypeScript, install the old package, and your client drops the connection on startup because a single stray console.log() corrupted the JSON-RPC stream.

Learning how to build an mcp server in late 2026 is much cleaner once you know two breaking changes that tripped up older guides. First, the 2026-07-28 MCP Specification went completely stateless, retiring the old initialize handshake and Mcp-Session-Id header in favor of server/discover and stateless Streamable HTTP. Second, both official SDKs shipped major v2 releases: Python SDK v2 renamed FastMCP to MCPServer, and TypeScript SDK v2 moved server code into @modelcontextprotocol/server.

Below is the complete, tested 2026 walkthrough for building a working Model Context Protocol server from scratch in both Python and TypeScript, testing every tool schema with MCP Inspector v2, and wiring it safely into Claude Desktop, Cursor, Claude Code, or a production Streamable HTTP endpoint.

Table of Contents

What changed in the 2026-07-28 MCP spec and SDK v2

The Model Context Protocol has grown from a desktop experiment into core AI infrastructure. According to Anthropic’s Agentic AI Foundation donation notice and the July 2026 MCP 2026-07-28 release summary, public registries crossed 10,000 active MCP servers in late 2025, and Tier 1 SDK downloads approached half a billion per month by mid-2026.

If you are starting a fresh server today, build against these three 2026 defaults rather than copying 2024 or 2025 boilerplate:

  • Stateless by default (2026-07-28 spec): Every JSON-RPC 2.0 request now carries its own protocol version and client capabilities in _meta. The old stateful initialize handshake, standalone GET /sse stream, and Mcp-Session-Id header are retired, allowing remote MCP servers to scale behind any standard load balancer without sticky sessions (REST API Tutorial 2026 Stateless Spec Guide).
  • Python SDK v2 (mcp >= 2.0.0): The old FastMCP import path was removed and replaced by from mcp.server import MCPServer. Tool errors use from mcp.server.mcpserver.exceptions import ToolError.
  • TypeScript SDK v2 (@modelcontextprotocol/server): Replaces the monolithic v1 @modelcontextprotocol/sdk package and pairs with zod/v4 and the serveStdio() factory helper so your server automatically supports both legacy 2025-11-25 clients and modern 2026-07-28 clients.

MCP architecture: Tools, Resources, and Prompts explained

Every MCP integration connects three pieces: the Host (your AI app, such as Claude Desktop, Claude Code, Cursor, or a web agent), an internal Client (one client instance per connected server), and your Server (the lightweight program you write). Inside your server, you expose up to three standard primitives documented in the official Model Context Protocol server guide:

  • Tools (Model-controlled actions): Executable functions with strict JSON Schema inputs (such as querying a PostgreSQL table, fetching weather alerts, or creating a GitHub issue). The LLM decides when to call a tool, and the host asks the user for permission on risky actions.
  • Resources (Application-controlled read-only data): File-like context identified by a URI (such as file:///project/config.json or db://orders/latest). Resources supply read-only context without causing side effects.
  • Prompts (User-controlled reusable templates): Pre-written instruction workflows that hosts surface as slash commands (for example, /code-review or /sql-audit).
2026 MCP Server architecture diagram and comparison matrix for stdio, Streamable HTTP 2026-07-28 stateless spec, and deprecated HTTP+SSE
2026 MCP server architecture comparing local stdio subprocesses, stateless Streamable HTTP (2026-07-28 spec), and legacy HTTP+SSE.

How to build an MCP server in Python (Official SDK v2 + uv)

Python is the fastest path to a working MCP server because the official Python SDK v2 converts your standard Python type hints and docstrings into valid JSON Schemas automatically. Make sure you have Python 3.10+ and uv installed.

Step 1: Initialize the Python project and install mcp[cli]

# Create and activate an isolated project with uv
uv init my-mcp-server
cd my-mcp-server
uv venv
source .venv/bin/activate   # On Windows PowerShell: .venv\Scripts\Activate.ps1

# Install Official MCP Python SDK v2 (2.0.0+)
uv add "mcp[cli]"
mcp version

Step 2: Write server.py with MCPServer, typed tools, and stderr logging

Create server.py in your project root. Notice two critical rules from the official MCP build guide: never call print() in a stdio server (always use Python’s logging module, which writes safely to stderr), and raise ToolError when an external API fails so the model receives a clean recovery message.

import logging
from typing import Any
import httpx2
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

# Always log to stderr, never stdout
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize MCPServer (SDK v2 replaces FastMCP)
mcp = MCPServer("dev-utility-server")

@mcp.tool()
def calculate_margin(revenue: float, cost: float) -> dict[str, Any]:
    """Calculate gross profit and gross margin percentage from revenue and cost."""
    if revenue <= 0:
        raise ToolError("Revenue must be greater than zero.")
    profit = round(revenue - cost, 2)
    margin_pct = round((profit / revenue) * 100, 2)
    logger.info("Calculated margin: %s%%", margin_pct)
    return {"profit": profit, "margin_percent": margin_pct}

@mcp.tool()
async def get_weather_alerts(state: str) -> str:
    """Fetch active US National Weather Service alerts for a two-letter state code (e.g. CA, NY)."""
    code = state.strip().upper()
    if len(code) != 2:
        raise ToolError("Provide a valid two-letter US state code such as CA or NY.")
    url = f"https://api.weather.gov/alerts/active/area/{code}"
    headers = {"User-Agent": "iconic18-mcp-demo/1.0", "Accept": "application/geo+json"}
    async with httpx2.AsyncClient(follow_redirects=True) as client:
        resp = await client.get(url, headers=headers, timeout=20.0)
        if resp.status_code != 200:
            raise ToolError(f"NWS API returned HTTP {resp.status_code}.")
        features = resp.json().get("features", [])
    if not features:
        return f"No active weather alerts for {code}."
    return "\n---\n".join(
        f"{f['properties'].get('event', 'Alert')}: {f['properties'].get('headline', '')}"
        for f in features[:5]
    )

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

If you run uv run server.py directly, the terminal will sit quietly waiting for JSON-RPC input on stdin. That means it is working; press Ctrl+C and move on to testing with MCP Inspector below.

How to build an MCP server in TypeScript (@modelcontextprotocol/server + Zod)

If your backend already runs on Node.js, Cloudflare Workers, Vercel, or Next.js, the official TypeScript SDK v2 gives you compile-time type safety plus runtime input validation via Zod. You will need Node.js 22+ (so both the server and MCP Inspector v2 run smoothly).

Step 1: Initialize the ESM TypeScript project

mkdir ts-mcp-server
cd ts-mcp-server
npm init -y
npm pkg set type=module
npm pkg set scripts.build="tsc"

# Install Official TypeScript SDK v2 + Zod
npm install @modelcontextprotocol/server zod
npm install -D typescript tsx @types/node
mkdir src

Create tsconfig.json in the project root with "types": ["node"] included explicitly (required in newer TypeScript releases):

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "outDir": "./build",
    "rootDir": "./src",
    "types": ["node"],
    "skipLibCheck": true
  },
  "include": ["src"]
}

Step 2: Create src/index.ts with createServer() and serveStdio()

As verified in the 2026-07-28 TypeScript quickstart and InterviewBit’s SDK v2 benchmark, wrap your tool registrations inside a createServer() factory function and pass it to serveStdio() instead of calling legacy server.connect(). That ensures your server speaks both 2025-11-25 and stateless 2026-07-28 protocol revisions automatically:

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

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

  server.registerTool(
    "calculate_margin",
    {
      description: "Calculate gross profit and margin percentage from revenue and cost",
      inputSchema: z.object({
        revenue: z.number().positive().describe("Total revenue in USD"),
        cost: z.number().min(0).describe("Total cost in USD"),
      }),
    },
    async ({ revenue, cost }) => {
      const profit = Number((revenue - cost).toFixed(2));
      const marginPct = Number(((profit / revenue) * 100).toFixed(2));
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify({ profit, margin_percent: marginPct }),
          },
        ],
      };
    }
  );

  return server;
}

serveStdio(createServer);
console.error("dev-utility-ts MCP server running on stdio");

Compile with npm run build (creating build/index.js) or run live during development with npx tsx src/index.ts.

Python vs TypeScript: which MCP SDK should you pick?

Both Python and TypeScript are Tier 1 official SDKs maintained directly alongside C# and Go (Stellagent 2026 SDK Tier Audit). Pick the runtime that already hosts your data or internal API clients:

FactorPython MCP SDK v2 (mcp)TypeScript MCP SDK v2 (@modelcontextprotocol/server)
Core Server ClassMCPServer (replaced v1 FastMCP)McpServer + serveStdio() factory
Input Schema ValidationPython type hints + Pydanticzod/v4 runtime schemas + TypeScript types
Best Ecosystem FitData science, local LLMs, SQL/Pandas, AI agentsNode.js web apps, Next.js, Express, Hono, Cloudflare Workers
Safe Local Logginglogging.getLogger(__name__) (writes to stderr)console.error() (writes to stderr)
Remote HTTP Deploymentmcp.run(transport="streamable-http") / FastAPIExpress, Hono, Fastify, or Cloudflare Workers edge runtime

How to test and debug with MCP Inspector v2 (Web, CLI, and TUI)

Never wire an untested server straight into Claude Desktop or Cursor and guess why tools are missing. Always test your server first with MCP Inspector v2 (@modelcontextprotocol/inspector), which runs via npx with zero global install and supports three interfaces (Web UI, scriptable --cli for CI, and interactive --tui in the terminal):

# 1. Open the interactive Web UI against your Python or TypeScript server
npx @modelcontextprotocol/inspector uv run server.py
npx @modelcontextprotocol/inspector npx tsx src/index.ts

# 2. Run a deterministic CLI check (great for CI pipelines)
npx @modelcontextprotocol/inspector --cli uv run server.py \
  --method tools/call --tool-name calculate_margin \
  --tool-arg revenue=1000 --tool-arg cost=350

# 3. Inspect a remote Streamable HTTP MCP server
npx @modelcontextprotocol/inspector --server-url https://api.example.com/mcp --transport http

Before moving to a host app, verify four things in the Inspector: every tool appears under tools/list with clear descriptions, valid inputs return clean JSON/text, invalid types return a graceful isError: true response without crashing the process, and raw JSON-RPC frames show zero stray debug text mixed into stdout.

How to connect your local MCP server to Claude Desktop, Cursor, and Claude Code

Once your server passes MCP Inspector, register it in your AI host’s JSON config file using absolute paths (never relative paths like ./server.py, because desktop apps launch subprocesses from a different working directory):

  • Claude Desktop config path: ~/Library/Application Support/Claude/claude_desktop_config.json (macOS), ~/.config/Claude/claude_desktop_config.json (Linux), or %APPDATA%\Claude\claude_desktop_config.json (Windows).
  • Cursor / Claude Code: Add the same mcpServers block to .cursor/mcp.json or your project’s .mcp.json file.
{
  "mcpServers": {
    "dev-utility-python": {
      "command": "uv",
      "args": [
        "--directory",
        "/ABSOLUTE/PATH/TO/my-mcp-server",
        "run",
        "server.py"
      ]
    },
    "dev-utility-ts": {
      "command": "node",
      "args": [
        "/ABSOLUTE/PATH/TO/ts-mcp-server/build/index.js"
      ],
      "env": {
        "EXAMPLE_API_KEY": "your-scoped-key-here"
      }
    }
  }
}

Save the file and restart Claude Desktop or reload Cursor. You can also test your custom MCP server alongside free local coding models using our Claude Code + Local Ollama Setup Guide, or explore 25 production-ready servers in our 25 Best MCP Servers on GitHub in 2026. Need quick browser-side developer utilities while testing JSON schemas? Try our Free Browser AI Tools and browse our GitHub Repo Directory.

Moving to production: Streamable HTTP, OAuth 2.1, and security rules

Local stdio servers are ideal for one developer on one laptop, but they break down when 50 team members need access to a shared CRM, billing database, or WordPress backend. For remote multi-user servers, switch to Streamable HTTP (POST /mcp) and apply four mandatory security controls from the 2026 MCP production security checklist and Wati’s transport engineering guide:

  • Enforce OAuth 2.1 with PKCE (S256 only): Never expose an unauthenticated remote /mcp endpoint, and never use a session ID or custom query token as authentication. Expose /.well-known/oauth-protected-resource (RFC 9728) so clients discover your authorization server automatically.
  • Validate the Origin header on every request: Reject unexpected browser origins to block DNS rebinding attacks against locally bound HTTP MCP servers.
  • Keep business state outside process memory: Because the 2026-07-28 spec removed protocol sessions, store multi-step workflow state (like a cart ID or async job ID) in Redis or PostgreSQL and return an explicit opaque ID in the tool result bound to the authenticated user.
  • Deploy to edge or container targets: Cloudflare Workers (100,000 free daily requests), Vercel, Fly.io, and Dockerized FastAPI/Hono containers all scale stateless Streamable HTTP servers cleanly behind standard HTTPS load balancers.

5 common mistakes that break new MCP servers (and how to fix them)

  1. Printing debug text to stdout: Over stdio, stdout belongs strictly to JSON-RPC frames. One stray print("debug") or console.log() crashes the client parser. Always route logs to stderr.
  2. Using relative file paths in client configs: Replace ./build/index.js with full absolute paths (/Users/name/... or C:\\Projects\\...) in claude_desktop_config.json.
  3. Exposing raw SQL or shell execution tools: Never give an LLM an unrestricted run_sql tool connected to an admin database role. Expose narrow, parameterized tools (like get_order_status(order_id)) backed by a read-only database user.
  4. Writing vague tool docstrings: The LLM chooses which tool to invoke solely by reading your tool name, docstring, and parameter .describe() hints. Treat docstrings as prompt engineering.
  5. Ignoring prompt injection in returned tool output: If your MCP tool scrapes external web pages or reads customer support tickets, sanitize HTML and strip untrusted instructions before returning the text to the host model.

My Opinion

The biggest trap I see developers fall into when learning how to build an MCP server is over-engineering on day one. You do not need 40 tools, a custom OAuth provider, and a Kubernetes cluster to prove value. In fact, exposing 40 overlapping tools on a single MCP server bloats the host model’s context window with thousands of schema tokens and makes tool selection noticeably worse.

Start small and sharp. Pick one repetitive internal lookup or workflow your team does 20 times a day, wrap it in three to five tightly scoped read-only tools using Python SDK v2 (MCPServer) or TypeScript SDK v2 (@modelcontextprotocol/server), and test every edge case inside npx @modelcontextprotocol/inspector --cli before anyone touches Claude Desktop. Once that 80-line stdio server saves your team real hours, flipping the transport to stateless Streamable HTTP behind OAuth 2.1 takes an afternoon instead of a month.

Frequently Asked Questions

Why did my Python MCP server fail with “cannot import name FastMCP”?

In Python MCP SDK v2 (mcp >= 2.0.0), the old FastMCP class was renamed to MCPServer and the legacy import path was removed. Change your import to from mcp.server import MCPServer, or pin mcp<2 if you are maintaining an older v1 repository.

What is the difference between @modelcontextprotocol/sdk and @modelcontextprotocol/server?

@modelcontextprotocol/sdk was the monolithic TypeScript SDK v1 package. In TypeScript SDK v2, server code moved into the dedicated @modelcontextprotocol/server package paired with zod/v4 and serveStdio() to support the 2026-07-28 stateless specification.

Should I use stdio or Streamable HTTP for my MCP server?

Use stdio when one developer runs the server locally on their own machine (for local files, Git, or SQLite). Use Streamable HTTP (POST /mcp) when multiple users connect over a network, when the server holds shared secrets users should not see, or when deploying to Cloudflare Workers, Vercel, or Docker.

Is HTTP+SSE still supported in MCP in 2026?

No. The legacy 2024-11-05 HTTP+SSE transport was deprecated in March 2025 and replaced by Streamable HTTP. Under the 2026-07-28 stateless revision, servers expose a single POST endpoint that can return either a JSON object or a request-scoped SSE stream.

Why does my stdio MCP server disconnect immediately with a JSON parse error?

Because something in your code (or a third-party library) wrote plain text to stdout. Over stdio, standard output can carry only newline-delimited JSON-RPC messages. Replace every print() in Python with logging.info() and every console.log() in TypeScript with console.error().

How do I test an MCP server without restarting Claude Desktop every time?

Run MCP Inspector v2 directly in your terminal with npx @modelcontextprotocol/inspector uv run server.py (Web UI) or npx @modelcontextprotocol/inspector --cli ... --method tools/call (CLI). It lets you inspect tool schemas, test invalid inputs, and view raw JSON-RPC frames in seconds.

How do stateless 2026 MCP servers handle multi-step workflows?

Since the 2026-07-28 specification removed protocol-level sessions (Mcp-Session-Id), return an explicit identifier (such as a job_id or draft_id) in your tool output, store the underlying state in Redis or a database tied to the authenticated user, and accept that ID as an argument on follow-up tool calls.

How do I secure a remote MCP server in production?

Serve all traffic over HTTPS, enforce OAuth 2.1 with PKCE (S256), publish /.well-known/oauth-protected-resource metadata (RFC 9728), validate the Origin header, apply least-privilege database/API credentials, and sanitize untrusted tool outputs against prompt injection.

Can one MCP server work across Claude Desktop, Claude Code, Cursor, and Gemini CLI?

Yes. Because MCP standardizes tool discovery (server/discover and tools/list) and execution (tools/call) over JSON-RPC 2.0, you write and test your server once and connect it to any MCP-compatible host without changing a line of server code.

Leave a Comment