Testing MCP (Model Context Protocol) Servers: A Complete Guide

Testing MCP (Model Context Protocol) Servers: A Complete Guide

Model Context Protocol (MCP) servers are becoming critical infrastructure for AI-powered applications. When your LLM application relies on MCP servers to access tools, databases, and external services, testing those servers thoroughly is non-negotiable. This guide covers everything you need to know to build a robust MCP server testing strategy.

What Is an MCP Server and Why Testing It Is Hard

MCP (Model Context Protocol) is an open protocol that standardizes how AI applications connect to external data sources and tools. An MCP server exposes:

  • Tools — functions the LLM can call (e.g., search_database, send_email)
  • Resources — data the LLM can read (e.g., file contents, database records)
  • Prompts — reusable prompt templates

Testing MCP servers is challenging because:

  1. Stateful interactions — tools may depend on prior state or session context
  2. LLM non-determinism — the client calling your tools is an LLM, not deterministic code
  3. Transport variety — MCP supports stdio and HTTP (SSE) transports, each with different testing needs
  4. Schema validation — tool inputs/outputs must match declared JSON schemas exactly
  5. Side effects — tools often write to databases, call external APIs, send notifications

Setting Up Your MCP Server Testing Environment

Before writing tests, set up a proper testing foundation.

Install Testing Dependencies

For a Python MCP server using the official SDK:

pip install mcp pytest pytest-asyncio httpx

For TypeScript/Node.js:

npm install @modelcontextprotocol/sdk vitest @types/node

Project Structure

my-mcp-server/
├── src/
│   ├── server.py          # MCP server implementation
│   ├── tools/
│   │   ├── search.py
│   │   └── database.py
│   └── resources/
│       └── files.py
├── tests/
│   ├── unit/
│   │   ├── test_tools.py
│   │   └── test_resources.py
│   ├── integration/
│   │   └── test_server.py
│   └── fixtures/
│       └── mock_data.py

Unit Testing MCP Tools

Unit tests for MCP tools should test the underlying tool functions directly, without going through the MCP protocol layer.

Testing Tool Logic Directly

# tests/unit/test_tools.py
import pytest
from unittest.mock import AsyncMock, patch
from src.tools.database import query_records, insert_record

@pytest.mark.asyncio
async def test_query_records_returns_list():
    with patch('src.tools.database.db_connection') as mock_db:
        mock_db.execute.return_value = [
            {"id": 1, "name": "Alice"},
            {"id": 2, "name": "Bob"}
        ]
        result = await query_records(table="users", limit=10)
        assert isinstance(result, list)
        assert len(result) == 2
        assert result[0]["name"] == "Alice"

@pytest.mark.asyncio
async def test_query_records_respects_limit():
    with patch('src.tools.database.db_connection') as mock_db:
        mock_db.execute.return_value = [{"id": 1, "name": "Alice"}]
        result = await query_records(table="users", limit=1)
        mock_db.execute.assert_called_once()
        call_args = mock_db.execute.call_args[0][0]
        assert "LIMIT 1" in call_args

@pytest.mark.asyncio
async def test_insert_record_returns_id():
    with patch('src.tools.database.db_connection') as mock_db:
        mock_db.execute.return_value = {"inserted_id": 42}
        result = await insert_record(table="users", data={"name": "Charlie"})
        assert result["inserted_id"] == 42

Testing Tool Schema Validation

MCP tools declare their input schemas. Test that your tools enforce these schemas correctly:

# tests/unit/test_tool_schemas.py
import pytest
from mcp.types import Tool
from src.server import get_tools

def test_all_tools_have_valid_schemas():
    tools = get_tools()
    for tool in tools:
        assert isinstance(tool, Tool)
        assert tool.name
        assert tool.description
        assert tool.inputSchema is not None
        assert "type" in tool.inputSchema
        assert tool.inputSchema["type"] == "object"

def test_search_tool_schema_requires_query():
    tools = {t.name: t for t in get_tools()}
    search_tool = tools["search"]
    required = search_tool.inputSchema.get("required", [])
    assert "query" in required

def test_database_tool_schema_has_correct_types():
    tools = {t.name: t for t in get_tools()}
    db_tool = tools["query_records"]
    properties = db_tool.inputSchema["properties"]
    assert properties["table"]["type"] == "string"
    assert properties["limit"]["type"] == "integer"

Integration Testing MCP Servers

Integration tests verify the full MCP protocol stack — tool registration, request routing, serialization, and response formatting.

Building a Test MCP Client

The key to integration testing is building a lightweight MCP client that speaks the full protocol:

