Model Context Protocol (MCP) for Developers / Protocol Foundations

Read the wire: JSON-RPC by hand

Lesson 4 of 29. Open to read. No account needed.

What You Will Build

The SDK client hid the messages from you in the last lesson. This lesson removes it: you start the preview server as a child process, write protocol messages to it one line at a time with nothing but the standard library, and read every byte that comes back. Six messages show a server describing itself, listing and reading a resource, running a tool with its two result channels, sending progress notifications in the middle of a call, and reporting a tool failure. The independent task sends four requests the server must refuse and predicts each reply from the rules.

Everything the SDK does from here on is some arrangement of these messages, so reading them once by hand makes every later error message legible.

Bridge 1: JSON-RPC

MCP messages are JSON-RPC 2.0, a small convention for calling named methods with JSON (S75). There are four shapes:

ShapeFieldsExample
Requestjsonrpc: "2.0", id, method, params{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {...}}
Resultjsonrpc, the same id, result{"jsonrpc": "2.0", "id": 1, "result": {...}}
Errorjsonrpc, the same id, error with code, message and optional data{"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "Method not found"}}
Notificationjsonrpc, method, params, and no id{"jsonrpc": "2.0", "method": "notifications/progress", "params": {...}}

A request gets exactly one reply, a result or an error, carrying the request's id; that is how a client matches replies to requests when several are in flight. A notification gets no reply at all. Error codes are integers: -32700 (parse error), -32600 (invalid request), -32601 (method not found), -32602 (invalid params) and -32603 (internal error) are defined by JSON-RPC itself; MCP adds codes of its own in the -32000 to -32099 range, which the lesson returns to (S42).

Bridge 2: a Child Process with Pipes

A local MCP server is a program that reads messages from its standard input and writes replies to its standard output, one JSON object per line (S44). To talk to one you start it as a child process with both streams connected to your program. Python's subprocess.Popen does this (S93):

server = subprocess.Popen([sys.executable, "preview_server.py"],
                          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                          stderr=subprocess.DEVNULL, text=True)

sys.executable is the Python running your script, so the server uses the course environment. stdin=PIPE and stdout=PIPE give you server.stdin to write to and server.stdout to read from; stderr=DEVNULL discards the server's log lines, which otherwise appear in your terminal mixed with the output; text=True makes both streams strings rather than bytes. Writing a message is write of one line ending in a newline, then flush() so it leaves the buffer now; reading a reply is readline(), which blocks until the server has written a whole line. Closing server.stdin tells the server there is no more input, and the SDK's server exits cleanly when that happens; wait() collects its exit code.

Exercise: Six Messages

Goal: send six hand-written messages to the preview server and read each reply as a result, an error or a notification.

Starting state: the course environment active; ~/mcp-practice/server-tour/preview_server.py from the previous lesson.

Effects: creates a folder with a copy of the server and one script; the script starts the server as a child process and stops it at the end. No network is used.

  1. Create the folder and copy the server in. macOS and Linux:

    mkdir -p ~/mcp-practice/wire-by-hand
    cd ~/mcp-practice/wire-by-hand
    cp ~/mcp-practice/server-tour/preview_server.py .
    

    Windows PowerShell:

    mkdir $HOME\mcp-practice\wire-by-hand
    cd $HOME\mcp-practice\wire-by-hand
    copy $HOME\mcp-practice\server-tour\preview_server.py .
    
  2. Save this as wire.py:

    """Send hand-written JSON-RPC messages to the preview server over stdio."""
    import json
    import subprocess
    import sys
    
    META = {
        "io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientCapabilities": {},
        "io.modelcontextprotocol/clientInfo": {"name": "wire-by-hand", "version": "0.1"},
    }
    
    server = subprocess.Popen(
        [sys.executable, "preview_server.py"],
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
    )
    
    
    def send(message: dict) -> dict:
        """Write one message as one line, then read replies until the response with the same id."""
        print(">>", json.dumps(message))
        server.stdin.write(json.dumps(message) + "\n")
        server.stdin.flush()
        while True:
            reply = json.loads(server.stdout.readline())
            print("<<", json.dumps(reply))
            if reply.get("id") == message["id"]:
                return reply
    
    
    send({"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": META}})
    send({"jsonrpc": "2.0", "id": 2, "method": "resources/list", "params": {"_meta": META}})
    send({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "stock_level", "arguments": {"sku": "belt-m6"}, "_meta": META}})
    send({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "recount_bin", "arguments": {"bin_id": "A1"}, "_meta": {**META, "progressToken": "count-1"}}})
    send({"jsonrpc": "2.0", "id": 5, "method": "resources/read", "params": {"uri": "inventory://summary", "_meta": META}})
    send({"jsonrpc": "2.0", "id": 6, "method": "tools/call", "params": {"name": "stock_level", "arguments": {"sku": "gear-7"}, "_meta": META}})
    
    server.stdin.close()
    print("server exit code:", server.wait(timeout=10))
    
  3. Run it:

    python wire.py
    

    The script prints each message it sends after >> and each line it receives after <<. The six exchanges are shown and read one at a time below; your output is the same, apart from nothing (the server is deterministic).

