Skip to the content.

MCP Servers Templates: Starter Kits for Building MCP Servers in TypeScript and Python

Two small, tested MCP server templates, one in TypeScript and one in Python, that you can copy and turn into your own Model Context Protocol server in minutes. Each one is a complete working example with tools, resources, a resource template and a prompt, typed input and output schemas, proper error handling, and tests that run the server both in-process and as a real stdio subprocess.

Both templates target the current v2 SDKs (@modelcontextprotocol/server for TypeScript, mcp 2.x with MCPServer for Python). Many tutorials online still show v1 code (@modelcontextprotocol/sdk, FastMCP), so this repo also includes a v1 to v2 cheat sheet. It is for developers who want to expose their APIs, databases or internal tools to Claude, ChatGPT, VS Code, Cursor and other MCP clients.

Last reviewed: December 2026. Tested with @modelcontextprotocol/server 2.4.0 on Node.js 22, and mcp 2.3.0 on Python 3.15. MCP and its SDKs move quickly: check the linked docs if something differs.

Contents

What is MCP?

The Model Context Protocol is an open protocol that lets AI applications (“hosts” such as Claude, IDEs and agent frameworks) connect to external “servers” that provide context and capabilities. Instead of writing a custom plugin for every AI app, you write one MCP server and any MCP-capable client can use it.

A server can offer three kinds of things:

Primitive Who decides to use it What it is Example in the template
Tools The model Functions the model can call, with a JSON Schema for their inputs (and optionally outputs) add_note, search_notes, delete_note
Resources The application or user Read-only data identified by a URI, which the client can attach as context notes://index, notes://{note_id}
Prompts The user Reusable prompt templates, often shown as slash commands or menu items summarize_notes

Messages are JSON-RPC 2.0. The current specification revision is 2026-07-28, which makes requests stateless and self-contained (each request carries its protocol version and capabilities), while SDKs keep compatibility with clients that use older, handshake-based revisions. The official SDKs handle all of this for you; your code only registers tools, resources and prompts.

The two templates at a glance

Both templates implement the same “notes” server so you can compare them line by line.

  TypeScript Python
Folder templates/typescript templates/python
SDK package @modelcontextprotocol/server 2.x mcp 2.x
Server class McpServer MCPServer
Schemas Zod v4 (z.object(...)) Type hints, docstrings and Pydantic models
Expected tool errors Return { isError: true, content } raise ToolError("...")
Missing resource Throw an error raise ResourceNotFoundError("...")
Transports wired stdio (src/index.ts); createServer() factory ready for HTTP stdio by default, Streamable HTTP with --http
Tests node:test via tsx: in-memory client, schema validation, tsc, real stdio subprocess (9 tests) pytest: in-process client, store, real stdio subprocess (8 tests)
Run npm start / node dist/index.js uv run notes-mcp-server
Lines of server code about 190 about 150

Which one should you pick? Use the language of the system you are wrapping. If you are starting fresh: TypeScript has the widest client-side ecosystem and is easy to ship with npx; Python is the natural choice for data, ML and scripting-heavy servers and ships easily with uvx.

Quick start: TypeScript

Requirements: Node.js 20 or newer.

git clone https://github.com/Ralpberry-Labs/mcp-servers-templates.git
cp -r mcp-servers-templates/templates/typescript my-mcp-server
cd my-mcp-server
npm install
npm test        # runs the 9 tests
npm run build   # compiles to dist/

Try it interactively with the official MCP Inspector:

npm run inspect     # = npx @modelcontextprotocol/inspector node dist/index.js

The heart of the TypeScript template (abridged from src/server.ts):

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

export function createServer(store = new NoteStore()): McpServer {
  const server = new McpServer({ name: "notes", version: "0.1.0" });

  server.registerTool(
    "add_note",
    {
      title: "Add note",
      description: "Create a note and return it with its new id.",
      inputSchema: z.object({
        title: z.string().describe("Short title, up to 200 characters"),
        body: z.string().describe("Note text, up to 20,000 characters"),
        tags: z.array(z.string()).optional(),
      }),
      outputSchema: NoteSchema,
      annotations: { readOnlyHint: false, destructiveHint: false },
    },
    async ({ title, body, tags }) => {
      try {
        const note = store.add(title, body, tags ?? []);
        return { content: [{ type: "text", text: JSON.stringify(note) }], structuredContent: note };
      } catch (err) {
        return { content: [{ type: "text", text: (err as Error).message }], isError: true };
      }
    },
  );
  // ... search_notes, delete_note, resources and a prompt
  return server;
}

