【async with】

pip install openai openai-agents
from agents.mcp import MCPServerSse

async def main():
    async with MCPServerSse(
        name="12306_mcp",
        params={
            "url": "https://mcp.api-inference.modelscope.cn/sse/56a8f2b1578fxx",  # 这里需要替换成 MCP的 SSE URL
            "timeout": 30,            # HTTP请求超时时间30秒
            "sse_read_timeout": 5   # 连接超时时间到5分钟
        },
        client_session_timeout_seconds=60,  # 增加客户端会话超时到60秒
        cache_tools_list=True,             # 启用工具列表缓存
    ) as mcp:
        print(f"连接MCP服务器成功: {mcp.name}")  # 通过静态方法name查看当前连接的MCP服务器名称
        try:
            tools = await mcp.list_tools()   # 通过其父类_MCPServerWithClientSession中的list_tools方法列出可用工具
            print(f"可用工具列表: {[tool.name for tool in tools]}")
        except Exception as e:
            print(f"获取工具列表失败: {e}")

async with 是 Python 中 异步上下文管理器(asynchronous context manager) 的语法,用来配合 async def 使用,管理异步资源的生命周期,比如网络连接、数据库连接、WebSocket、SSE 等。


✅ 普通 withasync with 对比

场景 语法 用法说明
同步资源 with 打开文件、加锁等
异步资源(如 aiohttp、数据库连接池) async with 支持 await 的上下文管理器,比如异步 HTTP 会话、异步数据库连接

🎯 你这段代码中 async with MCPServerSse(...) as mcp: 的含义:

async with MCPServerSse(...) as mcp:
    ...

表示你正在异步创建一个 MCPServerSse 的实例(可能是 SSE 连接),进入时会触发它的 __aenter__() 方法(即初始化连接),退出 with 块时会触发 __aexit__() 方法(即关闭连接)。

这可以确保资源自动关闭,避免“连接未关闭”“资源泄露”等问题。


✅ 举个例子帮助你理解

🔁 同步版本

with open("file.txt", "r") as f:
    content = f.read()

🔁 异步版本(以 aiohttp 举例)

import aiohttp

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://example.com") as response:
            print(await response.text())

aiohttp.ClientSession()session.get(...) 都是异步资源,必须用 async with 管理。


✅ 你为什么需要它?

因为你用的是 MCPServerSse,这个类背后大概率是基于 SSE(Server-Sent Events)或异步 HTTP 实现的,具备连接和断开两个阶段,必须被正确关闭。async with 正好自动管理这些步骤,保证健壮性和优雅退出。


如果你需要,我可以帮你展开 MCPServerSse 背后的实现细节(如它的 __aenter____aexit__ 实现)。需要的话请告诉我。

posted @ 2025-07-04 16:11  十三山入秋  阅读(61)  评论(1)    收藏  举报