Skip to content
devtoolbox.cc

FastMCP · Chapter 4 of 6

Testing FastMCP servers in memory and over stdio

12 min study · Examples checked with FastMCP 4.2 and MCP Python SDK 2.3 on Python 3.14 ·

A direct function test proves business logic, but it does not prove that an MCP caller can discover the tool, satisfy its schema, or decode its result. A transport test adds another boundary: interpreter selection, process startup, and protocol framing. This chapter tests both layers using one small server and Python’s standard test runner.

Create an isolated server factory

In a fresh directory, create server.py:

from typing import Annotated

from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
from pydantic import Field

def create_server() -> FastMCP:
    server = FastMCP("Catalog lookup", mask_error_details=True)
    lessons = {1: {"id": 1, "title": "Python functions", "minutes": 12}}

    @server.tool(annotations={"readOnlyHint": True})
    def get_lesson(lesson_id: Annotated[int, Field(ge=1)]) -> dict:
        """Return one published lesson by its positive catalog identifier."""
        lesson = lessons.get(lesson_id)
        if lesson is None:
            raise ToolError("Lesson not found. Use a published catalog identifier.")
        return lesson.copy()

    return server

if __name__ == "__main__":
    create_server().run()

The factory gives each test independent state. This matters as soon as tools can mutate objects, cache results, or initialize collaborators. Returning a copy also avoids sharing the dictionary that the server treats as its own record. Here the content is intentionally static; persistence appears in the last chapter.

Write protocol-level tests

Create test_server.py:

import unittest

from fastmcp import Client
from server import create_server

class CatalogTests(unittest.IsolatedAsyncioTestCase):
    async def test_discovery_and_result(self):
        async with Client(create_server()) as client:
            tools = await client.list_tools()
            self.assertEqual([tool.name for tool in tools], ["get_lesson"])
            self.assertEqual(tools[0].input_schema["properties"]["lesson_id"]["minimum"], 1)
            result = await client.call_tool("get_lesson", {"lesson_id": 1})
            self.assertEqual(result.data["title"], "Python functions")

    async def test_validation_and_missing_entity(self):
        async with Client(create_server()) as client:
            for identifier in (0, 999):
                result = await client.call_tool(
                    "get_lesson", {"lesson_id": identifier}, raise_on_error=False
                )
                self.assertTrue(result.is_error)

if __name__ == "__main__":
    unittest.main()

Run python -m unittest -v. The first test checks discovery, a meaningful schema constraint, and an observable result. The second covers both invalid shape and a missing business entity. These tests do not need a network listener, a model, or a real user account.

Test behavior that callers depend on rather than reproducing every line of implementation. A schema or public field changing accidentally can break clients even when the helper function still works. Conversely, reordering private code should not require rewriting a behavioral test.

Launch the same contract in a child process

Create stdio_client.py:

import asyncio
from pathlib import Path
import sys

from fastmcp import Client
from fastmcp.client.transports import StdioTransport

async def main():
    directory = Path(__file__).resolve().parent
    transport = StdioTransport(
        command=sys.executable,
        args=[str(directory / "server.py")],
        cwd=str(directory),
        env={"PYTHONUNBUFFERED": "1"},
    )
    async with Client(transport, timeout=10) as client:
        result = await client.call_tool("get_lesson", {"lesson_id": 1})
        assert result.data["minutes"] == 12
        print("Subprocess contract passed")

if __name__ == "__main__":
    asyncio.run(main())

Run python stdio_client.py. sys.executable chooses the interpreter that already has the dependencies installed. An absolute script path and explicit working directory avoid relying on the terminal’s location. The client owns the child process and releases it when the context exits.

The environment mapping intentionally passes only the setting needed for this example. Current FastMCP’s stdio transport forwards a small platform-specific allowlist by default, not every variable from your shell. Pass required credentials or configuration explicitly and narrowly; do not dump your entire environment into every subprocess. See client transports.

Diagnose failures by boundary

If in-memory tests fail, inspect tool registration, schema, and domain behavior first. If they pass but stdio fails, inspect interpreter paths, imports, environment, working directory, and unexpected stdout output. A missing dependency in the child is not a tool validation error.

If both pass but an HTTP client fails, investigate the URL, endpoint path, authentication, proxy behavior, and server lifecycle. A response timeout can mean work is still running; it is not proof that the server rolled back an operation. For writes, verify an operation’s durable outcome before retrying blindly.

Keep failure assertions as specific as the public contract requires. Checking only that “some exception happened” can pass when the server never started. The stdio test above confirms a successful known call, while invalid-input tests use a working in-memory connection to isolate input behavior.

Adapt client configuration without guessing host settings

Many hosts accept a command, arguments, working directory, and environment for a local server. Their configuration filenames and supported fields vary. Translate the tested launch command into the target host’s documented settings instead of presenting one JSON object as universal MCP configuration.

A Python client can select Client(server_object) for in-memory use, an explicit stdio transport for a managed child, or a URL for HTTP. The calling code remains similar, but those transports exercise different ownership and security boundaries. Reuse the behavioral checks, not an assumption that all transports behave identically.

Practice

Add a second lesson and test both identifiers. Deliberately choose an interpreter without FastMCP and observe the subprocess startup failure, then restore sys.executable. Add a client assertion that invalid input never returns a normal lesson dictionary.

Answer check: protocol tests catch schema and error-contract defects, stdio verifies a real child process, and client shutdown leaves no server running. No private account configuration or external API is necessary.

Summary

Use fast in-memory checks for most contracts and targeted transport checks for real integration boundaries. A working Python function, a working MCP operation, and a working host connection are related but distinct pieces of evidence.

All FastMCP chapters