Metadata-Version: 2.4
Name: mcp-testbench
Version: 0.2.0
Summary: Complete MCP server testing toolkit: MCP conformance and contract testing for Model Context Protocol servers -- schema snapshots, breaking change detection, recorded tool-call replay, a 21-rule MCP lint, and a pytest plugin for MCP CI over stdio, Streamable HTTP and SSE, with zero runtime dependencies.
Maintainer: agentella
License: MIT
Project-URL: Homepage, https://pypi.org/project/mcp-testbench/
Project-URL: Documentation, https://pypi.org/project/mcp-testbench/
Keywords: MCP,Model Context Protocol,MCP server testing,MCP conformance,MCP contract testing,MCP schema snapshot,breaking change detection,tool-call replay,pytest plugin,pytest-mcp,FastMCP testing,MCP CI,MCP lint,JSON-RPC testing,AI agent tools,LLM tool testing,MCP server validation,mcp,model-context-protocol,testing,pytest,conformance
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Framework :: Pytest
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: license-file

# mcp-testbench

**The complete MCP server testing toolkit** -- MCP conformance and contract
testing for Model Context Protocol servers, from a CLI or as a pytest plugin.

## What is mcp-testbench?

mcp-testbench is a testing, validation and CI tool for MCP (Model Context
Protocol) servers. It takes an MCP schema snapshot of a server's tools,
prompts and resources, detects breaking changes against that snapshot with
breaking change classification, lints the schema, and replays recorded
tool calls -- the full MCP server testing workflow in one package, built for
MCP CI. It is the only Python MCP testing package that combines schema
snapshot + breaking-change classification + recorded tool-call replay +
offline JSON definition mode in one zero-dependency package. It ships a
21-rule MCP lint covering tools, prompts and resources, works over stdio,
Streamable HTTP and the legacy SSE transport, and needs no dependency on the
official `mcp` package, so an SDK upgrade on the server side never breaks
your tests.

Use it for FastMCP testing, testing servers built on the official MCP SDK,
and black-box JSON-RPC testing of MCP servers written in any language (a
Node or Go server works too): mcp-testbench treats the server as a subprocess
or HTTP endpoint speaking JSON-RPC. It can also run entirely from an
**offline JSON server definition**, with no live server at all -- for MCP
server validation in restricted CI, pull-request checks, and reviewing a
vendor server you cannot run. If you test AI agent tools or LLM tool
calling, this is the pytest-mcp style plugin for contract-testing the MCP
servers those agents depend on.

## Install

```
pip install mcp-testbench
```

## Quickstart: snapshot -> check in CI -> replay

```
# 1. record the contract; commit the snapshot file
mcp-testbench snapshot -o mcp-snapshot.json -- python my_server.py

# 2. CI gate: exit 1 when a change breaks existing callers
mcp-testbench check mcp-snapshot.json -- python my_server.py

# 3. lint the schema (21 rules, tools + prompts + resources)
mcp-testbench lint -- python my_server.py

# 4. replay recorded tool calls (JSONL); exit 1 if any call fails
mcp-testbench replay calls.jsonl -- python my_server.py
```

Or in pytest, with the built-in pytest plugin:

```python
def test_no_breaking_changes(mcp_schema, mcp_snapshot):
    mcp_snapshot(mcp_schema, "mcp-snapshot.json")  # writes on first run
```

## How it compares

| Capability | mcp-testbench | MCP Inspector | mcp-contract | mcptest (`pytest-mcp-server`) | pytest-mcptest |
|---|---|---|---|---|---|
| Recorded tool-call replay | **Yes** | No | No (read-only, never calls tools) | No | Roadmap only, not shipped |
| Offline JSON definition mode | **Yes** | No | No | No | No |
| Schema snapshot + breaking-change diff | Yes | No | Yes | Yes | No |
| Lint rules | **21, across tools + prompts + resources** | None | None | 15, tools-first | None |
| Transports | stdio, Streamable HTTP, legacy SSE | stdio, Streamable HTTP, SSE | stdio | stdio, Streamable HTTP | stdio, Streamable HTTP, in-process |
| pytest plugin | Yes | No (npm / Node UI) | No | Yes | Yes |
| Runtime dependencies | **Zero (stdlib only)** | Node.js | -- | Zero | Requires the `mcp` SDK |

## Install from a local checkout (development)

```
pip install -e .
```

## Why this exists (the gap)

Researched 2026-12-05 (full write-up in the companion research notes):

- The official **MCP Inspector** is an interactive debugger (npm, Node) -- no
  pytest plugin, no snapshot, no breaking-change diff, no replay.
- **FastMCP's in-memory `Client`** is excellent, but only for FastMCP servers
  you can import in-process.
- Python incumbents `mcp-contract` and `pytest-mcp-server` (`mcptest`) do
  snapshot + breaking diff well -- but `mcp-contract` never calls a tool
  (read-only by design), and neither ships recorded-call replay or an offline
  definition mode. `pytest-mcptest` lists record/replay as a future roadmap
  item.

