MCP servers and clients · Chapter 2 of 16

JSON-RPC by hand

By the end of this chapter you can read and write every message MCP sends: requests, results, errors and notifications in JSON-RPC 2.0, one per line over a program's stdin and stdout. You will write a small server and a client with nothing but the standard library. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The protocol
  • 5 tasks
  • Python
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Gopal wants a price checker at every counter: a cashier scans a packet, the screen shows Bazaar Bhai's price, the MRP and the GST. The screens come from a vendor whose software is not written in Python, and it will talk to your code over a pipe. Before you write anything with the mcp package, Simran wants you to write the messages yourself.

Her reason is practical. An SDK hides the messages, which is what you want on a good day. On a bad day a client hangs, or a server says nothing, or an app gets an answer it never asked for, and the only truth is the lines that crossed the pipe. Every MCP message is JSON-RPC 2.0, so once you can read those lines, you can debug any MCP server or client, in any language.

The lesson

Four shapes

JSON-RPC 2.0 is a small standard for calling a method in another program: the whole specification fits on a few pages. A message is a JSON object, and there are four kinds.

A request asks the other side to run a method. It has the version, an id the caller picks, the method's name and, if the method takes any, its params:

{"jsonrpc": "2.0", "id": 1, "method": "store_hours", "params": {"store_id": "BB05"}}

A response answers one request, with the same id, and either a result or an error, never both:

