Seongwoo Choi / Journal

Build an MCP server in Python from scratch, step by step

At a glanceWrite a working MCP server in about 100 lines of Python, test it by hand, connect it to Claude Code, then rebuild it with the official SDK. Real output.

TestedEvery command was run on Linux with Python 3.13, Claude Code 2.1.322 and the MCP SDK 2.3.0. Tool calls were sent by hand, not by a model.

You need
Python 3.10 or later and Claude Code. No GPU, no API key and no packages for the first version.
You end up with
A to-do list server that Claude Code connects to and can use through three tools, in two versions: hand-written and SDK-based.
In this article 11 sections
  1. 1. What an MCP server is
  2. 2. What we will build
  3. 3. The server, in about 100 lines
  4. 4. Test it without any client
  5. 5. Two kinds of failure
  6. 6. Connect it to Claude Code
  7. 7. See what Claude Code actually sends
  8. 8. Why the server answers two kinds of client
  9. 9. The same server with the official SDK
  10. 10. Mistakes that cost an afternoon
  11. 11. Make it yours

The Model Context Protocol, MCP, is how an AI assistant gets tools that you wrote. Most guides start with a library and leave the protocol a mystery. This one goes the other way. You will write a complete server in about 100 lines of plain Python, send it messages by hand, connect it to Claude Code and record what Claude Code really sends. Then you will write the same server again with the official SDK, in half the lines, knowing what the library is doing for you.

For installing servers that other people wrote, see Claude Code plugins and MCP from the terminal. This guide is about writing your own.

1. What an MCP server is

Claude Codestarts your program
⇄
One JSON message per linerequests go in on stdin, replies come out on stdout
⇄
Your servera program that reads lines and answers them
→
Your dataa file, a database, an API
A local MCP server is an ordinary program. The client starts it and talks to it through its standard input and output.

That is the whole idea. The messages follow a small standard called JSON-RPC, and there are only three shapes:

MessageHas an id?What it means
RequestYes"Do this and answer me." It names a method, such as tools/list.
ReplyThe same idEither a result or an error.
NotificationNo"For your information." It must not be answered.

A server that offers tools has to answer three requests: who are you, what tools do you have, and run this tool. Everything else is optional.

2. What we will build

A to-do list that lives in a small JSON file, with three tools:

ToolInputWhat it does
add_tasktextAdds a task
list_tasksnothingLists every task with its number and state
complete_tasknumberMarks one task as done

It is deliberately plain. Once it works, you replace the JSON file with whatever you want Claude to reach: your ticket system, a database, a folder of notes.

Make a folder and check your Python:

macOS and LinuxWindows (PowerShell)
Foldermkdir ~/mcp-tasks && cd ~/mcp-tasksmkdir $HOME\mcp-tasks; cd $HOME\mcp-tasks
Pythonpython3 --versionpython --version

On Windows the command is usually python, not python3. Use whichever prints a version, everywhere this guide writes python3.

3. The server, in about 100 lines

Save this as tasks_server.py. It uses only the standard library.

"""tasks_server.py: an MCP server that keeps a to-do list. Standard library only."""
import json
import os
import sys
from pathlib import Path

# Where the list is kept: next to this file, unless TASKS_FILE names another place.
STORE = Path(os.environ.get("TASKS_FILE") or Path(__file__).with_name("tasks.json"))
MODERN = "2026-07-28"                    # versions where every request names its version
LEGACY = ("2025-11-25", "2025-06-18")    # versions that begin with an initialize handshake
INFO = {"name": "tasks", "version": "1.0.0"}
VERSION_KEY = "io.modelcontextprotocol/protocolVersion"

TOOLS = [
    {"name": "add_task",
     "description": "Add a task to the to-do list.",
     "inputSchema": {"type": "object",
                     "properties": {"text": {"type": "string", "description": "What needs doing"}},
                     "required": ["text"]}},
    {"name": "list_tasks",
     "description": "List every task with its number and whether it is done.",
     "inputSchema": {"type": "object", "properties": {}}},
    {"name": "complete_task",
     "description": "Mark one task as done.",
     "inputSchema": {"type": "object",
                     "properties": {"number": {"type": "integer", "description": "The task's number from list_tasks"}},
                     "required": ["number"]}},
]


class RpcError(Exception):
    """A protocol-level failure: the request itself was wrong."""
    def __init__(self, code, message, data=None):
        self.error = {"code": code, "message": message}
        if data is not None:
            self.error["data"] = data


