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:
| Shape | Fields | Example |
|---|---|---|
| Request | jsonrpc: "2.0", id, method, params | {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {...}} |
| Result | jsonrpc, the same id, result | {"jsonrpc": "2.0", "id": 1, "result": {...}} |
| Error | jsonrpc, the same id, error with code, message and optional data | {"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "Method not found"}} |
| Notification | jsonrpc, 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.
-
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 . -
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)) -
Run it:
python wire.pyThe 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, 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:
| Code | Name | When this server sends it |
|---|---|---|
-32600 | Invalid request | A message that does not fit the connection, such as a modern envelope on a connection in the older era (next lesson) |
-32601 | Method not found | An unknown or removed method; data carries the name |
-32602 | Invalid params | A missing or malformed _meta envelope; also a resource URI that does not exist, with the URI in data |
-32603 | Internal error | An unexpected exception inside a handler |
-32020 | Header mismatch | Over HTTP, when the version header and the envelope disagree (transports module) |
-32021 | Missing required client capability | The server needs a capability the client did not declare |
-32022 | Unsupported protocol version | A 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
| Symptom | Cause | Fix |
|---|---|---|
The script prints >> and then waits forever | readline() 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 it | Check the message has an id, ends in \n and is flushed |
json.decoder.JSONDecodeError: Expecting value | The 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 Popen | sys.executable is fine, but preview_server.py is not in the current folder | Copy it in, as step 1 does |
A reply with a different id than expected | Replies are read in order; a left-over reply from an earlier request is being matched | Send 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
- In exchange 4, label each of the four lines as request, result, error or notification, and say which field made the decision.
- Exchange 6 reports a failure inside a result. Why is that not a JSON-RPC error, and who is meant to read the message?
- The script's
sendfunction reads lines until the reply'sidmatches. 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
- Line 1 is a request: it has an
idand amethod. Lines 2 and 3 are notifications: they have amethodbut noid. Line 4 is a result: it has the request'sidand aresultfield. An error would have theidand anerrorfield instead. - 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. - 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
idis what real clients do, because notifications can arrive at any time.