[ Skip to content ](https://ai.pydantic.dev/api/mcp/#pydantic_aimcp)
**Join us at the inaugural PyAI Conf in San Francisco on March 10th![Learn More](https://pyai.events/?utm_source=pydantic-ai) **
[ ![logo](https://ai.pydantic.dev/img/logo-white.svg) ](https://ai.pydantic.dev/ "Pydantic AI")
Pydantic AI
pydantic_ai.mcp
Type to start searching
[ pydantic/pydantic-ai
  * v1.63.0
  * 15.1k
  * 1.7k

](https://github.com/pydantic/pydantic-ai "Go to repository")
[ ![logo](https://ai.pydantic.dev/img/logo-white.svg) ](https://ai.pydantic.dev/ "Pydantic AI") Pydantic AI
[ pydantic/pydantic-ai
  * v1.63.0
  * 15.1k
  * 1.7k

](https://github.com/pydantic/pydantic-ai "Go to repository")
  * [ Pydantic AI  ](https://ai.pydantic.dev/)
  * [ Installation  ](https://ai.pydantic.dev/install/)
  * [ Getting Help  ](https://ai.pydantic.dev/help/)
  * [ Troubleshooting  ](https://ai.pydantic.dev/troubleshooting/)
  * [ Pydantic AI Gateway  ](https://ai.pydantic.dev/gateway/)
  * Documentation
    * Core Concepts
      * [ Agents  ](https://ai.pydantic.dev/agent/)
      * [ Dependencies  ](https://ai.pydantic.dev/dependencies/)
      * [ Function Tools  ](https://ai.pydantic.dev/tools/)
      * [ Output  ](https://ai.pydantic.dev/output/)
      * [ Messages and chat history  ](https://ai.pydantic.dev/message-history/)
      * [ Direct Model Requests  ](https://ai.pydantic.dev/direct/)
    * Models & Providers
      * [ Overview  ](https://ai.pydantic.dev/models/overview/)
      * [ OpenAI  ](https://ai.pydantic.dev/models/openai/)
      * [ Anthropic  ](https://ai.pydantic.dev/models/anthropic/)
      * [ Google  ](https://ai.pydantic.dev/models/google/)
      * [ xAI  ](https://ai.pydantic.dev/models/xai/)
      * [ Bedrock  ](https://ai.pydantic.dev/models/bedrock/)
      * [ Cerebras  ](https://ai.pydantic.dev/models/cerebras/)
      * [ Cohere  ](https://ai.pydantic.dev/models/cohere/)
      * [ Groq  ](https://ai.pydantic.dev/models/groq/)
      * [ Hugging Face  ](https://ai.pydantic.dev/models/huggingface/)
      * [ Mistral  ](https://ai.pydantic.dev/models/mistral/)
      * [ OpenRouter  ](https://ai.pydantic.dev/models/openrouter/)
      * [ Outlines  ](https://ai.pydantic.dev/models/outlines/)
    * Tools & Toolsets
      * [ Function Tools  ](https://ai.pydantic.dev/tools/)
      * [ Advanced Tool Features  ](https://ai.pydantic.dev/tools-advanced/)
      * [ Toolsets  ](https://ai.pydantic.dev/toolsets/)
      * [ Deferred Tools  ](https://ai.pydantic.dev/deferred-tools/)
      * [ Built-in Tools  ](https://ai.pydantic.dev/builtin-tools/)
      * [ Common Tools  ](https://ai.pydantic.dev/common-tools/)
      * [ Third-Party Tools  ](https://ai.pydantic.dev/third-party-tools/)
    * Advanced Features
      * [ Image, Audio, Video & Document Input  ](https://ai.pydantic.dev/input/)
      * [ Thinking  ](https://ai.pydantic.dev/thinking/)
      * [ HTTP Request Retries  ](https://ai.pydantic.dev/retries/)
    * MCP
      * [ Overview  ](https://ai.pydantic.dev/mcp/overview/)
      * [ Client  ](https://ai.pydantic.dev/mcp/client/)
      * [ FastMCP Client  ](https://ai.pydantic.dev/mcp/fastmcp-client/)
      * [ Server  ](https://ai.pydantic.dev/mcp/server/)
    * [ Multi-Agent Patterns  ](https://ai.pydantic.dev/multi-agent-applications/)
    * [ Web Chat UI  ](https://ai.pydantic.dev/web/)
    * [ Embeddings  ](https://ai.pydantic.dev/embeddings/)
    * [ Testing  ](https://ai.pydantic.dev/testing/)
  * Pydantic Evals
    * [ Overview  ](https://ai.pydantic.dev/evals/)
    * Getting Started
      * [ Quick Start  ](https://ai.pydantic.dev/evals/quick-start/)
      * [ Core Concepts  ](https://ai.pydantic.dev/evals/core-concepts/)
    * Evaluators
      * [ Overview  ](https://ai.pydantic.dev/evals/evaluators/overview/)
      * [ Built-in Evaluators  ](https://ai.pydantic.dev/evals/evaluators/built-in/)
      * [ LLM Judge  ](https://ai.pydantic.dev/evals/evaluators/llm-judge/)
      * [ Custom Evaluators  ](https://ai.pydantic.dev/evals/evaluators/custom/)
      * [ Report Evaluators  ](https://ai.pydantic.dev/evals/evaluators/report-evaluators/)
      * [ Span-Based  ](https://ai.pydantic.dev/evals/evaluators/span-based/)
    * How-To Guides
      * [ Logfire Integration  ](https://ai.pydantic.dev/evals/how-to/logfire-integration/)
      * [ Dataset Management  ](https://ai.pydantic.dev/evals/how-to/dataset-management/)
      * [ Dataset Serialization  ](https://ai.pydantic.dev/evals/how-to/dataset-serialization/)
      * [ Concurrency & Performance  ](https://ai.pydantic.dev/evals/how-to/concurrency/)
      * [ Multi-Run Evaluation  ](https://ai.pydantic.dev/evals/how-to/multi-run/)
      * [ Retry Strategies  ](https://ai.pydantic.dev/evals/how-to/retry-strategies/)
      * [ Metrics & Attributes  ](https://ai.pydantic.dev/evals/how-to/metrics-attributes/)
    * Examples
      * [ Simple Validation  ](https://ai.pydantic.dev/evals/examples/simple-validation/)
  * Pydantic Graph
    * [ Overview  ](https://ai.pydantic.dev/graph/)
    * [ Beta API  ](https://ai.pydantic.dev/graph/beta/)
      * [ Steps  ](https://ai.pydantic.dev/graph/beta/steps/)
      * [ Joins & Reducers  ](https://ai.pydantic.dev/graph/beta/joins/)
      * [ Decisions  ](https://ai.pydantic.dev/graph/beta/decisions/)
      * [ Parallel Execution  ](https://ai.pydantic.dev/graph/beta/parallel/)
  * Integrations
    * [ Debugging & Monitoring with Pydantic Logfire  ](https://ai.pydantic.dev/logfire/)
    * Durable Execution
      * [ Overview  ](https://ai.pydantic.dev/durable_execution/overview/)
      * [ Temporal  ](https://ai.pydantic.dev/durable_execution/temporal/)
      * [ DBOS  ](https://ai.pydantic.dev/durable_execution/dbos/)
      * [ Prefect  ](https://ai.pydantic.dev/durable_execution/prefect/)
    * UI Event Streams
      * [ Overview  ](https://ai.pydantic.dev/ui/overview/)
      * [ AG-UI  ](https://ai.pydantic.dev/ui/ag-ui/)
      * [ Vercel AI  ](https://ai.pydantic.dev/ui/vercel-ai/)
    * [ Agent2Agent (A2A)  ](https://ai.pydantic.dev/a2a/)
  * Related Packages
    * [ clai  ](https://ai.pydantic.dev/cli/)
  * Examples
    * [ Setup  ](https://ai.pydantic.dev/examples/setup/)
    * Getting Started
      * [ Pydantic Model  ](https://ai.pydantic.dev/examples/pydantic-model/)
      * [ Weather agent  ](https://ai.pydantic.dev/examples/weather-agent/)
    * Conversational Agents
      * [ Chat App with FastAPI  ](https://ai.pydantic.dev/examples/chat-app/)
      * [ Bank support  ](https://ai.pydantic.dev/examples/bank-support/)
    * Data & Analytics
      * [ SQL Generation  ](https://ai.pydantic.dev/examples/sql-gen/)
      * [ Data Analyst  ](https://ai.pydantic.dev/examples/data-analyst/)
      * [ RAG  ](https://ai.pydantic.dev/examples/rag/)
    * Streaming
      * [ Stream markdown  ](https://ai.pydantic.dev/examples/stream-markdown/)
      * [ Stream whales  ](https://ai.pydantic.dev/examples/stream-whales/)
    * Complex Workflows
      * [ Flight booking  ](https://ai.pydantic.dev/examples/flight-booking/)
      * [ Question Graph  ](https://ai.pydantic.dev/examples/question-graph/)
    * Business Applications
      * [ Slack Lead Qualifier with Modal  ](https://ai.pydantic.dev/examples/slack-lead-qualifier/)
    * UI Examples
      * [ Agent User Interaction (AG-UI)  ](https://ai.pydantic.dev/examples/ag-ui/)
  * API Reference
    * pydantic_ai
      * [ pydantic_ai.ag_ui  ](https://ai.pydantic.dev/api/ag_ui/)
      * [ pydantic_ai.agent  ](https://ai.pydantic.dev/api/agent/)
      * [ pydantic_ai.builtin_tools  ](https://ai.pydantic.dev/api/builtin_tools/)
      * [ pydantic_ai.common_tools  ](https://ai.pydantic.dev/api/common_tools/)
      * [ pydantic_ai — Concurrency  ](https://ai.pydantic.dev/api/concurrency/)
      * [ pydantic_ai.direct  ](https://ai.pydantic.dev/api/direct/)
      * [ pydantic_ai.durable_exec  ](https://ai.pydantic.dev/api/durable_exec/)
      * [ pydantic_ai.embeddings  ](https://ai.pydantic.dev/api/embeddings/)
      * [ pydantic_ai.exceptions  ](https://ai.pydantic.dev/api/exceptions/)
      * [ pydantic_ai.ext  ](https://ai.pydantic.dev/api/ext/)
      * [ pydantic_ai.format_prompt  ](https://ai.pydantic.dev/api/format_prompt/)
      * pydantic_ai.mcp  [ pydantic_ai.mcp  ](https://ai.pydantic.dev/api/mcp/)
        * [ mcp  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp)
        * [ MCPError  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError)
          * [ message  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError.message)
          * [ code  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError.code)
          * [ data  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError.data)
          * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError.from_mcp_sdk)
        * [ ResourceAnnotations  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations)
          * [ audience  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations.audience)
          * [ priority  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations.priority)
          * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations.from_mcp_sdk)
        * [ BaseResource  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource)
          * [ name  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.name)
          * [ title  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.title)
          * [ description  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.description)
          * [ mime_type  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.mime_type)
          * [ annotations  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.annotations)
          * [ metadata  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.metadata)
        * [ Resource  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource)
          * [ uri  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource.uri)
          * [ size  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource.size)
          * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource.from_mcp_sdk)
        * [ ResourceTemplate  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceTemplate)
          * [ uri_template  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceTemplate.uri_template)
          * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceTemplate.from_mcp_sdk)
        * [ ServerCapabilities  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities)
          * [ experimental  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.experimental)
          * [ logging  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.logging)
          * [ prompts  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.prompts)
          * [ prompts_list_changed  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.prompts_list_changed)
          * [ resources  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.resources)
          * [ resources_list_changed  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.resources_list_changed)
          * [ tools  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.tools)
          * [ tools_list_changed  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.tools_list_changed)
          * [ completions  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.completions)
          * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.from_mcp_sdk)
        * [ MCPServer  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer)
          * [ tool_prefix  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.tool_prefix)
          * [ log_level  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.log_level)
          * [ log_handler  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.log_handler)
          * [ timeout  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.timeout)
          * [ read_timeout  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.read_timeout)
          * [ process_tool_call  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.process_tool_call)
          * [ allow_sampling  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.allow_sampling)
          * [ sampling_model  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.sampling_model)
          * [ max_retries  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.max_retries)
          * [ elicitation_callback  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.elicitation_callback)
          * [ cache_tools  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.cache_tools)
          * [ cache_resources  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.cache_resources)
          * [ client_streams  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.client_streams)
          * [ server_info  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.server_info)
          * [ capabilities  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.capabilities)
          * [ instructions  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.instructions)
          * [ list_tools  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.list_tools)
          * [ direct_call_tool  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.direct_call_tool)
          * [ list_resources  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.list_resources)
          * [ list_resource_templates  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.list_resource_templates)
          * [ read_resource  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.read_resource)
          * [ __aenter__  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.__aenter__)
          * [ is_running  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.is_running)
        * [ MCPServerStdio  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio)
          * [ __init__  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.__init__)
          * [ command  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.command)
          * [ args  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.args)
          * [ env  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.env)
          * [ cwd  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.cwd)
        * [ MCPServerSSE  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerSSE)
        * [ MCPServerHTTP  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerHTTP)
        * [ MCPServerStreamableHTTP  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStreamableHTTP)
        * [ ToolResult  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ToolResult)
        * [ CallToolFunc  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.CallToolFunc)
        * [ ProcessToolCallback  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ProcessToolCallback)
        * [ MCPServerConfig  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerConfig)
        * [ load_mcp_servers  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.load_mcp_servers)
      * [ pydantic_ai.messages  ](https://ai.pydantic.dev/api/messages/)
      * [ pydantic_ai.models.anthropic  ](https://ai.pydantic.dev/api/models/anthropic/)
      * [ pydantic_ai.models  ](https://ai.pydantic.dev/api/models/base/)
      * [ pydantic_ai.models.bedrock  ](https://ai.pydantic.dev/api/models/bedrock/)
      * [ pydantic_ai.models.cerebras  ](https://ai.pydantic.dev/api/models/cerebras/)
      * [ pydantic_ai.models.cohere  ](https://ai.pydantic.dev/api/models/cohere/)
      * [ pydantic_ai.models.fallback  ](https://ai.pydantic.dev/api/models/fallback/)
      * [ pydantic_ai.models.function  ](https://ai.pydantic.dev/api/models/function/)
      * [ pydantic_ai.models.google  ](https://ai.pydantic.dev/api/models/google/)
      * [ pydantic_ai.models.xai  ](https://ai.pydantic.dev/api/models/xai/)
      * [ pydantic_ai.models.groq  ](https://ai.pydantic.dev/api/models/groq/)
      * [ pydantic_ai.models.huggingface  ](https://ai.pydantic.dev/api/models/huggingface/)
      * [ pydantic_ai.models.instrumented  ](https://ai.pydantic.dev/api/models/instrumented/)
      * [ pydantic_ai.models.mcp_sampling  ](https://ai.pydantic.dev/api/models/mcp-sampling/)
      * [ pydantic_ai.models.mistral  ](https://ai.pydantic.dev/api/models/mistral/)
      * [ pydantic_ai.models.openai  ](https://ai.pydantic.dev/api/models/openai/)
      * [ pydantic_ai.models.openrouter  ](https://ai.pydantic.dev/api/models/openrouter/)
      * [ pydantic_ai.models.outlines  ](https://ai.pydantic.dev/api/models/outlines/)
      * [ pydantic_ai.models.test  ](https://ai.pydantic.dev/api/models/test/)
      * [ pydantic_ai.models.wrapper  ](https://ai.pydantic.dev/api/models/wrapper/)
      * [ pydantic_ai.output  ](https://ai.pydantic.dev/api/output/)
      * [ pydantic_ai.profiles  ](https://ai.pydantic.dev/api/profiles/)
      * [ pydantic_ai.providers  ](https://ai.pydantic.dev/api/providers/)
      * [ pydantic_ai.result  ](https://ai.pydantic.dev/api/result/)
      * [ pydantic_ai.retries  ](https://ai.pydantic.dev/api/retries/)
      * [ pydantic_ai.run  ](https://ai.pydantic.dev/api/run/)
      * [ pydantic_ai.settings  ](https://ai.pydantic.dev/api/settings/)
      * [ pydantic_ai.tools  ](https://ai.pydantic.dev/api/tools/)
      * [ pydantic_ai.toolsets  ](https://ai.pydantic.dev/api/toolsets/)
      * [ pydantic_ai.ui.ag_ui  ](https://ai.pydantic.dev/api/ui/ag_ui/)
      * [ pydantic_ai.ui  ](https://ai.pydantic.dev/api/ui/base/)
      * [ pydantic_ai.ui.vercel_ai  ](https://ai.pydantic.dev/api/ui/vercel_ai/)
      * [ pydantic_ai.usage  ](https://ai.pydantic.dev/api/usage/)
    * pydantic_evals
      * [ pydantic_evals.dataset  ](https://ai.pydantic.dev/api/pydantic_evals/dataset/)
      * [ pydantic_evals.evaluators  ](https://ai.pydantic.dev/api/pydantic_evals/evaluators/)
      * [ pydantic_evals.reporting  ](https://ai.pydantic.dev/api/pydantic_evals/reporting/)
      * [ pydantic_evals.otel  ](https://ai.pydantic.dev/api/pydantic_evals/otel/)
      * [ pydantic_evals.generation  ](https://ai.pydantic.dev/api/pydantic_evals/generation/)
    * pydantic_graph
      * [ pydantic_graph  ](https://ai.pydantic.dev/api/pydantic_graph/graph/)
      * [ pydantic_graph.nodes  ](https://ai.pydantic.dev/api/pydantic_graph/nodes/)
      * [ pydantic_graph.persistence  ](https://ai.pydantic.dev/api/pydantic_graph/persistence/)
      * [ pydantic_graph.mermaid  ](https://ai.pydantic.dev/api/pydantic_graph/mermaid/)
      * [ pydantic_graph.exceptions  ](https://ai.pydantic.dev/api/pydantic_graph/exceptions/)
      * Beta API
        * [ pydantic_graph.beta  ](https://ai.pydantic.dev/api/pydantic_graph/beta/)
        * [ pydantic_graph.beta.graph  ](https://ai.pydantic.dev/api/pydantic_graph/beta_graph/)
        * [ pydantic_graph.beta.graph_builder  ](https://ai.pydantic.dev/api/pydantic_graph/beta_graph_builder/)
        * [ pydantic_graph.beta.step  ](https://ai.pydantic.dev/api/pydantic_graph/beta_step/)
        * [ pydantic_graph.beta.join  ](https://ai.pydantic.dev/api/pydantic_graph/beta_join/)
        * [ pydantic_graph.beta.decision  ](https://ai.pydantic.dev/api/pydantic_graph/beta_decision/)
        * [ pydantic_graph.beta.node  ](https://ai.pydantic.dev/api/pydantic_graph/beta_node/)
    * fasta2a
      * [ fasta2a  ](https://ai.pydantic.dev/api/fasta2a/)
  * Project
    * [ Contributing  ](https://ai.pydantic.dev/contributing/)
    * [ Upgrade Guide  ](https://ai.pydantic.dev/changelog/)
    * [ Version policy  ](https://ai.pydantic.dev/version-policy/)


  * [ mcp  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp)
  * [ MCPError  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError)
    * [ message  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError.message)
    * [ code  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError.code)
    * [ data  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError.data)
    * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError.from_mcp_sdk)
  * [ ResourceAnnotations  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations)
    * [ audience  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations.audience)
    * [ priority  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations.priority)
    * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations.from_mcp_sdk)
  * [ BaseResource  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource)
    * [ name  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.name)
    * [ title  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.title)
    * [ description  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.description)
    * [ mime_type  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.mime_type)
    * [ annotations  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.annotations)
    * [ metadata  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource.metadata)
  * [ Resource  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource)
    * [ uri  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource.uri)
    * [ size  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource.size)
    * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource.from_mcp_sdk)
  * [ ResourceTemplate  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceTemplate)
    * [ uri_template  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceTemplate.uri_template)
    * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceTemplate.from_mcp_sdk)
  * [ ServerCapabilities  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities)
    * [ experimental  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.experimental)
    * [ logging  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.logging)
    * [ prompts  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.prompts)
    * [ prompts_list_changed  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.prompts_list_changed)
    * [ resources  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.resources)
    * [ resources_list_changed  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.resources_list_changed)
    * [ tools  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.tools)
    * [ tools_list_changed  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.tools_list_changed)
    * [ completions  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.completions)
    * [ from_mcp_sdk  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities.from_mcp_sdk)
  * [ MCPServer  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer)
    * [ tool_prefix  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.tool_prefix)
    * [ log_level  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.log_level)
    * [ log_handler  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.log_handler)
    * [ timeout  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.timeout)
    * [ read_timeout  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.read_timeout)
    * [ process_tool_call  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.process_tool_call)
    * [ allow_sampling  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.allow_sampling)
    * [ sampling_model  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.sampling_model)
    * [ max_retries  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.max_retries)
    * [ elicitation_callback  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.elicitation_callback)
    * [ cache_tools  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.cache_tools)
    * [ cache_resources  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.cache_resources)
    * [ client_streams  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.client_streams)
    * [ server_info  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.server_info)
    * [ capabilities  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.capabilities)
    * [ instructions  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.instructions)
    * [ list_tools  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.list_tools)
    * [ direct_call_tool  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.direct_call_tool)
    * [ list_resources  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.list_resources)
    * [ list_resource_templates  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.list_resource_templates)
    * [ read_resource  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.read_resource)
    * [ __aenter__  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.__aenter__)
    * [ is_running  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.is_running)
  * [ MCPServerStdio  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio)
    * [ __init__  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.__init__)
    * [ command  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.command)
    * [ args  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.args)
    * [ env  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.env)
    * [ cwd  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio.cwd)
  * [ MCPServerSSE  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerSSE)
  * [ MCPServerHTTP  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerHTTP)
  * [ MCPServerStreamableHTTP  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStreamableHTTP)
  * [ ToolResult  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ToolResult)
  * [ CallToolFunc  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.CallToolFunc)
  * [ ProcessToolCallback  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ProcessToolCallback)
  * [ MCPServerConfig  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerConfig)
  * [ load_mcp_servers  ](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.load_mcp_servers)


  1. [ Pydantic AI  ](https://ai.pydantic.dev/)
  2. [ API Reference  ](https://ai.pydantic.dev/api/ag_ui/)
  3. [ pydantic_ai  ](https://ai.pydantic.dev/api/ag_ui/)


# `pydantic_ai.mcp`
###  MCPError
Bases: `RuntimeError[](https://docs.python.org/3/library/exceptions.html#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`
```
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
```
| ```
class MCPError(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.
    """

    message: str
    """The error message."""

    code: int
    """The error code returned by the server."""

    data: dict[str, Any] | None
    """Additional information about the error, if provided by the server."""

    def __init__(self, message: str, code: int, data: dict[str, Any] | None = None):
        self.message = message
        self.code = code
        self.data = data
        super().__init__(message)

    @classmethod
    def from_mcp_sdk(cls, error: mcp_exceptions.McpError) -> MCPError:
        """Create an MCPError from an MCP SDK McpError.

        Args:
            error: An McpError from the MCP SDK.
        """
        # Extract error data from the McpError.error attribute
        error_data = error.error
        return cls(message=error_data.message, code=error_data.code, data=error_data.data)

    def __str__(self) -> str:
        if self.data:
            return f'{self.message} (code: {self.code}, data: {self.data})'
        return f'{self.message} (code: {self.code})'

```

---|---
####  message `instance-attribute`
```
message: str[](https://docs.python.org/3/library/stdtypes.html#str) = message

```

The error message.
####  code `instance-attribute`
```
code: int[](https://docs.python.org/3/library/functions.html#int) = code

```

The error code returned by the server.
####  data `instance-attribute`
```
data: dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")] | None = data

```

Additional information about the error, if provided by the server.
####  from_mcp_sdk `classmethod`
```
from_mcp_sdk(error: McpError[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.McpError "mcp.shared.exceptions.McpError")) -> MCPError[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError "MCPError \(pydantic_ai.mcp.MCPError\)")

```

Create an MCPError from an MCP SDK McpError.
Parameters:
Name | Type | Description | Default
---|---|---|---
`error` |  `McpError[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.McpError "mcp.shared.exceptions.McpError")` |  An McpError from the MCP SDK. |  _required_
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
85
86
87
88
89
90
91
92
93
94
```
| ```
@classmethod
def from_mcp_sdk(cls, error: mcp_exceptions.McpError) -> MCPError:
    """Create an MCPError from an MCP SDK McpError.

    Args:
        error: An McpError from the MCP SDK.
    """
    # Extract error data from the McpError.error attribute
    error_data = error.error
    return cls(message=error_data.message, code=error_data.code, data=error_data.data)

```

---|---
###  ResourceAnnotations `dataclass`
Additional properties describing MCP entities.
See the [resource annotations in the MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/server/resources#annotations).
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
```
| ```
@dataclass(repr=False, kw_only=True)
class ResourceAnnotations:
    """Additional properties describing MCP entities.

    See the [resource annotations in the MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/server/resources#annotations).
    """

    audience: list[mcp_types.Role] | None = None
    """Intended audience for this entity."""

    priority: Annotated[float, Field(ge=0.0, le=1.0)] | None = None
    """Priority level for this entity, ranging from 0.0 to 1.0."""

    __repr__ = _utils.dataclasses_no_defaults_repr

    @classmethod
    def from_mcp_sdk(cls, mcp_annotations: mcp_types.Annotations) -> ResourceAnnotations:
        """Convert from MCP SDK Annotations to ResourceAnnotations.

        Args:
            mcp_annotations: The MCP SDK annotations object.
        """
        return cls(audience=mcp_annotations.audience, priority=mcp_annotations.priority)

```

---|---
####  audience `class-attribute` `instance-attribute`
```
audience: list[](https://docs.python.org/3/library/stdtypes.html#list)[Role] | None = None

```

Intended audience for this entity.
####  priority `class-attribute` `instance-attribute`
```
priority: Annotated[](https://docs.python.org/3/library/typing.html#typing.Annotated "typing.Annotated")[float[](https://docs.python.org/3/library/functions.html#float), Field[](https://docs.pydantic.dev/latest/api/fields/#pydantic.fields.Field "pydantic.Field")(ge=0.0, le=1.0)] | None = (
    None
)

```

Priority level for this entity, ranging from 0.0 to 1.0.
####  from_mcp_sdk `classmethod`
```
from_mcp_sdk(
    mcp_annotations: Annotations,
) -> ResourceAnnotations[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations "ResourceAnnotations



      dataclass
   \(pydantic_ai.mcp.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`
```
117
118
119
120
121
122
123
124
```
| ```
@classmethod
def from_mcp_sdk(cls, mcp_annotations: mcp_types.Annotations) -> ResourceAnnotations:
    """Convert from MCP SDK Annotations to ResourceAnnotations.

    Args:
        mcp_annotations: The MCP SDK annotations object.
    """
    return cls(audience=mcp_annotations.audience, priority=mcp_annotations.priority)

```

---|---
###  BaseResource `dataclass`
Bases: `ABC[](https://docs.python.org/3/library/abc.html#abc.ABC "abc.ABC")`
Base class for MCP resources.
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
```
| ```
@dataclass(repr=False, kw_only=True)
class BaseResource(ABC):
    """Base class for MCP resources."""

    name: str
    """The programmatic name of the resource."""

    title: str | None = None
    """Human-readable title for UI contexts."""

    description: str | None = None
    """A description of what this resource represents."""

    mime_type: str | None = None
    """The MIME type of the resource, if known."""

    annotations: ResourceAnnotations | None = None
    """Optional annotations for the resource."""

    metadata: dict[str, Any] | None = None
    """Optional metadata for the resource."""

    __repr__ = _utils.dataclasses_no_defaults_repr

```

---|---
####  name `instance-attribute`
```
name: str[](https://docs.python.org/3/library/stdtypes.html#str)

```

The programmatic name of the resource.
####  title `class-attribute` `instance-attribute`
```
title: str[](https://docs.python.org/3/library/stdtypes.html#str) | None = None

```

Human-readable title for UI contexts.
####  description `class-attribute` `instance-attribute`
```
description: str[](https://docs.python.org/3/library/stdtypes.html#str) | None = None

```

A description of what this resource represents.
####  mime_type `class-attribute` `instance-attribute`
```
mime_type: str[](https://docs.python.org/3/library/stdtypes.html#str) | None = None

```

The MIME type of the resource, if known.
####  annotations `class-attribute` `instance-attribute`
```
annotations: ResourceAnnotations[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceAnnotations "ResourceAnnotations



      dataclass
   \(pydantic_ai.mcp.ResourceAnnotations\)") | None = None

```

Optional annotations for the resource.
####  metadata `class-attribute` `instance-attribute`
```
metadata: dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")] | None = None

```

Optional metadata for the resource.
###  Resource `dataclass`
Bases: `BaseResource[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource "BaseResource



      dataclass
   \(pydantic_ai.mcp.BaseResource\)")`
A resource that can be read from an MCP server.
See the [resources in the MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/server/resources).
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
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
```
| ```
@dataclass(repr=False, kw_only=True)
class Resource(BaseResource):
    """A resource that can be read from an MCP server.

    See the [resources in the MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/server/resources).
    """

    uri: str
    """The URI of the resource."""

    size: int | None = None
    """The size of the raw resource content in bytes (before base64 encoding), if known."""

    @classmethod
    def from_mcp_sdk(cls, mcp_resource: mcp_types.Resource) -> Resource:
        """Convert from MCP SDK Resource to PydanticAI Resource.

        Args:
            mcp_resource: The MCP SDK Resource object.
        """
        return cls(
            uri=str(mcp_resource.uri),
            name=mcp_resource.name,
            title=mcp_resource.title,
            description=mcp_resource.description,
            mime_type=mcp_resource.mimeType,
            size=mcp_resource.size,
            annotations=ResourceAnnotations.from_mcp_sdk(mcp_resource.annotations)
            if mcp_resource.annotations
            else None,
            metadata=mcp_resource.meta,
        )

```

---|---
####  uri `instance-attribute`
```
uri: str[](https://docs.python.org/3/library/stdtypes.html#str)

```

The URI of the resource.
####  size `class-attribute` `instance-attribute`
```
size: int[](https://docs.python.org/3/library/functions.html#int) | None = None

```

The size of the raw resource content in bytes (before base64 encoding), if known.
####  from_mcp_sdk `classmethod`
```
from_mcp_sdk(mcp_resource: Resource[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.Resource "mcp.types.Resource")) -> Resource[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource "Resource



      dataclass
   \(pydantic_ai.mcp.Resource\)")

```

Convert from MCP SDK Resource to PydanticAI Resource.
Parameters:
Name | Type | Description | Default
---|---|---|---
`mcp_resource` |  `Resource[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.Resource "mcp.types.Resource")` |  The MCP SDK Resource object. |  _required_
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
```
| ```
@classmethod
def from_mcp_sdk(cls, mcp_resource: mcp_types.Resource) -> Resource:
    """Convert from MCP SDK Resource to PydanticAI Resource.

    Args:
        mcp_resource: The MCP SDK Resource object.
    """
    return cls(
        uri=str(mcp_resource.uri),
        name=mcp_resource.name,
        title=mcp_resource.title,
        description=mcp_resource.description,
        mime_type=mcp_resource.mimeType,
        size=mcp_resource.size,
        annotations=ResourceAnnotations.from_mcp_sdk(mcp_resource.annotations)
        if mcp_resource.annotations
        else None,
        metadata=mcp_resource.meta,
    )

```

---|---
###  ResourceTemplate `dataclass`
Bases: `BaseResource[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.BaseResource "BaseResource



      dataclass
   \(pydantic_ai.mcp.BaseResource\)")`
A template for parameterized resources on an MCP server.
See the [resource templates in the MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/server/resources#resource-templates).
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
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
```
| ```
@dataclass(repr=False, kw_only=True)
class ResourceTemplate(BaseResource):
    """A template for parameterized resources on an MCP server.

    See the [resource templates in the MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/server/resources#resource-templates).
    """

    uri_template: str
    """URI template (RFC 6570) for constructing resource URIs."""

    @classmethod
    def from_mcp_sdk(cls, mcp_template: mcp_types.ResourceTemplate) -> ResourceTemplate:
        """Convert from MCP SDK ResourceTemplate to PydanticAI ResourceTemplate.

        Args:
            mcp_template: The MCP SDK ResourceTemplate object.
        """
        return cls(
            uri_template=mcp_template.uriTemplate,
            name=mcp_template.name,
            title=mcp_template.title,
            description=mcp_template.description,
            mime_type=mcp_template.mimeType,
            annotations=ResourceAnnotations.from_mcp_sdk(mcp_template.annotations)
            if mcp_template.annotations
            else None,
            metadata=mcp_template.meta,
        )

```

---|---
####  uri_template `instance-attribute`
```
uri_template: str[](https://docs.python.org/3/library/stdtypes.html#str)

```

URI template (RFC 6570) for constructing resource URIs.
####  from_mcp_sdk `classmethod`
```
from_mcp_sdk(
    mcp_template: ResourceTemplate,
) -> ResourceTemplate[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceTemplate "ResourceTemplate



      dataclass
   \(pydantic_ai.mcp.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`
```
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
```
| ```
@classmethod
def from_mcp_sdk(cls, mcp_template: mcp_types.ResourceTemplate) -> ResourceTemplate:
    """Convert from MCP SDK ResourceTemplate to PydanticAI ResourceTemplate.

    Args:
        mcp_template: The MCP SDK ResourceTemplate object.
    """
    return cls(
        uri_template=mcp_template.uriTemplate,
        name=mcp_template.name,
        title=mcp_template.title,
        description=mcp_template.description,
        mime_type=mcp_template.mimeType,
        annotations=ResourceAnnotations.from_mcp_sdk(mcp_template.annotations)
        if mcp_template.annotations
        else None,
        metadata=mcp_template.meta,
    )

```

---|---
###  ServerCapabilities `dataclass`
Capabilities that an MCP server supports.
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
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
```
| ```
@dataclass(repr=False, kw_only=True)
class ServerCapabilities:
    """Capabilities that an MCP server supports."""

    experimental: list[str] | None = None
    """Experimental, non-standard capabilities that the server supports."""

    logging: bool = False
    """Whether the server supports sending log messages to the client."""

    prompts: bool = False
    """Whether the server offers any prompt templates."""

    prompts_list_changed: bool = False
    """Whether the server will emit notifications when the list of prompts changes."""

    resources: bool = False
    """Whether the server offers any resources to read."""

    resources_list_changed: bool = False
    """Whether the server will emit notifications when the list of resources changes."""

    tools: bool = False
    """Whether the server offers any tools to call."""

    tools_list_changed: bool = False
    """Whether the server will emit notifications when the list of tools changes."""

    completions: bool = False
    """Whether the server offers autocompletion suggestions for prompts and resources."""

    __repr__ = _utils.dataclasses_no_defaults_repr

    @classmethod
    def from_mcp_sdk(cls, mcp_capabilities: mcp_types.ServerCapabilities) -> ServerCapabilities:
        """Convert from MCP SDK ServerCapabilities to PydanticAI ServerCapabilities.

        Args:
            mcp_capabilities: The MCP SDK ServerCapabilities object.
        """
        prompts_cap = mcp_capabilities.prompts
        resources_cap = mcp_capabilities.resources
        tools_cap = mcp_capabilities.tools
        return cls(
            experimental=list(mcp_capabilities.experimental.keys()) if mcp_capabilities.experimental else None,
            logging=mcp_capabilities.logging is not None,
            prompts=prompts_cap is not None,
            prompts_list_changed=bool(prompts_cap.listChanged) if prompts_cap else False,
            resources=resources_cap is not None,
            resources_list_changed=bool(resources_cap.listChanged) if resources_cap else False,
            tools=tools_cap is not None,
            tools_list_changed=bool(tools_cap.listChanged) if tools_cap else False,
            completions=mcp_capabilities.completions is not None,
        )

```

---|---
####  experimental `class-attribute` `instance-attribute`
```
experimental: list[](https://docs.python.org/3/library/stdtypes.html#list)[str[](https://docs.python.org/3/library/stdtypes.html#str)] | None = None

```

Experimental, non-standard capabilities that the server supports.
####  logging `class-attribute` `instance-attribute`
```
logging: bool[](https://docs.python.org/3/library/functions.html#bool) = False

```

Whether the server supports sending log messages to the client.
####  prompts `class-attribute` `instance-attribute`
```
prompts: bool[](https://docs.python.org/3/library/functions.html#bool) = False

```

Whether the server offers any prompt templates.
####  prompts_list_changed `class-attribute` `instance-attribute`
```
prompts_list_changed: bool[](https://docs.python.org/3/library/functions.html#bool) = False

```

Whether the server will emit notifications when the list of prompts changes.
####  resources `class-attribute` `instance-attribute`
```
resources: bool[](https://docs.python.org/3/library/functions.html#bool) = False

```

Whether the server offers any resources to read.
####  resources_list_changed `class-attribute` `instance-attribute`
```
resources_list_changed: bool[](https://docs.python.org/3/library/functions.html#bool) = False

```

Whether the server will emit notifications when the list of resources changes.
####  tools `class-attribute` `instance-attribute`
```
tools: bool[](https://docs.python.org/3/library/functions.html#bool) = False

```

Whether the server offers any tools to call.
####  tools_list_changed `class-attribute` `instance-attribute`
```
tools_list_changed: bool[](https://docs.python.org/3/library/functions.html#bool) = False

```

Whether the server will emit notifications when the list of tools changes.
####  completions `class-attribute` `instance-attribute`
```
completions: bool[](https://docs.python.org/3/library/functions.html#bool) = False

```

Whether the server offers autocompletion suggestions for prompts and resources.
####  from_mcp_sdk `classmethod`
```
from_mcp_sdk(
    mcp_capabilities: ServerCapabilities[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.ServerCapabilities "mcp.types.ServerCapabilities"),
) -> ServerCapabilities[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities "ServerCapabilities



      dataclass
   \(pydantic_ai.mcp.ServerCapabilities\)")

```

Convert from MCP SDK ServerCapabilities to PydanticAI ServerCapabilities.
Parameters:
Name | Type | Description | Default
---|---|---|---
`mcp_capabilities` |  `ServerCapabilities[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.ServerCapabilities "mcp.types.ServerCapabilities")` |  The MCP SDK ServerCapabilities object. |  _required_
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
```
| ```
@classmethod
def from_mcp_sdk(cls, mcp_capabilities: mcp_types.ServerCapabilities) -> ServerCapabilities:
    """Convert from MCP SDK ServerCapabilities to PydanticAI ServerCapabilities.

    Args:
        mcp_capabilities: The MCP SDK ServerCapabilities object.
    """
    prompts_cap = mcp_capabilities.prompts
    resources_cap = mcp_capabilities.resources
    tools_cap = mcp_capabilities.tools
    return cls(
        experimental=list(mcp_capabilities.experimental.keys()) if mcp_capabilities.experimental else None,
        logging=mcp_capabilities.logging is not None,
        prompts=prompts_cap is not None,
        prompts_list_changed=bool(prompts_cap.listChanged) if prompts_cap else False,
        resources=resources_cap is not None,
        resources_list_changed=bool(resources_cap.listChanged) if resources_cap else False,
        tools=tools_cap is not None,
        tools_list_changed=bool(tools_cap.listChanged) if tools_cap else False,
        completions=mcp_capabilities.completions is not None,
    )

```

---|---
###  MCPServer
Bases: `AbstractToolset[](https://ai.pydantic.dev/api/toolsets/#pydantic_ai.toolsets.AbstractToolset "AbstractToolset \(pydantic_ai.toolsets.abstract.AbstractToolset\)")[Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")]`, `ABC[](https://docs.python.org/3/library/abc.html#abc.ABC "abc.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`
```
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
```
| ```
class MCPServer(AbstractToolset[Any], ABC):
    """Base class for attaching agents to MCP servers.

    See <https://modelcontextprotocol.io> for more information.
    """

    tool_prefix: str | None
    """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: mcp_types.LoggingLevel | None
    """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: LoggingFnT | None
    """A handler for logging messages from the server."""

    timeout: float
    """The timeout in seconds to wait for the client to initialize."""

    read_timeout: float
    """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: ProcessToolCallback | None
    """Hook to customize tool calling and optionally pass extra metadata."""

    allow_sampling: bool
    """Whether to allow MCP sampling through this client."""

    sampling_model: models.Model | None
    """The model to use for sampling."""

    max_retries: int
    """The maximum number of times to retry a tool call."""

    elicitation_callback: ElicitationFnT | None = None
    """Callback function to handle elicitation requests from the server."""

    cache_tools: bool
    """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
    - [`MCPServer.__aexit__`][pydantic_ai.mcp.MCPServer.__aexit__] is called (when the last context exits)

    Set to `False` for servers that change tools dynamically without sending notifications.

    Note: When using durable execution (Temporal, DBOS), tool definitions are additionally cached
    at the wrapper level across activities/steps, to avoid redundant MCP connections. This
    wrapper-level cache is not invalidated by `tools/list_changed` notifications.
    Set to `False` to disable all caching if tools may change during a workflow.
    """

    cache_resources: bool
    """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
    - [`MCPServer.__aexit__`][pydantic_ai.mcp.MCPServer.__aexit__] is called (when the last context exits)

    Set to `False` for servers that change resources dynamically without sending notifications.
    """

    _id: str | None

    _enter_lock: Lock = field(compare=False)
    _running_count: int
    _exit_stack: AsyncExitStack | None

    _client: ClientSession
    _read_stream: MemoryObjectReceiveStream[SessionMessage | Exception]
    _write_stream: MemoryObjectSendStream[SessionMessage]
    _server_info: mcp_types.Implementation
    _server_capabilities: ServerCapabilities
    _instructions: str | None

    _cached_tools: list[mcp_types.Tool] | None
    _cached_resources: list[Resource] | None

    # TODO (v2): enforce the arguments to be passed as keyword arguments only
    def __init__(
        self,
        tool_prefix: str | None = None,
        log_level: mcp_types.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: models.Model | None = None,
        max_retries: int = 1,
        elicitation_callback: ElicitationFnT | None = None,
        cache_tools: bool = True,
        cache_resources: bool = True,
        *,
        id: str | None = None,
        client_info: mcp_types.Implementation | None = None,
    ):
        self.tool_prefix = tool_prefix
        self.log_level = log_level
        self.log_handler = log_handler
        self.timeout = timeout
        self.read_timeout = read_timeout
        self.process_tool_call = process_tool_call
        self.allow_sampling = allow_sampling
        self.sampling_model = sampling_model
        self.max_retries = max_retries
        self.elicitation_callback = elicitation_callback
        self.cache_tools = cache_tools
        self.cache_resources = cache_resources
        self.client_info = client_info

        self._id = id or tool_prefix

        self.__post_init__()

    def __post_init__(self):
        self._enter_lock = Lock()
        self._running_count = 0
        self._exit_stack = None
        self._cached_tools = None
        self._cached_resources = None

    @abstractmethod
    @asynccontextmanager
    async def client_streams(
        self,
    ) -> AsyncIterator[
        tuple[
            MemoryObjectReceiveStream[SessionMessage | Exception],
            MemoryObjectSendStream[SessionMessage],
        ]
    ]:
        """Create the streams for the MCP server."""
        raise NotImplementedError('MCP Server subclasses must implement this method.')
        yield

    @property
    def id(self) -> str | None:
        return self._id

    @id.setter
    def id(self, value: str | None):
        self._id = value

    @property
    def label(self) -> str:
        if self.id:
            return super().label  # pragma: no cover
        else:
            return repr(self)

    @property
    def tool_name_conflict_hint(self) -> str:
        return 'Set the `tool_prefix` attribute to avoid name conflicts.'

    @property
    def server_info(self) -> mcp_types.Implementation:
        """Access the information send by the MCP server during initialization."""
        if getattr(self, '_server_info', None) is None:
            raise AttributeError(
                f'The `{self.__class__.__name__}.server_info` is only instantiated after initialization.'
            )
        return self._server_info

    @property
    def capabilities(self) -> ServerCapabilities:
        """Access the capabilities advertised by the MCP server during initialization."""
        if getattr(self, '_server_capabilities', None) is None:
            raise AttributeError(
                f'The `{self.__class__.__name__}.capabilities` is only instantiated after initialization.'
            )
        return self._server_capabilities

    @property
    def instructions(self) -> str | None:
        """Access the instructions sent by the MCP server during initialization."""
        if not hasattr(self, '_instructions'):
            raise AttributeError(
                f'The `{self.__class__.__name__}.instructions` is only available after initialization.'
            )
        return self._instructions

    async def list_tools(self) -> list[mcp_types.Tool]:
        """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
        - `__aexit__` when the last context exits

        Set `cache_tools=False` for servers that change tools without sending notifications.
        """
        if self.cache_tools and self._cached_tools is not None:
            return self._cached_tools

        async with self:
            result = await self._client.list_tools()
            if self.cache_tools:
                self._cached_tools = result.tools
            return result.tools

    async def direct_call_tool(
        self,
        name: str,
        args: dict[str, Any],
        metadata: dict[str, Any] | None = None,
    ) -> ToolResult:
        """Call a tool on the server.

        Args:
            name: The name of the tool to call.
            args: The arguments to pass to the tool.
            metadata: Request-level metadata (optional)

        Returns:
            The result of the tool call.

        Raises:
            ModelRetry: If the tool call fails.
        """
        async with self:  # Ensure server is running
            try:
                result = await self._client.send_request(
                    mcp_types.ClientRequest(
                        mcp_types.CallToolRequest(
                            method='tools/call',
                            params=mcp_types.CallToolRequestParams(
                                name=name,
                                arguments=args,
                                _meta=mcp_types.RequestParams.Meta(**metadata) if metadata else None,
                            ),
                        )
                    ),
                    mcp_types.CallToolResult,
                )
            except mcp_exceptions.McpError as e:
                raise exceptions.ModelRetry(e.error.message)

        if result.isError:
            message: str | None = None
            if result.content:  # pragma: no branch
                text_parts = [part.text for part in result.content if isinstance(part, mcp_types.TextContent)]
                message = '\n'.join(text_parts)

            raise exceptions.ModelRetry(message or 'MCP tool call failed')

        # Prefer structured content if there are only text parts, which per the docs would contain the JSON-encoded structured content for backward compatibility.
        # See https://github.com/modelcontextprotocol/python-sdk#structured-output
        if (structured := result.structuredContent) and not any(
            not isinstance(part, mcp_types.TextContent) for part in result.content
        ):
            # The MCP SDK wraps primitives and generic types like list in a `result` key, but we want to use the raw value returned by the tool function.
            # See https://github.com/modelcontextprotocol/python-sdk#structured-output
            if isinstance(structured, dict) and len(structured) == 1 and 'result' in structured:
                return structured['result']
            return structured

        mapped = [await self._map_tool_result_part(part) for part in result.content]
        return mapped[0] if len(mapped) == 1 else mapped

    async def call_tool(
        self,
        name: str,
        tool_args: dict[str, Any],
        ctx: RunContext[Any],
        tool: ToolsetTool[Any],
    ) -> ToolResult:
        if self.tool_prefix:
            name = name.removeprefix(f'{self.tool_prefix}_')
            ctx = replace(ctx, tool_name=name)

        if self.process_tool_call is not None:
            return await self.process_tool_call(ctx, self.direct_call_tool, name, tool_args)
        else:
            return await self.direct_call_tool(name, tool_args)

    async def get_tools(self, ctx: RunContext[Any]) -> dict[str, ToolsetTool[Any]]:
        return {
            name: self.tool_for_tool_def(
                ToolDefinition(
                    name=name,
                    description=mcp_tool.description,
                    parameters_json_schema=mcp_tool.inputSchema,
                    metadata={
                        'meta': mcp_tool.meta,
                        'annotations': mcp_tool.annotations.model_dump() if mcp_tool.annotations else None,
                        'output_schema': mcp_tool.outputSchema or None,
                    },
                ),
            )
            for mcp_tool in await self.list_tools()
            if (name := f'{self.tool_prefix}_{mcp_tool.name}' if self.tool_prefix else mcp_tool.name)
        }

    def tool_for_tool_def(self, tool_def: ToolDefinition) -> ToolsetTool[Any]:
        return ToolsetTool(
            toolset=self,
            tool_def=tool_def,
            max_retries=self.max_retries,
            args_validator=TOOL_SCHEMA_VALIDATOR,
        )

    async def list_resources(self) -> list[Resource]:
        """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
        - `__aexit__` when the last context exits

        Set `cache_resources=False` for servers that change resources without sending notifications.

        Raises:
            MCPError: If the server returns an error.
        """
        if self.cache_resources and self._cached_resources is not None:
            return self._cached_resources

        async with self:
            if not self.capabilities.resources:
                return []
            try:
                result = await self._client.list_resources()
                resources = [Resource.from_mcp_sdk(r) for r in result.resources]
                if self.cache_resources:
                    self._cached_resources = resources
                return resources
            except mcp_exceptions.McpError as e:
                raise MCPError.from_mcp_sdk(e) from e

    async def list_resource_templates(self) -> list[ResourceTemplate]:
        """Retrieve resource templates that are currently present on the server.

        Raises:
            MCPError: If the server returns an error.
        """
        async with self:  # Ensure server is running
            if not self.capabilities.resources:
                return []
            try:
                result = await self._client.list_resource_templates()
            except mcp_exceptions.McpError as e:
                raise MCPError.from_mcp_sdk(e) from e
        return [ResourceTemplate.from_mcp_sdk(t) for t in result.resourceTemplates]

    @overload
    async def read_resource(self, uri: str) -> str | messages.BinaryContent | list[str | messages.BinaryContent]: ...

    @overload
    async def read_resource(
        self, uri: Resource
    ) -> str | messages.BinaryContent | list[str | messages.BinaryContent]: ...

    async def read_resource(
        self, uri: str | Resource
    ) -> str | messages.BinaryContent | list[str | messages.BinaryContent]:
        """Read the contents of a specific resource by URI.

        Args:
            uri: The URI of the resource to read, or a Resource object.

        Returns:
            The resource contents. If the resource has a single content item, returns that item directly.
            If the resource has multiple content items, returns a list of items.

        Raises:
            MCPError: If the server returns an error.
        """
        resource_uri = uri if isinstance(uri, str) else uri.uri
        async with self:  # Ensure server is running
            try:
                result = await self._client.read_resource(AnyUrl(resource_uri))
            except mcp_exceptions.McpError as e:
                raise MCPError.from_mcp_sdk(e) from e

        return (
            self._get_content(result.contents[0])
            if len(result.contents) == 1
            else [self._get_content(resource) for resource in result.contents]
        )

    async def __aenter__(self) -> Self:
        """Enter the MCP server context.

        This will initialize the connection to the server.
        If this server is an [`MCPServerStdio`][pydantic_ai.mcp.MCPServerStdio], the server will first be started as a subprocess.

        This is a no-op if the MCP server has already been entered.
        """
        async with self._enter_lock:
            if self._running_count == 0:
                async with AsyncExitStack() as exit_stack:
                    self._read_stream, self._write_stream = await exit_stack.enter_async_context(self.client_streams())

                    client = ClientSession(
                        read_stream=self._read_stream,
                        write_stream=self._write_stream,
                        sampling_callback=self._sampling_callback if self.allow_sampling else None,
                        elicitation_callback=self.elicitation_callback,
                        logging_callback=self.log_handler,
                        read_timeout_seconds=timedelta(seconds=self.read_timeout),
                        message_handler=self._handle_notification,
                        client_info=self.client_info,
                    )
                    self._client = await exit_stack.enter_async_context(client)

                    with anyio.fail_after(self.timeout):
                        result = await self._client.initialize()
                        self._server_info = result.serverInfo
                        self._server_capabilities = ServerCapabilities.from_mcp_sdk(result.capabilities)
                        self._instructions = result.instructions
                        if log_level := self.log_level:
                            await self._client.set_logging_level(log_level)

                    self._exit_stack = exit_stack.pop_all()
            self._running_count += 1
        return self

    async def __aexit__(self, *args: Any) -> bool | None:
        if self._running_count == 0:
            raise ValueError('MCPServer.__aexit__ called more times than __aenter__')
        async with self._enter_lock:
            self._running_count -= 1
            if self._running_count == 0 and self._exit_stack is not None:
                await self._exit_stack.aclose()
                self._exit_stack = None
                self._cached_tools = None
                self._cached_resources = None

    @property
    def is_running(self) -> bool:
        """Check if the MCP server is running."""
        return bool(self._running_count)

    async def _sampling_callback(
        self, context: RequestContext[ClientSession, Any], params: mcp_types.CreateMessageRequestParams
    ) -> mcp_types.CreateMessageResult | mcp_types.ErrorData:
        """MCP sampling callback."""
        if self.sampling_model is None:
            raise ValueError('Sampling model is not set')  # pragma: no cover

        pai_messages = _mcp.map_from_mcp_params(params)
        model_settings = models.ModelSettings()
        if max_tokens := params.maxTokens:  # pragma: no branch
            model_settings['max_tokens'] = max_tokens
        if temperature := params.temperature:  # pragma: no branch
            model_settings['temperature'] = temperature
        if stop_sequences := params.stopSequences:  # pragma: no branch
            model_settings['stop_sequences'] = stop_sequences

        model_response = await model_request(self.sampling_model, pai_messages, model_settings=model_settings)
        return mcp_types.CreateMessageResult(
            role='assistant',
            content=_mcp.map_from_model_response(model_response),
            model=self.sampling_model.model_name,
        )

    async def _handle_notification(
        self,
        message: RequestResponder[mcp_types.ServerRequest, mcp_types.ClientResult]
        | mcp_types.ServerNotification
        | Exception,
    ) -> None:
        """Handle notifications from the MCP server, invalidating caches as needed."""
        if isinstance(message, mcp_types.ServerNotification):  # pragma: no branch
            if isinstance(message.root, mcp_types.ToolListChangedNotification):
                self._cached_tools = None
            elif isinstance(message.root, mcp_types.ResourceListChangedNotification):
                self._cached_resources = None

    async def _map_tool_result_part(
        self, part: mcp_types.ContentBlock
    ) -> str | messages.BinaryContent | dict[str, Any] | list[Any]:
        # See https://github.com/jlowin/fastmcp/blob/main/docs/servers/tools.mdx#return-values

        if isinstance(part, mcp_types.TextContent):
            text = part.text
            if text.startswith(('[', '{')):
                try:
                    return pydantic_core.from_json(text)
                except ValueError:
                    pass
            return text
        elif isinstance(part, mcp_types.ImageContent):
            return messages.BinaryImage(data=base64.b64decode(part.data), media_type=part.mimeType)
        elif isinstance(part, mcp_types.AudioContent):
            # NOTE: The FastMCP server doesn't support audio content.
            # See <https://github.com/modelcontextprotocol/python-sdk/issues/952> for more details.
            return messages.BinaryContent(
                data=base64.b64decode(part.data), media_type=part.mimeType
            )  # pragma: no cover
        elif isinstance(part, mcp_types.EmbeddedResource):
            resource = part.resource
            return self._get_content(resource)
        elif isinstance(part, mcp_types.ResourceLink):
            return await self.read_resource(str(part.uri))
        else:
            assert_never(part)

    def _get_content(
        self, resource: mcp_types.TextResourceContents | mcp_types.BlobResourceContents
    ) -> str | messages.BinaryContent:
        if isinstance(resource, mcp_types.TextResourceContents):
            return resource.text
        elif isinstance(resource, mcp_types.BlobResourceContents):
            return messages.BinaryContent.narrow_type(
                messages.BinaryContent(
                    data=base64.b64decode(resource.blob), media_type=resource.mimeType or 'application/octet-stream'
                )
            )
        else:
            assert_never(resource)

    def __eq__(self, value: object, /) -> bool:
        return isinstance(value, MCPServer) and self.id == value.id and self.tool_prefix == value.tool_prefix

```

---|---
####  tool_prefix `instance-attribute`
```
tool_prefix: str[](https://docs.python.org/3/library/stdtypes.html#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[](https://docs.python.org/3/library/functions.html#float) = timeout

```

The timeout in seconds to wait for the client to initialize.
####  read_timeout `instance-attribute`
```
read_timeout: float[](https://docs.python.org/3/library/functions.html#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[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ProcessToolCallback "ProcessToolCallback



      module-attribute
   \(pydantic_ai.mcp.ProcessToolCallback\)") | None = (
    process_tool_call
)

```

Hook to customize tool calling and optionally pass extra metadata.
####  allow_sampling `instance-attribute`
```
allow_sampling: bool[](https://docs.python.org/3/library/functions.html#bool) = allow_sampling

```

Whether to allow MCP sampling through this client.
####  sampling_model `instance-attribute`
```
sampling_model: Model[](https://ai.pydantic.dev/api/models/base/#pydantic_ai.models.Model "Model \(pydantic_ai.models.Model\)") | None = sampling_model

```

The model to use for sampling.
####  max_retries `instance-attribute`
```
max_retries: int[](https://docs.python.org/3/library/functions.html#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[](https://docs.python.org/3/library/functions.html#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 - [`MCPServer.__aexit__`][pydantic_ai.mcp.MCPServer.__aexit__] is called (when the last context exits)
Set to `False` for servers that change tools dynamically without sending notifications.
Note: When using durable execution (Temporal, DBOS), tool definitions are additionally cached at the wrapper level across activities/steps, to avoid redundant MCP connections. This wrapper-level cache is not invalidated by `tools/list_changed` notifications. Set to `False` to disable all caching if tools may change during a workflow.
####  cache_resources `instance-attribute`
```
cache_resources: bool[](https://docs.python.org/3/library/functions.html#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 - [`MCPServer.__aexit__`][pydantic_ai.mcp.MCPServer.__aexit__] is called (when the last context exits)
Set to `False` for servers that change resources dynamically without sending notifications.
####  client_streams `abstractmethod` `async`
```
client_streams() -> AsyncIterator[](https://docs.python.org/3/library/collections.abc.html#collections.abc.AsyncIterator "collections.abc.AsyncIterator")[
    tuple[](https://docs.python.org/3/library/stdtypes.html#tuple)[
        MemoryObjectReceiveStream[
            SessionMessage | Exception[](https://docs.python.org/3/library/exceptions.html#Exception)
        ],
        MemoryObjectSendStream[SessionMessage],
    ]
]

```

Create the streams for the MCP server.
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
422
423
424
425
426
427
428
429
430
431
432
433
434
```
| ```
@abstractmethod
@asynccontextmanager
async def client_streams(
    self,
) -> AsyncIterator[
    tuple[
        MemoryObjectReceiveStream[SessionMessage | Exception],
        MemoryObjectSendStream[SessionMessage],
    ]
]:
    """Create the streams for the MCP server."""
    raise NotImplementedError('MCP Server subclasses must implement this method.')
    yield

```

---|---
####  server_info `property`
```
server_info: Implementation[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.Implementation "mcp.types.Implementation")

```

Access the information send by the MCP server during initialization.
####  capabilities `property`
```
capabilities: ServerCapabilities[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ServerCapabilities "ServerCapabilities



      dataclass
   \(pydantic_ai.mcp.ServerCapabilities\)")

```

Access the capabilities advertised by the MCP server during initialization.
####  instructions `property`
```
instructions: str[](https://docs.python.org/3/library/stdtypes.html#str) | None

```

Access the instructions sent by the MCP server during initialization.
####  list_tools `async`
```
list_tools() -> list[](https://docs.python.org/3/library/stdtypes.html#list)[Tool[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.Tool "mcp.types.Tool")]

```

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 - `__aexit__` when the last context exits
Set `cache_tools=False` for servers that change tools without sending notifications.
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
```
| ```
async def list_tools(self) -> list[mcp_types.Tool]:
    """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
    - `__aexit__` when the last context exits

    Set `cache_tools=False` for servers that change tools without sending notifications.
    """
    if self.cache_tools and self._cached_tools is not None:
        return self._cached_tools

    async with self:
        result = await self._client.list_tools()
        if self.cache_tools:
            self._cached_tools = result.tools
        return result.tools

```

---|---
####  direct_call_tool `async`
```
direct_call_tool(
    name: str[](https://docs.python.org/3/library/stdtypes.html#str),
    args: dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")],
    metadata: dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")] | None = None,
) -> ToolResult[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ToolResult "ToolResult



      module-attribute
   \(pydantic_ai.mcp.ToolResult\)")

```

Call a tool on the server.
Parameters:
Name | Type | Description | Default
---|---|---|---
`name` |  `str[](https://docs.python.org/3/library/stdtypes.html#str)` |  The name of the tool to call. |  _required_
`args` |  `dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")]` |  The arguments to pass to the tool. |  _required_
`metadata` |  `dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")] | None` |  Request-level metadata (optional) |  `None`
Returns:
Type | Description
---|---
`ToolResult[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ToolResult "ToolResult



      module-attribute
   \(pydantic_ai.mcp.ToolResult\)")` |  The result of the tool call.
Raises:
Type | Description
---|---
`ModelRetry[](https://ai.pydantic.dev/api/exceptions/#pydantic_ai.exceptions.ModelRetry "ModelRetry \(pydantic_ai.exceptions.ModelRetry\)")` |  If the tool call fails.
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
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
```
| ```
async def direct_call_tool(
    self,
    name: str,
    args: dict[str, Any],
    metadata: dict[str, Any] | None = None,
) -> ToolResult:
    """Call a tool on the server.

    Args:
        name: The name of the tool to call.
        args: The arguments to pass to the tool.
        metadata: Request-level metadata (optional)

    Returns:
        The result of the tool call.

    Raises:
        ModelRetry: If the tool call fails.
    """
    async with self:  # Ensure server is running
        try:
            result = await self._client.send_request(
                mcp_types.ClientRequest(
                    mcp_types.CallToolRequest(
                        method='tools/call',
                        params=mcp_types.CallToolRequestParams(
                            name=name,
                            arguments=args,
                            _meta=mcp_types.RequestParams.Meta(**metadata) if metadata else None,
                        ),
                    )
                ),
                mcp_types.CallToolResult,
            )
        except mcp_exceptions.McpError as e:
            raise exceptions.ModelRetry(e.error.message)

    if result.isError:
        message: str | None = None
        if result.content:  # pragma: no branch
            text_parts = [part.text for part in result.content if isinstance(part, mcp_types.TextContent)]
            message = '\n'.join(text_parts)

        raise exceptions.ModelRetry(message or 'MCP tool call failed')

    # Prefer structured content if there are only text parts, which per the docs would contain the JSON-encoded structured content for backward compatibility.
    # See https://github.com/modelcontextprotocol/python-sdk#structured-output
    if (structured := result.structuredContent) and not any(
        not isinstance(part, mcp_types.TextContent) for part in result.content
    ):
        # The MCP SDK wraps primitives and generic types like list in a `result` key, but we want to use the raw value returned by the tool function.
        # See https://github.com/modelcontextprotocol/python-sdk#structured-output
        if isinstance(structured, dict) and len(structured) == 1 and 'result' in structured:
            return structured['result']
        return structured

    mapped = [await self._map_tool_result_part(part) for part in result.content]
    return mapped[0] if len(mapped) == 1 else mapped

```

---|---
####  list_resources `async`
```
list_resources() -> list[](https://docs.python.org/3/library/stdtypes.html#list)[Resource[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource "Resource



      dataclass
   \(pydantic_ai.mcp.Resource\)")]

```

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 - `__aexit__` when the last context exits
Set `cache_resources=False` for servers that change resources without sending notifications.
Raises:
Type | Description
---|---
`MCPError[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError "MCPError \(pydantic_ai.mcp.MCPError\)")` |  If the server returns an error.
Source code in `pydantic_ai_slim/pydantic_ai/mcp.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
```
| ```
async def list_resources(self) -> list[Resource]:
    """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
    - `__aexit__` when the last context exits

    Set `cache_resources=False` for servers that change resources without sending notifications.

    Raises:
        MCPError: If the server returns an error.
    """
    if self.cache_resources and self._cached_resources is not None:
        return self._cached_resources

    async with self:
        if not self.capabilities.resources:
            return []
        try:
            result = await self._client.list_resources()
            resources = [Resource.from_mcp_sdk(r) for r in result.resources]
            if self.cache_resources:
                self._cached_resources = resources
            return resources
        except mcp_exceptions.McpError as e:
            raise MCPError.from_mcp_sdk(e) from e

```

---|---
####  list_resource_templates `async`
```
list_resource_templates() -> list[](https://docs.python.org/3/library/stdtypes.html#list)[ResourceTemplate[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ResourceTemplate "ResourceTemplate



      dataclass
   \(pydantic_ai.mcp.ResourceTemplate\)")]

```

Retrieve resource templates that are currently present on the server.
Raises:
Type | Description
---|---
`MCPError[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError "MCPError \(pydantic_ai.mcp.MCPError\)")` |  If the server returns an error.
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
628
629
630
631
632
633
634
635
636
637
638
639
640
641
```
| ```
async def list_resource_templates(self) -> list[ResourceTemplate]:
    """Retrieve resource templates that are currently present on the server.

    Raises:
        MCPError: If the server returns an error.
    """
    async with self:  # Ensure server is running
        if not self.capabilities.resources:
            return []
        try:
            result = await self._client.list_resource_templates()
        except mcp_exceptions.McpError as e:
            raise MCPError.from_mcp_sdk(e) from e
    return [ResourceTemplate.from_mcp_sdk(t) for t in result.resourceTemplates]

```

---|---
####  read_resource `async`
```
read_resource(
    uri: str[](https://docs.python.org/3/library/stdtypes.html#str),
) -> str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)") | list[](https://docs.python.org/3/library/stdtypes.html#list)[str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)")]

```

```
read_resource(
    uri: Resource[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource "Resource



      dataclass
   \(pydantic_ai.mcp.Resource\)"),
) -> str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)") | list[](https://docs.python.org/3/library/stdtypes.html#list)[str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)")]

```

```
read_resource(
    uri: str[](https://docs.python.org/3/library/stdtypes.html#str) | Resource[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource "Resource



      dataclass
   \(pydantic_ai.mcp.Resource\)"),
) -> str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)") | list[](https://docs.python.org/3/library/stdtypes.html#list)[str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)")]

```

Read the contents of a specific resource by URI.
Parameters:
Name | Type | Description | Default
---|---|---|---
`uri` |  `str[](https://docs.python.org/3/library/stdtypes.html#str) | Resource[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.Resource "Resource



      dataclass
   \(pydantic_ai.mcp.Resource\)")` |  The URI of the resource to read, or a Resource object. |  _required_
Returns:
Type | Description
---|---
`str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)") | list[](https://docs.python.org/3/library/stdtypes.html#list)[str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)")]` |  The resource contents. If the resource has a single content item, returns that item directly.
`str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)") | list[](https://docs.python.org/3/library/stdtypes.html#list)[str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)")]` |  If the resource has multiple content items, returns a list of items.
Raises:
Type | Description
---|---
`MCPError[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPError "MCPError \(pydantic_ai.mcp.MCPError\)")` |  If the server returns an error.
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
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
```
| ```
async def read_resource(
    self, uri: str | Resource
) -> str | messages.BinaryContent | list[str | messages.BinaryContent]:
    """Read the contents of a specific resource by URI.

    Args:
        uri: The URI of the resource to read, or a Resource object.

    Returns:
        The resource contents. If the resource has a single content item, returns that item directly.
        If the resource has multiple content items, returns a list of items.

    Raises:
        MCPError: If the server returns an error.
    """
    resource_uri = uri if isinstance(uri, str) else uri.uri
    async with self:  # Ensure server is running
        try:
            result = await self._client.read_resource(AnyUrl(resource_uri))
        except mcp_exceptions.McpError as e:
            raise MCPError.from_mcp_sdk(e) from e

    return (
        self._get_content(result.contents[0])
        if len(result.contents) == 1
        else [self._get_content(resource) for resource in result.contents]
    )

```

---|---
####  __aenter__ `async`
```
__aenter__() -> Self[](https://typing-extensions.readthedocs.io/en/latest/index.html#typing_extensions.Self "typing_extensions.Self")

```

Enter the MCP server context.
This will initialize the connection to the server. If this server is an [`MCPServerStdio`](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio "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`
```
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
```
| ```
async def __aenter__(self) -> Self:
    """Enter the MCP server context.

    This will initialize the connection to the server.
    If this server is an [`MCPServerStdio`][pydantic_ai.mcp.MCPServerStdio], the server will first be started as a subprocess.

    This is a no-op if the MCP server has already been entered.
    """
    async with self._enter_lock:
        if self._running_count == 0:
            async with AsyncExitStack() as exit_stack:
                self._read_stream, self._write_stream = await exit_stack.enter_async_context(self.client_streams())

                client = ClientSession(
                    read_stream=self._read_stream,
                    write_stream=self._write_stream,
                    sampling_callback=self._sampling_callback if self.allow_sampling else None,
                    elicitation_callback=self.elicitation_callback,
                    logging_callback=self.log_handler,
                    read_timeout_seconds=timedelta(seconds=self.read_timeout),
                    message_handler=self._handle_notification,
                    client_info=self.client_info,
                )
                self._client = await exit_stack.enter_async_context(client)

                with anyio.fail_after(self.timeout):
                    result = await self._client.initialize()
                    self._server_info = result.serverInfo
                    self._server_capabilities = ServerCapabilities.from_mcp_sdk(result.capabilities)
                    self._instructions = result.instructions
                    if log_level := self.log_level:
                        await self._client.set_logging_level(log_level)

                self._exit_stack = exit_stack.pop_all()
        self._running_count += 1
    return self

```

---|---
####  is_running `property`
```
is_running: bool[](https://docs.python.org/3/library/functions.html#bool)

```

Check if the MCP server is running.
###  MCPServerStdio
Bases: `MCPServer[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer "MCPServer \(pydantic_ai.mcp.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(  [](https://ai.pydantic.dev/api/mcp/#__code_72_annotation_1)
    'uv', args=['run', 'mcp-run-python', 'stdio'], timeout=10
)
agent = Agent('openai:gpt-5.2', toolsets=[server])

```

Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
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
```
| ```
class MCPServerStdio(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:
```python {py="3.10"}
    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-5.2', toolsets=[server])
```

    1. See [MCP Run Python](https://github.com/pydantic/mcp-run-python) for more information.
    """

    command: str
    """The command to run."""

    args: Sequence[str]
    """The arguments to pass to the command."""

    env: dict[str, str] | None
    """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`.
    """

    cwd: str | Path | None
    """The working directory to use when spawning the process."""

    # last fields are re-defined from the parent class so they appear as fields
    tool_prefix: str | None
    log_level: mcp_types.LoggingLevel | None
    log_handler: LoggingFnT | None
    timeout: float
    read_timeout: float
    process_tool_call: ProcessToolCallback | None
    allow_sampling: bool
    sampling_model: models.Model | None
    max_retries: int
    elicitation_callback: ElicitationFnT | None = None
    cache_tools: bool
    cache_resources: bool

    def __init__(
        self,
        command: str,
        args: Sequence[str],
        *,
        env: dict[str, str] | None = None,
        cwd: str | Path | None = None,
        tool_prefix: str | None = None,
        log_level: mcp_types.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: models.Model | None = None,
        max_retries: int = 1,
        elicitation_callback: ElicitationFnT | None = None,
        cache_tools: bool = True,
        cache_resources: bool = True,
        id: str | None = None,
        client_info: mcp_types.Implementation | None = None,
    ):
        """Build a new MCP server.

        Args:
            command: The command to run.
            args: The arguments to pass to the command.
            env: The environment variables to set in the subprocess.
            cwd: The working directory to use when spawning the process.
            tool_prefix: A prefix to add to all tools that are registered with the server.
            log_level: The log level to set when connecting to the server, if any.
            log_handler: A handler for logging messages from the server.
            timeout: The timeout in seconds to wait for the client to initialize.
            read_timeout: Maximum time in seconds to wait for new messages before timing out.
            process_tool_call: Hook to customize tool calling and optionally pass extra metadata.
            allow_sampling: Whether to allow MCP sampling through this client.
            sampling_model: The model to use for sampling.
            max_retries: The maximum number of times to retry a tool call.
            elicitation_callback: Callback function to handle elicitation requests from the server.
            cache_tools: Whether to cache the list of tools.
                See [`MCPServer.cache_tools`][pydantic_ai.mcp.MCPServer.cache_tools].
            cache_resources: Whether to cache the list of resources.
                See [`MCPServer.cache_resources`][pydantic_ai.mcp.MCPServer.cache_resources].
            id: 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.
            client_info: Information describing the MCP client implementation.
        """
        self.command = command
        self.args = args
        self.env = env
        self.cwd = cwd

        super().__init__(
            tool_prefix,
            log_level,
            log_handler,
            timeout,
            read_timeout,
            process_tool_call,
            allow_sampling,
            sampling_model,
            max_retries,
            elicitation_callback,
            cache_tools,
            cache_resources,
            id=id,
            client_info=client_info,
        )

    @classmethod
    def __get_pydantic_core_schema__(cls, _: Any, __: Any) -> CoreSchema:
        return core_schema.no_info_after_validator_function(
            lambda dct: MCPServerStdio(**dct),
            core_schema.typed_dict_schema(
                {
                    'command': core_schema.typed_dict_field(core_schema.str_schema()),
                    'args': core_schema.typed_dict_field(core_schema.list_schema(core_schema.str_schema())),
                    'env': core_schema.typed_dict_field(
                        core_schema.dict_schema(core_schema.str_schema(), core_schema.str_schema()),
                        required=False,
                    ),
                }
            ),
        )

    @asynccontextmanager
    async def client_streams(
        self,
    ) -> AsyncIterator[
        tuple[
            MemoryObjectReceiveStream[SessionMessage | Exception],
            MemoryObjectSendStream[SessionMessage],
        ]
    ]:
        server = StdioServerParameters(command=self.command, args=list(self.args), env=self.env, cwd=self.cwd)
        async with stdio_client(server=server) as (read_stream, write_stream):
            yield read_stream, write_stream

    def __repr__(self) -> str:
        repr_args = [
            f'command={self.command!r}',
            f'args={self.args!r}',
        ]
        if self.id:
            repr_args.append(f'id={self.id!r}')  # pragma: lax no cover
        return f'{self.__class__.__name__}({", ".join(repr_args)})'

    def __eq__(self, value: object, /) -> bool:
        return (
            super().__eq__(value)
            and isinstance(value, MCPServerStdio)
            and self.command == value.command
            and self.args == value.args
            and self.env == value.env
            and self.cwd == value.cwd
        )

```

---|---
####  __init__
```
__init__(
    command: str[](https://docs.python.org/3/library/stdtypes.html#str),
    args: Sequence[](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "collections.abc.Sequence")[str[](https://docs.python.org/3/library/stdtypes.html#str)],
    *,
    env: dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), str[](https://docs.python.org/3/library/stdtypes.html#str)] | None = None,
    cwd: str[](https://docs.python.org/3/library/stdtypes.html#str) | Path[](https://docs.python.org/3/library/pathlib.html#pathlib.Path "pathlib.Path") | None = None,
    tool_prefix: str[](https://docs.python.org/3/library/stdtypes.html#str) | None = None,
    log_level: LoggingLevel | None = None,
    log_handler: LoggingFnT | None = None,
    timeout: float[](https://docs.python.org/3/library/functions.html#float) = 5,
    read_timeout: float[](https://docs.python.org/3/library/functions.html#float) = 5 * 60,
    process_tool_call: ProcessToolCallback[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ProcessToolCallback "ProcessToolCallback



      module-attribute
   \(pydantic_ai.mcp.ProcessToolCallback\)") | None = None,
    allow_sampling: bool[](https://docs.python.org/3/library/functions.html#bool) = True,
    sampling_model: Model[](https://ai.pydantic.dev/api/models/base/#pydantic_ai.models.Model "Model \(pydantic_ai.models.Model\)") | None = None,
    max_retries: int[](https://docs.python.org/3/library/functions.html#int) = 1,
    elicitation_callback: ElicitationFnT | None = None,
    cache_tools: bool[](https://docs.python.org/3/library/functions.html#bool) = True,
    cache_resources: bool[](https://docs.python.org/3/library/functions.html#bool) = True,
    id: str[](https://docs.python.org/3/library/stdtypes.html#str) | None = None,
    client_info: Implementation[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.Implementation "mcp.types.Implementation") | None = None
)

```

Build a new MCP server.
Parameters:
Name | Type | Description | Default
---|---|---|---
`command` |  `str[](https://docs.python.org/3/library/stdtypes.html#str)` |  The command to run. |  _required_
`args` |  `Sequence[](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "collections.abc.Sequence")[str[](https://docs.python.org/3/library/stdtypes.html#str)]` |  The arguments to pass to the command. |  _required_
`env` |  `dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), str[](https://docs.python.org/3/library/stdtypes.html#str)] | None` |  The environment variables to set in the subprocess. |  `None`
`cwd` |  `str[](https://docs.python.org/3/library/stdtypes.html#str) | Path[](https://docs.python.org/3/library/pathlib.html#pathlib.Path "pathlib.Path") | None` |  The working directory to use when spawning the process. |  `None`
`tool_prefix` |  `str[](https://docs.python.org/3/library/stdtypes.html#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[](https://docs.python.org/3/library/functions.html#float)` |  The timeout in seconds to wait for the client to initialize. |  `5`
`read_timeout` |  `float[](https://docs.python.org/3/library/functions.html#float)` |  Maximum time in seconds to wait for new messages before timing out. |  `5 * 60`
`process_tool_call` |  `ProcessToolCallback[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ProcessToolCallback "ProcessToolCallback



      module-attribute
   \(pydantic_ai.mcp.ProcessToolCallback\)") | None` |  Hook to customize tool calling and optionally pass extra metadata. |  `None`
`allow_sampling` |  `bool[](https://docs.python.org/3/library/functions.html#bool)` |  Whether to allow MCP sampling through this client. |  `True`
`sampling_model` |  `Model[](https://ai.pydantic.dev/api/models/base/#pydantic_ai.models.Model "Model \(pydantic_ai.models.Model\)") | None` |  The model to use for sampling. |  `None`
`max_retries` |  `int[](https://docs.python.org/3/library/functions.html#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[](https://docs.python.org/3/library/functions.html#bool)` |  Whether to cache the list of tools. See [`MCPServer.cache_tools`](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.cache_tools "cache_tools



      instance-attribute
  "). |  `True`
`cache_resources` |  `bool[](https://docs.python.org/3/library/functions.html#bool)` |  Whether to cache the list of resources. See [`MCPServer.cache_resources`](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServer.cache_resources "cache_resources



      instance-attribute
  "). |  `True`
`id` |  `str[](https://docs.python.org/3/library/stdtypes.html#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`
`client_info` |  `Implementation[](https://modelcontextprotocol.github.io/python-sdk/api/#mcp.Implementation "mcp.types.Implementation") | None` |  Information describing the MCP client implementation. |  `None`
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
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
```
| ```
def __init__(
    self,
    command: str,
    args: Sequence[str],
    *,
    env: dict[str, str] | None = None,
    cwd: str | Path | None = None,
    tool_prefix: str | None = None,
    log_level: mcp_types.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: models.Model | None = None,
    max_retries: int = 1,
    elicitation_callback: ElicitationFnT | None = None,
    cache_tools: bool = True,
    cache_resources: bool = True,
    id: str | None = None,
    client_info: mcp_types.Implementation | None = None,
):
    """Build a new MCP server.

    Args:
        command: The command to run.
        args: The arguments to pass to the command.
        env: The environment variables to set in the subprocess.
        cwd: The working directory to use when spawning the process.
        tool_prefix: A prefix to add to all tools that are registered with the server.
        log_level: The log level to set when connecting to the server, if any.
        log_handler: A handler for logging messages from the server.
        timeout: The timeout in seconds to wait for the client to initialize.
        read_timeout: Maximum time in seconds to wait for new messages before timing out.
        process_tool_call: Hook to customize tool calling and optionally pass extra metadata.
        allow_sampling: Whether to allow MCP sampling through this client.
        sampling_model: The model to use for sampling.
        max_retries: The maximum number of times to retry a tool call.
        elicitation_callback: Callback function to handle elicitation requests from the server.
        cache_tools: Whether to cache the list of tools.
            See [`MCPServer.cache_tools`][pydantic_ai.mcp.MCPServer.cache_tools].
        cache_resources: Whether to cache the list of resources.
            See [`MCPServer.cache_resources`][pydantic_ai.mcp.MCPServer.cache_resources].
        id: 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.
        client_info: Information describing the MCP client implementation.
    """
    self.command = command
    self.args = args
    self.env = env
    self.cwd = cwd

    super().__init__(
        tool_prefix,
        log_level,
        log_handler,
        timeout,
        read_timeout,
        process_tool_call,
        allow_sampling,
        sampling_model,
        max_retries,
        elicitation_callback,
        cache_tools,
        cache_resources,
        id=id,
        client_info=client_info,
    )

```

---|---
####  command `instance-attribute`
```
command: str[](https://docs.python.org/3/library/stdtypes.html#str) = command

```

The command to run.
####  args `instance-attribute`
```
args: Sequence[](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "collections.abc.Sequence")[str[](https://docs.python.org/3/library/stdtypes.html#str)] = args

```

The arguments to pass to the command.
####  env `instance-attribute`
```
env: dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), str[](https://docs.python.org/3/library/stdtypes.html#str)] | None = env

```

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`.
####  cwd `instance-attribute`
```
cwd: str[](https://docs.python.org/3/library/stdtypes.html#str) | Path[](https://docs.python.org/3/library/pathlib.html#pathlib.Path "pathlib.Path") | None = cwd

```

The working directory to use when spawning the process.
###  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-5.2', toolsets=[server])

```

Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
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
```
| ```
class MCPServerSSE(_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:
```python {py="3.10"}
    from pydantic_ai import Agent
    from pydantic_ai.mcp import MCPServerSSE

    server = MCPServerSSE('http://localhost:3001/sse')
    agent = Agent('openai:gpt-5.2', toolsets=[server])
```
    """

    @classmethod
    def __get_pydantic_core_schema__(cls, _: Any, __: Any) -> CoreSchema:
        return core_schema.no_info_after_validator_function(
            lambda dct: MCPServerSSE(**dct),
            core_schema.typed_dict_schema(
                {
                    'url': core_schema.typed_dict_field(core_schema.str_schema()),
                    'headers': core_schema.typed_dict_field(
                        core_schema.dict_schema(core_schema.str_schema(), core_schema.str_schema()), required=False
                    ),
                }
            ),
        )

    # sse_client has a hang bug (https://github.com/modelcontextprotocol/python-sdk/issues/1811)
    # that prevents testing SSE transport in CI.
    # TODO: Remove pragma and add a test
    # once https://github.com/modelcontextprotocol/python-sdk/pull/1838 is released.
    @asynccontextmanager
    async def client_streams(  # pragma: no cover
        self,
    ) -> AsyncIterator[
        tuple[
            MemoryObjectReceiveStream[SessionMessage | Exception],
            MemoryObjectSendStream[SessionMessage],
        ]
    ]:
        if self.http_client and self.headers:
            raise ValueError('`http_client` is mutually exclusive with `headers`.')

        if self.http_client is not None:

            def httpx_client_factory(
                headers: dict[str, str] | None = None,
                timeout: httpx.Timeout | None = None,
                auth: httpx.Auth | None = None,
            ) -> httpx.AsyncClient:
                assert self.http_client is not None
                return self.http_client

            async with sse_client(
                url=self.url,
                timeout=self.timeout,
                sse_read_timeout=self.read_timeout,
                httpx_client_factory=httpx_client_factory,
            ) as (read_stream, write_stream, *_):
                yield read_stream, write_stream
        else:
            async with sse_client(
                url=self.url,
                timeout=self.timeout,
                sse_read_timeout=self.read_timeout,
                headers=self.headers,
            ) as (read_stream, write_stream, *_):
                yield read_stream, write_stream

    def __eq__(self, value: object, /) -> bool:
        return super().__eq__(value) and isinstance(value, MCPServerSSE) and self.url == value.url

```

---|---
###  MCPServerHTTP `deprecated`
Bases: `MCPServerSSE[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerSSE "MCPServerSSE \(pydantic_ai.mcp.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-5.2', toolsets=[server])

```

Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
```
| ```
@deprecated('The `MCPServerHTTP` class is deprecated, use `MCPServerSSE` instead.')
class MCPServerHTTP(MCPServerSSE):
    """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:
```python {py="3.10" test="skip"}
    from pydantic_ai import Agent
    from pydantic_ai.mcp import MCPServerHTTP

    server = MCPServerHTTP('http://localhost:3001/sse')
    agent = Agent('openai:gpt-5.2', toolsets=[server])
```
    """

```

---|---
###  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-5.2', toolsets=[server])

```

Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
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
```
| ```
class MCPServerStreamableHTTP(_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:
```python {py="3.10"}
    from pydantic_ai import Agent
    from pydantic_ai.mcp import MCPServerStreamableHTTP

    server = MCPServerStreamableHTTP('http://localhost:8000/mcp')
    agent = Agent('openai:gpt-5.2', toolsets=[server])
```
    """

    @classmethod
    def __get_pydantic_core_schema__(cls, _: Any, __: Any) -> CoreSchema:
        return core_schema.no_info_after_validator_function(
            lambda dct: MCPServerStreamableHTTP(**dct),
            core_schema.typed_dict_schema(
                {
                    'url': core_schema.typed_dict_field(core_schema.str_schema()),
                    'headers': core_schema.typed_dict_field(
                        core_schema.dict_schema(core_schema.str_schema(), core_schema.str_schema()), required=False
                    ),
                }
            ),
        )

    @asynccontextmanager
    async def client_streams(
        self,
    ) -> AsyncIterator[
        tuple[
            MemoryObjectReceiveStream[SessionMessage | Exception],
            MemoryObjectSendStream[SessionMessage],
        ]
    ]:
        if self.http_client and self.headers:
            raise ValueError('`http_client` is mutually exclusive with `headers`.')

        aexit_stack = AsyncExitStack()
        http_client = self.http_client or await aexit_stack.enter_async_context(
            httpx.AsyncClient(timeout=httpx.Timeout(self.timeout, read=self.read_timeout), headers=self.headers)
        )
        read_stream, write_stream, *_ = await aexit_stack.enter_async_context(
            streamable_http_client(self.url, http_client=http_client)
        )
        try:
            yield read_stream, write_stream
        finally:
            await aexit_stack.aclose()

    def __eq__(self, value: object, /) -> bool:
        return super().__eq__(value) and isinstance(value, MCPServerStreamableHTTP) and self.url == value.url

```

---|---
###  ToolResult `module-attribute`
```
ToolResult = (
    str[](https://docs.python.org/3/library/stdtypes.html#str)
    | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)")
    | dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")]
    | list[](https://docs.python.org/3/library/stdtypes.html#list)[Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")]
    | Sequence[](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "collections.abc.Sequence")[
        str[](https://docs.python.org/3/library/stdtypes.html#str) | BinaryContent[](https://ai.pydantic.dev/api/messages/#pydantic_ai.messages.BinaryContent "BinaryContent \(pydantic_ai.messages.BinaryContent\)") | dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")] | list[](https://docs.python.org/3/library/stdtypes.html#list)[Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")]
    ]
)

```

The result type of an MCP tool call.
###  CallToolFunc `module-attribute`
```
CallToolFunc = Callable[](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable "collections.abc.Callable")[
    [str[](https://docs.python.org/3/library/stdtypes.html#str), dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")], dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")] | None],
    Awaitable[](https://docs.python.org/3/library/collections.abc.html#collections.abc.Awaitable "collections.abc.Awaitable")[ToolResult[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ToolResult "ToolResult



      module-attribute
   \(pydantic_ai.mcp.ToolResult\)")],
]

```

A function type that represents a tool call.
###  ProcessToolCallback `module-attribute`
```
ProcessToolCallback = Callable[](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable "collections.abc.Callable")[
    [RunContext[](https://ai.pydantic.dev/api/tools/#pydantic_ai.tools.RunContext "RunContext



      dataclass
   \(pydantic_ai.tools.RunContext\)")[Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")], CallToolFunc[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.CallToolFunc "CallToolFunc



      module-attribute
   \(pydantic_ai.mcp.CallToolFunc\)"), str[](https://docs.python.org/3/library/stdtypes.html#str), dict[](https://docs.python.org/3/library/stdtypes.html#dict)[str[](https://docs.python.org/3/library/stdtypes.html#str), Any[](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")]],
    Awaitable[](https://docs.python.org/3/library/collections.abc.html#collections.abc.Awaitable "collections.abc.Awaitable")[ToolResult[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.ToolResult "ToolResult



      module-attribute
   \(pydantic_ai.mcp.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.
###  MCPServerConfig
Bases: `BaseModel[](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel "pydantic.BaseModel")`
Configuration for MCP servers.
Source code in `pydantic_ai_slim/pydantic_ai/mcp.py`
```
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
```
| ```
class MCPServerConfig(BaseModel):
    """Configuration for MCP servers."""

    mcp_servers: Annotated[
        dict[
            str,
            Annotated[
                Annotated[MCPServerStdio, Tag('stdio')]
                | Annotated[MCPServerStreamableHTTP, Tag('streamable-http')]
                | Annotated[MCPServerSSE, Tag('sse')],
                Discriminator(_mcp_server_discriminator),
            ],
        ],
        Field(alias='mcpServers'),
    ]

```

---|---
###  load_mcp_servers
```
load_mcp_servers(
    config_path: str[](https://docs.python.org/3/library/stdtypes.html#str) | Path[](https://docs.python.org/3/library/pathlib.html#pathlib.Path "pathlib.Path"),
) -> list[](https://docs.python.org/3/library/stdtypes.html#list)[
    MCPServerStdio[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio "MCPServerStdio \(pydantic_ai.mcp.MCPServerStdio\)") | MCPServerStreamableHTTP[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStreamableHTTP "MCPServerStreamableHTTP \(pydantic_ai.mcp.MCPServerStreamableHTTP\)") | MCPServerSSE[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerSSE "MCPServerSSE \(pydantic_ai.mcp.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[](https://docs.python.org/3/library/stdtypes.html#str) | Path[](https://docs.python.org/3/library/pathlib.html#pathlib.Path "pathlib.Path")` |  The path to the configuration file. |  _required_
Returns:
Type | Description
---|---
`list[](https://docs.python.org/3/library/stdtypes.html#list)[MCPServerStdio[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStdio "MCPServerStdio \(pydantic_ai.mcp.MCPServerStdio\)") | MCPServerStreamableHTTP[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerStreamableHTTP "MCPServerStreamableHTTP \(pydantic_ai.mcp.MCPServerStreamableHTTP\)") | MCPServerSSE[](https://ai.pydantic.dev/api/mcp/#pydantic_ai.mcp.MCPServerSSE "MCPServerSSE \(pydantic_ai.mcp.MCPServerSSE\)")]` |  A list of MCP servers.
Raises:
Type | Description
---|---
`FileNotFoundError[](https://docs.python.org/3/library/exceptions.html#FileNotFoundError)` |  If the configuration file does not exist.
`ValidationError` |  If the configuration file does not match the schema.
`ValueError[](https://docs.python.org/3/library/exceptions.html#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`
```
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
```
| ```
def 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

    Args:
        config_path: The path to the configuration file.

    Returns:
        A list of MCP servers.

    Raises:
        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.
    """
    config_path = Path(config_path)

    if not config_path.exists():
        raise FileNotFoundError(f'Config file {config_path} not found')

    config_data = pydantic_core.from_json(config_path.read_bytes())
    expanded_config_data = _expand_env_vars(config_data)
    config = MCPServerConfig.model_validate(expanded_config_data)

    servers: list[MCPServerStdio | MCPServerStreamableHTTP | MCPServerSSE] = []
    for name, server in config.mcp_servers.items():
        server.id = name
        server.tool_prefix = name
        servers.append(server)

    return servers

```

---|---
© Pydantic Services Inc. 2024 to present
