Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Debugging MCP servers

After this lesson: I can find the fault in an MCP server by reading a log of its messages.

65 min lesson6 commandsAgent lab: write an AI agent loop with tools, with a stand-in model

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

How to debug an MCP server

Debugging an MCP server means watching every message between client and server and checking each one. When a host says "server failed to start", the cause is almost always in those messages.

The MCP Inspector is the official tool that shows them. You will build its core in the lab and use it to find two common faults.

By the end of this lesson

Note

I can find the fault in an MCP server by reading a log of its messages.

Key words

WordWhat it meansExample
Inspectorthe MCP project's tool for calling a server and showing every message
Transcriptthe messages sent and received, in order
stdoutthe stream a stdio server sends messages on
stderrthe stream for a server's logs
Framinghow one message is told apart from the nextone per line

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The Inspector shows every message

On your own computer, npx @modelcontextprotocol/inspector starts the Inspector. Give it the command that starts your server, or a server address, and it lists the tools, calls them and shows each JSON-RPC message.

It comes as a web page, a command line and a terminal screen. The lab has no internet and no npm, so here you build its heart: a transcript of every line, with checks.

Two faults break most stdio servers

Over stdio, each message is one line on stdout, and that framing is all the client has. So one print("starting") on stdout puts a line in front of the client that is not JSON, and many clients give up.

Logs belong on stderr, which the client keeps apart. The other common fault is a reply whose id matches no request, so the client waits for ever.

Try it: check a transcript

Code: python
# A transcript: what the client sent (->) and what came back (<-).
import json

lines = [
    ["->", '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'],
    ["<-", "Loading tools..."],
    ["<-", '{"jsonrpc": "2.0", "id": 1, "result": {"tools": []}}'],
]
for number, (way, text) in enumerate(lines, 1):
    try:
        json.loads(text)
        print(number, way, "ok")
    except ValueError:
        print(number, way, "NOT JSON:", text)
# Add a reply with "id": 9. How would you notice it in this check?

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Write the lesson 1 server again, part 1

Command
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"A small MCP server over stdio. Which one it is comes from its first argument.\"\"\"' 'import json' 'import sys' 'VERSION = \"2026-07-28\"' 'SERVERS = {' '    \"buses\": [\"next_bus\", \"Next buses at a stop.\", \"stop\", {\"Market Street\": \"8:05 and 8:20\"}],' '    \"weather\": [\"forecast\", \"Tomorrow in a town.\", \"town\", {\"Leeds\": \"Rain, 9 C\"}],' '}' 'NAME = sys.argv[1]' 'TOOL, ABOUT, ARG, DATA = SERVERS[NAME]' 'SCHEMA = {\"type\": \"object\", \"properties\": {ARG: {\"type\": \"string\"}}, \"required\": [ARG]}' 'def answer(msg):' '    params = msg.get(\"params\", {})' '    asked = params.get(\"_meta\", {}).get(\"io.modelcontextprotocol/protocolVersion\")' '    if not asked == VERSION:' '        return {\"error\": {\"code\": -32022, \"message\": \"Unsupported protocol version\",' '                          \"data\": {\"supported\": [VERSION], \"requested\": asked}}}' > mcp/server.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the lesson 1 server again, part 2

Command
docker exec tools sh -c "printf '%s\n' '    if msg[\"method\"] == \"server/discover\":' '        about = {\"io.modelcontextprotocol/serverInfo\": {\"name\": NAME, \"version\": \"1.0\"}}' '        return {\"result\": {\"resultType\": \"complete\", \"supportedVersions\": [VERSION],' '                           \"capabilities\": {\"tools\": {}}, \"_meta\": about}}' '    if msg[\"method\"] == \"tools/list\":' '        tool = {\"name\": TOOL, \"description\": ABOUT, \"inputSchema\": SCHEMA}' '        return {\"result\": {\"resultType\": \"complete\", \"tools\": [tool],' '                           \"ttlMs\": 60000, \"cacheScope\": \"public\"}}' '    if msg[\"method\"] == \"tools/call\":' '        value = params[\"arguments\"][ARG]' '        text = DATA.get(value, \"nothing known for \" + value)' '        return {\"result\": {\"resultType\": \"complete\", \"isError\": False,' '                           \"content\": [{\"type\": \"text\", \"text\": text}]}}' >> mcp/server.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the lesson 1 server again, part 3

