Test and debug an MCP server — pytest and the patched Inspector
MCP Engineering course · M2
This guide is the printable companion to lesson L09. It covers the two ways the course tests a server: automated tests with pytest and the official SDK client, and the MCP Inspector, pinned to a patched release and used safely. The server under test is the lab-l08 notes server.
What changed in V2: the earlier version of this guide launched the Inspector with an unpinned npx command and described its web panels. Inspector releases below 0.14.1 allow unauthenticated remote code execution (CVE-2025-49596), and more advisories, two of them critical, were fixed in October and November 2026. V2 installs the Inspector at 2.16.0 from a lock file, uses its CLI mode, and does not describe UI panels that were not verified against 2.16.0.
Step 1 — Tests first: two layers
Download Lab files (ZIP); you need both lab-l08/ and lab-l09/. The lab-l09 tests import ../lab-l08/notes_server.py instead of copying it, so they cannot drift from the server.
| Item | Version | ||||
|---|---|---|---|---|---|
Python / mcp / pytest | 3.12.x / 2.3.0 / 9.2.0 (uv.lock, with hashes) | ||||
@modelcontextprotocol/inspector | 2.16.0, exact in package.json; package-lock.json with integrity hashes | ||||
| Node for the Inspector | `^22.23.4 \ | \ | ^24.22.1 \ | \ | >=26.12.1` |
Layer 1: in-memory. The official Client accepts the MCPServer object itself: no subprocess, no network, fast. A fixture resets the in-memory store after each test:
@pytest.fixture
def server():
"""The MCPServer instance, with the in-memory notes store reset after each test."""
snapshot = copy.deepcopy(notes_server._NOTES)
yield notes_server.mcp
notes_server._NOTES.clear()
notes_server._NOTES.update(snapshot)
@pytest.mark.parametrize("bad_id, fragment", [
("n-1", "expected the format N-001"),
("../../secret", "expected the format N-001"),
("N-404", "No note with id N-404"),
])
async def test_get_note_bad_input_is_a_tool_error_not_a_crash(server, bad_id, fragment):
async with Client(server) as client:
r = await client.call_tool("get_note", {"note_id": bad_id})
assert r.is_error is True
assert fragment in r.content[0].text
Other in-memory tests check that every tool has a real description (the model reads it), that add_note returns structuredContent matching its outputSchema, that a schema violation (an 81-character title) returns isError, and that state changes show up in the notes://index resource.
Layer 2: stdio. These tests launch the server as a subprocess, the way a host does:
PARAMS = StdioServerParameters(command=sys.executable, args=[str(SERVER_FILE)], cwd=str(LAB_L08))
async def test_stdio_modern_negotiates_2026_07_28():
async with Client(PARAMS) as client:
assert client.protocol_version == "2026-07-28"
A second stdio test uses Client(PARAMS, mode="legacy") and expects the 2025-11-25 handshake (legacy). A third proves stdout hygiene: if the server printed anything to stdout, the JSON-RPC stream would break. In-memory tests cannot catch that, which is why you need both layers.
Step 2 — Install the Inspector, pinned
The Inspector is a local program that launches the commands you give it with your user's privileges. Lab-l09 does not fetch it at run time:
"devDependencies": {
"@modelcontextprotocol/inspector": "2.16.0"
}
run.sh installs it with npm ci --ignore-scripts and runs node_modules/.bin/mcp-inspector. The Inspector does not check its Node range itself (in the lab build it also started on Node 22.14.0), so run.sh checks the version before launching it.
If you ever launch it outside the lab, pin the exact version and type the name exactly:
npx @modelcontextprotocol/inspector@2.16.0 --cli /abs/path/.venv/bin/python /abs/path/notes_server.py --method tools/list
For a TypeScript server, launch it with the project's locally installed runner or compiled JS (node_modules/.bin/tsx server.ts, or node dist/server.js), never with a second unpinned npx nested inside the first.
Step 3 — CLI mode (headless, good for CI)
--cli runs one method and prints JSON. The lab's exact calls:
"$INSPECTOR" --cli "$PY" "$SERVER" --method tools/list
"$INSPECTOR" --cli "$PY" "$SERVER" --method tools/call --tool-name get_note --tool-arg note_id=N-001
"$INSPECTOR" --cli "$PY" "$SERVER" --method resources/read --uri notes://index
In 2.16.0 a tool result with isError: true makes the CLI exit with code 5 and print {"error":{"code":"tool_is_error",...}}. The CLI opens no listening port.
UI mode: ./run.sh ui starts the web interface for the lab-l08 server on 127.0.0.1 with the defaults kept. The lab did not exercise the UI, so this guide does not describe its panels.
Step 4 — Safe use of the Inspector
| Rule | Why |
|---|---|
| Pin the exact version (2.16.0, or 1.0.6 on the v1 line) | Both include the fixes for every advisory published as of 2026-11-26. Recheck the advisories page before you upgrade or teach. |
| Localhost only | HOST defaults to 127.0.0.1; all-interface binds are refused unless DANGEROUSLY_BIND_ALL_INTERFACES is set. Never set it, never use HOST=0.0.0.0, and never expose the port through a tunnel or reverse proxy. |
| Keep the token on | MCP_INSPECTOR_API_TOKEN defaults to a random per-launch token that guards every /api/* route. Never set DANGEROUSLY_OMIT_AUTH, and never share the URL that carries the token. |
| Connect only to servers you trust | The critical 2026 RCEs were triggered by malicious servers (for example through an OAuth callback). |
| Mind secrets at rest | Without an OS keychain, secrets go to ~/.mcp-inspector/secrets.json, "unencrypted unless you supply a key". The lab sets MCP_CATALOG_PATH inside the lab so the CLI does not create ~/.mcp-inspector/. |
Logging is deprecated in protocol 2026-07-28. To debug, read the server's stderr: the Inspector CLI shows it (lines starting [notes-server]).
Diagnosing common errors
| Symptom | Likely cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'mcp.server.fastmcp' | Code written for SDK 1.x (legacy) | from mcp.server import MCPServer (L08) |
| stdio calls fail, in-memory tests pass | Something printed to stdout | Log to stderr; the stdout test catches this |
Result has isError: true | Tool execution error: bad input or a business rule | Read the message; that is what the model sees |
| Unknown tool name | Spec: JSON-RPC -32602; mcp 2.3.0 returned isError: true with Unknown tool: ... | Handle both shapes in clients |
| Tool missing in a TypeScript server | Wrong registration call | Use server.registerTool(...) (L10); server.tool(...) is the deprecated SDK 1.x form |
uv sync --locked fails | pyproject.toml and uv.lock disagree | Re-lock on purpose, re-run the tests |
node ...: TOO OLD for Inspector 2.16.0 | Node outside the supported range | Install a qualifying Node (L02) |
| Works in tests, fails in a host | Relative paths, or a different python | Register absolute paths (L08) |
| A host on the 2025-era handshake cannot connect | The server is modern-only | Serve both eras; SDK 2.3.0 does by default |
Practice and expected result
cd lab-l09
./run.sh # pytest, then the Inspector CLI checks
./run.sh test # pytest only (no Node needed)
- pytest reports
13 passed(10 in-memory, 3 stdio). node v...: OK for Inspector 2.16.0 (^22.23.4 || ^24.22.1 || >=26.12.1), then== Inspector versionprints2.16.0.tools/listreturnsadd_noteandget_note, each withinputSchema,outputSchemaandannotations.get_note note_id=N-001returnsstructuredContentwith"id": "N-001"and"isError": false.note_id=badreturns"isError": true, then(Inspector CLI exit code 5 for the isError result, as expected).- The last line is
L09 VERIFY: pytest and Inspector CLI both completed.
To remember
- Test in two layers: in-memory for speed, stdio for the process boundary and stdout hygiene.
- Inspector 2.16.0 (or 1.0.6), installed from a lock file; never an unpinned
npx. - 127.0.0.1 only, token on, no
DANGEROUSLY_*variables, trusted servers only. - CLI exit code 5 = the tool returned
isError: true. - Debug with the server's stderr; protocol logging is deprecated.
Turning Point Academy · MCP Engineering course · Module 2 · Lesson 9 (L09) · V2, spec 2026-07-28