Contract Tests and the Inspector
Explore the tracker server with the MCP Inspector (web UI and --cli), then write 15 contract tests with Python unittest that pin discovery, version errors, cache hints, tool definitions, schema-valid results, pagination, tool errors and resources, run them against both server tracks, and prove a test fails when stdout is polluted.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Explore the server in the Inspector
- Step 2: Script quick checks with --cli
- Step 3: Write the contract tests
- Step 4: Run the suite against both tracks
- Step 5: Prove that a test can fail
- Check your understanding
- Apply it
- Review prompt
Lessons of Building MCP Servers
- A First Server with an Official SDK Worked example · 20 min
- Designing Tools for Agents, Not for APIs Concept · 15 min
- Lab: Wrap a REST API as an MCP Server Lab · 30 min
- Contract Tests and the Inspector Lab · 20 min
- Remote Deployment with OAuth Authorization Worked example · 25 min
- Check: Server Design Review Knowledge check · 8 questions
What you will learn
- Test a server with the MCP Inspector and automated contract tests covering tool schemas, results and error cases.
Prerequisites: MCP Fundamentals
01. Goal and setup
A contract test pins the interface that hosts rely on: which tools exist, their schemas, the shape of results and the way errors are reported. It does not judge whether a model picks the right tool; that is an evaluation, a different activity. Contract tests run on every change, so a renamed field or a changed error path fails in CI instead of in a user's host.
You will use two tools:
- the MCP Inspector, the project's interactive client, to explore the server by hand and to script quick checks;
- unittest, from the Python standard library, for tests that start the server as a subprocess and speak MCP 2026-07-28 over stdio.
This lab continues in the tracker-lab folder from Lab: Wrap a REST API as an MCP Server. You need its files tracker_api.py, tracker_client.py, tracker_mcp.py, stdio_server.py, mini_schema.py and wire.py. If you skipped that lab, do its steps 1 to 5 first. The Inspector version pinned here, 2.15.0 (the same as in the MCP fundamentals lab), declares Node.js 22.23.4+, 24.22.1+ or 26.12.1+; the tests need only Python. Start the mock API again if it is not running:
export TRACKER_API_TOKEN=lab-only-token-not-a-secret
python tracker_api.py &02. Step 1: Explore the server in the Inspector
The Inspector starts your server as a subprocess, connects as a client and shows everything it exposes. Pin the version, as the Inspector documentation recommends for anything repeatable; -e passes an environment variable to the server. --protocol-era modern matters too: the Inspector negotiates the legacy era (the initialize handshake) unless told otherwise, and this lesson tests the 2026-07-28 per-request _meta style.
npx -y @modelcontextprotocol/[email protected] --protocol-era modern \
-e TRACKER_API_TOKEN=$TRACKER_API_TOKEN python tracker_mcp.pyOpen the URL it prints and check, by hand, what the tests will later check automatically:
- Tools lists
search_issues,get_issueandset_issue_state, each with an input and an output schema. - Calling
search_issueswithlabelset toauthandlimitto 3 showsstructuredContentand a text block; calling it again with the returned cursor shows the next three issues. - Calling
get_issuewith 99999 returns a result marked as an error, with the message aboutsearch_issues. - Resources shows the template
issues://{number}; readingissues://101returns the full record.
The Inspector stores secrets it is given, such as -e values, in the operating-system keychain, or in a file under ~/.mcp-inspector/ when there is no keychain. Use lab-only tokens with it.
03. Step 2: Script quick checks with --cli
The same package has a command-line mode for scripts and CI. With --cli, the server command comes first; everything after -- is an option for the Inspector itself. That split holds only when the line starts with the server command: put an Inspector option such as --protocol-era before the command and -- reverses, sending what follows to the server. --format json prints one JSON object, ready for jq, which keeps the output below short. The second command saves the result to a file so that $? is the exit code of the Inspector, not of a later command in a pipe.
INSPECT="npx -y @modelcontextprotocol/[email protected] --cli"
$INSPECT python tracker_mcp.py -- -e TRACKER_API_TOKEN=$TRACKER_API_TOKEN \
--protocol-era modern --method tools/list --format json \
| jq -r '.result.tools[].name'
$INSPECT python tracker_mcp.py -- -e TRACKER_API_TOKEN=$TRACKER_API_TOKEN \
--protocol-era modern --method tools/call --tool-name get_issue \
--tool-arg number=99999 > miss.json 2>/dev/null
echo "exit code: $?"
jq -c '{isError}' miss.json
$INSPECT python tracker_mcp.py -- -e TRACKER_API_TOKEN=$TRACKER_API_TOKEN \
--protocol-era modern --method resources/templates/list --format json \
| jq -r '.result.resourceTemplates[].uriTemplate'search_issues
get_issue
set_issue_state
exit code: 5
{"isError":true}
issues://{number}The first command lists the three tools in their fixed order. The second exits with code 5, which the 2.x CLI uses for a tool result with isError: true (version 1 exited 0), and miss.json holds the message about search_issues; on stderr the CLI also prints an error envelope with the code tool_is_error. The third lists the template issues://{number}. --method tools/list --strict also reports schema portability problems and exits 6 if any are serious. There is no --test option: the Inspector inspects and smoke-tests, and your test runner runs test suites.
04. Step 3: Write the contract tests
The tests talk to the server through wire.py from lab 3, so they work with any stdio server, whatever language or SDK it uses. The environment variable SERVER holds the command that starts it. The suite has five gates:
- Discovery and versions:
server/discoverlists 2026-07-28 and the tools and resources capabilities; an unknown version gets-32022with the supported list; a request without_metagets-32602; discovery, list and read results carry the required cache hintsttlMsandcacheScope. - Tool definitions:
tools/listreturns the same tools in the same order twice, with valid names, real descriptions and object schemas. - Results: happy-path results validate against each tool's
outputSchema, and the text block holds the same JSON. Followingnext_cursorvisits every match once, in order. - Errors: bad arguments, a stale cursor, a missing issue and an upstream outage are tool errors with useful messages; an unknown tool is rejected.
- Resources: the template is listed and readable, and a missing issue is
-32602with the URI.
Gate 0 is implicit: wire.py fails any test that sees a line on stdout that is not JSON-RPC.
"""Contract tests for the tracker MCP server, over stdio (stdlib unittest).
SERVER="python tracker_mcp.py" python -m unittest -v test_contract
"""
import json
import os
import re
import shlex
import unittest
from mini_schema import errors
from wire import META, StdioServer
TARGET = "2026-07-28"
class TrackerContract(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = StdioServer(shlex.split(os.environ["SERVER"]))
cls.tools = {t["name"]: t for t in cls.result("tools/list")["tools"]}
@classmethod
def tearDownClass(cls):
cls.server.close()
@classmethod
def result(cls, method, params=None):
reply = cls.server.request(method, params)
assert "result" in reply, reply
return reply["result"]
def call(self, name, **arguments):
return self.result("tools/call", {"name": name, "arguments": arguments})
def assert_valid_result(self, name, result):
self.assertFalse(result["isError"], result["content"])
data = result["structuredContent"]
self.assertEqual(errors(self.tools[name]["outputSchema"], data), [])
self.assertEqual(json.loads(result["content"][0]["text"]), data)
# Gate 1: discovery and versions
def test_discover_names_target_version_and_capabilities(self):
found = self.result("server/discover")
self.assertIn(TARGET, found["supportedVersions"])
self.assertIn("tools", found["capabilities"])
self.assertIn("resources", found["capabilities"])
def test_unknown_version_gets_unsupported_version_error(self):
reply = self.server.request("tools/list", meta=META | {
"io.modelcontextprotocol/protocolVersion": "1900-01-01"})
self.assertEqual(reply["error"]["code"], -32022)
self.assertIn(TARGET, reply["error"]["data"]["supported"])
def test_request_without_meta_is_invalid_params(self):
reply = self.server.request("tools/list", meta=None)
self.assertEqual(reply["error"]["code"], -32602)
def test_cacheable_results_carry_ttl_and_scope(self):
uri = {"uri": "issues://101"}
for method, params in [("server/discover", None), ("tools/list", None),
("resources/templates/list", None),
("resources/read", uri)]:
with self.subTest(method=method):
result = self.result(method, params)
self.assertIsInstance(result["ttlMs"], int)
self.assertGreaterEqual(result["ttlMs"], 0)
self.assertIn(result["cacheScope"], ("public", "private"))
# Gate 2: tool definitions
def test_tool_list_is_stable_and_well_formed(self):
again = self.result("tools/list")["tools"]
self.assertEqual([t["name"] for t in again], list(self.tools))
self.assertEqual(list(self.tools),
["search_issues", "get_issue", "set_issue_state"])
for tool in again:
with self.subTest(tool=tool["name"]):
self.assertRegex(tool["name"], r"^[A-Za-z0-9_.-]{1,128}$")
self.assertGreater(len(tool["description"]), 20)
self.assertEqual(tool["inputSchema"]["type"], "object")
self.assertEqual(tool["outputSchema"]["type"], "object")
# Gate 3: results match their output schema
def test_search_returns_schema_valid_page_with_text_copy(self):
result = self.call("search_issues", label="auth", limit=3)
self.assert_valid_result("search_issues", result)
self.assertEqual(len(result["structuredContent"]["issues"]), 3)
def test_cursor_walks_every_match_once_in_order(self):
seen, cursor = [], None
while True:
more = {"cursor": cursor} if cursor else {}
data = self.call("search_issues", label="auth", limit=3, **more)
data = data["structuredContent"]
seen += [i["number"] for i in data["issues"]]
cursor = data["next_cursor"]
if cursor is None:
break
everything = self.call("search_issues", label="auth", limit=50)
expected = [i["number"] for i in everything["structuredContent"]["issues"]]
self.assertEqual(seen, expected)
self.assertEqual(seen, sorted(set(seen)))
def test_get_issue_keeps_the_id_for_follow_up_calls(self):
result = self.call("get_issue", number=101)
self.assert_valid_result("get_issue", result)
self.assertEqual(result["structuredContent"]["number"], 101)
def test_state_change_round_trip(self):
closed = self.call("set_issue_state", number=102, state="closed")
self.assert_valid_result("set_issue_state", closed)
reopened = self.call("set_issue_state", number=102, state="open")
self.assertEqual(reopened["structuredContent"]["state"], "open")
# Gate 4: error behaviour
def test_bad_arguments_are_tool_errors(self):
for name, args in [("search_issues", {"limit": 500}),
("search_issues", {"cursor": "not-a-cursor"}),
("get_issue", {"number": 0}),
("set_issue_state", {"number": 101, "state": "gone"})]:
with self.subTest(name=name, args=args):
self.assertTrue(self.call(name, **args)["isError"])
def test_missing_issue_tells_the_model_what_to_do(self):
result = self.call("get_issue", number=99999)
self.assertTrue(result["isError"])
self.assertIn("search_issues", result["content"][0]["text"])
def test_upstream_outage_is_a_tool_error(self):
result = self.call("get_issue", number=666)
self.assertTrue(result["isError"])
self.assertIn("Try again", result["content"][0]["text"])
def test_unknown_tool_is_rejected(self):
reply = self.server.request("tools/call", {"name": "drop_tables"})
if "error" in reply: # what the spec shows: a protocol error
self.assertEqual(reply["error"]["code"], -32602)
else: # what the Python SDK 2.3 does: a tool error result
self.assertTrue(reply["result"]["isError"])
# Gate 5: resources
def test_issue_template_is_listed_and_readable(self):
templates = self.result("resources/templates/list")["resourceTemplates"]
self.assertIn("issues://{number}", [t["uriTemplate"] for t in templates])
contents = self.result("resources/read", {"uri": "issues://101"})["contents"]
self.assertEqual(json.loads(contents[0]["text"])["number"], 101)
def test_missing_resource_is_invalid_params(self):
reply = self.server.request("resources/read", {"uri": "issues://99999"})
self.assertEqual(reply["error"]["code"], -32602)
self.assertEqual(reply["error"]["data"]["uri"], "issues://99999")
if __name__ == "__main__":
unittest.main()Three choices keep the suite useful. It starts the server once per run, which is safe because 2026-07-28 is stateless: each request carries everything the server needs. The write test restores the state it changed, so the suite can run again against the same API. And the unknown-tool test accepts both a protocol error and a tool error, because the specification and the Python SDK differ there, as you saw in lab 3. Pin the behaviour of your own server more tightly if you can.
05. Step 4: Run the suite against both tracks
SERVER="python stdio_server.py" python -m unittest test_contract 2>&1 \
| sed -E 's/ in [0-9.]+s$//'
SERVER="python tracker_mcp.py" python -m unittest test_contract 2>&1 \
| sed -E 's/ in [0-9.]+s$//'...............
----------------------------------------------------------------------
Ran 15 tests
OK
...............
----------------------------------------------------------------------
Ran 15 tests
OKunittest prints its report on stderr, hence 2>&1, and sed removes the run time from the Ran line, because it differs on every machine. All 15 tests pass on both servers. That shows each server meets the contract written down here: discovery, version errors, cache hints, stable tool definitions, schema-valid results with text copies, pagination, error behaviour, resources and a clean stdout. It does not prove full compliance with the specification, and a hand-written suite only checks what you thought of: without the cache-hint test, it would pass a Track B that the official SDK client rejects. So keep the sdk_client.py run from lab 3 next to the suite, and add a test whenever your hosts start to rely on another part of the protocol. The servers' own log lines are in server-stderr.log.
06. Step 5: Prove that a test can fail
A test that has never failed may not test anything. Break Track B on purpose: in stdio_server.py, add print("debug:", msg.get("method")) as the first line of handle(), a typical leftover from debugging. Run the suite again and keep only the interesting lines.
SERVER="python stdio_server.py" python -m unittest test_contract 2>&1 \
| grep -E "^(AssertionError|Ran|FAILED)" | sed -E "s/ in [0-9.]+s$//"AssertionError: not JSON-RPC on stdout: 'debug: tools/list\n'
Ran 0 tests
FAILED (errors=1)The stray line reaches stdout before the response, so wire.py rejects it while the suite is still starting (setUpClass lists the tools), and no test runs. A real host would fail in a similar way, often with a vague parse error. Remove the print line and the suite passes again. The SDK protects Track A against most of this: while it serves, it diverts flushed writes to stdout onto stderr. Logging to stderr is still the rule.
In CI, start the mock API, run the suite against your server, and fail the build on a non-zero exit code. If you add Inspector checks there, pin an exact Inspector version and use --format json with jq assertions.
07. Check your understanding
08. Apply it
Extend the suite for the fourth tool you added in lab 3: a schema-valid happy path, an argument error and an upstream error. Then add one test you expect to fail today, for example that search_issues rejects an unknown state value, watch it fail, and decide whether to change the server or the test. Finally, run the suite in a CI job with the mock API started first, and add one Inspector CLI smoke check with a pinned version.
09. Review prompt
From memory, list the five gates of the suite with one assertion each, and explain why the suite can run unchanged against an SDK server and a hand-written one. Then say what the Inspector is good for, what it is not, and what a passing contract suite does and does not prove.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.