Sub topic 17
Testing and debugging your integration
This chapter assumes you have the server.py and client session code from the earlier chapters. You should also be comfortable running pytest and reading JSON-RPC traces.
Test the server alone first
When a tool call fails inside an agent loop, you can't tell whether the server, the client or the model is at fault. Test the server by itself before you involve the model.
The MCP Inspector is a browser tool that connects to a server and lets you list tools, fill in arguments and see raw responses. Start it with your server command:
npx @modelcontextprotocol/inspector python server.pyIn the Inspector, open the Tools tab and run add with a=2 and b=3. Check three things:
- The
inputSchemamatches what you expect. - The result contains the right text.
- Bad input, such as a string for
a, returns an error result and not a crash.
Keep stdout clean
A stdio server uses stdout for protocol messages. If your code calls print(), that text gets mixed into the JSON-RPC stream. The client then fails with parse errors or hangs during initialize(). Write diagnostics to stderr instead.
import logging
import sys
logging.basicConfig(
level=logging.DEBUG,
stream=sys.stderr,
format="%(asctime)s %(name)s %(levelname)s %(message)s",
)
log = logging.getLogger("calc")Put this at the top of server.py, then call log.debug("add called: a=%s b=%s", a, b) inside your tools. The stdio client passes the server's stderr through to your terminal by default.
Automate a client-side test
Once the Inspector shows the server behaving correctly, capture that behavior in tests. These tests start the real server as a subprocess, so they exercise the same path your application uses.
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
params = StdioServerParameters(command="python", args=["server.py"])
async def call_add(a, b):
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
return await session.call_tool("add", {"a": a, "b": b})
def test_add_returns_sum():
result = asyncio.run(call_add(2, 3))
assert not result.isError
assert result.content[0].text == "5"
def test_bad_input_sets_is_error():
result = asyncio.run(call_add("x", 3))
assert result.isErrorRun it with pytest. These tests don't call a model, so they are fast, free and repeatable.
Narrow down failures
| Symptom | Likely cause | What to check |
|---|---|---|
| `initialize()` hangs or raises a parse error | Server wrote to stdout, or crashed on start | Run `python server.py` by hand and read stderr |
| Tool missing from `list_tools()` | Decorator not applied, or wrong file launched | Check `command` and `args` in `StdioServerParameters` |
| `isError` is true | Invalid arguments or an exception in the tool | Reproduce in the Inspector with the same arguments |
| Model never calls the tool | Weak description or schema mapping problem | Print the output of `to_llm_tools` |
| Loop ends with `RuntimeError` | Model keeps requesting tools | Log each tool name and input per step |
Exercise
Your client hangs during initialize() after you add print("starting") to the top of a stdio server. Why does this happen, and how do you fix it?
Show answer
Stdout carries the JSON-RPC messages, so the printed text corrupts the stream and the client cannot parse the handshake. Remove the print or send it to stderr, for example with logging configured to sys.stderr.