Search IOCombats

Search challenges, guides, questions and articles

You have built an MCP server in TypeScript. How would you test it before other teams start using it?

Intermediate10 min interview
Skills tested:
Splitting MCP server tests into logic, protocol, process and eval layersDriving a server through an in-process MCP client in VitestAsserting on tool listings, structuredContent and isError resultsUsing the MCP Inspector manually and from the CLIKnowing what stdio servers break when they write to stdout

Advertisement

🧩 Scenario

You built an MCP server for your company's pricing service with a tool called apply-discount. Three teams plan to connect it to their AI assistants next sprint. Your lead asks how you will test it so nobody finds bugs in production.

Architecture Walkthrough

Think of testing an MCP server like testing an Express API. You unit test the services, you run integration tests through the real router, and you do a smoke test against the running server. MCP adds one more layer at the end: checking that models actually use your tools well.

Layer 1: business logic

Keep each handler thin and move the real work into plain functions, like applyDiscount(price, percent). Test those with normal Vitest or Jest tests. No MCP involved.

Layer 2: protocol tests with a real client

This is the most valuable layer. Connect a real MCP Client to your server inside the test process and call it the way a host would:

  • listTools() returns the names, descriptions and schemas you expect. A renamed tool is a breaking change for every host using it.
  • callTool() with valid input returns the right content and structuredContent.
  • Invalid input is rejected by the schema.
  • A failing handler returns a result with isError: true, which is how MCP reports tool execution errors. Protocol problems, such as an unknown tool, come back as JSON-RPC errors instead.

The v2 TypeScript SDK docs show an in-process path: wrap your server factory with createMcpHandler and give the client transport a custom fetch that calls the handler directly, so no port is opened. The older InMemoryTransport.createLinkedPair() still exists, but the docs say it only connects 2025-era protocol instances.

Layer 3: real process smoke test

Start the built server the way hosts will: spawn it with StdioClientTransport or hit the deployed HTTP endpoint. This catches packaging problems, missing env vars, and the classic stdio bug: writing logs to stdout. The spec says a stdio server must not write anything to stdout that is not a valid MCP message, so logs belong on stderr.

Layer 4: manual checks and evals

The MCP Inspector lets you browse and call tools by hand, and its CLI mode can run methods from a script. Finally, whether a model picks apply-discount for "give this customer 10 percent off" depends on your names and descriptions. That is an eval: run a set of prompts through a real model and score tool choice, separately from your fast test suite.


Key Code Explained (TypeScript)

// pricing-server.test.ts (Vitest, MCP TypeScript SDK v2)
import { afterEach, beforeEach, expect, it } from 'vitest';
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import { createMcpHandler } from '@modelcontextprotocol/server';
import { createServer } from './pricing-server'; // returns a configured McpServer

let client: Client;
let handler: ReturnType<typeof createMcpHandler>;

beforeEach(async () => {
  handler = createMcpHandler(createServer);
  // Custom fetch routes requests straight into the handler: no port, no network
  const transport = new StreamableHTTPClientTransport(new URL('http://test.local/mcp'), {
    fetch: (url, init) => handler.fetch(new Request(url, init)),
  });
  client = new Client({ name: 'test-harness', version: '1.0.0' });
  await client.connect(transport);
});

afterEach(async () => {
  // Close the client first, then the handler
  await client.close();
  await handler.close();
});

it('lists apply-discount with the expected schema', async () => {
  const { tools } = await client.listTools();
  const tool = tools.find((t) => t.name === 'apply-discount');
  expect(tool?.inputSchema.properties).toHaveProperty('price');
  expect(tool?.inputSchema.properties).toHaveProperty('percent');
});

it('applies the discount', async () => {
  const result = await client.callTool({
    name: 'apply-discount',
    arguments: { price: 80, percent: 25 },
  });
  expect(result.isError).toBeFalsy();
  expect(result.structuredContent).toEqual({ finalPrice: 60 });
});