And the stdio entry point (src/index.ts):

import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
import { createServer } from "./server.js";

await createServer().connect(new StdioServerTransport());
console.error("notes MCP server running on stdio"); // stderr, never stdout

Quick start: Python

Requirements: Python 3.10 or newer. uv is recommended but optional.

cp -r mcp-servers-templates/templates/python my-mcp-server
cd my-mcp-server
uv sync --extra dev
uv run pytest                                   # 8 tests
uv run notes-mcp-server                         # stdio
uv run notes-mcp-server --http --port 8000      # Streamable HTTP

Without uv:

python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest

The heart of the Python template (abridged from src/notes_server/server.py):

from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ResourceNotFoundError, ToolError
from mcp.types import ToolAnnotations
from pydantic import BaseModel

mcp = MCPServer("notes", instructions="A small note store. Use search_notes before add_note.")

class NoteOut(BaseModel):
    id: str
    title: str
    body: str
    tags: list[str]

@mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=False))
def add_note(title: str, body: str, tags: list[str] | None = None) -> NoteOut:
    """Create a note and return it with its new id."""
    try:
        note = store.add(title, body, tags)
    except ValueError as exc:
        raise ToolError(str(exc)) from exc   # the model sees this message
    return NoteOut(**vars(note))

@mcp.resource("notes://{note_id}", mime_type="text/markdown")
def read_note(note_id: str) -> str:
    """One note rendered as Markdown."""
    note = store.get(note_id)
    if note is None:
        raise ResourceNotFoundError(f"note {note_id} does not exist")
    return f"# {note.title}\n\n{note.body}"

@mcp.prompt()
def summarize_notes(topic: str) -> str:
    """Ask the model to summarize everything the notes say about a topic."""
    return f"Use the search_notes tool to find notes about '{topic}' and summarize them."

if __name__ == "__main__":
    mcp.run()          # stdio; mcp.run(transport="streamable-http", port=8000) for HTTP

Connect the server to a client

Use absolute paths in client configs: clients start your server from their own working directory. Example config files are in examples/client-configs/.

Client How to add a local stdio server
Claude Code claude mcp add notes -- node /abs/path/dist/index.js (add -s project to write a shared .mcp.json, -s user for all projects)
Claude Desktop Edit claude_desktop_config.json and add the server under "mcpServers" (example), then restart the app
VS Code (GitHub Copilot agent mode) Add .vscode/mcp.json with a "servers" object (example)
Cursor Add .cursor/mcp.json (project) or ~/.cursor/mcp.json (global) with an "mcpServers" object, same shape as the Claude Desktop example
Any SDK client StdioClientTransport (TypeScript) or StdioServerParameters with Client (Python), as in the templates’ tests

Claude Code examples:

# TypeScript template, this project only
claude mcp add notes -- node /abs/path/my-mcp-server/dist/index.js

# Python template with an environment variable
claude mcp add -e NOTES_FILE=/abs/path/notes.json notes-py -- uv run --directory /abs/path/my-mcp-server notes-mcp-server

# A server you are running over HTTP
claude mcp add --transport http notes-http http://127.0.0.1:8000/mcp

Each client documents its own config format; see Where to go next for links.

Anatomy of the template

Both templates use the same structure, which scales well beyond a toy:

store       pure business logic, no MCP imports  -> unit-testable, reusable
server      registers tools/resources/prompts     -> thin adapter: validate, call store, shape result
index/main  picks a transport and starts          -> stdio for local, HTTP for remote
tests       in-process client + real subprocess   -> protocol-level confidence

Why separate the store? Your server is an adapter around something that already exists (an API, a database, a CLI). Keeping MCP out of that code means you can test it normally, reuse it elsewhere, and swap SDK versions without touching business logic.

Things the templates do deliberately:

Tools, resources and prompts: when to use which

