MCP Host 是一个 AI 应用,它在运行 MCP 客户端的同时,为执行基于 AI 的任务提供环境。它集成交互工具和数据,以实现与外部服务的顺畅通信。比如: Claude Desktop 用于 AI 辅助内容创建,Cursor 是一个 AI 驱动的 IDE,用于代码补全和软件开发,以及执行复杂任务的 AI Agent。MCP 主机承载 MCP 客户端,并确保与外部 MCP 服务器通信。
**MCP Server (服务终端) 就像是各个专业部门或外部服务提供商,每一个都负责特定类型的服务。有的提供数据分析(如财务部),有的提供信息检索(如资料室),还有的提供内容生成(如市场部)。在MCP架构中,每个Server提供特定类型的功能:工具、资源或提示。在MCP出现之前,开发者则需要为每个工具单独编写连接代码,效率低下且难以维护。在MCP之后,秘书只需使用一个统一的通信平台,就能以相同的方式联系所有部门和服务提供商。开发者也只需实现一次MCP接口,就能让AI系统与所有支持该协议的工具进行交互。
# 省略了无关的代码 asyncdefstart(self): """启动服务的主流程""" # 1. 初始化所有的 MCP 服务器 for server inself.servers: await server.initialize()
# 2. 收集所有可用的工具 # 从所有服务器获取可用工具列表,合并到统一列表 all_tools = [] for server inself.servers: tools = await server.list_tools() # 异步获取工具列表 all_tools.extend(tools) # 合并多个服务器的工具
# 3. 格式化工具描述供LLM使用 # 将每个工具转换为LLM可理解的格式,生成完整的工具描述字符串 # 每个工具的描述包含名称、功能说明和参数信息 tools_description = "\n".join( [tool.format_for_llm() for tool in all_tools] # 调用每个工具的格式化方法 ) # 4. 构建系统提示消息 # ---------------------------- # 包含以下关键信息: # - 可用工具列表 # - JSON响应格式要求 # - 后续数据处理规范 system_message = ( "You are a helpful assistant with access to these tools:\n\n" f"{tools_description}\n" "Choose the appropriate tool based on the user's question. " "If no tool is needed, reply directly.\n\n" # JSON 格式要求说明 "IMPORTANT: When you need to use a tool, you must ONLY respond with " "the exact JSON object format below, nothing else:\n" "{\n" ' "tool": "tool-name",\n' ' "arguments": {\n' ' "argument-name": "value"\n' " }\n" "}\n\n" "After receiving a tool's response:\n" "1. Transform the raw data into a natural, conversational response\n" "2. Keep responses concise but informative\n" "3. Focus on the most relevant information\n" "4. Use appropriate context from the user's question\n" "5. Avoid simply repeating the raw data\n\n" "Please use only the tools that are explicitly defined above." )
# 5. 初始化消息历史 messages = [{"role": "system", "content": system _message}]