Command
docker exec tools sh -c "printf '%s\n' '    return {\"error\": {\"code\": -32601, \"message\": \"Method not found\"}}' '' '' '# One message a line in, one a line out. Logs would go to stderr, never stdout.' 'for line in sys.stdin:' '    msg = json.loads(line)' '    reply = {\"jsonrpc\": \"2.0\", \"id\": msg[\"id\"]}' '    reply.update(answer(msg))' '    print(json.dumps(reply), flush=True)' >> mcp/server.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the transcript checker, part 1

Command
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"Runs a client against four copies of the lesson 1 server, logs every line and checks it.\"\"\"' 'import json' 'import subprocess' 'import sys' 'Q = chr(34)' 'SOURCE = open(\"mcp/server.py\").read()' 'COPIES = {' '    \"good\": SOURCE,' '    \"chatty\": SOURCE.replace(\"for line in sys.stdin:\", \"print(\" + Q + \"starting\" + Q + \")\" + chr(10) + \"for line in sys.stdin:\"),' '    \"to_stderr\": SOURCE.replace(\"for line in sys.stdin:\", \"print(\" + Q + \"starting\" + Q + \", file=sys.stderr)\" + chr(10) + \"for line in sys.stdin:\"),' '    \"wrong_id\": SOURCE.replace(\"msg[\" + Q + \"id\" + Q + \"]}\", \"7}\"),' '}' 'ASK = {\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"server/discover\",' '       \"params\": {\"_meta\": {\"io.modelcontextprotocol/protocolVersion\": \"2026-07-28\"}}}' 'for name, text in COPIES.items():' '    with open(\"mcp/\" + name + \".py\", \"w\") as out:' '        out.write(text)' > mcp/debug.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the transcript checker, part 2

Command
docker exec tools sh -c "printf '%s\n' '    run = subprocess.run([sys.executable, \"mcp/\" + name + \".py\", \"buses\"], input=json.dumps(ASK) + chr(10),' '                         capture_output=True, text=True, timeout=10)' '    print(name)' '    print(\"  -> \" + json.dumps(ASK)[:60] + \" ...\")' '    for line in run.stderr.splitlines():' '        print(\"  stderr: \" + line)' '    for line in run.stdout.splitlines():' '        print(\"  <- \" + line[:60] + (\" ...\" if len(line) > 60 else \"\"))' '        try:' '            reply = json.loads(line)' '        except ValueError:' '            print(\"  PROBLEM: this line is not JSON. stdout must carry only MCP messages.\")' '            continue' '        if not reply.get(\"id\") == ASK[\"id\"]:' '            print(\"  PROBLEM: reply id\", reply.get(\"id\"), \"matches no request.\")' >> mcp/debug.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check four copies of the server

Command
docker exec tools python3 mcp/debug.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What debug.py printed

CopyWhat the transcript showedVerdict
goodOne request, one reply with id 1No problem
chatty<- starting, then the replyPROBLEM: this line is not JSON
to_stderrstderr: starting, then the replyNo problem: logs on stderr are fine
wrong_idA reply with id 7PROBLEM: reply id 7 matches no request

The cells students fill in are left blank in this preview.

Check the Run

Have a go

Check the Run

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people debug a stdio server by adding print statements. Over stdio a print goes to stdout, into the message stream, and makes a new fault. Print to stderr, write to a log file, or watch the messages in the Inspector instead.

Debug from the outside in

Work in this order. Does the server start, and does it stay up? Does each line parse as JSON? Does each reply carry the id of a request?

Then check the content: the version in _meta, resultType, and the headers on HTTP. Run the Inspector's command-line client in a test so a broken server fails before a person meets it.

Outside in: where to look first

flowchart LR
  A[Does it start?] --> B[Is every stdout line JSON?]
  B --> C[Does each reply match an id?]
  C --> D[Version and resultType right?]
  D --> E[Tool results right?]

Match each symptom to its likely cause

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Assignment: check a transcript

Write the check at the heart of a debugging tool.

check_transcript(lines) reads a list of [direction, text] pairs and returns the problems it finds, by the rules in the starter: lines that are not JSON, ids sent twice, replies to unknown ids, and requests never answered.

Code: python
import json


def check_transcript(lines):
    # lines: a list of [direction, text], direction "->" (sent) or "<-" (received).
    # Return a list of problems, in the order found, then the unanswered ones:
    #   "line N is not JSON"     a received line that is not JSON (N counts from 1)
    #   "id X sent twice"        a sent request reusing an id still waiting
    #   "reply to unknown id X"  a received reply whose id is not waiting
    #   "no reply to id X"       at the end, every id still waiting, in the order sent
    # A message with no "id" is a notification: it needs no reply.
    return []

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.