Index
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 | |
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 | |
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. |
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 | |
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
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 | |
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
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 | |
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
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 | |
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
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 | |
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
868 869 870 871 872 | |
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 | |
ClientSessionGroup
Client for managing connections to multiple MCP servers.
This class is responsible for encapsulating management of server connections. It aggregates tools, resources, and prompts from all connected servers.
For auxiliary handlers, such as resource subscription, this is delegated to the client and can be accessed via the session.
Example
name_fn = lambda name, server_info: f"{(server_info.name)}_{name}"
async with ClientSessionGroup(component_name_hook=name_fn) as group:
for server_param in server_params:
await group.connect_to_server(server_param)
...
Source code in src/mcp/client/session_group.py
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 | |
__init__
__init__(
exit_stack: AsyncExitStack | None = None,
component_name_hook: _ComponentNameHook | None = None,
) -> None
Initializes the MCP client.
Source code in src/mcp/client/session_group.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
__aexit__
async
__aexit__(
_exc_type: type[BaseException] | None,
_exc_val: BaseException | None,
_exc_tb: TracebackType | None,
) -> bool | None
Closes session exit stacks and main exit stack upon completion.
Source code in src/mcp/client/session_group.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |
prompts
property
Returns the prompts as a dictionary of names to prompts.
resources
property
Returns the resources as a dictionary of names to resources.
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
) -> 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
) -> 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: bool = False
) -> CallToolResult | InputRequiredResult
Executes a tool given its name and arguments.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the server returns an |
Source code in src/mcp/client/session_group.py
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 | |
disconnect_from_server
async
disconnect_from_server(session: ClientSession) -> None
Disconnects from a single MCP server.
Source code in src/mcp/client/session_group.py
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 | |
connect_with_session
async
connect_with_session(
server_info: Implementation, session: ClientSession
) -> ClientSession
Connects to a single MCP server.
Source code in src/mcp/client/session_group.py
287 288 289 290 291 292 | |
connect_to_server
async
connect_to_server(
server_params: ServerParameters,
session_params: ClientSessionParameters | None = None,
) -> ClientSession
Connects to a single MCP server.
Source code in src/mcp/client/session_group.py
294 295 296 297 298 299 300 301 | |
StdioServerParameters
Bases: BaseModel
Source code in src/mcp/client/stdio.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
args
class-attribute
instance-attribute
Command line arguments to pass to the executable.
env
class-attribute
instance-attribute
Extra environment variables, merged over get_default_environment().
cwd
class-attribute
instance-attribute
The working directory to use when spawning the process.
encoding
class-attribute
instance-attribute
encoding: str = 'utf-8'
Text encoding for messages to and from the server.
encoding_error_handler
class-attribute
instance-attribute
encoding_error_handler: Literal[
"strict", "ignore", "replace"
] = "strict"
Encoding error handler; see https://docs.python.org/3/library/codecs.html#error-handlers.
stdio_client
async
stdio_client(
server: StdioServerParameters, errlog: TextIO = stderr
) -> AsyncGenerator[TransportStreams, None]
Spawns an MCP server subprocess and connects to it over stdin/stdout.
Raises:
| Type | Description |
|---|---|
OSError
|
If the server process cannot be spawned. |
ValueError
|
If the spawn parameters are invalid (embedded NUL bytes). |
Source code in src/mcp/client/stdio.py
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 | |
ServerSession
Per-request proxy for server-to-client requests and notifications.
Built once per inbound request by the kernel's _make_context. Holds two
Outbound channels: the request-scoped one (the per-request
DispatchContext, which on streamable HTTP routes onto the originating
POST's response stream) and the connection's standalone channel
(connection.outbound). related_request_id on the public methods is the
selector — present means request-scoped, absent means standalone — and
never crosses the Outbound Protocol.
Source code in src/mcp/server/session.py
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 | |
client_params
property
client_params: InitializeRequestParams | None
The client's initialize request params; None when no client info was supplied.
protocol_version
property
protocol_version: str
The protocol version this connection speaks.
Populated at Connection construction and overwritten once the
handshake commits on the loop path; never None.
send_request
async
send_request(
request: ServerRequest,
result_type: type[ResultT],
request_read_timeout_seconds: float | None = None,
metadata: ServerMessageMetadata | None = None,
progress_callback: ProgressFnT | None = None,
) -> ResultT
Send a typed server-to-client request and validate the result.
Raises:
| Type | Description |
|---|---|
MCPError
|
The peer responded with an error. |
NoBackChannelError
|
The connection has no back-channel for
server-initiated requests (raised by the held |
ValidationError
|
The peer's result does not match |
Source code in src/mcp/server/session.py
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 | |
send_notification
async
send_notification(
notification: ServerNotification,
related_request_id: RequestId | None = None,
) -> None
Send a typed server-to-client notification.
Source code in src/mcp/server/session.py
88 89 90 91 92 93 94 95 96 | |
check_client_capability
check_client_capability(
capability: ClientCapabilities,
) -> bool
Check if the client supports a specific capability.
Source code in src/mcp/server/session.py
98 99 100 | |
send_log_message
async
send_log_message(
level: LoggingLevel,
data: Any,
logger: str | None = None,
related_request_id: RequestId | None = None,
) -> None
Send a log message notification.
Source code in src/mcp/server/session.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
send_resource_updated
async
Send a resource updated notification.
Source code in src/mcp/server/session.py
122 123 124 125 126 127 128 | |
create_message
async
create_message(
messages: list[SamplingMessage],
*,
max_tokens: int,
system_prompt: str | None = None,
include_context: IncludeContext | None = None,
temperature: float | None = None,
stop_sequences: list[str] | None = None,
metadata: dict[str, Any] | None = None,
model_preferences: ModelPreferences | None = None,
tools: None = None,
tool_choice: ToolChoice | None = None,
related_request_id: RequestId | None = None
) -> CreateMessageResult
create_message(
messages: list[SamplingMessage],
*,
max_tokens: int,
system_prompt: str | None = None,
include_context: IncludeContext | None = None,
temperature: float | None = None,
stop_sequences: list[str] | None = None,
metadata: dict[str, Any] | None = None,
model_preferences: ModelPreferences | None = None,
tools: list[Tool],
tool_choice: ToolChoice | None = None,
related_request_id: RequestId | None = None
) -> CreateMessageResultWithTools
create_message(
messages: list[SamplingMessage],
*,
max_tokens: int,
system_prompt: str | None = None,
include_context: IncludeContext | None = None,
temperature: float | None = None,
stop_sequences: list[str] | None = None,
metadata: dict[str, Any] | None = None,
model_preferences: ModelPreferences | None = None,
tools: list[Tool] | None = None,
tool_choice: ToolChoice | None = None,
related_request_id: RequestId | None = None
) -> CreateMessageResult | CreateMessageResultWithTools
Send a sampling/create_message request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[SamplingMessage]
|
The conversation messages to send. |
required |
max_tokens
|
int
|
Maximum number of tokens to generate. |
required |
system_prompt
|
str | None
|
Optional system prompt. |
None
|
include_context
|
IncludeContext | None
|
Optional context inclusion setting. Should only be set to "thisServer" or "allServers" if the client has sampling.context capability. |
None
|
temperature
|
float | None
|
Optional sampling temperature. |
None
|
stop_sequences
|
list[str] | None
|
Optional stop sequences. |
None
|
metadata
|
dict[str, Any] | None
|
Optional metadata to pass through to the LLM provider. |
None
|
model_preferences
|
ModelPreferences | None
|
Optional model selection preferences. |
None
|
tools
|
list[Tool] | None
|
Optional list of tools the LLM can use during sampling. Requires client to have sampling.tools capability. |
None
|
tool_choice
|
ToolChoice | None
|
Optional control over tool usage behavior. Requires client to have sampling.tools capability. |
None
|
related_request_id
|
RequestId | None
|
Optional ID of a related request. |
None
|
Returns:
| Type | Description |
|---|---|
CreateMessageResult | CreateMessageResultWithTools
|
The sampling result from the client. |
Raises:
| Type | Description |
|---|---|
MCPError
|
If tools are provided but client doesn't support them. |
ValueError
|
If tool_use or tool_result message structure is invalid. |
NoBackChannelError
|
The connection has no back-channel for server-initiated requests. |
Source code in src/mcp/server/session.py
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 | |
list_roots
async
list_roots() -> ListRootsResult
Send a roots/list request.
Raises:
| Type | Description |
|---|---|
NoBackChannelError
|
The connection has no back-channel for server-initiated requests. |
Source code in src/mcp/server/session.py
246 247 248 249 250 251 252 253 254 255 256 257 | |
elicit
async
elicit(
message: str,
requested_schema: ElicitRequestedSchema,
related_request_id: RequestId | None = None,
) -> ElicitResult
Send a form mode elicitation/create request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The message to present to the user. |
required |
requested_schema
|
ElicitRequestedSchema
|
Schema defining the expected response structure. |
required |
related_request_id
|
RequestId | None
|
Optional ID of the request that triggered this elicitation. |
None
|
Returns:
| Type | Description |
|---|---|
ElicitResult
|
The client's response. |
Note
This method is deprecated in favor of elicit_form(). It remains for backward compatibility but new code should use elicit_form().
Source code in src/mcp/server/session.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
elicit_form
async
elicit_form(
message: str,
requested_schema: ElicitRequestedSchema,
related_request_id: RequestId | None = None,
) -> ElicitResult
Send a form mode elicitation/create request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The message to present to the user. |
required |
requested_schema
|
ElicitRequestedSchema
|
Schema defining the expected response structure. |
required |
related_request_id
|
RequestId | None
|
Optional ID of the request that triggered this elicitation. |
None
|
Returns:
| Type | Description |
|---|---|
ElicitResult
|
The client's response with form data. |
Raises:
| Type | Description |
|---|---|
NoBackChannelError
|
The connection has no back-channel for server-initiated requests. |
Source code in src/mcp/server/session.py
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 | |
elicit_url
async
elicit_url(
message: str,
url: str,
elicitation_id: str,
related_request_id: RequestId | None = None,
) -> ElicitResult
Send a URL mode elicitation/create request.
This directs the user to an external URL for out-of-band interactions like OAuth flows, credential collection, or payment processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Human-readable explanation of why the interaction is needed. |
required |
url
|
str
|
The URL the user should navigate to. |
required |
elicitation_id
|
str
|
Unique identifier for tracking this elicitation. |
required |
related_request_id
|
RequestId | None
|
Optional ID of the request that triggered this elicitation. |
None
|
Returns:
| Type | Description |
|---|---|
ElicitResult
|
The client's response indicating acceptance, decline, or cancellation. |
Raises:
| Type | Description |
|---|---|
NoBackChannelError
|
The connection has no back-channel for server-initiated requests. |
Source code in src/mcp/server/session.py
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 | |
send_ping
async
send_ping() -> EmptyResult
Send a ping request.
Source code in src/mcp/server/session.py
349 350 351 352 353 354 | |
report_progress
async
Report progress for the inbound request this session is scoped to.
A no-op when the caller did not request progress. Dispatcher-agnostic:
on JSON-RPC the held DispatchContext emits notifications/progress
against the caller's token; on the in-process direct dispatcher it
invokes the caller's callback directly.
Source code in src/mcp/server/session.py
356 357 358 359 360 361 362 363 364 | |
send_progress_notification
async
send_progress_notification(
progress_token: str | int,
progress: float,
total: float | None = None,
message: str | None = None,
related_request_id: str | None = None,
) -> None
Send a progress notification.
Source code in src/mcp/server/session.py
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | |
send_resource_list_changed
async
send_resource_list_changed() -> None
Send a resource list changed notification.
Source code in src/mcp/server/session.py
387 388 389 | |
send_tool_list_changed
async
send_tool_list_changed() -> None
Send a tool list changed notification.
Source code in src/mcp/server/session.py
391 392 393 | |
send_prompt_list_changed
async
send_prompt_list_changed() -> None
Send a prompt list changed notification.
Source code in src/mcp/server/session.py
395 396 397 | |
send_elicit_complete
async
Send an elicitation completion notification.
This should be sent when a URL mode elicitation has been completed out-of-band to inform the client that it may retry any requests that were waiting for this elicitation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
elicitation_id
|
str
|
The unique identifier of the completed elicitation |
required |
related_request_id
|
RequestId | None
|
Optional ID of the request that triggered this notification |
None
|
Source code in src/mcp/server/session.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | |
stdio_server
async
Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout.
Source code in src/mcp/server/stdio.py
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 | |
MCPDeprecationWarning
Bases: UserWarning
A custom deprecation warning for the MCP SDK.
Unlike the built-in DeprecationWarning, this inherits from UserWarning so
it is shown by default, helping users discover deprecated features without
enabling warnings explicitly.
Reference: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
Source code in src/mcp/shared/exceptions.py
8 9 10 11 12 13 14 15 16 | |
MCPError
Bases: Exception
Exception type raised when an error arrives over an MCP connection.
Source code in src/mcp/shared/exceptions.py
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 | |
UrlElicitationRequiredError
Bases: MCPError
Specialized error for when a tool requires URL mode elicitation(s) before proceeding.
Servers can raise this error from tool handlers to indicate that the client must complete one or more URL elicitations before the request can be processed.
Example
raise UrlElicitationRequiredError([
ElicitRequestURLParams(
message="Authorization required for your files",
url="https://example.com/oauth/authorize",
elicitation_id="auth-001"
)
])
Source code in src/mcp/shared/exceptions.py
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 | |
__init__
__init__(
elicitations: list[ElicitRequestURLParams],
message: str | None = None,
)
Initialize UrlElicitationRequiredError.
Source code in src/mcp/shared/exceptions.py
92 93 94 95 96 97 98 99 100 101 102 103 | |
elicitations
property
elicitations: list[ElicitRequestURLParams]
The list of URL elicitations required before the request can proceed.
from_error
classmethod
from_error(error: ErrorData) -> UrlElicitationRequiredError
Reconstruct from an ErrorData received over the wire.
Source code in src/mcp/shared/exceptions.py
110 111 112 113 114 115 116 117 118 119 | |
InvalidUriTemplate
Bases: ValueError
Raised when a URI template string is malformed or unsupported.
Attributes:
| Name | Type | Description |
|---|---|---|
template |
The template string that failed to parse. |
|
position |
Character offset where the error was detected, or None if the error is not tied to a specific position. |
Source code in src/mcp/shared/uri_template.py
124 125 126 127 128 129 130 131 132 133 134 135 136 | |
UriTemplate
dataclass
A parsed RFC 6570 URI template.
Construct via :meth:parse. Instances are immutable and hashable;
equality is based on the template string alone.
Source code in src/mcp/shared/uri_template.py
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 | |
is_template
staticmethod
Check whether a string contains URI template expressions.
A cheap heuristic for distinguishing concrete URIs from templates
without the cost of full parsing. Returns True if the string
contains at least one {...} pair.
Example::
>>> UriTemplate.is_template("file://docs/{name}")
True
>>> UriTemplate.is_template("file://docs/readme.txt")
False
Note
This does not validate the template. A True result does
not guarantee :meth:parse will succeed.
Source code in src/mcp/shared/uri_template.py
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
parse
classmethod
parse(
template: str,
*,
max_length: int = DEFAULT_MAX_TEMPLATE_LENGTH,
max_variables: int = DEFAULT_MAX_VARIABLES
) -> UriTemplate
Parse a URI template string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
An RFC 6570 URI template. |
required |
max_length
|
int
|
Maximum permitted length of the template string. Guards against resource exhaustion. |
DEFAULT_MAX_TEMPLATE_LENGTH
|
max_variables
|
int
|
Maximum number of variables permitted across
all expressions. Counting variables rather than
|
DEFAULT_MAX_VARIABLES
|
Raises:
| Type | Description |
|---|---|
InvalidUriTemplate
|
If the template is malformed, exceeds the size limits, or uses unsupported RFC 6570 features. |
Source code in src/mcp/shared/uri_template.py
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 | |
variable_names
property
All variable names in the template, in order of appearance.
query_variable_names
property
Names of variables that :meth:match treats as optional query parameters.
These are the variables in a trailing run of {?...}/{&...}
expressions, which are matched leniently: a URI that omits some
(or all) of them still matches, and the omitted names are simply
absent from the result. Any value bound to such a name therefore
needs a fallback for the omitted case.
Every other variable is bound on every successful :meth:match
(possibly to an empty string) and is not in this set. That
includes a {&...} expression with no preceding {?...}: it
never emits the ? the lenient query split keys on, so it is
matched strictly.
expand
Expand the template by substituting variable values.
String values are percent-encoded according to their operator:
simple {var} encodes reserved characters; {+var} and
{#var} leave them intact. Sequence values are joined with
commas for non-explode variables, or with the operator's
separator for explode variables.
Example::
>>> t = UriTemplate.parse("file://docs/{name}")
>>> t.expand({"name": "hello world.txt"})
'file://docs/hello%20world.txt'
>>> t = UriTemplate.parse("file://docs/{+path}")
>>> t.expand({"path": "src/main.py"})
'file://docs/src/main.py'
>>> t = UriTemplate.parse("/search{?q,lang}")
>>> t.expand({"q": "mcp", "lang": "en"})
'/search?q=mcp&lang=en'
>>> t = UriTemplate.parse("/files{/path*}")
>>> t.expand({"path": ["a", "b", "c"]})
'/files/a/b/c'
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variables
|
Mapping[str, str | Sequence[str]]
|
Values for each template variable. Keys must be
strings; values must be |
required |
Returns:
| Type | Description |
|---|---|
str
|
The expanded URI string. |
Note
Per RFC 6570, variables absent from the mapping are
silently omitted. This is the correct behavior for
optional query parameters ({?page} with no page yields
no ?page=), but for required path segments it produces
a structurally incomplete URI. If you need all variables
present, validate before calling::
missing = set(t.variable_names) - variables.keys()
if missing:
raise ValueError(f"Missing: {missing}")
Raises:
| Type | Description |
|---|---|
TypeError
|
If a value is neither |
Source code in src/mcp/shared/uri_template.py
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 | |
match
match(
uri: str,
*,
max_uri_length: int = DEFAULT_MAX_URI_LENGTH
) -> dict[str, str | list[str]] | None
Match a concrete URI against this template and extract variables.
This is the inverse of :meth:expand. The URI is matched via a
linear scan of the template and captured values are
percent-decoded. The round-trip match(expand({k: v})) == {k: v}
holds when v does not contain its operator's separator
unencoded: {.ext} with ext="tar.gz" expands to
.tar.gz but does not match — the scan stops ext at the
first . and the trailing .gz has nothing to consume it.
RFC 6570 §1.4 notes this is an inherent reversal limitation.
Matching is structural at the URI level only: a simple {name}
will not match across a literal / in the URI (the scan stops
there), but a percent-encoded %2F that decodes to / is
accepted as part of the value. Path-safety validation belongs at
a higher layer; see :mod:mcp.shared.path_security.
Example::
>>> t = UriTemplate.parse("file://docs/{name}")
>>> t.match("file://docs/readme.txt")
{'name': 'readme.txt'}
>>> t.match("file://docs/hello%20world.txt")
{'name': 'hello world.txt'}
>>> t = UriTemplate.parse("file://docs/{+path}")
>>> t.match("file://docs/src/main.py")
{'path': 'src/main.py'}
>>> t = UriTemplate.parse("/files{/path*}")
>>> t.match("/files/a/b/c")
{'path': ['a', 'b', 'c']}
Query parameters ({?q,lang} at the end of a template)
are matched leniently: order-agnostic, partial, and unrecognized
params are ignored. Absent params are omitted from the result so
downstream function defaults can apply::
>>> t = UriTemplate.parse("logs://{service}{?since,level}")
>>> t.match("logs://api")
{'service': 'api'}
>>> t.match("logs://api?level=error")
{'service': 'api', 'level': 'error'}
>>> t.match("logs://api?level=error&since=5m&utm=x")
{'service': 'api', 'since': '5m', 'level': 'error'}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
A concrete URI string. |
required |
max_uri_length
|
int
|
Maximum permitted length of the input URI.
Oversized inputs return |
DEFAULT_MAX_URI_LENGTH
|
Returns:
| Type | Description |
|---|---|
dict[str, str | list[str]] | None
|
A mapping from variable names to decoded values ( |
dict[str, str | list[str]] | None
|
scalar variables, |
dict[str, str | list[str]] | None
|
|
dict[str, str | list[str]] | None
|
|
Source code in src/mcp/shared/uri_template.py
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 | |