Skip to content

MCP 协议 — 概念

MCP 协议规范

MCP(Model Context Protocol)是一种标准化协议,允许 AI 模型与外部工具和数据源交互。Codex 通过 McpConnectionManagercodex-mcp/src/connection_manager.rs)管理 MCP 服务器连接:

McpConnectionManager 的核心字段:

rust
pub struct McpConnectionManager {
    clients: HashMap<String, AsyncManagedClient>,
    server_metadata: HashMap<String, McpServerMetadata>,
    tool_plugin_provenance: HashMap<...>,
    host_owned_codex_apps_enabled: bool,
    prefix_mcp_tool_names: bool,
    elicitation_requests: ElicitationRequestManager,
    startup_cancellation_token: CancellationToken,
}

核心方法:

方法功能
new_uninitialized()创建未初始化的管理器
has_servers()检查是否有配置的 MCP 服务器
begin_shutdown()开始优雅关闭
shutdown()等待所有连接关闭
set_approval_policy()设置工具调用的审批策略
set_permission_profile()设置权限配置

工具注册与发现

MCP 工具的注册和发现流程:

工具注册的关键步骤:

  1. 配置加载:从 config.toml[mcp_servers] 段读取 MCP 服务器配置
  2. 连接建立:根据传输类型(InProcess/Stdio/StreamableHttp)建立连接
  3. 工具发现:连接建立后,服务器报告其支持的工具列表
  4. 可见性过滤tool_is_model_visible() 根据工具的 UI 可见性元数据过滤,确保模型只看到应使用的工具
  5. 工具注册:通过 tool_plugin_provenance 跟踪工具的来源服务器

数据源集成

MCP 服务器不仅提供工具,还可以提供资源(Resources)和提示(Prompts):

MCP 能力说明Codex 集成
Tools可调用的函数注册到代理循环的工具列表
Resources可读取的数据源通过 read_mcp_resource() 访问
Prompts预定义的提示模板注入到上下文中

CodexThread 提供 MCP 相关的便捷方法:

rust
impl CodexThread {
    pub fn read_mcp_resource(&self, server: &str, uri: &str) -> Result<String>
    pub fn call_mcp_tool(&self, server: &str, tool: &str, args: Value) -> Result<Value>
}

生命周期管理

MCP 服务器的生命周期由 McpConnectionManager 管理:

生命周期关键事件:

  • 启动:配置加载时创建连接,支持 startup_cancellation_token 取消
  • Elicitation:MCP 服务器可通过 ElicitationRequestManager 向用户请求信息(仅在 TUI 模式下有效)
  • 关闭begin_shutdown() 开始优雅关闭,shutdown() 等待所有连接终止
  • 配置热更新:支持运行时添加/移除 MCP 服务器

相关概念