# How to test an MCP server: tools, schemas and error cases

> MCP Server Testing: Tools, Schemas and Error Cases With Code. Canonical page: <https://zapple.tech/blog/types-of-automation-testing/how-to-test-mcp-server/>

To test an MCP server, connect a real MCP client to it inside a test process, with no model. List the tools and compare their schemas with a saved contract. Call each tool with valid, invalid and out-of-range input, and assert on the result, on isError and on protocol errors. Then gate CI on the MCP Inspector CLI's exit codes.

This post covers MCP server testing for a server you built: the tools an AI client calls through the Model Context
Protocol (MCP). It is not about MCP servers that help you test other software. It is also not about the agent that
calls the tools. For that layer, see [how to test AI agents with a tool-call regression
suite](/blog/types-of-automation-testing/how-to-test-ai-agents/).

You get a small TypeScript server, a four-layer suite and the log of one recorded run, with versions and a download.
One result sets up the rest. Of nine defects planted on purpose, the contract tests caught all nine. For five of them,
nothing else did.

## How do you test an MCP server?

In layers, cheapest first, with a real MCP client and no model. The example has four:

1. **Unit tests** of the plain functions behind the tools, with no MCP involved.
2. **Contract tests** through a real client in the test process: the tool list, the schemas, the results and both
   kinds of error.
3. **A stdio smoke test** that starts the server as a process, the way a local client does.
4. **An Inspector gate.** The MCP Inspector CLI sends four requests, and the build fails on a wrong exit code.

One setting matters on every layer: the **protocol era**. In the recorded run, a client with default options
negotiated the older revision, `2025-11-25`, both in-process and over stdio. The Inspector CLI did the same without
`--protocol-era`. The server also speaks `2026-07-28`, so a suite that never sets the era tests only one of the two.
The Inspector's documentation lists `legacy` as "The default" ([MCP Inspector, Protocol
eras](https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector/protocol-eras)). The example sets the era on every
path and asserts the negotiated version.

One question sits above this stack on purpose: does a model pick the right tool and fill it correctly? No test here
calls a model.

The example uses v2 of the official TypeScript SDK: the separate `@modelcontextprotocol/server` and
`@modelcontextprotocol/client` packages. If your project imports the single v1 package, `@modelcontextprotocol/sdk`,
the imports below will differ.

Tested on 2026-11-19, on macOS 27.2 (arm64). Versions: `@modelcontextprotocol/server` and `@modelcontextprotocol/client`
2.4.0, `@modelcontextprotocol/inspector` 2.16.0, Zod 4.6.7, Vitest 5.1.1, TypeScript 7.0.2 and Node.js 26.13.1. The contract
and stdio layers ran in both eras. The gate ran in the modern era, `2026-07-28`.

## What is MCP server testing?

MCP testing, in the sense used here, means checking that a server keeps the contract its clients rely on. **MCP server
testing** takes that contract from the specification's own terms ([MCP specification, revision 2026-07-28,
Tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)):

- Each tool has a `name`, a `description`, an `inputSchema` and an optional `outputSchema`.
- A result carries a `content` array and, when the tool declares an output schema, `structuredContent`.
- Errors come in two kinds: protocol errors and tool execution errors.

The specification is strict about output. It says: "Servers MUST provide structured results that conform to this
schema." It also asks a tool with structured content to return the same JSON in a text block, for older clients. The example
asserts both.

The term has a second sense. An MCP server such as Playwright MCP lets an AI tool drive a browser, which helps with
testing other software. That is a testing aid, not the subject here. This post uses MCP server testing for the server
side only.

## What should MCP server tests check?

Five things, each of which a client or a model depends on. The last column is the assertion the example makes.

| What to check | Why a client or model depends on it | The example's assertion |
|:--|:--|:--|
| The tool list | Clients cache it. The specification says servers "SHOULD return tools in a deterministic order" | Names and order are equal on two `listTools` calls |
| Input and output schemas | They tell the model which arguments are valid and what comes back | Every tool equals a committed snapshot, `test/tool-contract.json` |
| Results | Newer clients read `structuredContent`; older ones read the text | `structuredContent` equals the expected object, and the text block parses to the same JSON |
| Tool execution errors | The model reads the message and retries | `isError: true`, and the message names the field or the reason |
| Protocol errors | A wrong tool name must fail loudly | The call rejects with `ProtocolError`, code -32602 |

