Test your MCP server by calling it the way a client does
I recently built a small MCP server in TypeScript. It exposes a handful of real estate calculators as tools: a mortgage payment, affordability, a seller net sheet, rent versus buy, and investment returns. An AI assistant connects to it, sees the list of tools, and calls them with JSON arguments.
The math was the easy part to test. Each calculator is a plain function that takes numbers and returns numbers, so I wrote ordinary unit tests for it. Those tests went green early. They also told me almost nothing about whether the thing would work when an assistant actually connected to it.
What unit tests on the logic miss
An MCP server is a process that speaks a protocol. The client does not import your functions. It starts your program, talks to it over stdin and stdout (or over HTTP), asks what tools exist, and calls them by name. A lot can go wrong between your pure function and that conversation:
- A tool never gets registered, or gets registered under a slightly different name.
- The input or output schema is missing, so the client cannot validate anything.
- Bad input throws and crashes the process instead of coming back as a tool error.
- The built file is not executable, or is missing the
#!/usr/bin/env nodeline, sonpxfails. - Something writes a log line to stdout. Over stdio, stdout is the protocol stream, so one stray
console.logcorrupts the messages and the client disconnects.
None of those show up in a test that imports calculateMortgage and checks the result. Every one
of them shows up the first time a real client tries to use the server.
Spawn the built server and drive it with a real client
So the most valuable test in the project does exactly what a client does. It runs after the build, starts the compiled entry point as a child process, connects with the official MCP client library, and works through the server’s surface:
const transport = new StdioClientTransport({
command: 'node',
args: [path.join(root, 'dist', 'index.js')],
stderr: 'pipe',
});
const client = new Client({ name: 'server-test', version: '1.0.0' });
await client.connect(transport);
const { tools } = await client.listTools();
expect(tools.map((t) => t.name).sort()).toEqual([
'affordability',
'investment_returns',
'mortgage_payment',
'rent_vs_buy',
'seller_net_sheet',
]);
const args = { principal: 200_000, annualInterestRate: 6, termYears: 30 };
const result = await client.callTool({ name: 'mortgage_payment', arguments: args });
expect(result.isError).toBeFalsy();
expect(result.structuredContent).toMatchObject(calculateMortgage(args));
const rejected = await client.callTool({
name: 'seller_net_sheet',
arguments: { salePrice: -10, mortgagePayoff: 0, commissionPercent: 6 },
});
expect(rejected.isError).toBe(true);
A few choices in there are deliberate.
Run the built file, not the source. Pointing the test at dist/index.js means the build,
the shebang, and the entry point are all part of what gets tested. I also check that the file
starts with the shebang and that package.json points its bin at that same path. If someone
renames the output folder, this test fails before a user does.
Assert the exact tool list. Comparing the full sorted list of names catches a missing tool,
a renamed tool, and an extra tool somebody forgot to mention in the README. A check like
“contains mortgage_payment” would let the other two slide.
Compare against the pure function, not a hard-coded number. The expected value for the tool call comes from calling the same calculator directly. The unit tests already prove the math is right. This test only has to prove the server returns what the math returns, without dropping or reshaping fields on the way out. That keeps one source of truth for the numbers, so changing a formula does not mean updating expected values in two places.
Send bad input on purpose. A negative sale price should be rejected by the input schema and
come back as isError: true. If the server crashed instead, the next call in the same test would
fail too, which makes that failure easy to spot.
The same test also reads a resource and fetches a prompt, since those are part of what a client sees. One connection, one walk through everything the server offers.
Keep stdout clean
That last bullet in the list above deserves its own rule, because it is the easiest one to break by accident. Over stdio, anything your server prints to stdout is treated as a protocol message. So every log goes to stderr, and the entry point says so in a comment right where the startup message is printed:
// stdout is the MCP protocol stream. Keep logs on stderr.
console.error('server ready on stdio');
The spawn test is what enforces this. If a stray log lands on stdout, the client fails to parse
it and the test goes red. I set stderr: 'pipe' so the server’s own logs do not clutter the test
output but are still there if I need them.
Test the other transport too
The server can also run over Streamable HTTP on loopback. That path has its own wiring: a port,
a route, and host and origin checks to block DNS rebinding. So it gets its own test. The test
grabs a free port, starts the built server with --http, waits until stderr says it is
listening, connects with the HTTP client transport, and makes one real tool call. An
afterEach kills the child process so a failed test does not leave a server running in the
background.
Waiting for the “listening” line instead of sleeping for a fixed time matters. A fixed sleep is either too short on a slow CI runner or wastes time on a fast laptop. A timeout around the wait still catches a server that never starts, and an exit listener reports the server’s own logs if it dies early.
The tradeoffs
These tests are slower than unit tests. They need a build first, and they start real processes. In my setup the test script runs the build and then the whole suite, so there is no way to run the integration tests against a stale build by mistake. That costs a few seconds per run, which I think is fine.
Grabbing a free port and then starting the server on it has a small race: something else could take the port in between. I have not seen that happen, and the failure would be loud, not silent. If it ever became a problem, the next step would be letting the server pick port zero and report the port it actually got.
I also put most of the stdio checks in one test instead of many small ones. That is less granular, but starting one process and walking through everything is closer to what a client does, and the assertion messages still point at what broke.
The general rule
If your code is going to be called through a protocol, at least one test should go through that protocol. Unit tests prove your logic is right. A test that spawns the real program and talks to it like a client proves people can actually use it. For an MCP server, that means building it, starting it, listing its tools, calling one, and checking that bad input comes back as an error instead of a crash.