You want to… Use Why
Let the model take an action (create, update, send, run) Tool The model decides when; annotations communicate risk
Let the model look something up with parameters Tool (read-only) Models call tools much more reliably than they request resources
Let a user attach a document, file or record as context Resource The application controls what goes into context
Expose a family of records by ID Resource template (notes://{id}) One handler serves many URIs; a list callback lets clients browse
Offer a reusable workflow the user starts on purpose Prompt Shows up as a slash command or menu item in many clients

Client support varies: tools are supported almost everywhere, while resources and prompts are surfaced differently (or not at all) by some clients. If something must work everywhere, make it a tool, and optionally also a resource.

Designing good tools

The model only sees your tool’s name, description and schemas. Design for that reader.

  1. Name by intent, not by endpoint. search_notes beats get_v2_notes_query. Use snake_case verbs, and prefix with a namespace if you expect many servers (notes_search).
  2. Fewer, higher-level tools. One create_invoice that does the three API calls internally beats three low-level tools the model must chain correctly. Aim for a handful of tools per server, not dozens.
  3. Describe like documentation for a new colleague. Say what it does, when to use it, what it returns and important limits: “Returns at most 50 results, best matches first”.
  4. Constrain inputs. Enums instead of free strings, minimum and maximum values, formats (date, uri), and defaults. Validation failures should produce messages the model can act on.
  5. Return compact, relevant output. Do not dump whole API responses. Return the fields the model needs, paginate large results, and include IDs the model can pass to follow-up calls.
  6. Make errors actionable. “note 42 does not exist; use search_notes to find ids” is better than “404”.
  7. Be idempotent where you can. Models retry. Accept a client-supplied idempotency key for operations that must not happen twice.
  8. Mark destructive tools. Set destructiveHint: true so clients can ask for confirmation, and consider a dry-run parameter.
  9. Keep secrets out of arguments. Credentials belong in environment variables or the transport’s auth, never in tool inputs the model can see or log.

A before and after:

Weak Strong
name: "query", description: "Query the DB", input: { sql: string } name: "find_customers", description: "Find customers by name or email. Returns up to 20 matches with id, name, email and plan.", input: { text: string, plan?: "free" \| "pro" \| "team", limit?: 1..20 }

The weak version invites SQL injection, returns unpredictable shapes, and gives the model no idea when to use it.

Error handling in the v2 SDKs

There are two kinds of failure, and they should be reported differently:

Kind Example Report as The model sees
Tool execution error (expected, recoverable) Validation failed, item not found, rate limited A tool result with isError: true Your message, and can retry or change approach
Protocol error Unknown tool, malformed request A JSON-RPC error The client handles it; the model may not see details

How each template does it:

Keep error messages free of secrets, internal hostnames and stack traces; they go to the model and may be shown to the user.

Transports: stdio vs Streamable HTTP

  stdio Streamable HTTP
How it runs The client launches your server as a subprocess and talks over stdin and stdout Your server is a web service; each message is an HTTP POST to one endpoint (often /mcp)
Best for Local tools, developer machines, desktop apps, anything touching local files Shared or remote servers, SaaS integrations, many users
Auth Inherits the user’s local environment (env vars, files) Needs real authentication; MCP specifies OAuth-based authorization for HTTP
Scaling One process per client Normal web scaling; stateless requests in the 2026-07-28 revision make this simpler
Template support Both templates Python: --http; TypeScript: use createServer() with an HTTP adapter

The older “HTTP+SSE” transport from early versions of MCP has been superseded by Streamable HTTP. The Python SDK still offers transport="sse" for old clients; prefer Streamable HTTP for anything new.

For HTTP in TypeScript, the v2 SDK provides optional adapters for common frameworks: @modelcontextprotocol/express, @modelcontextprotocol/hono, @modelcontextprotocol/fastify and @modelcontextprotocol/node. Follow the SDK’s serving guide for current wiring.

For local HTTP servers: bind to 127.0.0.1 (the Python template’s default), not 0.0.0.0, and keep the SDK’s DNS-rebinding and Origin protections enabled.

Testing your server

Test at three levels. The templates include examples of each.

1. Unit tests for the store. Plain tests, no MCP. Fast and the place for most edge cases.

2. In-process protocol tests. Connect a real MCP client to your server object without spawning a process:

from mcp import Client

async with Client(srv.mcp) as client:            # pass the MCPServer instance directly
    result = await client.call_tool("add_note", {"title": "x", "body": "y"})
    assert not result.is_error
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";

const [clientT, serverT] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: "test", version: "1.0.0" });
await Promise.all([createServer().connect(serverT), client.connect(clientT)]);
const result = await client.callTool({ name: "add_note", arguments: { title: "x", body: "y" } });