*What MCP server tests check, and how the example asserts each.*

The **schema snapshot** compares every published input and output schema with a JSON file in the repository. A
loosened range or a dropped required field then fails the build. In the run, it was the first test to fail for two
planted defects: a required field made optional, and a dropped range.

A contract test of an MCP server is close kin to a contract test of an HTTP API. The habits from [API test
automation](/blog/types-of-automation-testing/what-is-api-test-automation/) carry over: fixed inputs, exact
expectations, and a saved contract to compare with.

## How do you test an MCP server locally, without a model?

Connect a client to the server inside the test process. The SDK's testing guide describes the pattern. Pass
`handler.fetch` as the client transport's `fetch` option, and "the transport never dials" the URL ([MCP TypeScript SDK
v2, Testing](https://ts.sdk.modelcontextprotocol.io/v2/testing.html)). No port, no socket and no model are involved. The
SDK's own `Client` is the MCP test client; you need no other tool.

The whole example is a [download (ZIP, 62 KB)](/downloads/mcp-server-testing-example.zip). Every file named below is in
it. It needs Node.js 26.12.1 or newer, which runs the `.ts` files directly.

### The server

`test-run-notes` reads a fixed fixture of six CI test runs and offers three tools: `list_test_runs`,
`find_flaky_tests` and `quarantine_test`. This is one tool in full (`src/server.ts`, lines 63 to 94):

```ts
function registerFindFlakyTests(server: McpServer, deps: ServerDeps) {
  server.registerTool(
    'find_flaky_tests',
    {
      description: 'Find tests that both passed and failed, with at least min_runs executions and a fail rate of at least threshold.',
      inputSchema: z.object({
        min_runs: z.int().min(1).max(50).describe('Minimum executed runs (skipped runs do not count)'),
        threshold: z.number().min(0).max(1).describe('Minimum fail rate, 0 to 1'),
        suite: z.enum(['api', 'ui', 'unit']).optional(),
      }),
      outputSchema: z.object({
        tests: z.array(
          z.object({
            test_id: z.string(),
            suite: z.enum(['api', 'ui', 'unit']),
            runs: z.int(),
            failures: z.int(),
            fail_rate: z.number(),
            quarantined: z.boolean(),
          }),
        ),
        count: z.int(),
      }),
    },
    async ({ min_runs, threshold, suite }) => {
      const tests = findFlakyTests(readRuns(deps), { minRuns: min_runs, threshold, suite }, deps.store.has);
      const result = { tests, count: tests.length };
      // The specification asks for the same JSON in a text block, for clients that only read content.
      return { content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result };
    },
  );
}
```

The logic lives in plain functions in `src/runs.ts`, so the unit layer tests it without MCP. State that must outlive a
request, here the quarantine list, is created outside the server factory and passed in.

### The test setup

Each contract test gets a fresh handler and client (`test/contract.test.ts`, lines 33 to 52):

```ts
  async function connect(deps: Partial<ServerDeps> = {}) {
    const store = deps.store ?? createQuarantineStore();
    const handler = createMcpHandler(() => createServer({ ...deps, store }));
    const client = new Client({ name: 'contract-tests', version: '1.0.0' }, { versionNegotiation: { mode } });
    await client.connect(
      new StreamableHTTPClientTransport(new URL('http://test.local/mcp'), {
        fetch: (url, init) => handler.fetch(new Request(url, init)),
      }),
    );
    open.push({ client, handler });
    return client;
  }

  afterEach(async () => {
    // The client first, then the handler, as the SDK's testing guide says.
    for (const { client, handler } of open.splice(0)) {
      await client.close();
      await handler.close();
    }
  });
```

`mode` is `'auto'` for the modern era and `'legacy'` for the older one. The suite runs every contract test in both,
16 tests per era. Teardown closes the client first, then the handler, as the guide says.

### A happy-path test

One call, one exact object, and the same JSON in the text block (lines 83 to 96):

```ts
  it('find_flaky_tests returns structuredContent that matches its outputSchema', async () => {
    const client = await connect();
    const result = await client.callTool({ name: 'find_flaky_tests', arguments: { min_runs: 3, threshold: 0.2 } });
    expect(result.isError).toBeFalsy();
    expect(result.structuredContent).toEqual({
      tests: [
        { test_id: 'ui.checkout_shows_total', suite: 'ui', runs: 6, failures: 3, fail_rate: 0.5, quarantined: false },
        { test_id: 'api.refund_rejects_negative', suite: 'api', runs: 6, failures: 2, fail_rate: 0.333, quarantined: false },
        { test_id: 'ui.search_filters_by_date', suite: 'ui', runs: 4, failures: 1, fail_rate: 0.25, quarantined: false },
      ],
      count: 3,
    });
    expect(JSON.parse(textOf(result))).toEqual(result.structuredContent);
  });
```

### The server as a process

One smoke test per era spawns the real server with `StdioClientTransport`, the way a local client starts it. The
guide puts it plainly: "Stdio has no in-process shortcut". The test lists the tools, calls `find_flaky_tests`, closes
the client and checks that the process has exited. Both stdio tests passed in the run.

## How do you test MCP tool errors?

Assert on the result for a tool error and on a rejection for a protocol error. In the run, only the unknown tool
rejected. Every other failure resolved as a result with `isError: true`. A suite that waits for a thrown error on bad
input will never see one.

| Case | Came back as | Message in the run |
|:--|:--|:--|
| Wrong type (`min_runs: 'five'`) | result, `isError: true` | `Input validation error: Invalid arguments for tool find_flaky_tests: min_runs: Invalid input: expected number, received string` |
| Out of range (`threshold: 7`) | result, `isError: true` | `Input validation error: Invalid arguments for tool find_flaky_tests: threshold: Too big: expected number to be <=1` |
| Missing argument (`reason`) | result, `isError: true` | `Input validation error: Invalid arguments for tool quarantine_test: reason: Invalid input: expected string, received undefined` |
| Extra argument, `z.strictObject` | result, `isError: true` | `Input validation error: Invalid arguments for tool list_test_runs: Unrecognized key: "verbose"` |
| Extra argument, `z.object` | result, success; the key was dropped | the normal result, `count` 2 |
| Unknown `test_id` (business rule) | result, `isError: true` | `Unknown test_id "api.not_a_test": no recorded run contains it. Call find_flaky_tests to see known ids.` |
| Already quarantined | result, `isError: true` | `Test ui.checkout_shows_total is already quarantined; nothing changed.` |
| Fixture unreadable (the handler throws) | result, `isError: true` | `Test run data is unavailable` |
| Unknown tool (`find_flaky`) | rejected: `ProtocolError`, code -32602 | `Tool find_flaky not found` |

*Contract layer, run 1 of 2026-11-19. Both protocol eras returned the same messages.*

The two extra-argument rows are the surprise. A plain `z.object` input schema accepted an unknown argument and dropped
it without a word. Only `z.strictObject` reported it, and its published JSON Schema then carries
`additionalProperties: false`. Decide which you want, and test for it.

The tool-error tests share one shape (`test/contract.test.ts`, lines 114 to 130):

```ts
  // Tool execution errors: the call resolves, with isError: true and a message a model can act on.
  // Assert on the meaning (the field or the reason is named), not on the whole string.
  it.each([
    { case: 'wrong type', tool: 'find_flaky_tests', args: { min_runs: 'five', threshold: 0.3 }, mentions: 'min_runs' },
    { case: 'out of range', tool: 'find_flaky_tests', args: { min_runs: 5, threshold: 7 }, mentions: 'threshold' },
    { case: 'missing argument', tool: 'quarantine_test', args: { test_id: 'ui.checkout_shows_total' }, mentions: 'reason' },
    { case: 'pattern mismatch', tool: 'quarantine_test', args: { test_id: 'Checkout', reason: 'fails on slow runners' }, mentions: 'test_id' },
    { case: 'extra argument, strict schema', tool: 'list_test_runs', args: { verbose: true }, mentions: 'verbose' },
    { case: 'unknown test id (business rule)', tool: 'quarantine_test', args: { test_id: 'api.not_a_test', reason: 'fails on slow runners' }, mentions: 'Unknown test_id' },
  ])('$case: resolves with isError and names $mentions', async ({ case: name, tool, args, mentions }) => {
    const client = await connect();
    const result = await client.callTool({ name: tool, arguments: args });
    record({ era, case: name, tool, isError: result.isError, message: textOf(result) });
    expect(result.isError).toBe(true);
    expect(textOf(result)).toContain(mentions);
    expect(result.structuredContent).toBeUndefined();
  });
```

The protocol error is a rejection, with its code (lines 140 to 148):

```ts
  // Protocol error: the call rejects. An unknown tool is -32602 (invalid params), as in the specification.
  it('unknown tool: rejects with a protocol error, code -32602', async () => {
    const client = await connect();
    const call = client.callTool({ name: 'find_flaky', arguments: {} });
    await expect(call).rejects.toBeInstanceOf(ProtocolError);
    await expect(call).rejects.toMatchObject({ code: -32602 });
    const err = await call.catch((e: ProtocolError) => e);
    record({ era, case: 'unknown tool', rejected: true, code: (err as ProtocolError).code, message: (err as Error).message });
  });
```

The message is part of the interface. The specification says: "Clients SHOULD provide tool execution errors to
language models to enable self-correction." So the tests assert on meaning, such as the field name, and not on the
whole string. The fixture test goes one step further: it checks that neither `ENOENT` nor the file path reaches the
client.

## How do you test an MCP server with MCP Inspector?

Use the web client to explore and the CLI to gate. Each CLI run "connects to a server, invokes the single request you
name with `--method`, prints the result, and exits" ([MCP Inspector, CLI
client](https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector/cli)). The example's gate sends four requests
to the stdio server: `initialize`, `tools/list --strict`, one good call and one bad call.