mcp-testbench's wedge is the combination in one zero-dependency package:
snapshot + classified diff + **JSONL replay** + **lint** + pytest fixtures +
**offline JSON definitions**, over stdio and HTTP.

## What v0.2 closed

v0.1 was behind the incumbents on three dimensions; v0.2 closes all three:

| Incumbent advantage (v0.1 gap) | v0.2 fix |
|---|---|
| `mcptest` / `pytest-mcptest`: Streamable HTTP transport | **Streamable HTTP client** (plain JSON and SSE-framed responses, `Mcp-Session-Id` handling, custom headers) plus the **legacy SSE transport** (`SSEClient` / `--sse`) |
| `mcp-contract`: deep, direction-aware diff (nested `$ref`, input vs output rules, annotation hints) | **Deep diff**: local `$ref` resolution, recursive nested diffing with dotted paths, direction-aware input/output rules, annotation-hint flips, title changes as cosmetic, enum / `additionalProperties` / constraint direction handling |
| `mcptest`: 15-rule linter | **`lint` command with 21 rules** covering tools **and** prompts **and** resources (the incumbent's lint is tools-first), including tool-poisoning / instruction-injection patterns |

Plus: replay expectations now cover **structured content**
(`expect.structured` deep-subset match, `expect.json_path` field equality),
not just text / `isError`.

## CLI

```
# look at a server -- stdio, HTTP, or offline
mcp-testbench inspect -- python my_server.py
mcp-testbench inspect --url http://localhost:8000/mcp
mcp-testbench inspect --url http://localhost:8000/sse --sse        # legacy SSE
mcp-testbench inspect --definition server.json                     # offline, no server

# record the contract; commit the file
mcp-testbench snapshot -o mcp-snapshot.json -- python my_server.py
mcp-testbench snapshot -o mcp-snapshot.json --url https://example.com/mcp \
    --header "Authorization: Bearer TOKEN"

# CI gate: exit 1 when a change breaks existing callers
mcp-testbench check mcp-snapshot.json -- python my_server.py
mcp-testbench check mcp-snapshot.json --definition server.json
mcp-testbench check mcp-snapshot.json --url http://localhost:8000/mcp

# lint the schema: exit 1 on errors (--strict also fails on warnings)
mcp-testbench lint -- python my_server.py
mcp-testbench lint --url http://localhost:8000/mcp
mcp-testbench lint --definition server.json --strict

# replay recorded tool calls (JSONL); exit 1 if any call fails
mcp-testbench replay calls.jsonl -- python my_server.py
mcp-testbench replay calls.jsonl --url http://localhost:8000/mcp
```

## Deep diff

Schemas are diffed recursively. Local `$ref` pointers (`#/$defs/...`,
`#/definitions/...`, `#/components/schemas/...`) are resolved, and changes
are reported with dotted paths, e.g. `tool echo.input.config.timeout`.

Change classes: `breaking`, `non-breaking`, `routing` (description or
annotation-hint changes -- no call breaks, but an agent may behave
differently; `destructiveHint` false -> true lands here), and `cosmetic`
(`title` changes). Only `breaking` fails `check`.

Input and output schemas follow opposite rules where the contract is
asymmetric:

| change | input schema | output schema |
|---|---|---|
| property removed | breaking | breaking |
| property added | breaking if required, else non-breaking | non-breaking |
| became required | breaking | non-breaking |
| no longer required | non-breaking | breaking |
| type / enum widened | non-breaking | breaking |
| type / enum narrowed | breaking | non-breaking |
| constraints tightened | breaking | non-breaking |
| constraints loosened | non-breaking | breaking |

The same direction logic applies to enum changes, `additionalProperties`
tightening/loosening, and numeric / length constraints (`minimum`,
`maxLength`, `pattern`, ...) at any nesting depth.

## Lint rules

`mcp-testbench lint` (Python API: `mcp_testbench.lint_schema(schema)`; pytest:
the `mcp_lint` fixture or `mcp_testbench.plugin.assert_no_lint_errors`).
Each finding carries a rule id, a severity (`error` / `warning`), the
surface and name, and a message. Exit code is 1 on any error; `--strict`
also fails on warnings.

| rule id | severity | surface | what it flags |
|---|---|---|---|
| `tool-missing-description` | error | tool | no / empty description |
| `tool-short-description` | warning | tool | description < 20 chars, too short to route on |
| `tool-poisoning-pattern` | error | tool | instruction-injection phrases ("ignore previous instructions", "you must always...", "do not tell the user", `<important>` tags, ...) |
| `tool-name-format` | warning | tool | name is not snake_case |
| `tool-name-too-long` | warning | tool | name > 64 chars |
| `tool-name-collision` | error | tool | two tools share a name (case-insensitive) |
| `tool-missing-output-schema` | warning | tool | no `outputSchema` declared |
| `param-missing-type` | error | tool | parameter with no type / `$ref` / enum / composition |
| `param-untyped-object` | warning | tool | `type: object` with no properties declared |
| `credential-param-unprotected` | warning | tool | credential-sounding parameter name (`password`, `api_key`, `token`, ...) with no `format` hint |
| `param-required-with-default` | error | tool | required parameter that also declares a default |
| `param-string-no-maxlength` | warning | tool | string parameter with no `maxLength` |
| `param-single-value-enum` | warning | tool | enum with exactly one value (use `const`) |
| `param-case-duplicate` | error | tool | two parameters in one tool differ only by casing |
| `prompt-missing-description` | error | prompt | no / empty description |
| `prompt-short-description` | warning | prompt | description < 20 chars |
| `prompt-poisoning-pattern` | error | prompt | instruction-injection phrases in a prompt description |
| `prompt-argument-missing-description` | warning | prompt | a prompt argument has no description |
| `resource-missing-description` | warning | resource | no / empty description |
| `resource-missing-mimetype` | warning | resource | no `mimeType` declared |
| `resource-invalid-uri` | error | resource | URI has no scheme |
| `resource-suspicious-scheme` | error | resource | scriptable / inline-data scheme (`javascript:`, `vbscript:`, `data:`) |

Parameter rules recurse into nested object properties and array items,
resolving local `$ref` pointers.

## Replay

One JSON object per line:

```
{"tool": "echo", "arguments": {"text": "hi"}, "expect": {"contains": "hi"}}
{"tool": "add", "arguments": {"a": 2, "b": 3}, "expect": {"text": "5"}}
{"tool": "boom", "arguments": {}, "expect": {"is_error": true}}
{"tool": "add", "arguments": {"a": 2, "b": 3}, "expect": {"structured": {"result": 5}}}
{"tool": "add", "arguments": {"a": 2, "b": 3}, "expect": {"json_path": {"result": 5}}}
```

`expect` keys: `contains` / `text` (text result), `is_error`,
`structured` (deep-subset match against the result's `structuredContent`:
nested dicts subset-match recursively, lists match element-for-element,
extra actual keys are ignored), and `json_path` (dotted path -> expected
value, resolved against `structuredContent` when present, else against
the whole result). With no `expect`, a call passes if it does not error.

## pytest

Install the package and the plugin loads automatically (`pytest11` entry
point). Point it at your server in `conftest.py`:

```python
import sys
import pytest

@pytest.fixture
def mcp_server_command():
    return [sys.executable, "my_server.py"]

# or, for an HTTP server:
@pytest.fixture
def mcp_url():
    return "http://localhost:8000/mcp"
```

or on the command line / in ini: `--mcp-server "python my_server.py"`,
`--mcp-url http://localhost:8000/mcp` (plus repeatable
`--mcp-header "Authorization: Bearer X"`), or `--mcp-definition server.json`
for the offline mode. Then:

```python
def test_tools_exist(mcp_schema):
    assert "echo" in [t["name"] for t in mcp_schema["tools"]]

def test_no_breaking_changes(mcp_schema, mcp_snapshot):
    mcp_snapshot(mcp_schema, "mcp-snapshot.json")  # writes on first run

def test_schema_lints_clean(mcp_lint):
    assert mcp_lint() == []  # asserts no errors, returns all findings

def test_call(mcp_client):
    result = mcp_client.call_tool("echo", {"text": "hi"})
    assert result["content"][0]["text"] == "hi"
```

Helpers without fixtures, from `mcp_testbench.plugin`:
`assert_no_breaking(old, new)`, `assert_matches_snapshot(schema, path)`,
and `assert_no_lint_errors(schema)`. The engines themselves are
`mcp_testbench.diff_snapshots(old, new)` and `mcp_testbench.lint_schema(schema)`.

## Try the sample servers

```
# stdio
mcp-testbench inspect -- python examples/echo_server.py
mcp-testbench snapshot -o /tmp/snap.json -- python examples/echo_server.py
mcp-testbench check /tmp/snap.json -- python examples/echo_server.py
mcp-testbench lint -- python examples/echo_server.py

# Streamable HTTP (plain JSON at /mcp, SSE-framed at /mcp-sse)
python examples/echo_server_http.py 8765 &
mcp-testbench inspect --url http://127.0.0.1:8765/mcp
mcp-testbench inspect --url http://127.0.0.1:8765/mcp-sse
mcp-testbench lint --url http://127.0.0.1:8765/mcp
```

## Scope of v0.2 / remaining limitations

- Transports: stdio, Streamable HTTP, and legacy SSE are all implemented
  and tested. The legacy SSE client is single-session and does not
  implement resumability / `Last-Event-ID` reconnection.
- Diffing covers tools (input + output schemas, deeply), prompts
  (arguments), and resources (description, name/title, mimeType).
  Composition keywords (`anyOf` / `oneOf` / `allOf`) are not diffed
  branch-by-branch; a change inside a composition branch that does not
  alter the compared keywords above will not be reported.
- Replay's structured assertions cover `structuredContent` (subset match
  and dotted-path equality); arbitrary JSONPath expressions are not
  supported -- `json_path` is dotted lookup only.
- Lint's missing-output-schema rule is a warning by design: whether a
  tool *should* return structured data cannot be detected from the
  schema alone.

## License

MIT