These catch schema mistakes, wrong result shapes and error handling bugs.

3. End-to-end over stdio. Spawn the real entry point, as a client would. This catches the classic bug of printing to stdout, broken imports and missing executables. See test_stdio_end_to_end and the “stdio end to end” test.

Manual exploration with the MCP Inspector:

npx @modelcontextprotocol/inspector node dist/index.js          # TypeScript
npx @modelcontextprotocol/inspector uv run notes-mcp-server     # Python

Model-level evaluation. Once the protocol works, test whether a model actually picks the right tool with the right arguments for realistic requests. Keep a small list of prompts and expected tool calls, and re-run it when you change names or descriptions.

Logging without breaking stdio

In stdio mode, stdout is the protocol channel. A single print() or console.log() corrupts the stream and the client disconnects with a confusing parse error.

Clients usually show or save a server’s stderr. Claude Code, for example, can show MCP server status with /mcp.

Security checklist

An MCP server runs with real permissions on behalf of a model that can be manipulated by whatever text it reads. Treat every tool call as untrusted input.

The specification’s security best practices page covers attacks such as confused deputy and token passthrough in detail.

Packaging and publishing

Channel How Users run it with
npm Set "bin" in package.json (the template does), npm publish npx -y your-package
PyPI [project.scripts] entry (the template has one), uv build and uv publish uvx your-package
Docker Build an image whose entrypoint starts the server on stdio or HTTP docker run -i --rm your-image
MCP Registry Publish metadata (server.json) with the mcp-publisher CLI, pointing to your npm, PyPI or container package Clients and catalogs that read the registry

The official MCP Registry lists published servers. Namespaces are verified: io.github.<user>/... requires GitHub login as that user, and domain namespaces require a DNS or HTTP challenge. See the registry repository for the current publishing guide.

Before publishing, double-check: the package name is unique, the README documents every tool and required environment variable, and the server starts cleanly with no network access when it does not need it.

Migrating from v1 SDK code

Most blog posts and many examples still use v1 APIs. The main renames:

Python (mcp 1.x to 2.x)

v1 v2
from mcp.server.fastmcp import FastMCP from mcp.server.mcpserver import MCPServer
FastMCP("Demo") MCPServer("Demo") (pass instructions= by keyword)
FastMCP("Demo", port=9000, stateless_http=True) mcp.run(transport="streamable-http", port=9000, stateless_http=True) (transport options moved to run())
ctx = mcp.get_context() declare a ctx: Context parameter
await ctx.info("msg", extra={...}) await ctx.info({"message": "msg", ...})
McpError(ErrorData(code, msg)) MCPError(code, msg)
result.isError, tool.inputSchema result.is_error, tool.input_schema
read_resource(AnyUrl("x://y")) read_resource("x://y")
streamablehttp_client streamable_http_client
Any exception text reached the model Only ToolError messages reach the model; other exceptions are crashes

In v2, importing mcp.server.fastmcp raises an error that points to the migration guide. To keep running v1 code, pin mcp<2.

TypeScript (@modelcontextprotocol/sdk 1.x to v2 packages)

v1 v2
@modelcontextprotocol/sdk (one package) @modelcontextprotocol/server, @modelcontextprotocol/client (split packages)
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { McpServer } from "@modelcontextprotocol/server"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js" import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"
server.tool(name, shape, handler) (deprecated) server.registerTool(name, { inputSchema: z.object({...}) }, handler)
inputSchema: { a: z.number() } (raw shape) inputSchema: z.object({ a: z.number() }) (raw shapes are deprecated)
Zod 3 Zod v4 (import * as z from "zod/v4"), or another Standard Schema library

According to the TypeScript SDK repository, the v1 line keeps receiving bug fixes and security updates for at least six months after the v2 release. Official guides: Python migration guide and the TypeScript v2 docs.

Other official SDKs

The MCP project maintains SDKs in several languages, grouped into tiers by feature completeness and maintenance commitment (as listed on the SDK page at review time):