{"jsonrpc": "2.0", "id": 1, "result": {"opens": "07:00", "closes": "23:00"}}
{"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "Method not found", "data": "nope"}}

The result can be any JSON value. An error has an integer code, a message for people, and optional data with more detail.

A notification is a request with no id key at all. It says something and expects nothing, and the receiver never replies to it, not even with an error. MCP uses notifications for things like "I am ready" and "here is some progress". Note the difference between "id": null and no id: the first is a request with a strange id, the second a notification.

The id is the caller's to choose: a number or a string. 0 is a fine id, which is worth remembering the day an if id: skips one.

The standard error codes

The specification reserves five codes, and an MCP server uses the same ones:

CodeNameWhen
-32700Parse errorthe line is not JSON at all
-32600Invalid RequestJSON, but not a request object
-32601Method not foundno such method here
-32602Invalid paramsthe method exists; its params are wrong
-32603Internal errorthe server failed while running it

A parse error has a problem: the server could not read the message, so it cannot know its id. The reply carries "id": null, the JSON value, which is None in Python. The string "null" is a different id, and a client waiting on it would be confused.

One message per line

MCP's stdio transport is the simplest possible: the client starts the server as a subprocess, writes messages to its stdin and reads replies from its stdout. Each message is one line of JSON, ended by a newline, in UTF-8. json.dumps writes a dict on one line, so a minimal server is a loop over the lines of stdin:

import json, sqlite3, sys

for line in sys.stdin:
    message = json.loads(line)
    if "id" not in message:
        continue
    with sqlite3.connect("/workspace/data/bazaar.db") as db:
        opens, closes = db.execute("SELECT opens, closes FROM stores WHERE id = ?",
                                   (message["params"]["store_id"],)).fetchone()
    reply = {"jsonrpc": "2.0", "id": message["id"], "result": {"opens": opens, "closes": closes}}
    print(json.dumps(reply), flush=True)
$ echo '{"jsonrpc": "2.0", "id": 1, "method": "store_hours", "params": {"store_id": "BB05"}}' | python3 hours_rpc.py
{"jsonrpc": "2.0", "id": 1, "result": {"opens": "07:00", "closes": "23:00"}}

Two rules come with the pipe, and both cause real bugs:

  • stdout is for protocol messages only. A print("ready") lands in the client's input, where it is not JSON. Logs, banners and debugging go to stderr: print(..., file=sys.stderr).
  • Flush every line. When stdout is a pipe, Python keeps output in a buffer and writes it out in chunks. Your reply sits in the buffer, and the client waits for a line that never arrives. flush=True sends it now.

This server is also fragile. Send it a line that is not JSON and it dies:

$ echo 'hello' | python3 hours_rpc.py
...
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

A server is a long-running program that strangers talk to. It must answer a bad message with the right error and carry on with the next one.

A client over pipes

The other side is subprocess.Popen with pipes for the child's stdin and stdout. You write a line and flush, then read a line:

server = subprocess.Popen([sys.executable, "hours_rpc.py"],
                          stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
request = {"jsonrpc": "2.0", "id": 1, "method": "store_hours", "params": {"store_id": "BB21"}}
server.stdin.write(json.dumps(request) + "\n")
server.stdin.flush()
reply = json.loads(server.stdout.readline())
print(reply["id"], reply["result"])
1 {'opens': '08:00', 'closes': '23:00'}

Leave out the flush() and this program never prints anything: the request waits in the client's buffer, the server waits for a request, and readline() waits for the server. Both sides are polite, and nothing moves.

Matching replies by id

Nothing in JSON-RPC says replies come back in order. A server may work on several requests at once and answer a quick one before a slow one. That is what the id is for: the client keeps track of what it asked under each id, and pairs every reply with its request when it arrives.

Count, too. Three requests and one notification are four messages, but only three replies will ever come. A client that reads one line per message sent waits forever on the fourth.

What an MCP server does

The mcp package's servers speak exactly this. Here is the chapter 1 stock_server.py, sent messages by hand over its stdin after its opening handshake (chapter 3; trimmed here). Each -> line was sent, each <- line received:

-> {"jsonrpc":"2.0","method":"notifications/initialized"}
-> {"jsonrpc":"2.0","id":2,"method":"nope"}
<- {"jsonrpc":"2.0","id":2,"error":{"code":-32601,"message":"Method not found","data":"nope"}}
-> hello
-> {"jsonrpc":"2.0","id":3,"method":"ping"}
<- {"jsonrpc":"2.0","id":3,"result":{}}

The notification gets no reply, as the rules say. The line that is not JSON gets no reply either: this server chooses to skip it, where your server in this chapter answers -32700. Both keep serving. ping with an empty result is real MCP: either side may send it to check the other is alive.

Your turn

Build the four messages in task 1, then the price server in tasks 2 and 3: answer price_of and ping, then every kind of bad message, without ever stopping. Task 4 talks to price_desk.py, which answers in its own order: match by id, and count the replies you wait for. The interview question is a server with three bugs that this chapter has named.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    messages.py: the four messages

    Every MCP message is one of four JSON-RPC 2.0 shapes. In messages.py, write four functions that return the message as a dict:

    request(id, method, params=None) returns {"jsonrpc": "2.0", "id": id, "method": method, "params": params}, without params when it is None.

    result(id, value) returns {"jsonrpc": "2.0", "id": id, "result": value}.

    error(id, code, message, data=None) returns {"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message, "data": data}}, without data when it is None. The id may be None, and the key stays.

    notification(method, params=None) returns {"jsonrpc": "2.0", "method": method, "params": params}, without params when it is None, and with no id key at all.

    An id of 0 or a string is a real id.

  2. Task 2

    price_rpc.py: a JSON-RPC server

    Gopal's price checkers will talk to your code over a pipe. In price_rpc.py, read JSON-RPC messages from stdin, one per line, until stdin ends, and write each reply to stdout as one line of JSON:

    price_of with params {"product_id": "P017"} replies with the result {"product_id": "P017", "name": "Masoor Dal 1 kg", "price": 115, "mrp": 115, "gst_rate": 5}, from the products table of /workspace/data/bazaar.db.

    ping replies with the result {}.

    Every reply carries "jsonrpc": "2.0" and the request's id exactly as it came (a number or a string). Print nothing else on stdout, and flush after every reply.

  3. Task 3

    price_rpc.py: every bad message

    A server must survive anything a client sends. Make price_rpc.py answer each bad message with an error object (a code and a message) and keep serving:

    a line that is not JSON: -32700, with the id null;

    JSON that is not a request (not an object, or no "jsonrpc": "2.0", or no method): -32600;

    a method it does not have: -32601;

    price_of without a product_id, or for a product that is not in the database: -32602, with a message that names the missing parameter or the unknown id.

    A notification (a message with no id key) gets no reply at all, whatever its method.

  4. Task 4

    ask_rpc.py: a client over pipes

    price_desk.py is a finished JSON-RPC server that answers in its own order. In ask_rpc.py, start it with subprocess.Popen, with pipes for its stdin and stdout, and send it:

    three requests, price_of for P047, P086 and P150, with the ids 1, 2 and 3;

    one notification, log, with the params {"message": "price check from ask_rpc"}.

    Read the three replies and print one line per request, in the order of the ids: for a product, P047 <name>: ₹<price> (MRP ₹<mrp>, GST <gst_rate>%); for an error, P150: error <code> <message>.

    Do not open the database in this file.

  5. Task 5 · interview question

    Interview: fix_me.py, a server that breaks the rules

    fix_me.py is the supplier desk: a JSON-RPC server answering supplier_of {"product_id": ...} and ping. Gopal's client cannot talk to it. Fix its three bugs, changing as little as you can:

    the first line on stdout must be a JSON-RPC message;

    a notification never gets a reply;

    a parse error's id is JSON null, not a string.

    It must still answer supplier_of and ping as it does now.

What you will learn

  • The four shapes of a JSON-RPC message: request, result, error and notification.
  • The standard error codes, and which one fits which mistake.
  • Messages over stdio: one per line, flushed, and nothing else on stdout.
  • Matching replies by id, because a server may answer in its own order.

More in The protocol

Build "JSON-RPC by hand" yourself

Bazaar Bhai, a chain of 40 kirana stores in Jaipur, exposes its stock and orders once, to every AI tool. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.