Step 1, from `run-output.log`:

```text
$ mcp-inspector --cli node src/stdio.ts --protocol-era modern --method initialize --format json
stdout: {"result":{"serverInfo":{"name":"test-run-notes","version":"1.0.0"},"protocolVersion":"2026-07-28","capabilities":{"tools":{"listChanged":true}}}}
stderr: 
exit: 0 (expected 0)
```

Step 4, the bad call:

```text
$ mcp-inspector --cli node src/stdio.ts --protocol-era modern --method tools/call --tool-name find_flaky_tests --tool-arg min_runs=5 --tool-arg threshold=7 --format json
stdout: {"result":{"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"test-run-notes","version":"1.0.0"}},"content":[{"type":"text","text":"Input validation error: Invalid arguments for tool find_flaky_tests: threshold: Too big: expected number to be <=1"}],"isError":true}}
stderr: {"error":{"code":"tool_is_error","message":"Tool 'find_flaky_tests' returned isError:true."}}
exit: 5 (expected 5)
```

Three of the exit codes the docs define, and which of them the run met:

| Exit | Meaning in the Inspector docs | In the run |
|:--|:--|:--|
| 0 | Success. | Steps 1 to 3 |
| 5 | Tool error: `tools/call` returned `isError: true`, or the tool wasn't found. | Step 4, `threshold=7` |
| 6 | `--strict` found an error-severity tool-schema portability problem. | Never met |