def load():
    return json.loads(STORE.read_text()) if STORE.exists() else []


def save(tasks):
    STORE.write_text(json.dumps(tasks, indent=2))


def run_tool(name, args):
    """Do the work and return the text the model will read."""
    tasks = load()
    if name == "add_task":
        tasks.append({"text": args["text"], "done": False})
        save(tasks)
        return f"Added task {len(tasks)}: {args['text']}"
    if name == "list_tasks":
        lines = [f"{n}. [{'x' if t['done'] else ' '}] {t['text']}" for n, t in enumerate(tasks, 1)]
        return "\n".join(lines) or "No tasks yet."
    if name == "complete_task":
        number = args["number"]
        if not 1 <= number <= len(tasks):
            raise ValueError(f"There is no task {number}. Call list_tasks to see the numbers.")
        tasks[number - 1]["done"] = True
        save(tasks)
        return f"Done: {tasks[number - 1]['text']}"
    raise RpcError(-32602, f"Unknown tool: {name}")


def handle(method, params):
    version = params.get("_meta", {}).get(VERSION_KEY)
    if version not in (None, MODERN):
        raise RpcError(-32022, "Unsupported protocol version", {"supported": [MODERN], "requested": version})

    if method == "server/discover":      # a modern client asks who we are
        return {"resultType": "complete", "supportedVersions": [MODERN],
                "capabilities": {"tools": {}},
                "_meta": {"io.modelcontextprotocol/serverInfo": INFO},
                "ttlMs": 3600000, "cacheScope": "public"}
    if method == "initialize":           # a legacy client opens with a handshake
        asked = params.get("protocolVersion")
        return {"protocolVersion": asked if asked in LEGACY else LEGACY[0],
                "capabilities": {"tools": {}}, "serverInfo": INFO}
    if method == "ping":
        return {}
    if method == "tools/list":
        return {"resultType": "complete", "tools": TOOLS, "ttlMs": 3600000, "cacheScope": "public"}
    if method == "tools/call":
        try:
            text, failed = run_tool(params.get("name"), params.get("arguments") or {}), False
        except KeyError as missing:      # the model left out an argument: say which one
            text, failed = f"Error: missing argument {missing}", True
        except ValueError as problem:    # the tool ran and failed: tell the model why
            text, failed = f"Error: {problem}", True
        return {"resultType": "complete", "content": [{"type": "text", "text": text}], "isError": failed}
    raise RpcError(-32601, f"Method not found: {method}")


for line in sys.stdin:
    if not line.strip():
        continue
    request = json.loads(line)
    if "id" not in request:              # a notification: there is nothing to answer
        continue
    try:
        reply = {"result": handle(request.get("method"), request.get("params") or {})}
    except RpcError as problem:
        reply = {"error": problem.error}
    print(json.dumps({"jsonrpc": "2.0", "id": request["id"], **reply}), flush=True)

Read it from the bottom up:

PartWhat it does
The loop at the endReads one line, turns it into a request, calls handle, and prints one line back. flush=True sends the reply at once; without it the client waits forever.
handleAnswers each method. server/discover and initialize are the two ways a client asks "who are you" (section 8 explains why there are two).
run_toolThe actual work. It returns the text the model will read.
TOOLSThe menu. Each tool has a name, a description and a JSON Schema for its input. The description is what the model reads to decide when to use the tool, so write it for a reader.
The model only sees what you describeA tool called ct with the description "completes" will be used badly. "Mark one task as done" and "The task's number from list_tasks" tell the model what to do and where the input comes from.

4. Test it without any client

Because the server only reads lines and prints lines, you can test it with a pipe. First, ask who it is:

$ echo '{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}' | python3 tasks_server.py
{"jsonrpc": "2.0", "id": 1, "result": {"resultType": "complete", "supportedVersions": ["2026-07-28"], "capabilities": {"tools": {}}, "_meta": {"io.modelcontextprotocol/serverInfo": {"name": "tasks", "version": "1.0.0"}}, "ttlMs": 3600000, "cacheScope": "public"}}
One line in, one line out.

