Skip to content

Last update 

Adoption · Build

Testing MCP servers

Test MCP servers across unit, protocol, and agent layers for logic, 2026-07-28 compliance, and tool selection.

Confirm models discover tools, extract valid parameters, and recover from errors. A tool that works in isolation can still fail if its description is ambiguous or its schema is unclear.

Three layers of testing

Layer Focus Speed What it catches
1. Unit tests Tool logic and business rules Fast, deterministic Validation bugs, rule errors, unhandled exceptions
2. Protocol tests MCP specification compliance Moderate Invalid schemas, header mismatches, authentication gaps
3. Agent tests End-to-end language-model behavior Slowest Wrong tool selection, bad parameter extraction, broken workflows

Skip unit tests and you chase basic logic errors through agent failures. Skip agent tests and you ship tools that pass protocol checks but fail in real user conversations.

Unit tests for tool logic

Test each tool as a pure function with mocked databases and APIs:

  • Input validation. Enforce required fields, reject invalid values, and test edge cases.
  • Business logic. Verify refund limits, permissions, and data transforms.
  • Output structure. Confirm results match your schema and include every required field.
  • Error conditions. Confirm network, not-found, and rate-limit failures return sanitized tool errors.
Unit test examples
from unittest import mock
import pytest


def test_file_support_request_creates_ticket():
    """Test basic ticket creation flow."""
    result = file_support_request(
        customer_email="test@example.com",
        issue_type="billing",
        description="Charged twice",
    )
    assert result["ticket_id"] is not None
    assert result["assigned_team"] == "Finance"
    assert result["status"] == "open"


def test_file_support_request_validates_email():
    """Test input validation."""
    with pytest.raises(ValueError, match="Invalid email format"):
        file_support_request(
            customer_email="not-an-email",
            issue_type="billing",
            description="Issue",
        )


def test_file_support_request_handles_api_timeout():
    """Test error handling."""
    with mock.patch("ticketing_api.create", side_effect=TimeoutError):
        result = file_support_request(
            customer_email="test@example.com",
            issue_type="technical",
            description="Cannot sign in",
        )
        assert result["isError"] is True
        assert "retry" in result["content"][0]["text"].lower()

Protocol tests for MCP compliance

Verify stateless Model Context Protocol (MCP) specification 2026-07-28 requests, JSON-RPC format, and authentication.

Changed in 2026-07-28

Specification 2026-07-28 removes initialize and protocol sessions. Servers must implement server/discover. Every request sends MCP-Protocol-Version, Mcp-Method, _meta["io.modelcontextprotocol/protocolVersion"], and _meta["io.modelcontextprotocol/clientCapabilities"]. Requests to tools/call, resources/read, and prompts/get also send Mcp-Name. See What's new.

Verify 6 protocol areas:

  • Discovery and versioning. Confirm server/discover returns versions and capabilities, and unsupported versions fail with HTTP 400 and -32022 (UnsupportedProtocolVersion).
  • Request metadata. Confirm requests without _meta["io.modelcontextprotocol/protocolVersion"] or _meta["io.modelcontextprotocol/clientCapabilities"] fail with HTTP 400 and -32602.
  • Tool discovery. Confirm tools/list returns valid tool definitions with JSON Schema 2020-12 inputSchema objects.
  • Tool invocation. Confirm tools/call accepts the required MCP-Protocol-Version, Mcp-Method, and Mcp-Name headers and returns valid results with resultType.
  • Header and method errors. Confirm header-body mismatches return HTTP 400 and -32020 (HeaderMismatch), and GET and DELETE return 405 Method Not Allowed.
  • Authentication. Confirm absent, invalid, or wrong-audience (aud) tokens fail with HTTP 401. Confirm insufficient scope fails with HTTP 403.

Examples use placeholder helpers (MCPClient, ProtocolError, create_test_agent, mock_rate_limiting). Substitute your MCP SDK and HTTP test clients.

Protocol test examples
import httpx
import pytest


def test_tools_list_returns_valid_schemas():
    """Verify tool definitions conform to the MCP specification."""
    response = client.request("tools/list")
    assert "tools" in response

    for tool in response["tools"]:
        assert "name" in tool
        assert "description" in tool
        assert "inputSchema" in tool
        validate_json_schema(tool["inputSchema"])


