-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathtest_jsonrpc_dispatcher.py
More file actions
2388 lines (2049 loc) · 110 KB
/
Copy pathtest_jsonrpc_dispatcher.py
File metadata and controls
2388 lines (2049 loc) · 110 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
"""JSON-RPC-specific dispatcher tests; contract tests shared with `DirectDispatcher` live in `test_dispatcher.py`."""
import contextvars
import json
import logging
from collections.abc import Mapping
from types import TracebackType
from typing import Any
import anyio
import anyio.lowlevel
import pytest
from mcp_types import (
CONNECTION_CLOSED,
INTERNAL_ERROR,
INVALID_PARAMS,
REQUEST_TIMEOUT,
CallToolRequest,
CallToolRequestParams,
CallToolResult,
CancelledNotification,
CancelledNotificationParams,
ErrorData,
JSONRPCError,
JSONRPCNotification,
JSONRPCRequest,
JSONRPCResponse,
RequestId,
Tool,
)
from trio.testing import MockClock
from mcp import Client
from mcp.server import Server, ServerRequestContext
from mcp.shared._compat import resync_tracer
from mcp.shared._context_streams import ContextReceiveStream, ContextSendStream
from mcp.shared.dispatcher import CallOptions, DispatchContext
from mcp.shared.exceptions import MCPError, NoBackChannelError
from mcp.shared.jsonrpc_dispatcher import ( # pyright: ignore[reportPrivateUsage]
JSONRPCDispatcher,
_coerce_id,
_OutboundPlan,
_Pending,
_plan_outbound,
)
from mcp.shared.message import ClientMessageMetadata, MessageMetadata, ServerMessageMetadata, SessionMessage
from mcp.shared.transport_context import TransportContext
from .conftest import jsonrpc_pair
from .test_dispatcher import Recorder, echo_handlers, running_pair
DCtx = DispatchContext[TransportContext]
@pytest.fixture(autouse=True)
def _module_runner_lease() -> None:
"""Opt out of the shared per-module event loop: this module parametrizes `anyio_backend`."""
class RecordingWriteStream:
"""Records sends without a checkpoint, so a pending cancellation cannot interrupt the write or mask it."""
def __init__(self) -> None:
self.sent: list[SessionMessage] = []
async def send(self, item: SessionMessage) -> None:
self.sent.append(item)
async def aclose(self) -> None:
raise NotImplementedError # the dispatcher releases streams via __aexit__, never aclose
async def __aenter__(self) -> "RecordingWriteStream":
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> bool | None:
return None
@pytest.mark.anyio
async def test_concurrent_send_raw_requests_correlate_by_id_when_responses_arrive_out_of_order():
release_first = anyio.Event()
async def server_on_request(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
if method == "first":
await release_first.wait()
return {"m": method}
async with running_pair(jsonrpc_pair, server_on_request=server_on_request) as (client, *_):
results: dict[str, dict[str, Any]] = {}
async def call(method: str) -> None:
results[method] = await client.send_raw_request(method, None)
with anyio.fail_after(5):
async with anyio.create_task_group() as tg: # pragma: no branch
tg.start_soon(call, "first")
await anyio.sleep(0)
tg.start_soon(call, "second")
await anyio.sleep(0)
# second resolves while first is still parked
assert "first" not in results
release_first.set()
assert results == {"first": {"m": "first"}, "second": {"m": "second"}}
@pytest.mark.anyio
async def test_handler_raising_exception_sends_code_zero_with_str_message():
"""Matches the existing server's `_handle_request`: code=0, message=str(e)."""
async def server_on_request(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
raise RuntimeError("kaboom")
async with running_pair(jsonrpc_pair, server_on_request=server_on_request) as (client, *_):
with anyio.fail_after(5), pytest.raises(MCPError) as exc:
await client.send_raw_request("tools/list", None)
assert exc.value.error.code == 0
assert exc.value.error.message == "kaboom"
assert exc.value.__cause__ is None # cause does not survive the wire
@pytest.mark.anyio
async def test_peer_cancel_interrupt_mode_writes_cancelled_error_response():
"""Matches the existing server: a peer-cancelled request is answered with code=0."""
handler_started = anyio.Event()
handler_exited = anyio.Event()
seen_ctx: list[DCtx] = []
async def server_on_request(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
seen_ctx.append(ctx)
handler_started.set()
try:
await anyio.sleep_forever()
finally:
handler_exited.set()
raise NotImplementedError
seen_error: list[ErrorData] = []
async with running_pair(jsonrpc_pair, server_on_request=server_on_request) as (client, *_):
with anyio.fail_after(5):
async with anyio.create_task_group() as tg: # pragma: no branch
async def call_then_record() -> None:
with pytest.raises(MCPError) as exc:
await client.send_raw_request("slow", None)
seen_error.append(exc.value.error)
tg.start_soon(call_then_record)
await handler_started.wait()
await client.notify("notifications/cancelled", {"requestId": 1})
await handler_exited.wait()
assert seen_ctx[0].cancel_requested.is_set()
assert seen_error == [ErrorData(code=0, message="Request cancelled")]
@pytest.mark.anyio
async def test_peer_cancel_landing_after_handlers_last_checkpoint_writes_only_the_result():
"""A peer cancel that fails to interrupt the handler writes only the result: one answer per
id goes on the wire (SDK-defined). The recording stream is needed because a memory stream's
`send` checkpoints, letting the deferred cancellation land mid-write and hide a double answer."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](4)
recording = RecordingWriteStream()
server: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(c2s_recv, recording)
handler_started = anyio.Event()
async def on_request(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
handler_started.set()
await ctx.cancel_requested.wait()
return {"completed": "after-cancel"}
async def on_notify(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> None:
pass # the cancelled notification is teed here; nothing to observe
try:
async with anyio.create_task_group() as tg:
await tg.start(server.run, on_request, on_notify)
await c2s_send.send(SessionMessage(message=JSONRPCRequest(jsonrpc="2.0", id=1, method="t", params=None)))
with anyio.fail_after(5):
await handler_started.wait()
# The cancel is also the handler's wakeup, so anyio defers it and the handler completes.
await c2s_send.send(
SessionMessage(
message=JSONRPCNotification(
jsonrpc="2.0", method="notifications/cancelled", params={"requestId": 1}
)
)
)
# Quiesce: the handler has resumed, completed, and exited its scope.
await anyio.wait_all_tasks_blocked()
tg.cancel_scope.cancel()
finally:
c2s_send.close()
c2s_recv.close()
assert [m.message for m in recording.sent] == [
JSONRPCResponse(jsonrpc="2.0", id=1, result={"completed": "after-cancel"})
]
@pytest.mark.anyio
async def test_peer_cancel_signal_mode_sets_event_but_handler_runs_to_completion():
handler_started = anyio.Event()
cancel_seen = anyio.Event()
async def server_on_request(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
handler_started.set()
await ctx.cancel_requested.wait()
cancel_seen.set()
return {"finished": True}
def factory(*, can_send_request: bool = True):
client, server, close = jsonrpc_pair(can_send_request=can_send_request)
assert isinstance(server, JSONRPCDispatcher)
server._peer_cancel_mode = "signal" # pyright: ignore[reportPrivateUsage]
return client, server, close
result_box: list[dict[str, Any]] = []
async with running_pair(factory, server_on_request=server_on_request) as (client, *_):
with anyio.fail_after(5):
async with anyio.create_task_group() as tg: # pragma: no branch
async def call() -> None:
result_box.append(await client.send_raw_request("slow", None))
tg.start_soon(call)
await handler_started.wait()
await client.notify("notifications/cancelled", {"requestId": 1})
await cancel_seen.wait()
assert result_box == [{"finished": True}]
@pytest.mark.anyio
async def test_send_raw_request_raises_connection_closed_when_read_stream_eofs_mid_await():
"""A blocked send_raw_request is woken with CONNECTION_CLOSED when run() exits."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, c2s_send)
on_request, on_notify = echo_handlers(Recorder())
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
async def caller() -> None:
with pytest.raises(MCPError) as exc:
await client.send_raw_request("ping", None)
assert exc.value.error.code == CONNECTION_CLOSED
tg.start_soon(caller)
await anyio.sleep(0)
# No server: simulate the peer dropping by closing the read side.
s2c_send.close()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
@pytest.mark.anyio
async def test_run_returns_cleanly_when_read_stream_receive_end_is_closed():
"""Iterating a closed receive end is EOF, not a crash (stateless SHTTP closes it during teardown)."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
server: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(c2s_recv, s2c_send)
on_request, on_notify = echo_handlers(Recorder())
# Close the receive end itself (not the send end): __anext__ then raises ClosedResourceError.
c2s_recv.close()
with anyio.fail_after(5):
await server.run(on_request, on_notify)
for s in (c2s_send, s2c_send, s2c_recv):
s.close()
@pytest.mark.anyio
async def test_run_cancels_in_flight_handlers_when_read_stream_eofs():
"""run() cancels still-running handlers at read-stream EOF; otherwise its join waits forever
(over SSE, leaking the handler and the GET request hosting the session)."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
server: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(c2s_recv, s2c_send)
handler_started = anyio.Event()
handler_cancelled = anyio.Event()
async def park(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
handler_started.set()
try:
await anyio.sleep_forever()
finally:
handler_cancelled.set()
raise NotImplementedError
async def on_notify(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> None:
raise NotImplementedError
run_returned = anyio.Event()
async def drive() -> None:
await server.run(park, on_notify)
run_returned.set()
async with anyio.create_task_group() as tg:
tg.start_soon(drive)
await c2s_send.send(SessionMessage(message=JSONRPCRequest(jsonrpc="2.0", id=1, method="x", params=None)))
with anyio.fail_after(5):
await handler_started.wait()
c2s_send.close() # EOF the read side; run() must cancel the parked handler
await run_returned.wait()
assert handler_cancelled.is_set()
s2c_recv.close()
@pytest.mark.anyio
async def test_run_closes_write_stream_on_exit():
"""run() owns both streams; the write end is released once the EOF teardown completes."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
server: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(c2s_recv, s2c_send)
on_request, on_notify = echo_handlers(Recorder())
async with anyio.create_task_group() as tg:
await tg.start(server.run, on_request, on_notify)
c2s_send.close() # EOF the read side; run() exits
with anyio.fail_after(5), pytest.raises(anyio.EndOfStream): # pragma: no branch
await s2c_recv.receive()
s2c_recv.close()
@pytest.mark.anyio
async def test_late_response_after_timeout_is_dropped_without_crashing():
handler_started = anyio.Event()
proceed = anyio.Event()
async def server_on_request(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
handler_started.set()
await proceed.wait()
return {"late": True}
async with running_pair(jsonrpc_pair, server_on_request=server_on_request) as (client, *_):
with anyio.fail_after(5):
with pytest.raises(MCPError): # REQUEST_TIMEOUT
await client.send_raw_request("slow", None, {"timeout": 0})
# Let the parked handler respond to an id the client has already discarded.
await handler_started.wait()
proceed.set()
# One more round-trip proves the dispatcher is still healthy.
assert await client.send_raw_request("ping", None) == {"late": True}
@pytest.mark.anyio
async def test_raise_handler_exceptions_true_propagates_out_of_run():
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
def builder(_meta: object) -> TransportContext:
return TransportContext(kind="jsonrpc", can_send_request=True)
server: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(
c2s_recv, s2c_send, transport_builder=builder, raise_handler_exceptions=True
)
async def boom(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
raise RuntimeError("propagate me")
async def on_notify(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> None:
raise NotImplementedError
try:
with pytest.raises(BaseException) as exc:
async with anyio.create_task_group() as tg:
await tg.start(server.run, boom, on_notify)
await c2s_send.send(
SessionMessage(message=JSONRPCRequest(jsonrpc="2.0", id=1, method="x", params=None))
)
assert exc.group_contains(RuntimeError, match="propagate me")
# The error response was still written before re-raising.
sent = s2c_recv.receive_nowait()
assert isinstance(sent, SessionMessage)
assert isinstance(sent.message, JSONRPCError)
assert sent.message.error.code == 0
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
@pytest.mark.anyio
async def test_ctx_send_raw_request_tags_outbound_with_server_message_metadata():
"""Server-to-client requests carry related_request_id for SHTTP routing."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
server: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(c2s_recv, s2c_send)
async def server_on_request(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
return await ctx.send_raw_request("sampling/createMessage", {"prompt": "hi"})
async def on_notify(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> None:
raise NotImplementedError
try:
async with anyio.create_task_group() as tg:
await tg.start(server.run, server_on_request, on_notify)
await c2s_send.send(SessionMessage(message=JSONRPCRequest(jsonrpc="2.0", id=7, method="t", params=None)))
with anyio.fail_after(5):
outbound = await s2c_recv.receive()
assert isinstance(outbound, SessionMessage)
assert isinstance(outbound.message, JSONRPCRequest)
assert isinstance(outbound.metadata, ServerMessageMetadata)
assert outbound.metadata.related_request_id == 7
await c2s_send.send(
SessionMessage(message=JSONRPCResponse(jsonrpc="2.0", id=outbound.message.id, result={"ok": True}))
)
with anyio.fail_after(5):
final = await s2c_recv.receive()
assert isinstance(final, SessionMessage)
assert isinstance(final.message, JSONRPCResponse)
assert final.message.id == 7
tg.cancel_scope.cancel()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
@pytest.mark.anyio
async def test_courtesy_cancel_on_timeout_tags_outbound_with_server_message_metadata():
"""The timeout-path `notifications/cancelled` carries the originating request id: SHTTP's
`message_router` keys on `related_request_id`; without it the cancel would be dropped."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
server: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(c2s_recv, s2c_send)
async def server_on_request(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
with pytest.raises(MCPError): # REQUEST_TIMEOUT
await ctx.send_raw_request("sampling/createMessage", None, {"timeout": 0})
return {"gave_up": True}
async def on_notify(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> None:
raise NotImplementedError
try:
async with anyio.create_task_group() as tg:
await tg.start(server.run, server_on_request, on_notify)
await c2s_send.send(SessionMessage(message=JSONRPCRequest(jsonrpc="2.0", id=7, method="t", params=None)))
with anyio.fail_after(5):
outbound = await s2c_recv.receive()
assert isinstance(outbound, SessionMessage)
assert isinstance(outbound.message, JSONRPCRequest)
assert outbound.message.method == "sampling/createMessage"
sampling_id = outbound.message.id
# Don't respond; let the timeout fire. Next on the wire is the courtesy cancel.
with anyio.fail_after(5):
cancel = await s2c_recv.receive()
assert isinstance(cancel, SessionMessage)
assert isinstance(cancel.message, JSONRPCNotification)
assert cancel.message.method == "notifications/cancelled"
assert cancel.message.params == {"requestId": sampling_id, "reason": "timed out after 0s"}
assert isinstance(cancel.metadata, ServerMessageMetadata)
assert cancel.metadata.related_request_id == 7
with anyio.fail_after(5):
final = await s2c_recv.receive()
assert isinstance(final, SessionMessage)
assert isinstance(final.message, JSONRPCResponse)
assert final.message.result == {"gave_up": True}
tg.cancel_scope.cancel()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
@pytest.mark.anyio
async def test_dispatch_context_request_with_dropped_resumption_hints_still_sends_courtesy_cancel():
"""Resumption hints that never reach the transport must not suppress the abandon cancel:
`related_request_id` takes metadata precedence and drops the hints, so the request is not resumable."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
server: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(c2s_recv, s2c_send)
async def server_on_request(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
with pytest.raises(MCPError): # REQUEST_TIMEOUT
await ctx.send_raw_request("sampling/createMessage", None, {"timeout": 0, "resumption_token": "tok"})
return {"gave_up": True}
async def on_notify(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> None:
raise NotImplementedError
try:
async with anyio.create_task_group() as tg:
await tg.start(server.run, server_on_request, on_notify)
await c2s_send.send(SessionMessage(message=JSONRPCRequest(jsonrpc="2.0", id=7, method="t", params=None)))
with anyio.fail_after(5):
outbound = await s2c_recv.receive()
assert isinstance(outbound, SessionMessage)
assert isinstance(outbound.message, JSONRPCRequest)
# The hints were dropped: dispatch-context routing won the metadata.
assert isinstance(outbound.metadata, ServerMessageMetadata)
sampling_id = outbound.message.id
# Don't respond; let the timeout fire. Next on the wire must be the courtesy cancel.
with anyio.fail_after(5):
cancel = await s2c_recv.receive()
assert isinstance(cancel, SessionMessage)
assert isinstance(cancel.message, JSONRPCNotification)
assert cancel.message.method == "notifications/cancelled"
assert cancel.message.params == {"requestId": sampling_id, "reason": "timed out after 0s"}
with anyio.fail_after(5):
final = await s2c_recv.receive()
assert isinstance(final, SessionMessage)
assert isinstance(final.message, JSONRPCResponse)
assert final.message.result == {"gave_up": True}
tg.cancel_scope.cancel()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
@pytest.mark.anyio
async def test_caller_cancel_sends_courtesy_cancellation_on_the_wire():
"""Cancelling the scope around send_raw_request emits notifications/cancelled by default."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, c2s_send)
on_request, on_notify = echo_handlers(Recorder())
scopes: list[anyio.CancelScope] = []
gave_up = anyio.Event()
async def caller() -> None:
with anyio.CancelScope() as scope:
scopes.append(scope)
await client.send_raw_request("slow", None)
raise NotImplementedError # unreachable: the scope is cancelled
gave_up.set()
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
tg.start_soon(caller)
with anyio.fail_after(5):
request = await c2s_recv.receive()
assert isinstance(request, SessionMessage)
assert isinstance(request.message, JSONRPCRequest)
scopes[0].cancel()
with anyio.fail_after(5):
await gave_up.wait()
cancel = await c2s_recv.receive()
assert isinstance(cancel, SessionMessage)
assert isinstance(cancel.message, JSONRPCNotification)
assert cancel.message.method == "notifications/cancelled"
assert cancel.message.params == {"requestId": request.message.id, "reason": "caller cancelled"}
assert cancel.metadata is None
tg.cancel_scope.cancel()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
assert scopes[0].cancelled_caught
@pytest.mark.anyio
async def test_caller_cancel_during_blocked_request_write_still_sends_courtesy_cancellation():
"""A request write interrupted by cancellation may still have delivered its message, so the
courtesy cancel goes out anyway: the peer drops cancels for ids it never saw, while skipping
the cancel would leak a delivered request's handler. The fake stream wedges only the first
write, so the courtesy cancel itself still lands."""
class FirstWriteWedgedStream:
def __init__(self) -> None:
self.sent: list[SessionMessage] = []
self.first_write_started = anyio.Event()
async def send(self, item: SessionMessage) -> None:
if not self.first_write_started.is_set():
self.first_write_started.set()
await anyio.sleep_forever() # the request write wedges until the caller is cancelled
self.sent.append(item)
async def aclose(self) -> None:
raise NotImplementedError
async def __aenter__(self) -> "FirstWriteWedgedStream":
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> bool | None:
return None
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](4)
wedged = FirstWriteWedgedStream()
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, wedged)
on_request, on_notify = echo_handlers(Recorder())
scopes: list[anyio.CancelScope] = []
gave_up = anyio.Event()
async def caller() -> None:
with anyio.CancelScope() as scope:
scopes.append(scope)
await client.send_raw_request("slow", None)
raise NotImplementedError # unreachable: the scope is cancelled
gave_up.set()
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
tg.start_soon(caller)
with anyio.fail_after(5):
await wedged.first_write_started.wait() # the caller is parked in the request write
scopes[0].cancel()
with anyio.fail_after(5):
await gave_up.wait()
await client.notify("notifications/marker", None)
tg.cancel_scope.cancel()
finally:
await resync_tracer()
s2c_send.close()
s2c_recv.close()
assert scopes[0].cancelled_caught
# The wedged request write started, so it counts as issued: the cancel precedes the marker.
assert [m.message for m in wedged.sent] == [
JSONRPCNotification(
jsonrpc="2.0", method="notifications/cancelled", params={"requestId": 1, "reason": "caller cancelled"}
),
JSONRPCNotification(jsonrpc="2.0", method="notifications/marker"),
]
@pytest.mark.anyio
async def test_caller_cancel_during_delivered_request_write_sends_courtesy_cancellation():
"""A cancelled request write may still deliver: on a buffer-0 stream the transport can pop the
parked request in the same tick the cancel lands, so send() raises CancelledError after handing
the message over. The peer saw the id, so the courtesy cancel must still go out."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](0)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, c2s_send)
on_request, on_notify = echo_handlers(Recorder())
scopes: list[anyio.CancelScope] = []
gave_up = anyio.Event()
async def caller() -> None:
with anyio.CancelScope() as scope:
scopes.append(scope)
await client.send_raw_request("slow", None)
raise NotImplementedError # unreachable: the scope is cancelled
gave_up.set()
async def marker_after_caller_unwinds() -> None:
# Without the courtesy cancel, the marker is the next message: a missing
# cancel fails the assertion below instead of hanging the receive.
await gave_up.wait()
await client.notify("notifications/marker", None)
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
tg.start_soon(caller)
await anyio.wait_all_tasks_blocked() # the caller is parked in the buffer-0 request write
scopes[0].cancel() # the cancel lands on the parked send() first...
request = c2s_recv.receive_nowait() # ...then the transport pops the request: delivered
assert isinstance(request, SessionMessage)
assert isinstance(request.message, JSONRPCRequest)
tg.start_soon(marker_after_caller_unwinds)
with anyio.fail_after(5):
cancel = await c2s_recv.receive()
assert isinstance(cancel, SessionMessage)
assert cancel.message == JSONRPCNotification(
jsonrpc="2.0",
method="notifications/cancelled",
params={"requestId": request.message.id, "reason": "caller cancelled"},
)
with anyio.fail_after(5):
marker = await c2s_recv.receive()
assert isinstance(marker, SessionMessage)
assert marker.message == JSONRPCNotification(jsonrpc="2.0", method="notifications/marker")
tg.cancel_scope.cancel()
finally:
await resync_tracer()
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
assert scopes[0].cancelled_caught
@pytest.mark.anyio
async def test_caller_cancelled_before_request_write_starts_sends_no_courtesy_cancellation():
"""A caller whose scope is already cancelled never gets the request onto the wire, so no
courtesy cancel goes out either: there is provably no id for the peer to stop."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, c2s_send)
on_request, on_notify = echo_handlers(Recorder())
scopes: list[anyio.CancelScope] = []
gave_up = anyio.Event()
async def caller() -> None:
with anyio.CancelScope() as scope:
scopes.append(scope)
scope.cancel() # already cancelled when send_raw_request runs: the write never starts
await client.send_raw_request("slow", None)
raise NotImplementedError # unreachable: the scope is cancelled
gave_up.set()
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
tg.start_soon(caller)
with anyio.fail_after(5):
await gave_up.wait()
# A request or courtesy cancel would have to precede the marker on the ordered stream.
await client.notify("notifications/marker", None)
with anyio.fail_after(5):
first = await c2s_recv.receive()
assert isinstance(first, SessionMessage)
assert first.message == JSONRPCNotification(jsonrpc="2.0", method="notifications/marker")
tg.cancel_scope.cancel()
finally:
await resync_tracer()
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
assert scopes[0].cancelled_caught
@pytest.mark.anyio
async def test_caller_cancel_with_resumption_hints_suppresses_the_courtesy_cancellation():
"""A request sent with resumption hints is meant to be resumed; abandoning it must not stop the peer's work."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, c2s_send)
on_request, on_notify = echo_handlers(Recorder())
async def on_token(token: str) -> None:
raise NotImplementedError
scopes: list[anyio.CancelScope] = []
gave_up = anyio.Event()
async def caller() -> None:
with anyio.CancelScope() as scope:
scopes.append(scope)
await client.send_raw_request("slow", None, {"on_resumption_token": on_token})
raise NotImplementedError # unreachable: the scope is cancelled
gave_up.set()
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
tg.start_soon(caller)
with anyio.fail_after(5):
request = await c2s_recv.receive()
assert isinstance(request, SessionMessage)
assert isinstance(request.message, JSONRPCRequest)
scopes[0].cancel()
with anyio.fail_after(5):
await gave_up.wait()
# A courtesy cancel would have to precede the marker on the ordered stream.
await client.notify("marker", None)
with anyio.fail_after(5):
nxt = await c2s_recv.receive()
assert isinstance(nxt, SessionMessage)
assert isinstance(nxt.message, JSONRPCNotification)
assert nxt.message.method == "marker"
tg.cancel_scope.cancel()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
@pytest.mark.anyio
async def test_timeout_with_resumption_hints_suppresses_the_courtesy_cancellation():
"""A timed-out request that carries resumption hints stays resumable: no cancellation is sent."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, c2s_send)
on_request, on_notify = echo_handlers(Recorder())
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
with anyio.fail_after(5):
with pytest.raises(MCPError) as exc:
await client.send_raw_request("slow", None, {"timeout": 0, "resumption_token": "tok"})
assert exc.value.error.code == REQUEST_TIMEOUT
with anyio.fail_after(5):
request = await c2s_recv.receive()
assert isinstance(request, SessionMessage)
assert isinstance(request.message, JSONRPCRequest)
await client.notify("marker", None)
with anyio.fail_after(5):
nxt = await c2s_recv.receive()
assert isinstance(nxt, SessionMessage)
assert isinstance(nxt.message, JSONRPCNotification)
assert nxt.message.method == "marker"
tg.cancel_scope.cancel()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
@pytest.mark.anyio
async def test_cancel_on_abandon_false_suppresses_the_courtesy_cancellation_on_timeout():
"""Callers opt out per call for requests the protocol forbids cancelling (initialize)."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, c2s_send)
on_request, on_notify = echo_handlers(Recorder())
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
with anyio.fail_after(5):
with pytest.raises(MCPError) as exc:
await client.send_raw_request("slow", None, {"timeout": 0, "cancel_on_abandon": False})
assert exc.value.error.code == REQUEST_TIMEOUT
with anyio.fail_after(5):
request = await c2s_recv.receive()
assert isinstance(request, SessionMessage)
assert isinstance(request.message, JSONRPCRequest)
await client.notify("marker", None)
with anyio.fail_after(5):
nxt = await c2s_recv.receive()
assert isinstance(nxt, SessionMessage)
assert isinstance(nxt.message, JSONRPCNotification)
assert nxt.message.method == "marker"
tg.cancel_scope.cancel()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
class TimingOutWriteStream:
"""`send()` raises builtin `TimeoutError`, like a custom transport whose bounded send expired."""
def __init__(self) -> None:
self.attempts = 0
self.error = TimeoutError("transport send timed out")
async def send(self, item: SessionMessage) -> None:
self.attempts += 1
raise self.error
async def aclose(self) -> None:
raise NotImplementedError # the dispatcher releases streams via __aexit__, never aclose
async def __aenter__(self) -> "TimingOutWriteStream":
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> bool | None:
return None
@pytest.mark.anyio
async def test_transport_write_timeout_propagates_raw_when_no_request_timeout_is_set():
"""A builtin TimeoutError from the transport's own bounded `send()` is a transport failure,
not `opts["timeout"]` elapsing — no timeout is set here, so `fail_after(None)` cannot have
fired — and must propagate raw instead of being mislabelled REQUEST_TIMEOUT. (Genuine expiry
after a completed write is pinned by the timeout tests above and
`test_timeout_courtesy_cancel_write_is_bounded_when_the_transport_is_wedged`.)"""
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
transport = TimingOutWriteStream()
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, transport)
on_request, on_notify = echo_handlers(Recorder())
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
with anyio.fail_after(5):
with pytest.raises(TimeoutError) as exc:
await client.send_raw_request("tools/call", {"name": "x"}, None)
assert exc.value is transport.error # the exact instance propagated unwrapped
# The request never reached the peer, so no courtesy cancel may follow the failed write.
assert transport.attempts == 1
tg.cancel_scope.cancel()
finally:
await resync_tracer()
s2c_send.close()
s2c_recv.close()
@pytest.mark.parametrize(
"anyio_backend",
[pytest.param(("trio", {"clock": MockClock(autojump_threshold=0)}), id="trio-mockclock")],
)
@pytest.mark.anyio
async def test_caller_cancel_courtesy_write_is_bounded_when_the_transport_is_wedged(
caplog: pytest.LogCaptureFixture,
):
"""A wedged transport write cannot turn caller cancellation into an unbounded shielded hang:
`_ABANDON_WRITE_TIMEOUT` abandons the courtesy-cancel write (SDK-defined bound). On regression
the test hangs rather than failing fast - fail_after cannot cancel through the shield."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](0)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](0)
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, c2s_send)
on_request, on_notify = echo_handlers(Recorder())
scopes: list[anyio.CancelScope] = []
gave_up = anyio.Event()
async def caller() -> None:
with anyio.CancelScope() as scope:
scopes.append(scope)
await client.send_raw_request("slow", None)
raise NotImplementedError # unreachable: the scope is cancelled
gave_up.set()
try:
# Both bounds exceed the in-loop _ABANDON_WRITE_TIMEOUT (5s); the virtual clock makes them instant.
with anyio.fail_after(30):
async with anyio.create_task_group() as tg: # pragma: no branch
await tg.start(client.run, on_request, on_notify)
tg.start_soon(caller)
# Consume only the request; the later courtesy cancel finds no reader and wedges.
request = await c2s_recv.receive()
assert isinstance(request, SessionMessage)
assert isinstance(request.message, JSONRPCRequest)
scopes[0].cancel()
with anyio.fail_after(20):
await gave_up.wait()
tg.cancel_scope.cancel()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
assert scopes[0].cancelled_caught
# The warning proves it was the bound (not a completed write) that released the shield.
assert "courtesy cancel for caller-cancelled request" in caplog.text
@pytest.mark.parametrize(
"anyio_backend",
[pytest.param(("trio", {"clock": MockClock(autojump_threshold=0)}), id="trio-mockclock")],
)
@pytest.mark.anyio
async def test_timeout_courtesy_cancel_write_is_bounded_when_the_transport_is_wedged(
caplog: pytest.LogCaptureFixture,
):
"""A wedged transport write cannot delay the REQUEST_TIMEOUT error indefinitely (SDK-defined
bound): `_ABANDON_WRITE_TIMEOUT` abandons the courtesy cancel so the error still surfaces."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](0)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](0)
client: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(s2c_recv, c2s_send)
on_request, on_notify = echo_handlers(Recorder())
errors: list[MCPError] = []
gave_up = anyio.Event()
async def caller() -> None:
with pytest.raises(MCPError) as exc:
await client.send_raw_request("slow", None, {"timeout": 1})
errors.append(exc.value)
gave_up.set()
try:
async with anyio.create_task_group() as tg:
await tg.start(client.run, on_request, on_notify)
tg.start_soon(caller)
# Consume only the request; the later courtesy cancel finds no reader and wedges.
with anyio.fail_after(5):
request = await c2s_recv.receive()
assert isinstance(request, SessionMessage)
assert isinstance(request.message, JSONRPCRequest)
# Exceeds the request timeout (1s) plus _ABANDON_WRITE_TIMEOUT (5s); virtual clock, no wall time.
with anyio.fail_after(10):
await gave_up.wait()
tg.cancel_scope.cancel()
finally:
for s in (c2s_send, c2s_recv, s2c_send, s2c_recv):
s.close()
assert errors[0].error.code == REQUEST_TIMEOUT
assert "courtesy cancel for timed-out request" in caplog.text
@pytest.mark.parametrize(
"anyio_backend",
[pytest.param(("trio", {"clock": MockClock(autojump_threshold=0)}), id="trio-mockclock")],
)
@pytest.mark.anyio
async def test_shutdown_error_response_write_is_bounded_when_the_transport_is_wedged(
caplog: pytest.LogCaptureFixture,
):
"""Cancelling the task group hosting run() completes even when the shutdown error write wedges:
only `_SHUTDOWN_WRITE_TIMEOUT` releases the join (SDK-defined). A 0-buffer stream nobody reads
expresses the wedge: run() closes its write stream only after the join, so the send stays parked."""
c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](1)
s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage | Exception](0)
server: JSONRPCDispatcher[TransportContext] = JSONRPCDispatcher(c2s_recv, s2c_send)
handler_started = anyio.Event()
async def park(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> dict[str, Any]:
handler_started.set()
await anyio.sleep_forever()
raise NotImplementedError
async def on_notify(ctx: DCtx, method: str, params: Mapping[str, Any] | None) -> None:
raise NotImplementedError
try: