pydantic_ai.mcp
MCPServer
基类: ABC
用于将代理附加到 MCP 服务器的基类。
参见 https://modelcontextprotocol.io 了解更多信息。
源代码位于 pydantic_ai_slim/pydantic_ai/mcp.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
|
client_streams abstractmethod
async
client_streams() -> AsyncIterator[
tuple[
MemoryObjectReceiveStream[
JSONRPCMessage | Exception
],
MemoryObjectSendStream[JSONRPCMessage],
]
]
为 MCP 服务器创建流。
源代码位于 pydantic_ai_slim/pydantic_ai/mcp.py
43 44 45 46 47 48 49 50 51 52 |
|
list_tools async
list_tools() -> list[ToolDefinition]
检索当前在服务器上处于活动状态的工具。
注意:- 我们不缓存工具,因为它们可能会更改。- 我们也不订阅服务器以避免复杂性。
源代码位于 pydantic_ai_slim/pydantic_ai/mcp.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
call_tool async
在服务器上调用工具。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
tool_name
|
字符串
|
要调用的工具的名称。 |
必需 |
参数
|
dict[str, Any]
|
传递给工具的参数。 |
必需 |
返回值
类型 | 描述 |
---|---|
CallToolResult
|
工具调用的结果。 |
源代码位于 pydantic_ai_slim/pydantic_ai/mcp.py
71 72 73 74 75 76 77 78 79 80 81 |
|
MCPServerStdio dataclass
基类: MCPServer
在子进程中运行 MCP 服务器,并通过 stdin/stdout 与其通信。
此类实现了 MCP 规范中的 stdio 传输。请参阅 https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#stdio 了解更多信息。
注意
将此类用作异步上下文管理器将在进入上下文时启动服务器作为子进程,并在退出上下文时停止它。
示例
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio
server = MCPServerStdio('npx', ['-y', '@pydantic/mcp-run-python', 'stdio']) # (1)!
agent = Agent('openai:gpt-4o', mcp_servers=[server])
async def main():
async with agent.run_mcp_servers(): # (2)!
...
- 参见 MCP 运行 Python 了解更多信息。
- 这将启动服务器作为子进程并连接到它。
源代码位于 pydantic_ai_slim/pydantic_ai/mcp.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
|
MCPServerHTTP dataclass
基类: MCPServer
通过可流式 HTTP 连接连接的 MCP 服务器。
此类实现了 MCP 规范中的 SSE 传输。请参阅 https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse 了解更多信息。
名称 "HTTP" 的使用是因为此实现将在未来进行调整,以使用新的 Streamable HTTP 目前正在开发中。
注意
将此类用作异步上下文管理器将创建一个新的 HTTP 连接池,以连接到应该已经在运行的服务器。
示例
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerHTTP
server = MCPServerHTTP('https://127.0.0.1:3001/sse') # (1)!
agent = Agent('openai:gpt-4o', mcp_servers=[server])
async def main():
async with agent.run_mcp_servers(): # (2)!
...
- 例如,您可能正在连接到使用以下命令运行的服务器:
npx @pydantic/mcp-run-python sse
,请参阅 MCP 运行 Python 了解更多信息。 - 这将连接到运行在
localhost:3001
的服务器。
源代码位于 pydantic_ai_slim/pydantic_ai/mcp.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
|
url instance-attribute
url: str
MCP 服务器上 SSE 端点的 URL。
例如,对于本地运行的服务器,这可能是 https://127.0.0.1:3001/sse
。