Language Repository Tier
TypeScript modelcontextprotocol/typescript-sdk 1
Python modelcontextprotocol/python-sdk 1
C# modelcontextprotocol/csharp-sdk 1
Go modelcontextprotocol/go-sdk 1
Rust modelcontextprotocol/rust-sdk 1
Ruby modelcontextprotocol/ruby-sdk 1
Java modelcontextprotocol/java-sdk 2
Swift modelcontextprotocol/swift-sdk 3
PHP modelcontextprotocol/php-sdk 3
Kotlin modelcontextprotocol/kotlin-sdk 3

The structure of these templates (store, thin server adapter, transport entry point, three levels of tests) carries over to any of them.

Troubleshooting

The client says the server disconnected or “failed to parse message”. Something wrote to stdout. Search for print(, console.log( and noisy dependencies. Run the stdio end-to-end test.

The client cannot find the command. Desktop apps do not always inherit your shell’s PATH. Use absolute paths for node, uv or python in the config, or a wrapper script.

Tools do not show up. Rebuild (npm run build) after TypeScript changes, restart or reload the client, and check the client’s MCP log. In Claude Code, /mcp shows server status.

ModuleNotFoundError: No module named 'mcp.server.fastmcp'. You are running v1 code against the v2 Python SDK. Migrate (see the table above) or pin mcp<2.

TypeScript: Cannot find module '@modelcontextprotocol/sdk/...'. v1 import paths. Switch to @modelcontextprotocol/server and @modelcontextprotocol/client.

Python tool errors show only “Error executing tool”. In v2, only ToolError messages reach the model. Catch expected exceptions and re-raise them as ToolError.

Structured output is missing in Python. Return a typed value (a Pydantic model, TypedDict, or annotated primitive). Untyped dict returns are not turned into structured content. Lists come back wrapped as {"result": [...]}.

The model calls the wrong tool or invents arguments. Improve names and descriptions, add enums and .describe() texts, and reduce the number of overlapping tools.

FAQ

Do I need an MCP server, or just function calling? If only your own app uses the tools, plain function calling in your app is simpler. Build an MCP server when you want the same tools usable from several AI clients (Claude, IDEs, agents) without re-integrating each time.

Can one server have both stdio and HTTP? Yes. The Python template switches with --http. In TypeScript, call createServer() from a second entry point that wires an HTTP adapter.

How many tools should a server have? As few as cover the use cases well, often under ten. Every tool’s description costs context in every conversation, and overlapping tools confuse models.

Should I return JSON or prose from tools? Both: structuredContent for clients that parse it, plus a short text block. The templates do this automatically (Python) or explicitly (TypeScript).

Is MCP only for Claude? No. MCP is an open protocol supported by many clients and frameworks. Check each client’s documentation for which primitives and transports it supports.

How do I handle authentication for a remote server? Use the HTTP transport with the OAuth-based authorization flow described in the specification and supported by the SDKs. Never accept credentials as tool arguments.

Why are my v1 tutorials not working? Both major SDKs had breaking v2 releases in 2026. Use the migration tables above, or pin v1 packages if you must run old code.

Where to go next

Repository layout

mcp-servers-templates/
├── templates/
│   ├── typescript/
│   │   ├── src/store.ts         # business logic
│   │   ├── src/server.ts        # createServer(): tools, resources, prompt
│   │   ├── src/index.ts         # stdio entry point
│   │   ├── test/server.test.ts  # 9 tests
│   │   ├── package.json, tsconfig.json, README.md
│   └── python/
│       ├── src/notes_server/store.py
│       ├── src/notes_server/server.py   # MCPServer, stdio + HTTP
│       ├── tests/test_server.py         # 8 tests
│       ├── pyproject.toml, README.md
├── examples/client-configs/     # Claude Desktop, VS Code, project .mcp.json
├── LICENSE
└── README.md

Contributing

Pull requests are welcome: templates for other official SDKs (Go, C#, Rust, Java…), HTTP hosting examples, and fixes when SDK APIs change. Please keep each template small, include tests that run the server over a real transport, pin to a major SDK version, and note the exact versions you tested with.

License

MIT.

If these templates saved you an afternoon, a star helps others find them.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.