Pydantic AI 模型上下文协议服务器
模型上下文协议服务器在沙箱中运行Python代码。
服务介绍
MCP Run Python
Model Context Protocol 服务器用于在沙箱中运行 Python 代码。
该代码使用 Deno 中的 Pyodide 执行,因此与操作系统的其他部分隔离。
完整的文档请参见 https://ai.pydantic.dev/mcp/run-python/。
可以使用安装了 deno 的方式运行服务器:
deno run \
-N -R=node_modules -W=node_modules --node-modules-dir=auto \
jsr:@pydantic/mcp-run-python [stdio|sse|warmup]
其中:
-N -R=node_modules -W=node_modules(--allow-net --allow-read=node_modules --allow-write=node_modules的别名)允许网络访问和对./node_modules的读写访问。这些是必需的,以便 Pyodide 可以下载并缓存 Python 标准库和包。--node-modules-dir=auto告诉 Deno 使用本地的node_modules目录。stdio使用
Stdio MCP 传输 运行服务器 —— 适合在本地作为子进程运行。sse使用
SSE MCP 传输 运行服务器 —— 将服务器作为 HTTP 服务器运行,以便本地或远程连接。warmup会运行一个最小的 Python 脚本来下载并缓存 Python 标准库。这也可用于检查服务器是否正常运行。
以下是一个使用 @pydantic/mcp-run-python 和 PydanticAI 的示例:
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio
import logfire
logfire.configure()
logfire.instrument_mcp()
logfire.instrument_pydantic_ai()
server = MCPServerStdio('deno',
args=[
'run',
'-N',
'-R=node_modules',
'-W=node_modules',
'--node-modules-dir=auto',
'jsr:@pydantic/mcp-run-python',
'stdio',
])
agent = Agent('claude-3-5-haiku-latest', mcp_servers=[server])
async def main():
async with agent.run_mcp_servers():
result = await agent.run('How many days between 2000-01-01 and 2025-03-18?')
print(result.output)
#> There are 9,208 days between January 1, 2000, and March 18, 2025.w
if __name__ == '__main__':
import asyncio
asyncio.run(main())