ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

UFO 客户端 MCP 集成实战指南:Computer、MCP 服务器管理与工具执行全解析

UFO 客户端 MCP 集成实战指南:Computer、MCP 服务器管理与工具执行全解析 UFO 客户端 MCP 集成实战指南Computer、MCP 服务器管理与工具执行全解析【免费下载链接】UFOUFO³: Weaving the Digital Agent Galaxy项目地址: https://gitcode.com/GitHub_Trending/uf/UFOMCPModel Context Protocol是 UFO 客户端中的工具执行层它让 Agent 通过统一接口采集系统状态并执行动作。本文围绕客户端视角完整讲解 MCP 在 UFO 客户端架构中的角色、Computer作为 MCP 管理器的内部机制、数据收集/动作两类服务器的区别、config/ufo/mcp.yaml的配置写法以及端到端的工具调用与执行流程。读完本文你将掌握 UFO 客户端 MCP 的完整调用链AIP Command → CommandRouter → Computer → MCP Server能够独立配置、调试并扩展自己的 MCP 工具。MCP 在客户端架构中的角色在 UFO 客户端中MCP 不是孤立的组件而是位于Agent Server 与真实操作系统/应用之间的执行桥梁服务端通过 WebSocket 下发 AIP 命令客户端内的Computer管理所有 MCP 服务器实例、路由工具调用并在线程池中隔离执行。关键组件一览组件源码位置职责Computerufo/client/computer.py管理 MCP 服务器、路由工具调用、在线程池中执行MCP Server Managerufo/client/mcp/mcp_server_manager.py创建/管理服务器实例local/http/stdioCommand Routerufo/client/computer.py将命令路由到对应的 Computer 实例数据收集服务器ufo/client/mcp/local_servers/提供采集系统状态的只读工具动作服务器ufo/client/mcp/local_servers/提供执行状态变更的工具从源码结构看Computer是整个客户端 MCP 的入口与核心它同时持有数据收集服务器集合_data_collection_servers、动作服务器集合_action_servers和工具注册表_tools_registry并通过注入的MCPServerManager完成服务器生命周期的管理。客户端-MCP 集成流程端到端调用链一次完整的工具执行跨越服务端、客户端、路由层和 MCP 服务器四个层次其时序如下执行阶段分解阶段组件描述1. 命令接收UFO Client从服务端接收 AIP Command含tool_name、tool_type、parameters2. 命令路由Command Router依据agent_name/process_name/root_name定位 Computer 实例3. 命令转换Computer调用command2tool()将 AIP Command 转为MCPToolCall4. 工具执行Computer通过 MCP Server 调用call_tool()在独立线程中运行5. 结果返回UFO Client将List[Result]封装为 AIP Result 消息回传服务端这条调用链中涉及的Command、MCPToolCall、Result、ResultStatus等数据结构均定义在 aip/messages.py 中。其中Command是服务端下发的原子工作单元必填tool_name与tool_typeMCPToolCall则是 Computer 内部注册表中保存的“可执行工具描述 服务器引用”的合体。Computer客户端侧的 MCP 管理器类结构与职责Computer类是客户端侧的 MCP 管理器负责服务器注册、工具发现与执行。其核心属性与源码对应关系如下见 ufo/client/computer.py_data_collection_servers/_action_servers按 namespace 保存的BaseMCPServer字典_tools_registry工具注册表键为tool_type::tool_name值为MCPToolCall_meta_tools内置自省工具如list_tools_executorThreadPoolExecutor(max_workers10, thread_name_prefixmcp_tool_)隔离阻塞型 MCP 调用_tool_timeout单工具执行超时默认 6000 秒。初始化示例from ufo.client.computer import Computer from ufo.client.mcp.mcp_server_manager import MCPServerManager # Initialize Computer with MCP servers computer Computer( namenotepad_computer, process_namenotepad.exe, mcp_server_managermcp_manager, data_collection_servers_config[ {namespace: UICollector, type: local, reset: False} ], action_servers_config[ {namespace: HostUIExecutor, type: local, reset: False} ] ) # Async initialization registers all tools await computer.async_init()初始化序列对应Computer.async_init()见 ufo/client/computer.py步骤动作结果1创建 MCP Server Manager服务器生命周期管理器就绪2初始化数据收集服务器注册观察类工具如 UICollector3初始化动作服务器注册执行类工具如 HostUIExecutor、CommandLineExecutor4注册 MCP 服务器通过asyncio.gather并行查询各服务器工具列表填充工具注册表值得注意的源码细节async_init()使用asyncio.gather同时注册数据收集与动作两组服务器注册过程对重复工具键会跳过并打 warning见register_one_mcp_server中对tool_key not in self._tools_registry的判重逻辑避免命名冲突。工具键Tool Key规则Computer.make_tool_key()生成唯一工具键staticmethod def make_tool_key(tool_type: str, tool_name: str) - str: return f{tool_type}::{tool_name}例如data_collection::take_screenshot、action::click、action::run_shell。两个 namespace 允许同名工具共存如data_collection::get_file_info与action::get_file_info这是 namespace 隔离带来的灵活性。命令自动类型探测command2tool()在Command.tool_type缺省时会先在数据收集注册表中查找、再在动作注册表中查找自动推断工具类型这为服务端下发更精简的 Command 提供了容错能力见 ufo/client/computer.py。两类 MCP 服务器数据收集与动作正确区分服务器类型是使用 MCP 的前提。UFO 将 MCP 服务器严格划分为两类方面数据收集服务器动作服务器目的观察系统状态修改系统状态示例工具take_screenshot、detect_ui_elementsclick、type_text、run_command调用方式LLM 选择 / 框架自动调用LLM 选择副作用❌ 无只读✅ 有状态变更namespace 归类data_collectionaction工具键格式data_collection::tool_nameaction::tool_name数据收集示例截图用于 UI 分析# Example: Take screenshot for UI analysis result await computer.run_actions([ computer.command2tool(Command( tool_nametake_screenshot, tool_typedata_collection, parameters{region: active_window} )) ])动作示例点击按钮# Example: Click a button result await computer.run_actions([ computer.command2tool(Command( tool_nameclick, tool_typeaction, parameters{ control_text: Save, control_type: Button } )) ])在 UFO 中数据收集服务器通常由框架自动调用以构建观察上下文observation动作服务器则由 LLM Agent 在每一步根据任务主动选择。动作工具的类型注解Annotated[...]和 docstring 会被自动提取并转换为 LLM 提示中的结构化指令因此为工具编写清晰完整的 docstring 与类型注解会直接影响 LLM 正确使用工具的能力。服务器配置config/ufo/mcp.yaml 全解所有 MCP 服务器的挂载都由 config/ufo/mcp.yaml 声明式驱动。文件采用AgentName → SubType → 工具类别 → 服务器列表的四级层级结构。完整配置结构HostAgent: default: data_collection: - namespace: UICollector # Server namespace type: local # local, http, or stdio start_args: [] reset: false # Reset on each step? action: - namespace: HostUIExecutor # Server namespace type: local start_args: [] reset: false - namespace: CommandLineExecutor # Multiple servers allowed type: local start_args: [] reset: false公共配置参数参数类型必填描述示例namespacestr✅服务器标识须与注册名一致UICollectortypestr✅部署类型local、http、stdiolocalresetbool❌切换上下文时是否重置服务器状态默认falsefalsestart_argsarray❌传给服务器初始化/工厂函数的参数[]三种部署类型补充字段local进程内从MCPRegistry按 namespace 惰性获取FastMCP实例见 ufo/client/mcp/mcp_registry.pyhttp远程额外需要host、port、path由 ufo/client/mcp/mcp_server_manager.py 中的HTTPMCPServer拼装为http://{host}:{port}{path}可选auth支持${ENV_VAR}环境变量注入未解析会抛ValueErrorstdio子进程额外需要command、start_args、env、cwd由StdioMCPServer构造StdioTransport。仓库内置的 Agent 配置一览以当前仓库 config/ufo/mcp.yaml 实际内容为准AgentSubType数据收集动作HostAgentdefaultUICollectorHostUIExecutor、CommandLineExecutorAppAgentdefaultUICollectorAppUIExecutor、CommandLineExecutorAppAgentWINWORD.EXEUICollectorAppUIExecutor、WordCOMExecutorreset: trueAppAgentEXCEL.EXEUICollectorAppUIExecutor、ExcelCOMExecutorreset: trueAppAgentPOWERPNT.EXEUICollectorAppUIExecutor、PowerPointCOMExecutorreset: trueAppAgentexplorer.exeUICollectorAppUIExecutor、PDFReaderExecutorreset: trueConstellationAgentdefault—ConstellationEditorHardwareAgentdefaultHardwareCollectorhttp: localhost:8006/mcpHardwareExecutorhttp: localhost:8006/mcpLinuxAgentdefault—BashExecutorhttp: localhost:8010/mcpMobileAgentdefaultMobileDataCollectorhttp: 8020auth: ${UFO_MCP_API_KEY}MobileActionExecutorhttp: 8021auth: ${UFO_MCP_API_KEY}配置要点与最佳实践更完整的字段说明可参考 documents/docs/mcp/configuration.md始终提供defaultSubType作为兜底ComputerManager.get_or_create在找不到root_name对应配置时会回退到default见 ufo/client/computer.pyreset: true适用于有状态工具如 Word/Excel/PowerPoint 的 COM 执行器避免在切换文档/上下文时状态泄漏文档切换场景见AppAgent各应用子配置HTTP 服务器需先于客户端启动HardwareAgent/LinuxAgent/MobileAgent依赖远程 HTTP 服务对应实现位于 ufo/client/mcp/http_servers/远程端口约定硬件采集 8006、Linux Bash 8010、移动端 8020/8021path统一为/mcp。工具注册表与执行机制自动发现与注册Computer初始化时会自动从所有已配置服务器发现并注册工具。核心逻辑对应源码register_one_mcp_server见 ufo/client/computer.py# During computer.async_init() async def register_mcp_servers(self, servers, tool_type): Register tools from all MCP servers for namespace, server in servers.items(): # Connect to MCP server async with Client(server.server) as client: # List available tools tools await client.list_tools() # Register each tool with unique key for tool in tools: tool_key self.make_tool_key(tool_type, tool.name) self._tools_registry[tool_key] MCPToolCall( tool_keytool_key, tool_nametool.name, titletool.title, namespacenamespace, tool_typetool_type, descriptiontool.description, input_schematool.inputSchema, output_schematool.outputSchema, mcp_serverserver )工具注册表结构MCPToolCall定义于 aip/messages.py字段类型描述tool_keystr唯一键tool_type::tool_nametool_namestr工具名如take_screenshottitlestr展示标题namespacestr服务器命名空间如UICollectortool_typestrdata_collection或actiondescriptionstr工具描述input_schemadict参数 JSON Schemaoutput_schemadict结果 JSON Schemamcp_serverBaseMCPServer所属服务器实例线程隔离与超时保护工具在独立线程中执行并带超时保护默认 6000 秒。这一点在 ufo/client/computer.py 中有完整实现# Thread pool configuration self._executor concurrent.futures.ThreadPoolExecutor( max_workers10, thread_name_prefixmcp_tool_ ) self._tool_timeout 6000 # seconds执行路径_call_tool_in_thread会为每次调用创建独立事件循环防止 MCP 工具中的阻塞操作如time.sleep、同步 I/O拖垮主事件循环、进而引发 WebSocket 断连。超时后返回带is_errorTrue的CallToolResult异常同样被捕获并包装为错误结果返回而不是向上抛出破坏会话。服务器生命周期管理MCPServerManager维护_server_type_mappinghttp → HTTPMCPServer、local → LocalMCPServer、stdio → StdioMCPServer并通过create_or_get_server实现“已存在则复用、resetTrue则先重置”的幂等语义见 ufo/client/mcp/mcp_server_manager.py。集成示例从零搭建调用链基本用法CommandRouter 一键执行from ufo.client.computer import ComputerManager, CommandRouter from ufo.client.mcp.mcp_server_manager import MCPServerManager from aip.messages import Command # Create MCP server manager mcp_server_manager MCPServerManager() # Create computer manager (manages Computer instances) computer_manager ComputerManager(config, mcp_server_manager) # Create command router command_router CommandRouter(computer_manager) # Execute action through MCP command Command( tool_nameclick, tool_typeaction, parameters{ control_text: Save, control_type: Button } ) # Router creates Computer instance and executes results await command_router.execute( agent_nameHostAgent, process_namenotepad.exe, root_namedefault, commands[command] )此处config即为加载后的 UFO 配置包含mcp段。CommandRouter.execute支持early_exit参数为True时遇到失败会跳过后续命令并将状态置为ResultStatus.SKIPPED此外每条命令执行后会asyncio.sleep(0.1)以平滑请求压力。对应的可运行测试可参考 ufo/client/computer.py 底部的test_command_router()函数。自定义 MCP 服务器利用FastMCP定义新工具并在mcp.yaml中注册from fastmcp import FastMCP # Define custom MCP server mcp FastMCP(CustomTools) mcp.tool() async def custom_action(param: str) - str: Execute custom action return fExecuted: {param}# Register in config/ufo/mcp.yaml: # action: # - namespace: CustomTools # type: local # reset: false更完整的自定义服务器开发步骤本地/HTTP/stdio 三种形态、MCPRegistry.register_factory_decorator注册工厂、docstring 与类型注解规范等见 documents/docs/tutorials/creating_mcp_servers.md。仓库内置服务器的真实范例位于 ufo/client/mcp/local_servers/如ui_mcp_server.py同时提供 UICollector 与 UI 执行器、ufo/client/mcp/http_servers/硬件、Linux、移动端远程服务。与其他客户端组件的集成点组件协作方式UFO Client接收服务端 AIP Command委托给 Command Router返回 AIP ResultCommand Router按 agent/process/root 名称路由到对应 Computer 实例管理 early-exit 执行语义ComputerMCP 入口管理全部 MCP 服务器、经 MCPServerManager 执行工具、维护工具注册表MCP Server Manager创建并管理服务器实例支持 local/HTTP/stdio 三种部署类型此外Computer还提供动态服务器管理能力add_server()/delete_server()可在运行期挂载/卸载服务器及工具支持热插拔场景内置元工具list_tools通过Computer.meta_tool(list_tools)装饰器注册可用于自省当前可用的全部工具。UFO Client 的会话编排与 WebSocket 通信细节见 documents/docs/client/ufo_client.md 与 documents/docs/client/websocket_client.md。关键要点Computer 是 MCP 管理器管理全部 MCP 服务器实例、路由工具调用、在线程池中隔离执行两类服务器数据收集只读观察与动作状态变更执行LLM 主要选择动作工具配置驱动服务器在 config/ufo/mcp.yaml 中声明支持 local/HTTP/stdio 三种部署自动注册初始化时自动发现工具依据服务器元数据构建工具注册表纵深防御线程池10 workers 独立事件循环 6000 秒超时保障 WebSocket 连接与主事件循环稳定深入阅读MCP 体系总览见 documents/docs/mcp/overview.mdComputer 详细类文档见 documents/docs/client/computer.md自建工具教程见 documents/docs/tutorials/creating_mcp_servers.md。【免费下载链接】UFOUFO³: Weaving the Digital Agent Galaxy项目地址: https://gitcode.com/GitHub_Trending/uf/UFO创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表