*Inspector CLI 2.16.0, gate run 1.*

**Exit 6 never occurred.** `--strict` found no error-severity problem in this server, and none of the nine planted
defects produced one. So the run shows 0 and 5, and 6 is described only from the docs.

Exit 5 covers two failures: a tool error and a missing tool. The gate therefore also reads the error code in the JSON
line on stderr, here `tool_is_error`, before it passes the step.

The CLI asserts nothing about values. The gate's checks, such as the three names in order or `count` 2, are small
expressions in the script, not Inspector features.

## How do you run MCP server tests in CI?

Run the suite, then the gate, on every pull request. These are the example's scripts (`package.json`, lines 10 to 18):

```json
  "scripts": {
    "start": "node src/stdio.ts",
    "typecheck": "tsc --noEmit -p tsconfig.json",
    "test": "vitest run",
    "gate": "sh scripts/inspector-gate.sh",
    "defects": "node scripts/seeded-defects.ts",
    "eras": "node scripts/era-defaults.ts",
    "hygiene": "HYGIENE=1 vitest run",
    "all": "sh scripts/run-all.sh"
```

A pipeline needs four commands: `npm ci`, `npm run typecheck`, `npm test` and `npm run gate`. `npm test` runs layers 1
to 3, 41 tests. The gate's last step shows how one check rides on an exit code and on stderr
(`scripts/inspector-gate.sh`, lines 53 to 56):