# tests/integration/mcp_test_client.py
import asyncio
import json
import subprocess
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

class MCPTestClient:
    def __init__(self, server_command: list[str]):
        self.server_command = server_command
        self.session = None
    
    async def __aenter__(self):
        server_params = StdioServerParameters(
            command=self.server_command[0],
            args=self.server_command[1:]
        )
        self.read, self.write = await stdio_client(server_params).__aenter__()
        self.session = ClientSession(self.read, self.write)
        await self.session.__aenter__()
        await self.session.initialize()
        return self
    
    async def __aexit__(self, *args):
        await self.session.__aexit__(*args)
    
    async def list_tools(self):
        result = await self.session.list_tools()
        return result.tools
    
    async def call_tool(self, name: str, arguments: dict):
        result = await self.session.call_tool(name, arguments)
        return result.content
    
    async def list_resources(self):
        result = await self.session.list_resources()
        return result.resources
    
    async def read_resource(self, uri: str):
        result = await self.session.read_resource(uri)
        return result.contents

Writing Integration Tests

# tests/integration/test_server.py
import pytest
from tests.integration.mcp_test_client import MCPTestClient

@pytest.fixture
async def mcp_client():
    async with MCPTestClient(["python", "-m", "src.server"]) as client:
        yield client

@pytest.mark.asyncio
async def test_server_exposes_expected_tools(mcp_client):
    tools = await mcp_client.list_tools()
    tool_names = {t.name for t in tools}
    expected_tools = {"search", "query_records", "insert_record", "send_email"}
    assert expected_tools.issubset(tool_names)

@pytest.mark.asyncio
async def test_search_tool_returns_results(mcp_client):
    result = await mcp_client.call_tool("search", {"query": "test query"})
    assert len(result) > 0
    # MCP tool results are ContentBlock objects
    assert result[0].type == "text"
    assert isinstance(result[0].text, str)

@pytest.mark.asyncio
async def test_tool_with_invalid_args_returns_error(mcp_client):
    # Missing required argument
    result = await mcp_client.call_tool("search", {})
    # MCP servers should return isError=True for invalid calls
    assert any(hasattr(r, 'isError') and r.isError for r in result)

@pytest.mark.asyncio
async def test_resources_are_accessible(mcp_client):
    resources = await mcp_client.list_resources()
    assert len(resources) > 0
    
    # Read the first resource
    first_resource = resources[0]
    content = await mcp_client.read_resource(str(first_resource.uri))
    assert len(content) > 0

Testing MCP Servers Over HTTP Transport

Many production MCP servers use HTTP+SSE transport instead of stdio. Here's how to test those:

# tests/integration/test_http_server.py
import pytest
import httpx
import asyncio
from tests.fixtures.server_process import start_http_server

@pytest.fixture
async def http_server():
    process = start_http_server(port=8765)
    await asyncio.sleep(0.5)  # Wait for server to start
    yield "http://localhost:8765"
    process.terminate()

@pytest.mark.asyncio
async def test_http_server_health(http_server):
    async with httpx.AsyncClient() as client:
        response = await client.get(f"{http_server}/health")
        assert response.status_code == 200

@pytest.mark.asyncio
async def test_http_mcp_initialize(http_server):
    async with httpx.AsyncClient() as client:
        # MCP over HTTP uses JSON-RPC
        response = await client.post(
            f"{http_server}/mcp",
            json={
                "jsonrpc": "2.0",
                "id": 1,
                "method": "initialize",
                "params": {
                    "protocolVersion": "2024-11-05",
                    "capabilities": {},
                    "clientInfo": {"name": "test-client", "version": "1.0"}
                }
            }
        )
        assert response.status_code == 200
        result = response.json()
        assert "result" in result
        assert result["result"]["protocolVersion"] == "2024-11-05"

Building Mock MCP Clients for End-to-End Testing

When you want to test how your MCP server behaves when called by an actual LLM, you need a mock client that simulates LLM-driven tool use patterns.

Scripted LLM Behavior Simulator

# tests/mocks/llm_simulator.py
from dataclasses import dataclass
from typing import Callable, Any

@dataclass
class ToolCallScenario:
    """Simulates a specific LLM tool-calling pattern."""
    name: str
    steps: list[dict]  # Each step is {tool, args, expected_response_contains}

