-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathclient.py
More file actions
714 lines (591 loc) · 29.8 KB
/
Copy pathclient.py
File metadata and controls
714 lines (591 loc) · 29.8 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
"""Unified MCP Client that wraps ClientSession with transport management."""
from __future__ import annotations
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
from contextlib import AsyncExitStack
from dataclasses import KW_ONLY, dataclass, field
from typing import Any, Literal, TypeVar
import anyio
import mcp_types as types
from mcp_types import (
CallToolResult,
CompleteResult,
EmptyResult,
ErrorData,
GetPromptResult,
Implementation,
InputRequest,
InputRequiredResult,
InputResponse,
InputResponses,
ListPromptsResult,
ListResourcesResult,
ListResourceTemplatesResult,
ListToolsResult,
LoggingLevel,
PaginatedRequestParams,
Prompt,
PromptReference,
ReadResourceResult,
RequestParamsMeta,
Resource,
ResourceTemplate,
ResourceTemplateReference,
ServerCapabilities,
Tool,
)
from mcp_types.version import HANDSHAKE_PROTOCOL_VERSIONS, MODERN_PROTOCOL_VERSIONS
from typing_extensions import deprecated
from mcp.client._input_required import DEFAULT_INPUT_REQUIRED_MAX_ROUNDS, run_input_required_driver
from mcp.client._memory import InMemoryTransport
from mcp.client._probe import negotiate_auto
from mcp.client._transport import Transport
from mcp.client.session import (
ClientRequestContext,
ClientSession,
ElicitationFnT,
ListRootsFnT,
LoggingFnT,
MessageHandlerFnT,
SamplingFnT,
)
from mcp.client.streamable_http import streamable_http_client
from mcp.server import Server
from mcp.server.mcpserver import MCPServer
from mcp.server.runner import modern_on_request
from mcp.shared.direct_dispatcher import create_direct_dispatcher_pair
from mcp.shared.dispatcher import Dispatcher, ProgressFnT
from mcp.shared.exceptions import MCPDeprecationWarning
from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher
ConnectMode = Literal["legacy", "auto"] | str
"""``mode=`` value: ``"legacy"`` (initialize handshake), ``"auto"`` (discover, fall back to
initialize), or a modern protocol-version string (adopt directly). The ``str`` arm is for
forward-compat; ``Client.__post_init__`` rejects anything outside that set at construction."""
_T = TypeVar("_T")
_ResultT = TypeVar("_ResultT")
_Connector = Callable[[AsyncExitStack, ConnectMode, bool], Awaitable["Dispatcher[Any]"]]
"""Resolved at ``__post_init__`` from the shape of ``server`` alone: enter whatever resources
are needed onto the exit stack and hand back the ``Dispatcher`` ``ClientSession`` will drive.
``mode`` and ``raise_exceptions`` are passed at call time so they're read at the same moment
``__aenter__`` reads them for the handshake step."""
def _connect_transport(transport: Transport) -> _Connector:
"""Connector for the stream-backed paths (URL, user-supplied ``Transport``)."""
async def connect(exit_stack: AsyncExitStack, _mode: ConnectMode, _raise_exceptions: bool) -> Dispatcher[Any]:
read_stream, write_stream = await exit_stack.enter_async_context(transport)
return JSONRPCDispatcher(read_stream, write_stream)
return connect
def _connect_inproc(server: Server[Any]) -> _Connector:
"""Connector for an in-process ``Server``: legacy mode drives the stream loop via
``InMemoryTransport``; any other mode drives the modern per-request path through a
``DirectDispatcher`` peer pair (no streams, no JSON-RPC framing, no initialize handshake)."""
async def connect(exit_stack: AsyncExitStack, mode: ConnectMode, raise_exceptions: bool) -> Dispatcher[Any]:
if mode == "legacy":
transport = InMemoryTransport(server, raise_exceptions=raise_exceptions)
read_stream, write_stream = await exit_stack.enter_async_context(transport)
return JSONRPCDispatcher(read_stream, write_stream)
lifespan_state = await exit_stack.enter_async_context(server.lifespan(server))
client_disp, server_disp = create_direct_dispatcher_pair(raise_handler_exceptions=raise_exceptions)
tg = await exit_stack.enter_async_context(anyio.create_task_group())
exit_stack.callback(server_disp.close)
on_request = modern_on_request(server, lifespan_state)
await tg.start(server_disp.run, on_request, _no_inbound_client_notifications)
return client_disp
return connect
def _connected(value: _T | None) -> _T:
"""Narrow a post-handshake session attribute from ``T | None`` to ``T``.
``Client.__aenter__`` only assigns ``_session`` after the handshake succeeds, so inside
``async with Client(...)`` these attributes are always populated; the ``.session`` gate
raises before this is reached otherwise. The guard exists for pyright, not runtime.
"""
if value is None: # pragma: no cover
raise RuntimeError("Client must be used within an async context manager")
return value
def _synthesize_discover(protocol_version: str) -> types.DiscoverResult:
return types.DiscoverResult(
supported_versions=[protocol_version],
capabilities=types.ServerCapabilities(),
server_info=types.Implementation(name="", version=""),
result_type="complete",
ttl_ms=0,
cache_scope="public",
)
async def _no_inbound_client_notifications(_dctx: Any, _method: str, _params: Mapping[str, Any] | None) -> None:
"""Server-side inbound ``OnNotify`` for the modern in-process path — receives nothing.
At 2026-07-28 the spec defines no client→server notifications: ``initialized`` and
``roots/list_changed`` are removed, and cancellation is structural (anyio scope cancel
through the direct await, not a notify). Server→client notifications (progress, log
messages) flow the other way via the per-request ``DispatchContext`` into the client's
callbacks, and are not seen here.
"""
@dataclass
class Client:
"""A high-level MCP client for connecting to MCP servers.
Supports in-memory transport for testing (pass a Server or MCPServer instance),
Streamable HTTP transport (pass a URL string), or a custom Transport instance.
Example:
```python
from mcp.client import Client
from mcp.server.mcpserver import MCPServer
server = MCPServer("test")
@server.tool()
def add(a: int, b: int) -> int:
return a + b
async def main():
async with Client(server) as client:
result = await client.call_tool("add", {"a": 1, "b": 2})
asyncio.run(main())
```
"""
server: Server[Any] | MCPServer | Transport | str
"""The MCP server to connect to.
If the server is a `Server` or `MCPServer` instance, it will be connected in-process.
If the server is a URL string, it will be used as the URL for a `streamable_http_client` transport.
If the server is a `Transport` instance, it will be used directly.
"""
_: KW_ONLY
# TODO(Marcelo): When do `raise_exceptions=True` actually raises?
raise_exceptions: bool = False
"""Whether to raise exceptions from the server."""
read_timeout_seconds: float | None = None
"""Timeout for read operations."""
sampling_callback: SamplingFnT | None = None
"""Callback for handling sampling requests."""
list_roots_callback: ListRootsFnT | None = None
"""Callback for handling list roots requests."""
logging_callback: LoggingFnT | None = None
"""Callback for handling logging notifications."""
# TODO(Marcelo): Why do we have both "callback" and "handler"?
message_handler: MessageHandlerFnT | None = None
"""Callback for handling raw messages."""
client_info: Implementation | None = None
"""Client implementation info to send to server."""
mode: ConnectMode = "auto"
"""How to negotiate the protocol version.
'auto' (the default) probes `server/discover` and falls back to the initialize handshake on legacy servers;
for an in-process `Server`/`MCPServer` it dispatches directly without JSON-RPC framing. 'legacy' forces the
initialize handshake (byte-identical pre-2026 behavior). A modern protocol-version string (e.g. '2026-07-28')
adopts that version directly without a probe — supply `prior_discover` to reuse a known DiscoverResult, or
omit it to synthesize a minimal one."""
prior_discover: types.DiscoverResult | None = None
"""A previously-obtained DiscoverResult to install via .adopt() when mode is a version pin.
Ignored when mode='legacy'."""
elicitation_callback: ElicitationFnT | None = None
"""Callback for handling elicitation requests."""
input_required_max_rounds: int = DEFAULT_INPUT_REQUIRED_MAX_ROUNDS
"""Cap on `InputRequiredResult` retry rounds before `call_tool` / `get_prompt` /
`read_resource` give up. Use `client.session.<method>(..., allow_input_required=True)`
to drive the loop manually instead."""
extensions: dict[str, dict[str, Any]] | None = None
"""SEP-2133 extension support to advertise under `ClientCapabilities.extensions`
(identifier -> settings), e.g. `{"io.modelcontextprotocol/ui": {"mimeTypes": [...]}}`."""
_entered: bool = field(init=False, default=False)
_session: ClientSession | None = field(init=False, default=None)
_exit_stack: AsyncExitStack | None = field(init=False, default=None)
_connect: _Connector = field(init=False, repr=False, compare=False)
def __post_init__(self) -> None:
if self.mode not in ("legacy", "auto") and self.mode not in MODERN_PROTOCOL_VERSIONS:
hint = (
f" ({self.mode!r} is a handshake-era version; use mode='legacy')"
if self.mode in HANDSHAKE_PROTOCOL_VERSIONS
else ""
)
raise ValueError(
f"mode must be 'legacy', 'auto', or one of {list(MODERN_PROTOCOL_VERSIONS)}; got {self.mode!r}{hint}"
)
srv = self.server
if isinstance(srv, MCPServer):
srv = srv._lowlevel_server # pyright: ignore[reportPrivateUsage]
if isinstance(srv, Server):
self._connect = _connect_inproc(srv)
elif isinstance(srv, str):
self._connect = _connect_transport(streamable_http_client(srv))
else:
self._connect = _connect_transport(srv)
async def _build_session(self, exit_stack: AsyncExitStack) -> ClientSession:
"""Enter the resolved connector and return an un-entered ClientSession."""
dispatcher = await self._connect(exit_stack, self.mode, self.raise_exceptions)
return ClientSession(
dispatcher=dispatcher,
read_timeout_seconds=self.read_timeout_seconds,
sampling_callback=self.sampling_callback,
list_roots_callback=self.list_roots_callback,
logging_callback=self.logging_callback,
message_handler=self.message_handler,
client_info=self.client_info,
elicitation_callback=self.elicitation_callback,
extensions=self.extensions,
)
async def __aenter__(self) -> Client:
"""Enter the async context manager."""
if self._entered:
raise RuntimeError("Client is already entered; cannot reenter")
self._entered = True
async with AsyncExitStack() as exit_stack:
session = await self._build_session(exit_stack)
session = await exit_stack.enter_async_context(session)
if self.mode == "legacy":
await session.initialize()
elif self.mode == "auto":
await negotiate_auto(session)
else:
session.adopt(self.prior_discover or _synthesize_discover(self.mode))
# Only publish the session after the handshake succeeds, so `_session is not None`
# implies the protocol_version/server_info/server_capabilities are populated. If the
# handshake raised above, the local exit_stack unwinds the transport for us.
self._session = session
self._exit_stack = exit_stack.pop_all()
return self
async def __aexit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any) -> None:
"""Exit the async context manager."""
if self._exit_stack: # pragma: no branch
await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
self._session = None
@property
def session(self) -> ClientSession:
"""Get the underlying ClientSession.
This provides access to the full ClientSession API for advanced use cases.
Raises:
RuntimeError: If accessed before entering the context manager.
"""
if self._session is None:
raise RuntimeError("Client must be used within an async context manager")
return self._session
# TODO(maxisbey): the by-construction shape is for __aenter__ to return a connected-view
# type whose protocol_version/server_info/server_capabilities are non-Optional fields,
# eliminating these guards (and the one in .session). Same family as resolving the
# transport/connector at __post_init__ so the Optional internal fields disappear.
@property
def protocol_version(self) -> str:
"""Negotiated protocol version (set by initialize/discover/adopt during ``__aenter__``)."""
return _connected(self.session.protocol_version)
@property
def server_info(self) -> Implementation:
"""Server name/version (set by initialize/discover/adopt during ``__aenter__``)."""
return _connected(self.session.server_info)
@property
def server_capabilities(self) -> ServerCapabilities:
"""Server capabilities (set by initialize/discover/adopt during ``__aenter__``)."""
return _connected(self.session.server_capabilities)
@property
def instructions(self) -> str | None:
"""Server-provided instructions text, if any."""
return self.session.instructions
@deprecated(
"ping is removed as of 2026-07-28; the method only works under mode='legacy'.",
category=MCPDeprecationWarning,
)
async def send_ping(self, *, meta: RequestParamsMeta | None = None) -> EmptyResult:
"""Send a ping request to the server."""
return await self.session.send_ping(meta=meta)
@deprecated(
"Client-to-server progress is deprecated as of 2026-07-28; progress is server-to-client only.",
category=MCPDeprecationWarning,
)
async def send_progress_notification(
self,
progress_token: str | int,
progress: float,
total: float | None = None,
message: str | None = None,
) -> None:
"""Send a progress notification to the server."""
await self.session.send_progress_notification( # pyright: ignore[reportDeprecated]
progress_token=progress_token,
progress=progress,
total=total,
message=message,
)
@deprecated("The logging capability is deprecated as of 2026-07-28 (SEP-2577).", category=MCPDeprecationWarning)
async def set_logging_level(self, level: LoggingLevel, *, meta: RequestParamsMeta | None = None) -> EmptyResult:
"""Set the logging level on the server."""
return await self.session.set_logging_level(level=level, meta=meta) # pyright: ignore[reportDeprecated]
async def list_resources(
self,
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
) -> ListResourcesResult:
"""List a single page of available resources from the server.
Returns one page only. The result may include a `next_cursor` if more
pages are available. Use `list_all_resources` to drain every page.
"""
return await self.session.list_resources(params=PaginatedRequestParams(cursor=cursor, _meta=meta))
async def list_resource_templates(
self,
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
) -> ListResourceTemplatesResult:
"""List a single page of available resource templates from the server.
Returns one page only. The result may include a `next_cursor` if more
pages are available. Use `list_all_resource_templates` to drain every
page.
"""
return await self.session.list_resource_templates(params=PaginatedRequestParams(cursor=cursor, _meta=meta))
async def read_resource(
self,
uri: str,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
) -> ReadResourceResult:
"""Read a resource from the server.
If the server returns an `InputRequiredResult`, the embedded input
requests are dispatched to this client's sampling / elicitation / roots
callbacks and the read is retried automatically (up to
`input_required_max_rounds`).
Args:
uri: The URI of the resource to read.
input_responses: Responses to seed the first call with (e.g. when
resuming from a persisted `InputRequiredResult`).
request_state: Opaque state to seed the first call with.
meta: Additional metadata for the request.
Returns:
The resource content.
Raises:
InputRequiredRoundsExceededError: `input_required_max_rounds` exhausted.
MCPError: A callback returned `ErrorData` for an embedded input request.
"""
async def retry(r: InputResponses | None, s: str | None) -> ReadResourceResult | InputRequiredResult:
return await self.session.read_resource(
uri, input_responses=r, request_state=s, meta=meta, allow_input_required=True
)
return await self._drive_input_required(await retry(input_responses, request_state), retry)
async def subscribe_resource(self, uri: str, *, meta: RequestParamsMeta | None = None) -> EmptyResult:
"""Subscribe to resource updates."""
return await self.session.subscribe_resource(uri, meta=meta)
async def unsubscribe_resource(self, uri: str, *, meta: RequestParamsMeta | None = None) -> EmptyResult:
"""Unsubscribe from resource updates."""
return await self.session.unsubscribe_resource(uri, meta=meta)
async def call_tool(
self,
name: str,
arguments: dict[str, Any] | None = None,
read_timeout_seconds: float | None = None,
progress_callback: ProgressFnT | None = None,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
) -> CallToolResult:
"""Call a tool on the server.
If the server returns an `InputRequiredResult`, the embedded input
requests are dispatched to this client's sampling / elicitation / roots
callbacks and the call is retried automatically (up to
`input_required_max_rounds`). To drive the loop yourself — e.g. to
persist `request_state` across process restarts — use
`client.session.call_tool(..., allow_input_required=True)`.
Args:
name: The name of the tool to call.
arguments: Arguments to pass to the tool.
read_timeout_seconds: Timeout for each underlying `tools/call` round.
progress_callback: Callback for progress updates.
input_responses: Responses to seed the first call with (e.g. when
resuming from a persisted `InputRequiredResult`).
request_state: Opaque state to seed the first call with.
meta: Additional metadata for the request.
Returns:
The tool result.
Raises:
InputRequiredRoundsExceededError: `input_required_max_rounds` exhausted.
MCPError: A callback returned `ErrorData` for an embedded input request.
"""
async def retry(r: InputResponses | None, s: str | None) -> CallToolResult | InputRequiredResult:
return await self.session.call_tool(
name,
arguments,
read_timeout_seconds=read_timeout_seconds,
progress_callback=progress_callback,
input_responses=r,
request_state=s,
meta=meta,
allow_input_required=True,
)
return await self._drive_input_required(await retry(input_responses, request_state), retry)
async def list_prompts(
self,
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
) -> ListPromptsResult:
"""List a single page of available prompts from the server.
Returns one page only. The result may include a `next_cursor` if more
pages are available. Use `list_all_prompts` to drain every page.
"""
return await self.session.list_prompts(params=PaginatedRequestParams(cursor=cursor, _meta=meta))
async def get_prompt(
self,
name: str,
arguments: dict[str, str] | None = None,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
) -> GetPromptResult:
"""Get a prompt from the server.
If the server returns an `InputRequiredResult`, the embedded input
requests are dispatched to this client's sampling / elicitation / roots
callbacks and the get is retried automatically (up to
`input_required_max_rounds`).
Args:
name: The name of the prompt.
arguments: Arguments to pass to the prompt.
input_responses: Responses to seed the first call with (e.g. when
resuming from a persisted `InputRequiredResult`).
request_state: Opaque state to seed the first call with.
meta: Additional metadata for the request.
Returns:
The prompt content.
Raises:
InputRequiredRoundsExceededError: `input_required_max_rounds` exhausted.
MCPError: A callback returned `ErrorData` for an embedded input request.
"""
async def retry(r: InputResponses | None, s: str | None) -> GetPromptResult | InputRequiredResult:
return await self.session.get_prompt(
name, arguments, input_responses=r, request_state=s, meta=meta, allow_input_required=True
)
return await self._drive_input_required(await retry(input_responses, request_state), retry)
async def _drive_input_required(
self,
first: _ResultT | InputRequiredResult,
retry: Callable[[InputResponses | None, str | None], Awaitable[_ResultT | InputRequiredResult]],
) -> _ResultT:
"""Hand an `InputRequiredResult` to the SEP-2322 driver, or pass a terminal result through.
`dispatch` routes each embedded request through the same callback table
that serves legacy server→client RPCs, so the two paths stay
behaviourally identical by construction.
"""
if not isinstance(first, InputRequiredResult):
return first
session = self.session
async def dispatch(key: str, req: InputRequest) -> InputResponse | ErrorData:
ctx = ClientRequestContext(session=session, request_id=key, meta=req.params.meta if req.params else None)
return await session._dispatch_input_request(ctx, req) # pyright: ignore[reportPrivateUsage]
return await run_input_required_driver(
first, dispatch=dispatch, retry=retry, max_rounds=self.input_required_max_rounds
)
async def complete(
self,
ref: ResourceTemplateReference | PromptReference,
argument: dict[str, str],
context_arguments: dict[str, str] | None = None,
) -> CompleteResult:
"""Get completions for a prompt or resource template argument.
Args:
ref: Reference to the prompt or resource template
argument: The argument to complete
context_arguments: Additional context arguments
Returns:
Completion suggestions.
"""
return await self.session.complete(ref=ref, argument=argument, context_arguments=context_arguments)
async def list_tools(self, *, cursor: str | None = None, meta: RequestParamsMeta | None = None) -> ListToolsResult:
"""List a single page of available tools from the server.
Returns one page only. The result may include a `next_cursor` if more
pages are available. Use `list_all_tools` to drain every page.
"""
return await self.session.list_tools(params=PaginatedRequestParams(cursor=cursor, _meta=meta))
async def iter_all_tools(self, *, meta: RequestParamsMeta | None = None) -> AsyncIterator[Tool]:
"""Yield every tool from the server, paging through `next_cursor`.
Useful for streaming consumers that want to process tools without
materializing the full list in memory.
Raises:
RuntimeError: The server returned a pagination cursor that did not advance.
"""
cursor: str | None = None
while True:
result = await self.list_tools(cursor=cursor, meta=meta)
for tool in result.tools:
yield tool
if result.next_cursor is None:
return
if result.next_cursor == cursor:
raise RuntimeError(
"Server returned a pagination cursor that did not advance; refusing to page forever."
)
cursor = result.next_cursor
async def list_all_tools(self, *, meta: RequestParamsMeta | None = None) -> list[Tool]:
"""List every tool from the server, draining `next_cursor` across pages.
Unlike `list_tools`, which returns one page, this walks pagination
until the server reports no further pages and returns the combined
list.
Raises:
RuntimeError: The server returned a pagination cursor that did not advance.
"""
return [tool async for tool in self.iter_all_tools(meta=meta)]
async def iter_all_prompts(self, *, meta: RequestParamsMeta | None = None) -> AsyncIterator[Prompt]:
"""Yield every prompt from the server, paging through `next_cursor`.
Raises:
RuntimeError: The server returned a pagination cursor that did not advance.
"""
cursor: str | None = None
while True:
result = await self.list_prompts(cursor=cursor, meta=meta)
for prompt in result.prompts:
yield prompt
if result.next_cursor is None:
return
if result.next_cursor == cursor:
raise RuntimeError(
"Server returned a pagination cursor that did not advance; refusing to page forever."
)
cursor = result.next_cursor
async def list_all_prompts(self, *, meta: RequestParamsMeta | None = None) -> list[Prompt]:
"""List every prompt from the server, draining `next_cursor` across pages.
Raises:
RuntimeError: The server returned a pagination cursor that did not advance.
"""
return [prompt async for prompt in self.iter_all_prompts(meta=meta)]
async def iter_all_resources(self, *, meta: RequestParamsMeta | None = None) -> AsyncIterator[Resource]:
"""Yield every resource from the server, paging through `next_cursor`.
Raises:
RuntimeError: The server returned a pagination cursor that did not advance.
"""
cursor: str | None = None
while True:
result = await self.list_resources(cursor=cursor, meta=meta)
for resource in result.resources:
yield resource
if result.next_cursor is None:
return
if result.next_cursor == cursor:
raise RuntimeError(
"Server returned a pagination cursor that did not advance; refusing to page forever."
)
cursor = result.next_cursor
async def list_all_resources(self, *, meta: RequestParamsMeta | None = None) -> list[Resource]:
"""List every resource from the server, draining `next_cursor` across pages.
Raises:
RuntimeError: The server returned a pagination cursor that did not advance.
"""
return [resource async for resource in self.iter_all_resources(meta=meta)]
async def iter_all_resource_templates(
self, *, meta: RequestParamsMeta | None = None
) -> AsyncIterator[ResourceTemplate]:
"""Yield every resource template from the server, paging through `next_cursor`.
Raises:
RuntimeError: The server returned a pagination cursor that did not advance.
"""
cursor: str | None = None
while True:
result = await self.list_resource_templates(cursor=cursor, meta=meta)
for template in result.resource_templates:
yield template
if result.next_cursor is None:
return
if result.next_cursor == cursor:
raise RuntimeError(
"Server returned a pagination cursor that did not advance; refusing to page forever."
)
cursor = result.next_cursor
async def list_all_resource_templates(self, *, meta: RequestParamsMeta | None = None) -> list[ResourceTemplate]:
"""List every resource template from the server, draining `next_cursor` across pages.
Raises:
RuntimeError: The server returned a pagination cursor that did not advance.
"""
return [template async for template in self.iter_all_resource_templates(meta=meta)]
@deprecated("The roots capability is deprecated as of 2026-07-28 (SEP-2577).", category=MCPDeprecationWarning)
async def send_roots_list_changed(self) -> None:
"""Send a notification that the roots list has changed."""
# TODO(Marcelo): Currently, there is no way for the server to handle this. We should add support.
await self.session.send_roots_list_changed() # pyright: ignore[reportDeprecated]