-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathtest_client_caching.py
More file actions
1577 lines (1208 loc) · 66.3 KB
/
Copy pathtest_client_caching.py
File metadata and controls
1577 lines (1208 loc) · 66.3 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
"""`Client` wiring for the response cache: the `cache=` kwarg, server identity
resolution, the custom-store guard, notification eviction, and the five cacheable
verbs. The coordinator's own behavior is covered in `test_caching.py`."""
import hashlib
import json
import time
from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import asynccontextmanager
from types import TracebackType
from typing import Any, Literal
import anyio
import anyio.lowlevel
import httpx2
import mcp_types as types
import pytest
from inline_snapshot import snapshot
from mcp_types import (
INTERNAL_ERROR,
INVALID_PARAMS,
CallToolResult,
DiscoverResult,
ElicitRequest,
ElicitRequestFormParams,
ElicitResult,
InputRequiredResult,
ListPromptsResult,
ListResourcesResult,
ListResourceTemplatesResult,
ListToolsResult,
ReadResourceResult,
ResourceListChangedNotification,
ResourceUpdatedNotification,
ResourceUpdatedNotificationParams,
ServerCapabilities,
ServerNotification,
TextContent,
TextResourceContents,
Tool,
ToolListChangedNotification,
)
from mcp_types.version import LATEST_MODERN_VERSION
from mcp.client import Client
from mcp.client._transport import TransportStreams
from mcp.client.caching import (
CacheConfig,
CacheEntry,
CacheKey,
ClientResponseCache,
InMemoryResponseCacheStore,
)
from mcp.client.streamable_http import streamable_http_client
from mcp.server import Server, ServerRequestContext
from mcp.server.caching import CacheHint
from mcp.shared.exceptions import MCPError
from mcp.shared.memory import MessageStream, create_client_server_memory_streams
from mcp.shared.message import SessionMessage
from mcp.shared.session import RequestResponder
from tests.interaction._connect import BASE_URL, mounted_app
pytestmark = pytest.mark.anyio
IncomingMessage = RequestResponder[types.ServerRequest, types.ClientResult] | types.ServerNotification | Exception
def _coordinator(client: Client) -> ClientResponseCache:
cache = client._response_cache
assert cache is not None
return cache
def _private_arm(client: Client) -> str:
"""The identity arm stamped into store keys; only equality between clients matters here."""
return _coordinator(client)._arm("private")
def _tools_list_key(client: Client) -> CacheKey:
return CacheKey("tools/list", "", _private_arm(client))
class _OpaqueTransport:
"""Shape-only `Transport`: identity resolution happens at construction, so tests never enter it."""
async def __aenter__(self) -> TransportStreams:
raise NotImplementedError
async def __aexit__(
self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
) -> None:
raise NotImplementedError
def _list_changed_server() -> Server[Any]:
"""Server whose `touch` tool emits tools/list_changed; connect with `mode="legacy"`
because the modern in-process path drops standalone server notifications."""
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
return ListToolsResult(tools=[types.Tool(name="touch", input_schema={"type": "object"})])
async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult:
assert params.name == "touch"
await ctx.session.send_tool_list_changed()
return CallToolResult(content=[TextContent(text="touched")])
return Server("notifier", on_list_tools=list_tools, on_call_tool=call_tool)
async def _warm_tools_list_entry(client: Client) -> CacheKey:
"""Seed a private-arm tools/list entry directly in the store; payload and expiry are inert to eviction."""
key = _tools_list_key(client)
await _coordinator(client)._store.set(key, CacheEntry(value="warm", scope="private", expires_at=None))
return key
def test_an_explicit_target_id_overrides_both_url_and_in_process_identity() -> None:
by_target_url = Client("https://example.com/mcp", cache=CacheConfig(target_id="svc"))
by_target_inproc = Client(Server("plain"), cache=CacheConfig(target_id="svc"))
by_url = Client("https://example.com/mcp")
assert _private_arm(by_target_url) == _private_arm(by_target_inproc)
assert _private_arm(by_target_url) != _private_arm(by_url)
def test_userinfo_variants_of_a_server_url_share_one_cache_identity() -> None:
"""Stripping userinfo is the single permitted URL rewrite."""
bare = Client("https://example.com/mcp")
with_password = Client("https://user:secret@example.com/mcp")
with_token = Client("https://token@example.com/mcp")
assert _private_arm(bare) == _private_arm(with_password) == _private_arm(with_token)
@pytest.mark.parametrize(
("with_userinfo", "bare"),
[
("HTTPS://a@X.example/mcp", "HTTPS://X.example/mcp"),
("https://u@h/p?", "https://h/p?"),
("https://u@h/p#", "https://h/p#"),
("https://u\tser:p@h.example/p", "https://h.example/p"),
("https://u:p@h.example/pa\tth", "https://h.example/pa\tth"),
],
ids=["scheme-case", "empty-query", "empty-fragment", "tab-in-userinfo", "tab-in-path"],
)
def test_stripping_userinfo_changes_no_other_byte_of_the_url(with_userinfo: str, bare: str) -> None:
"""The removed `userinfo@` is the only byte difference: no scheme case-folding, no dropped
empty `?`/`#` delimiters, and control characters - which urlsplit would silently strip,
misaligning any parser-derived slice - stay byte-exact outside the removed span. A
userinfo-free URL passes through untouched, so arm equality proves the stripped form is
byte-identical to the bare URL."""
assert _private_arm(Client(with_userinfo)) == _private_arm(Client(bare))
def test_a_url_without_an_authority_passes_through_unchanged() -> None:
"""No `//` means no authority span, so an `@` elsewhere strips nothing."""
arm_id = hashlib.sha256(b"mailto:a@b").hexdigest()
assert _private_arm(Client("mailto:a@b")) == json.dumps(["private", None, arm_id, ""])
def test_the_server_url_is_sha256_hashed_before_it_enters_key_material() -> None:
"""Pins the docs' secrets-never-in-keys claim: a query-string secret never appears in store keys."""
client = Client("https://user:pass@example.com/mcp?api_key=SECRET")
arm_id = hashlib.sha256(b"https://example.com/mcp?api_key=SECRET").hexdigest()
# The era slot is None pre-connect; only the identity hash matters here.
assert _private_arm(client) == json.dumps(["private", None, arm_id, ""])
def test_urls_differing_only_in_query_have_distinct_cache_identities() -> None:
"""URL identity is byte-exact outside userinfo; over-normalization would merge tenants."""
tenant_a = Client("https://example.com/mcp?tenant=a")
tenant_b = Client("https://example.com/mcp?tenant=b")
assert _private_arm(tenant_a) != _private_arm(tenant_b)
def test_two_clients_on_one_in_process_server_get_distinct_cache_identities() -> None:
server = Server("plain")
assert _private_arm(Client(server)) != _private_arm(Client(server))
def test_a_transport_object_gets_a_per_client_cache_identity() -> None:
transport = _OpaqueTransport()
assert _private_arm(Client(transport)) != _private_arm(Client(transport))
@pytest.mark.parametrize("make_server", [lambda: Server("plain"), _OpaqueTransport], ids=["in-process", "transport"])
def test_a_custom_store_without_a_url_or_target_id_is_rejected(make_server: Any) -> None:
with pytest.raises(ValueError) as exc_info:
Client(make_server(), cache=CacheConfig(store=InMemoryResponseCacheStore(), partition="p"))
assert str(exc_info.value) == snapshot(
"a custom cache store requires CacheConfig.target_id when the server is not a URL: in-process servers "
"and Transport instances get a random per-client identity, so their entries in a shared store could "
"never be served to another client"
)
def test_a_custom_store_with_a_url_server_constructs_and_is_used() -> None:
store = InMemoryResponseCacheStore()
client = Client("https://example.com/mcp", cache=CacheConfig(store=store, partition="p"))
assert _coordinator(client)._store is store
def test_a_custom_store_with_an_explicit_target_id_constructs_for_any_server() -> None:
store = InMemoryResponseCacheStore()
client = Client(Server("plain"), cache=CacheConfig(store=store, partition="p", target_id="svc"))
assert _coordinator(client)._store is store
async def test_cache_none_disables_the_cache_and_the_handler_wrap() -> None:
async def handler(message: IncomingMessage) -> None:
raise NotImplementedError
client = Client(_list_changed_server(), cache=None, message_handler=handler)
assert client._response_cache is None
async with client:
assert client.session._message_handler is handler
def test_the_default_cache_uses_a_per_client_in_memory_store() -> None:
"""The default `CacheConfig()` is cache-on."""
server = Server("plain")
first = Client(server)
second = Client(server)
assert isinstance(_coordinator(first)._store, InMemoryResponseCacheStore)
assert _coordinator(first)._store is not _coordinator(second)._store
async def test_the_negotiated_version_supplier_tracks_the_session_lifecycle() -> None:
"""The era gate must never read a stale or raising source."""
client = Client(_list_changed_server())
supplier = _coordinator(client)._negotiated_version
assert supplier() is None
async with client:
assert supplier() == client.protocol_version
assert supplier() is None
async def test_a_list_changed_notification_evicts_without_a_user_handler() -> None:
"""Spec SHOULD (notifications invalidate): the entry is deleted from both arms."""
class _EventedStore(InMemoryResponseCacheStore):
"""Signals once both arms of an eviction have been deleted."""
def __init__(self) -> None:
super().__init__()
self._deletes = 0
self.both_arms_deleted = anyio.Event()
async def delete(self, key: CacheKey) -> None:
await super().delete(key)
self._deletes += 1
if self._deletes == 2:
self.both_arms_deleted.set()
store = _EventedStore()
client = Client(
_list_changed_server(), mode="legacy", cache=CacheConfig(store=store, partition="p", target_id="svc")
)
async with client:
key = await _warm_tools_list_entry(client)
await client.call_tool("touch", {})
with anyio.fail_after(5):
await store.both_arms_deleted.wait()
assert await store.get(key) is None
async def test_a_user_handler_receives_the_notification_the_eviction_consumed() -> None:
"""Eviction is a tee, not a filter."""
received: list[IncomingMessage] = []
seen = anyio.Event()
async def collect(message: IncomingMessage) -> None:
received.append(message)
seen.set()
client = Client(_list_changed_server(), mode="legacy", message_handler=collect)
async with client:
key = await _warm_tools_list_entry(client)
await client.call_tool("touch", {})
with anyio.fail_after(5):
await seen.wait()
# The wrap evicts before delegating: delivery implies the entry is gone.
assert await _coordinator(client)._store.get(key) is None
assert received == snapshot([ToolListChangedNotification()])
async def test_non_notification_items_pass_through_to_the_user_handler_untouched() -> None:
"""Transport `Exception` items can't occur in-process, so the installed handler is invoked directly."""
received: list[IncomingMessage] = []
async def collect(message: IncomingMessage) -> None:
received.append(message)
client = Client(_list_changed_server(), message_handler=collect)
async with client:
installed = client.session._message_handler
assert installed is not collect # the wrap, not the bare user handler
key = await _warm_tools_list_entry(client)
fault = RuntimeError("stream broke")
await installed(fault)
assert received == [fault]
assert await _coordinator(client)._store.get(key) is not None
async def test_a_raising_eviction_does_not_block_notification_delivery(caplog: pytest.LogCaptureFixture) -> None:
class _ExplodingCache(ClientResponseCache):
async def evict_for_notification(self, notification: ServerNotification) -> None:
raise RuntimeError("cache bug")
received: list[IncomingMessage] = []
seen = anyio.Event()
async def collect(message: IncomingMessage) -> None:
received.append(message)
seen.set()
client = Client(_list_changed_server(), mode="legacy", message_handler=collect)
# The wrap reads `_response_cache` at session build, so the swap must happen pre-enter.
client._response_cache = _ExplodingCache(
store=InMemoryResponseCacheStore(),
partition="",
arm_id="arm",
default_ttl_ms=0,
clock=time.time,
share_public=False,
negotiated_version=lambda: None,
)
async with client:
await client.call_tool("touch", {})
with anyio.fail_after(5):
await seen.wait()
assert received == snapshot([ToolListChangedNotification()])
assert "Response cache eviction failed; the notification is still delivered" in [
record.message for record in caplog.records
]
# --- The cacheable verbs ---
class _ManualClock:
"""Injected wall clock: tests advance `now` instead of sleeping."""
def __init__(self) -> None:
self.now = 1_000_000.0
def __call__(self) -> float:
return self.now
def _varying_tools_server(
*, ttl_ms: int = 60_000, scope: Literal["public", "private"] = "private"
) -> tuple[Server[Any], list[str | None]]:
"""Server whose every tools/list fetch returns a distinct tool name `t<n>`,
so a served entry is distinguishable from a refetch by payload."""
fetches: list[str | None] = []
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
fetches.append(params.cursor if params is not None else None)
return ListToolsResult(tools=[Tool(name=f"t{len(fetches) - 1}", input_schema={"type": "object"})])
server = Server(
"varying", on_list_tools=list_tools, cache_hints={"tools/list": CacheHint(ttl_ms=ttl_ms, scope=scope)}
)
return server, fetches
def _tool_names(result: ListToolsResult) -> list[str]:
return [tool.name for tool in result.tools]
async def test_a_second_list_tools_within_the_ttl_is_served_from_the_cache() -> None:
"""SEP-2549: a result carrying a `ttlMs` hint is reusable until it expires."""
server, fetches = _varying_tools_server()
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
first = await client.list_tools()
second = await client.list_tools()
assert fetches == [None]
assert second == first
async def test_an_expired_entry_is_refetched() -> None:
"""Freshness is strict: at exactly `ttlMs` the entry is expired."""
clock = _ManualClock()
server, fetches = _varying_tools_server(ttl_ms=60_000)
async with Client(server, cache=CacheConfig(clock=clock)) as client:
assert _tool_names(await client.list_tools()) == ["t0"]
clock.now += 60.0
assert _tool_names(await client.list_tools()) == ["t1"]
assert fetches == [None, None]
async def test_each_list_verb_caches_independently_under_its_own_method() -> None:
"""Cache keys discriminate by method (spec MUST)."""
fetched: list[str] = []
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
fetched.append("tools/list")
return ListToolsResult(tools=[])
async def list_prompts(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListPromptsResult:
fetched.append("prompts/list")
return ListPromptsResult(prompts=[])
async def list_resources(
ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
) -> ListResourcesResult:
fetched.append("resources/list")
return ListResourcesResult(resources=[])
async def list_templates(
ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
) -> ListResourceTemplatesResult:
fetched.append("resources/templates/list")
return ListResourceTemplatesResult(resource_templates=[])
hint = CacheHint(ttl_ms=60_000)
server = Server(
"all-lists",
on_list_tools=list_tools,
on_list_prompts=list_prompts,
on_list_resources=list_resources,
on_list_resource_templates=list_templates,
cache_hints={
"tools/list": hint,
"prompts/list": hint,
"resources/list": hint,
"resources/templates/list": hint,
},
)
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
await client.list_tools()
await client.list_prompts()
await client.list_resources()
await client.list_resource_templates()
await client.list_tools()
await client.list_prompts()
await client.list_resources()
await client.list_resource_templates()
assert fetched == ["tools/list", "prompts/list", "resources/list", "resources/templates/list"]
async def test_read_resource_caches_per_uri() -> None:
"""Cache keys discriminate by result-affecting params (spec MUST)."""
reads: list[str] = []
async def read(ctx: ServerRequestContext, params: types.ReadResourceRequestParams) -> ReadResourceResult:
reads.append(params.uri)
return ReadResourceResult(contents=[TextResourceContents(uri=params.uri, text=params.uri)])
server = Server("res", on_read_resource=read, cache_hints={"resources/read": CacheHint(ttl_ms=60_000)})
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
first_a = await client.read_resource("memo://a")
first_b = await client.read_resource("memo://b")
assert await client.read_resource("memo://a") == first_a
assert await client.read_resource("memo://b") == first_b
assert reads == ["memo://a", "memo://b"]
def _paginated_tools_server() -> tuple[Server[Any], list[str | None]]:
"""Cacheable first page; cursor "expired" -> INVALID_PARAMS (the spec's expired-cursor
signal), "fail" -> INTERNAL_ERROR."""
fetches: list[str | None] = []
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
cursor = params.cursor if params is not None else None
fetches.append(cursor)
if cursor is None:
first_page = Tool(name="first-page", input_schema={"type": "object"})
return ListToolsResult(tools=[first_page], next_cursor="page-2")
if cursor == "page-2":
return ListToolsResult(tools=[Tool(name="second-page", input_schema={"type": "object"})])
if cursor == "fail":
raise MCPError(code=INTERNAL_ERROR, message="transient failure")
raise MCPError(code=INVALID_PARAMS, message=f"Unknown cursor: {cursor!r}")
server = Server("paginated", on_list_tools=list_tools, cache_hints={"tools/list": CacheHint(ttl_ms=60_000)})
return server, fetches
async def test_cursor_continuations_neither_read_nor_write_the_cache() -> None:
"""Only cursor-less calls participate in caching (SDK-defined single-page entry)."""
server, fetches = _paginated_tools_server()
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
assert _tool_names(await client.list_tools()) == ["first-page"]
assert _tool_names(await client.list_tools(cursor="page-2")) == ["second-page"]
assert _tool_names(await client.list_tools()) == ["first-page"] # not overwritten by the continuation
assert fetches == [None, "page-2"]
async def test_an_expired_cursor_rejection_evicts_the_methods_entry() -> None:
"""Spec SHOULD: INVALID_PARAMS on a continuation cursor means the listing changed."""
server, fetches = _paginated_tools_server()
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
await client.list_tools()
with pytest.raises(MCPError) as exc_info:
await client.list_tools(cursor="expired")
assert exc_info.value.code == INVALID_PARAMS
await client.list_tools()
assert fetches == [None, "expired", None]
async def test_an_expired_cursor_rejection_under_bypass_does_not_evict() -> None:
"""Bypass means no cache side-effects at all, eviction included."""
server, fetches = _paginated_tools_server()
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
await client.list_tools()
with pytest.raises(MCPError) as exc_info:
await client.list_tools(cursor="expired", cache_mode="bypass")
assert exc_info.value.code == INVALID_PARAMS
await client.list_tools() # still served from the warm entry
assert fetches == [None, "expired"]
async def test_a_non_cursor_error_on_a_continuation_does_not_evict() -> None:
"""Only INVALID_PARAMS signals cursor expiry."""
server, fetches = _paginated_tools_server()
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
await client.list_tools()
with pytest.raises(MCPError) as exc_info:
await client.list_tools(cursor="fail")
assert exc_info.value.code == INTERNAL_ERROR
await client.list_tools() # still served from the warm entry
assert fetches == [None, "fail"]
async def test_bypass_neither_serves_nor_disturbs_a_warm_entry() -> None:
server, fetches = _varying_tools_server()
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
assert _tool_names(await client.list_tools()) == ["t0"]
assert _tool_names(await client.list_tools(cache_mode="bypass")) == ["t1"]
assert _tool_names(await client.list_tools()) == ["t0"] # warm entry intact
assert fetches == [None, None]
async def test_refresh_skips_the_read_and_stores_the_refetched_result() -> None:
server, fetches = _varying_tools_server()
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
assert _tool_names(await client.list_tools()) == ["t0"]
assert _tool_names(await client.list_tools(cache_mode="refresh")) == ["t1"]
assert _tool_names(await client.list_tools()) == ["t1"]
assert fetches == [None, None]
async def test_refresh_storing_a_ttl_zero_result_purges_the_warm_entry() -> None:
"""An uncacheable refetch still supersedes the warm entry."""
fetches: list[str | None] = []
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
fetches.append(params.cursor if params is not None else None)
ttl_ms = 60_000 if len(fetches) == 1 else 0
tool = Tool(name=f"t{len(fetches) - 1}", input_schema={"type": "object"})
return ListToolsResult(tools=[tool], ttl_ms=ttl_ms)
server = Server("flip", on_list_tools=list_tools)
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
assert _tool_names(await client.list_tools()) == ["t0"]
assert _tool_names(await client.list_tools(cache_mode="refresh")) == ["t1"]
assert _tool_names(await client.list_tools()) == ["t2"] # t0 purged, t1 (ttl 0) never stored
assert fetches == [None, None, None]
async def test_a_list_call_carrying_meta_is_fetched_and_replaces_the_warm_entry() -> None:
"""SDK-defined: `meta` (a progress token, tracing fields) expects a wire request,
so under the default "use" the call behaves as a refresh."""
server, fetches = _varying_tools_server()
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
assert _tool_names(await client.list_tools()) == ["t0"]
assert _tool_names(await client.list_tools()) == ["t0"] # warm, meta-less: served
assert _tool_names(await client.list_tools(meta={"progress_token": "tok"})) == ["t1"] # meta: fetched
assert _tool_names(await client.list_tools()) == ["t1"] # the fresh result replaced the entry
assert fetches == [None, None]
async def test_a_read_resource_carrying_meta_is_fetched_and_replaces_the_warm_entry() -> None:
reads: list[str] = []
async def read(ctx: ServerRequestContext, params: types.ReadResourceRequestParams) -> ReadResourceResult:
reads.append(params.uri)
return ReadResourceResult(contents=[TextResourceContents(uri=params.uri, text=f"v{len(reads)}")], ttl_ms=60_000)
server = Server("versioned-reads", on_read_resource=read)
def text(result: ReadResourceResult) -> str:
content = result.contents[0]
assert isinstance(content, TextResourceContents)
return content.text
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
assert text(await client.read_resource("memo://a")) == "v1"
assert text(await client.read_resource("memo://a")) == "v1" # warm, meta-less: served
assert text(await client.read_resource("memo://a", meta={"progress_token": "tok"})) == "v2" # meta: fetched
assert text(await client.read_resource("memo://a")) == "v2" # the fresh result replaced the entry
assert reads == ["memo://a", "memo://a"]
async def test_cache_mode_is_inert_when_caching_is_disabled() -> None:
server, fetches = _varying_tools_server()
async with Client(server, cache=None) as client:
await client.list_tools()
await client.list_tools(cache_mode="use")
await client.list_tools(cache_mode="refresh")
assert fetches == [None, None, None]
@pytest.mark.parametrize(
"seed",
[{"request_state": "round-2"}, {"input_responses": {"ask": ElicitResult(action="decline")}}],
ids=["request_state", "input_responses"],
)
async def test_a_seeded_read_resource_skips_the_cache_and_ignores_cache_mode(seed: dict[str, Any]) -> None:
"""Spec MUST: results of requests carrying `inputResponses` or `requestState` are never cached."""
reads = 0
async def read(ctx: ServerRequestContext, params: types.ReadResourceRequestParams) -> ReadResourceResult:
nonlocal reads
reads += 1
return ReadResourceResult(contents=[TextResourceContents(uri=params.uri, text=f"v{reads}")], ttl_ms=60_000)
server = Server("res", on_read_resource=read)
def text(result: ReadResourceResult) -> str:
content = result.contents[0]
assert isinstance(content, TextResourceContents)
return content.text
async with Client(server, cache=CacheConfig(clock=_ManualClock())) as client:
assert text(await client.read_resource("memo://a")) == "v1"
assert text(await client.read_resource("memo://a", **seed)) == "v2"
assert text(await client.read_resource("memo://a", **seed, cache_mode="refresh")) == "v3"
assert text(await client.read_resource("memo://a")) == "v1" # nothing read, written, or purged
assert reads == 3
async def test_a_terminal_read_reached_through_driver_rounds_is_never_cached() -> None:
"""Spec MUST: the driver's retry rounds carry `inputResponses`, so their terminal result is not cached."""
seeded_rounds: list[bool] = []
ask = ElicitRequest(
params=ElicitRequestFormParams(
message="What is your name?",
requested_schema={"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]},
)
)
async def read(
ctx: ServerRequestContext, params: types.ReadResourceRequestParams
) -> ReadResourceResult | InputRequiredResult:
seeded_rounds.append(params.input_responses is not None)
if params.input_responses is not None:
return ReadResourceResult(contents=[TextResourceContents(uri=params.uri, text="terminal")], ttl_ms=60_000)
return InputRequiredResult(input_requests={"ask": ask})
async def elicitation_callback(
context: Any, params: types.ElicitRequestParams
) -> types.ElicitResult | types.ErrorData:
return ElicitResult(action="accept", content={"name": "Ada"})
server = Server("gated", on_read_resource=read)
with anyio.fail_after(5):
async with Client(
server, elicitation_callback=elicitation_callback, cache=CacheConfig(clock=_ManualClock())
) as client:
first = await client.read_resource("memo://gated")
second = await client.read_resource("memo://gated")
assert isinstance(first.contents[0], TextResourceContents) and first.contents[0].text == "terminal"
assert second == first
assert seeded_rounds == [False, True, False, True] # two wire rounds per call: never served
async def test_a_refresh_that_resolves_to_input_required_purges_the_warm_entry() -> None:
"""The refresh cannot store its driven terminal result (the rounds carry
`inputResponses`, a spec MUST), but it still purges the warm entry."""
reads = 0
ask = ElicitRequest(
params=ElicitRequestFormParams(
message="What is your name?",
requested_schema={"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]},
)
)
async def read(
ctx: ServerRequestContext, params: types.ReadResourceRequestParams
) -> ReadResourceResult | InputRequiredResult:
nonlocal reads
reads += 1
# Starts plain, then flips to requiring input.
if reads > 1 and params.input_responses is None:
return InputRequiredResult(input_requests={"ask": ask})
return ReadResourceResult(contents=[TextResourceContents(uri=params.uri, text=f"v{reads}")], ttl_ms=60_000)
async def elicitation_callback(
context: Any, params: types.ElicitRequestParams
) -> types.ElicitResult | types.ErrorData:
return ElicitResult(action="accept", content={"name": "Ada"})
server = Server("flipping", on_read_resource=read)
def text(result: ReadResourceResult) -> str:
content = result.contents[0]
assert isinstance(content, TextResourceContents)
return content.text
with anyio.fail_after(5):
async with Client(
server, elicitation_callback=elicitation_callback, cache=CacheConfig(clock=_ManualClock())
) as client:
assert text(await client.read_resource("memo://a")) == "v1" # cached for 60s
assert text(await client.read_resource("memo://a", cache_mode="refresh")) == "v3"
# v1 purged and v3 never stored: the plain read drives fresh rounds.
assert text(await client.read_resource("memo://a")) == "v5"
assert reads == 5
def _output_schema_server(call_result: CallToolResult) -> tuple[Server[Any], list[str | None]]:
"""One tool declaring an output schema; `call_tool` returns the canned `call_result`."""
fetches: list[str | None] = []
tool = Tool(
name="run",
input_schema={"type": "object"},
output_schema={"type": "object", "properties": {"n": {"type": "integer"}}, "required": ["n"]},
)
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
fetches.append(params.cursor if params is not None else None)
return ListToolsResult(tools=[tool])
async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult:
assert params.name == "run"
return call_result
server = Server(
"schemas",
on_list_tools=list_tools,
on_call_tool=call_tool,
cache_hints={"tools/list": CacheHint(ttl_ms=60_000)},
)
return server, fetches
async def test_a_listing_served_from_a_shared_store_rebuilds_output_schemas() -> None:
"""A served listing is absorbed into the session: output validation works without a wire fetch."""
call_result = CallToolResult(content=[TextContent(text="ok")], structured_content={"n": 1})
server, fetches = _output_schema_server(call_result)
config = CacheConfig(store=InMemoryResponseCacheStore(), partition="p", target_id="svc", clock=_ManualClock())
async with Client(server, cache=config) as warming:
listing = await warming.list_tools()
async with Client(server, cache=config) as fresh:
assert await fresh.list_tools() == listing # served from the shared store
result = await fresh.call_tool("run", {})
assert result.structured_content == {"n": 1}
# A starved schema cache would have re-listed here.
assert fetches == [None]
async def test_validation_from_a_served_listing_rejects_missing_structured_content() -> None:
"""The schema absorbed from a served listing is enforced, not just present."""
server, fetches = _output_schema_server(CallToolResult(content=[TextContent(text="ok")]))
config = CacheConfig(store=InMemoryResponseCacheStore(), partition="p", target_id="svc", clock=_ManualClock())
async with Client(server, cache=config) as warming:
await warming.list_tools()
async with Client(server, cache=config) as fresh:
await fresh.list_tools()
with pytest.raises(RuntimeError) as exc_info:
await fresh.call_tool("run", {})
assert str(exc_info.value) == snapshot("Tool run has an output schema but did not return structured content")
assert fetches == [None]
async def test_a_cache_hit_listing_still_mirrors_x_mcp_headers_on_tools_call() -> None:
"""The arg-to-header maps are rebuilt from a served listing. Asserted at the wire
because the client never surfaces outgoing headers."""
tool = Tool(
name="run",
input_schema={"type": "object", "properties": {"region": {"type": "string", "x-mcp-header": "Region"}}},
)
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
return ListToolsResult(tools=[tool], ttl_ms=60_000)
async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult:
assert params.name == "run"
return CallToolResult(content=[TextContent(text="ok")])
server = Server("headers", on_list_tools=list_tools, on_call_tool=call_tool)
posts: list[httpx2.Request] = []
async def on_request(request: httpx2.Request) -> None:
posts.append(request)
config = CacheConfig(store=InMemoryResponseCacheStore(), partition="p", target_id="svc")
discover = DiscoverResult(
supported_versions=[LATEST_MODERN_VERSION],
capabilities=ServerCapabilities(),
)
with anyio.fail_after(5):
async with mounted_app(server, on_request=on_request) as (http, _):
warming = Client(
streamable_http_client(f"{BASE_URL}/mcp", http_client=http),
mode=LATEST_MODERN_VERSION,
prior_discover=discover,
cache=config,
)
async with warming:
await warming.list_tools()
fresh = Client(
streamable_http_client(f"{BASE_URL}/mcp", http_client=http),
mode=LATEST_MODERN_VERSION,
prior_discover=discover,
cache=config,
)
async with fresh:
await fresh.list_tools()
await fresh.call_tool("run", {"region": "us-west1"})
# One tools/list on the wire: the fresh client served from the store.
assert [json.loads(request.content)["method"] for request in posts] == ["tools/list", "tools/call"]
assert posts[-1].headers["mcp-param-region"] == "us-west1"
async def test_a_shared_store_hit_prunes_a_header_map_the_writers_filter_dropped() -> None:
"""Cached listings are post-filter: when another client's refresh wrote a listing whose
filter dropped tool `x` (its annotation went invalid), a hit on that entry must prune the
reader's stale arg-to-header map, or it would keep emitting Mcp-Param-* headers for `x`."""
valid = {"type": "object", "properties": {"region": {"type": "string", "x-mcp-header": "Region"}}}
invalid = {"type": "object", "properties": {"region": {"type": "string", "x-mcp-header": "bad name"}}}
schema = valid
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
return ListToolsResult(tools=[Tool(name="x", input_schema=schema)])
server = Server("filtering", on_list_tools=list_tools, cache_hints={"tools/list": CacheHint(ttl_ms=60_000)})
config = CacheConfig(store=InMemoryResponseCacheStore(), partition="p", target_id="svc", clock=_ManualClock())
with anyio.fail_after(5):
async with Client(server, cache=config) as reader, Client(server, cache=config) as writer:
await reader.list_tools() # fetches while `x` is valid; the reader holds its header map
assert "x" in reader.session._x_mcp_header_maps
schema = invalid
await writer.list_tools(cache_mode="refresh") # the writer's filter drops `x`; the entry is replaced
served = await reader.list_tools() # hit on the writer's entry
assert served.tools == []
assert "x" not in reader.session._x_mcp_header_maps
async def test_a_tools_list_changed_notification_makes_the_next_list_refetch() -> None:
"""Spec SHOULD: list_changed invalidates the cached listing. Legacy session +
`default_ttl_ms` entry: eviction is era-independent."""
fetches: list[str | None] = []
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
fetches.append(params.cursor if params is not None else None)
return ListToolsResult(tools=[Tool(name="touch", input_schema={"type": "object"})])
async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult:
assert params.name == "touch"
await ctx.session.send_tool_list_changed()
return CallToolResult(content=[TextContent(text="ok")])
server = Server("notify", on_list_tools=list_tools, on_call_tool=call_tool)
# The wrap evicts before delegating: delivery implies eviction completed.
delivered = anyio.Event()
async def on_message(message: IncomingMessage) -> None:
assert isinstance(message, ToolListChangedNotification) # the only message this server emits
delivered.set()
client = Client(server, mode="legacy", cache=CacheConfig(default_ttl_ms=60_000), message_handler=on_message)
async with client:
await client.list_tools()
await client.list_tools()
assert fetches == [None] # cached via default_ttl_ms
await client.call_tool("touch", {})
with anyio.fail_after(5):
await delivered.wait()
await client.list_tools()
assert fetches == [None, None]
async def test_a_resource_updated_notification_evicts_that_uris_read_entry() -> None:
"""Spec SHOULD: resources/updated invalidates the cached read for its uri,
and the notification's `params.uri` must match the stored key's uri form."""
uri = "memo://cached"
reads: list[str] = []
async def read(ctx: ServerRequestContext, params: types.ReadResourceRequestParams) -> ReadResourceResult:
reads.append(params.uri)
return ReadResourceResult(contents=[TextResourceContents(uri=params.uri, text=f"v{len(reads)}")])
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
return ListToolsResult(tools=[Tool(name="poke", input_schema={"type": "object"})])
async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult:
assert params.name == "poke"
await ctx.session.send_resource_updated(uri)
return CallToolResult(content=[TextContent(text="ok")])
server = Server("updates", on_read_resource=read, on_list_tools=list_tools, on_call_tool=call_tool)
delivered: list[str] = []
seen = anyio.Event()
async def on_message(message: IncomingMessage) -> None:
assert isinstance(message, ResourceUpdatedNotification) # the only message this server emits
delivered.append(message.params.uri)
seen.set()
client = Client(server, mode="legacy", cache=CacheConfig(default_ttl_ms=60_000), message_handler=on_message)
async with client:
await client.read_resource(uri)
await client.read_resource(uri)
assert reads == [uri] # cached via default_ttl_ms
await client.call_tool("poke", {})
with anyio.fail_after(5):
await seen.wait()
await client.read_resource(uri)
assert delivered == [uri] # the exact string the entry was stored under
assert reads == [uri, uri]
async def test_the_modern_in_process_path_drops_the_eviction_notification() -> None:
"""Pins the documented gap: the default in-process path (DirectDispatcher) drops
standalone notifications, so the warm entry survives. If this starts failing the
path gained delivery: flip the `docs/client/caching.md` caveat and the legacy-mode tests."""
fetches: list[str | None] = []
async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult:
fetches.append(params.cursor if params is not None else None)
return ListToolsResult(tools=[Tool(name="touch", input_schema={"type": "object"})])
async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult:
assert params.name == "touch"
await ctx.session.send_tool_list_changed()
return CallToolResult(content=[TextContent(text="ok")])
server = Server(
"notify",
on_list_tools=list_tools,
on_call_tool=call_tool,
cache_hints={"tools/list": CacheHint(ttl_ms=60_000)},
)