-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest-mcp-stdio.py
More file actions
3467 lines (3238 loc) · 144 KB
/
Copy pathtest-mcp-stdio.py
File metadata and controls
3467 lines (3238 loc) · 144 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import collections
import concurrent.futures
import json
import os
import platform
import select
import shutil
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
from mcp_test_util import (
MCP_LEGACY_PROTOCOL_VERSION,
MCP_MODERN_PROTOCOL_VERSION,
MCP_PUBLIC_CACHE_TTL_MS,
fail,
notification_params,
notifications_by_method,
progress_messages,
require,
require_document_progress_range,
save_warning_text,
shared_lib_name,
)
CI_TIMEOUT_TRACKER = "https://github.com/leanprover/lean-beam/issues/110"
CI_TIMEOUT_TRACKER_NOTE = "\n".join(
[
f"Comment on {CI_TIMEOUT_TRACKER} if this scheduler-sensitive timeout hits an unrelated CI PR.",
"Include:",
" - PR URL and branch",
" - failing GitHub Actions run URL and job URL",
" - job name, runner OS/arch, run attempt, and commit SHA",
" - failing test/scenario and this timeout headline",
(
" - MCP stdio pending requests, completed requests, server requests, "
"notifications, event timeline, stderr/server trace or watchdog lines, and process snapshot"
),
" - rerun URL and whether the rerun passed or reproduced",
]
)
def compact_json(value, limit=700):
try:
text = json.dumps(value, separators=(",", ":"), sort_keys=True)
except TypeError:
text = repr(value)
if len(text) <= limit:
return text
return text[: limit - 3] + "..."
def short_value(value, limit=120):
return compact_json(value, limit=limit)
def env_enabled(name):
value = os.environ.get(name)
if value is None:
return False
return value.lower() not in ("", "0", "false", "no", "off")
def copy_project_fixture(source, target):
shutil.copytree(source, target, ignore=shutil.ignore_patterns(".beam"))
def runtime_context_lines():
lines = [
f"platform: {platform.platform()}",
f"machine: {platform.machine()}",
f"python: {platform.python_implementation()} {platform.python_version()}",
f"os.cpu_count: {os.cpu_count()}",
]
if hasattr(os, "sched_getaffinity"):
try:
lines.append(f"sched_getaffinity: {len(os.sched_getaffinity(0))}")
except OSError as err:
lines.append(f"sched_getaffinity: <failed: {err}>")
if hasattr(os, "getloadavg"):
try:
load1, load5, load15 = os.getloadavg()
lines.append(f"loadavg: {load1:.2f} {load5:.2f} {load15:.2f}")
except OSError as err:
lines.append(f"loadavg: <failed: {err}>")
for name in (
"GITHUB_ACTIONS",
"RUNNER_OS",
"RUNNER_ARCH",
"RUNNER_NAME",
"ImageOS",
"LEAN_NUM_THREADS",
"LEAN_OPTIONS",
"BEAM_MCP_STDIO_TIMEOUT",
"BEAM_MCP_SERVER_TRACE",
"LEAN_BEAM_BROKER_WAIT_DIAGNOSTICS_WATCHDOG_MS",
"LEAN_BEAM_MCP_TEST_STATUS_DELAY_MS",
):
lines.append(f"{name}: {os.environ.get(name, '<unset>')}")
return lines
def format_duration_stats(values):
require(values, "cannot format empty duration stats")
ordered = sorted(values)
total = sum(ordered)
return (
f"runs={len(ordered)} "
f"min={ordered[0]:.3f}s "
f"median={ordered[len(ordered) // 2]:.3f}s "
f"max={ordered[-1]:.3f}s "
f"avg={total / len(ordered):.3f}s"
)
def request_label(method, params):
label = method
if method == "tools/call" and isinstance(params, dict):
tool_name = params.get("name")
if isinstance(tool_name, str):
label = f"{method} {tool_name}"
arguments = params.get("arguments")
details = []
if isinstance(arguments, dict):
for key in ("path", "root", "mode"):
if key in arguments:
details.append(f"{key}={short_value(arguments[key], 80)}")
meta = params.get("_meta")
if isinstance(meta, dict) and "progressToken" in meta:
details.append(f"progressToken={short_value(meta['progressToken'], 80)}")
if details:
label = f"{label} ({', '.join(details)})"
return label
def notification_summary(notification):
method = notification.get("method")
params = notification.get("params")
if method == "notifications/progress" and isinstance(params, dict):
return (
f"{method} token={short_value(params.get('progressToken'), 80)} "
f"progress={short_value(params.get('progress'), 40)} "
f"message={short_value(params.get('message'), 180)}"
)
if method == "notifications/message" and isinstance(params, dict):
return (
f"{method} level={short_value(params.get('level'), 40)} "
f"logger={short_value(params.get('logger'), 80)} "
f"data={compact_json(params.get('data'), 240)}"
)
return compact_json(notification, limit=300)
def request_id_key(request_id):
if isinstance(request_id, str):
return ("string", request_id)
if isinstance(request_id, bool) or not isinstance(request_id, int):
fail(f"MCP request id must be a string or integer, got {request_id!r}")
return ("number", request_id)
def with_modern_metadata(params=None, *, log_level=None):
params = dict(params or {})
meta = dict(params.get("_meta") or {})
meta.update(
{
"io.modelcontextprotocol/protocolVersion": MCP_MODERN_PROTOCOL_VERSION,
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {
"name": "lean-beam-mcp-test",
"version": "0",
},
}
)
if log_level is not None:
meta["io.modelcontextprotocol/logLevel"] = log_level
params["_meta"] = meta
return params
class McpClient:
def __init__(
self,
repo_root,
project_root,
timeout,
*,
label="mcp-client",
server_trace=False,
drain_stdout=True,
extra_env=None,
resolve_with_beam_cli=False,
):
self.repo_root = repo_root
self.project_root = project_root
self.timeout = timeout
self.label = label
self.server_trace = server_trace or env_enabled("BEAM_MCP_SERVER_TRACE")
self.runtime_context = runtime_context_lines()
self.state_changed = threading.Condition(threading.RLock())
self.stdin_lock = threading.Lock()
self.next_id = 0
self.server_requests = collections.deque(maxlen=20)
self.pending_requests = {}
self.responses = {}
self.stdout_error = None
self.stdout_eof = False
self.completed_requests = collections.deque(maxlen=20)
self.notifications = []
self.event_log = collections.deque(maxlen=80)
self.started_at = time.monotonic()
self.last_notification_at = None
self.stderr_lines = collections.deque(maxlen=80)
exe = repo_root / ".lake" / "build" / "bin" / "lean-beam-mcp"
require(exe.exists(), f"missing lean-beam-mcp executable at {exe}")
cmd = [str(exe)]
if resolve_with_beam_cli:
beam_cli = repo_root / ".lake" / "build" / "bin" / "beam-cli"
require(beam_cli.exists(), f"missing beam-cli executable at {beam_cli}")
cmd.extend(["--beam-cli", str(beam_cli)])
else:
plugin = repo_root / ".lake" / "build" / "lib" / shared_lib_name()
lean_cmd = shutil.which("lean") or "lean"
require(plugin.exists(), f"missing Beam LSP plugin shared library at {plugin}")
cmd.extend(
[
"--lean-cmd",
lean_cmd,
"--lean-plugin",
str(plugin),
]
)
env = os.environ.copy()
if extra_env is not None:
env.update({str(key): str(value) for key, value in extra_env.items()})
if self.server_trace:
env["LEAN_BEAM_MCP_TRACE"] = "1"
env["LEAN_BEAM_BROKER_TRACE"] = "1"
self.proc = subprocess.Popen(
cmd,
cwd=str(repo_root),
env=env,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
bufsize=1,
)
self.stdout_thread = None
if drain_stdout:
self.stdout_thread = threading.Thread(target=self._drain_stdout, daemon=True)
self.stdout_thread.start()
self.stderr_thread = threading.Thread(target=self._drain_stderr, daemon=True)
self.stderr_thread.start()
self._record_event(f"process started pid={self.proc.pid}")
def _drain_stdout(self):
try:
for line in self.proc.stdout:
try:
message = json.loads(line)
except json.JSONDecodeError as err:
raise RuntimeError(f"stdout line is not valid JSON: {err}: {line!r}") from err
require(message.get("jsonrpc") == "2.0", f"bad JSON-RPC message: {message}")
if "method" in message and "id" in message:
self.handle_server_request(message)
continue
with self.state_changed:
if "method" in message:
self.last_notification_at = time.monotonic()
self.notifications.append(message)
self._record_event_locked(
f"server notification: {notification_summary(message)}"
)
else:
response_id = message.get("id")
response_key = request_id_key(response_id)
require(
response_key in self.pending_requests,
f"received response for unknown request id {response_id}: {message}",
)
require(
response_key not in self.responses,
f"received duplicate response id {response_id}: {message}",
)
self.responses[response_key] = message
self.state_changed.notify_all()
with self.state_changed:
self.stdout_eof = True
self.state_changed.notify_all()
except Exception as err:
with self.state_changed:
self.stdout_error = str(err)
self.state_changed.notify_all()
def _drain_stderr(self):
try:
for line in self.proc.stderr:
self.stderr_lines.append(line.rstrip("\n"))
except Exception as err:
self.stderr_lines.append(f"<stderr drain failed: {err}>")
def _record_event(self, label):
with self.state_changed:
self._record_event_locked(label)
def _record_event_locked(self, label):
self.event_log.append({"at": time.monotonic(), "label": label})
def close(self):
if self.proc.poll() is None:
try:
self.close_input()
except Exception:
self.proc.kill()
try:
self.proc.wait(timeout=5)
except subprocess.TimeoutExpired:
self.proc.kill()
self.proc.wait(timeout=5)
if self.stdout_thread is not None:
self.stdout_thread.join(timeout=1)
self.stderr_thread.join(timeout=1)
stderr = "\n".join(self.stderr_lines)
if not self.server_trace:
require(stderr.strip() == "", f"lean-beam-mcp wrote unexpected stderr:\n{stderr}")
def send_message(self, message):
require(self.proc.poll() is None, "lean-beam-mcp exited before request")
line = json.dumps(message, separators=(",", ":"))
with self.stdin_lock:
self.proc.stdin.write(line + "\n")
self.proc.stdin.flush()
def handle_server_request(self, request):
method = request.get("method")
request_id = request.get("id")
with self.state_changed:
self._record_event_locked(f"server request id {request_id}: {method}")
self.server_requests.append(
{
"id": request_id,
"method": method,
"params": request.get("params"),
"received": time.monotonic(),
}
)
fail(f"lean-beam-mcp emitted forbidden server request {method!r}: {request}")
def _request_label(self, request_id):
pending = self.pending_requests.get(request_id_key(request_id))
if pending is None:
return "<unknown request>"
return pending["label"]
def _client_context(self):
return "\n".join(
[
f"client label: {self.label}",
f"project root: {self.project_root}",
f"process pid: {self.proc.pid}",
"runtime context:",
*[f" {line}" for line in self.runtime_context],
]
)
def _pending_requests_summary(self):
now = time.monotonic()
lines = []
for _request_key, pending in sorted(self.pending_requests.items()):
request_id = pending["id"]
age = now - pending["started"]
lines.append(
f" id {request_id}: {pending['label']} age={age:.3f}s "
f"params={compact_json(pending.get('params'), 500)}"
)
return "\n".join(lines) if lines else " <none>"
def _completed_requests_summary(self):
completed = "\n".join(
f" id {entry['id']}: {entry['label']} in {entry['elapsed']:.3f}s"
for entry in self.completed_requests
)
return completed or " <none>"
def _server_requests_summary(self):
now = time.monotonic()
lines = []
for entry in self.server_requests:
age = now - entry["received"]
lines.append(
f" id {entry['id']}: {entry['method']} age={age:.3f}s "
f"params={compact_json(entry.get('params'), 300)}"
)
return "\n".join(lines) if lines else " <none>"
def _notifications_summary(self):
rows = self.notifications[-12:]
if not rows:
return " <none>"
return "\n".join(f" {notification_summary(notification)}" for notification in rows)
def _event_timeline_summary(self):
now = time.monotonic()
if not self.event_log:
return " <none>"
return "\n".join(
f" +{entry['at'] - self.started_at:.3f}s "
f"({now - entry['at']:.3f}s ago): {entry['label']}"
for entry in self.event_log
)
def _last_notification_summary(self):
if self.last_notification_at is None:
return "last notification: <none>"
return f"last notification: {time.monotonic() - self.last_notification_at:.3f}s ago"
def _process_snapshot(self):
try:
out = subprocess.run(
["ps", "-ef"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=5,
check=False,
)
except Exception as err:
return f"<ps failed: {err}>"
needles = [
"lean-beam-mcp",
"beam-daemon",
"beam-daemon-smo",
"lean --server",
]
lines = [
line
for line in out.stdout.splitlines()
if any(needle in line for needle in needles)
]
return "\n".join(lines[-40:]) if lines else "<no Beam/Lean processes found>"
def _diagnostic_context(self):
stderr_tail = "\n".join(self.stderr_lines)
return (
f"MCP client context:\n{self._client_context()}\n"
f"pending MCP requests:\n{self._pending_requests_summary()}\n"
f"recent completed MCP requests:\n{self._completed_requests_summary()}\n"
f"recent server requests received from lean-beam-mcp:\n"
f"{self._server_requests_summary()}\n"
f"recent notifications:\n{self._notifications_summary()}\n"
f"MCP event timeline ({self._last_notification_summary()}):\n"
f"{self._event_timeline_summary()}\n"
f"CI timeout tracker:\n{CI_TIMEOUT_TRACKER_NOTE}\n"
f"lean-beam-mcp stderr tail:\n{stderr_tail or ' <empty>'}\n"
f"process snapshot:\n{self._process_snapshot()}"
)
def _timeout_message(self, expected_id):
label = self._request_label(expected_id)
pending = self.pending_requests.get(request_id_key(expected_id))
elapsed = time.monotonic() - pending["started"] if pending is not None else 0.0
return (
f"timed out waiting for MCP response id {expected_id} ({label}) "
f"for client {self.label!r} after {elapsed:.3f}s\n"
f"{self._diagnostic_context()}"
)
def read_response(self, expected_id, timeout=None):
require(self.stdout_thread is not None, "MCP stdout reader is disabled")
response_key = request_id_key(expected_id)
deadline = time.monotonic() + (self.timeout if timeout is None else timeout)
with self.state_changed:
while response_key not in self.responses:
remaining = deadline - time.monotonic()
if remaining <= 0:
fail(self._timeout_message(expected_id))
if self.stdout_error is not None:
fail(f"failed reading lean-beam-mcp stdout: {self.stdout_error}")
if self.stdout_eof:
fail(f"lean-beam-mcp closed stdout before response id {expected_id}")
if self.proc.poll() is not None:
stderr = "\n".join(self.stderr_lines)
fail(f"lean-beam-mcp exited early with code {self.proc.returncode}\n{stderr}")
self.state_changed.wait(timeout=min(remaining, 0.1))
response = self.responses.pop(response_key)
pending = self.pending_requests.pop(response_key, None)
if pending is not None:
elapsed = time.monotonic() - pending["started"]
self.completed_requests.append(
{
"id": expected_id,
"label": pending["label"],
"elapsed": elapsed,
}
)
self._record_event_locked(
f"response id {expected_id}: {pending['label']} elapsed={elapsed:.3f}s"
)
return response
def send_request(self, method, params=None, *, request_id=None, inject_workspace=True):
if inject_workspace and method == "tools/call" and isinstance(params, dict):
tool_name = params.get("name")
if tool_name == "beam_feedback_report" or (
isinstance(tool_name, str)
and tool_name.startswith("lean_")
):
params = dict(params)
arguments = dict(params.get("arguments") or {})
arguments.setdefault(
"workspace",
{"root": str(self.project_root.resolve())},
)
params["arguments"] = arguments
with self.state_changed:
if request_id is None:
self.next_id += 1
request_id = self.next_id
request_key = request_id_key(request_id)
require(
request_key not in self.pending_requests and request_key not in self.responses,
f"duplicate pending MCP request id {request_id!r}",
)
label = request_label(method, params)
self.pending_requests[request_key] = {
"id": request_id,
"label": label,
"method": method,
"params": params,
"started": time.monotonic(),
}
self._record_event_locked(f"request id {request_id}: {label}")
message = {"jsonrpc": "2.0", "id": request_id, "method": method}
if params is not None:
message["params"] = params
self.send_message(message)
return request_id
def request(self, method, params=None, *, request_id=None, inject_workspace=True):
request_id = self.send_request(
method,
params,
request_id=request_id,
inject_workspace=inject_workspace,
)
return self.read_response(request_id)
def modern_request(self, method, params=None, *, request_id=None, log_level=None):
return self.request(
method,
with_modern_metadata(params, log_level=log_level),
request_id=request_id,
)
def close_input(self):
if self.proc.stdin and not self.proc.stdin.closed:
self.proc.stdin.close()
def wait_for_exit_after_eof(self, timeout):
try:
return self.proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
fail(
f"timed out waiting {timeout:.1f}s for lean-beam-mcp to exit after EOF\n"
f"{self._diagnostic_context()}"
)
def response_ready(self, request_id):
with self.state_changed:
return request_id_key(request_id) in self.responses
def forget_request(self, request_id):
request_key = request_id_key(request_id)
with self.state_changed:
require(
request_key not in self.responses,
f"request id {request_id!r} unexpectedly received a response",
)
self.pending_requests.pop(request_key, None)
def notify(self, method, params=None):
message = {"jsonrpc": "2.0", "method": method}
if params is not None:
message["params"] = params
self._record_event(f"client notification: {method}")
self.send_message(message)
def initialize(self):
response = self.request(
"initialize",
{
"protocolVersion": MCP_LEGACY_PROTOCOL_VERSION,
"capabilities": {},
"clientInfo": {"name": "lean-beam-mcp-test", "version": "0"},
},
)
result = expect_result(response)
require(
result.get("protocolVersion") == MCP_LEGACY_PROTOCOL_VERSION,
f"server negotiated unexpected protocol version: {result}",
)
tools = result.get("capabilities", {}).get("tools")
require(isinstance(tools, dict), f"initialize did not advertise tools capability: {result}")
logging = result.get("capabilities", {}).get("logging")
require(isinstance(logging, dict), f"initialize did not advertise logging capability: {result}")
self.notify("notifications/initialized")
def call_tool(self, name, arguments=None):
params = {"name": name}
if arguments is not None:
params["arguments"] = arguments
response = self.request("tools/call", params)
result = expect_result(response)
require(result.get("isError") is not True, f"tool {name} returned MCP tool error: {result}")
content = result.get("content")
require(isinstance(content, list) and content, f"tool {name} missing content: {result}")
require(content[0].get("type") == "text", f"tool {name} first content block is not text: {result}")
structured = result.get("structuredContent")
require(isinstance(structured, dict), f"tool {name} missing structuredContent: {result}")
return structured
def progress_notifications(self, token):
with self.state_changed:
notifications = list(self.notifications)
rows = []
for notification in notifications_by_method(notifications, "notifications/progress"):
params = notification_params(notification, "notifications/progress", "progress notification")
if params.get("progressToken") == token:
rows.append(notification)
return rows
def expect_result(response):
if "error" in response:
fail(f"unexpected JSON-RPC error response: {response}")
result = response.get("result")
require(result is not None, f"missing JSON-RPC result: {response}")
return result
def expect_error_code(response, code):
error = response.get("error")
require(isinstance(error, dict), f"expected JSON-RPC error response, got {response}")
require(error.get("code") == code, f"expected JSON-RPC error code {code}, got {response}")
return error
def require_modern_result_envelope(result, label):
require(result.get("resultType") == "complete", f"{label} missing resultType: {result}")
server_info = result.get("_meta", {}).get("io.modelcontextprotocol/serverInfo")
require(
isinstance(server_info, dict) and server_info.get("name") == "lean-beam-mcp",
f"{label} missing serverInfo: {result}",
)
def write_save_warning_file(project_root, marker):
(project_root / "SaveSmoke" / "B.lean").write_text(save_warning_text(marker), encoding="utf-8")
def diagnostic_log_notifications(client):
rows = []
for notification in notifications_by_method(client.notifications, "notifications/message"):
params = notification_params(notification, "notifications/message", "diagnostic log notification")
if params.get("logger") == "lean.diagnostic":
rows.append(notification)
return rows
def status_log_notifications(client, request_id=None):
rows = []
for notification in notifications_by_method(client.notifications, "notifications/message"):
params = notification_params(notification, "notifications/message", "status log notification")
if params.get("logger") != "beam.status":
continue
data = params.get("data")
if request_id is not None and (
not isinstance(data, dict) or data.get("requestId") != request_id
):
continue
rows.append(notification)
return rows
def wait_for_status_log(client, request_id, timeout, label):
deadline = time.monotonic() + timeout
with client.state_changed:
while True:
notifications = status_log_notifications(client, request_id)
if notifications:
return notifications[0]
remaining = deadline - time.monotonic()
if remaining <= 0:
fail(f"{label}: timed out waiting for beam.status requestId={request_id!r}")
client.state_changed.wait(timeout=min(remaining, 0.05))
def wait_for_progress_notification(client, token, timeout, label):
deadline = time.monotonic() + timeout
with client.state_changed:
while True:
notifications = client.progress_notifications(token)
if notifications:
return notifications[0]
remaining = deadline - time.monotonic()
if remaining <= 0:
fail(f"{label}: timed out waiting for progress token={token!r}")
client.state_changed.wait(timeout=min(remaining, 0.05))
def expect_status_log(client, *, request_id, tool, state, timeout, label):
notification = wait_for_status_log(client, request_id, timeout, label)
params = notification_params(notification, "notifications/message", label)
data = params.get("data", {})
require(params.get("level") == "notice", f"{label} level: {notification}")
require(data.get("tool") == tool, f"{label} tool: {notification}")
require(data.get("state") == state, f"{label} state: {notification}")
require(
"progressToken" in data.get("progressHint", ""),
f"{label} should make detailed progress discoverable: {notification}",
)
return notification
def expect_diagnostic_log(client, *, level, severity, path):
for notification in diagnostic_log_notifications(client):
params = notification_params(notification, "notifications/message", "diagnostic log notification")
data = params.get("data", {})
if (
params.get("level") == level
and isinstance(data, dict)
and data.get("severity") == severity
and data.get("path") == path
):
require(isinstance(data.get("uri"), str), f"diagnostic log missing uri: {notification}")
require(isinstance(data.get("version"), int), f"diagnostic log missing version: {notification}")
require(isinstance(data.get("range"), dict), f"diagnostic log missing range: {notification}")
require(isinstance(data.get("message"), str) and data["message"], f"diagnostic log missing message: {notification}")
return notification
fail(f"missing {level}/{severity} diagnostic log for {path}: {client.notifications}")
def expect_reply_diagnostic(sync, *, severity, path):
diagnostics = sync.get("diagnostics", {}).get("items")
require(isinstance(diagnostics, list) and diagnostics, f"sync reply missing diagnostics: {sync}")
for diagnostic in diagnostics:
if (
isinstance(diagnostic, dict)
and diagnostic.get("severity") == severity
and diagnostic.get("path") == path
):
require(isinstance(diagnostic.get("uri"), str), f"reply diagnostic missing uri: {diagnostic}")
require(isinstance(diagnostic.get("version"), int), f"reply diagnostic missing version: {diagnostic}")
require(isinstance(diagnostic.get("range"), dict), f"reply diagnostic missing range: {diagnostic}")
require(isinstance(diagnostic.get("message"), str) and diagnostic["message"], f"reply diagnostic missing message: {diagnostic}")
return diagnostic
fail(f"missing {severity} reply diagnostic for {path}: {sync}")
def expect_error_message_contains(response, code, needle):
error = expect_error_code(response, code)
message = error.get("message")
require(isinstance(message, str), f"error response missing message: {response}")
require(needle in message, f"expected error message to contain {needle!r}, got {response}")
return error
def expect_tool_error_code(response, code):
result = expect_result(response)
require(result.get("isError") is True, f"expected MCP tool error result, got {response}")
structured = result.get("structuredContent")
require(isinstance(structured, dict), f"tool error missing structuredContent: {response}")
require(structured.get("code") == code, f"expected tool error code {code}, got {response}")
return structured
def workspace_descriptor(root):
return {"root": str(Path(root).resolve())}
def result_workspace_root(structured, label):
workspace = structured.get("workspace")
require(isinstance(workspace, dict), f"{label}: missing workspace descriptor: {structured}")
root = workspace.get("root")
require(isinstance(root, str), f"{label}: workspace descriptor has no root: {structured}")
return Path(root)
def workspace_cache_key(root):
return f"local:{Path(root).resolve()}"
def beam_cli_mcp_config(repo_root, root, timeout):
beam_cli = repo_root / ".lake" / "build" / "bin" / "beam-cli"
completed = subprocess.run(
[str(beam_cli), "--root", str(root), "mcp-config"],
cwd=str(repo_root),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
timeout=timeout,
check=False,
)
require(
completed.returncode == 0,
f"beam-cli mcp-config failed for {root}:\n{completed.stdout}\n{completed.stderr}",
)
try:
config = json.loads(completed.stdout)
except json.JSONDecodeError as err:
fail(f"beam-cli mcp-config returned invalid JSON for {root}: {err}: {completed.stdout!r}")
require(isinstance(config, dict), f"beam-cli mcp-config returned no object for {root}: {config}")
return config
def require_version_mismatch_data(error, expected_version, accepted_version, label, *, expected_uri_suffix=None):
data = error.get("data")
require(isinstance(data, dict), f"{label}: tool error missing data: {error}")
require(
data.get("reason") == "documentVersionMismatch",
f"{label}: expected documentVersionMismatch data, got {error}",
)
require(
data.get("expectedVersion") == expected_version,
f"{label}: expected expectedVersion={expected_version}, got {error}",
)
require(
data.get("acceptedVersion") == accepted_version,
f"{label}: expected acceptedVersion={accepted_version}, got {error}",
)
require(
data.get("currentVersion") == accepted_version,
f"{label}: expected currentVersion={accepted_version}, got {error}",
)
if expected_uri_suffix is not None:
uri = data.get("uri")
require(
isinstance(uri, str) and uri.endswith(expected_uri_suffix),
f"{label}: expected uri ending in {expected_uri_suffix!r}, got {error}",
)
def require_success(label, structured):
require(structured.get("success") is True, f"{label} should succeed: {structured}")
def require_failure(label, structured):
require(structured.get("success") is False, f"{label} should fail semantically: {structured}")
def wait_for_file(path, timeout, label):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if path.exists():
return
time.sleep(0.02)
fail(f"timed out waiting for {label} at {path}")
def require_message_contains(label, structured, needle):
messages = structured.get("messages")
require(isinstance(messages, list), f"{label}: missing messages array: {structured}")
require(
any(
isinstance(message, dict)
and isinstance(message.get("text"), str)
and needle in message["text"]
for message in messages
),
f"{label}: expected message containing {needle!r}, got {structured}",
)
def drop_workspace(client, root, *, expected_dropped=True):
descriptor = workspace_descriptor(root)
structured = client.call_tool(
"lean_drop_workspace",
{"workspace": descriptor},
)
require(
structured.get("workspace") == descriptor,
f"drop workspace returned wrong descriptor {descriptor!r}: {structured}",
)
require(
structured.get("dropped") is expected_dropped,
f"drop workspace returned wrong dropped={expected_dropped}: {structured}",
)
if expected_dropped:
require(
structured.get("invalidated_handles") is True,
f"drop workspace should report handle invalidation: {structured}",
)
return structured
def require_progress_sequence(notifications, token, label):
require(notifications, f"{label}: expected progress notifications for {token!r}")
previous = None
for notification in notifications:
params = notification_params(notification, "notifications/progress", label)
require(params.get("progressToken") == token, f"{label}: wrong progress token: {notification}")
progress = params.get("progress")
require(isinstance(progress, (int, float)), f"{label}: progress is not numeric: {notification}")
if previous is not None:
require(progress > previous, f"{label}: progress is not strictly increasing: {notifications}")
previous = progress
message = params.get("message")
require(message is None or isinstance(message, str), f"{label}: progress message is not a string: {notification}")
return [notification["params"]["progress"] for notification in notifications]
def require_progress_message_contains(notifications, label, *needles):
messages = [message for message in progress_messages(notifications) if isinstance(message, str)]
for needle in needles:
require(
any(needle in message for message in messages),
f"{label}: expected a progress message containing {needle!r}, got {messages}",
)
def require_document_progress_range_end(structured, label, range_end):
require_document_progress_range(structured, label)
progress = structured["document_progress"]
require(
progress.get("range_end_line") == range_end,
f"{label}: expected document_progress range_end_line={range_end}, got {progress}",
)
def expect_stale_handle(client, handle, label, *, root=None):
arguments = {
"path": "PositionEmptyLine.lean",
"handle": handle,
"text": "def mcpResetAfter : Nat := mcpResetBase + 1",
}
if root is not None:
arguments["workspace"] = workspace_descriptor(root)
response = client.request(
"tools/call",
{
"name": "lean_run_with",
"arguments": arguments,
},
)
error = expect_tool_error_code(response, "contentModified")
require(
"stale backend session" in error.get("message", ""),
f"{label}: handle should be stale after reset: {error}",
)
def run_iteration(client, suffix):
update = client.call_tool("lean_update", {"path": "PositionEmptyLine.lean"})
require(
result_workspace_root(update, "lean_update").resolve() == client.project_root.resolve(),
f"update returned wrong workspace descriptor: {update}",
)
version = update.get("version")
require(isinstance(version, int), f"update did not return a document version: {update}")
changed = update.get("changed")
require(isinstance(changed, bool), f"update did not return changed flag: {update}")
command_update = client.call_tool("lean_update", {"path": "CommandA.lean"})
command_version = command_update.get("version")
require(isinstance(command_version, int), f"CommandA update did not return a version: {command_update}")
command_path = client.project_root / "CommandA.lean"
command_text = command_path.read_text(encoding="utf-8")
command_path.write_text(f"{command_text}\n-- mcp stale-version {suffix}\n", encoding="utf-8")
command_changed = client.call_tool("lean_update", {"path": "CommandA.lean"})
accepted_version = command_changed.get("version")
require(isinstance(accepted_version, int), f"CommandA changed update did not return a version: {command_changed}")
stale_response = client.request(
"tools/call",
{
"name": "lean_run_at",
"arguments": {
"path": "CommandA.lean",
"version": command_version,
"line": 0,
"character": 2,
"text": "#check answerA",
},
},
)
stale_error = expect_tool_error_code(stale_response, "contentModified")
require_version_mismatch_data(
stale_error,
command_version,
accepted_version,