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
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 | |
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
128 129 130 131 132 133 134 135 136 137 | |
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
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 | |
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.
last_modified
class-attribute
instance-attribute
last_modified: str | None = None
ISO 8601 timestamp of the last modification.
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
163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
Icon
dataclass
An icon for display in user interfaces.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
mime_type
class-attribute
instance-attribute
mime_type: str | None = None
Optional MIME type for the icon.
BaseResource
dataclass
Bases: ABC
Base class for MCP resources.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
title
class-attribute
instance-attribute
title: str | None = None
Human-readable title for UI contexts.
description
class-attribute
instance-attribute
description: str | None = None
A description of what this resource represents.
mime_type
class-attribute
instance-attribute
mime_type: str | None = None
The MIME type of the resource, if known.
annotations
class-attribute
instance-attribute
annotations: ResourceAnnotations | None = None
Optional annotations for the resource.
icons
class-attribute
instance-attribute
Optional icons for the resource.
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
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 | |
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
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
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
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 | |
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
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
ResourceLink
dataclass
A resource link referenced in a prompt or tool call result.
Unlike EmbeddedResource, this does not include the resource
content directly — it is a reference to a resource that the server can read.
Note: resource links returned by tools are not guaranteed to appear in the results of
resources/list requests.
See the MCP specification.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
title
class-attribute
instance-attribute
title: str | None = None
Human-readable title for UI contexts.
description
class-attribute
instance-attribute
description: str | None = None
A description of what this linked resource represents.
mime_type
class-attribute
instance-attribute
mime_type: str | None = None
The MIME type of the linked resource, if known.
size
class-attribute
instance-attribute
size: int | None = None
The size of the raw resource content in bytes (before base64 encoding), if known.
annotations
class-attribute
instance-attribute
annotations: ResourceAnnotations | None = None
Optional annotations for the linked resource.
icons
class-attribute
instance-attribute
Optional icons for the linked resource.
metadata
class-attribute
instance-attribute
Optional metadata for the linked resource.
type
class-attribute
instance-attribute
type: Literal['resource_link'] = 'resource_link'
Discriminator for resource link content.
from_mcp_sdk
classmethod
from_mcp_sdk(
mcp_resource_link: ResourceLink,
) -> ResourceLink
Convert from MCP SDK ResourceLink to PydanticAI ResourceLink.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
PromptArgument
dataclass
An argument for a prompt template.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | |
title
class-attribute
instance-attribute
title: str | None = None
Human-readable title for the argument.
description
class-attribute
instance-attribute
description: str | None = None
A human-readable description of the argument.
required
class-attribute
instance-attribute
required: bool | None = None
Whether the argument is required or optional. If not specified, the server may determine this based on context.
Prompt
dataclass
A prompt or prompt template that the server offers.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
description
class-attribute
instance-attribute
description: str | None = None
An optional description of what this prompt provides.
arguments
class-attribute
instance-attribute
arguments: list[PromptArgument] | None = None
A list of arguments to use for templating the prompt.
icons
class-attribute
instance-attribute
An optional list of icons for this prompt.
metadata
class-attribute
instance-attribute
See MCP specification for notes on _meta usage.
from_mcp_sdk
classmethod
from_mcp_sdk(mcp_prompt: Prompt) -> Prompt
Convert from MCP SDK Prompt to PydanticAI Prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mcp_prompt
|
Prompt
|
The MCP SDK Prompt object. |
required |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
EmbeddedResource
dataclass
A resource embedded into a prompt or tool call result.
Contains the actual resource content alongside its metadata, unlike
ResourceLink which is only a reference.
See the MCP specification.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
type
class-attribute
instance-attribute
type: Literal['resource'] = 'resource'
Discriminator for embedded resource content.
mime_type
class-attribute
instance-attribute
mime_type: str | None = None
The MIME type of the resource, if known.
annotations
class-attribute
instance-attribute
annotations: ResourceAnnotations | None = None
Optional annotations for the resource.
metadata
class-attribute
instance-attribute
See MCP specification for notes on _meta usage.
resource_metadata
class-attribute
instance-attribute
_meta carried on the nested resource contents (separate from the embedding's own _meta).
from_mcp_sdk
classmethod
from_mcp_sdk(
part: EmbeddedResource, content: str | BinaryContent
) -> EmbeddedResource
Convert from MCP SDK EmbeddedResource to PydanticAI EmbeddedResource.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
482 483 484 485 486 487 488 489 490 491 492 | |
ContentBlock
module-attribute
ContentBlock = (
TextContent
| BinaryContent
| ResourceLink
| EmbeddedResource
)
A content block that can be used in prompts and tool results.
PromptMessage
dataclass
A message returned as part of a prompt result.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
499 500 501 502 503 504 505 506 507 508 509 | |
role
instance-attribute
role: PromptRole
The role of the message sender.
PromptResult
dataclass
The result of a get_prompt request.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 | |
description
class-attribute
instance-attribute
description: str | None = None
An optional description for the prompt.
metadata
class-attribute
instance-attribute
See MCP specification for notes on _meta usage.
ServerCapabilities
dataclass
Capabilities that an MCP server supports.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
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
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 | |
ToolResult
module-attribute
ToolResult = (
str
| BinaryContent
| dict[str, Any]
| list[Any]
| Sequence[
str | BinaryContent | dict[str, Any] | list[Any]
]
)
The result type of an MCP tool call.
CallToolFunc
Bases: Protocol
A callable that invokes an MCP tool — typically MCPToolset.direct_call_tool or its legacy equivalent.
Passed to user-defined ProcessToolCallback functions as
the underlying call hook. metadata is keyword-only — pass it as
await call_tool(name, args, metadata=...).
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 | |
ProcessToolCallback
module-attribute
ProcessToolCallback = Callable[
[RunContext[Any], CallToolFunc, str, dict[str, Any]],
Awaitable[ToolResult],
]
A process tool callback.
It accepts a run context, the original tool call function, a tool name, and arguments.
Allows wrapping an MCP server tool call to customize it, including adding extra request metadata.
MCPToolsetClient
module-attribute
MCPToolsetClient: TypeAlias = (
Client[Any]
| ClientTransport
| FastMCP
| FastMCP
| AnyUrl
| Path
| str
)
Anything MCPToolset accepts as its client argument — a pre-built fastmcp.Client, a FastMCP
ClientTransport, an in-process FastMCP server, an AnyUrl/URL string, a script Path, or a
URL/path/script string.
For multi-server JSON config files, use load_mcp_toolsets
instead — it expands env vars and constructs one MCPToolset per server entry.
MCPToolset
dataclass
Bases: AbstractToolset[AgentDepsT]
A toolset for connecting to an MCP server.
MCPToolset is the recommended way to use Model Context Protocol
servers in Pydantic AI. It is built on the FastMCP Client, which
supports the full MCP protocol — tools, resources, sampling, elicitation, OAuth — and a wide
range of transports (HTTP, SSE, stdio, in-process FastMCP servers, multi-server configs).
Pass any input that FastMCP can build a transport from — a URL, a script path, a FastMCP
server instance for in-process testing — or a pre-built fastmcp.Client for full control over
its configuration. For multi-server JSON config files, use
load_mcp_toolsets instead.
Example — connect to a streamable-HTTP MCP server:
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPToolset
toolset = MCPToolset('http://localhost:8000/mcp')
agent = Agent('openai:gpt-5', toolsets=[toolset])
Example — connect to a local stdio MCP server:
from pydantic_ai.mcp import MCPToolset
toolset = MCPToolset('my_mcp_server.py')
Example — pass a pre-built FastMCP Client for full configuration control:
from fastmcp.client import Client
from fastmcp.client.transports import StreamableHttpTransport
from pydantic_ai.mcp import MCPToolset
client = Client(StreamableHttpTransport('http://localhost:8000/mcp'), auth='oauth')
toolset = MCPToolset(client)
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 | |
client
instance-attribute
client: Client[Any]
The underlying FastMCP Client. Always normalized to a fastmcp.Client regardless of how
the toolset was constructed.
__init__
__init__(
client: MCPToolsetClient,
*,
id: str | None = None,
max_retries: int | None = None,
tool_error_behavior: Literal[
"retry", "error"
] = "retry",
process_tool_call: ProcessToolCallback | None = None,
cache_tools: bool = True,
cache_resources: bool = True,
cache_prompts: bool = True,
include_instructions: bool = False,
include_return_schema: bool | None = None,
sampling_model: Model | None = None,
sampling_handler: (
SamplingHandler[Any, Any] | None
) = None,
elicitation_handler: (
ElicitationHandler[Any, Any] | None
) = None,
log_handler: LogHandler | None = None,
log_level: LoggingLevel | None = None,
progress_handler: ProgressHandler | None = None,
message_handler: MessageHandlerT | None = None,
client_info: Implementation | None = None,
init_timeout: float | None = _UNSET,
read_timeout: float | None = _UNSET,
roots: RootsList | RootsHandler[Any] | None = None,
auth: Auth | Literal["oauth"] | str | None = None,
verify: SSLContext | bool | str | None = None,
headers: dict[str, str] | None = None,
http_client: AsyncClient | None = None
)
Build a new MCPToolset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
MCPToolsetClient
|
How to connect to the MCP server. See the class docstring for accepted shapes. |
required |
id
|
str | None
|
An optional unique identifier for this toolset. Required for use in durable execution environments like Temporal or DBOS, where it identifies the toolset's activities/steps within a workflow. |
None
|
max_retries
|
int | None
|
Maximum number of times a tool call may be retried after a |
None
|
tool_error_behavior
|
Literal['retry', 'error']
|
|
'retry'
|
process_tool_call
|
ProcessToolCallback | None
|
Hook to wrap tool calls. See
|
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
|
cache_prompts
|
bool
|
Whether to cache the list of prompts. See
|
True
|
include_instructions
|
bool
|
Whether to include the server's instructions in the agent's
instructions. See
|
False
|
include_return_schema
|
bool | None
|
Whether to include return schemas in tool definitions. See
|
None
|
sampling_model
|
Model | None
|
A Pydantic AI model the server may sample from. Mutually exclusive with
|
None
|
sampling_handler
|
SamplingHandler[Any, Any] | None
|
A FastMCP-shaped sampling handler. Use for full control over the sampling response. |
None
|
elicitation_handler
|
ElicitationHandler[Any, Any] | None
|
A FastMCP-shaped elicitation handler that receives MCP
|
None
|
log_handler
|
LogHandler | None
|
A FastMCP-shaped log handler that receives log messages from the server. |
None
|
log_level
|
LoggingLevel | None
|
Log level requested from the server via |
None
|
progress_handler
|
ProgressHandler | None
|
A FastMCP-shaped progress handler. |
None
|
message_handler
|
MessageHandlerT | None
|
A FastMCP-shaped message handler called for every server-sent message.
Pydantic AI installs its own message handler internally to invalidate caches on
|
None
|
client_info
|
Implementation | None
|
Information describing the MCP client implementation, sent to the server during initialization. |
None
|
init_timeout
|
float | None
|
Timeout in seconds for the initial connection and |
_UNSET
|
read_timeout
|
float | None
|
Maximum time in seconds to wait for new messages on the long-lived connection. Defaults to 5 minutes. |
_UNSET
|
roots
|
RootsList | RootsHandler[Any] | None
|
Filesystem roots advertised to the server. |
None
|
auth
|
Auth | Literal['oauth'] | str | None
|
HTTP authentication for HTTP transports — an |
None
|
verify
|
SSLContext | bool | str | None
|
SSL verification mode for HTTP transports — an |
None
|
headers
|
dict[str, str] | None
|
Extra HTTP headers for HTTP transports. Mutually exclusive with |
None
|
http_client
|
AsyncClient | None
|
A pre-configured |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a pre-built |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
max_retries
instance-attribute
max_retries: int | None = max_retries
Maximum number of times a tool call may be retried after a ModelRetry.
None (default) inherits the agent's retry count at runtime. Set explicitly to override.
tool_error_behavior
instance-attribute
tool_error_behavior: Literal["retry", "error"] = (
tool_error_behavior
)
How to handle tool errors raised by the server.
'retry' (default) raises ModelRetry so the model can
self-correct; 'error' propagates the underlying fastmcp.exceptions.ToolError to the caller.
process_tool_call
instance-attribute
process_tool_call: ProcessToolCallback | None = (
process_tool_call
)
Hook to wrap tool calls — useful for adding request-level metadata, custom retry policies,
or telemetry. See ProcessToolCallback.
cache_tools
instance-attribute
cache_tools: bool = cache_tools
Whether to cache the list of tools across get_tools() calls.
When enabled (default), tools are fetched once and cached until either:
- The server sends a
notifications/tools/list_changednotification - The toolset is fully exited (last
__aexit__matches the first__aenter__)
Set to False for servers that change tools dynamically without sending notifications, or when
passing a pre-built FastMCP Client (the cache-invalidation message handler isn't installed in
that case, so caches are only invalidated by session close).
cache_resources
instance-attribute
cache_resources: bool = cache_resources
Whether to cache the list of resources across list_resources() calls.
Same semantics as cache_tools but for
notifications/resources/list_changed notifications.
cache_prompts
instance-attribute
cache_prompts: bool = cache_prompts
Whether to cache the list of prompts across list_prompts() calls.
Same semantics as cache_tools but for
notifications/prompts/list_changed notifications.
include_instructions
instance-attribute
include_instructions: bool = include_instructions
Whether to include the server's initialize instructions string in the agent's instruction set.
Defaults to False for backward compatibility. When True, the instructions returned by the
server during initialization are added to the agent's instructions.
include_return_schema
instance-attribute
include_return_schema: bool | None = include_return_schema
Whether to include each tool's outputSchema in the schema sent to the model.
When None (the default), defaults to False unless the
IncludeToolReturnSchemas capability is
used.
sampling_model
instance-attribute
sampling_model: Model | None = sampling_model
A Pydantic AI model that the server may sample from via the MCP sampling/createMessage flow.
When set (and no explicit sampling_handler is passed), Pydantic AI builds a sampling handler
that delegates to this model with the request's maxTokens/temperature/stopSequences
settings applied. If both sampling_model and sampling_handler are passed, an error is raised.
log_level
instance-attribute
log_level: LoggingLevel | None = log_level
Log level requested from the server via logging/setLevel after initialization.
None (default) leaves the server's default log level alone. Combine with log_handler to
receive log messages.
server_info
property
server_info: Implementation
The server-implementation info sent during initialization.
Raises AttributeError when accessed before the toolset has been entered.
capabilities
property
capabilities: ServerCapabilities
The capabilities advertised by the server during initialization.
Raises AttributeError when accessed before the toolset has been entered.
instructions
property
instructions: str | None
The instructions sent by the server during initialization.
Raises AttributeError when accessed before the toolset has been entered.
is_running
property
is_running: bool
Whether the toolset is currently entered (the FastMCP session is open).
set_sampling_model
set_sampling_model(model: Model) -> None
Set the sampling_model on an already-constructed toolset.
Swaps both the public attribute and the underlying FastMCP client's sampling callback. Takes effect on the next session opened by the client; calls already in flight on an existing session continue using the previously configured handler.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1049 1050 1051 1052 1053 1054 1055 1056 1057 | |
get_instructions
async
get_instructions(
ctx: RunContext[AgentDepsT],
) -> InstructionPart | None
Return the server's instructions if include_instructions is enabled.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1112 1113 1114 1115 1116 1117 1118 1119 1120 | |
list_tools
async
Retrieve the tools currently exposed by the server.
When cache_tools is enabled (default), results
are cached and invalidated by notifications/tools/list_changed or the toolset's last
__aexit__.
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 | |
direct_call_tool
async
direct_call_tool(
name: str,
args: dict[str, Any],
*,
metadata: dict[str, Any] | None = None,
use_task: bool = False
) -> Any
Call a tool on the server directly.
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
|
Optional request-level |
None
|
use_task
|
bool
|
When |
False
|
Raises:
| Type | Description |
|---|---|
ModelRetry
|
If the tool errors and |
ToolError
|
If the tool errors and |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
list_prompts
async
Retrieve the prompts currently exposed by the server.
When cache_prompts is enabled (default),
results are cached and invalidated by notifications/prompts/list_changed or the
toolset's last __aexit__.
Returns an empty list if the server does not advertise the prompts capability.
Raises:
| Type | Description |
|---|---|
MCPError
|
If the server returns an error. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
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 | |
get_prompt
async
get_prompt(
name: str, arguments: dict[str, str] | None = None
) -> PromptResult
Retrieve a specific prompt from the server, optionally parameterized.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the prompt to retrieve. |
required |
arguments
|
dict[str, str] | None
|
Arguments to parameterize the prompt, if applicable. |
None
|
Raises:
| Type | Description |
|---|---|
MCPError
|
If the server doesn't advertise the |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 | |
list_resources
async
Retrieve the resources currently exposed by the server.
When cache_resources is enabled (default),
results are cached and invalidated by notifications/resources/list_changed or the
toolset's last __aexit__.
Returns an empty list if the server does not advertise the resources capability.
Raises:
| Type | Description |
|---|---|
MCPError
|
If the server returns an error. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 | |
list_resource_templates
async
list_resource_templates() -> list[ResourceTemplate]
Retrieve the resource templates currently exposed by the server.
Returns an empty list if the server does not advertise the resources capability.
Raises:
| Type | Description |
|---|---|
MCPError
|
If the server returns an error. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 | |
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 |
required |
Returns:
| Type | Description |
|---|---|
str | BinaryContent | list[str | BinaryContent]
|
The resource contents — a single value if the resource has one content item, or a list |
str | BinaryContent | list[str | BinaryContent]
|
otherwise. Text content is returned as |
str | BinaryContent | list[str | BinaryContent]
|
Raises:
| Type | Description |
|---|---|
MCPError
|
If the server returns an error. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 | |
load_mcp_toolsets
load_mcp_toolsets(
config_path: str | Path,
) -> list[AbstractToolset[Any]]
Load MCPToolsets from a configuration file.
The configuration file uses the same mcpServers JSON shape as Claude Desktop, Cursor, and the
MCP specification. Each server entry produces one MCPToolset,
wrapped in a PrefixedToolset using the server's name
as prefix to disambiguate tools across multiple servers.
Environment variables can be referenced in the configuration file using:
${VAR_NAME}syntax — expands to the value ofVAR_NAME, raises if not defined${VAR_NAME:-default}syntax — expands toVAR_NAMEif set, otherwise the default
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str | Path
|
Path to the JSON configuration file. |
required |
Returns:
| Type | Description |
|---|---|
list[AbstractToolset[Any]]
|
A list of toolsets, one per server in the config file, each prefixed with the server name. |
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 is provided. |
Source code in pydantic_ai_slim/pydantic_ai/mcp.py
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 | |