Exchange 1: the server describes itself

>> {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}, "io.modelcontextprotocol/clientInfo": {"name": "wire-by-hand", "version": "0.1"}}}}
<< {"jsonrpc": "2.0", "id": 1, "result": {"cacheScope": "private", "capabilities": {"prompts": {"listChanged": true}, "resources": {"listChanged": true, "subscribe": true}, "tools": {"listChanged": true}}, "instructions": "Read-only view of a workshop parts inventory.", "resultType": "complete", "supportedVersions": ["2026-07-28"], "ttlMs": 0, "_meta": {"io.modelcontextprotocol/serverInfo": {"name": "inventory-preview", "version": "0.1.0"}}}}

The request's params holds only _meta, and _meta is the envelope every request in this protocol revision carries: the protocol version the client is speaking, the client's capabilities (none here) and, optionally, who the client is. server/discover is the method a client calls to learn about a server (S50), and the previous lesson's header lines came from this one result: supportedVersions, capabilities (with the wire spelling listChanged), instructions, and serverInfo tucked inside the result's own _meta. resultType: "complete" says this reply is final rather than a request for more input; ttlMs and cacheScope tell a client how long it may cache the answer and for whom. Every result in the rest of the transcript carries the same serverInfo and resultType.

Exchange 2: list the resources

>> {"jsonrpc": "2.0", "id": 2, "method": "resources/list", "params": {"_meta": {...}}}
<< {"jsonrpc": "2.0", "id": 2, "result": {"cacheScope": "private", "resources": [{"description": "Totals for the whole inventory.", "mimeType": "text/plain", "name": "summary", "uri": "inventory://summary"}], "resultType": "complete", "ttlMs": 0, "_meta": {"io.modelcontextprotocol/serverInfo": {"name": "inventory-preview", "version": "0.1.0"}}}}

({...} stands for the same envelope as in exchange 1; your output prints it in full.) One fixed resource; the template is listed by a different method, resources/templates/list, which the tour used.

Exchange 3: call a tool

>> {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "stock_level", "arguments": {"sku": "belt-m6"}, "_meta": {...}}}
<< {"jsonrpc": "2.0", "id": 3, "result": {"content": [{"text": "belt-m6: 7 each in bin B1", "type": "text"}], "isError": false, "resultType": "complete", "structuredContent": {"result": "belt-m6: 7 each in bin B1"}, "_meta": {...}}}

tools/call names the tool and passes its arguments as an object. The result has two channels: content, a list of blocks for the model to read (one text block here), and structuredContent, data for the application; because the tool returned a plain string, the SDK wrapped it under a result key. isError: false says the tool ran and succeeded. The structured-results lesson shows how to shape the second channel.

Exchange 4: a call that reports progress

