Sub topic 11
Testing with the MCP Inspector
This chapter assumes you have written a small MCP server with the Python SDK, as in the earlier chapters, and that you can run commands in a terminal. It also assumes you have Node.js installed, because the Inspector runs through npx. By the end you will know how to test your server's tools, resources, and prompts without a host application, and how to read the failures you are likely to see.
Why test before connecting a host
A host such as a chat application adds several layers between you and your server. The model decides whether to call a tool, picks arguments, and summarizes the result. When something goes wrong, you cannot tell whether your server, the model, or the host configuration caused it.
The MCP Inspector removes those layers. It is a developer tool that acts as a plain MCP client. It launches or connects to your server, performs the initialization handshake, and lets you call each feature by hand. If a tool works in the Inspector, any failure in a host is more likely a configuration or description problem than a server bug.
Testing here also checks what the model will actually see: tool names, descriptions, and JSON Schemas. You can read them exactly as a client receives them.
Starting the Inspector
Install the SDK with its command-line extras, then start the Inspector and give it the command that runs your server.
pip install "mcp[cli]"
npx @modelcontextprotocol/inspector python server.pyThe Inspector starts a local web interface and prints its address in the terminal. Open that address in a browser. Behind the scenes, it starts python server.py as a subprocess and talks to it over stdio, the same way a host would.
The SDK's command-line extras also include a shortcut. Running mcp dev server.py starts the Inspector for a FastMCP server file. The npx form works with any server in any language, so this chapter uses it.
What the Inspector connects with
The interface has connection settings on the left. For a local stdio server, they hold the transport type, the command, and its arguments. Those values correspond to the command and args keys you will later put in a host's configuration file. Getting them right here saves debugging time later.
If your server needs environment variables, such as an API token, add them in the Inspector's environment section. Do not hard-code secrets in the server file to make testing easier.
A server to test
The examples below use this server. It combines a tool, a resource template, and a prompt from the earlier chapters, and it logs to stderr.
import logging
import sys
from typing import Annotated, Literal
from pydantic import Field
from mcp.server.fastmcp import FastMCP
# With the stdio transport, stdout carries protocol messages.
# Send all logs to stderr so they do not corrupt the stream.
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
logger = logging.getLogger("team-tools")
mcp = FastMCP("team-tools")
OWNERS = {"billing": "payments-team", "search": "discovery-team"}
DEPLOYS = {
"staging": ["v1.4.2", "v1.4.1", "v1.4.0"],
"production": ["v1.4.0", "v1.3.9"],
}
RUNBOOKS = {
"billing": "1. Check the queue depth.\n2. Restart the worker.\n3. Page payments-team.",
}
@mcp.tool()
def get_service_owner(service: str) -> str:
"""Return the team that owns a service, given its short name."""
logger.info("get_service_owner called with %s", service)
if service not in OWNERS:
raise ValueError(f"Unknown service: {service}")
return OWNERS[service]
@mcp.tool()
def list_deploys(
environment: Literal["staging", "production"],
limit: Annotated[int, Field(ge=1, le=20)] = 5,
) -> list[str]:
"""List the most recent deployed versions for an environment, newest first."""
return DEPLOYS[environment][:limit]
@mcp.resource("runbook://{service}")
def runbook(service: str) -> str:
"""Runbook text for a service."""
return RUNBOOKS.get(service, "No runbook found.")
@mcp.prompt()
def incident_summary(service: str) -> str:
"""Ask the model to draft an incident summary for a service."""
return (
f"Draft a short incident summary for the {service} service. "
"Include impact, current status, and next steps."
)
if __name__ == "__main__":
mcp.run()Save it as server.py and start the Inspector against it.
A tour of the interface
After you click Connect, the Inspector runs the initialization handshake. It shows the server's name and the capabilities it declared. The interface then offers a tab for each feature.
| Tab | What it does | What to check |
|---|---|---|
| Tools | Lists tools and lets you call them with a form | Names, descriptions, input schemas, results |
| Resources | Lists resources and templates, and reads them by URI | URIs, content type, returned text |
| Prompts | Lists prompts and renders them with arguments | Argument names, the generated messages |
| Notifications / History | Shows messages exchanged during the session | Raw requests, responses, and server logs |
A tab appears only if the server declared the matching capability. If the Tools tab is missing, the server did not advertise tools, which usually means no tool was registered before mcp.run().
Testing tools
Open the Tools tab and choose List Tools. You should see get_service_owner and list_deploys. Select one and read three things.
- The description. It comes from the docstring. This is the text the model uses to decide when to call the tool. If it is vague, fix the docstring now.
- The input schema. For
list_deploys,environmentshould appear as an enum with two values.limitshould show a minimum of 1 and a maximum of 20, with a default of 5. If the schema shows a barestringwhere you expected an enum, the type hint is missing or wrong. - The required fields. Parameters without defaults should be required.
limitshould not be.
Run the happy path
Call get_service_owner with billing. The result should be payments-team. Then call list_deploys with production and a limit of 1. You should get ["v1.4.0"].
Run the failure paths
The failure paths matter more than the happy path, because a model will eventually send bad input. Try each of these:
- Call
get_service_ownerwithpayroll. Your function raisesValueError. The SDK catches it and returns a tool result flagged as an error, with the message in the content. The server process keeps running. The model can read the message and correct its call. - Call
list_deployswith a limit of0or50. Schema validation rejects the call before your function runs, so your own code never sees it. - Call
list_deployswithenvironmentset todev. The enum rejects it in the same way.
If a call crashes the server instead, the Inspector reports the connection as closed. Check the terminal where you started it for a Python traceback on stderr.
Testing resources and prompts
Open the Resources tab. Because runbook://{service} takes a parameter, it appears under Resource Templates, not in the plain resource list. Select the template, enter billing for service, and read it. You should see the three-step runbook. Try payroll and confirm you get No runbook found., which is the fallback you chose instead of an error.
In the Prompts tab, choose incident_summary, enter billing, and get the prompt. The Inspector shows the messages the server would hand to a host. Check that the text reads as an instruction you would want a model to follow.
Reading the message history
Every action produces JSON-RPC messages. The history pane shows each request and response. For a successful tool call, the exchange looks like this in outline:
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_service_owner",
"arguments": { "service": "billing" }
}
}The response carries the same id, which is how a client matches replies to requests. For a raised exception, the result contains "isError": true and the message text in content. Seeing the raw shape helps you understand what a host will pass to the model.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Connection fails or closes immediately | Python import error, wrong interpreter, or wrong path | Run `python server.py` directly and read the traceback |
| Connection succeeds, then parse errors appear | Something printed to stdout, such as a `print()` call | Remove it, or send logs to stderr |
| Tools tab is empty | Tools registered after `mcp.run()`, or in a module never imported | Register all tools before the `if __name__` block runs the server |
| Schema shows `string` for everything | Missing type hints | Add annotations to every parameter |
| Server works in the Inspector but not in a host | Relative paths or a different Python environment | Use absolute paths and the interpreter that has the SDK installed |
| Edits have no effect | The Inspector is still running the old process | Click **Disconnect** and **Connect** again, or restart it |
Building a repeatable test routine
The Inspector is interactive, so it is best for exploring and for quick checks after each change. A short routine keeps it effective.
- Connect and confirm the server name and capabilities.
- List tools and read every description and schema as if you were the model.
- Call each tool once with valid input.
- Call each tool with at least one invalid input and one unknown value, such as a missing service.
- Read the resource template and the prompt.
- Check the terminal for stderr logs and unexpected warnings.
For checks that must run on every commit, write automated tests that call your plain Python functions or use the SDK's client in a test. Use the Inspector for the exploratory work that comes before, and when a host behaves strangely.
Exercises
Exercise
You start the Inspector and the connection succeeds, but the first tool call produces a JSON parse error. Your tool function contains a line that prints a debug message with print(). Why does this fail, and how do you fix it?
Show answer
With the stdio transport, stdout carries the JSON-RPC messages between client and server. The print() call writes non-protocol text into that stream, so the client cannot parse it. Remove the call or use a logger configured with stream=sys.stderr.
Exercise
In the Inspector you call list_deploys with limit set to 50. Does your function run? What does that tell you about where to put input validation for simple ranges?
Show answer
The function does not run. The Field(ge=1, le=20) constraint becomes part of the JSON Schema, and the request is rejected during validation before your code executes. Simple range and enum checks can live in the type annotations. Put checks that need business logic, such as whether a service exists, inside the function.
Exercise
You call get_service_owner with an unknown service. The Inspector shows an error result, but the server keeps running and later calls still work. Which part of your code and the SDK produces this behavior?
Show answer
Your function raises ValueError with a clear message. The SDK catches the exception and returns a tool result marked as an error, with the message as content, instead of letting the exception end the process. The model can read the message and retry with a valid service.