it('reports bad business input as a tool error, not a crash', async () => {
  const result = await client.callTool({
    name: 'apply-discount',
    arguments: { price: 80, percent: 150 },
  });
  expect(result.isError).toBe(true);
});

A quick scripted check against the built stdio server with the Inspector CLI:

npx @modelcontextprotocol/inspector --cli node dist/server.js --method tools/list

The last test assumes your handler returns isError: true for a percent above 100. If you enforce that limit in the Zod schema instead, the input is rejected before your handler runs, so assert on whatever your server actually returns for invalid input and keep that behaviour consistent across tools.


Tradeoffs

Test layerCatchesCost
Logic unit testsWrong calculations, edge casesFast, but misses protocol bugs
In-process client testsSchema, naming, result shape, error handlingFast, needs SDK test wiring
Real process smoke testPackaging, env vars, stdout logging, startup crashesSlower, needs a build step
Inspector (manual or CLI)Things you did not think to automateManual effort, or a small CI script
Model evalsPoor tool names or descriptions, wrong tool choiceCosts tokens, results vary run to run

What Interviewers Actually Check

  • Whether you test through the protocol, not only the handler functions
  • Whether you know tool failures come back as isError results
  • Whether you treat tool names and schemas as a public contract
  • Whether you separate deterministic tests from model evals
  • Whether you know the MCP Inspector and the stdout rule for stdio servers

Follow-Up Questions

  1. How would you detect a breaking change in a tool's input schema before release?
  2. How would you test a tool that calls a slow external API without hitting it in CI?
  3. What would you check in a smoke test for a Streamable HTTP server that you would not check for stdio?
  4. How would you write an eval that checks the model picks the right tool?
  5. How would you test that unauthorised callers cannot use a tool?

Common Candidate Mistakes

  • Testing only applyDiscount() and assuming the MCP wiring is fine.
  • Using expect(...).rejects for tool failures that actually resolve with isError: true.
  • Running a live model in every CI run and accepting flaky tests.
  • Leaving console.log in a stdio server because the in-process tests passed.
  • Forgetting teardown, which leaves open handles and hangs the test runner.

Interview Readiness Checklist

Before you leave this question, make sure you can answer:

  • Can you name the layers of testing for an MCP server?
  • Can you connect a test client to a server without opening a port?
  • Can you write assertions for listTools, a success result and an isError result?
  • Can you run the Inspector CLI against a built server?
  • Can you explain the difference between a protocol test and a tool choice eval?

Summary

Test an MCP server the way you would test an API, plus one extra layer for model behaviour. Unit test the logic inside each handler. Then drive the whole server through a real MCP client in-process (with the v2 SDK, createMcpHandler plus a client transport whose fetch calls the handler) and assert on listTools, structuredContent and isError results. Add a smoke test that runs the real built server, which catches stdout logging bugs in stdio servers, and use the MCP Inspector for manual exploration or CLI checks in CI. Finally, measure whether models pick your tools correctly with evals, kept separate from your fast deterministic tests.

Frequently Asked Questions

Do I need a real model to test an MCP server?

No. The server never talks to a model. A test client can call tools/list and tools/call directly, which keeps protocol tests fast and deterministic. You only need a model when you test whether tool names and descriptions lead the model to pick the right tool, which is an eval, not a unit test.

What is the MCP Inspector?

It is the official developer tool for MCP servers, published as @modelcontextprotocol/inspector. It can connect to a server, list and call tools, and run in web, terminal UI or CLI mode. The CLI mode is useful for scripted checks in CI.

Should a failing tool throw in tests?

Not usually. In MCP, a tool execution failure comes back as a normal result with isError set to true, so the model can read the message and recover. Your tests should assert on that result rather than expecting a thrown error.

Advertisement


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.

Namaste Dev
Sponsored

Cohort-style courses to go from tutorials to job-ready.

Explore Courses

Advertisement