def test_tools_call_returns_correct_format():
    """Verify tool invocation returns the expected structure."""
    response = client.call_tool(
        "file_support_request",
        {
            "customer_email": "test@example.com",
            "issue_type": "billing",
            "description": "Issue",
        },
    )

    assert response["resultType"] == "complete"
    assert "content" in response
    assert isinstance(response["content"], list)
    assert all("type" in item for item in response["content"])


def test_header_mismatch_rejected():
    """Verify mismatched Mcp-Name headers return HTTP 400 and -32020."""
    response = httpx.post(
        server_url,
        headers={
            "Accept": "application/json, text/event-stream",
            "Authorization": f"Bearer {valid_token}",
            "MCP-Protocol-Version": "2026-07-28",
            "Mcp-Method": "tools/call",
            "Mcp-Name": "other_tool",
        },
        json={
            "jsonrpc": "2.0",
            "id": 1,
            "method": "tools/call",
            "params": {
                "name": "file_support_request",
                "arguments": {},
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                    "io.modelcontextprotocol/clientCapabilities": {},
                },
            },
        },
    )

    assert response.status_code == 400
    assert response.json()["error"]["code"] == -32020


def test_unauthorized_request_rejected():
    """Verify authentication is enforced."""
    client_no_auth = MCPClient(server_url, auth_token=None)

    with pytest.raises(ProtocolError, match="401"):
        client_no_auth.call_tool(
            "file_support_request",
            {
                "customer_email": "test@example.com",
                "issue_type": "billing",
                "description": "Issue",
            },
        )

Use MCP Inspector interactively, MCP SDK utilities for conformance, and a JSON Schema 2020-12 validator.

Agent tests for real-world usage

Agent tests verify 4 behaviors on live language models:

  • Tool selection. Given a user request, the agent chooses the right tool.
  • Parameter extraction. The agent extracts valid arguments from user input.
  • Multi-step workflows. The agent chains calls for multi-step tasks.
  • Error recovery. On isError: true, the agent retries or reports the error.
Agent test examples
def test_agent_files_billing_complaint():
    """Test end-to-end ticket creation from a user request."""
    agent = create_test_agent(tools=["file_support_request"])

    response = agent.process(
        "Customer jane@example.com was charged twice for order #5678"
    )

    calls = [c for c in response.tool_calls if c["name"] == "file_support_request"]
    assert len(calls) == 1
    args = calls[0]["arguments"]
    assert args["customer_email"] == "jane@example.com"
    assert args["issue_type"] == "billing"
    assert "charged twice" in args["description"]


def test_agent_handles_ambiguous_request():
    """Test how the agent handles unclear user input."""
    agent = create_test_agent(tools=["file_support_request"])

    response = agent.process("I need help")

    assert any(
        keyword in response.text.lower()
        for keyword in ["what", "which", "tell me more"]
    )


def test_agent_recovers_from_rate_limit():
    """Test that the agent retries after a rate-limit error (first call succeeds, second hits limit, third retries)."""
    agent = create_test_agent(tools=["lookup_order"])

    with mock_rate_limiting(limit=1):
        response = agent.process(
            "Look up order #1234, then order #5678"
        )

    assert response.success
    assert [c["name"] for c in response.tool_calls] == [
        "lookup_order",
        "lookup_order",
        "lookup_order",
    ]

Cover 5 scenarios: happy paths, ambiguous input, multi-step tasks, validation-error recovery, and high-priority edge cases.

Testing strategy

Build test coverage layer by layer:

  1. Run unit tests on every commit. Verify rules, input validation, and errors.
  2. Run protocol tests on every commit. Verify server/discover, schemas, headers, and auth rejection.
  3. Run agent tests on pull requests or nightly builds. Catch unclear descriptions, bad parameters, and workflow regressions.

On agent failure, check unit and protocol tests first. If both pass, inspect descriptions, schemas, and tool count.

Testing checklist

Verify before production release:

  • Run unit tests per commit for validation, guardrails, and sanitized errors.
  • Test server/discover, _meta, -32020, -32022, and HTTP 405 on GET and DELETE (MCP-02, MCP-06).
  • Test HTTP 401 on absent or wrong-audience tokens and HTTP 403 on insufficient scope (MCP-01, MCP-02).
  • Run agent tests for tool selection, parameters, and error recovery.

Related OWASP MCP Top 10, 2025 edition risks: MCP03 Tool Poisoning, MCP05 Command Injection and Execution, MCP06 Intent Flow Subversion