How to Build an MCP Server from Scratch: A Developer’s Hands-On Guide

Most guides on how to build an MCP server from scratch start with pip install and an SDK that hides everything interesting. You get a working server and no idea what travels between the client and your code. This guide builds a minimal MCP server in Python on raw JSON-RPC 2.0 over stdio, zero dependencies: you see every message and handle each one. Once the loop makes sense, the SDK version takes five minutes.

MCP in one minute: clients, servers, messages

MCP, the Model Context Protocol, is an open protocol from Anthropic that standardizes how AI applications connect to external tools and data. Your AI app (the client, for example Claude Desktop or an agent framework) talks to small programs (servers) that expose capabilities, and every message between them is JSON-RPC 2.0: a method name plus parameters, answered by a result or an error. Each session opens with an initialize handshake where the server declares its protocol version and capabilities, the client confirms with notifications/initialized, then lists and calls what the server offers.

Servers expose three primitives:

Primitive What it gives the model Example
Tools Actions it can call with arguments add(a, b), search_docs(query)
Resources Read-only content it can read a config file, demo://greeting
Prompts Reusable templates that package context for a task a “review this diff” template with repo conventions baked in

The demo below implements tools and resources.

The server, part by part

Create a file called server.py. The standard library is enough. Here is the whole thing, then each part explained.

import json
import sys
import traceback


def log(message):
    print(message, file=sys.stderr, flush=True)  # stdout is the protocol channel


TOOLS = {
    "add": {
        "description": "Add two numbers together.",
        "input_schema": {
            "type": "object",
            "properties": {"a": {"type": "number"}, "b": {"type": "number"}},
            "required": ["a", "b"],
        },
    },
}


def tool_add(arguments):
    return str(arguments["a"] + arguments["b"])


TOOL_HANDLERS = {"add": tool_add}

RESOURCES = {
    "demo://greeting": {
        "name": "greeting",
        "description": "A sample text resource.",
        "mimeType": "text/plain",
        "text": "Hello from the MCP server.",
    },
}


def send(obj):
    sys.stdout.write(json.dumps(obj) + "n")
    sys.stdout.flush()


def result(message_id, payload):
    return {"jsonrpc": "2.0", "id": message_id, "result": payload}


def error(message_id, code, message):
    return {
        "jsonrpc": "2.0",
        "id": message_id,
        "error": {"code": code, "message": message},
    }


def handle(message):
    method = message.get("method")
    message_id = message.get("id")
    params = message.get("params") or {}

    if method == "initialize":
        return result(message_id, {
            "protocolVersion": params.get("protocolVersion", "2024-11-05"),
            "capabilities": {"tools": {}, "resources": {}},
            "serverInfo": {"name": "demo-server", "version": "0.1.0"},
        })

    if method == "notifications/initialized":
        log("Client finished initialization")
        return None  # notifications get no response

    if method == "tools/list":
        return result(message_id, {
            "tools": [
                {
                    "name": name,
                    "description": spec["description"],
                    "inputSchema": spec["input_schema"],
                }
                for name, spec in TOOLS.items()
            ],
        })

    if method == "tools/call":
        name = params.get("name")
        if name not in TOOL_HANDLERS:
            return error(message_id, -32602, f"Unknown tool: {name}")
        output = TOOL_HANDLERS[name](params.get("arguments") or {})
        return result(message_id, {
            "content": [{"type": "text", "text": output}],
        })

    if method == "resources/list":
        return result(message_id, {
            "resources": [
                {
                    "uri": uri,
                    "name": spec["name"],
                    "description": spec["description"],
                    "mimeType": spec["mimeType"],
                }
                for uri, spec in RESOURCES.items()
            ],
        })

    if method == "resources/read":
        uri = params.get("uri")
        if uri not in RESOURCES:
            return error(message_id, -32602, f"Unknown resource: {uri}")
        return result(message_id, {
            "contents": [{
                "uri": uri,
                "mimeType": RESOURCES[uri]["mimeType"],
                "text": RESOURCES[uri]["text"],
            }],
        })

    if message_id is None:
        return None  # unknown notification: ignore

    return error(message_id, -32601, f"Method not found: {method}")


def main():
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            message = json.loads(line)
        except json.JSONDecodeError:
            log(f"Ignoring malformed line: {line[:80]}")
            continue
        try:
            response = handle(message)
        except Exception as exc:
            log(traceback.format_exc())
            if message.get("id") is not None:
                send(error(message["id"], -32000, f"Internal error: {exc}"))
            continue
        if response is not None:
            send(response)


