跳转到主要内容
MCPClient 是一个用于与任意 MCP 服务器通信的异步 Python Client。它负责处理 MCP 握手(initialize)、传输层初始化和会话管理——这样你就可以专注于要执行的具体操作。 当你需要显式且可预测的控制时,使用 MCPClient,例如:
  • 在开发过程中测试 MCP 服务器
  • 构建需要可靠 MCP 交互的应用
  • 在类型化协议层之上构建更高层的客户端(包括“智能体式”流程)

快速开始

连接 → 执行任务 → 关闭。
import asyncio
from dedalus_mcp.client import MCPClient

async def main():
    # 运行 `await server.serve()` 时的本地开发默认地址
    client = await MCPClient.connect("http://127.0.0.1:8000/mcp")
    try:
        tools = await client.list_tools()
        result = await client.call_tool("add", {"a": 5, "b": 3})
        print(result)
    finally:
        await client.close()

asyncio.run(main())
若需要确保资源被正确清理,建议优先使用 async with
from dedalus_mcp.client import MCPClient

async with await MCPClient.connect("http://127.0.0.1:8000/mcp") as client:
    tools = await client.list_tools()

Connection

连接

from dedalus_mcp.client import MCPClient

client = await MCPClient.connect("http://127.0.0.1:8000/mcp")

协议信息

在连接建立后,initialize_result 会被填充:
print(f"Server: {client.initialize_result.serverInfo.name}")
print(f"Protocol: {client.initialize_result.protocolVersion}")
print(f"Session: {client.session_id}")

关闭

await client.close()

替代方案:open_connection(...)

open_connection(...) 是一个便捷封装函数,会建立一个已连接的 MCPClient,并在结束时自动清理资源:
from dedalus_mcp.client import open_connection

async with open_connection("http://127.0.0.1:8000/mcp") as client:
    tools = await client.list_tools()

Ping

await client.ping()

操作

大多数 Client 代码可以归为以下几类:

Client 能力(服务器 → Client)

部分模型上下文协议 (MCP) 功能由服务器发起。如果你想支持这些功能,需要在连接时配置相应的处理程序。

身份验证

对于受保护的 MCP 服务器:

DPoP 认证

对于使用 DPoP(RFC 9449)发送方绑定令牌的服务器:
from dedalus_mcp.auth.dpop import generate_dpop_keypair
from dedalus_mcp.client import DPoPAuth, MCPClient

dpop_key, _ = generate_dpop_keypair()
auth = DPoPAuth(access_token="eyJ...", dpop_key=dpop_key)

# 本地开发:
client = await MCPClient.connect("http://127.0.0.1:8000/mcp", auth=auth)

# 生产:
# client = await MCPClient.connect("<your MCP endpoint URL>", auth=auth)