pydantic_ai.mcp
MCPError
Bases: RuntimeError
Raised when an MCP server returns an error response.
This exception wraps error responses from MCP servers, following the ErrorData schema from the MCP specification.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
data
instance-attribute
Additional information about the error, if provided by the server.
from_mcp_sdk
classmethod
Create an MCPError from an MCP SDK McpError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
McpError
|
An McpError from the MCP SDK. |
required |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
86 87 88 89 90 91 92 93 94 95 | |
ResourceAnnotations
dataclass
Additional properties describing MCP entities.
See the resource annotations in the MCP specification.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
audience
class-attribute
instance-attribute
audience: list[Role] | None = None
Intended audience for this entity.
priority
class-attribute
instance-attribute
Priority level for this entity, ranging from 0.0 to 1.0.
from_mcp_sdk
classmethod
from_mcp_sdk(
mcp_annotations: Annotations,
) -> ResourceAnnotations
Convert from MCP SDK Annotations to ResourceAnnotations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mcp_annotations
|
Annotations
|
The MCP SDK annotations object. |
required |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
118 119 120 121 122 123 124 125 | |
Resource
dataclass
Bases: BaseResource
A resource that can be read from an MCP server.
See the resources in the MCP specification.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
size
class-attribute
instance-attribute
size: int | None = None
The size of the raw resource content in bytes (before base64 encoding), if known.
from_mcp_sdk
classmethod
Convert from MCP SDK Resource to PydanticAI Resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mcp_resource
|
Resource
|
The MCP SDK Resource object. |
required |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
ResourceTemplate
dataclass
Bases: BaseResource
A template for parameterized resources on an MCP server.
See the resource templates in the MCP specification.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
uri_template
instance-attribute
uri_template: str
URI template (RFC 6570) for constructing resource URIs.
from_mcp_sdk
classmethod
from_mcp_sdk(
mcp_template: ResourceTemplate,
) -> ResourceTemplate
Convert from MCP SDK ResourceTemplate to PydanticAI ResourceTemplate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mcp_template
|
ResourceTemplate
|
The MCP SDK ResourceTemplate object. |
required |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | |
ServerCapabilities
dataclass
Capabilities that an MCP server supports.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
experimental
class-attribute
instance-attribute
Experimental, non-standard capabilities that the server supports.
logging
class-attribute
instance-attribute
logging: bool = False
Whether the server supports sending log messages to the client.
prompts
class-attribute
instance-attribute
prompts: bool = False
Whether the server offers any prompt templates.
prompts_list_changed
class-attribute
instance-attribute
prompts_list_changed: bool = False
Whether the server will emit notifications when the list of prompts changes.
resources
class-attribute
instance-attribute
resources: bool = False
Whether the server offers any resources to read.
resources_list_changed
class-attribute
instance-attribute
resources_list_changed: bool = False
Whether the server will emit notifications when the list of resources changes.
tools
class-attribute
instance-attribute
tools: bool = False
Whether the server offers any tools to call.
tools_list_changed
class-attribute
instance-attribute
tools_list_changed: bool = False
Whether the server will emit notifications when the list of tools changes.
completions
class-attribute
instance-attribute
completions: bool = False
Whether the server offers autocompletion suggestions for prompts and resources.
from_mcp_sdk
classmethod
from_mcp_sdk(
mcp_capabilities: ServerCapabilities,
) -> ServerCapabilities
Convert from MCP SDK ServerCapabilities to PydanticAI ServerCapabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mcp_capabilities
|
ServerCapabilities
|
The MCP SDK ServerCapabilities object. |
required |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
MCPServer
Bases: AbstractToolset[Any], ABC
Base class for attaching agents to MCP servers.
See https://modelcontextprotocol.io for more information.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
tool_prefix
instance-attribute
tool_prefix: str | None = tool_prefix
A prefix to add to all tools that are registered with the server.
If not empty, will include a trailing underscore(_).
e.g. if tool_prefix='foo', then a tool named bar will be registered as foo_bar
log_level
instance-attribute
log_level: LoggingLevel | None = log_level
The log level to set when connecting to the server, if any.
See https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/logging#logging for more details.
If None, no log level will be set.
log_handler
instance-attribute
log_handler: LoggingFnT | None = log_handler
A handler for logging messages from the server.
timeout
instance-attribute
timeout: float = timeout
The timeout in seconds to wait for the client to initialize.
read_timeout
instance-attribute
read_timeout: float = read_timeout
Maximum time in seconds to wait for new messages before timing out.
This timeout applies to the long-lived connection after it's established. If no new messages are received within this time, the connection will be considered stale and may be closed. Defaults to 5 minutes (300 seconds).
process_tool_call
instance-attribute
process_tool_call: ProcessToolCallback | None = (
process_tool_call
)
Hook to customize tool calling and optionally pass extra metadata.
allow_sampling
instance-attribute
allow_sampling: bool = allow_sampling
Whether to allow MCP sampling through this client.
sampling_model
instance-attribute
sampling_model: Model | None = sampling_model
The model to use for sampling.
max_retries
instance-attribute
max_retries: int = max_retries
The maximum number of times to retry a tool call.
elicitation_callback
class-attribute
instance-attribute
elicitation_callback: ElicitationFnT | None = (
elicitation_callback
)
Callback function to handle elicitation requests from the server.
cache_tools
instance-attribute
cache_tools: bool = cache_tools
Whether to cache the list of tools.
When enabled (default), tools are fetched once and cached until either:
- The server sends a notifications/tools/list_changed notification
- The connection is closed
Set to False for servers that change tools dynamically without sending notifications.
cache_resources
instance-attribute
cache_resources: bool = cache_resources
Whether to cache the list of resources.
When enabled (default), resources are fetched once and cached until either:
- The server sends a notifications/resources/list_changed notification
- The connection is closed
Set to False for servers that change resources dynamically without sending notifications.
client_streams
abstractmethod
async
client_streams() -> AsyncIterator[
tuple[
MemoryObjectReceiveStream[
SessionMessage | Exception
],
MemoryObjectSendStream[SessionMessage],
]
]
Create the streams for the MCP server.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
415 416 417 418 419 420 421 422 423 424 425 426 427 | |
server_info
property
server_info: Implementation
Access the information send by the MCP server during initialization.
capabilities
property
capabilities: ServerCapabilities
Access the capabilities advertised by the MCP server during initialization.
instructions
property
instructions: str | None
Access the instructions sent by the MCP server during initialization.
list_tools
async
Retrieve tools that are currently active on the server.
Tools are cached by default, with cache invalidation on:
- notifications/tools/list_changed notifications from the server
- Connection close (cache is cleared in __aexit__)
Set cache_tools=False for servers that change tools without sending notifications.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
direct_call_tool
async
direct_call_tool(
name: str,
args: dict[str, Any],
metadata: dict[str, Any] | None = None,
) -> ToolResult
Call a tool on the server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the tool to call. |
required |
args
|
dict[str, Any]
|
The arguments to pass to the tool. |
required |
metadata
|
dict[str, Any] | None
|
Request-level metadata (optional) |
None
|
Returns:
| Type | Description |
|---|---|
ToolResult
|
The result of the tool call. |
Raises:
| Type | Description |
|---|---|
ModelRetry
|
If the tool call fails. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
list_resources
async
Retrieve resources that are currently present on the server.
Resources are cached by default, with cache invalidation on:
- notifications/resources/list_changed notifications from the server
- Connection close (cache is cleared in __aexit__)
Set cache_resources=False for servers that change resources without sending notifications.
Raises:
| Type | Description |
|---|---|
MCPError
|
If the server returns an error. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
list_resource_templates
async
list_resource_templates() -> list[ResourceTemplate]
Retrieve resource templates that are currently present on the server.
Raises:
| Type | Description |
|---|---|
MCPError
|
If the server returns an error. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
625 626 627 628 629 630 631 632 633 634 635 636 637 638 | |
read_resource
async
read_resource(
uri: str,
) -> str | BinaryContent | list[str | BinaryContent]
read_resource(
uri: Resource,
) -> str | BinaryContent | list[str | BinaryContent]
read_resource(
uri: str | Resource,
) -> str | BinaryContent | list[str | BinaryContent]
Read the contents of a specific resource by URI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str | Resource
|
The URI of the resource to read, or a Resource object. |
required |
Returns:
| Type | Description |
|---|---|
str | BinaryContent | list[str | BinaryContent]
|
The resource contents. If the resource has a single content item, returns that item directly. |
str | BinaryContent | list[str | BinaryContent]
|
If the resource has multiple content items, returns a list of items. |
Raises:
| Type | Description |
|---|---|
MCPError
|
If the server returns an error. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
__aenter__
async
__aenter__() -> Self
Enter the MCP server context.
This will initialize the connection to the server.
If this server is an MCPServerStdio, the server will first be started as a subprocess.
This is a no-op if the MCP server has already been entered.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
MCPServerStdio
Bases: MCPServer
Runs an MCP server in a subprocess and communicates with it over stdin/stdout.
This class implements the stdio transport from the MCP specification. See https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#stdio for more information.
Note
Using this class as an async context manager will start the server as a subprocess when entering the context, and stop it when exiting the context.
Example:
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio
server = MCPServerStdio( # (1)!
'uv', args=['run', 'mcp-run-python', 'stdio'], timeout=10
)
agent = Agent('openai:gpt-4o', toolsets=[server])
- See MCP Run Python for more information.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
__init__
__init__(
command: str,
args: Sequence[str],
*,
env: dict[str, str] | None = None,
cwd: str | Path | None = None,
tool_prefix: str | None = None,
log_level: LoggingLevel | None = None,
log_handler: LoggingFnT | None = None,
timeout: float = 5,
read_timeout: float = 5 * 60,
process_tool_call: ProcessToolCallback | None = None,
allow_sampling: bool = True,
sampling_model: Model | None = None,
max_retries: int = 1,
elicitation_callback: ElicitationFnT | None = None,
cache_tools: bool = True,
cache_resources: bool = True,
id: str | None = None
)
Build a new MCP server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
The command to run. |
required |
args
|
Sequence[str]
|
The arguments to pass to the command. |
required |
env
|
dict[str, str] | None
|
The environment variables to set in the subprocess. |
None
|
cwd
|
str | Path | None
|
The working directory to use when spawning the process. |
None
|
tool_prefix
|
str | None
|
A prefix to add to all tools that are registered with the server. |
None
|
log_level
|
LoggingLevel | None
|
The log level to set when connecting to the server, if any. |
None
|
log_handler
|
LoggingFnT | None
|
A handler for logging messages from the server. |
None
|
timeout
|
float
|
The timeout in seconds to wait for the client to initialize. |
5
|
read_timeout
|
float
|
Maximum time in seconds to wait for new messages before timing out. |
5 * 60
|
process_tool_call
|
ProcessToolCallback | None
|
Hook to customize tool calling and optionally pass extra metadata. |
None
|
allow_sampling
|
bool
|
Whether to allow MCP sampling through this client. |
True
|
sampling_model
|
Model | None
|
The model to use for sampling. |
None
|
max_retries
|
int
|
The maximum number of times to retry a tool call. |
1
|
elicitation_callback
|
ElicitationFnT | None
|
Callback function to handle elicitation requests from the server. |
None
|
cache_tools
|
bool
|
Whether to cache the list of tools.
See |
True
|
cache_resources
|
bool
|
Whether to cache the list of resources.
See |
True
|
id
|
str | None
|
An optional unique ID for the MCP server. An MCP server needs to have an ID in order to be used in a durable execution environment like Temporal, in which case the ID will be used to identify the server's activities within the workflow. |
None
|
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
env
instance-attribute
The environment variables the CLI server will have access to.
By default the subprocess will not inherit any environment variables from the parent process.
If you want to inherit the environment variables from the parent process, use env=os.environ.
MCPServerSSE
Bases: _MCPServerHTTP
An MCP server that connects over streamable HTTP connections.
This class implements the SSE transport from the MCP specification. See https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse for more information.
Note
Using this class as an async context manager will create a new pool of HTTP connections to connect to a server which should already be running.
Example:
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerSSE
server = MCPServerSSE('http://localhost:3001/sse')
agent = Agent('openai:gpt-4o', toolsets=[server])
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
MCPServerHTTP
deprecated
Bases: MCPServerSSE
Deprecated
The MCPServerHTTP class is deprecated, use MCPServerSSE instead.
An MCP server that connects over HTTP using the old SSE transport.
This class implements the SSE transport from the MCP specification. See https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse for more information.
Note
Using this class as an async context manager will create a new pool of HTTP connections to connect to a server which should already be running.
Example:
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerHTTP
server = MCPServerHTTP('http://localhost:3001/sse')
agent = Agent('openai:gpt-4o', toolsets=[server])
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 | |
MCPServerStreamableHTTP
Bases: _MCPServerHTTP
An MCP server that connects over HTTP using the Streamable HTTP transport.
This class implements the Streamable HTTP transport from the MCP specification. See https://modelcontextprotocol.io/introduction#streamable-http for more information.
Note
Using this class as an async context manager will create a new pool of HTTP connections to connect to a server which should already be running.
Example:
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP
server = MCPServerStreamableHTTP('http://localhost:8000/mcp')
agent = Agent('openai:gpt-4o', toolsets=[server])
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
load_mcp_servers
load_mcp_servers(
config_path: str | Path,
) -> list[
MCPServerStdio | MCPServerStreamableHTTP | MCPServerSSE
]
Load MCP servers from a configuration file.
Environment variables can be referenced in the configuration file using:
- ${VAR_NAME} syntax - expands to the value of VAR_NAME, raises error if not defined
- ${VAR_NAME:-default} syntax - expands to VAR_NAME if set, otherwise uses the default value
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str | Path
|
The path to the configuration file. |
required |
Returns:
| Type | Description |
|---|---|
list[MCPServerStdio | MCPServerStreamableHTTP | MCPServerSSE]
|
A list of MCP servers. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the configuration file does not exist. |
ValidationError
|
If the configuration file does not match the schema. |
ValueError
|
If an environment variable referenced in the configuration is not defined and no default value is provided. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 | |