Now put several requests in a file, one per line. Save this as requests.jsonl:

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add_task","arguments":{"text":"Renew the TLS certificate"}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"add_task","arguments":{"text":"Write the release notes"}}}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"complete_task","arguments":{"number":1}}}
{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"list_tasks","arguments":{}}}
{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"complete_task","arguments":{"number":9}}}
{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"add_task","arguments":{}}}
{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"delete_everything","arguments":{}}}
$ python3 tasks_server.py < requests.jsonl
{"jsonrpc": "2.0", "id": 1, "result": {"resultType": "complete", "content": [{"type": "text", "text": "Added task 1: Renew the TLS certificate"}], "isError": false}}
{"jsonrpc": "2.0", "id": 2, "result": {"resultType": "complete", "content": [{"type": "text", "text": "Added task 2: Write the release notes"}], "isError": false}}
{"jsonrpc": "2.0", "id": 3, "result": {"resultType": "complete", "content": [{"type": "text", "text": "Done: Renew the TLS certificate"}], "isError": false}}
{"jsonrpc": "2.0", "id": 4, "result": {"resultType": "complete", "content": [{"type": "text", "text": "1. [x] Renew the TLS certificate\n2. [ ] Write the release notes"}], "isError": false}}
{"jsonrpc": "2.0", "id": 5, "result": {"resultType": "complete", "content": [{"type": "text", "text": "Error: There is no task 9. Call list_tasks to see the numbers."}], "isError": true}}
{"jsonrpc": "2.0", "id": 6, "result": {"resultType": "complete", "content": [{"type": "text", "text": "Error: missing argument 'text'"}], "isError": true}}
{"jsonrpc": "2.0", "id": 7, "error": {"code": -32602, "message": "Unknown tool: delete_everything"}}
Seven requests, seven replies. The last three are failures, of two different kinds.

The list is now on disk, in tasks.json next to the script, with the first task marked done.

5. Two kinds of failure

Replies 5 to 7 above show a distinction the specification makes, and it matters for how well the model recovers.

Tool errorProtocol error
Example"There is no task 9""Unknown tool"
How it is sentA normal result with "isError": trueA JSON-RPC error with a code
Who it is forThe model. It reads the text and can try again.The client program. Something is wrong with the request itself.
What to writeWhat went wrong and what to do nextA short, exact message

So when a tool fails for a reason the model could fix, say how. "There is no task 9. Call list_tasks to see the numbers." gives the model its next step. A bare "invalid input" does not.

6. Connect it to Claude Code

Register the server with its full path. Everything after the -- is the command Claude Code will run:

Command
macOS and Linuxclaude mcp add tasks -- python3 ~/mcp-tasks/tasks_server.py
Windowsclaude mcp add tasks -- python C:\Users\you\mcp-tasks\tasks_server.py

Then ask Claude Code to check it:

$ claude mcp add tasks -- python3 ~/mcp-tasks/tasks_server.py
Added stdio MCP server tasks with command: python3 ~/mcp-tasks/tasks_server.py to local config
File modified: ~/.claude.json [project: ~/proj]
$ claude mcp list
Checking MCP server health…

tasks: python3 ~/mcp-tasks/tasks_server.py - ✔ Connected
Claude Code 2.1.322. "Connected" means it started the program, asked who it is and received the tool list.

In a session, /mcp shows the server and its three tools. From there you talk normally: "add a task to renew the certificate", "what is on my list?". Claude Code asks for permission the first time it uses each tool.

Three details from our test that save time:

  • The working folder is your project. Claude Code started the server with the project folder as its current directory and set CLAUDE_PROJECT_DIR to the same path. Our script stores its file next to itself instead, so the list is the same in every project.
  • Settings go in with --env. To keep a separate list somewhere else: claude mcp add --env TASKS_FILE=/path/to/work.json --transport stdio work-tasks -- python3 ~/mcp-tasks/tasks_server.py. The script reads that variable on its first lines. The documentation notes that another option must sit between --env and the server's name, which is why --transport stdio is there.
  • It is registered for this project only. That is the default scope. Add --scope user to have it in every project. The three scopes are explained in the plugins and MCP guide.

When the path is wrong, the same check tells you:

$ claude mcp list
tasks: python3 ~/mcp-tasks/task_server.py - ✘ Failed to connect — CONNECTION_CLOSED: Connection closed
$ python3 ~/mcp-tasks/task_server.py
python3: can't open file '~/mcp-tasks/task_server.py': [Errno 2] No such file or directory
The file name is misspelled, so Python exited at once. Running the command after the dash yourself shows the real error.

7. See what Claude Code actually sends

You do not have to guess what a client says to your server. Put a recorder between them. Save this as tap.py:

