mcpsheriff 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcpsheriff/__init__.py +5 -0
- mcpsheriff/checks.py +420 -0
- mcpsheriff/cli.py +172 -0
- mcpsheriff/protocol.py +288 -0
- mcpsheriff/report.py +93 -0
- mcpsheriff-0.1.0.dist-info/METADATA +160 -0
- mcpsheriff-0.1.0.dist-info/RECORD +10 -0
- mcpsheriff-0.1.0.dist-info/WHEEL +5 -0
- mcpsheriff-0.1.0.dist-info/entry_points.txt +2 -0
- mcpsheriff-0.1.0.dist-info/top_level.txt +1 -0
mcpsheriff/__init__.py
ADDED
mcpsheriff/checks.py
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
"""Individual checks for an MCP server.
|
|
2
|
+
|
|
3
|
+
Each check is a small function that receives the session (already initialized)
|
|
4
|
+
and returns ``Result``. Checks never raise: a crash inside a check becomes a
|
|
5
|
+
failed result with the exception text, because a tester that dies on the first
|
|
6
|
+
bad server is useless.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import time
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any, Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
from .protocol import KNOWN_VERSIONS, PROTOCOL_VERSION, ProtocolError, RpcError, Session
|
|
18
|
+
|
|
19
|
+
TOOL_NAME = re.compile(r"^[a-z0-9_-]{1,64}$")
|
|
20
|
+
LATENCY_BUDGET_MS = 5000
|
|
21
|
+
|
|
22
|
+
SEVERITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class Result:
|
|
27
|
+
name: str
|
|
28
|
+
ok: bool
|
|
29
|
+
detail: str = ""
|
|
30
|
+
severity: str = "high"
|
|
31
|
+
skipped: bool = False
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def status(self) -> str:
|
|
35
|
+
if self.skipped:
|
|
36
|
+
return "skip"
|
|
37
|
+
return "pass" if self.ok else "FAIL"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Context:
|
|
42
|
+
"""Everything a check may need beyond the live session."""
|
|
43
|
+
|
|
44
|
+
session: Session
|
|
45
|
+
timeout: float = 10.0
|
|
46
|
+
latency_budget_ms: int = LATENCY_BUDGET_MS
|
|
47
|
+
tools: List[Dict[str, Any]] = field(default_factory=list)
|
|
48
|
+
resources: List[Dict[str, Any]] = field(default_factory=list)
|
|
49
|
+
prompts: List[Dict[str, Any]] = field(default_factory=list)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _fail(name: str, detail: str, severity: str = "high") -> Result:
|
|
53
|
+
return Result(name=name, ok=False, detail=detail, severity=severity)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _pass(name: str, detail: str = "", severity: str = "high") -> Result:
|
|
57
|
+
return Result(name=name, ok=True, detail=detail, severity=severity)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# --------------------------------------------------------------------------
|
|
61
|
+
# handshake
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def check_handshake(ctx: Context) -> Result:
|
|
65
|
+
session = ctx.session
|
|
66
|
+
version = session.protocol_version
|
|
67
|
+
if not version:
|
|
68
|
+
return _fail("handshake", "initialize returned no protocolVersion", "critical")
|
|
69
|
+
|
|
70
|
+
info = session.server_info or {}
|
|
71
|
+
missing = [key for key in ("name", "version") if not info.get(key)]
|
|
72
|
+
caps = session.capabilities
|
|
73
|
+
|
|
74
|
+
notes = [f"protocolVersion={version}", f"serverInfo={info.get('name')!r}/{info.get('version')!r}"]
|
|
75
|
+
if not isinstance(caps, dict) or not caps:
|
|
76
|
+
return _fail("handshake", "; ".join(notes + ["no capabilities advertised"]), "high")
|
|
77
|
+
notes.append(f"capabilities={','.join(sorted(caps))}")
|
|
78
|
+
|
|
79
|
+
if missing:
|
|
80
|
+
return _fail("handshake", "; ".join(notes + [f"serverInfo missing {missing}"]), "medium")
|
|
81
|
+
if version not in KNOWN_VERSIONS:
|
|
82
|
+
return Result(
|
|
83
|
+
"handshake",
|
|
84
|
+
ok=True,
|
|
85
|
+
detail="; ".join(notes + [f"unknown protocol version (known: {', '.join(KNOWN_VERSIONS)})"]),
|
|
86
|
+
severity="medium",
|
|
87
|
+
)
|
|
88
|
+
return _pass("handshake", "; ".join(notes))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# --------------------------------------------------------------------------
|
|
92
|
+
# tools
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_tools_list(ctx: Context) -> Result:
|
|
96
|
+
if "tools" not in (ctx.session.capabilities or {}):
|
|
97
|
+
return Result("tools.list", ok=True, skipped=True, detail="server does not advertise tools")
|
|
98
|
+
try:
|
|
99
|
+
response = ctx.session.request("tools/list", {}, timeout=ctx.timeout)
|
|
100
|
+
except RpcError as error:
|
|
101
|
+
return _fail("tools.list", f"tools/list returned an error: {error}", "critical")
|
|
102
|
+
tools = response.get("tools")
|
|
103
|
+
if not isinstance(tools, list):
|
|
104
|
+
return _fail("tools.list", "tools/list result has no 'tools' array", "critical")
|
|
105
|
+
if not tools:
|
|
106
|
+
return _fail("tools.list", "server advertises tools but tools/list is empty", "high")
|
|
107
|
+
|
|
108
|
+
ctx.tools = [tool for tool in tools if isinstance(tool, dict)]
|
|
109
|
+
problems: List[str] = []
|
|
110
|
+
names: List[str] = []
|
|
111
|
+
for index, tool in enumerate(tools):
|
|
112
|
+
if not isinstance(tool, dict):
|
|
113
|
+
problems.append(f"entry #{index} is not an object")
|
|
114
|
+
continue
|
|
115
|
+
name = tool.get("name")
|
|
116
|
+
if not isinstance(name, str) or not TOOL_NAME.match(name):
|
|
117
|
+
problems.append(f"bad name {name!r} (must match {TOOL_NAME.pattern})")
|
|
118
|
+
else:
|
|
119
|
+
names.append(name)
|
|
120
|
+
if not isinstance(tool.get("description"), str) or not tool["description"].strip():
|
|
121
|
+
problems.append(f"{name or index}: empty description")
|
|
122
|
+
schema = tool.get("inputSchema")
|
|
123
|
+
if not isinstance(schema, dict) or schema.get("type") != "object":
|
|
124
|
+
problems.append(f"{name or index}: inputSchema must be an object with type=object")
|
|
125
|
+
duplicates = sorted({name for name in names if names.count(name) > 1})
|
|
126
|
+
if duplicates:
|
|
127
|
+
problems.append(f"duplicate names: {', '.join(duplicates)}")
|
|
128
|
+
|
|
129
|
+
detail = f"{len(tools)} tools; names: {', '.join(names[:8])}" + ("…" if len(names) > 8 else "")
|
|
130
|
+
if problems:
|
|
131
|
+
return _fail("tools.list", "; ".join(problems[:6]), "high")
|
|
132
|
+
return _pass("tools.list", detail)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def check_tool_schemas(ctx: Context) -> Result:
|
|
136
|
+
tools = [tool for tool in ctx.tools if isinstance(tool.get("inputSchema"), dict)]
|
|
137
|
+
if not tools:
|
|
138
|
+
return Result("tools.schema", ok=True, skipped=True, detail="no tool schemas to validate")
|
|
139
|
+
problems: List[str] = []
|
|
140
|
+
for tool in tools:
|
|
141
|
+
name = tool.get("name")
|
|
142
|
+
schema = tool["inputSchema"]
|
|
143
|
+
properties = schema.get("properties", {})
|
|
144
|
+
if not isinstance(properties, dict):
|
|
145
|
+
problems.append(f"{name}: inputSchema.properties must be an object")
|
|
146
|
+
continue
|
|
147
|
+
required = schema.get("required", [])
|
|
148
|
+
if not isinstance(required, list):
|
|
149
|
+
problems.append(f"{name}: inputSchema.required must be an array")
|
|
150
|
+
continue
|
|
151
|
+
unknown = [key for key in required if key not in properties]
|
|
152
|
+
if unknown:
|
|
153
|
+
problems.append(f"{name}: required lists undeclared properties {unknown}")
|
|
154
|
+
for prop, spec in properties.items():
|
|
155
|
+
if not isinstance(spec, dict):
|
|
156
|
+
problems.append(f"{name}.{prop}: property schema must be an object")
|
|
157
|
+
elif "type" not in spec and not any(key in spec for key in ("anyOf", "oneOf", "allOf", "$ref")):
|
|
158
|
+
problems.append(f"{name}.{prop}: property has no type")
|
|
159
|
+
if problems:
|
|
160
|
+
return _fail("tools.schema", "; ".join(problems[:6]), "high")
|
|
161
|
+
return _pass("tools.schema", f"{len(tools)} schemas look consistent")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def check_unknown_tool(ctx: Context) -> Result:
|
|
165
|
+
if not ctx.tools:
|
|
166
|
+
return Result("tools.unknown", ok=True, skipped=True, detail="no tools to test against")
|
|
167
|
+
bogus = "mcpsheriff_does_not_exist_9f3a"
|
|
168
|
+
try:
|
|
169
|
+
response = ctx.session.request(
|
|
170
|
+
"tools/call", {"name": bogus, "arguments": {}}, timeout=ctx.timeout
|
|
171
|
+
)
|
|
172
|
+
except RpcError as error:
|
|
173
|
+
return _pass("tools.unknown", f"rejected with JSON-RPC error ({error.error.get('code')})")
|
|
174
|
+
except ProtocolError as error:
|
|
175
|
+
return _fail("tools.unknown", f"server did not answer a call to an unknown tool: {error}", "critical")
|
|
176
|
+
if response.get("isError") is True:
|
|
177
|
+
return _pass("tools.unknown", "unknown tool returned isError=true")
|
|
178
|
+
return _fail(
|
|
179
|
+
"tools.unknown",
|
|
180
|
+
"calling an unknown tool neither returned isError=true nor a JSON-RPC error",
|
|
181
|
+
"high",
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# --------------------------------------------------------------------------
|
|
186
|
+
# resources / prompts
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _check_list(ctx: Context, capability: str, method: str, key: str, required_keys: List[str]) -> Result:
|
|
190
|
+
label = f"{capability}.list"
|
|
191
|
+
if capability not in (ctx.session.capabilities or {}):
|
|
192
|
+
return Result(label, ok=True, skipped=True, detail=f"server does not advertise {capability}")
|
|
193
|
+
try:
|
|
194
|
+
response = ctx.session.request(method, {}, timeout=ctx.timeout)
|
|
195
|
+
except RpcError as error:
|
|
196
|
+
return _fail(label, f"{method} returned an error: {error}", "high")
|
|
197
|
+
items = response.get(key)
|
|
198
|
+
if not isinstance(items, list):
|
|
199
|
+
return _fail(label, f"{method} result has no '{key}' array", "high")
|
|
200
|
+
if not items:
|
|
201
|
+
return _fail(label, f"server advertises {capability} but {method} is empty", "medium")
|
|
202
|
+
problems: List[str] = []
|
|
203
|
+
for index, item in enumerate(items):
|
|
204
|
+
if not isinstance(item, dict):
|
|
205
|
+
problems.append(f"entry #{index} is not an object")
|
|
206
|
+
continue
|
|
207
|
+
for required in required_keys:
|
|
208
|
+
if not item.get(required):
|
|
209
|
+
problems.append(f"entry #{index}: missing '{required}'")
|
|
210
|
+
if problems:
|
|
211
|
+
return _fail(label, "; ".join(problems[:6]), "medium")
|
|
212
|
+
return _pass(label, f"{len(items)} entries")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def check_resources(ctx: Context) -> Result:
|
|
216
|
+
result = _check_list(ctx, "resources", "resources/list", "resources", ["uri", "name"])
|
|
217
|
+
if result.ok and not result.skipped:
|
|
218
|
+
try:
|
|
219
|
+
ctx.resources = ctx.session.request("resources/list", {}, timeout=ctx.timeout)["resources"]
|
|
220
|
+
except ProtocolError:
|
|
221
|
+
pass
|
|
222
|
+
return result
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def check_prompts(ctx: Context) -> Result:
|
|
226
|
+
result = _check_list(ctx, "prompts", "prompts/list", "prompts", ["name"])
|
|
227
|
+
if result.ok and not result.skipped:
|
|
228
|
+
try:
|
|
229
|
+
ctx.prompts = ctx.session.request("prompts/list", {}, timeout=ctx.timeout)["prompts"]
|
|
230
|
+
except ProtocolError:
|
|
231
|
+
pass
|
|
232
|
+
return result
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# --------------------------------------------------------------------------
|
|
236
|
+
# robustness
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def check_stdout_hygiene(ctx: Context) -> Result:
|
|
240
|
+
noise = list(ctx.session.noise)
|
|
241
|
+
if not noise:
|
|
242
|
+
return _pass("stdout.hygiene", "every stdout line was valid JSON-RPC")
|
|
243
|
+
sample = "; ".join(noise[:3])
|
|
244
|
+
return _fail(
|
|
245
|
+
"stdout.hygiene",
|
|
246
|
+
f"{len(noise)} non-JSON line(s) on stdout, e.g. {sample}",
|
|
247
|
+
"critical",
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def check_survives_bad_request(ctx: Context) -> Result:
|
|
252
|
+
try:
|
|
253
|
+
try:
|
|
254
|
+
ctx.session.request("mcpsheriff/unknown_method", {}, timeout=ctx.timeout)
|
|
255
|
+
except RpcError:
|
|
256
|
+
pass # a JSON-RPC error is the correct answer here
|
|
257
|
+
except ProtocolError as error:
|
|
258
|
+
return _fail("errors.recovery", f"server stopped answering after an unknown method: {error}", "critical")
|
|
259
|
+
|
|
260
|
+
try:
|
|
261
|
+
ctx.session.request("ping", {}, timeout=ctx.timeout)
|
|
262
|
+
except ProtocolError as error:
|
|
263
|
+
return _fail("errors.recovery", f"no reply to ping after an unknown method: {error}", "high")
|
|
264
|
+
except RpcError:
|
|
265
|
+
pass # ping may be unimplemented; an error still proves the process lives
|
|
266
|
+
return _pass("errors.recovery", "still responding after an unknown method")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def check_latency(ctx: Context) -> Result:
|
|
270
|
+
started = time.monotonic()
|
|
271
|
+
try:
|
|
272
|
+
ctx.session.request("tools/list", {}, timeout=max(ctx.timeout, 30.0))
|
|
273
|
+
except (ProtocolError, RpcError) as error:
|
|
274
|
+
return _fail("latency", f"tools/list failed: {error}", "low")
|
|
275
|
+
elapsed_ms = int((time.monotonic() - started) * 1000)
|
|
276
|
+
if elapsed_ms > ctx.latency_budget_ms:
|
|
277
|
+
return Result(
|
|
278
|
+
"latency",
|
|
279
|
+
ok=False,
|
|
280
|
+
detail=f"tools/list took {elapsed_ms} ms (budget {ctx.latency_budget_ms} ms)",
|
|
281
|
+
severity="low",
|
|
282
|
+
)
|
|
283
|
+
return _pass("latency", f"tools/list in {elapsed_ms} ms")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
# --------------------------------------------------------------------------
|
|
287
|
+
# schema drift
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def snapshot_of(ctx: Context) -> Dict[str, Any]:
|
|
291
|
+
def summarise(items: List[Dict[str, Any]], keys: List[str]) -> Dict[str, Any]:
|
|
292
|
+
out: Dict[str, Any] = {}
|
|
293
|
+
for item in items:
|
|
294
|
+
if isinstance(item, dict) and isinstance(item.get("name"), str):
|
|
295
|
+
out[item["name"]] = {key: item.get(key) for key in keys}
|
|
296
|
+
return out
|
|
297
|
+
|
|
298
|
+
return {
|
|
299
|
+
"protocolVersion": ctx.session.protocol_version,
|
|
300
|
+
"tools": summarise(ctx.tools, ["description", "inputSchema"]),
|
|
301
|
+
"resources": summarise(ctx.resources, ["uri", "description"]),
|
|
302
|
+
"prompts": summarise(ctx.prompts, ["description", "arguments"]),
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def diff_snapshot(old: Dict[str, Any], new: Dict[str, Any]) -> List[str]:
|
|
307
|
+
changes: List[str] = []
|
|
308
|
+
if old.get("protocolVersion") != new.get("protocolVersion"):
|
|
309
|
+
changes.append(f"protocolVersion {old.get('protocolVersion')} -> {new.get('protocolVersion')}")
|
|
310
|
+
for section in ("tools", "resources", "prompts"):
|
|
311
|
+
before = old.get(section) or {}
|
|
312
|
+
after = new.get(section) or {}
|
|
313
|
+
for name in sorted(set(after) - set(before)):
|
|
314
|
+
changes.append(f"{section}: added {name}")
|
|
315
|
+
for name in sorted(set(before) - set(after)):
|
|
316
|
+
changes.append(f"{section}: removed {name}")
|
|
317
|
+
for name in sorted(set(before) & set(after)):
|
|
318
|
+
if before[name] != after[name]:
|
|
319
|
+
changes.append(f"{section}: changed {name}")
|
|
320
|
+
return changes
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def check_snapshot(ctx: Context, snapshot_path: str, update: bool = False) -> Optional[Result]:
|
|
324
|
+
"""Returns None when there is nothing to compare against and no --update."""
|
|
325
|
+
current = snapshot_of(ctx)
|
|
326
|
+
try:
|
|
327
|
+
with open(snapshot_path, "r", encoding="utf-8") as handle:
|
|
328
|
+
previous = json.load(handle)
|
|
329
|
+
except FileNotFoundError:
|
|
330
|
+
if update:
|
|
331
|
+
_write_snapshot(snapshot_path, current)
|
|
332
|
+
return _pass("schema.snapshot", f"baseline written to {snapshot_path}")
|
|
333
|
+
return Result(
|
|
334
|
+
"schema.snapshot",
|
|
335
|
+
ok=False,
|
|
336
|
+
detail=f"no snapshot at {snapshot_path}; run again with --update-snapshot to create it",
|
|
337
|
+
severity="medium",
|
|
338
|
+
)
|
|
339
|
+
except (OSError, ValueError) as error:
|
|
340
|
+
return _fail("schema.snapshot", f"cannot read snapshot {snapshot_path}: {error}", "medium")
|
|
341
|
+
|
|
342
|
+
changes = diff_snapshot(previous, current)
|
|
343
|
+
if update:
|
|
344
|
+
_write_snapshot(snapshot_path, current)
|
|
345
|
+
if changes:
|
|
346
|
+
return _pass("schema.snapshot", "baseline updated; changes: " + "; ".join(changes[:8]))
|
|
347
|
+
return _pass("schema.snapshot", f"baseline unchanged ({snapshot_path})")
|
|
348
|
+
if changes:
|
|
349
|
+
return _fail("schema.snapshot", "schema drift: " + "; ".join(changes[:8]), "high")
|
|
350
|
+
return _pass("schema.snapshot", f"no drift against {snapshot_path}")
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _write_snapshot(path: str, payload: Dict[str, Any]) -> None:
|
|
354
|
+
with open(path, "w", encoding="utf-8") as handle:
|
|
355
|
+
json.dump(payload, handle, indent=2, sort_keys=True, ensure_ascii=False)
|
|
356
|
+
handle.write("\n")
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
# --------------------------------------------------------------------------
|
|
360
|
+
# registry
|
|
361
|
+
|
|
362
|
+
CHECK_ORDER = [
|
|
363
|
+
"handshake",
|
|
364
|
+
"tools.list",
|
|
365
|
+
"tools.schema",
|
|
366
|
+
"tools.unknown",
|
|
367
|
+
"resources.list",
|
|
368
|
+
"prompts.list",
|
|
369
|
+
"stdout.hygiene",
|
|
370
|
+
"errors.recovery",
|
|
371
|
+
"latency",
|
|
372
|
+
]
|
|
373
|
+
|
|
374
|
+
CHECK_FUNCTIONS = {
|
|
375
|
+
"handshake": check_handshake,
|
|
376
|
+
"tools.list": check_tools_list,
|
|
377
|
+
"tools.schema": check_tool_schemas,
|
|
378
|
+
"tools.unknown": check_unknown_tool,
|
|
379
|
+
"resources.list": check_resources,
|
|
380
|
+
"prompts.list": check_prompts,
|
|
381
|
+
"stdout.hygiene": check_stdout_hygiene,
|
|
382
|
+
"errors.recovery": check_survives_bad_request,
|
|
383
|
+
"latency": check_latency,
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def run_checks(ctx: Context, only: Optional[List[str]] = None) -> List[Result]:
|
|
388
|
+
"""Runs the suite in order. `only` keeps the listed checks (snapshot excluded)."""
|
|
389
|
+
if only:
|
|
390
|
+
unknown = [name for name in only if name not in CHECK_FUNCTIONS]
|
|
391
|
+
if unknown:
|
|
392
|
+
raise ValueError(f"unknown check(s): {', '.join(unknown)}; run `mcpsheriff list-checks`")
|
|
393
|
+
results: List[Result] = []
|
|
394
|
+
for name in CHECK_ORDER:
|
|
395
|
+
if only and name not in only:
|
|
396
|
+
continue
|
|
397
|
+
function = CHECK_FUNCTIONS[name]
|
|
398
|
+
try:
|
|
399
|
+
results.append(function(ctx))
|
|
400
|
+
except Exception as error: # noqa: BLE001 - a check must never kill the run
|
|
401
|
+
results.append(_fail(name, f"check crashed: {type(error).__name__}: {error}", "critical"))
|
|
402
|
+
return results
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def initialize(session: Session, timeout: float = 10.0, client_version: str = "0.1.0") -> None:
|
|
406
|
+
"""Performs the MCP handshake and stores the negotiated values on the session."""
|
|
407
|
+
response = session.request(
|
|
408
|
+
"initialize",
|
|
409
|
+
{
|
|
410
|
+
"protocolVersion": PROTOCOL_VERSION,
|
|
411
|
+
"capabilities": {},
|
|
412
|
+
"clientInfo": {"name": "mcpsheriff", "version": client_version},
|
|
413
|
+
},
|
|
414
|
+
timeout=timeout,
|
|
415
|
+
)
|
|
416
|
+
session.protocol_version = str(response.get("protocolVersion") or "")
|
|
417
|
+
session.capabilities = response.get("capabilities") or {}
|
|
418
|
+
session.server_info = response.get("serverInfo") or {}
|
|
419
|
+
session.instructions = str(response.get("instructions") or "")
|
|
420
|
+
session.notify("notifications/initialized")
|
mcpsheriff/cli.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Command line interface.
|
|
2
|
+
|
|
3
|
+
mcpsheriff run -- npx -y @normahub/mcp-server
|
|
4
|
+
mcpsheriff run --http https://example.com/mcp
|
|
5
|
+
mcpsheriff run -- npx -y @normahub/mcp-server --snapshot mcp.snapshot.json
|
|
6
|
+
mcpsheriff list-checks
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import sys
|
|
13
|
+
from typing import List, Optional, Sequence
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .checks import CHECK_ORDER, Context, check_snapshot, initialize, run_checks
|
|
17
|
+
from .protocol import HttpSession, ProtocolError, StdioSession
|
|
18
|
+
from .report import render_table, summary, summary_line, write_json, write_junit
|
|
19
|
+
|
|
20
|
+
EXIT_OK = 0
|
|
21
|
+
EXIT_FAIL = 1
|
|
22
|
+
EXIT_ERROR = 2
|
|
23
|
+
|
|
24
|
+
USAGE = """mcpsheriff — test any MCP server
|
|
25
|
+
|
|
26
|
+
mcpsheriff run -- <command> [args...] run checks against a stdio server
|
|
27
|
+
mcpsheriff run --http <url> run checks against a Streamable HTTP server
|
|
28
|
+
mcpsheriff list-checks show check names and order
|
|
29
|
+
mcpsheriff version print version
|
|
30
|
+
|
|
31
|
+
Run options:
|
|
32
|
+
--timeout SECONDS reply timeout per request (default: 30)
|
|
33
|
+
--latency-budget-ms MS budget for tools/list (default: 5000)
|
|
34
|
+
--only a,b,c run only the listed checks
|
|
35
|
+
--snapshot FILE compare schemas against a saved snapshot
|
|
36
|
+
--update-snapshot write/refresh the snapshot and pass
|
|
37
|
+
--json FILE write machine-readable results
|
|
38
|
+
--junit FILE write JUnit XML for CI
|
|
39
|
+
--quiet do not print the per-check table
|
|
40
|
+
|
|
41
|
+
Exit codes: 0 all checks passed, 1 at least one failed, 2 could not run the server.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
46
|
+
parser = argparse.ArgumentParser(prog="mcpsheriff", add_help=False)
|
|
47
|
+
parser.add_argument("--http", metavar="URL")
|
|
48
|
+
parser.add_argument("--timeout", type=float, default=30.0)
|
|
49
|
+
parser.add_argument("--latency-budget-ms", type=int, default=5000)
|
|
50
|
+
parser.add_argument("--only", default=None)
|
|
51
|
+
parser.add_argument("--snapshot", default=None)
|
|
52
|
+
parser.add_argument("--update-snapshot", action="store_true")
|
|
53
|
+
parser.add_argument("--json", dest="json_path", default=None)
|
|
54
|
+
parser.add_argument("--junit", dest="junit_path", default=None)
|
|
55
|
+
parser.add_argument("--quiet", action="store_true")
|
|
56
|
+
return parser
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _split_args(argv: Sequence[str]) -> tuple:
|
|
60
|
+
"""Everything before `--` is ours, everything after belongs to the server."""
|
|
61
|
+
if "--" in argv:
|
|
62
|
+
index = argv.index("--")
|
|
63
|
+
return list(argv[:index]), list(argv[index + 1 :])
|
|
64
|
+
return list(argv), []
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _print_results(results: List, quiet: bool, json_path: Optional[str], junit_path: Optional[str]) -> int:
|
|
68
|
+
if not quiet:
|
|
69
|
+
print(render_table(results))
|
|
70
|
+
print()
|
|
71
|
+
print(summary_line(results))
|
|
72
|
+
|
|
73
|
+
stats = summary(results)
|
|
74
|
+
if json_path:
|
|
75
|
+
write_json(results, json_path)
|
|
76
|
+
print(f"json: {json_path}")
|
|
77
|
+
if junit_path:
|
|
78
|
+
write_junit(results, junit_path)
|
|
79
|
+
print(f"junit: {junit_path}")
|
|
80
|
+
return EXIT_FAIL if stats["failed"] else EXIT_OK
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _run(argv: Sequence[str], parser: argparse.ArgumentParser) -> int:
|
|
84
|
+
options, command = _split_args(argv)
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
args = parser.parse_args(options)
|
|
88
|
+
except SystemExit:
|
|
89
|
+
print(USAGE, file=sys.stderr)
|
|
90
|
+
return EXIT_ERROR
|
|
91
|
+
|
|
92
|
+
if bool(args.http) == bool(command):
|
|
93
|
+
print("error: pass either `-- <command>` or `--http <url>`, not both/neither.", file=sys.stderr)
|
|
94
|
+
print(USAGE, file=sys.stderr)
|
|
95
|
+
return EXIT_ERROR
|
|
96
|
+
|
|
97
|
+
only = None
|
|
98
|
+
if args.only:
|
|
99
|
+
only = [name.strip() for name in args.only.split(",") if name.strip()]
|
|
100
|
+
unknown = [name for name in only if name not in CHECK_ORDER]
|
|
101
|
+
if unknown:
|
|
102
|
+
print(f"error: unknown check(s): {', '.join(unknown)}", file=sys.stderr)
|
|
103
|
+
print(f"available: {', '.join(CHECK_ORDER)}", file=sys.stderr)
|
|
104
|
+
return EXIT_ERROR
|
|
105
|
+
|
|
106
|
+
session = None
|
|
107
|
+
try:
|
|
108
|
+
if args.http:
|
|
109
|
+
session = HttpSession(args.http, timeout=args.timeout)
|
|
110
|
+
else:
|
|
111
|
+
session = StdioSession(command)
|
|
112
|
+
session.start()
|
|
113
|
+
|
|
114
|
+
initialize(session, timeout=args.timeout, client_version=__version__)
|
|
115
|
+
context = Context(
|
|
116
|
+
session=session,
|
|
117
|
+
timeout=args.timeout,
|
|
118
|
+
latency_budget_ms=args.latency_budget_ms,
|
|
119
|
+
)
|
|
120
|
+
results = run_checks(context, only=only)
|
|
121
|
+
|
|
122
|
+
if args.snapshot:
|
|
123
|
+
snapshot_result = check_snapshot(context, args.snapshot, update=args.update_snapshot)
|
|
124
|
+
if snapshot_result is not None:
|
|
125
|
+
results.append(snapshot_result)
|
|
126
|
+
|
|
127
|
+
return _print_results(results, args.quiet, args.json_path, args.junit_path)
|
|
128
|
+
|
|
129
|
+
except ProtocolError as error:
|
|
130
|
+
print(f"error: {error}", file=sys.stderr)
|
|
131
|
+
if session is not None:
|
|
132
|
+
tail = session.stderr_tail()
|
|
133
|
+
if tail:
|
|
134
|
+
print("--- server stderr (tail) ---", file=sys.stderr)
|
|
135
|
+
print(tail, file=sys.stderr)
|
|
136
|
+
return EXIT_ERROR
|
|
137
|
+
finally:
|
|
138
|
+
if session is not None:
|
|
139
|
+
try:
|
|
140
|
+
session.close()
|
|
141
|
+
except Exception: # noqa: BLE001 - closing must never mask the result
|
|
142
|
+
pass
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
146
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
147
|
+
|
|
148
|
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
|
149
|
+
print(USAGE)
|
|
150
|
+
return EXIT_OK
|
|
151
|
+
|
|
152
|
+
command, rest = argv[0], argv[1:]
|
|
153
|
+
|
|
154
|
+
if command == "version" or command == "--version":
|
|
155
|
+
print(f"mcpsheriff {__version__}")
|
|
156
|
+
return EXIT_OK
|
|
157
|
+
|
|
158
|
+
if command == "list-checks":
|
|
159
|
+
for index, name in enumerate(CHECK_ORDER, 1):
|
|
160
|
+
print(f"{index:2}. {name}")
|
|
161
|
+
return EXIT_OK
|
|
162
|
+
|
|
163
|
+
if command == "run":
|
|
164
|
+
return _run(rest, _build_parser())
|
|
165
|
+
|
|
166
|
+
print(f"error: unknown command '{command}'", file=sys.stderr)
|
|
167
|
+
print(USAGE, file=sys.stderr)
|
|
168
|
+
return EXIT_ERROR
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
if __name__ == "__main__":
|
|
172
|
+
raise SystemExit(main())
|
mcpsheriff/protocol.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Minimal JSON-RPC clients for MCP: stdio subprocess and Streamable HTTP.
|
|
2
|
+
|
|
3
|
+
Deliberately stdlib-only. The tool has to work on a clean machine right after
|
|
4
|
+
`pip install mcpsheriff`, and a broken MCP server must not be able to crash or
|
|
5
|
+
hang the checker.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import queue
|
|
12
|
+
import subprocess
|
|
13
|
+
import threading
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any, Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
PROTOCOL_VERSION = "2025-06-18"
|
|
18
|
+
KNOWN_VERSIONS = ("2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25")
|
|
19
|
+
|
|
20
|
+
STDERR_LIMIT = 8192
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ProtocolError(RuntimeError):
|
|
24
|
+
"""Transport-level failure: process died, timeout, unparsable reply."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class RpcError(ProtocolError):
|
|
28
|
+
def __init__(self, method: str, error: Dict[str, Any]) -> None:
|
|
29
|
+
self.error = error
|
|
30
|
+
super().__init__(f"{method} returned JSON-RPC error {error.get('code')}: {error.get('message')}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Session:
|
|
35
|
+
"""What a check needs from a transport."""
|
|
36
|
+
|
|
37
|
+
noise: List[str] = field(default_factory=list)
|
|
38
|
+
stderr: List[str] = field(default_factory=list)
|
|
39
|
+
server_info: Dict[str, Any] = field(default_factory=dict)
|
|
40
|
+
capabilities: Dict[str, Any] = field(default_factory=dict)
|
|
41
|
+
protocol_version: str = ""
|
|
42
|
+
instructions: str = ""
|
|
43
|
+
|
|
44
|
+
def request(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: float = 10.0) -> Dict[str, Any]:
|
|
45
|
+
raise NotImplementedError
|
|
46
|
+
|
|
47
|
+
def notify(self, method: str, params: Optional[Dict[str, Any]] = None) -> None:
|
|
48
|
+
raise NotImplementedError
|
|
49
|
+
|
|
50
|
+
def close(self) -> None:
|
|
51
|
+
raise NotImplementedError
|
|
52
|
+
|
|
53
|
+
def stderr_tail(self) -> str:
|
|
54
|
+
return "".join(self.stderr)[-2000:]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class StdioSession(Session):
|
|
58
|
+
def __init__(self, command: List[str], env: Optional[Dict[str, str]] = None) -> None:
|
|
59
|
+
super().__init__()
|
|
60
|
+
self.command = command
|
|
61
|
+
self.env = env
|
|
62
|
+
self._process: Optional[subprocess.Popen] = None
|
|
63
|
+
self._pending: Dict[int, "queue.Queue[Dict[str, Any]]"] = {}
|
|
64
|
+
self._lock = threading.Lock()
|
|
65
|
+
self._next_id = 0
|
|
66
|
+
self._reader: Optional[threading.Thread] = None
|
|
67
|
+
self._stderr_reader: Optional[threading.Thread] = None
|
|
68
|
+
|
|
69
|
+
def start(self) -> None:
|
|
70
|
+
try:
|
|
71
|
+
self._process = subprocess.Popen(
|
|
72
|
+
self.command,
|
|
73
|
+
stdin=subprocess.PIPE,
|
|
74
|
+
stdout=subprocess.PIPE,
|
|
75
|
+
stderr=subprocess.PIPE,
|
|
76
|
+
text=True,
|
|
77
|
+
encoding="utf-8",
|
|
78
|
+
errors="replace",
|
|
79
|
+
bufsize=1,
|
|
80
|
+
env=self.env,
|
|
81
|
+
)
|
|
82
|
+
except FileNotFoundError as error:
|
|
83
|
+
raise ProtocolError(f"command not found: {self.command[0]}") from error
|
|
84
|
+
|
|
85
|
+
self._reader = threading.Thread(target=self._read_stdout, daemon=True)
|
|
86
|
+
self._reader.start()
|
|
87
|
+
self._stderr_reader = threading.Thread(target=self._read_stderr, daemon=True)
|
|
88
|
+
self._stderr_reader.start()
|
|
89
|
+
|
|
90
|
+
def _read_stdout(self) -> None:
|
|
91
|
+
assert self._process and self._process.stdout
|
|
92
|
+
for raw in self._process.stdout:
|
|
93
|
+
line = raw.strip()
|
|
94
|
+
if not line:
|
|
95
|
+
continue
|
|
96
|
+
try:
|
|
97
|
+
message = json.loads(line)
|
|
98
|
+
except json.JSONDecodeError:
|
|
99
|
+
# Protocol violation: anything on stdout must be JSON-RPC.
|
|
100
|
+
self.noise.append(line[:400])
|
|
101
|
+
continue
|
|
102
|
+
if not isinstance(message, dict):
|
|
103
|
+
self.noise.append(line[:400])
|
|
104
|
+
continue
|
|
105
|
+
message_id = message.get("id")
|
|
106
|
+
if message_id is None:
|
|
107
|
+
continue
|
|
108
|
+
inbox = self._pending.pop(message_id, None)
|
|
109
|
+
if inbox is not None:
|
|
110
|
+
inbox.put(message)
|
|
111
|
+
|
|
112
|
+
def _read_stderr(self) -> None:
|
|
113
|
+
assert self._process and self._process.stderr
|
|
114
|
+
total = 0
|
|
115
|
+
for raw in self._process.stderr:
|
|
116
|
+
if total < STDERR_LIMIT:
|
|
117
|
+
self.stderr.append(raw)
|
|
118
|
+
total += len(raw)
|
|
119
|
+
|
|
120
|
+
def request(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: float = 10.0) -> Dict[str, Any]:
|
|
121
|
+
if self._process is None or self._process.poll() is not None:
|
|
122
|
+
exit_code = self._process.poll() if self._process else "?"
|
|
123
|
+
raise ProtocolError(f"server exited before '{method}' (exit code {exit_code})")
|
|
124
|
+
|
|
125
|
+
with self._lock:
|
|
126
|
+
self._next_id += 1
|
|
127
|
+
request_id = self._next_id
|
|
128
|
+
inbox: "queue.Queue[Dict[str, Any]]" = queue.Queue(maxsize=1)
|
|
129
|
+
self._pending[request_id] = inbox
|
|
130
|
+
payload: Dict[str, Any] = {"jsonrpc": "2.0", "id": request_id, "method": method}
|
|
131
|
+
if params is not None:
|
|
132
|
+
payload["params"] = params
|
|
133
|
+
|
|
134
|
+
assert self._process.stdin
|
|
135
|
+
try:
|
|
136
|
+
self._process.stdin.write(json.dumps(payload) + "\n")
|
|
137
|
+
self._process.stdin.flush()
|
|
138
|
+
except (BrokenPipeError, ValueError) as error:
|
|
139
|
+
self._pending.pop(request_id, None)
|
|
140
|
+
raise ProtocolError(f"server closed stdin during '{method}'") from error
|
|
141
|
+
|
|
142
|
+
try:
|
|
143
|
+
message = inbox.get(timeout=timeout)
|
|
144
|
+
except queue.Empty:
|
|
145
|
+
self._pending.pop(request_id, None)
|
|
146
|
+
raise ProtocolError(f"no reply to '{method}' within {timeout:g}s") from None
|
|
147
|
+
|
|
148
|
+
if "error" in message:
|
|
149
|
+
raise RpcError(method, message["error"])
|
|
150
|
+
result = message.get("result")
|
|
151
|
+
return result if isinstance(result, dict) else {"value": result}
|
|
152
|
+
|
|
153
|
+
def notify(self, method: str, params: Optional[Dict[str, Any]] = None) -> None:
|
|
154
|
+
if self._process is None or self._process.stdin is None:
|
|
155
|
+
raise ProtocolError("server is not running")
|
|
156
|
+
payload: Dict[str, Any] = {"jsonrpc": "2.0", "method": method}
|
|
157
|
+
if params is not None:
|
|
158
|
+
payload["params"] = params
|
|
159
|
+
self._process.stdin.write(json.dumps(payload) + "\n")
|
|
160
|
+
self._process.stdin.flush()
|
|
161
|
+
|
|
162
|
+
def close(self) -> None:
|
|
163
|
+
if self._process is None:
|
|
164
|
+
return
|
|
165
|
+
try:
|
|
166
|
+
if self._process.stdin:
|
|
167
|
+
self._process.stdin.close()
|
|
168
|
+
except OSError:
|
|
169
|
+
pass
|
|
170
|
+
try:
|
|
171
|
+
self._process.wait(timeout=2)
|
|
172
|
+
except subprocess.TimeoutExpired:
|
|
173
|
+
self._process.kill()
|
|
174
|
+
try:
|
|
175
|
+
self._process.wait(timeout=2)
|
|
176
|
+
except subprocess.TimeoutExpired:
|
|
177
|
+
pass
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class HttpSession(Session):
|
|
181
|
+
"""Streamable HTTP transport: one POST per JSON-RPC message."""
|
|
182
|
+
|
|
183
|
+
def __init__(self, url: str, timeout: float = 10.0) -> None:
|
|
184
|
+
super().__init__()
|
|
185
|
+
self.url = url
|
|
186
|
+
self.timeout = timeout
|
|
187
|
+
self.session_id: Optional[str] = None
|
|
188
|
+
self._next_id = 0
|
|
189
|
+
|
|
190
|
+
def _post(self, payload: Dict[str, Any], expect_reply: bool = True) -> Optional[Dict[str, Any]]:
|
|
191
|
+
import urllib.error
|
|
192
|
+
import urllib.request
|
|
193
|
+
|
|
194
|
+
headers = {
|
|
195
|
+
"Content-Type": "application/json",
|
|
196
|
+
"Accept": "application/json, text/event-stream",
|
|
197
|
+
"User-Agent": "mcpsheriff",
|
|
198
|
+
}
|
|
199
|
+
if self.session_id:
|
|
200
|
+
headers["Mcp-Session-Id"] = self.session_id
|
|
201
|
+
|
|
202
|
+
request = urllib.request.Request(
|
|
203
|
+
self.url, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST"
|
|
204
|
+
)
|
|
205
|
+
try:
|
|
206
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
207
|
+
session_id = response.headers.get("Mcp-Session-Id")
|
|
208
|
+
if session_id:
|
|
209
|
+
self.session_id = session_id
|
|
210
|
+
content_type = response.headers.get("Content-Type", "")
|
|
211
|
+
body = response.read().decode("utf-8", "replace")
|
|
212
|
+
except urllib.error.HTTPError as error:
|
|
213
|
+
body = error.read().decode("utf-8", "replace")
|
|
214
|
+
raise ProtocolError(f"HTTP {error.code} from {self.url}: {body[:300]}") from error
|
|
215
|
+
except Exception as error: # noqa: BLE001 - network stack
|
|
216
|
+
raise ProtocolError(f"cannot reach {self.url}: {type(error).__name__}: {error}") from error
|
|
217
|
+
|
|
218
|
+
if not expect_reply:
|
|
219
|
+
return None
|
|
220
|
+
if "text/event-stream" in content_type:
|
|
221
|
+
return self._parse_sse(body, payload.get("id"))
|
|
222
|
+
try:
|
|
223
|
+
return json.loads(body) if body.strip() else None
|
|
224
|
+
except json.JSONDecodeError as error:
|
|
225
|
+
raise ProtocolError(f"response is not JSON and not SSE: {body[:200]}") from error
|
|
226
|
+
|
|
227
|
+
def _parse_sse(self, body: str, request_id: Any) -> Dict[str, Any]:
|
|
228
|
+
data_lines: List[str] = []
|
|
229
|
+
for line in body.splitlines():
|
|
230
|
+
if line.startswith("data:"):
|
|
231
|
+
data_lines.append(line[5:].strip())
|
|
232
|
+
continue
|
|
233
|
+
if line.strip() == "" and data_lines:
|
|
234
|
+
message = self._decode("".join(data_lines), request_id)
|
|
235
|
+
if message is not None:
|
|
236
|
+
return message
|
|
237
|
+
data_lines = []
|
|
238
|
+
if data_lines:
|
|
239
|
+
message = self._decode("".join(data_lines), request_id)
|
|
240
|
+
if message is not None:
|
|
241
|
+
return message
|
|
242
|
+
raise ProtocolError("SSE stream ended without a JSON-RPC response")
|
|
243
|
+
|
|
244
|
+
@staticmethod
|
|
245
|
+
def _decode(raw: str, request_id: Any) -> Optional[Dict[str, Any]]:
|
|
246
|
+
try:
|
|
247
|
+
message = json.loads(raw)
|
|
248
|
+
except json.JSONDecodeError:
|
|
249
|
+
return None
|
|
250
|
+
if isinstance(message, dict) and message.get("id") == request_id:
|
|
251
|
+
return message
|
|
252
|
+
return None
|
|
253
|
+
|
|
254
|
+
def request(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: float = 10.0) -> Dict[str, Any]:
|
|
255
|
+
self.timeout = timeout
|
|
256
|
+
self._next_id += 1
|
|
257
|
+
payload: Dict[str, Any] = {"jsonrpc": "2.0", "id": self._next_id, "method": method}
|
|
258
|
+
if params is not None:
|
|
259
|
+
payload["params"] = params
|
|
260
|
+
message = self._post(payload)
|
|
261
|
+
if message is None:
|
|
262
|
+
raise ProtocolError(f"empty reply to '{method}'")
|
|
263
|
+
if "error" in message:
|
|
264
|
+
raise RpcError(method, message["error"])
|
|
265
|
+
result = message.get("result")
|
|
266
|
+
return result if isinstance(result, dict) else {"value": result}
|
|
267
|
+
|
|
268
|
+
def notify(self, method: str, params: Optional[Dict[str, Any]] = None) -> None:
|
|
269
|
+
payload: Dict[str, Any] = {"jsonrpc": "2.0", "method": method}
|
|
270
|
+
if params is not None:
|
|
271
|
+
payload["params"] = params
|
|
272
|
+
self._post(payload, expect_reply=False)
|
|
273
|
+
|
|
274
|
+
def close(self) -> None:
|
|
275
|
+
"""Best effort: tell the server the session is over (DELETE is optional in the spec)."""
|
|
276
|
+
if not self.session_id:
|
|
277
|
+
return
|
|
278
|
+
import urllib.request
|
|
279
|
+
|
|
280
|
+
try:
|
|
281
|
+
request = urllib.request.Request(
|
|
282
|
+
self.url,
|
|
283
|
+
headers={"Mcp-Session-Id": self.session_id, "User-Agent": "mcpsheriff"},
|
|
284
|
+
method="DELETE",
|
|
285
|
+
)
|
|
286
|
+
urllib.request.urlopen(request, timeout=2).close()
|
|
287
|
+
except Exception: # noqa: BLE001 - optional cleanup
|
|
288
|
+
return
|
mcpsheriff/report.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Reporters: human table, JSON and JUnit XML.
|
|
2
|
+
|
|
3
|
+
The JUnit output is what makes mcpsheriff usable as a CI gate without extra glue:
|
|
4
|
+
GitHub Actions, GitLab and Jenkins all read JUnit XML natively.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import xml.etree.ElementTree as ET
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Iterable, List
|
|
13
|
+
|
|
14
|
+
from .checks import Result
|
|
15
|
+
|
|
16
|
+
_WIDTH = 22
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def summary(results: Iterable[Result]) -> dict:
|
|
20
|
+
results = list(results)
|
|
21
|
+
failed = [r for r in results if not r.ok and not r.skipped]
|
|
22
|
+
skipped = [r for r in results if r.skipped]
|
|
23
|
+
return {
|
|
24
|
+
"total": len(results),
|
|
25
|
+
"passed": len(results) - len(failed) - len(skipped),
|
|
26
|
+
"failed": len(failed),
|
|
27
|
+
"skipped": len(skipped),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def summary_line(results: Iterable[Result]) -> str:
|
|
32
|
+
stats = summary(results)
|
|
33
|
+
return (
|
|
34
|
+
f"{stats['passed']} passed, {stats['failed']} failed, "
|
|
35
|
+
f"{stats['skipped']} skipped ({stats['total']} checks)"
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def render_table(results: Iterable[Result]) -> str:
|
|
40
|
+
results = list(results)
|
|
41
|
+
lines: List[str] = []
|
|
42
|
+
for result in results:
|
|
43
|
+
marker = {"pass": "PASS", "FAIL": "FAIL", "skip": "SKIP"}[result.status]
|
|
44
|
+
lines.append(f"{marker} {result.name.ljust(_WIDTH)} {result.detail}".rstrip())
|
|
45
|
+
return "\n".join(lines)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def write_json(results: Iterable[Result], path: str) -> None:
|
|
49
|
+
payload = {
|
|
50
|
+
"summary": summary(results := list(results)),
|
|
51
|
+
"checks": [
|
|
52
|
+
{
|
|
53
|
+
"name": r.name,
|
|
54
|
+
"status": r.status,
|
|
55
|
+
"severity": r.severity,
|
|
56
|
+
"detail": r.detail,
|
|
57
|
+
}
|
|
58
|
+
for r in results
|
|
59
|
+
],
|
|
60
|
+
}
|
|
61
|
+
Path(path).write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def write_junit(results: Iterable[Result], path: str, suite_name: str = "mcpsheriff") -> None:
|
|
65
|
+
results = list(results)
|
|
66
|
+
stats = summary(results)
|
|
67
|
+
suite = ET.Element(
|
|
68
|
+
"testsuite",
|
|
69
|
+
{
|
|
70
|
+
"name": suite_name,
|
|
71
|
+
"tests": str(stats["total"]),
|
|
72
|
+
"failures": str(stats["failed"]),
|
|
73
|
+
"errors": "0",
|
|
74
|
+
"skipped": str(stats["skipped"]),
|
|
75
|
+
},
|
|
76
|
+
)
|
|
77
|
+
for result in results:
|
|
78
|
+
case = ET.SubElement(
|
|
79
|
+
suite,
|
|
80
|
+
"testcase",
|
|
81
|
+
{"classname": "mcpsheriff", "name": result.name},
|
|
82
|
+
)
|
|
83
|
+
if result.skipped:
|
|
84
|
+
ET.SubElement(case, "skipped", {"message": result.detail or "not applicable"})
|
|
85
|
+
elif not result.ok:
|
|
86
|
+
failure = ET.SubElement(
|
|
87
|
+
case,
|
|
88
|
+
"failure",
|
|
89
|
+
{"message": result.detail or "check failed", "type": result.severity},
|
|
90
|
+
)
|
|
91
|
+
failure.text = f"{result.name} failed ({result.severity}): {result.detail}"
|
|
92
|
+
tree = ET.ElementTree(suite)
|
|
93
|
+
tree.write(path, encoding="utf-8", xml_declaration=True)
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mcpsheriff
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Test any MCP server: handshake, tools, schemas, stdout hygiene and schema drift, from one command
|
|
5
|
+
Author-email: NormaHub <manager@normahub.cc>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://normahub.cc
|
|
8
|
+
Project-URL: Documentation, https://normahub.cc/docs
|
|
9
|
+
Project-URL: Repository, https://github.com/normahubcc/mcpsheriff
|
|
10
|
+
Project-URL: Issues, https://github.com/normahubcc/mcpsheriff/issues
|
|
11
|
+
Keywords: mcp,model-context-protocol,testing,ci,junit,json-rpc,ai-agents
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
22
|
+
Classifier: Topic :: Software Development :: Testing
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
27
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
28
|
+
|
|
29
|
+
# mcpsheriff
|
|
30
|
+
|
|
31
|
+
Проверка MCP-сервера одной командой: рукопожатие, инструменты, схемы, чистота
|
|
32
|
+
stdout, выживание после плохого запроса и дрейф схем между релизами.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install mcpsheriff
|
|
36
|
+
mcpsheriff run -- npx -y @normahub/mcp-server
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
PASS handshake protocol 2025-06-18, server io.github.normahubcc/mcp-server-normahub 0.2.6
|
|
41
|
+
PASS tools.list 8 tools, names and schemas valid
|
|
42
|
+
PASS tools.schema every required field exists in properties
|
|
43
|
+
PASS tools.unknown unknown tool rejected without crashing the server
|
|
44
|
+
PASS resources.list 2 resources
|
|
45
|
+
PASS prompts.list 3 prompts
|
|
46
|
+
PASS stdout.hygiene stdout carried only JSON-RPC
|
|
47
|
+
PASS errors.recovery server answered ping after an unknown method
|
|
48
|
+
PASS latency tools/list answered in 41 ms
|
|
49
|
+
9 passed, 0 failed, 0 skipped (9 checks)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Зачем
|
|
53
|
+
|
|
54
|
+
MCP-сервер легко «работает» у автора и падает у пользователя: библиотека печатает
|
|
55
|
+
баннер в stdout и ломает протокол, схема инструмента объявляет обязательное поле,
|
|
56
|
+
которого нет в `properties`, неизвестный вызов убивает процесс, а между релизами
|
|
57
|
+
незаметно меняется контракт. Все эти поломки видны только тем, кто подключил
|
|
58
|
+
сервер к клиенту. `mcpsheriff` воспроизводит их до публикации.
|
|
59
|
+
|
|
60
|
+
## Что проверяется
|
|
61
|
+
|
|
62
|
+
| Проверка | Что ловит |
|
|
63
|
+
|---|---|
|
|
64
|
+
| `handshake` | нет `protocolVersion`, `serverInfo`, capabilities; версия вне известных |
|
|
65
|
+
| `tools.list` | имя не по `^[a-z0-9_-]{1,64}$`, дубликаты, пустое описание, `inputSchema` без `type: object` |
|
|
66
|
+
| `tools.schema` | `required` содержит поле, которого нет в `properties`; property без типа |
|
|
67
|
+
| `tools.unknown` | вызов несуществующего инструмента роняет сервер вместо `isError` |
|
|
68
|
+
| `resources.list` | capability заявлена, а список пуст или записи без `uri`/`name` |
|
|
69
|
+
| `prompts.list` | то же для промптов |
|
|
70
|
+
| `stdout.hygiene` | в stdout попал `print`/`console.log` — протокол сломан |
|
|
71
|
+
| `errors.recovery` | после неизвестного метода сервер больше не отвечает на `ping` |
|
|
72
|
+
| `latency` | `tools/list` дольше бюджета (по умолчанию 5 с, информационно) |
|
|
73
|
+
|
|
74
|
+
Проверки `resources.list` и `prompts.list` пропускаются, если сервер не объявил
|
|
75
|
+
соответствующую capability: отсутствие функции — не дефект.
|
|
76
|
+
|
|
77
|
+
## Транспорты
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
# локальный процесс, общение по stdin/stdout
|
|
81
|
+
mcpsheriff run -- python my_server.py
|
|
82
|
+
mcpsheriff run -- npx -y @normahub/mcp-server
|
|
83
|
+
|
|
84
|
+
# удалённый сервер по Streamable HTTP (POST JSON-RPC, ответ может быть SSE)
|
|
85
|
+
mcpsheriff run --http https://example.com/mcp
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Ключи и прочие переменные передаются обычным окружением:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
NORMAHUB_API_KEY=... mcpsheriff run -- npx -y @normahub/mcp-server
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Дрейф схем
|
|
95
|
+
|
|
96
|
+
Закрепите контракт инструментов и проверяйте его в CI:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
mcpsheriff run --snapshot mcp-schema.json -- npx -y @normahub/mcp-server # первый раз
|
|
100
|
+
mcpsheriff run --snapshot mcp-schema.json -- npx -y @normahub/mcp-server # дальше — падает при изменениях
|
|
101
|
+
mcpsheriff run --snapshot mcp-schema.json --update-snapshot -- npx -y @normahub/mcp-server # осознанно принять
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Изменение описания, схемы, набора инструментов или версии протокола — это
|
|
105
|
+
изменение публичного контракта. Теперь оно не проходит молча.
|
|
106
|
+
|
|
107
|
+
## Отчёты
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
mcpsheriff run --json report.json --junit report.xml -- npx -y @normahub/mcp-server
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`--junit` даёт XML, который понимают GitHub Actions, GitLab, Jenkins и `pytest`-отчёты.
|
|
114
|
+
`--json` — машинный формат для своих пайплайнов.
|
|
115
|
+
|
|
116
|
+
Коды возврата: `0` — всё прошло, `1` — есть провалы, `2` — сервер не запустился
|
|
117
|
+
или ответил не по протоколу.
|
|
118
|
+
|
|
119
|
+
## В CI
|
|
120
|
+
|
|
121
|
+
```yaml
|
|
122
|
+
- uses: actions/setup-python@v5
|
|
123
|
+
with:
|
|
124
|
+
python-version: '3.12'
|
|
125
|
+
- run: pip install mcpsheriff
|
|
126
|
+
- run: mcpsheriff run --junit mcpsheriff.xml -- npx -y @normahub/mcp-server
|
|
127
|
+
env:
|
|
128
|
+
NORMAHUB_API_KEY: ${{ secrets.NORMAHUB_API_KEY }}
|
|
129
|
+
- if: always()
|
|
130
|
+
uses: actions/upload-artifact@v4
|
|
131
|
+
with:
|
|
132
|
+
name: mcpsheriff-report
|
|
133
|
+
path: mcpsheriff.xml
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Ограничения
|
|
137
|
+
|
|
138
|
+
- Проверяются объявленные интерфейсы, а не качество ответов модели. Доменные
|
|
139
|
+
ошибки в бизнес-логике инструмента `mcpsheriff` не ищет.
|
|
140
|
+
- `tools.unknown` считает корректным и `isError: true`, и JSON-RPC error: оба
|
|
141
|
+
варианта допустимы спецификацией.
|
|
142
|
+
- HTTP-транспорт рассчитан на Streamable HTTP. Устаревший HTTP+SSE (раздельные
|
|
143
|
+
`/sse` и `/messages`) не поддерживается — он снят с рекомендаций спецификации.
|
|
144
|
+
- Внешние зависимости не используются: пакет ставится в закрытый контур без сети.
|
|
145
|
+
|
|
146
|
+
## Разработка
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
python -m pip install -e ".[dev]"
|
|
150
|
+
python -m pytest -q # 13 тестов, фиктивные MCP-серверы на stdlib
|
|
151
|
+
ruff check .
|
|
152
|
+
python -m build && twine check dist/*
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Тесты поднимают настоящие процессы-серверы и настоящий HTTP-сервер на
|
|
156
|
+
`127.0.0.1`, поэтому проверяется реальный протокол, а не моки.
|
|
157
|
+
|
|
158
|
+
## Лицензия
|
|
159
|
+
|
|
160
|
+
MIT.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
mcpsheriff/__init__.py,sha256=itvK8DBf0RmMKsCZORlGHdvC071zAykg7rUGsGEcNq8,109
|
|
2
|
+
mcpsheriff/checks.py,sha256=1yMAAfd2xS92LGmUeB1rggRRsR6kqa-hk49CMKEGE7g,16462
|
|
3
|
+
mcpsheriff/cli.py,sha256=Ye4ueZYlI0W8Kp59cxKiNSfTnCWw9uZg2BXfK4aQ66U,5950
|
|
4
|
+
mcpsheriff/protocol.py,sha256=GjjpDDp5tiqrFQFvx9cEJcgM4_shlpqp7Oty6k7ap1k,11071
|
|
5
|
+
mcpsheriff/report.py,sha256=EQt4T2lkSWk9k6Ng0Cn7dzt_dIl7688sRzUz0Sr45lA,2889
|
|
6
|
+
mcpsheriff-0.1.0.dist-info/METADATA,sha256=Xa-nT_7zh0Jmk226zbwAU3TTYlmz2UxZdlPxJkMkoH0,7729
|
|
7
|
+
mcpsheriff-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
mcpsheriff-0.1.0.dist-info/entry_points.txt,sha256=P9GSDlpR6kWOKaPXjNEGugZ6cF-k1OSU2VETpJa8O_0,51
|
|
9
|
+
mcpsheriff-0.1.0.dist-info/top_level.txt,sha256=xHnJ0Bx0Qlh3H2cDA1upOeEfpxiSHqJn-Yzk4Rfaro8,11
|
|
10
|
+
mcpsheriff-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mcpsheriff
|