NewAI Content Creation is now live in Early Access
Turning Point Training Instituteby Training Center
Skip to content
0%
Module 2 — Build your first serverLesson 2 of 4
Video lesson

Test and debug an MCP server: pytest and the patched Inspector

IntermediateVideo lesson
7 min readIntermediate
Downloads & resources
Download this lesson's materials, ready to use.

Skill packs and prompts are provided in English so they work best with the AI tools. Use them as-is.

Test and debug an MCP server: pytest and the patched Inspector

Example prompt

Read this before the video (optional, partially obsolete). The Inspector part of the embedded freeCodeCamp course (YouTube DosHnyq78xY) launches the Inspector with an unpinned npx command, which today fetches whatever release is newest, and it shows an older Inspector interface. Do not copy that command. 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. Use only the pinned release 2.16.0, installed as this lesson shows, and keep its security defaults. Where the video and this lesson disagree, follow the lesson.

Where you are

Module 2, lesson 9. You built the lab-l08 notes server (L08). Now you test it automatically, inspect it with the Inspector's command-line mode, and learn to read the most common failures.

What you will be able to do

  • Write fast in-memory tests and realistic stdio tests for an MCP server with pytest and the official SDK client.
  • Install the MCP Inspector at a pinned, patched version and run it headless with --cli.
  • Use the Inspector safely: localhost only, per-launch token on, no DANGEROUSLY_* variables, trusted servers only.
  • Diagnose the errors learners hit most often.

Tests first: two layers

The lab-l09 tests import ../lab-l08/notes_server.py instead of copying it, so they cannot drift from the server. Download Lab files (ZIP); you need both lab-l08/ and lab-l09/. Pins: Python 3.12, mcp 2.3.0, pytest 9.2.0 (in uv.lock, with hashes).

Layer 1: in-memory. The official Client accepts the MCPServer object itself. No subprocess and no network, so these tests are fast. A fixture resets the in-memory store after each test:

python
@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)
python
@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:

python
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 and the call would fail. In-memory tests cannot catch that, which is why you need both layers.

The MCP Inspector, pinned

The Inspector is the official tool for interactive and scripted inspection of a server. Treat it as what it 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. package.json pins it exactly, and package-lock.json fixes every dependency with an integrity hash:

json
  "devDependencies": {
    "@modelcontextprotocol/inspector": "2.16.0"
  }

run.sh installs it with npm ci --ignore-scripts and runs node_modules/.bin/mcp-inspector. It needs Node ^22.23.4 || ^24.22.1 || >=26.12.1. The Inspector does not check this itself (in the lab build it also started on Node 22.14.0), so run.sh checks the version before launching it.

CLI mode (headless). --cli runs one method and prints JSON. These are the lab's exact calls:

bash
"$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",...}}. That makes it usable in CI. 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 lesson does not describe its panels.

Safe use of the Inspector

RuleWhy
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 onlyHOST defaults to 127.0.0.1, and all-interface binds are refused unless DANGEROUSLY_BIND_ALL_INTERFACES is set. Never set it, and never expose the port through a tunnel or reverse proxy.
Keep the token onMCP_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 trustThe critical 2026 RCEs were triggered by malicious servers (for example through an OAuth callback).
Mind secrets at restWithout 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

SymptomLikely causeFix
ModuleNotFoundError: No module named 'mcp.server.fastmcp'Code written for SDK 1.x (legacy)Use from mcp.server import MCPServer (L08)
Connection or calls fail over stdio, but in-memory tests passSomething printed to stdoutLog to stderr; the stdout test catches this
Result has isError: trueTool execution error: bad input or a business ruleRead the message; that is what the model sees. Not a crash
Unknown tool nameSpec example: JSON-RPC -32602. mcp 2.3.0 returned isError: true with Unknown tool: ... (L04)Handle both shapes in clients
uv sync --locked failspyproject.toml and uv.lock disagreeRe-lock on purpose, re-run the tests
node ...: TOO OLD for Inspector 2.16.0Node outside the supported rangeInstall a qualifying Node (L02)
Works in tests, fails in a hostRelative paths, or a different pythonRegister absolute paths (L08)
A host on the 2025-era handshake cannot connectThe server is modern-onlyServe both eras; SDK 2.3.0 does by default

Practice

In lab-l09/, with a qualifying Node on PATH:

bash
./run.sh            # pytest, then the Inspector CLI checks

Without Node, ./run.sh test runs only pytest.

Check your result

  • 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 version prints 2.16.0.
  • tools/list returns add_note and get_note, each with inputSchema, outputSchema and annotations.
  • get_note note_id=N-001 returns structuredContent with "id": "N-001" and "isError": false.
  • note_id=bad returns "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.

Compare with lab-l09/VERIFY-OUTPUT.txt.

Check your understanding

  1. Why keep stdio tests when the in-memory tests already cover every tool? In-memory tests skip the process boundary. Only a real subprocess shows stdout pollution, a missing dependency in the launched interpreter, or a handshake difference between the modern and legacy paths.

  2. A colleague sets DANGEROUSLY_OMIT_AUTH=true because pasting the token is annoying. What is the risk? The token is the only guard on the Inspector's /api/* routes, which can launch local commands. Without it, any page or process that reaches the port can drive it; the 2025 CVE-2025-49596 was exactly an unauthenticated proxy. Keep the default.

  3. In CI, the Inspector CLI step fails with exit code 5. Is the server broken? Not necessarily. In 2.16.0, exit code 5 means the tool returned isError: true. If your test deliberately sends bad input (as the lab does), that is the expected result; assert on it. If the input was valid, read the error text.

Sources