How to Build an MCP Server in Python and TypeScript
Table of content
Learning how to build an MCP server starts with choosing an official SDK, registering typed functions or schemas as tools and resources, and binding a JSON-RPC transport such as stdio or Streamable HTTP. With the current Python and TypeScript SDK releases, you can expose external APIs, local filesystems, or enterprise databases to LLM applications in a few dozen lines of code without writing custom model-specific glue.
This guide is for software developers, engineering managers, and technical founders evaluating or implementing Model Context Protocol integrations. By the end, you will know how to write, test, and secure a working server in both Python and TypeScript, inspect its JSON-RPC payloads, and wire it into desktop and IDE clients.
What is an MCP server and what primitives can it expose?
An MCP server is a lightweight program that exposes external tools, data, and message templates to LLM host applications over the open-source Model Context Protocol without talking to the AI model directly. Hosted by The Linux Foundation as a Series of LF Projects, LLC, the Model Context Protocol specification standardizes how AI applications connect to external data sources, tools, and workflows. As of November 2026, the latest version of the specification is 2026-07-28. If you are new to the protocol’s conceptual design, read our overview on what MCP is in AI before writing your first server.
The architecture separates responsibilities across three distinct participants: * Host: the LLM application that the end user interacts with, such as Claude Desktop, VS Code, or Cursor. * Client: the connector living inside the host that maintains a 1:1 connection with a single server. * Server: the standalone program you build to expose capabilities over a standard transport without communicating with the language model itself.
In any MCP server tutorial, you will work with three core primitives that the server can expose to a connected client: * Tools: model-controlled functions that the LLM can invoke (with user approval) to perform actions or query live APIs. * Resources: application-controlled, file-like data sources that the client reads directly into the conversation context. * Prompts: user-controlled, pre-written message templates that a user invokes by name inside the host interface.
Which official MCP SDK should you choose?
As of November 2026, six languages hold Tier 1 status in the Model Context Protocol ecosystem (Python, TypeScript, C#, Go, Rust, and Ruby), with the Python and TypeScript SDKs serving as the primary reference implementations. The MCP project classifies its official SDKs into tiers based on feature completeness and maintenance commitment. Tier 1 comprises TypeScript, Python, C#, Go, Rust, and Ruby; Tier 2 covers Java; and Tier 3 includes Swift, PHP, and Kotlin. When selecting a runtime for production systems, align your choice with your existing backend software development technologies so your server can share domain models and internal client libraries.
Both the Python and TypeScript ecosystems have moved to major version 2 releases as of November 2026. In Python, the latest v2 release is v2.3.0, which requires Python 3.11+ on the main branch after dropping Python 3.10 support in October 2026 (while the general server quickstart notes Python 3.10+ with MCP SDK 2.0.0+). In TypeScript, the latest v2 release is v2.4.0, which splits the older v1 monolithic @modelcontextprotocol/sdk package into dedicated @modelcontextprotocol/server and @modelcontextprotocol/client packages. If you maintain existing Node.js servers on the v1.x branch (@modelcontextprotocol/sdk), that branch continues to receive bug fixes and security updates for at least six months following the July 27, 2026 v2 release.
Engineering teams auditing open-source compliance should also note a licensing transition across the ecosystem. The MCP project is transitioning its licensing from the MIT License to the Apache License 2.0 for all new code and specification contributions, and to CC-BY-4.0 for documentation. During this transition, the Python SDK remains under the MIT License, while the TypeScript SDK v2 is published under Apache-2.0.
| Criterion | Python SDK (mcp) |
TypeScript SDK (@modelcontextprotocol/server) |
stdio Transport |
Streamable HTTP Transport |
|---|---|---|---|---|
| Runtime requirements (as of Nov 2026) | Python 3.11+ on main branch (3.10+ in general quickstart); latest v2.3.0 | Node.js 20+ (also Bun and Deno), ES modules only ("type": "module"); latest v2.4.0 |
Local subprocess launched by the client | HTTP server endpoint accessible to one or more clients |
| Core package & installation | uv add "mcp[cli]" or pip install "mcp[cli]" |
@modelcontextprotocol/server (split from v1 @modelcontextprotocol/sdk) |
Included in core server packages (serveStdio in TS) |
Core SDK plus optional TS adapters (@modelcontextprotocol/express, hono, fastify, node) |
| Schema definition & validation | Automatic JSON Schema generation and input validation from Python type hints and docstrings | Standard Schema support (Zod v4, Valibot, ArkType) passed to server.registerTool() |
N/A (transport layer) | N/A (transport layer) |
| Message framing & network model | Handled by MCPServer over chosen transport |
Handled by McpServer over chosen transport |
Newline-delimited UTF-8 JSON-RPC over stdin/stdout |
UTF-8 JSON-RPC via HTTP POST to a single endpoint; replies via JSON or request-scoped SSE |
| Authentication & credential handling | Depends on transport (env vars for stdio, OAuth 2.1 for HTTP) |
Depends on transport; HTTP adapters validate Host/Origin headers | Environment variables; do not use HTTP OAuth 2.1 | Optional OAuth 2.1 resource server validating audience claims |
| License | MIT License | Apache-2.0 | Specification under Apache-2.0 / CC-BY-4.0 transition | Specification under Apache-2.0 / CC-BY-4.0 transition |
How to build an MCP server in Python with SDK v2
You build a Python MCP server by installing the mcp[cli] package, instantiating MCPServer from mcp.server, and decorating typed Python functions with @mcp.tool() or @mcp.resource(). The MCPServer class inspects your Python function type hints and docstrings to generate JSON Schema tool definitions, parse incoming requests, and validate inputs automatically without manual schema boilerplate.
Follow these steps from the official MCP server build guide to understand how to build an MCP server in Python:
- Initialize a Python project (Python 3.11+ recommended for the v2.3.0 main branch, or Python 3.10+ per the general quickstart) and install the SDK with the
cliextra. Installingmcp[cli]provides themcpcommand-line tool (mcp dev,mcp run,mcp install).
uv init my-mcp-server
cd my-mcp-server
uv add "mcp[cli]"
- Create a
server.pyfile, importMCPServerfrommcp.server, and register both a tool and a dynamic resource using decorators.
import sys
from mcp.server import MCPServer
# Initialize the MCPServer instance
mcp = MCPServer("release-notes-server")
@mcp.tool()
def calculate_error_budget(total_requests: int, failed_requests: int) -> str:
"""Calculate the remaining error budget percentage from request counts."""
if total_requests <= 0:
raise ValueError("total_requests must be greater than zero.")
failure_rate = (failed_requests / total_requests) * 100
print(f"Calculated failure rate: {failure_rate:.4f}%", file=sys.stderr)
return f"Failure rate is {failure_rate:.4f}%"
@mcp.resource("config://{service_name}")
def get_service_config(service_name: str) -> str:
"""Return configuration metadata for a given service name."""
return f"Service: {service_name}\nStatus: active"
if __name__ == "__main__":
mcp.run()
- Notice how
sys.stderris used for logging inside the tool handler. In anystdio-based MCP server, writing to standard output (stdout) via a standardprint()call corrupts the newline-delimited JSON-RPC message stream and breaks the connection. Always write diagnostic logs tostderror to a log file.
How to build an MCP server in TypeScript with SDK v2
In the TypeScript SDK, you build a server by installing @modelcontextprotocol/server, defining tool input schemas with a Standard Schema library such as Zod v4 via server.registerTool(), and binding a transport with serveStdio. The TypeScript SDK requires Node.js 20 or later (it also runs on Bun and Deno) and ships exclusively as ES modules, meaning your package.json must include "type": "module".
Follow the steps below, based on the MCP TypeScript SDK first server guide, to create a TypeScript server:
- Create a new Node.js 20+ project configured for ES modules and install
@modelcontextprotocol/serveralongside a Standard Schema validation library such as Zod v4 (or Valibot or ArkType).
mkdir ts-mcp-server && cd ts-mcp-server
npm init -y
npm pkg set type="module"
npm install @modelcontextprotocol/server zod
npm install -D typescript tsx @types/node
- Create
src/index.tsand implement a factory function that constructs anMcpServer, registers a tool withserver.registerTool(name, config, handler), and passes the factory toserveStdio(createServer)from@modelcontextprotocol/server/stdio.
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
function createServer(): McpServer {
const server = new McpServer({
name: "deployment-audit-server",
version: "1.0.0",
});
server.registerTool(
"check_service_quota",
{
description: "Verify whether a service is within its request quota.",
inputSchema: z.object({
serviceId: z.string(),
currentUsage: z.number(),
limit: z.number(),
}),
},
async ({ serviceId, currentUsage, limit }) => {
console.error(`Checking quota for ${serviceId}`);
if (limit <= 0) {
return {
isError: true,
content: [{ type: "text", text: "Quota limit must be positive." }],
};
}
const remaining = limit - currentUsage;
return {
content: [
{
type: "text",
text: `Service ${serviceId} has ${remaining} units remaining.`,
},
],
};
}
);
return server;
}
serveStdio(createServer);
- Review the return structure and logging in the handler above. Tool handlers return an object containing
{ content: [{ type: 'text', text: '...' }] }and can set an optionalisError: trueflag when an operation fails. Just asprint()breaks Pythonstdioservers, callingconsole.log()in TypeScript writes tostdoutand corrupts the JSON-RPC stream, so useconsole.error()to direct logs tostderr. When you later move fromstdioto HTTP, the TypeScript SDK also publishes thin middleware adapter packages (@modelcontextprotocol/node,@modelcontextprotocol/express,@modelcontextprotocol/fastify, and@modelcontextprotocol/hono) that provide Streamable HTTP wrappers and Host/Origin header validation.
How do you test and debug a server with the MCP Inspector?
You can test any MCP server locally without spinning up an LLM host by running @modelcontextprotocol/inspector via npx or uv run mcp dev, which launches a browser UI, CLI, or terminal UI to inspect JSON-RPC traffic and execute tools.
The MCP Inspector (@modelcontextprotocol/inspector) is the official reference testing and debugging tool. Current releases require Node.js 22.23.4 or later on the 22.x line (or 24.22.1+ / 26.12.1+) and provides three interfaces behind a single binary:
* Browser Web UI (launched by default).
* Scriptable CLI (invoked with --cli).
* Interactive terminal UI (invoked with --tui).
To test your Python server interactively using the mcp CLI installed earlier, run:
uv run mcp dev server.py
To test your TypeScript server (or any executable server binary) directly with the Inspector, pass the launch command to npx @modelcontextprotocol/inspector:
npx @modelcontextprotocol/inspector npx tsx src/index.ts
If the Inspector fails to complete the initial handshake, check your server output for stray stdout writes from startup banners, debug print() calls, or console.log() statements, which are the primary cause of malformed JSON-RPC streams over stdio.
How to connect your custom MCP server to Claude Desktop and IDEs
To connect a local stdio server to Claude for Desktop, you register its launch command and absolute file paths under the mcpServers key in claude_desktop_config.json and restart the client. Because Claude for Desktop acts as the MCP Host and spawns a Client connection per configured server, it launches your server as a local subprocess.
-
Open or create
claude_desktop_config.jsonat the path for your operating system: * macOS:~/Library/Application Support/Claude/claude_desktop_config.json* Linux:~/.config/Claude/claude_desktop_config.json* Windows:$env:AppData\Claude\claude_desktop_config.json -
Add your Python or TypeScript server under the
mcpServersobject using absolute paths for the server directory:
{
"mcpServers": {
"release-notes-python": {
"command": "uv",
"args": [
"--directory",
"/Users/developer/projects/my-mcp-server",
"run",
"server.py"
]
},
"deployment-audit-ts": {
"command": "npx",
"args": [
"--prefix",
"/Users/developer/projects/ts-mcp-server",
"tsx",
"/Users/developer/projects/ts-mcp-server/src/index.ts"
]
}
}
}
- Save the configuration file and restart Claude for Desktop so the host initializes the client connections and discovers your server’s tools, resources, and prompts. Other MCP hosts such as VS Code and Cursor follow the same host-client-server architecture to connect to local or remote servers.
Stdio vs. Streamable HTTP: which transport and auth model should you use?
Use stdio with environment-variable credentials when the MCP server runs as a local subprocess on the user’s machine, and use Streamable HTTP protected by OAuth 2.1 when deploying a remote, multi-client server. Choosing the right transport and authentication boundary is a core part of designing scalable MCP vs. API integration architectures for production agents.
MCP defines two standard transport bindings that carry UTF-8 encoded JSON-RPC messages:
* stdio: The client launches the MCP server as a subprocess and exchanges newline-delimited JSON-RPC messages over stdin and stdout. Servers using stdio should not follow the HTTP OAuth 2.1 authorization specification; instead, they should retrieve API keys and credentials from the local environment.
* Streamable HTTP: Every client message is sent as an HTTP POST to a single MCP endpoint, and replies arrive either as standard JSON responses or as a request-scoped Server-Sent Events (SSE) stream. In TypeScript, you can mount a Streamable HTTP server using the official middleware adapters (@modelcontextprotocol/node, @modelcontextprotocol/express, @modelcontextprotocol/fastify, or @modelcontextprotocol/hono), which also handle Host and Origin header validation.
When exposing a remote server over HTTP, follow the protocol’s authorization and security rules:
* Validate OAuth 2.1 audience claims: For HTTP-based transports, MCP defines an optional authorization flow where a protected MCP server acts as an OAuth 2.1 resource server. Your server must validate inbound tokens and reject any token that does not specifically include the server in the audience claim.
* Bind non-deterministic session IDs: According to MCP Security Best Practices, servers should generate non-deterministic session handles using secure random number generators and bind session IDs to user-specific identifiers using a format such as <user_id>:<session_id>.
If you build a publicly accessible MCP server or package and want other developers to discover it, you can publish it to the official MCP Registry by creating a server.json file and running the mcp-publisher tool. Private servers restricted to private networks are not supported on the public registry.
Frequently asked questions
Below are direct answers to the most common engineering questions when building, debugging, and securing MCP servers in production.
Why does console.log or print() break a local stdio MCP server?
Writing to standard output (stdout) via print() in Python or console.log() in TypeScript corrupts the newline-delimited UTF-8 JSON-RPC message stream that stdio uses for client-server communication. Because the client parses every line on stdout as a JSON-RPC frame, any plain-text log line causes a protocol parsing failure and breaks the server. Always direct diagnostic logs to stderr (for example, console.error() or print(..., file=sys.stderr)) or write them to a file.
What changed between v1 and v2 of the MCP TypeScript and Python SDKs?
In the TypeScript SDK (v2.4.0 as of November 2026), v2 splits the monolithic v1 @modelcontextprotocol/sdk package into dedicated @modelcontextprotocol/server and @modelcontextprotocol/client packages, adopts Standard Schema (supporting Zod v4, Valibot, and ArkType) in server.registerTool(), and introduces serveStdio(createServer). The TypeScript v1.x branch continues to receive bug fixes and security updates for at least six months after the July 27, 2026 v2 release. In the Python SDK (v2.3.0 as of November 2026), v2 centers on MCPServer from mcp.server, and requires Python 3.11+ on the main branch after dropping Python 3.10 support in October 2026.
How do I secure a remote HTTP MCP server with OAuth 2.1?
Configure your HTTP MCP server as an OAuth 2.1 resource server that validates every inbound bearer token and rejects any token that does not explicitly include your server in its audience claim. In addition to token validation, follow MCP Security Best Practices by generating non-deterministic session handles with a secure random number generator and binding each session ID to a user identifier in the format <user_id>:<session_id>. Do not apply the HTTP OAuth 2.1 flow to local stdio servers; pass credentials to stdio servers via environment variables instead.
Can I publish a private company MCP server to the official MCP Registry?
No, private servers restricted to private networks are not supported on the public MCP Registry. The official MCP Registry only accepts publicly accessible MCP servers or packages, which developers publish by defining a server.json manifest and running the mcp-publisher tool.
Which programming languages have Tier 1 official MCP SDK support?
As of November 2026, six languages hold Tier 1 official MCP SDK status based on feature completeness and maintenance commitment: TypeScript, Python, C#, Go, Rust, and Ruby. Java holds Tier 2 status, while Swift, PHP, and Kotlin are classified in Tier 3.
From a local prototype to a production MCP server
A stdio server on a laptop proves the idea; a shared remote server needs OAuth, audience checks, rate limits, logging, and tools designed around what users actually ask for. If you are planning MCP integrations for internal systems or customer-facing AI products, see our MCP server development page or our AI integration services.