-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreference_plugin.py
More file actions
241 lines (190 loc) · 7.03 KB
/
Copy pathreference_plugin.py
File metadata and controls
241 lines (190 loc) · 7.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/env python3
"""Reference plugin for the MCP Test Harness.
This module demonstrates how to build a plugin that follows the
:class:`~mcp_test_harness.plugins.MCPTestPlugin` protocol. It registers
a custom assertion, a custom fixture, and a custom reporter.
Usage
-----
**Via config file** -- add the file path to the ``plugins`` list in your
``mcp-test.yaml``::
plugins:
- examples/reference_plugin.py
**Via entry point** -- declare the plugin in your package's
``pyproject.toml`` so it is discovered automatically::
[project.entry-points.mcp_test_harness]
latency = "my_package.reference_plugin:plugin"
In the entry-point case, the registry loads the ``plugin`` module-level
object (an instance of :class:`LatencyPlugin`).
Requirements: 9.6
"""
from __future__ import annotations
import time
from collections.abc import Callable
from typing import Any
from mcp_test_harness.assertions import MCPAssertionError
from mcp_test_harness.fixtures import FixtureScope
from mcp_test_harness.models import SessionResults, CaseStatus
from mcp_test_harness.plugins import PluginContext
# ---------------------------------------------------------------------------
# Custom assertion
# ---------------------------------------------------------------------------
async def assert_response_time(
session: Any,
tool_name: str,
arguments: dict[str, Any],
max_ms: float = 500.0,
) -> Any:
"""Assert that a tool call completes within *max_ms* milliseconds.
Parameters
----------
session:
An MCP ``ClientSession`` (or duck-typed equivalent).
tool_name:
Name of the tool to invoke.
arguments:
Arguments dict passed to the tool.
max_ms:
Maximum acceptable latency in milliseconds.
Returns
-------
The raw result from ``session.call_tool``.
Raises
------
MCPAssertionError
When the tool call takes longer than *max_ms*.
"""
start = time.monotonic()
result = await session.call_tool(tool_name, arguments)
elapsed_ms = (time.monotonic() - start) * 1000.0
if elapsed_ms > max_ms:
raise MCPAssertionError(
f"Tool '{tool_name}' took {elapsed_ms:.1f}ms "
f"(limit: {max_ms:.1f}ms)",
)
return result
# ---------------------------------------------------------------------------
# Custom fixture
# ---------------------------------------------------------------------------
def test_config_factory() -> dict[str, Any]:
"""Factory for the ``test_config`` fixture.
Returns a configuration dict that tests can request by declaring a
``test_config`` parameter::
async def test_my_tool(mcp_server, test_config):
timeout = test_config["timeout"]
...
Because the scope is ``PER_MODULE``, the same dict is shared across
all tests in a module.
"""
return {
"timeout": 30.0,
"retry_count": 2,
"server_name": "my-mcp-server",
"tags": ["smoke", "integration"],
}
# ---------------------------------------------------------------------------
# Custom reporter
# ---------------------------------------------------------------------------
class MarkdownReporter:
"""Reporter that generates a Markdown summary of the test run.
The output is suitable for pasting into a pull-request comment or
saving as a ``.md`` file.
"""
def generate(self, results: SessionResults) -> str:
"""Return a Markdown-formatted test report.
Parameters
----------
results:
Aggregated results from the test run.
Returns
-------
str
A Markdown string with a summary table and per-test details.
"""
lines: list[str] = [
"# MCP Test Report",
"",
f"**Protocol version:** {results.protocol_version} ",
f"**Duration:** {results.total_duration_ms:.1f}ms",
"",
"## Summary",
"",
"| Status | Count |",
"|--------|-------|",
f"| PASS | {results.passed} |",
f"| FAIL | {results.failed} |",
f"| ERROR | {results.errored} |",
f"| SKIP | {results.skipped} |",
"",
"## Results",
"",
"| Test | Status | Duration |",
"|------|--------|----------|",
]
for tr in results.test_results:
icon = _status_icon(tr.status)
flaky_tag = " *(flaky)*" if tr.flaky else ""
lines.append(
f"| {tr.name} | {icon} {tr.status.value}{flaky_tag} "
f"| {tr.duration_ms:.1f}ms |"
)
# Append failure details if any
failures = [
tr
for tr in results.test_results
if tr.status in (CaseStatus.FAILED, CaseStatus.ERROR)
]
if failures:
lines.append("")
lines.append("## Failure Details")
for tr in failures:
lines.append("")
lines.append(f"### {tr.name}")
if tr.error:
lines.append("")
lines.append(f"**Error:** {tr.error}")
if tr.assertion_diff:
lines.append("")
lines.append("```diff")
lines.append(tr.assertion_diff)
lines.append("```")
return "\n".join(lines)
def _status_icon(status: CaseStatus) -> str:
"""Return a text label for the given test status."""
return {
CaseStatus.PASSED: "PASS",
CaseStatus.FAILED: "FAIL",
CaseStatus.ERROR: "ERROR",
CaseStatus.TIMEOUT: "TIMEOUT",
CaseStatus.SKIPPED: "SKIP",
}.get(status, "?")
# ---------------------------------------------------------------------------
# Plugin class (implements MCPTestPlugin protocol)
# ---------------------------------------------------------------------------
class LatencyPlugin:
"""Reference plugin demonstrating the MCPTestPlugin protocol.
Registers:
- ``assert_response_time`` -- custom assertion checking tool latency
- ``test_config`` -- per-module fixture providing test configuration
- ``markdown`` -- reporter that generates a Markdown summary
"""
name: str = "latency"
def register(self, context: PluginContext) -> None:
"""Register all extensions with the harness.
Parameters
----------
context:
The :class:`~mcp_test_harness.plugins.PluginContext` provided
by the plugin registry during loading.
"""
# 1. Custom assertion
context.add_assertion("assert_response_time", assert_response_time)
# 2. Custom fixture (per-module scope so it's shared across tests)
context.add_fixture(
"test_config",
test_config_factory,
scope=FixtureScope.PER_MODULE,
)
# 3. Custom reporter
context.add_reporter("markdown", MarkdownReporter())
# Module-level instance used by entry-point discovery.
plugin = LatencyPlugin()