AI Atlas
All guides
🛠️ GUIDE

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:

MCP Server SDK
BUILD YOUR OWN MCP SERVER server.ts import { Server } server.tool({ name: 'add_task', inputSchema: { … }, handler }) // stdio transport stdio AI Assistant (Claude, Cline, Continue…) list_tasks() add_task(...) search_tasks(q) Local task manager → one server, every host.

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/initialized handshake is gone. Every request carries its protocol version and client capabilities in _meta (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities).
  • No sessions. The Mcp-Session-Id header 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/discover is required. Servers advertise their supported versions, capabilities and identity through it.
  • No server-to-client requests. Server-initiated requests such as sampling/createMessage and elicitation/create are replaced by Multi Round-Trip Requests: the server asks for more input with resultType: "input_required" and the client re-sends the request with it. Every result now carries a resultType field.
  • Change notifications moved to a single subscriptions/listen stream; ping and logging/setLevel were 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/node

tsconfig.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.js

The terminal sits silent; that's expected, the server is waiting on stdin. The key parts:

  1. registerTool registers 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.
  2. 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.
  3. isError: true separates a business error (task not found) from a protocol error; the model reads the message and relays it properly.
  4. 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 mcp

tasks_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.py

What'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 in structuredContent.
  • Raising ToolError marks the result isError: 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=test

Check 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.js

    Per Claude Code's documentation, local and user scope are stored in ~/.claude.json and project scope (shared with your team) in .mcp.json at the project root. Inside .mcp.json you 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 the mcp package (Python) and feed the server's tools into your own LLM calls. The TypeScript SDK v2 client uses the 2025 handshake by default; turn on versionNegotiation: { 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 bin field to package.json so npx tasks-mcp runs; in Python define a console script so uvx tasks-mcp runs.
  • MCP Registry: the official registry is registry.modelcontextprotocol.io. You don't publish through a pull request but with the mcp-publisher tool: mcp-publisher init generates a server.json, then mcp-publisher login github and mcp-publisher publish. For npm packages, ownership is verified by adding an mcpName field to package.json that matches the name in server.json (with GitHub login it takes the form io.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

Sources

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.