```sh
# Exit 5 means isError OR an unknown tool, so the gate also checks the error code on stderr.
step "tools/call find_flaky_tests (threshold=7): a tool error, not a missing tool" 5 \
  'err.error.code === "tool_is_error" && /threshold/.test(out.result.content[0].text)' \
  -- --method tools/call --tool-name find_flaky_tests --tool-arg min_runs=5 --tool-arg threshold=7 --format json
```

Wall clock in the recorded run, three runs per layer, with process start-up included:

| Layer | Tests | Run 1 | Run 2 | Run 3 |
|:--|--:|--:|--:|--:|
| Unit | 7 | 421 ms | 402 ms | 377 ms |
| Contract, both eras | 32 | 624 ms | 713 ms | 611 ms |
| Stdio, both eras | 2 | 1,079 ms | 1,363 ms | 860 ms |
| Inspector gate | 4 steps | 2,842 ms | 2,042 ms | 1,840 ms |

*Measured on a laptop on 2026-11-19, with other work running.*

Treat these as an order of magnitude, not a benchmark. The seeded-defect run builds nine broken copies and runs every
layer on each; it took 36.4 seconds, once. That fits a nightly job better than every commit.

The example was not run in a hosted CI service, so no vendor file is shown here. For wiring the two steps into an
existing pipeline, see [CI/CD and tools integration](/services/tools-integration/).

## Which defects did the tests catch?

All nine, as planned before the runs. Each defect is one change to a copy of the server, and each copy ran through all
four layers. The expected catches were committed in `PLAN.md` before the first defect run. A control copy with no
change passed every layer first.

One full run came before the recorded one. After it, every successful result's text block became the serialized JSON,
and the contract tests gained an assertion on it. D4's replacement was re-pointed at the new line, the hygiene test
moved to its own script, and an era probe was added. The defect list and the expected catches did not change.

| # | Planted defect | Unit | Contract | Stdio | Gate |
|:--|:--|:-:|:-:|:-:|:-:|
| D1 | A tool is renamed | missed | 18 of 32 | 2 of 2 | 3 of 4 |
| D2 | A required input becomes optional | missed | 4 of 32 | missed | missed |
| D3 | A range is dropped (`threshold` accepts 7) | missed | 4 of 32 | missed | 1 of 4 |
| D4 | An output field changes type (`count` as a string) | missed | 8 of 32 | 2 of 2 | 1 of 4 |
| D5 | A failure is returned as a success with an apology | missed | 2 of 32 | missed | missed |
| D6 | Tool order changes on every second factory call | missed | 3 of 32 | missed | missed |
| D7 | A thrown error leaks a file path | missed | 2 of 32 | missed | missed |
| D8 | State leaks between handlers | missed | 4 of 32 | missed | missed |
| D9 | The fail rate counts skipped runs | 1 of 7 | 2 of 32 | missed | missed |

*Failing tests or gate steps per layer. Expected matched actual on all nine rows. Totals: unit 1 of 9, contract 9 of 9,
stdio 2 of 9, gate 3 of 9.*

What the table shows:

- **Five defects reached only the contract layer:** D2, D5, D6, D7 and D8. Stdio and the gate saw a working server
  each time.
- **One test caught D5, in both eras.** Only the business-rule test failed: `isError` was undefined.
- **D6 and D8 failed first in tests written for them.** D6 surfaced in the test that calls `listTools` twice, and D8
  in the test that connects two handlers.
- **D7 shows why messages are tested.** The client got `ENOENT: no such file or directory, op…`. The test expected
  `Test run data is unavailable`.
- **The gate caught D3 on its exit code.** `threshold=7` exited 0, where the gate expected 5.

The likely reason stdio and the gate missed D6 is an inference, not a measurement. Over stdio, the SDK keeps one server
instance per connection, so the order never changes inside it.