class LLMSimulator:
    """Replays scripted tool-calling sequences to test MCP server behavior."""
    
    def __init__(self, mcp_client):
        self.client = mcp_client
        self.call_log = []
    
    async def run_scenario(self, scenario: ToolCallScenario):
        results = []
        for step in scenario.steps:
            result = await self.client.call_tool(step["tool"], step["args"])
            self.call_log.append({
                "tool": step["tool"],
                "args": step["args"],
                "result": result
            })
            
            if "expected_response_contains" in step:
                result_text = " ".join(r.text for r in result if hasattr(r, 'text'))
                assert step["expected_response_contains"] in result_text, \
                    f"Expected '{step['expected_response_contains']}' in tool response"
            
            results.append(result)
        
        return results

# Test using the simulator
@pytest.mark.asyncio
async def test_multi_step_workflow(mcp_client):
    simulator = LLMSimulator(mcp_client)
    
    scenario = ToolCallScenario(
        name="search-then-read",
        steps=[
            {
                "tool": "search",
                "args": {"query": "user accounts"},
                "expected_response_contains": "users"
            },
            {
                "tool": "query_records",
                "args": {"table": "users", "limit": 5},
            }
        ]
    )
    
    results = await simulator.run_scenario(scenario)
    assert len(results) == 2
    assert len(simulator.call_log) == 2

Testing Error Handling and Edge Cases

Robust MCP servers must handle edge cases gracefully. Test these explicitly:

# tests/unit/test_error_handling.py
import pytest
from src.server import handle_tool_call

@pytest.mark.asyncio
async def test_tool_handles_database_timeout():
    with patch('src.tools.database.db_connection') as mock_db:
        mock_db.execute.side_effect = TimeoutError("DB timeout after 5s")
        result = await handle_tool_call("query_records", {"table": "users"})
        assert result.isError
        assert "timeout" in result.content[0].text.lower()

@pytest.mark.asyncio
async def test_tool_handles_sql_injection_attempt():
    result = await handle_tool_call(
        "query_records",
        {"table": "users; DROP TABLE users; --"}
    )
    assert result.isError
    assert "invalid table name" in result.content[0].text.lower()

@pytest.mark.asyncio
async def test_tool_handles_rate_limit():
    # Simulate hitting an external API rate limit
    with patch('src.tools.search.external_api') as mock_api:
        mock_api.search.side_effect = RateLimitError(retry_after=60)
        result = await handle_tool_call("search", {"query": "test"})
        assert result.isError
        assert "rate limit" in result.content[0].text.lower()

CI/CD Integration for MCP Server Tests

Add MCP server tests to your CI pipeline with proper isolation:

# .github/workflows/test-mcp-server.yml
name: Test MCP Server

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: test
          POSTGRES_DB: testdb
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    
    steps:
      - uses: actions/checkout@v4
      
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      
      - name: Install dependencies
        run: pip install -r requirements-test.txt
      
      - name: Run unit tests
        run: pytest tests/unit/ -v --tb=short
      
      - name: Run integration tests
        env:
          DATABASE_URL: postgresql://postgres:test@localhost/testdb
        run: pytest tests/integration/ -v --tb=short --timeout=30
      
      - name: Upload test results
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: test-results
          path: test-results/

Key Testing Patterns to Remember

1. Test tool contracts, not implementations. Your tests should verify that tools return the data they promise in the schema, not the specific SQL queries they execute internally.

2. Mock external dependencies at the boundary. Database connections, HTTP clients, and file system access should all be mockable. Keep your tool functions thin wrappers around injectable dependencies.

3. Test the full protocol round-trip. Unit tests catch logic bugs. Integration tests catch serialization bugs, schema mismatches, and MCP protocol violations.

4. Document expected LLM interaction patterns. Use the LLMSimulator pattern to encode the tool-calling sequences that your MCP server is designed to support. These become living documentation.

5. Chaos test your error handlers. Every tool should return a valid MCP error response (not throw an unhandled exception) when given bad inputs, when dependencies fail, or when rate limits are hit.

Monitoring MCP Servers in Production

Testing in CI is only half the battle. Once your MCP server is live, you need continuous monitoring to catch regressions and performance degradation.

Tools like HelpMeTest can run automated tests against your MCP server on a schedule — verifying that tools continue to return valid responses, that latency stays within acceptable bounds, and that error rates don't spike when you ship updates. With 24/7 monitoring and 5-minute check intervals on the free plan, you get early warning before LLM applications that depend on your MCP server start breaking.

Summary

Testing MCP servers requires a three-layer approach:

  • Unit tests for individual tool and resource logic — fast, isolated, comprehensive
  • Integration tests using a real MCP client against your full server — catches protocol and serialization issues
  • End-to-end tests with scripted LLM behavior — validates the real-world usage patterns your server is designed to support

Start with unit tests for all your tools, add integration tests for critical paths, and use the LLM simulator pattern to document and protect your most important workflows.

Read more

Start now free