if __name__ == "__main__":
    main()

The read loop

main() reads stdin line by line, since on the stdio transport each JSON-RPC message is one line. It parses the line, hands the dict to handle(), and writes the reply to stdout as one flushed line. Bad lines get logged and skipped; the loop never dies over one.

initialize: the handshake

Every client starts by sending initialize. The reply carries a protocolVersion, a capabilities object listing the primitives this server supports (here tools and resources), and serverInfo. The demo echoes the requested protocol version; production servers validate it against supported versions.

tools/list and tools/call

TOOLS holds the metadata, TOOL_HANDLERS the functions. tools/list returns the metadata so the client can show the model what exists. tools/call runs the matching handler with the supplied arguments and wraps the output in a content array, the shape MCP clients expect. The model reads the description to decide when to call, so write it like documentation.

resources/list and resources/read

Resources are a dict keyed by URI. resources/list returns each resource’s URI, name, description, and MIME type; resources/read returns the content for one URI. The model never calls a resource; the client reads it into context, from a file, a database row, or a static string as here.

Notifications get no reply

JSON-RPC separates requests, which carry an id, from notifications, which do not. notifications/initialized is a notification, so the server must not answer it: the demo returns None for any message without an id, and main() sends nothing. Answering a notification confuses some clients, a common first-server bug.

Errors, and the one rule of stdio

Unknown methods get a -32601 error, unknown tools get -32602, and a crashed handler gets a -32000 server error: the standard JSON-RPC 2.0 codes. The one rule of stdio: stdout is the protocol channel. A stray print() corrupts the stream and kills the client with no useful error, so log() writes to stderr.

Smoke-test it without a client

No AI app needed to verify the loop. Pipe a raw request into stdin:

printf '%sn' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}' | python server.py

You get back one JSON line with the protocol version, capabilities, and server info. Then a tool call:

printf '%sn' '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"add","arguments":{"a":3,"b":5}}}' | python server.py

The response content is the text 8. If a message hangs, the bug is in handle(), not in some client config.

The pragmatic shortcut: the official SDK

The production route is the official Python SDK, which hides message handling and builds schemas from your type hints:

from fastmcp import FastMCP

mcp = FastMCP("demo-server")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

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

Same server, five lines of real code. The SDK API evolves, so confirm decorator names against the current SDK docs before relying on this.

Test it with the MCP Inspector

The MCP Inspector is the official testing tool: a web UI with Tools and Resources panels where you fill in parameters and call your tools by hand.

npx @modelcontextprotocol/inspector python server.py

Call add with 3 and 5; 8 comes back. The log panel shows every JSON-RPC message, read it first when something misbehaves.

Connect it to an MCP client

To use the server from Claude Desktop, register it in claude_desktop_config.json under mcpServers, with the command and arguments that launch it:

{
  "mcpServers": {
    "demo-server": {
      "command": "python",
      "args": ["/absolute/path/to/server.py"]
    }
  }
}

Restart the client: it spawns your script, runs the handshake, and your tools appear in the UI. With the SDK, mcp install server.py writes this entry for you.

Picking a transport: stdio vs HTTP

stdio pipes JSON-RPC through a local process’s stdin and stdout, which is what we built: the default for local tools, with no ports and no auth story. Remote servers use HTTP-based transport. Current MCP guidance says Streamable HTTP; older docs say SSE. Going remote means real authentication, because your tools become network-reachable. When in doubt, check the official MCP spec for the latest transport recommendations. Once a remote server is worth sharing, the standard move is to put it behind a reverse proxy with TLS so authentication and certificates live in one place.

Three mistakes that break new servers

  • Printing to stdout. Any print() outside send() corrupts the protocol stream. Log to stderr or a file instead.
  • Forgetting to flush. The client waits for a complete line; unflushed output makes the handshake hang. Flush after every write.
  • Answering notifications or ignoring unknown methods silently. Every request with an id deserves a reply (unknown methods get -32601); notifications get none.

You now have a server you fully understand, a way to test it, and a path to connect it. Next: take one function from your own codebase, a database lookup, a file search, a deployment script, register it in TOOLS and TOOL_HANDLERS, and watch an AI client use it.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.