import asyncio import json import sys import time from typing import Optional from contextlib import AsyncExitStack from mcp.client.sse import sse_client from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from openai import AsyncOpenAI
class MCPClient: def __init__(self): # Initialize session and client objects self.session: Optional[ClientSession] = None self.exit_stack = AsyncExitStack() self.client = AsyncOpenAI( # 此处使用阿里的qwen-plus大模型 api_key="your api key", base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", )
2、创建连接到MCP服务端函数
MCP服务端传输协议支持stdio和sse,所以此处创建2个函数
async def connect_to_server(self, server_script_path: str): """Connect to an MCP server
Args: server_script_path: Path to the server script (.py or .js) """ is_python = server_script_path.endswith(".py") is_js = server_script_path.endswith(".js") ifnot (is_python or is_js): raise ValueError("Server script must be a .py or .js file")
# List available tools response = await self.session.list_tools() tools = response.tools print("\nConnected to server with tools:", [tool.namefortoolintools])
async def connect_to_sse_server(self, server_url: str): """Connect to an MCP server
Args: server_script_path: Path to the server script (.py or .js) """ self._streams_context = sse_client(url=server_url)
await self.session.initialize() # List available tools response = await self.session.list_tools() tools = response.tools print("\nConnected to server with tools:", [tool.namefortoolintools])
# MCP Server传输协议为stdio,启动命令为: uv run client.py"完整server端脚本路径"
# MCP Server传输协议为sse,启动命令为: uv run client.py http://127.0.0.1:8000/sse # 上面的sse地址根据自己的进行调整
8、运行截图
9、完整源码
import asyncio import json import sys import time from typing import Optional from contextlib import AsyncExitStack from mcp.client.sse import sse_client from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from openai import AsyncOpenAI
async def connect_to_server(self, server_script_path: str): """Connect to an MCP server
Args: server_script_path: Path to the server script (.py or .js) """ is_python = server_script_path.endswith(".py") is_js = server_script_path.endswith(".js") ifnot (is_python or is_js): raise ValueError("Server script must be a .py or .js file")
# List available tools response = await self.session.list_tools() tools = response.tools print("\nConnected to server with tools:", [tool.namefortoolintools])
async def connect_to_sse_server(self, server_url: str): """Connect to an MCP server
Args: server_script_path: Path to the server script (.py or .js) """ self._streams_context = sse_client(url=server_url)
await self.session.initialize() # List available tools response = await self.session.list_tools() tools = response.tools print("\nConnected to server with tools:", [tool.namefortoolintools])