Build Your Own MCP Server
Write an MCP server from scratch that adds capabilities to your AI assistant: what changed in the 2026-07-28 spec, a local task manager tested with TypeScript SDK v2 and Python SDK 2.x, testing with the Inspector, wiring it into Claude Desktop and Claude Code, and publishing to the MCP Registry.
Updated:
Why write your own MCP server?
MCP (Model Context Protocol) is the standard way to give an AI assistant the ability to touch the outside world. Ready-made servers (see the MCP Server Catalog) cover most common needs, but you'll write your own when:
- Personal assistant: you want an assistant that talks to your notes, your habits, your own data.
- Internal systems: you want to open an internal CRM, ERP or product API to your assistant.
- Open-source tooling: you're packaging a useful integration as MCP for the community.
- Control layer: you want to wrap a SaaS API as a tool with clear limits instead of handing it over raw.
This guide walks through writing a host-independent MCP server end to end. Any MCP-aware assistant (Claude Desktop, Claude Code, Cursor, VS Code, Cline and others) can connect to the same server.
First: what changed in the 2026-07-28 spec?
The current MCP revision is 2026-07-28 (released as stable on 28 July 2026). Most older examples online target the previous revision (2025-11-25), so the differences matter. From the official changelog, the main ones:
- The protocol is stateless. The
initialize/notifications/initializedhandshake is gone. Every request carries its protocol version and client capabilities in_meta(io.modelcontextprotocol/protocolVersion,io.modelcontextprotocol/clientCapabilities). - No sessions. The
Mcp-Session-Idheader and protocol-level sessions were removed from Streamable HTTP. A server that needs state across calls returns its own handle as an ordinary tool result and takes it back as an argument. server/discoveris required. Servers advertise their supported versions, capabilities and identity through it.- No server-to-client requests. Server-initiated requests such as
sampling/createMessageandelicitation/createare replaced by Multi Round-Trip Requests: the server asks for more input withresultType: "input_required"and the client re-sends the request with it. Every result now carries aresultTypefield. - Change notifications moved to a single
subscriptions/listenstream;pingandlogging/setLevelwere removed. - Deprecated: Roots, Sampling and Logging; the old HTTP+SSE transport (use Streamable HTTP); Dynamic Client Registration (use Client ID Metadata Documents).
The good news: the official SDKs hide most of this. Both servers below answer 2026-07-28 clients and 2025-era clients that use the handshake from the same code.
What an MCP server provides
A server exposes three kinds of things:
- Tools: functions the assistant can call (e.g.
add_task). - Resources: data the assistant can read (e.g. a file, a record).
- Prompts: prompt templates the server suggests.
In most practical scenarios tools are enough; this guide is tool-focused. Local servers talk over stdio (the host launches the server as a subprocess and they exchange newline-delimited JSON-RPC messages); remote servers talk over Streamable HTTP.
Scenario: a personal task manager
You want to tell your assistant "add 'write the report' for tomorrow", "show what's due this week", "mark X as done". The data lives in a JSON file on your own disk, not in a third-party cloud.
Tools:
list_tasks(status?, due_before?)— list tasks.add_task(title, due?, tags?)— add a task.complete_task(id)— mark a task done.search_tasks(query)— search by title or tag.
Data lives in ~/.tasks.json by default; the TASKS_FILE environment variable points it elsewhere (handy for testing).
We'll write the same server in TypeScript, then Python. Both were tested on 8 November 2026 with @modelcontextprotocol/server 2.4.0 and mcp 2.3.0, against 2026-07-28 and 2025-11-25 clients.
TypeScript implementation
The v2 line of the TypeScript SDK replaces the old single @modelcontextprotocol/sdk package with separate server and client packages. v1 (1.x) is still published but knows 2025-11-25 as its newest protocol revision; use v2 for new projects.
Setup
mkdir tasks-mcp && cd tasks-mcp
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server zod
npm install -D typescript @types/nodetsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"types": ["node"]
},
"include": ["src"]
}The "types": ["node"] line is needed: per the SDK's README, TypeScript 6.0 and later no longer include @types/* packages automatically.
Server code
src/index.ts:
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { homedir } from "node:os";
import { randomUUID } from "node:crypto";
const STORE = process.env.TASKS_FILE ?? join(homedir(), ".tasks.json");
type Task = {
id: string;
title: string;
due?: string; // ISO date
tags?: string[];
done: boolean;
created: string;
};
async function loadTasks(): Promise<Task[]> {
try {
return JSON.parse(await readFile(STORE, "utf8"));
} catch {
return [];
}
}
async function saveTasks(tasks: Task[]) {
await writeFile(STORE, JSON.stringify(tasks, null, 2), "utf8");
}
const text = (t: string) => ({ content: [{ type: "text" as const, text: t }] });
function createServer() {
const server = new McpServer({ name: "tasks-mcp", version: "0.1.0" });
server.registerTool(
"list_tasks",
{
description: "Returns the to-do list. Status and due-date filters are optional.",
inputSchema: z.object({
status: z.enum(["open", "done", "all"]).default("open"),
due_before: z.string().optional().describe("ISO date; only tasks due before it"),
}),
annotations: { readOnlyHint: true },
},
async ({ status, due_before }) => {
const before = due_before ? new Date(due_before) : null;
const hits = (await loadTasks()).filter((t) => {
if (status === "open" && t.done) return false;
if (status === "done" && !t.done) return false;
if (before && (!t.due || new Date(t.due) >= before)) return false;
return true;
});
return text(JSON.stringify(hits, null, 2));
},
);
server.registerTool(
"add_task",
{
description: "Adds a new task. due is an ISO date; tags is an array of strings.",
inputSchema: z.object({
title: z.string().describe("Task title"),
due: z.string().optional().describe("Due date, ISO format"),
tags: z.array(z.string()).optional().describe("Tags, e.g. ['work', 'report']"),
}),
},
async ({ title, due, tags }) => {
const tasks = await loadTasks();
const task: Task = { id: randomUUID().slice(0, 8), title, due, tags, done: false, created: new Date().toISOString() };
tasks.push(task);
await saveTasks(tasks);
return text(`Added: ${task.id} — ${task.title}`);
},
);
server.registerTool(
"complete_task",
{
description: "Marks a task as done.",
inputSchema: z.object({ id: z.string().describe("Task ID") }),
annotations: { idempotentHint: true },
},
async ({ id }) => {
const tasks = await loadTasks();
const t = tasks.find((x) => x.id === id);
if (!t) return { ...text(`Task not found: ${id}`), isError: true };
t.done = true;
await saveTasks(tasks);
return text(`Done: ${t.title}`);
},
);
server.registerTool(
"search_tasks",
{
description: "Searches tasks by title or tag.",
inputSchema: z.object({ query: z.string() }),
annotations: { readOnlyHint: true },
},
async ({ query }) => {
const q = query.toLowerCase();
const hits = (await loadTasks()).filter(
(t) => t.title.toLowerCase().includes(q) || (t.tags ?? []).some((tag) => tag.toLowerCase().includes(q)),
);
return text(JSON.stringify(hits, null, 2));
},
);
return server;
}
// serveStdio answers both modern (2026-07-28, per-request) and legacy
// (2025-era initialize handshake) clients from the same factory.
serveStdio(createServer);Build and run:
npx tsc
node dist/index.jsThe terminal sits silent; that's expected, the server is waiting on stdin. The key parts:
registerToolregisters each tool with a name, a description and a Zod schema. The SDK advertises the schema to the client as JSON Schema and validates incoming arguments: if a required field is missing the handler never runs and the client gets a descriptive error.annotations(readOnlyHint,idempotentHint) give the host hints about the tool's behavior; for example it may skip a confirmation for read-only tools. They are hints, not security guarantees.isError: trueseparates a business error (task not found) from a protocol error; the model reads the message and relays it properly.serveStdio(createServer)takes a factory and serves the connection correctly for whichever protocol era it opens with.
Python implementation
Version 2.x of the Python SDK ships the high-level MCPServer class: the function's type hints are the schema and its docstring is the description.
python -m venv .venv
.venv/bin/pip install mcptasks_mcp/server.py:
import json
import os
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Literal
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
STORE = Path(os.environ.get("TASKS_FILE", Path.home() / ".tasks.json"))
mcp = MCPServer("tasks-mcp", version="0.1.0")
def load_tasks() -> list[dict]:
if not STORE.exists():
return []
return json.loads(STORE.read_text("utf-8"))
def save_tasks(tasks: list[dict]) -> None:
STORE.write_text(json.dumps(tasks, indent=2, ensure_ascii=False), "utf-8")
@mcp.tool()
def list_tasks(status: Literal["open", "done", "all"] = "open", due_before: str | None = None) -> list[dict]:
"""Returns the to-do list. due_before is an ISO date; only tasks due before it are returned."""
out = []
for t in load_tasks():
if status == "open" and t["done"]:
continue
if status == "done" and not t["done"]:
continue
if due_before and (not t.get("due") or t["due"] >= due_before):
continue
out.append(t)
return out
@mcp.tool()
def add_task(title: str, due: str | None = None, tags: list[str] | None = None) -> str:
"""Adds a new task. due is an ISO date; tags is a list of strings."""
tasks = load_tasks()
task = {
"id": uuid.uuid4().hex[:8],
"title": title,
"due": due,
"tags": tags,
"done": False,
"created": datetime.now(timezone.utc).isoformat(),
}
tasks.append(task)
save_tasks(tasks)
return f"Added: {task['id']} — {title}"
@mcp.tool()
def complete_task(id: str) -> str:
"""Marks a task as done."""
tasks = load_tasks()
for t in tasks:
if t["id"] == id:
t["done"] = True
save_tasks(tasks)
return f"Done: {t['title']}"
raise ToolError(f"Task not found: {id}")
@mcp.tool()
def search_tasks(query: str) -> list[dict]:
"""Searches tasks by title or tag."""
q = query.lower()
return [
t for t in load_tasks()
if q in t["title"].lower() or any(q in tag.lower() for tag in (t.get("tags") or []))
]
if __name__ == "__main__":
mcp.run()Run:
.venv/bin/python tasks_mcp/server.pyWhat's different:
- The schema comes from type hints.
Literal[...]becomes an enum and parameters with defaults become optional fields; you don't write JSON Schema by hand. - The return type becomes structured output. A tool returning
list[dict]gives its result both as text and instructuredContent. - Raising
ToolErrormarks the resultisError: true. mcp.run()uses stdio by default and handles both protocol eras.
Testing: MCP Inspector
Before wiring the server into a host, exercise it with the official MCP Inspector. The 2.x line of the Inspector ships a web UI, a CLI and a TUI; per its README it needs Node ^22.23.4, ^24.22.1 or >=26.12.1.
# Web UI
npx @modelcontextprotocol/inspector node dist/index.js
# List tools from the CLI in one command
npx @modelcontextprotocol/inspector --cli node dist/index.js --method tools/list
# Call a tool on the Python server
npx @modelcontextprotocol/inspector --cli .venv/bin/python tasks_mcp/server.py \
--method tools/call --tool-name add_task --tool-arg title=testCheck the tool list, add and list a few tasks, then deliberately leave out a parameter to see how the error comes back. Add -e TASKS_FILE=/tmp/test-tasks.json so testing doesn't touch your real file.
Connecting to an AI assistant
Because MCP is a standard, the same server connects to any MCP-aware host. The idea is always the same: tell the host "launch this command as a subprocess". Use absolute paths; the host does not start the server from your terminal's working directory.
Typical Claude Desktop config:
{
"mcpServers": {
"tasks": {
"command": "node",
"args": ["/full/path/tasks-mcp/dist/index.js"]
}
}
}For Python, point at the virtualenv's Python and the script's full path:
{
"mcpServers": {
"tasks": {
"command": "/full/path/tasks-mcp/.venv/bin/python",
"args": ["/full/path/tasks-mcp/tasks_mcp/server.py"],
"env": { "TASKS_FILE": "/full/path/tasks.json" }
}
}
}Per host:
-
Claude Desktop:
claude_desktop_config.json, opened via Settings → Developer → Edit Config. It lives in~/Library/Application Support/Claude/on macOS,%APPDATA%\Claude\on Windows and~/.config/Claude/on Linux. Fully quit and reopen the app after changing it. -
Claude Code: the CLI is easiest:
claude mcp add tasks -- node /full/path/tasks-mcp/dist/index.js # user scope, to use it in every project: claude mcp add tasks --scope user -e TASKS_FILE=/full/path/tasks.json -- node /full/path/tasks-mcp/dist/index.jsPer Claude Code's documentation, local and user scope are stored in
~/.claude.jsonand project scope (shared with your team) in.mcp.jsonat the project root. Inside.mcp.jsonyou can use environment variables with${VAR}and${VAR:-default}; that is a Claude Code feature and won't work in every host. -
Cursor, VS Code, Cline and others: add the server through their UI or a similar JSON file; field names can differ slightly, so check their docs.
-
Your own app: connect with
@modelcontextprotocol/client(TypeScript) or the client side of themcppackage (Python) and feed the server's tools into your own LLM calls. The TypeScript SDK v2 client uses the 2025 handshake by default; turn onversionNegotiation: { mode: "auto" }to speak 2026-07-28.
Once the host starts the server, "add 'write the report' for tomorrow" makes the assistant call add_task, which writes to the file and returns a short summary.
Common pitfalls
Logging to stdout
On stdio, stdout is the protocol channel. The spec says a server must not write anything to stdout that isn't a valid MCP message; stderr may be used for logging. In Node use console.error instead of console.log; in Python use print(..., file=sys.stderr) or logging. A single stray print breaks the connection.
Vague tool descriptions
The model decides when to call a tool from its description. "Add a task" is weaker than "Adds a new task. due is an ISO date; tags is an array of strings." Describe every parameter too (.describe() or the docstring).
Over-broad permissions
For servers that touch real systems, least privilege is critical: read-only tokens, narrowly scoped IAM roles, only the endpoints you need. A model mistake shouldn't become damage in production. External content your server reads can carry prompt injection; design tools that write accordingly.
Swallowed errors
When a disk or network operation fails, return a meaningful message with isError, such as "Task not found: 12345". A tool that fails silently leads the model to make something up.
Relying on sessions
In 2026-07-28 there are no protocol-level sessions; don't assume consecutive calls arrive on the same connection or process. If you need state across calls (say, a paginated search), return a server-minted handle as a tool result and take it as an argument on the next call. Don't build new servers on deprecated features like Roots, Sampling and Logging: take directories as tool parameters or configuration, and log to stderr or OpenTelemetry.
Choosing a transport
Start with stdio for local use. For remote access use Streamable HTTP (each message is an HTTP POST to a single endpoint); the old HTTP+SSE transport is deprecated. Once a server is remote, authentication (the spec's OAuth-based authorization section) is your responsibility.
Concurrency safety
An assistant may call several tools in one message. The example's "read file, modify, write" flow can lose one of two writes that arrive together; in real use add a file lock or use a database such as SQLite.
Publishing and sharing
Once it works, package and share it:
- npm / PyPI: in TypeScript add a
binfield topackage.jsonsonpx tasks-mcpruns; in Python define a console script souvx tasks-mcpruns. - MCP Registry: the official registry is
registry.modelcontextprotocol.io. You don't publish through a pull request but with themcp-publishertool:mcp-publisher initgenerates aserver.json, thenmcp-publisher login githubandmcp-publisher publish. For npm packages, ownership is verified by adding anmcpNamefield topackage.jsonthat matches the name inserver.json(with GitHub login it takes the formio.github.your-username/...). Per the latest status note in the repo README, the Registry API has been frozen at v0.1 since October 2025. - README: document setup, required environment variables and an example config.
- Internal: if it contains sensitive logic, publish to a private npm/PyPI registry.
Common scenario ideas
The same skeleton applied to different data sources gives many useful servers:
- Personal notes / wiki: read and search local Markdown files.
- Smart home: switch lights, query temperature.
- Music library: recent plays, add to playlist.
- Expense ledger: add an expense, totals by category.
- Digital archive: book/movie/game tracking lists.
- Business-specific: CRM, product analytics, content calendar, ticketing.
Continue reading
- MCP — the underlying concept.
- MCP Server Catalog — check for a ready-made server before writing your own.
- A map of agent protocols — where MCP, A2A and payment protocols sit.
- Claude Skills Guide — how skills and MCP servers work together.
- Function Calling — the tool-calling behavior MCP rides on.
Sources
- MCP specification 2026-07-28 — Key Changes
- MCP specification — Versioning and Compatibility
- MCP TypeScript SDK and v2 docs
- MCP Python SDK
- MCP Inspector
- MCP Registry
- Claude Code — MCP
- Connect to local MCP servers (Claude Desktop)
Frequently asked questions
What changed in MCP 2026-07-28?
The protocol became stateless: the initialize handshake and Mcp-Session-Id sessions were removed, and every request now carries its protocol version and client capabilities in _meta. Servers must implement server/discover. Roots, Sampling, Logging and the old HTTP+SSE transport are deprecated.
Will older (2025) MCP clients work with my new server?
With the official SDKs, yes. TypeScript SDK v2's serveStdio and Python SDK 2.x answer both 2026-07-28 clients and 2025-era clients that use the initialize handshake from the same server. Both servers in this guide were tested against both eras.
Can I still use the @modelcontextprotocol/sdk package?
The v1 line (1.x) is still published, but it knows 2025-11-25 as its newest protocol revision. For 2026-07-28, use TypeScript SDK v2's @modelcontextprotocol/server and @modelcontextprotocol/client packages.
Where does Claude Code store MCP server settings?
Per Claude Code's documentation, local- and user-scoped servers live in ~/.claude.json and project-scoped servers in .mcp.json at the project root. The easiest way to add one is the claude mcp add command.
Where do I publish my MCP server?
After publishing the package to npm or PyPI, register it in the official MCP Registry with the mcp-publisher tool and a server.json file. For npm packages, ownership is verified through an mcpName field in package.json.