Testing FastMCP Servers with Pytest

Write quick, reliable tests with an in-memory client, pytest fixtures, parametrised cases and snapshots.

Terminal showing a pytest run with all FastMCP server tests passing

Key takeaways

  • Client(mcp) tests a server in memory, with no ports or subprocesses.
  • Set asyncio_mode = "auto" for pytest-asyncio.
  • Test failure paths and error messages as well as results.
  • Use inline-snapshot for complex output and run tests in CI.

Because the FastMCP client can connect to a server object in the same process, you can test every tool, resource and prompt without starting a subprocess or opening a port. Tests run in milliseconds and behave the same on every machine, which makes them a natural part of everyday development.

Why Test an MCP Server?

Models are forgiving readers, but they cannot fix a broken tool. Tests catch the problems that would otherwise surface only in a conversation: a renamed tool, a changed parameter, a resource that returns the wrong format or an error message that no longer helps. They also give you the confidence to upgrade FastMCP itself.

Set Up Pytest

The client is asynchronous, so install the asyncio plugin for pytest alongside pytest itself:

uv add --dev pytest pytest-asyncio
# or
pip install pytest pytest-asyncio

Then set the asyncio mode to auto in pyproject.toml, which removes the need to mark every async test individually:

[tool.pytest.ini_options]
asyncio_mode = "auto"

A typical layout keeps the server in a package and the tests beside it:

my_project/
    __init__.py
    main.py          # defines mcp = FastMCP(...)
tests/
    conftest.py      # shared fixtures
    test_tools.py
    test_resources.py
pyproject.toml

Create a Client Fixture

A fixture in conftest.py opens one in-memory connection per test and closes it afterwards:

import pytest
from fastmcp.client import Client

from my_project.main import mcp


@pytest.fixture
async def client():
    async with Client(mcp) as c:
        yield c

Every test that names client as an argument receives a fresh, connected client. No server process, no port and no clean-up code in the tests themselves.

Write Your First Test

async def test_lists_expected_tools(client):
    tools = await client.list_tools()
    names = {tool.name for tool in tools}
    assert {"add", "greet"} <= names

This confirms that the server registers the tools you expect, which catches accidental renames and missing decorators. Using a subset check (<=) means adding a new tool will not break the test.

Test Tool Results

async def test_greet(client):
    result = await client.call_tool("greet", {"name": "Ada"})
    assert result.data == "Hello, Ada!"

Assert on result.data, the Python value, rather than on raw text. It keeps tests readable and type-aware.

Many inputs at once

pytest.mark.parametrize runs the same test against several cases, each reported separately:

import pytest


@pytest.mark.parametrize(
    "a, b, expected",
    [(1, 2, 3), (2, 3, 5), (-4, 4, 0)],
)
async def test_add(client, a, b, expected):
    result = await client.call_tool("add", {"a": a, "b": b})
    assert result.data is not None
    assert isinstance(result.data, int)
    assert result.data == expected

Test the Failure Paths

Good tests check that bad input is refused. Call a tool with a wrongly typed argument and assert that an exception is raised:

async def test_add_rejects_text(client):
    with pytest.raises(Exception):
        await client.call_tool("add", {"a": "one", "b": 2})

Where a tool raises ToolError with a deliberate message, assert on that message too. It is part of the contract with the model, because the model relies on it to correct its next call.

async def test_count_days_explains_bad_range(client):
    with pytest.raises(Exception, match="start_date must be before end_date"):
        await client.call_tool(
            "count_days", {"start_date": "2026-05-02", "end_date": "2026-05-01"}
        )

Test Resources and Prompts

async def test_config_resource(client):
    content = await client.read_resource("config://app")
    assert "dark" in content[0].text


async def test_review_prompt(client):
    prompt = await client.get_prompt("review_code", {"code": "print(1)"})
    assert "print(1)" in str(prompt.messages)

Use Snapshots for Complex Output

For large or nested results, the FastMCP documentation suggests inline-snapshot. Write assert value == snapshot(), then let the tool fill in the expected value:

from inline_snapshot import snapshot


async def test_tool_listing(client):
    tools = await client.list_tools()
    assert [t.name for t in tools] == snapshot()
pytest --inline-snapshot=fix,create

The recorded value appears directly in your test file, where reviewers can read it. When behaviour changes intentionally, run the same command to update the snapshot.

Values that change between runs

Timestamps and generated identifiers differ on every run. dirty-equals lets you assert on their shape rather than their exact content, for example that a value is a string or a positive integer.

Measure Coverage

Coverage reports show which parts of your server the tests exercise. With the pytest-cov plugin installed, run:

pytest --cov=my_project --cov-report=term-missing

Aim for every tool, resource and prompt to have at least one test of its normal behaviour and, where relevant, one of its failure behaviour.

Run Tests in CI

  • Install dependencies from your lockfile so CI uses the same FastMCP version as development.
  • Run pytest -q on every pull request and block merging when it fails.
  • Keep network-dependent tests separate and mark them, so the core suite stays fast and deterministic.
  • Run the suite against a new FastMCP release on a branch before upgrading the main project.

The FastMCP repository’s own test suite is a useful source of further examples covering clients, tools, resources and prompts.

Frequently Asked Questions

No. Passing the server object to the client creates an in-memory connection in the same process, which is faster and more reliable than starting a separate server.

pytest needs the pytest-asyncio plugin to run async tests. Install it and set asyncio_mode = "auto" in pyproject.toml, or mark each test individually.

Not in the main suite. Models are slow and non-deterministic. Test your tools directly through the client, and keep any model-based checks in a separate, optional suite.

Use dirty-equals to assert on the shape of a value, such as being a string or a positive integer, rather than on its exact content.

Keep reading

Related Guides