What this proves is narrow. The same people chose the nine defects and wrote the suite, so the run shows that each
check can fail. It does not show that the suite catches defects nobody thought of. D9 was added to the plan before the
run, so the unit layer had a defect of its own.

A tested server is half of the picture. Whether an agent uses its tools correctly is the other half. Zapple.Tech offers
AI agent testing and LLM evaluation. The first step is fixed in scope and takes about one week: an evaluation baseline
with a written report. [Start with a one-week agent evaluation baseline](/services/ai-agent-testing/).

## What does MCP server testing not cover?

MCP server testing checks the contract, not how anything uses it. Four things stay outside this suite:

1. **Tool choice by a model.** Whether a model picks the right tool and arguments depends on the descriptions and on
   the model. That belongs to agent tests on recorded runs, as in the post on how to test AI agents, and to [AI agent
   testing services](/services/ai-agent-testing/).
2. **Security.** Authorization, token handling and tool descriptions that change after discovery need their own tests.
   The example has no authorization and checks only that one error does not leak a path.
3. **Load and remote transport.** Everything here ran in-process or over local stdio. Behavior under load, or behind
   proxies on a remote HTTP server, was not tested.
4. **Host applications.** Each host can treat tools, errors and eras in its own way. The suite tests one client, the
   SDK's own.

For testing the LLM features built around the server, see [AI testing services for LLM
features](/services/ai-testing/).

When is this suite the wrong first step? A server with one read-only tool and one user needs the Inspector and nothing
more. Add the contract tests when a second client, a write tool or a release schedule appears.

Copy the contract tests first: one client, one handler, a schema snapshot and both kinds of error, in both protocol
eras. That is MCP server testing that runs on every commit, with no model and no key. To have Zapple.Tech test the
agent that uses your server, [tell us about it in the form below](#start).

## FAQ

### Is there a free MCP server I can use for testing?

Yes. The example server in this post is a free download and runs locally, with no account and no API key once its packages are installed. It has three tools over a fixture of six CI test runs, and it ships with the full test suite and the log of its run. It needs Node.js 26.12.1 or newer and was tested on 26.13.1.

### Do you need an LLM to test an MCP server?

No. The server's contract, meaning its tool list, schemas, results and errors, is tested with an MCP client and ordinary assertions, and it gives the same result on every run. The example runs 41 tests and an Inspector gate with no model and no key. A model is needed for a different question: whether an agent picks and fills the tools correctly.

### What is the difference between a tool error and a protocol error in MCP?

A tool execution error is a normal result with isError set to true. It covers bad input and failed operations, and its text is written so a model can correct the call. A protocol error is a JSON-RPC error, such as an unknown tool, and the client call rejects. In the example run, the unknown tool came back with code -32602. Tests assert the two differently.

### Is MCP Inspector enough to test an MCP server?

For exploring and debugging, yes. For regression, not on its own. The web client is manual, and each CLI run sends one request and returns an exit code. In the example, the Inspector gate caught three of nine planted defects, while the contract tests caught all nine. Use the CLI as a gate next to a suite that asserts on values and schemas.

### Which tools do you need to test an MCP server?

Four kinds: a test runner, the SDK's own client, a schema library and the MCP Inspector CLI. The example uses Vitest 5.1.1, the official TypeScript SDK v2 (the server and client packages, 2.4.0), Zod 4.6.7 and Inspector 2.16.0. No hosted service and no model are needed to test the server's contract.

## Sources

- [MCP specification, revision 2026-07-28, Tools: tool fields, deterministic order, output schema rule, structured content with a text block, protocol errors and tool execution errors, the -32602 example, self-correction](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)
- [MCP TypeScript SDK v2 documentation, Testing: handler.fetch as the transport's fetch, the transport never dials the URL, versionNegotiation mode auto, teardown order, createLinkedPair limits, stdio by spawning the process](https://ts.sdk.modelcontextprotocol.io/v2/testing.html)
- [MCP Inspector documentation, CLI client: one request per run, --strict, --format json, exit codes 0, 5 and 6](https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector/cli)
- [MCP Inspector documentation, Protocol eras: legacy, auto and modern; legacy is the default; the --protocol-era flag](https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector/protocol-eras)
