frommcpimportClientSession, StdioServerParameters frommcp.client.stdioimportstdio_client ... classMCPClient: def__init__(self): # Initialize session and client objects self.session: Optional[ClientSession] =None self.exit_stack = AsyncExitStack() self.anthropic = Anthropic() # methods will go here
asyncdefconnect_to_server(self, server_script_path: str): """Connect to an MCP server Args: server_script_path: Path to the server script (.py or .js) """ ... command ="python"ifis_pythonelse"node" server_params = StdioServerParameters( command=command, args=[server_script_path], env=None ) stdio_transport =awaitself.exit_stack.enter_async_context(stdio_client(server_params)) self.stdio, self.write = stdio_transport self.session =awaitself.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
awaitself.session.initialize() # List available tools response =awaitself.session.list_tools() tools = response.tools print("\nConnected to server with tools:", [tool.namefortoolintools])
asyncdefprocess_query(self, query: str)-> str: """rocess a query using Claude and available tools""" messages = [ { "role":"user", "content": query } ]
未来,随着大模型应用的深入,MCP Server 将变得更加丰富和强大,各类应用也将逐步适配 MCP,降低 AI 接入门槛。正如 OpenAI CEO Sam Altman 所说,2025 is“the year of the AI agent”。或许不久的将来,我们只需一句话,就能让 AI 远程操控电脑、管理手机,彻底改变人机交互方式。