Skip to content

Mcp

This module implements the MCP server interface between the agent and the LLM.

See https://docs.cursor.com/context/model-context-protocol for more information.

MCPServer

Bases: ABC

Base class for MCP servers that can be used to run a command or connect to an SSE server.

See https://modelcontextprotocol.io/introduction for more information.

Source code in pydantic_ai_slim/pydantic_ai/mcp.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class MCPServer(ABC):
    """Base class for MCP servers that can be used to run a command or connect to an SSE server.

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

    is_running: bool = False

    _client: ClientSession
    _read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception]
    _write_stream: MemoryObjectSendStream[JSONRPCMessage]
    _exit_stack: AsyncExitStack

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

    async def list_tools(self) -> list[ToolDefinition]:
        """Retrieve tools that are currently active on the server.

        Note:
        - We don't cache tools as they might change.
        - We also don't subscribe to the server to avoid complexity.
        """
        tools = await self._client.list_tools()
        return [
            ToolDefinition(
                name=tool.name,
                description=tool.description or '',
                parameters_json_schema=tool.inputSchema,
            )
            for tool in tools.tools
        ]

    async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> CallToolResult:
        """Call a tool on the server.

        Args:
            tool_name: The name of the tool to call.
            arguments: The arguments to pass to the tool.

        Returns:
            The result of the tool call.
        """
        return await self._client.call_tool(tool_name, arguments)

    async def __aenter__(self) -> Self:
        self._exit_stack = AsyncExitStack()

        self._read_stream, self._write_stream = await self._exit_stack.enter_async_context(self.client_streams())
        client = ClientSession(read_stream=self._read_stream, write_stream=self._write_stream)
        self._client = await self._exit_stack.enter_async_context(client)

        await self._client.initialize()
        self.is_running = True
        return self

    async def __aexit__(
        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
    ) -> bool | None:
        await self._exit_stack.aclose()
        self.is_running = False

client_streams abstractmethod async

client_streams() -> AsyncIterator[
    tuple[
        MemoryObjectReceiveStream[
            JSONRPCMessage | Exception
        ],
        MemoryObjectSendStream[JSONRPCMessage],
    ]
]

Create the streams for the MCP server.

Source code in pydantic_ai_slim/pydantic_ai/mcp.py
48
49
50
51
52
53
54
55
56
57
@abstractmethod
@asynccontextmanager
async def client_streams(
    self,
) -> AsyncIterator[
    tuple[MemoryObjectReceiveStream[JSONRPCMessage | Exception], MemoryObjectSendStream[JSONRPCMessage]]
]:
    """Create the streams for the MCP server."""
    raise NotImplementedError('MCP Server subclasses must implement this method.')
    yield

list_tools async

list_tools() -> list[ToolDefinition]

Retrieve tools that are currently active on the server.

Note: - We don't cache tools as they might change. - We also don't subscribe to the server to avoid complexity.

Source code in pydantic_ai_slim/pydantic_ai/mcp.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
async def list_tools(self) -> list[ToolDefinition]:
    """Retrieve tools that are currently active on the server.

    Note:
    - We don't cache tools as they might change.
    - We also don't subscribe to the server to avoid complexity.
    """
    tools = await self._client.list_tools()
    return [
        ToolDefinition(
            name=tool.name,
            description=tool.description or '',
            parameters_json_schema=tool.inputSchema,
        )
        for tool in tools.tools
    ]

call_tool async

call_tool(
    tool_name: str, arguments: dict[str, Any]
) -> CallToolResult

Call a tool on the server.

Parameters:

Name Type Description Default
tool_name str

The name of the tool to call.

required
arguments dict[str, Any]

The arguments to pass to the tool.

required

Returns:

Type Description
CallToolResult

The result of the tool call.

Source code in pydantic_ai_slim/pydantic_ai/mcp.py
76
77
78
79
80
81
82
83
84
85
86
async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> CallToolResult:
    """Call a tool on the server.

    Args:
        tool_name: The name of the tool to call.
        arguments: The arguments to pass to the tool.

    Returns:
        The result of the tool call.
    """
    return await self._client.call_tool(tool_name, arguments)

MCPServerStdio dataclass

Bases: MCPServer

An MCP server that runs a subprocess.

This class implements the stdio transport from the MCP specification. See https://modelcontextprotocol.io/docs/concepts/transports#standard-input%2Foutput-stdio for more information.

Example:

from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio

server = MCPServerStdio('python', ['-m', 'pydantic_ai_examples.mcp_server'])
agent = Agent('openai:gpt-4o', mcp_servers=[server])

Source code in pydantic_ai_slim/pydantic_ai/mcp.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@dataclass
class MCPServerStdio(MCPServer):
    """An MCP server that runs a subprocess.

    This class implements the stdio transport from the MCP specification.
    See <https://modelcontextprotocol.io/docs/concepts/transports#standard-input%2Foutput-stdio> for more information.

    Example:
    ```python {py="3.10"}
    from pydantic_ai import Agent
    from pydantic_ai.mcp import MCPServerStdio

    server = MCPServerStdio('python', ['-m', 'pydantic_ai_examples.mcp_server'])
    agent = Agent('openai:gpt-4o', mcp_servers=[server])
    ```
    """

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

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

    env: dict[str, str] | None = None
    """The environment variables the CLI server will have access to."""

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

command instance-attribute

command: str

The command to run.

args instance-attribute

args: Sequence[str]

The arguments to pass to the command.

env class-attribute instance-attribute

env: dict[str, str] | None = None

The environment variables the CLI server will have access to.

MCPServerSSE dataclass

Bases: MCPServer

An MCP server that connects to a remote server.

This class implements the SSE transport from the MCP specification. See https://modelcontextprotocol.io/docs/concepts/transports#server-sent-events-sse for more information.

Source code in pydantic_ai_slim/pydantic_ai/mcp.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
@dataclass
class MCPServerSSE(MCPServer):
    """An MCP server that connects to a remote server.

    This class implements the SSE transport from the MCP specification.
    See <https://modelcontextprotocol.io/docs/concepts/transports#server-sent-events-sse> for more information.
    """

    url: str
    """The URL of the remote server."""

    @asynccontextmanager
    async def client_streams(
        self,
    ) -> AsyncIterator[
        tuple[MemoryObjectReceiveStream[JSONRPCMessage | Exception], MemoryObjectSendStream[JSONRPCMessage]]
    ]:  # pragma: no cover
        async with sse_client(url=self.url) as (read_stream, write_stream):
            yield read_stream, write_stream

url instance-attribute

url: str

The URL of the remote server.