"""tap.py: sit between an MCP client and a server and record every message.

Use:  python3 tap.py wire.log python3 tasks_server.py
"""
import subprocess
import sys
import threading

log = open(sys.argv[1], "a", buffering=1)
server = subprocess.Popen(sys.argv[2:], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1)


def replies():
    for line in server.stdout:
        log.write("server  " + line)
        sys.stdout.write(line)
        sys.stdout.flush()


threading.Thread(target=replies, daemon=True).start()
for line in sys.stdin:
    log.write("client  " + line)
    server.stdin.write(line)
    server.stdin.flush()
server.stdin.close()
server.wait()

Register the server through it, then run the health check:

claude mcp remove tasks
claude mcp add tasks -- python3 ~/mcp-tasks/tap.py ~/mcp-tasks/wire.log python3 ~/mcp-tasks/tasks_server.py
claude mcp list

This is what landed in wire.log, with the long lines shortened:

client  {"jsonrpc":"2.0","id":"server-discover-probe-1","method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"claude-code","title":"Claude Code","version":"2.1.322", …},"io.modelcontextprotocol/clientCapabilities":{"roots":{"listChanged":true},"elicitation":{"form":{},"url":{}}}}}}
server  {"jsonrpc": "2.0", "id": "server-discover-probe-1", "result": {"resultType": "complete", "supportedVersions": ["2026-07-28"], …}}
client  {"method":"tools/list","jsonrpc":"2.0","id":0,"params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28", …}}}
server  {"jsonrpc": "2.0", "id": 0, "result": {"resultType": "complete", "tools": [{"name": "add_task", …}], "ttlMs": 3600000, "cacheScope": "public"}}
Two requests and two replies. There is no opening handshake: each request says which version of the protocol it is using.

Keep tap.py. When a server "does not work", the log shows in seconds whether the client never asked, the server never answered, or the answer was malformed.

8. Why the server answers two kinds of client

The log above shows the current revision of the protocol, dated 2026-07-28. It changed how a conversation starts.

Earlier revisions (2025-11-25 and before)Revision 2026-07-28
How it startsThe client sends initialize, the server answers, the client sends notifications/initializedNo handshake
Where the version isAgreed once, at the startIn _meta on every request
"Who are you?"Part of initializeserver/discover, which servers must implement
ResultsNo resultTypeEvery result carries resultType; lists also carry caching hints (ttlMs, cacheScope)
Unsupported versionThe server proposes another in its initialize replyError -32022 listing the versions the server supports

Plenty of clients still speak the earlier way, so a server you want people to use should answer both. Ours does: handle answers server/discover for new clients and initialize for old ones, and the tool methods are the same for both.

Claude Code handles the other side of this for you. Its documentation says it asks stdio servers whether they support the newer revision and uses it with those that do. We saw exactly that. Against our server it sent server/discover and carried on in the new style. Against an older test server that did not understand the question, it fell back to initialize with version 2025-11-25, and connected just the same.

If you upgrade an old serverThe documentation notes that Claude Code can skip asking a stdio server about the newer revision for 7 days, for example after the server exited when asked. If you add server/discover to a server and Claude Code keeps using the old handshake, set MCP_PROTOCOL_NEGOTIATION=auto to have it asked again.

9. The same server with the official SDK

Now that the protocol holds no secrets, let a library do the routine parts. Install the official Python SDK in a virtual environment:

macOS and LinuxWindows (PowerShell)
Createpython3 -m venv venvpython -m venv venv
Install./venv/bin/pip install "mcp==2.3.0".\venv\Scripts\pip install "mcp==2.3.0"

Save this as tasks_sdk.py:

"""tasks_sdk.py: the same to-do list server, written with the official MCP Python SDK."""
import json
from pathlib import Path

from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

STORE = Path(__file__).with_name("tasks.json")
server = MCPServer("tasks", version="1.0.0")


def load():
    return json.loads(STORE.read_text()) if STORE.exists() else []


def save(tasks):
    STORE.write_text(json.dumps(tasks, indent=2))


@server.tool()
def add_task(text: str) -> str:
    """Add a task to the to-do list."""
    tasks = load()
    tasks.append({"text": text, "done": False})
    save(tasks)
    return f"Added task {len(tasks)}: {text}"


@server.tool()
def list_tasks() -> str:
    """List every task with its number and whether it is done."""
    lines = [f"{n}. [{'x' if t['done'] else ' '}] {t['text']}" for n, t in enumerate(load(), 1)]
    return "\n".join(lines) or "No tasks yet."


