-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_stdout.py
More file actions
53 lines (45 loc) · 1.63 KB
/
Copy pathvalidate_stdout.py
File metadata and controls
53 lines (45 loc) · 1.63 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
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import TextIO
def validate_stream(handle: TextIO) -> int:
checked = 0
for line_number, raw in enumerate(handle, 1):
text = raw.strip()
if not text:
continue
checked += 1
try:
message = json.loads(text)
except json.JSONDecodeError as exc:
print(
f"FAIL line {line_number}: not valid JSON: {exc.msg}; sample={text[:160]!r}",
file=sys.stderr,
)
return 2
if not isinstance(message, dict):
print(f"FAIL line {line_number}: expected a JSON object, got {type(message).__name__}", file=sys.stderr)
return 3
if message.get("jsonrpc") != "2.0":
print(
f"FAIL line {line_number}: JSON object is not JSON-RPC 2.0; sample={text[:160]!r}",
file=sys.stderr,
)
return 4
print(f"PASS: checked {checked} non-empty stdout line(s); all are JSON-RPC 2.0 objects")
return 0
def main() -> int:
parser = argparse.ArgumentParser(
description="Validate that captured MCP stdio stdout contains only JSON-RPC 2.0 objects."
)
parser.add_argument("path", nargs="?", help="Captured stdout file. Reads stdin when omitted.")
args = parser.parse_args()
if args.path:
with Path(args.path).open("r", encoding="utf-8") as handle:
return validate_stream(handle)
return validate_stream(sys.stdin)
if __name__ == "__main__":
raise SystemExit(main())