MCP server testing checks that tool logic behaves correctly, that tools are exposed through a valid Model Context Protocol (MCP) interface, and that malformed or hostile inputs do not cause unsafe behaviour. This tutorial builds a practical test pipeline in Python, using unit tests, in-memory protocol tests, property-based tests and a final agent evaluation before production. Start by treating the MCP server as a software boundary, not as a prompt that happens to work in a demo. If you are designing the server itself, see our MCP server development service for the engineering work involved, or evaluate your organisation's baseline with the AI readiness test.
The goal is a repeatable check that you can run locally and in continuous integration (CI), the automated build and test process that runs when code changes. We will use a small finance tool that calculates invoice tax. The same approach applies to search, customer support, reporting and internal operations tools. It does not make a system safe by itself. It gives you evidence about the parts you can test before an agent can call them.
What does MCP server testing need to prove?
An MCP server presents tools and other capabilities through a protocol that a compatible client can call. A reasoning agent may choose a tool and fill its arguments based on a user request and the tool's description. That creates two related testing jobs:
- Technical correctness: Does the handler enforce business rules, return the right result and handle failures without exposing sensitive details?
- Agent usability: Can a client discover the tool, understand its schema and provide arguments that work for the intended task?
A passing unit test only addresses part of the first job. It does not prove that the tool is registered, that its schema is useful, or that a client can call it over MCP. An agent evaluation addresses a different question again: whether a particular model and prompt choose the right tool and arguments. Keep these checks separate so a failure tells you where to look.
This tutorial uses four gates. Staging gates like these mirror the five gates between demo and production required for production AI systems. Each gate catches a different class of defect:
| Gate | What you test | Typical failure it catches | Needs a paid model API? |
|---|---|---|---|
| Unit tests | Business rules without MCP wrappers | Incorrect calculations or missing boundary rules | No |
| Protocol contract tests | Tool discovery, schema and calls through an in-memory client | Missing registration, wrong argument handling or unexpected result shape | No |
| Property-based tests | Many generated and deliberately invalid inputs | Crashes, boundary errors and unsafe assumptions | No |
| Agent evaluation | Tool choice and argument formation for realistic requests | Ambiguous descriptions or poor tool selection | Only if you choose to test with a hosted model |
The first three gates are deterministic. They can run without an LLM, which keeps most feedback quick and reproducible. Agent tests are useful, but they should not replace checks that give the same answer on every run.
What do you need before you start?
You need Python, the MCP Python SDK, FastMCP, pytest, pytest-asyncio and Hypothesis. FastMCP is a Python framework for defining MCP servers and tools. Hypothesis is a property-based testing library that generates input examples for your tests. Install the dependencies in your project environment and record the resolved versions in your lock file. SDK interfaces can change, so keep the test code aligned with the versions you deploy.
You also need:
- A tool with a narrow, understandable responsibility.
- A way to run tests without connecting to production systems.
- A clear statement of valid inputs, invalid inputs and expected side effects.
- A test identity or fake dependency for any access-control checks.
The code below uses an invoice tax calculation as its example. It assumes a decimal-style rate: 0.10 means ten per cent. For a real finance system, use a decimal arithmetic type and the relevant accounting rules instead of assuming binary floating-point arithmetic is suitable. The example is intentionally small so that the testing pattern is visible.
For the protocol layer, follow in-memory testing patterns and align your tests with your installed SDK version. If your team builds on Node or Deno, repositories like FastMCP TypeScript provide equivalent tools to set up your runtime test harness.
Step 1: Separate business logic from the MCP tool
Keep the rule you are testing in a plain function. The MCP wrapper should validate the request boundary, call that function and format the result. This separation makes it possible to test calculations without opening a server session.
Create tools/calculator.py:
def calculate_vat(subtotal: float, rate: float = 0.10) -> float:
if subtotal < 0:
raise ValueError("Subtotal cannot be negative")
if not 0 <= rate <= 1.0:
raise ValueError("Rate must be between 0.0 and 1.0")
return round(subtotal * rate, 2)
Then create tests/test_calculator_unit.py:
import pytest
from tools.calculator import calculate_vat
def test_calculate_vat_for_valid_input():
assert calculate_vat(100.0, 0.10) == 10.0
def test_calculate_vat_allows_zero_rate():
assert calculate_vat(100.0, 0.0) == 0.0
def test_calculate_vat_rejects_negative_subtotal():
with pytest.raises(ValueError, match="Subtotal cannot be negative"):
calculate_vat(-10.0, 0.10)
def test_calculate_vat_rejects_rate_above_one():
with pytest.raises(ValueError, match="Rate must be between"):
calculate_vat(100.0, 1.01)
Run the focused tests with pytest tests/test_calculator_unit.py. You should see four passing tests. If a valid case fails, correct the business logic before moving on. If an invalid case does not raise, the validation rule is missing or applied too late.
Add cases that reflect your own policy. For example, decide whether a zero subtotal is valid, how many decimal places a currency amount supports, and whether a missing rate means a default or an error. A test suite should record an explicit decision, not silently preserve an accidental behaviour.
The example uses float for brevity. Floating-point numbers cannot represent every decimal fraction exactly. For invoices, use Decimal and define rounding at the same point your finance rules require it. Then test values around rounding boundaries. Do not change a financial representation without checking how it affects callers and stored data.
Step 2: Expose the function as an MCP tool
The wrapper below registers a tool called compute_vat. Its description tells a client what the tool does and gives the important input constraints. Tool descriptions are part of the interface. Keep them accurate and direct, but enforce the constraints in code as well. A model reading a description is not a validation mechanism.
Create server.py:
from mcp.server.fastmcp import FastMCP
from tools.calculator import calculate_vat
mcp = FastMCP("EnterpriseFinanceTools")
@mcp.tool()
def compute_vat(subtotal: float, rate: float = 0.10) -> str:
"""Calculate invoice tax. Subtotal must be non-negative. Rate must be between 0 and 1."""
vat = calculate_vat(subtotal, rate)
return f"Calculated VAT: ${vat:.2f}"
For production, be more explicit about the currency, rounding policy and whether the output is tax only or includes the original subtotal. Do not put secrets, internal instructions or sensitive implementation details in a tool description. A client may expose tool metadata to an agent as context.
Step 3: Test discovery and calls through an in-memory session
A unit test does not prove the tool is visible to an MCP client. Add a contract test that opens an in-memory client and server session. This exercises registration and tool calls without starting a separate process or listening on a network socket.
Create tests/test_mcp_contract.py:
import pytest
from mcp.shared.memory import create_connected_server_and_client_session
from server import mcp
@pytest.mark.asyncio
async def test_compute_vat_is_listed_and_callable():
async with create_connected_server_and_client_session(
mcp._mcp_server
) as session:
tools_result = await session.list_tools()
tools_by_name = {tool.name: tool for tool in tools_result.tools}
assert "compute_vat" in tools_by_name
tool = tools_by_name["compute_vat"]
assert "subtotal" in tool.inputSchema["properties"]
assert "subtotal" in tool.inputSchema["required"]
result = await session.call_tool(
"compute_vat",
{"subtotal": 200.0, "rate": 0.10},
)
assert result.isError is False
assert "Calculated VAT: $20.00" in result.content[0].text
The example uses the in-memory helper documented by the Python SDK pattern in the supplied testing dossier. Internal server attributes and returned schema field names can vary between SDK releases. If your installed SDK has changed these APIs, follow its current testing documentation and preserve the assertions: discover the tool, inspect its advertised input contract, call it and check the result.
Run pytest tests/test_mcp_contract.py. You should see the test pass. If the tool is missing from list_tools(), check that the decorator ran and that the test imported the same server instance you expect. If the result text differs, decide whether the contract should be a structured result rather than matching presentation text. Prefer stable, machine-readable output when downstream code needs to interpret fields.
Add negative contract cases as well. An invalid request should produce a controlled tool error, not a process crash, a hanging client or a response that leaks internal exception details. Exact error representation depends on the SDK and how your handler catches exceptions, so assert the behaviour your client contract requires rather than assuming every SDK reports it identically.
For example, use a separate test to call the tool with a negative subtotal and check that the result is marked as an error. Then check that the response does not contain a traceback, a database connection string or an access token. Keep detailed diagnostics in restricted server-side logs, with sensitive values removed.
The official MCP Inspector documentation describes an interactive way to inspect and call server tools. Use it during development when you need to see the tool list and inspect the request and response. The in-memory test remains valuable because it is repeatable and can run in CI.
Step 4: Fuzz values and test the boundaries
Property-based testing checks a general rule across many generated values instead of relying only on a handful of examples. It is useful for numeric boundaries, unusual strings, optional fields and combinations that a developer might not think to add manually.
First test the pure function. This keeps generated examples fast and avoids repeatedly starting a protocol session just to check arithmetic. Add this to tests/test_calculator_properties.py:
from hypothesis import given, strategies as st
from tools.calculator import calculate_vat
@given(
subtotal=st.floats(
min_value=0,
max_value=1_000_000,
allow_nan=False,
allow_infinity=False,
),
rate=st.floats(
min_value=0,
max_value=1,
allow_nan=False,
allow_infinity=False,
),
)
def test_valid_inputs_return_non_negative_tax(subtotal, rate):
result = calculate_vat(subtotal, rate)
assert result >= 0
assert round(result, 2) == result
Run pytest tests/test_calculator_properties.py. Hypothesis will generate examples and report a failing input if it finds a violation. Keep the generated range realistic for the business rule. Add a separate explicit test if your tool must accept larger values, because the chosen maximum is a test boundary, not a universal limit.
Next check invalid values. A simple property test can assert that negative subtotals and out-of-range rates are rejected:
from hypothesis import given, strategies as st
import pytest
from tools.calculator import calculate_vat
@given(subtotal=st.floats(max_value=-0.01, allow_nan=False, allow_infinity=False))
def test_negative_subtotals_are_rejected(subtotal):
with pytest.raises(ValueError):
calculate_vat(subtotal, 0.10)
@given(rate=st.floats(min_value=1.01, allow_nan=False, allow_infinity=False))
def test_rates_above_one_are_rejected(rate):
with pytest.raises(ValueError):
calculate_vat(10.0, rate)
Review generated examples as carefully as hand-written ones. Hypothesis can find edge cases; it cannot decide whether your policy is right. Decide what to do with NaN, infinity, extremely large amounts and values with more precision than the business accepts. The first function currently lets NaN pass comparisons because comparisons with it behave differently from ordinary numbers. If those values could arrive from your transport or an upstream system, add an explicit finite-number check and test it.
For endpoint-level negative tests, call the in-memory tool with representative invalid inputs and check that it returns a controlled error. You can use parameterised tests for a stable list of cases such as a negative subtotal, a rate above one, a missing required field and a wrong JSON type. These tests complement the pure-function fuzz tests: they verify that invalid data is handled correctly at the MCP boundary as well as in the underlying rule.
For strings, use generated inputs when the tool accepts text. Test empty values, long values, Unicode, embedded null characters and strings that resemble SQL or shell commands. These are not magic attack strings that prove a tool is secure. They are prompts to check that input validation, parameterised database access and safe process APIs are in place. Never build a SQL statement or shell command by concatenating an agent-provided string.
Keep fuzz tests bounded enough to be useful in CI. Purpose-built utilities like the MCP server fuzzer repository can uncover boundary regressions in transport and schema parsing before deployment. A small set of property tests can run on every change. Longer fuzzing sessions can run on a schedule or before a release. If a test discovers a defect, save the failing case as a regression test so the same failure is checked directly in future runs.
Step 5: Test side effects and security boundaries safely
A tool that reads a database, creates a ticket or changes a payment record needs tests for more than its return value. Verify what it is authorised to do, which records it can reach and whether repeated calls create duplicate effects. Do not run destructive agent tests against production systems.
Use a disposable database, an isolated staging tenant, a containerised test dependency or a fake HTTP service. Give each test a clear data boundary and remove its test data afterwards. If your real tool calls an external service, inject the client as a dependency so tests can substitute a stub that records requests without sending them. When managing infrastructure dependencies, our enterprise platform engineering team designs isolated environments that replicate production constraints without exposing real systems.
For a write tool, test at least these cases:
- An authorised request changes only the intended record.
- A read-only identity cannot invoke a mutation, even if it can discover the tool.
- A user cannot use an identifier to access another user's record.
- Invalid input is rejected before any write occurs.
- A retry does not create an unintended duplicate, where the operation is designed to be retry-safe.
- An upstream timeout or failure does not return a success message that claims a change was made.
The MCP server should not treat a tool description as an access-control rule. Enforce permissions in server-side code and, where possible, in the underlying service or database. Authentication answers who is making the request; authorisation answers what that identity may do. Test both at the point where the operation is performed.
Check logs and error responses for secrets. A useful test can pass a recognisable fake token into a request context or stub, trigger a controlled failure, and assert that the token does not appear in the tool result or captured logs. Use a test-only marker, never a real credential. The OWASP MCP Top 10 security breakdown is a useful source for reviewing MCP-specific security risks, but your threat model should reflect the tools, identities and data in your own environment.
Test tool metadata as well as arguments. The tool name, description and input schema influence what a client can discover and what an agent may try. Add a review or snapshot check for unexpected changes to these fields. A description change can alter agent behaviour without changing the handler code. Treat edits to tool metadata as interface changes that need review.
If a server uses stdio transport, keep protocol messages on standard output and send diagnostic logs to standard error. A stray print() or console.log() can corrupt message framing for clients that expect protocol data on standard output. Start the actual server process in a separate smoke test and verify that it starts, responds to the intended protocol handshake and exits cleanly. The in-memory harness does not prove that process launch and transport configuration work.
Step 6: Check the real transport with the MCP Inspector
In-memory tests isolate tool behaviour, but they do not validate every part of your launch command, environment or transport configuration. Use the Inspector to investigate the live server interface during development and to add a smoke check where it fits your CI setup. The MCP Inspector guide explains its interface and supported workflows; check the documentation for the version you install.
A typical CLI workflow looks like this, but confirm the exact flags against your installed Inspector version:
npx @modelcontextprotocol/inspector --cli python server.py --method tools/list
You should see a successful response listing compute_vat and its input schema. If the command hangs, inspect the process startup and transport rather than changing the calculation test. If the response contains unexpected output, check whether a log line has been written to the protocol stream.
You can also call the tool through the CLI. The following illustrates the shape of a test command; argument and output flags may differ by Inspector release:
npx @modelcontextprotocol/inspector --cli python server.py \
--method tools/call \
--tool-name compute_vat \
--tool-arg subtotal=150.0 \
--tool-arg rate=0.10
Check that the call returns the expected result and a successful status. Do not make a CI test depend on an unpinned package that may change without notice. Pin the Inspector version or use a lock file, and store the expected response shape in the test. Keep credentials out of command-line arguments where process listings or CI logs could expose them.
Step 7: Put the gates in CI
Run unit, contract and property tests on every change to the server or tool definitions. Add the process-level Inspector smoke test where the runner can install the required dependencies safely. Keep agent evaluations separate if they are slower, nondeterministic or use a paid model API.
A simple CI sequence is:
pytest tests/test_calculator_unit.py
pytest tests/test_calculator_properties.py
pytest tests/test_mcp_contract.py
The exact commands depend on your project configuration. What matters is that a failure blocks the change from reaching the next deployment stage, and that each test result points to a specific gate. Add timeouts so a broken process cannot hold a CI worker indefinitely. Avoid using live customer data or production credentials in the pipeline.
Keep the tool schema and test fixtures under version control. Review changes to argument names, required fields, descriptions, permissions and output shapes as API changes. If a tool is used by several agents or clients, record the compatibility expectations and run the relevant client checks before deploying a change.
A useful release rule is: do not connect a new tool to a production reasoning agent until its handler tests pass, its protocol contract is verified, its security-relevant negative cases are covered, and the required process smoke test succeeds. For write-capable tools, include a sandbox test of the side effect. This is a minimum evidence bar, not a certification.
Step 8: Evaluate whether an agent uses the tool correctly
A technically correct tool can still be difficult for an agent to use. Agent evaluation checks whether a selected model can identify when the tool is appropriate, provide the right arguments and handle the response sensibly. It answers a different question from unit testing.
Start with a small, controlled set of representative user requests. Include requests that should call the tool, requests that should not call it and requests that need clarification. For each case, define the expected tool choice, required arguments and acceptable response. Run the same cases when the model, system instructions, tool description or schema changes.
Use a sandbox tool with fake records and no external write access. Inspect traces for tool choice, arguments, tool response, final answer and any retry. Score the behaviours that matter to your operation, such as whether the agent asks for a missing required value rather than guessing. An evaluation should expose failures for review, not silently turn a model's plausible explanation into evidence that the underlying operation was correct.
For more on testing model behaviour beyond a basic demo, see our guide to evaluations for Claude agents. The Signadot guide to testing MCP servers also discusses the distinct testing concerns around MCP servers and their clients, while resources like the MCPJam guide to MCP server testing explore testing interactive agent interfaces.
What should you do when a test fails?
Trace the failure to the layer that owns it:
| Symptom | First place to investigate | Useful next check |
|---|---|---|
| Unit test returns the wrong amount | Business rule or numeric representation | Add a boundary example and verify rounding policy |
Tool is absent from tools/list |
Registration, imports or server instance | Inspect the server and list tools with the Inspector |
| Schema omits a required field | Function signature or SDK schema generation | Compare the advertised schema with the contract |
| Valid call returns a tool error | Wrapper, type conversion or dependency | Inspect a restricted server-side trace |
| Invalid input crashes the process | Exception handling and input validation | Add a negative contract test and test process recovery |
| Test hangs over stdio | Startup, protocol framing or blocked dependency | Redirect logs to standard error and add a timeout |
| Agent chooses the wrong tool | Tool description, overlap or model behaviour | Test clearer descriptions and competing-tool scenarios |
Do not fix a failing test by weakening the assertion without understanding what changed. Sometimes the expected contract is wrong. Sometimes the implementation has regressed. Record the decision and update the relevant tests so future changes are intentional.
Where PADISO fits
We help teams design MCP tools, connect them to business systems and build the testing and operational controls needed before agents use them. Our MCP server development service covers the tool interface, while AI agents and automation focuses on how agents use those tools in workflows. A sensible first step is to map the tool's permissions, side effects and failure cases before choosing the test gates.
To put this into practice, pick one low-risk tool and write its business-rule tests before exposing it to an agent. Then add the protocol, fuzz and sandbox checks that match its risks. If you want help reviewing the design, talk to PADISO about your MCP server.
Frequently asked questions
Why can't I just test an MCP server with Claude or another model?
Model-based tests are non-deterministic, slower and incur API costs for every run. Relying exclusively on an LLM leaves basic defects like malformed schemas, unhandled nulls or process crashes undetected until a prompt triggers them.
What is the difference between an in-memory test and an MCP Inspector test?
In-memory tests run within the same Python process using simulated protocol channels, making them fast and suitable for automated CI pipelines. The MCP Inspector tests the compiled process and its transport layer, verifying subprocess startup, environment variables and stdio communication.
How should I secure database write operations exposed to MCP tools?
Enforce access control and validation inside the server-side tool logic rather than relying on the tool description. Use isolated staging tenants, read-only database credentials where possible and strict schema validation before any mutation occurs.