DEV Community

Shipcode
Shipcode

Posted on

Build an MCP server from scratch in about 90 lines of Python

MCP (Model Context Protocol) sounds big, but the core of a server is small: read JSON from stdin, answer on stdout. No SDK needed. In this post we write a working MCP server with tools in about 90 lines of plain Python, and then plug it into a real client.

What actually goes over the wire

An MCP server that uses the stdio transport is just a process. The client (Claude Desktop, Cursor, an agent you wrote) starts it and talks to it with JSON-RPC 2.0 messages, one per line:

  • Requests have an id, a method and optional params. You must answer each one with the same id.
  • Notifications have no id. You never answer them.
  • Responses carry either a result or an error with a numeric code.

A session looks like this:

  1. Client sends initialize. Server replies with its protocol version, capabilities and name.
  2. Client sends the notifications/initialized notification.
  3. Client asks tools/list to see what the server can do.
  4. Client sends tools/call whenever the model wants to use a tool.

That is the whole loop for a tools-only server.

The full server

import json
import sys

PROTOCOL_VERSION = "2025-06-18"

TOOLS = {}

def tool(name, description, schema):
    def register(fn):
        TOOLS[name] = {"fn": fn, "description": description, "inputSchema": schema}
        return fn
    return register

@tool("add", "Add two numbers", {
    "type": "object",
    "properties": {"a": {"type": "number"}, "b": {"type": "number"}},
    "required": ["a", "b"],
})
def add(args):
    return str(args["a"] + args["b"])

@tool("word_count", "Count the words in a piece of text", {
    "type": "object",
    "properties": {"text": {"type": "string"}},
    "required": ["text"],
})
def word_count(args):
    return str(len(args["text"].split()))

def handle_initialize(params):
    return {
        "protocolVersion": PROTOCOL_VERSION,
        "capabilities": {"tools": {}},
        "serverInfo": {"name": "tiny-mcp", "version": "0.1.0"},
    }

def handle_tools_list(params):
    return {"tools": [
        {"name": n, "description": t["description"], "inputSchema": t["inputSchema"]}
        for n, t in TOOLS.items()
    ]}

def handle_tools_call(params):
    name = params.get("name")
    if name not in TOOLS:
        raise LookupError(f"Unknown tool: {name}")
    try:
        text = TOOLS[name]["fn"](params.get("arguments", {}))
        return {"content": [{"type": "text", "text": text}], "isError": False}
    except KeyError as e:
        return {"content": [{"type": "text", "text": f"Missing argument: {e}"}], "isError": True}
    except Exception as e:
        # Tool failures go back to the model as a normal result
        return {"content": [{"type": "text", "text": f"Error: {e}"}], "isError": True}

METHODS = {
    "initialize": handle_initialize,
    "tools/list": handle_tools_list,
    "tools/call": handle_tools_call,
    "ping": lambda params: {},
}

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

def main():
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            msg = json.loads(line)
        except json.JSONDecodeError:
            send({"jsonrpc": "2.0", "id": None,
                  "error": {"code": -32700, "message": "Parse error"}})
            continue
        if "id" not in msg:
            continue  # notification, e.g. notifications/initialized
        handler = METHODS.get(msg.get("method"))
        if handler is None:
            send({"jsonrpc": "2.0", "id": msg["id"],
                  "error": {"code": -32601, "message": "Method not found"}})
            continue
        try:
            result = handler(msg.get("params") or {})
            send({"jsonrpc": "2.0", "id": msg["id"], "result": result})
        except LookupError as e:
            send({"jsonrpc": "2.0", "id": msg["id"],
                  "error": {"code": -32602, "message": str(e)}})

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

The interesting parts

Tools are just data plus a function. The @tool decorator stores a name, a description and a JSON Schema for the arguments. tools/list returns exactly that, and the model uses the description and schema to decide when and how to call the tool. Good descriptions matter more than clever code here.

Two kinds of errors. If the client calls a method that does not exist or names an unknown tool, that is a protocol error, so we return a JSON-RPC error (-32601 method not found, -32602 invalid params). If the tool itself fails, for example a missing argument, we return a normal result with isError: true. That way the model sees the failure as text and can fix its call and retry.

Notifications get silence. Anything without an id is skipped. Answering notifications/initialized is a classic bug that confuses clients.

stdout is sacred. Only protocol messages go to stdout, one JSON object per line, flushed right away. If you want debug output, write it to stderr. A stray print() will break the session.

Try it by hand

Save the file as server.py and pipe a few messages into it:

printf '%s\n' \
  '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"me","version":"1"}}}' \
  '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
  '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \
  '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add","arguments":{"a":2,"b":40}}}' \
  | python3 server.py
Enter fullscreen mode Exit fullscreen mode

You get three responses (the notification gets none), and the last one is:

{"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "42"}], "isError": false}}
Enter fullscreen mode Exit fullscreen mode

Plug it into a real client

Most MCP clients take a config entry with a command to launch. For example:

{
  "mcpServers": {
    "tiny-mcp": {
      "command": "python3",
      "args": ["/absolute/path/to/server.py"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Restart the client and the add and word_count tools show up. Ask it to add two numbers and watch it call your 90 lines of Python.

Where to go next

This covers the handshake and tools. A real server usually adds:

  • Resources (resources/list and resources/read) to expose files or data the model can read.
  • Stricter validation of arguments against the schema before calling the tool.
  • Version negotiation, answering with a protocol version both sides support.

If you want to build it step by step with tests checking each stage (handshake, tools, resources, protocol errors), in any language and your own editor, there is a guided project for that: Build your own MCP server.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The 'stdout is sacred' rule is the line that would have saved me an afternoon, Shipcode — a stray print() breaking the session is exactly the kind of bug that looks like the client is broken, not your code. The framing I would add is that the whole protocol is a REPL with an id: read a line, answer with the same id, stay silent for anything without one. Once you see it that way, the 90 lines stop feeling like a protocol and start feeling like a loop you could write from memory. The part I would add next is the long-running tool: a tool that takes thirty seconds is where the simple loop first breaks, because the client is waiting on one line of stdout, so progress notifications are the next real lesson. Which was the first real tool you plugged in after add and word_count — the one that made the server feel useful instead of a demo?