MCP servers and clients in TypeScript · 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 Node's own modules. 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
  • TypeScript
  • 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 TypeScript, and it will talk to your code over a pipe. Before you write anything with the MCP SDK, 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, even 0 or null. An error has an integer code, a message for people, and optional data with more detail. Spaces and the order of the keys do not matter: JSON.stringify writes no spaces, and the SDK you meet in chapter 4 puts result before jsonrpc. Both are the same message.

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 (message.id) skips one.

Telling the shapes apart in TypeScript

In TypeScript each shape is an object type, and a message is the union of the four. Nothing in a message says "I am a notification": you tell them apart by which keys are there, and the in operator does exactly that. TypeScript understands it, so inside the branch it knows which type you have. Here is the same idea on two other things that happen in a store:

type Delivery = { supplier: string; cases: number };
type Sale = { store: string; amount: number };

function describe(event: Delivery | Sale): string {
  if ('cases' in event) return `${event.supplier} delivered ${event.cases} cases`;
  return `${event.store} sold ₹${event.amount}`;
}
S03 delivered 4 cases
BB11 sold ₹1250

One JavaScript detail matters for JSON-RPC: a key set to undefined is still a key. JSON.stringify leaves it out of the text, but in still finds it:

const note = { jsonrpc: '2.0', id: undefined, method: 'log' };
console.log(JSON.stringify(note));
console.log('id' in note);
{"jsonrpc":"2.0","method":"log"}
true

On the wire that is a notification; in your own program, 'id' in note says it is a request. Build a message by adding a key only when you have a value for it, and the two never disagree.

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 null in TypeScript too. 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 child process, 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.stringify writes an object on one line, and console.log adds the newline. Node's node:readline module turns any stream into lines, so a minimal server is a loop over the lines of process.stdin:

import { createInterface } from 'node:readline';
import { DatabaseSync } from 'node:sqlite';

const db = new DatabaseSync('/workspace/data/bazaar.db', { readOnly: true });
const hours = db.prepare('SELECT opens, closes FROM stores WHERE id = ?');

for await (const line of createInterface({ input: process.stdin })) {
  const message = JSON.parse(line);
  if (!('id' in message)) continue;
  const row = hours.get(message.params.store_id);
  console.log(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { ...row } }));
}
$ echo '{"jsonrpc":"2.0","id":1,"method":"store_hours","params":{"store_id":"BB05"}}' | node hours-rpc.ts
{"jsonrpc":"2.0","id":1,"result":{"opens":"07:00","closes":"23:00"}}

The for await loop reads one line, handles it, and waits for the next; when stdin ends, the loop ends and so does the program. ({ ...row } copies the row into a plain object: SQLite hands back an object with no prototype, which prints oddly but turns into the same JSON.)

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

  • stdout is for protocol messages only. console.log writes to stdout, so a console.log('ready') lands in the client's input, where it is not JSON. Logs, banners and debugging go to stderr: console.error(...).
  • The newline ends the message. The reader on the other side waits for it. console.log adds one; process.stdout.write and child.stdin.write write exactly what you give them and nothing more.

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

$ echo 'hello' | node hours-rpc.ts
...
SyntaxError: Unexpected token 'h', "hello" is not valid JSON
    at JSON.parse (<anonymous>)

And JSON.parse happily returns any JSON value, not only objects. Send it the line null and the in check is what crashes:

$ echo null | node hours-rpc.ts
...
TypeError: Cannot use 'in' operator to search for 'id' in null

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. Parsing gives you unknown in spirit: check that it is an object (and not null, whose typeof is also 'object', and not an array) before you look inside.

A client over pipes

The other side is spawn from node:child_process. It starts the server and gives you child.stdin to write to and child.stdout to read from; readline turns the stdout into lines again:

const server = spawn(process.execPath, ['hours-rpc.ts']);
const lines = createInterface({ input: server.stdout });
server.stdin.write(JSON.stringify(request) + '\n');
for await (const line of lines) {
  const reply = JSON.parse(line);
  console.log(reply.id, reply.result);
  break;
}
server.stdin.end();
1 { opens: '08:00', closes: '23:00' }

The request asked for BB21, Tilak Nagar. Two lines in it each prevent a program that never ends:

  • Leave out the + '\n' and nothing prints, ever: the server's readline is still waiting for the end of the line, and the client waits for the server. timeout 5 has to kill it (exit 124).
  • Leave out server.stdin.end() and the answer prints, but the program still never exits: the server is waiting for its next line, and a running child process keeps your Node alive. Ending its stdin is how you say "that is all"; its loop finishes and it exits.

Node has no output buffer to flush here, unlike some languages: a write goes to the pipe at once. Its traps are the missing newline and the forgotten end().

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. In TypeScript a Map from id to "what I am waiting for" is the natural shape, and it is what the SDK's own client keeps inside.

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

What an MCP server does

The MCP SDK's servers speak exactly this. Here is chapter 1's stock-server.ts, sent messages by hand over its stdin after its opening handshake (chapter 3 shows that part). 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"}}
-> hello
-> {"jsonrpc":"2.0","id":3,"method":"ping"}
<- {"result":{},"jsonrpc":"2.0","id":3}

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. And result comes first in the SDK's reply: the key order really does not matter.

Your turn

Build the four messages and kindOf 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.ts, which answers in its own order: match by id, count the replies you wait for, and end its stdin. 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.ts: the four messages

    Every MCP message is one of four JSON-RPC 2.0 shapes. In messages.ts, export a type for each shape, a Message type that is their union, and four functions that return the message as an object:

    request(id, method, params?) returns { jsonrpc: '2.0', id, method, params }, without the params key when no params were given.

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

    error(id, code, message, data?) returns { jsonrpc: '2.0', id, error: { code, message, data } }, without the data key when no data was given. The id may be null, and the key stays.

    notification(method, params?) returns { jsonrpc: '2.0', method, params }, without the params key when no params were given, and with no id key at all.

    Then export kindOf(message), which returns 'request', 'notification', 'result' or 'error' for any Message, by the keys it has. An id of 0, a string id and a null id are all real ids, and a result of 0 or null is still a result.

  2. Task 2

    price-rpc.ts: a JSON-RPC server

    Gopal's price checkers will talk to your code over a pipe. In price-rpc.ts, 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, 0 included, or a string). Print nothing else on stdout.

  3. Task 3

    price-rpc.ts: every bad message

    A server must survive anything a client sends. Make price-rpc.ts 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 (a string, null, an array, 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.ts: a client over pipes

    price-desk.ts is a finished JSON-RPC server that answers in its own order. In ask-rpc.ts, start it with spawn from node:child_process 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>.

    Then end the desk's stdin so both programs finish. Do not open the database in this file.

  5. Task 5 · interview question

    Interview: fix-me.ts, a server that breaks the rules

    fix-me.ts 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, and how TypeScript tells them apart.
  • The standard error codes, and which one fits which mistake.
  • Messages over stdio: one per line, ended by a newline, 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. You build it in TypeScript. 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.