Test the Server with Your Own Client
An MCP server is only useful if a client can find its tools and call them correctly, and you do not need an AI assistant to find out whether it can. A short test can play the part of the client: it connects to the server, asks which tools exist, calls one with arguments you choose, and checks every part of the answer. Written in Python, such tests run in a fraction of a second, with no model involved.
Discover first, then call
A client starts out knowing nothing about a server. It does not know the names of the tools, what they do, or which arguments they take. So every conversation about tools has the same two steps.
- Discover. The client sends a
tools/listrequest. The server answers with one entry per tool: itsname, adescriptionin plain words, and aninputSchema, a small JSON Schema document that says which arguments exist, what type each one has and which are required. - Call. The client sends a
tools/callrequest with the name of one tool and a dictionary of arguments. The server runs the tool and answers with its result.
Each step is a pair of messages: a request from the client and a response from the server. MCP writes these messages in JSON-RPC 2.0, a plain format for calling a method on another program with JSON. A request names a method, carries its params and has an id. The response carries the same id, so the client knows which question it answers. Inside it is either a result or an error.
- Client
- Server
- Client to Server: tools/list
- Server to Client: names, descriptions, input schemas
- Client to Server: tools/call: name + arguments
- Server to Client: result
Here is that exchange for a server with one tool, word_count, which counts the words in a text. A few bookkeeping fields that every message also carries are left out so the shape stays easy to read.
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
{"jsonrpc": "2.0", "id": 1, "result": {"tools": [
{
"name": "word_count",
"description": "Count the words in a text.",
"inputSchema": {
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"]
}
}
]}}{"jsonrpc": "2.0", "id": 2, "method": "tools/call",
"params": {"name": "word_count", "arguments": {"text": "one two three"}}}
{"jsonrpc": "2.0", "id": 2, "result": {
"content": [{"type": "text", "text": "3"}],
"structuredContent": {"result": 3},
"isError": false
}}The listing is everything a caller has to go on. The name and the description tell it which tool fits a task, and the input schema tells it how to build the arguments. That is why the discover step comes first, and why a test that checks the listing checks something real: if the schema says text is required, every caller will be told to send it.
True or false?
A client must already know the names of the tools before it can talk to a server.
False. It learns them from the server itself: a tools/list request returns every tool with its name, description and input schema.
A tools/call request names the tool to run and carries its arguments as a JSON object.
True. Its params hold name and arguments, and the response with the same id carries the result.
What a tool call returns
The result of a call is more than a single string. It has up to three parts, each for a different reader.
| Part of the result | What it holds | Who reads it |
|---|---|---|
| content | A list of content blocks, most often text blocks such as {"type": "text", "text": "3"} | The model, as text added to the conversation |
| structuredContent | Optional data as JSON, shaped by the output schema of the tool | Programs that want values, not sentences |
| isError | true when the call failed, false otherwise | Both: it says whether to trust the rest |
Content blocks are the main answer. Text is the common kind; a block can also hold an image or audio, or point to a resource. A host places these blocks in front of the model, which reads them the way it reads any other text.
Structured content is the same answer as data. The Python SDK builds it from the return type of the function, the type its type hint declares. A plain number or string is wrapped in a dictionary under the key result, so a tool declared as returning int gives {"result": 3}. A program can read 3 from there instead of parsing it out of a sentence.
Not every client reads structured content. So when a tool returns it, the tool should also return the same data serialized as JSON in a text block, and clients that only read text still get the answer.
The error flag matters more than it looks. With this SDK, a failed call does not travel back as an exception. A tool that raises, arguments that do not fit the input schema, and even a tool name the server does not know all come back as an ordinary result with isError set to true and a message in the content. For an unknown name, the text reads Unknown tool: does_not_exist. The model can read that message and try again with a better call.
True or false?
A tool written to return an int still produces structured content when called through the Python SDK.
True. The return type becomes the output schema, and a plain value is wrapped as {"result": ...}, next to the text block "3".
With the Python SDK, calling a tool name the server does not have makes the client raise an exception.
False. The call returns normally: the result has isError set to true and the text Unknown tool followed by the name.
Testing without a model
When an AI assistant uses a server, a lot happens around the call. The model reads the tool listing, decides which tool to use and invents the arguments. The model is not predictable: ask it the same thing twice and it may phrase the call differently, or choose another tool.
The server, though, is ordinary code. Given the text "one two three", word_count returns 3 every time, whoever asked. The model is only the caller, and a caller can be replaced by anything that sends the same requests. A test does exactly that: it sends fixed arguments and compares the answer with the value it expects.
- The model chooses the call
- Client in the host
- Server runs the tool
- The model to Client in the host
- Client in the host to Server
- Test function fixed arguments
- Client
- Server same tool code
- Test function to Client
- Client to Server
This split gives each question its own place. Whether the tool computes the right answer, publishes the right schema and reports errors clearly is a property of the server, and a test settles it in milliseconds, with no account, no cost and no randomness. Whether a model picks the tool well is a different question, about names and descriptions, and no test of the code answers it. A tool that keeps data, for example in a file or a database, is given a fresh temporary copy for each test, so every run starts from the same state and gives the same answer.
True or false?
To check that a tool returns the right answer, a test has to send a prompt to a model and see what it does.
False. The tool is deterministic code. The test calls it through a client with fixed arguments and compares the result; no model is needed.
Tests that go through a client can check the input schema the server publishes, not only the answers of its tools.
True. The client can list the tools and assert on each schema, and arguments that break the schema come back as an error result.
Connecting in memory
A real host reaches a server through a transport, the channel the messages travel on. A local server is usually started as a separate program that reads requests on its standard input and writes responses on its standard output (the stdio transport); a remote one is reached over HTTP. Both work, but for a test they bring extra moving parts: a process to start and stop, a port to open, output to keep apart from the messages.
The Python SDK offers a shortcut for tests. Its client class, Client, accepts the server object itself, the MCPServer instance your server module creates. (In the 1.x line of the SDK and in older tutorials that class is called FastMCP, which is also the name of a separate framework.)
from mcp import Client
from server import mcp # the MCPServer object of the server module
async with Client(mcp) as client:
result = await client.call_tool("word_count", {"text": "one two three"})Handed the object, the client connects inside the same Python process: no subprocess, no port, nothing on a network. The request does not take a shortcut to your function, though. It goes through the same request handling the server uses for stdio and HTTP: the arguments are validated against the input schema, the tool runs, errors are turned into error results, and the result is built and serialized the same way. What is left out is only the outer layer: the JSON-RPC text on a wire and the transport that carries it.
| How the client connects | Client receives | Separate process | JSON-RPC text on a wire |
|---|---|---|---|
| stdio | the command that starts the server | yes | yes, one message per line |
| HTTP | a URL | yes, often on another machine | yes, in HTTP requests |
| In memory | the server object | no | no, the request is handled directly |
Because the server code and the handling of each request are the same, a test that passes in memory tells you that the tools, their schemas and their results are right. What it does not test is the launch itself, such as the command a host uses to start the server.
True or false?
An in-memory client skips the server's input validation and calls the tool function directly.
False. Each request still runs through the server's own request handling: schema validation, the tool, error conversion and result serialization.
An in-memory connection needs no free port and starts no second program.
True. Client(mcp) connects to the server object inside the test's own process.
Writing the tests
Tests in Python are most often written with pytest. It needs only three ideas here.
- A test function is a function whose name starts with
test_, in a file whose name starts withtest_. The commandpytestfinds and runs them all. - An assert statement states something that must be true, such as
assert total == 3. If it is false, the test fails and pytest shows both values. - A fixture is a function marked
@pytest.fixturethat prepares something a test needs. A test asks for it by naming it as a parameter, and pytest passes in what the fixture provides. Code after ayieldin the fixture runs when the test is over, to clean up.
The client side of the SDK is asynchronous. A request may have to wait for an answer, and asynchronous code lets the program wait without freezing everything else while it does. Reading it takes three keywords:
async defdefines a function that can wait.await, inside such a function, waits for one result, such as the answer to a request.async withopens something whose opening and closing involve waiting, here the connection, and closes it when the block ends.
The tools on the server stay ordinary functions; only the client code and the tests use these keywords.
pytest does not run an async def test on its own. The SDK depends on a library called anyio, which includes a pytest plugin. Marking a test with @pytest.mark.anyio lets it run. A fixture named anyio_backend that returns "asyncio" picks asyncio, the standard event loop that comes with Python and runs asynchronous code. Nothing besides pytest has to be installed for this.
import pytest
from mcp import Client
from server import mcp
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.fixture
async def client():
async with Client(mcp, raise_exceptions=True) as c:
yield c
@pytest.mark.anyio
async def test_lists_word_count(client):
listing = await client.list_tools()
tool = listing.tools[0]
assert tool.name == "word_count"
assert tool.description == "Count the words in a text."
assert tool.input_schema["required"] == ["text"]
@pytest.mark.anyio
async def test_counts_words(client):
result = await client.call_tool("word_count", {"text": "one two three"})
assert result.is_error is False
assert result.content[0].text == "3"
assert result.structured_content == {"result": 3}
@pytest.mark.anyio
async def test_unknown_tool_is_an_error_result(client):
result = await client.call_tool("does_not_exist", {})
assert result.is_error is True
assert "Unknown tool" in result.content[0].textThe client fixture opens a new in-memory connection for each test and closes it afterwards, so no test can leave anything behind for the next one. Passing raise_exceptions=True is recommended for tests: a failure inside the SDK's own machinery, outside the body of a tool, then shows its real message instead of a generic one. It does not change how a failing tool is reported; that is still an error result.
The first test checks the discovery step: list_tools() returns the listing, and each tool in .tools has a name, a description and an input_schema, a dictionary you can index like any other. The second calls the tool and reads every part of the result: is_error, the text of the first content block with .text, and structured_content. In Python these names are written in snake_case; the camelCase names, such as isError and structuredContent, are only how they appear in the JSON messages.
The third test shows why is_error is the first thing to check. A failed call returns normally, so a try and except around call_tool catches nothing; the failure is in the result, and the test asserts on it like any other value.
True or false?
In a Python test, the error flag of a result is read as result.isError.
False. Python attributes are snake_case: result.is_error. isError is the name in the JSON message.
With raise_exceptions=True, a tool that raises makes call_tool raise in the test.
False. A failure inside a tool still comes back as a result with is_error set to true. The flag only reveals failures outside the tool body.
Each test that takes the client fixture gets its own connection, opened before the test and closed after it.
True. A fixture runs once per test by default, and the code after yield, here the end of async with, closes the connection.