Sub topic 17
Testing and debugging your integration
This chapter assumes you have the minimal server.py (the add tool), the stdio client session, the to_llm_tools mapping and the agent loop from the earlier chapters. You should also be comfortable with pytest and async/await.
An MCP integration has three layers that can fail on their own: the server, the transport and session, and the model loop. Debugging goes faster if you test each layer separately and only then test them together.
Test in layers
The diagram shows where to look first for each kind of symptom.
Start at the top. If the Inspector can't run the tool, nothing in your client code will fix it.
Debug the server with the Inspector
The MCP Inspector is a web tool that connects to a server as a client. It lets you list tools, fill in arguments from the schema, call them, and watch the raw messages. Start it with npx, and put your server command after the package name:
npx @modelcontextprotocol/inspector python server.pyThe command prints a local URL. Open it, choose the stdio transport, connect, and open the Tools tab. Check three things:
- The tool appears with the name and description you expect.
- The input schema has the right types and marks the right fields as required.
- A call with valid arguments returns content, and a call with bad arguments returns an error instead of crashing the server.
If you installed the SDK with its CLI extra, mcp dev server.py starts the same Inspector for you.
The Inspector also shows a history of requests and responses. When your own client behaves differently from the Inspector, compare the two message sequences. The difference is usually in the arguments or in the handshake.
Keep stdout clean on stdio servers
On the stdio transport, the server writes protocol messages to stdout. A stray print() puts non-JSON text in that stream. The client then fails to parse it, and you see a hang or a parse error that doesn't mention your print.
Send diagnostics to stderr instead:
import logging
import sys
from mcp.server.fastmcp import FastMCP
logging.basicConfig(
stream=sys.stderr,
level=logging.INFO,
format="%(asctime)s %(name)s %(levelname)s %(message)s",
)
log = logging.getLogger("calc")
mcp = FastMCP("calc")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers."""
log.info("add called with a=%s b=%s", a, b)
return a + b
if __name__ == "__main__":
mcp.run(transport="stdio")When your client starts the server as a subprocess, the server's stderr goes to your client's stderr by default. The Inspector shows it in a log pane. With Streamable HTTP the rule is looser, because messages don't travel on stdout. Logging to stderr is still the safe habit.
Test the server through a real session
The most reliable server test uses the same path as production: launch the subprocess and talk to it through ClientSession. This catches schema, startup and transport problems that a direct function call would miss.
import asyncio
import sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
PARAMS = StdioServerParameters(command=sys.executable, args=["server.py"])
async def _with_session(fn):
async with stdio_client(PARAMS) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
return await fn(session)
def test_lists_add_tool_with_integer_schema():
async def check(session):
tools = (await session.list_tools()).tools
by_name = {t.name: t for t in tools}
assert "add" in by_name
props = by_name["add"].inputSchema["properties"]
assert props["a"]["type"] == "integer"
assert set(by_name["add"].inputSchema["required"]) == {"a", "b"}
asyncio.run(_with_session(check))
def test_add_returns_sum():
async def check(session):
result = await session.call_tool("add", {"a": 2, "b": 3})
assert not result.isError
assert result.content[0].text == "5"
asyncio.run(_with_session(check))
def test_bad_arguments_are_reported_as_tool_error():
async def check(session):
result = await session.call_tool("add", {"a": "two", "b": 3})
assert result.isError
asyncio.run(_with_session(check))Two details matter here. sys.executable makes the subprocess use the same interpreter and virtual environment as the test, which avoids a "module not found" failure caused by a different python on the path. The third test checks that a bad call comes back as a result with isError set, which is the path your agent loop must handle.
Unit-test the schema mapping
to_llm_tools is a pure function, so test it without a server. A stand-in object with the same attributes is enough.
from types import SimpleNamespace
def to_llm_tools(mcp_tools):
return [
{
"name": t.name,
"description": t.description or "",
"input_schema": t.inputSchema,
}
for t in mcp_tools
]
def test_mapping_renames_fields_and_defaults_description():
schema = {"type": "object", "properties": {"x": {"type": "string"}}}
tool = SimpleNamespace(name="echo", description=None, inputSchema=schema)
mapped = to_llm_tools([tool])
assert mapped == [{"name": "echo", "description": "", "input_schema": schema}]The test covers the one real edge case, a tool with no description. A missing description often makes the model call a tool poorly, so consider also failing a test when a description is empty.
Test the loop without a real model
Real model calls are slow, cost money and give different answers each time. To test the loop's logic, replace the model with a scripted fake that returns a tool request first and a final answer second. This requires run_turn to take the model client as a parameter, instead of using a module-level llm. That small change is worth making.
A fake response needs only the attributes the loop reads: content, stop_reason, and for each block type, id, name, input and text. With it you can assert:
- The loop sends a
tool_resultwith the matchingtool_use_idafter a tool call. - The loop returns the final text when
stop_reasonis not"tool_use". - A fake that always asks for a tool makes the loop raise at
MAX_STEPS, instead of running forever.
Keep a small number of tests against the real model, marked so they run only when you ask. They check that your prompt and tool descriptions lead to sensible tool choices, which a fake can't tell you.
Log what crosses the boundary
When a conversation goes wrong, you need to see what the model asked for and what the server returned. Log at the point where your loop calls the tool:
import json
import logging
import time
log = logging.getLogger("host")
async def logged_call(session, name, arguments):
started = time.perf_counter()
result = await session.call_tool(name, arguments)
log.info(
"tool=%s args=%s is_error=%s ms=%d",
name,
json.dumps(arguments),
result.isError,
(time.perf_counter() - started) * 1000,
)
return resultKeep secrets out of these logs. Arguments and results can contain user data, so truncate or redact them before they reach shared log storage.
Servers can also send log messages to the client over the protocol. In the Python SDK you can pass a logging_callback to ClientSession to receive them, so server-side logs show up beside your host logs.
Common failures
| Symptom | Likely cause | Check |
|---|---|---|
| Client hangs at `initialize()` | Server crashed on startup, or wrong command | Run the server command by hand and read stderr |
| JSON parse error from the client | Text on the server's stdout | Search for `print` and noisy imports |
| Tool missing from `list_tools` | Decorator not applied, or wrong server file | Compare against the Inspector's list |
| Model never calls the tool | Weak description or schema | Improve the description, then test with the real model |
| `isError` is true on a valid call | Server exception | Read the server's stderr log |
| Loop stops with `RuntimeError` | Model repeats a failing call | Log each step and return clearer error text |
Exercise
Your stdio server works in the Inspector but your client hangs right after initialize(). You recently added a line print("starting") at the top of server.py. Why can this cause the hang, and what is the fix?
Show answer
On stdio, the server's stdout carries the JSON-RPC messages. The extra "starting" line is not valid JSON, so the client's parser fails or waits on a corrupted stream. Replace print with logging configured to write to stderr, or remove the line.
Exercise
Why does the server test use sys.executable for the subprocess command instead of the string "python"?
Show answer
"python" is resolved through the system path and may point to a different interpreter than the one running the tests. That interpreter may lack the mcp package. sys.executable guarantees the server runs in the same environment as the test.
Exercise
Write down the three assertions you would put in a fake-model test of the agent loop that always returns a tool request.
Show answer
The loop calls the tool once per step and sends a tool_result with the matching tool_use_id. The loop stops after MAX_STEPS iterations. The loop raises RuntimeError instead of returning an answer.