>> {"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "recount_bin", "arguments": {"bin_id": "A1"}, "_meta": {..., "progressToken": "count-1"}}}
<< {"jsonrpc": "2.0", "method": "notifications/progress", "params": {"progressToken": "count-1", "progress": 1, "total": 2, "message": "counted bolt-m4"}}
<< {"jsonrpc": "2.0", "method": "notifications/progress", "params": {"progressToken": "count-1", "progress": 2, "total": 2, "message": "counted bolt-m6"}}
<< {"jsonrpc": "2.0", "id": 4, "result": {"content": [{"text": "bin A1: 2 parts counted", "type": "text"}], "isError": false, "resultType": "complete", "structuredContent": {"result": "bin A1: 2 parts counted"}, "_meta": {...}}}

The request adds progressToken to _meta, which is the client saying "I would like progress reports, and tag them with this token". The server sends two notifications/progress messages before the result: no id, a progressToken matching the request, a rising progress with an optional total and message (S53). This is why send in the script reads lines in a loop until it sees the request's id: notifications arrive on the same stream, interleaved with results, and a client must be ready for them.

Exchange 5: read a resource

>> {"jsonrpc": "2.0", "id": 5, "method": "resources/read", "params": {"uri": "inventory://summary", "_meta": {...}}}
<< {"jsonrpc": "2.0", "id": 5, "result": {"cacheScope": "private", "contents": [{"mimeType": "text/plain", "text": "6 parts, 264 units in stock, 3 below their reorder level", "uri": "inventory://summary"}], "resultType": "complete", "ttlMs": 0, "_meta": {...}}}

A read returns contents, a list because one URI may yield several items, each with its uri, mimeType and either text or base64 blob.

Exchange 6: a tool that fails

>> {"jsonrpc": "2.0", "id": 6, "method": "tools/call", "params": {"name": "stock_level", "arguments": {"sku": "gear-7"}, "_meta": {...}}}
<< {"jsonrpc": "2.0", "id": 6, "result": {"content": [{"text": "Error executing tool stock_level: Unknown part 'gear-7'; known parts: ['belt-m6', 'bolt-m4', 'bolt-m6', 'cable-m4', 'nut-m4', 'washer-m4']", "type": "text"}], "isError": true, "resultType": "complete", "_meta": {...}}}
server exit code: 0

The part does not exist, so the tool raised an error. Notice what the server sent: a result, not a JSON-RPC error, with isError: true and the message as text content. The distinction is deliberate. A JSON-RPC error means the protocol exchange itself failed (bad request, unknown method); a tool failing is a normal outcome that the model should read and act on, so it travels as a result the model will see (S42). There is no structuredContent on a failed call. The last line is the server's exit code after stdin was closed: 0, a clean stop.

Success: six exchanges as above, two progress notifications before the fourth result, isError: true on the sixth, and exit code 0.

The Shape of a Message

A request and its result drawn side by side. The request shows jsonrpc 2.0, id 3, method tools/call and params holding name, arguments and the _meta envelope with protocolVersion, clientCapabilities and clientInfo. The result shows the same id 3 and a result holding content, structuredContent, isError, resultType complete and _meta with serverInfo. Below them a notification shows jsonrpc, method notifications/progress and params, with the id slot crossed out to show it has none.

A request, its result and a notification. The id ties a result to its request; a notification has none.

Error Codes

The independent task below produces four errors. Here are the codes you will meet in this course, from the base protocol (S42) and the recorded replies of this server:

CodeNameWhen this server sends it
-32600Invalid requestA message that does not fit the connection, such as a modern envelope on a connection in the older era (next lesson)
-32601Method not foundAn unknown or removed method; data carries the name
-32602Invalid paramsA missing or malformed _meta envelope; also a resource URI that does not exist, with the URI in data
-32603Internal errorAn unexpected exception inside a handler
-32020Header mismatchOver HTTP, when the version header and the envelope disagree (transports module)
-32021Missing required client capabilityThe server needs a capability the client did not declare
-32022Unsupported protocol versionA version the server does not speak; data lists supported and requested

Codes from -32000 to -32019 are reserved for the older era's errors, and -32020 to -32099 for this revision's.

When It Goes Wrong

SymptomCauseFix
The script prints >> and then waits foreverreadline() is waiting for a reply that will not come: the message had no id (a notification), the newline or flush() was left out, or the line was not valid JSON and the server ignored itCheck the message has an id, ends in \n and is flushed
json.decoder.JSONDecodeError: Expecting valueThe server wrote something that is not JSON to standard output, or exited before replying (an empty line)Run python preview_server.py alone to see the error; make sure the file is in this folder
FileNotFoundError on Popensys.executable is fine, but preview_server.py is not in the current folderCopy it in, as step 1 does
A reply with a different id than expectedReplies are read in order; a left-over reply from an earlier request is being matchedSend one request at a time, as send does, and read until the matching id

Your Turn: Four Refusals

Predict the reply to each of these before running them: a request with params but no _meta; a request whose envelope claims version 2030-01-01; a ping request (a method the older era had and this revision removed); and a read of inventory://bins/Z9, a bin that does not exist. Use the error-code table. Then save this as wire_errors.py and run it:

"""One good request to fix the era, then four requests the server must refuse."""
import json
import subprocess
import sys

META = {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}
server = subprocess.Popen([sys.executable, "preview_server.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)


def send(message: dict) -> None:
    print(">>", json.dumps(message))
    server.stdin.write(json.dumps(message) + "\n")
    server.stdin.flush()
    print("<<", server.stdout.readline().strip())


send({"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": META}})
send({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}})
send({"jsonrpc": "2.0", "id": 3, "method": "tools/list", "params": {"_meta": {**META, "io.modelcontextprotocol/protocolVersion": "2030-01-01"}}})
send({"jsonrpc": "2.0", "id": 4, "method": "ping", "params": {"_meta": META}})
send({"jsonrpc": "2.0", "id": 5, "method": "resources/read", "params": {"uri": "inventory://bins/Z9", "_meta": META}})
server.stdin.close()
server.wait(timeout=10)

The script sends one good server/discover first; the next lesson explains why that matters.

Reset and Clean Up

The script starts and stops its own server, so rerunning it is safe. Remove this lesson's folder after looking at it; keep server-tour, which the next lesson still uses. macOS and Linux:

cd ~/mcp-practice
ls
rm -r wire-by-hand
ls

Windows PowerShell:

cd $HOME\mcp-practice
ls
Remove-Item -Recurse wire-by-hand
ls

.venv, data and server-tour remain.

Check Your Understanding

  1. In exchange 4, label each of the four lines as request, result, error or notification, and say which field made the decision.
  2. Exchange 6 reports a failure inside a result. Why is that not a JSON-RPC error, and who is meant to read the message?
  3. The script's send function reads lines until the reply's id matches. What would go wrong if it read exactly one line per request?

Answer and Reasoning

Your turn

>> {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}}}
<< {"jsonrpc":"2.0","id":1,"result":{"cacheScope":"private","capabilities":{"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":true},"tools":{"listChanged":true}},"instructions":"Read-only view of a workshop parts inventory.","resultType":"complete","supportedVersions":["2026-07-28"],"ttlMs":0,"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"inventory-preview","version":"0.1.0"}}}}
>> {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}
<< {"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"params._meta must be an object carrying the required 'io.modelcontextprotocol/protocolVersion' and 'io.modelcontextprotocol/clientCapabilities' envelope keys"}}
>> {"jsonrpc": "2.0", "id": 3, "method": "tools/list", "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2030-01-01", "io.modelcontextprotocol/clientCapabilities": {}}}}
<< {"jsonrpc":"2.0","id":3,"error":{"code":-32022,"message":"Unsupported protocol version","data":{"supported":["2026-07-28"],"requested":"2030-01-01"}}}
>> {"jsonrpc": "2.0", "id": 4, "method": "ping", "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}}}
<< {"jsonrpc":"2.0","id":4,"error":{"code":-32601,"message":"Method not found","data":"ping"}}
>> {"jsonrpc": "2.0", "id": 5, "method": "resources/read", "params": {"uri": "inventory://bins/Z9", "_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}}}
<< {"jsonrpc":"2.0","id":5,"error":{"code":-32602,"message":"inventory://bins/Z9","data":{"uri":"inventory://bins/Z9"}}}

The server's error replies are printed as the server wrote them, without spaces after the colons; the script's own messages were formatted by json.dumps. All four are JSON-RPC errors, unlike the failed tool call in exchange 6: each one is a request the server could not process at all. The missing envelope is invalid params (-32602) and the message names the two required keys; the unknown version is -32022 with supported and requested in data, which is how a client learns what to retry with; ping is -32601 because this revision removed it, with the method name in data; the missing resource is -32602 with the URI in data, the code the resources specification assigns to a URI the server does not have.

Understanding check

  1. Line 1 is a request: it has an id and a method. Lines 2 and 3 are notifications: they have a method but no id. Line 4 is a result: it has the request's id and a result field. An error would have the id and an error field instead.
  2. The protocol exchange succeeded: the server understood the request, found the tool and ran it; the tool itself reported that the part is unknown. That outcome is for the model, which can read "known parts" and call again with a valid code, so it travels as content with isError: true. A JSON-RPC error is for the client program and means the request could not be carried out as a request.
  3. For the progress call it would return the first notification as if it were the reply, and every later request would be answered with the previous request's leftover lines, one message late. Reading until the matching id is what real clients do, because notifications can arrive at any time.

References

24 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy