Index
MCP Client module.
InputRequiredRoundsExceededError
Bases: RuntimeError
The server kept returning InputRequiredResult past the configured max_rounds.
Source code in src/mcp/client/_input_required.py
40 41 42 43 44 45 46 47 48 49 | |
Transport
Bases: AbstractAsyncContextManager[TransportStreams], Protocol
Protocol for MCP transports.
A transport is an async context manager that yields read and write streams for bidirectional communication with an MCP server.
Source code in src/mcp/client/_transport.py
16 17 18 19 20 21 | |
CacheConfig
dataclass
Configuration for a Client's response cache.
Raises:
| Type | Description |
|---|---|
ValueError
|
On a custom |
Source code in src/mcp/client/caching.py
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 | |
store
class-attribute
instance-attribute
store: ResponseCacheStore | None = None
Backing store; None means a per-client InMemoryResponseCacheStore.
A custom store requires an explicit partition.
partition
class-attribute
instance-attribute
partition: str = ''
Authorization-context identifier isolating "private"-scoped entries
within a shared store. Derive it from a verified credential - never from
request-supplied data or the server URL. Fixed for the Client's
lifetime: construct a new Client when the principal changes.
target_id
class-attribute
instance-attribute
target_id: str | None = None
Server-identity override for custom transports and proxies where the SDK cannot derive one from a URL; must be non-empty when provided.
default_ttl_ms
class-attribute
instance-attribute
default_ttl_ms: int = 0
TTL in milliseconds for results carrying no ttlMs hint; the default 0 leaves them uncached.
clock
class-attribute
instance-attribute
Wall-clock source returning epoch seconds; injectable for expiry tests.
share_public
class-attribute
instance-attribute
share_public: bool = False
Serve server-marked "public" entries across every partition in the store.
WARNING: this trusts the server's "public" classification for every
principal sharing the store - a mislabeled response leaks across tenants.
Constructor-level only: the per-call cache_mode can never widen sharing.
CacheEntry
dataclass
One cached response with its freshness and sharing metadata.
Source code in src/mcp/client/caching.py
57 58 59 60 61 62 63 64 65 66 67 68 | |
value
instance-attribute
value: Any
The cached result; the SDK deep-copies on write and on serve, so a store may hold it as-is.
scope
instance-attribute
scope: Literal['public', 'private']
Server-asserted cacheScope: only "public" entries may be shared across authorization contexts.
expires_at
instance-attribute
expires_at: float | None
Epoch seconds after which the entry is stale; None is never fresh.
CacheKey
dataclass
Identity of one cached response; compare as the field tuple, never a flattened string (collision hazard).
Source code in src/mcp/client/caching.py
44 45 46 47 48 49 50 51 52 53 54 | |
CacheMode
module-attribute
CacheMode = Literal['use', 'refresh', 'bypass']
Per-call cache behavior: "use" serves and stores, "refresh" stores
without serving, "bypass" skips the cache entirely.
InMemoryResponseCacheStore
Default in-process ResponseCacheStore.
Method bodies are synchronous, so concurrent tasks never observe a torn
write. max_entries caps the whole store, evicting least-recently-used
at the cap (0 disables it); get and set both refresh recency, so a
hot entry survives churn from other keys.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/mcp/client/caching.py
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 | |
ResponseCacheStore
Bases: Protocol
Storage contract for the client response cache.
Each Client calls its store from a single event loop; per-operation
atomicity is the implementation's responsibility. Operations may raise -
the SDK degrades to a miss rather than failing the call. A serializing
store must round-trip value back to the result model object (a
wrong-shape entry is a miss, never an error). A lookup may issue two
sequential get calls (private arm, then public).
Source code in src/mcp/client/caching.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |
Client
dataclass
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
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())
Source code in src/mcp/client/client.py
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 | |
server
instance-attribute
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.
raise_exceptions
class-attribute
instance-attribute
raise_exceptions: bool = False
Whether to raise exceptions from the server.
read_timeout_seconds
class-attribute
instance-attribute
read_timeout_seconds: float | None = None
Timeout for read operations.
sampling_callback
class-attribute
instance-attribute
sampling_callback: SamplingFnT | None = None
Callback for handling sampling requests.
list_roots_callback
class-attribute
instance-attribute
list_roots_callback: ListRootsFnT | None = None
Callback for handling list roots requests.
logging_callback
class-attribute
instance-attribute
logging_callback: LoggingFnT | None = None
Callback for handling logging notifications.
message_handler
class-attribute
instance-attribute
message_handler: MessageHandlerFnT | None = None
Callback for handling raw messages.
client_info
class-attribute
instance-attribute
client_info: Implementation | None = None
Client implementation info to send to server.
mode
class-attribute
instance-attribute
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
class-attribute
instance-attribute
prior_discover: DiscoverResult | None = None
A previously-obtained DiscoverResult to install via .adopt() when mode is a version pin. Ignored when mode='legacy'.
elicitation_callback
class-attribute
instance-attribute
elicitation_callback: ElicitationFnT | None = None
Callback for handling elicitation requests.
input_required_max_rounds
class-attribute
instance-attribute
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
class-attribute
instance-attribute
extensions: Sequence[ClientExtension] | None = None
Opt-in client extensions (SEP-2133).
Each instance contributes its capability ad, its result claims (resolved
transparently by call_tool), and its notification bindings. For an
ad-only entry use mcp.client.advertise(identifier, settings).
cache
class-attribute
instance-attribute
cache: CacheConfig | Literal[False] | None = None
Client-side response caching for the SEP-2549 cacheable methods (2026-07-28).
None (the default) honors server ttlMs/cacheScope hints with a per-client
in-memory store; pass a CacheConfig to customize, or False to disable. The
cacheable verbs take a per-call cache_mode (see CacheMode); calls carrying
meta always reach the server. A CacheConfig with a custom store requires
target_id when the server is not a URL (no identity can be derived).
__aenter__
async
__aenter__() -> Client
Enter the async context manager.
Source code in src/mcp/client/client.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 | |
__aexit__
async
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: Any,
) -> None
Exit the async context manager.
Source code in src/mcp/client/client.py
455 456 457 458 459 | |
session
property
session: ClientSession
Get the underlying ClientSession.
This provides access to the full ClientSession API for advanced use cases.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If accessed before entering the context manager. |
protocol_version
property
protocol_version: str
Negotiated protocol version (set by initialize/discover/adopt during __aenter__).
server_info
property
server_info: Implementation
Server name/version (set by initialize/discover/adopt during __aenter__).
server_capabilities
property
server_capabilities: ServerCapabilities
Server capabilities (set by initialize/discover/adopt during __aenter__).
send_ping
async
send_ping(
*, meta: RequestParamsMeta | None = None
) -> EmptyResult
Send a ping request to the server.
Source code in src/mcp/client/client.py
498 499 500 501 502 503 504 | |
send_progress_notification
async
send_progress_notification(
progress_token: str | int,
progress: float,
total: float | None = None,
message: str | None = None,
) -> None
Send a progress notification to the server.
Source code in src/mcp/client/client.py
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | |
set_logging_level
async
set_logging_level(
level: LoggingLevel,
*,
meta: RequestParamsMeta | None = None
) -> EmptyResult
Set the logging level on the server.
Source code in src/mcp/client/client.py
525 526 527 528 | |
list_resources
async
list_resources(
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
cache_mode: CacheMode = "use"
) -> ListResourcesResult
List available resources from the server.
Source code in src/mcp/client/client.py
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | |
list_resource_templates
async
list_resource_templates(
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
cache_mode: CacheMode = "use"
) -> ListResourceTemplatesResult
List available resource templates from the server.
Source code in src/mcp/client/client.py
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 | |
read_resource
async
read_resource(
uri: str,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
cache_mode: CacheMode = "use"
) -> 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).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
The URI of the resource to read. |
required |
input_responses
|
InputResponses | None
|
Responses to seed the first call with (e.g. when
resuming from a persisted |
None
|
request_state
|
str | None
|
Opaque state to seed the first call with. |
None
|
meta
|
RequestParamsMeta | None
|
Additional metadata for the request. |
None
|
cache_mode
|
CacheMode
|
Cache behavior for this call (see |
'use'
|
Returns:
| Type | Description |
|---|---|
ReadResourceResult
|
The resource content. |
Raises:
| Type | Description |
|---|---|
InputRequiredRoundsExceededError
|
|
MCPError
|
A callback returned |
ValidationError
|
The server returned a result that does not conform to the negotiated protocol version. |
Source code in src/mcp/client/client.py
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 | |
subscribe_resource
async
subscribe_resource(
uri: str, *, meta: RequestParamsMeta | None = None
) -> EmptyResult
Subscribe to resource updates.
Source code in src/mcp/client/client.py
665 666 667 | |
unsubscribe_resource
async
unsubscribe_resource(
uri: str, *, meta: RequestParamsMeta | None = None
) -> EmptyResult
Unsubscribe from resource updates.
Source code in src/mcp/client/client.py
669 670 671 | |
call_tool
async
call_tool(
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). Persisted
state is still subject to the server's TTL, request binding, and key
lifetime; a server on the default process-local key rejects it after a restart.
Result shapes claimed by this client's extensions are finished by the
owning claim's resolver, whose CallToolResult is returned; resolver
exceptions propagate as-is. To receive the claimed shape yourself, use
client.session.call_tool(..., allow_claimed=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the tool to call. |
required |
arguments
|
dict[str, Any] | None
|
Arguments to pass to the tool. |
None
|
read_timeout_seconds
|
float | None
|
Timeout for each underlying |
None
|
progress_callback
|
ProgressFnT | None
|
Callback for progress updates. |
None
|
input_responses
|
InputResponses | None
|
Responses to seed the first call with (e.g. when
resuming from a persisted |
None
|
request_state
|
str | None
|
Opaque state to seed the first call with. |
None
|
meta
|
RequestParamsMeta | None
|
Additional metadata for the request. |
None
|
Returns:
| Type | Description |
|---|---|
CallToolResult
|
The tool result. |
Raises:
| Type | Description |
|---|---|
InputRequiredRoundsExceededError
|
|
MCPError
|
A callback returned |
ValidationError
|
The server returned a result that does not conform to the negotiated protocol version. |
TaskFailedError
|
The call was augmented into a task that |
TaskCancelledError
|
The call was augmented into a task that was cancelled before completing. |
TaskInputRequiredError
|
The call was augmented into a task that
reached |
Source code in src/mcp/client/client.py
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 | |
list_prompts
async
list_prompts(
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
cache_mode: CacheMode = "use"
) -> ListPromptsResult
List available prompts from the server.
Source code in src/mcp/client/client.py
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 | |
get_prompt
async
get_prompt(
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).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the prompt. |
required |
arguments
|
dict[str, str] | None
|
Arguments to pass to the prompt. |
None
|
input_responses
|
InputResponses | None
|
Responses to seed the first call with (e.g. when
resuming from a persisted |
None
|
request_state
|
str | None
|
Opaque state to seed the first call with. |
None
|
meta
|
RequestParamsMeta | None
|
Additional metadata for the request. |
None
|
Returns:
| Type | Description |
|---|---|
GetPromptResult
|
The prompt content. |
Raises:
| Type | Description |
|---|---|
InputRequiredRoundsExceededError
|
|
MCPError
|
A callback returned |
ValidationError
|
The server returned a result that does not conform to the negotiated protocol version. |
Source code in src/mcp/client/client.py
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 | |
complete
async
complete(
ref: ResourceTemplateReference | PromptReference,
argument: dict[str, str],
context_arguments: dict[str, str] | None = None,
) -> CompleteResult
Get completions for a prompt or resource template argument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
ResourceTemplateReference | PromptReference
|
Reference to the prompt or resource template |
required |
argument
|
dict[str, str]
|
The argument to complete |
required |
context_arguments
|
dict[str, str] | None
|
Additional context arguments |
None
|
Returns:
| Type | Description |
|---|---|
CompleteResult
|
Completion suggestions. |
Source code in src/mcp/client/client.py
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 | |
list_tools
async
list_tools(
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
cache_mode: CacheMode = "use"
) -> ListToolsResult
List available tools from the server.
Source code in src/mcp/client/client.py
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 | |
send_roots_list_changed
async
send_roots_list_changed() -> None
Send a notification that the roots list has changed.
Source code in src/mcp/client/client.py
878 879 880 881 882 | |
ClientRequestContext
dataclass
Context for a server-initiated request, passed to the sampling/elicitation/list-roots callbacks.
Source code in src/mcp/client/session.py
112 113 114 115 116 117 118 | |
ClaimContext
dataclass
Host-injected context for one ResultClaim.resolve call.
Source code in src/mcp/client/extension.py
59 60 61 62 63 64 65 | |
ClientExtension
Base class for an opt-in client extension; override only what you need.
The surface is declarative, fixed at construction, and never receives the client.
Source code in src/mcp/client/extension.py
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 | |
settings
Per-extension settings advertised at ClientCapabilities.extensions[identifier].
Read once at Client construction. A claim-bearing extension is
advertised only at protocol versions where at least one of its claims
is active.
Source code in src/mcp/client/extension.py
160 161 162 163 164 165 166 167 | |
claims
claims() -> Sequence[ResultClaim[Any]]
Extra result shapes this extension claims, with their resolvers.
Source code in src/mcp/client/extension.py
169 170 171 | |
notifications
notifications() -> Sequence[NotificationBinding[Any]]
Server notifications this extension observes.
Source code in src/mcp/client/extension.py
173 174 175 | |
NotificationBinding
dataclass
Bases: Generic[NotifyParamsT]
Deliver server notifications for method (the bare wire name) to handler.
Observation-only: validated params arrive one at a time per binding, in dispatch order, through a bounded queue that drops the oldest with a warning on overflow. Stream transports dispatch each notification independently, so near-simultaneous notifications may be dispatched out of wire order. Methods the negotiated version's core tables handle are never delivered to bindings.
Source code in src/mcp/client/extension.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
ResultClaim
dataclass
Bases: Generic[ClaimedT]
One extra result shape on one spec verb, keyed by the wire resultType.
Active only while the declaring extension is constructed into the client and
the negotiated protocol version admits it. resolve finishes a claimed
result, may send follow-ups through ctx.session, and must return the
verb's ordinary result. All field constraints are enforced at construction.
Source code in src/mcp/client/extension.py
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 | |
UnexpectedClaimedResult
Bases: RuntimeError
A claimed (extension) result arrived on a call_tool that did not opt in.
The parsed value is carried as result; the server may already hold state it
references. Opt in via Client(extensions=[...]) or allow_claimed=True.
Source code in src/mcp/client/extension.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
advertise
advertise(
identifier: str, settings: dict[str, Any] | None = None
) -> ClientExtension
Advertise an extension identifier (with optional settings) and nothing else.
Advertising an extension you do not implement asserts wire support you do not have; for behavioral extensions construct the real extension instead.
Source code in src/mcp/client/extension.py
189 190 191 192 193 194 195 196 | |
ClientSession
Client half of an MCP connection, running on a Dispatcher.
Construct it over a transport's stream pair (or pass a pre-built
dispatcher=), enter as an async context manager, then call
initialize(). The dispatcher owns the receive loop and request
correlation; this class owns the typed MCP layer and the constructor
callbacks. Transport Exception items reach message_handler only when
the session builds its own dispatcher from a stream pair.
Extension result_claims fold into tools/call parsing at adopt();
notification_bindings observe vendor notifications via bounded FIFOs.
Source code in src/mcp/client/session.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 | |
send_request
async
send_request(
request: ClientRequest | Request[Any, Any],
result_type: (
type[ReceiveResultT] | TypeAdapter[ReceiveResultT]
),
request_read_timeout_seconds: float | None = None,
metadata: ClientMessageMetadata | None = None,
progress_callback: ProgressFnT | None = None,
) -> ReceiveResultT
Send a request and wait for its typed result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
ClientMessageMetadata | None
|
Streamable HTTP resumption hints. |
None
|
Raises:
| Type | Description |
|---|---|
MCPError
|
Error response, read timeout, or connection closed. |
RuntimeError
|
Called before entering the context manager. |
ValueError
|
The request declares |
ValidationError
|
The server returned a result that does not conform to the negotiated protocol version. |
Source code in src/mcp/client/session.py
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 | |
send_notification
async
send_notification(notification: ClientNotification) -> None
Send a one-way notification. Usable before entering the context manager.
Fire-and-forget: after the connection has closed, the notification is dropped with a debug log instead of raising.
Source code in src/mcp/client/session.py
496 497 498 499 500 501 502 503 504 505 | |
adopt
adopt(result: InitializeResult | DiscoverResult) -> None
Install negotiated state from a result the caller already holds (no wire traffic).
Clears the opposite slot, so at most one of initialize_result /
discover_result is ever non-None.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
|
Source code in src/mcp/client/session.py
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 | |
send_discover
async
Send a single server/discover at version and return the raw result dict.
No retry, no adopt(). The _meta envelope and the
Mcp-Protocol-Version header are stamped at version so the
server-side era router sees a coherent probe. Used by discover() and
the connect-time auto-negotiation policy.
Raises:
| Type | Description |
|---|---|
MCPError
|
The server returned a JSON-RPC error, or the transport bounced the request at its own layer (a bare HTTP 4xx is synthesized into a JSON-RPC error by the transport). |
Source code in src/mcp/client/session.py
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 | |
discover
async
discover() -> DiscoverResult
Probe server/discover and adopt the result.
Sends a single server/discover proposing the newest modern protocol
version. On UNSUPPORTED_PROTOCOL_VERSION (-32022) the server's
supported list is intersected with MODERN_PROTOCOL_VERSIONS and the
probe is retried once at the highest mutual version. Any other error —
including METHOD_NOT_FOUND (-32601) and REQUEST_TIMEOUT (-32001) —
propagates; the legacy initialize() fallback is the caller's policy.
Raises:
| Type | Description |
|---|---|
MCPError
|
The server rejected |
RuntimeError
|
|
Source code in src/mcp/client/session.py
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 | |
initialize_result
property
initialize_result: InitializeResult | None
The server's InitializeResult. None unless initialize() ran (or was adopted).
discover_result
property
discover_result: DiscoverResult | None
The server's DiscoverResult. None unless discover() ran (or was adopted).
Retained intact (supported_versions, ttl_ms, cache_scope) so callers
can round-trip it as prior_discover=.
protocol_version
property
protocol_version: str | None
Negotiated protocol version. None until initialize(), discover(), or adopt().
server_info
property
server_info: Implementation | None
Server name/version. None until initialize(), discover(), or adopt().
server_capabilities
property
server_capabilities: ServerCapabilities | None
Server capabilities. None until initialize(), discover(), or adopt().
send_ping
async
send_ping(
*, meta: RequestParamsMeta | None = None
) -> EmptyResult
Send a ping request.
Source code in src/mcp/client/session.py
730 731 732 | |
send_progress_notification
async
send_progress_notification(
progress_token: str | int,
progress: float,
total: float | None = None,
message: str | None = None,
*,
meta: RequestParamsMeta | None = None
) -> None
Send a progress notification.
Source code in src/mcp/client/session.py
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 | |
set_logging_level
async
set_logging_level(
level: LoggingLevel,
*,
meta: RequestParamsMeta | None = None
) -> EmptyResult
Send a logging/setLevel request.
Source code in src/mcp/client/session.py
760 761 762 763 764 765 766 767 768 769 770 771 | |
list_resources
async
list_resources(
*, params: PaginatedRequestParams | None = None
) -> ListResourcesResult
Send a resources/list request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
PaginatedRequestParams | None
|
Full pagination parameters including cursor and any future fields |
None
|
Source code in src/mcp/client/session.py
773 774 775 776 777 778 779 | |
list_resource_templates
async
list_resource_templates(
*, params: PaginatedRequestParams | None = None
) -> ListResourceTemplatesResult
Send a resources/templates/list request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
PaginatedRequestParams | None
|
Full pagination parameters including cursor and any future fields |
None
|
Source code in src/mcp/client/session.py
781 782 783 784 785 786 787 788 789 790 791 792 | |
read_resource
async
read_resource(
uri: str,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
allow_input_required: Literal[False] = False
) -> ReadResourceResult
read_resource(
uri: str,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
allow_input_required: bool
) -> ReadResourceResult | InputRequiredResult
read_resource(
uri: str,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
allow_input_required: bool = False
) -> ReadResourceResult | InputRequiredResult
Send a resources/read request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_responses
|
InputResponses | None
|
Responses to a prior |
None
|
request_state
|
str | None
|
Opaque state echoed from a prior |
None
|
allow_input_required
|
bool
|
When |
False
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the server returns an |
Source code in src/mcp/client/session.py
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 | |
subscribe_resource
async
subscribe_resource(
uri: str, *, meta: RequestParamsMeta | None = None
) -> EmptyResult
Send a resources/subscribe request.
Source code in src/mcp/client/session.py
853 854 855 856 857 858 | |
unsubscribe_resource
async
unsubscribe_resource(
uri: str, *, meta: RequestParamsMeta | None = None
) -> EmptyResult
Send a resources/unsubscribe request.
Source code in src/mcp/client/session.py
860 861 862 863 864 865 | |
call_tool
async
call_tool(
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,
allow_input_required: Literal[False] = False,
allow_claimed: Literal[False] = False
) -> CallToolResult
call_tool(
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,
allow_input_required: bool,
allow_claimed: Literal[False] = False
) -> CallToolResult | InputRequiredResult
call_tool(
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,
allow_input_required: Literal[False] = False,
allow_claimed: bool
) -> CallToolResult | Result
call_tool(
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,
allow_input_required: bool,
allow_claimed: bool
) -> CallToolResult | InputRequiredResult | Result
call_tool(
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,
allow_input_required: bool = False,
allow_claimed: bool = False
) -> CallToolResult | InputRequiredResult | Result
Send a tools/call request with optional progress callback support.
On a modern (2026-07-28) connection, arguments annotated with x-mcp-header
in the tool's input schema are mirrored into Mcp-Param-* request headers.
The annotations are read from the tool's last list_tools entry, so list
the tool before calling it to enable header emission.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_responses
|
InputResponses | None
|
Responses to a prior |
None
|
request_state
|
str | None
|
Opaque state echoed from a prior |
None
|
allow_input_required
|
bool
|
When |
False
|
allow_claimed
|
bool
|
When |
False
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the server returns an |
UnexpectedClaimedResult
|
Claimed result with |
Source code in src/mcp/client/session.py
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 | |
validate_tool_result
async
validate_tool_result(
name: str, result: CallToolResult
) -> None
Revalidate a CallToolResult against the tool's declared output schema.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Structured content is missing or does not conform to the schema. |
Source code in src/mcp/client/session.py
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 | |
list_prompts
async
list_prompts(
*, params: PaginatedRequestParams | None = None
) -> ListPromptsResult
Send a prompts/list request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
PaginatedRequestParams | None
|
Full pagination parameters including cursor and any future fields |
None
|
Source code in src/mcp/client/session.py
1021 1022 1023 1024 1025 1026 1027 | |
get_prompt
async
get_prompt(
name: str,
arguments: dict[str, str] | None = None,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
allow_input_required: Literal[False] = False
) -> GetPromptResult
get_prompt(
name: str,
arguments: dict[str, str] | None = None,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
allow_input_required: bool
) -> GetPromptResult | InputRequiredResult
get_prompt(
name: str,
arguments: dict[str, str] | None = None,
*,
input_responses: InputResponses | None = None,
request_state: str | None = None,
meta: RequestParamsMeta | None = None,
allow_input_required: bool = False
) -> GetPromptResult | InputRequiredResult
Send a prompts/get request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_responses
|
InputResponses | None
|
Responses to a prior |
None
|
request_state
|
str | None
|
Opaque state echoed from a prior |
None
|
allow_input_required
|
bool
|
When |
False
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the server returns an |
Source code in src/mcp/client/session.py
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 | |
complete
async
complete(
ref: ResourceTemplateReference | PromptReference,
argument: dict[str, str],
context_arguments: dict[str, str] | None = None,
) -> CompleteResult
Send a completion/complete request.
Source code in src/mcp/client/session.py
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 | |
list_tools
async
list_tools(
*, params: PaginatedRequestParams | None = None
) -> ListToolsResult
Send a tools/list request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
PaginatedRequestParams | None
|
Full pagination parameters including cursor and any future fields |
None
|
Source code in src/mcp/client/session.py
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 | |
send_roots_list_changed
async
send_roots_list_changed() -> None
Send a roots/list_changed notification.
Source code in src/mcp/client/session.py
1161 1162 1163 1164 | |
dispatch_input_request
async
dispatch_input_request(
ctx: ClientRequestContext, request: InputRequest
) -> InputResponse | ErrorData
Route an input request through the client's callback table.
Shared by the legacy server→client RPC path (_on_request) and the
2026-07-28 multi-round-trip driver, which dispatches the embedded
InputRequiredResult.input_requests through the same callbacks.
Returns the callback's InputResponse, or ErrorData when the callback declines.
Source code in src/mcp/client/session.py
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 | |
TaskCancelledError
Bases: TaskError
The task reached cancelled before producing a result (SEP-2663).
Source code in src/mcp/client/tasks.py
89 90 91 92 93 94 95 96 97 98 99 100 | |
__reduce__
Pickle via the constructor args (args holds the formatted message, which does not round-trip).
Source code in src/mcp/client/tasks.py
98 99 100 | |
TaskError
Bases: Exception
Base for the typed SEP-2663 task-outcome errors.
A task that ends anywhere other than completed surfaces as one of three
subclasses — TaskFailedError, TaskCancelledError,
TaskInputRequiredError — so except TaskError handles any non-completion.
Source code in src/mcp/client/tasks.py
64 65 66 67 68 69 70 | |
TaskFailedError
The task reached failed: a JSON-RPC error occurred during execution (SEP-2663).
Carries the JSON-RPC error inlined on tasks/get as code/message/data,
plus the snapshot's optional statusMessage diagnostic.
Source code in src/mcp/client/tasks.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
__reduce__
Pickle via the constructor args (args holds MCPError's, which do not round-trip).
Source code in src/mcp/client/tasks.py
84 85 86 | |
TaskInputRequiredError
Bases: TaskError
The task reached input_required, which the polling loop does not drive yet.
SEP-2663's in-task input loop (fulfil inputRequests via tasks/update) is
a deferred follow-up in this SDK. Drive it manually: fetch the snapshot with
get_task and answer its inputRequests with update_task.
Source code in src/mcp/client/tasks.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
__reduce__
__reduce__() -> (
tuple[type[TaskInputRequiredError], tuple[str]]
)
Pickle via the constructor args (args holds the formatted message, which does not round-trip).
Source code in src/mcp/client/tasks.py
119 120 121 | |
TasksExtension
Bases: ClientExtension
SEP-2663 Tasks as a client extension.
Declares io.modelcontextprotocol/tasks and claims the task resultType on
tools/call: a CreateTaskResult is resolved by polling tasks/get to the
final CallToolResult, exactly as wait_task does by hand.
Source code in src/mcp/client/tasks.py
318 319 320 321 322 323 324 325 326 327 328 329 | |