@server.tool()
def complete_task(number: int) -> str:
    """Mark one task as done. The number comes from list_tasks."""
    tasks = load()
    if not 1 <= number <= len(tasks):
        raise ToolError(f"There is no task {number}. Call list_tasks to see the numbers.")
    tasks[number - 1]["done"] = True
    save(tasks)
    return f"Done: {tasks[number - 1]['text']}"


if __name__ == "__main__":
    server.run()

Register it with the virtual environment's Python, so the library is found:

$ claude mcp add tasks-sdk -- ~/mcp-tasks/venv/bin/python ~/mcp-tasks/tasks_sdk.py
Added stdio MCP server tasks-sdk with command: ~/mcp-tasks/venv/bin/python ~/mcp-tasks/tasks_sdk.py to local config
$ claude mcp list
Checking MCP server health…

tasks: python3 ~/mcp-tasks/tasks_server.py - ✔ Connected
tasks-sdk: ~/mcp-tasks/venv/bin/python ~/mcp-tasks/tasks_sdk.py - ✔ Connected
Both versions, side by side. On Windows the interpreter is venv\Scripts\python.exe.

What the library took over, compared with the hand-written version:

JobBy handWith the SDK
Tool list and schemasThe TOOLS list, typed outBuilt from each function's name, docstring and type hints
Checking the inputOurs checks very littleAutomatic. Sending "one" for number came back as "Input should be a valid integer"
Both kinds of clientTwo branches in handleAutomatic. It answered server/discover and, on a separate run, an old-style initialize
Reading and writing linesThe loop at the endserver.run()

Two things we ran into that the examples online often get wrong:

  • The class was renamed. Version 2 of the SDK calls it MCPServer. Code written for version 1 imports FastMCP from mcp.server.fastmcp, and on 2.3.0 that import fails with a message pointing to the migration guide.
  • Raise ToolError, not a plain exception. When our tool raised an ordinary ValueError, the model would have received only "Error executing tool complete_task", with the reason hidden. With ToolError the message arrives whole: "Error executing tool complete_task: There is no task 9. Call list_tasks to see the numbers."

10. Mistakes that cost an afternoon

MistakeWhat you seeFix
Printing debug text with print()The specification forbids anything on stdout that is not a protocol message. Claude Code tolerated one stray line in our test; do not count on that from every client.print("…", file=sys.stderr)
Forgetting to flushThe client waits and then times outprint(…, flush=True)
A relative path in claude mcp addWorks in one folder, "Failed to connect" in another, because the server starts in the project folderUse full paths for the interpreter and the script
Answering a notificationConfused clients; a message with no id expects no replySkip any message without an id
A reply spread over several linesThe client cannot parse itOne message per line. json.dumps without indent does this for you
Vague tool descriptionsThe model picks the wrong tool, or noneSay what the tool does and where each input comes from
Secrets in the code or the commandKeys end up in shell history or a repositoryPass them with --env and read them from the environment

11. Make it yours

Replace the three functions and you have a different server. Some that take an evening:

  • Your notes. Search a folder of Markdown files and return the matching paragraphs.
  • Your database, read-only. One tool that runs a fixed, named query, such as "orders from the last 7 days". Do not start with a tool that accepts any SQL.
  • Your own server's health. Ask the metrics endpoint from the vLLM monitoring guide and return the queue length and memory in a sentence.
A tool runs with your permissionsWhatever your server can do, the model can ask it to do. Start with tools that only read. Check every input as if a stranger had typed it. Give a tool the narrowest job that is still useful, and keep the permission prompt on for anything that writes or deletes.

For the habits that keep an agent with tools under control, see AI coding agent tips and Claude Code hooks, tested.

Sources

This article reflects public information available when it was written. Versions, defaults and prices can change; check the linked official documentation.

Every command and every line of output is from a run on November 12, 2026, on Linux with Python 3.13, Claude Code 2.1.322 and the MCP Python SDK 2.3.0. The connection to Claude Code was checked with claude mcp list and by recording the messages it sent. The tool calls were sent by hand as JSON; no model session was run, so the article does not show Claude choosing a tool. The macOS and Windows commands follow the documentation and were not run. Long lines of output are shortened where marked. Written for this site with AI assistance, from the sources above. For errors or additional information, please request a correction. Editorial policy