Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,532 @@
use super::PluginMcpConfigParseOutcome;
use super::PluginMcpServerParseError;
use codex_config::McpServerConfig;
use serde::Deserialize;
use serde_json::Map as JsonMap;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::Path;
use std::path::PathBuf;
use url::Host;
// Published Agent Plugins v1 MCP schema:
// https://github.com/agentplugins/agent-plugins-spec/blob/main/schemas/1.0.0/mcp.schema.json
const AGENT_PLUGIN_MCP_SCHEMA_URI: &str = "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json";
const SUPPORTED_AGENT_PLUGIN_MCP_SCHEMA_URIS: &[&str] = &[AGENT_PLUGIN_MCP_SCHEMA_URI];
const PLUGIN_ROOT_VARIABLE: &str = "PLUGIN_ROOT";
const PLUGIN_DATA_VARIABLE: &str = "PLUGIN_DATA";
const CLIENT_OWNED_HTTP_HEADERS: &[&str] = &[
"accept",
"authorization",
"connection",
"content-encoding",
"content-length",
"content-type",
"host",
"last-event-id",
"mcp-protocol-version",
"mcp-session-id",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"user-agent",
];
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct AgentPluginMcpFile {
#[serde(rename = "$schema")]
schema: String,
mcp_servers: BTreeMap<String, JsonValue>,
}
#[derive(Debug, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
enum AgentPluginMcpServer {
#[serde(rename = "stdio")]
Stdio {
command: String,
#[serde(default)]
args: Vec<String>,
#[serde(default)]
env: BTreeMap<String, String>,
cwd: Option<String>,
},
#[serde(rename = "streamable-http")]
StreamableHttp {
url: String,
headers: Option<BTreeMap<String, String>>,
},
#[serde(rename = "sse")]
Sse {
#[serde(rename = "url")]
_url: String,
#[serde(rename = "headers")]
_headers: Option<BTreeMap<String, String>>,
},
}
/// Translates an Agent Plugins `mcp.json` into Codex MCP configuration.
pub fn parse_agent_plugin_mcp_config(
plugin_root: &Path,
plugin_data_root: &Path,
contents: &str,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
parse_agent_plugin_mcp_config_from(contents, plugin_root, plugin_data_root)
}
fn parse_agent_plugin_mcp_config_from(
contents: &str,
plugin_root: &Path,
plugin_data_root: &Path,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
let AgentPluginMcpFile {
schema,
mcp_servers,
} = serde_json::from_str(contents)?;
if !SUPPORTED_AGENT_PLUGIN_MCP_SCHEMA_URIS.contains(&schema.as_str()) {
return Err(plugin_mcp_json_error(format!(
"unsupported Agent Plugins MCP schema `{schema}`; supported schemas: {}",
SUPPORTED_AGENT_PLUGIN_MCP_SCHEMA_URIS.join(", ")
)));
}
let mut outcome = PluginMcpConfigParseOutcome::default();
for (name, value) in mcp_servers {
match normalize_agent_plugin_mcp_server(value, plugin_root, plugin_data_root) {
Ok(config) => {
outcome.servers.insert(name, config);
}
Err(message) => outcome
.errors
.push(PluginMcpServerParseError { name, message }),
}
}
Ok(outcome)
}
fn normalize_agent_plugin_mcp_server(
value: JsonValue,
plugin_root: &Path,
plugin_data_root: &Path,
) -> Result<McpServerConfig, String> {
let object = value
.as_object()
.ok_or_else(|| "Agent Plugins MCP server must be an object".to_string())?;
match object.get("type").and_then(JsonValue::as_str) {
Some("stdio") => reject_explicit_null(object, "cwd")?,
Some("streamable-http" | "sse") => reject_explicit_null(object, "headers")?,
_ => {}
}
let server =
serde_json::from_value::<AgentPluginMcpServer>(value).map_err(|err| err.to_string())?;
let object = match server {
AgentPluginMcpServer::Stdio {
command,
args,
env,
cwd,
} => normalize_agent_plugin_stdio_server(
command,
args,
env,
cwd,
plugin_root,
plugin_data_root,
)?,
AgentPluginMcpServer::StreamableHttp { url, headers } => {
normalize_agent_plugin_http_server(url, headers)?
}
AgentPluginMcpServer::Sse { .. } => {
return Err("Agent Plugins legacy SSE transport is not supported by Codex".to_string());
}
};
serde_json::from_value(JsonValue::Object(object)).map_err(|err| err.to_string())
}
fn normalize_agent_plugin_stdio_server(
mut command: String,
mut args: Vec<String>,
mut env: BTreeMap<String, String>,
cwd: Option<String>,
plugin_root: &Path,
plugin_data_root: &Path,
) -> Result<JsonMap<String, JsonValue>, String> {
#[cfg(windows)]
let has_windows_path_prefix = matches!(
Path::new(&command).components().next(),
Some(std::path::Component::Prefix(_))
);
#[cfg(not(windows))]
let has_windows_path_prefix = false;
let is_bare_command = !command.is_empty()
&& !command.contains('/')
&& !command.contains('\\')
&& !has_windows_path_prefix;
let is_plugin_relative_command =
command.starts_with("./") && is_portable_relative_path(&command);
if !is_bare_command && !is_plugin_relative_command {
return Err(
"Agent Plugins stdio command must be a bare executable name or a contained `./` path"
.to_string(),
);
}
for reserved in [PLUGIN_ROOT_VARIABLE, PLUGIN_DATA_VARIABLE] {
if env
.keys()
.any(|name| environment_variable_names_match(name, reserved))
{
return Err(format!(
"Agent Plugins stdio `env` cannot override reserved variable `{reserved}`"
));
}
}
#[cfg(windows)]
{
let mut normalized_env = BTreeMap::new();
for (name, value) in env {
let normalized_name = name.to_ascii_uppercase();
if normalized_env.insert(normalized_name, value).is_some() {
return Err(format!(
"duplicate case-insensitive Agent Plugins environment variable `{name}`"
));
}
}
env = normalized_env;
}
let root_path = absolute_plugin_path(plugin_root)?;
let data_root_path = absolute_plugin_path(plugin_data_root)?;
let root = host_path_string(&root_path);
let data_root = host_path_string(&data_root_path);
if command.starts_with("./") {
command = host_path_string(&resolve_contained_host_path(
&command, &root_path, &root_path,
)?);
}
for arg in &mut args {
*arg = expand_agent_plugin_placeholders(arg, &root, &data_root);
}
for value in env.values_mut() {
*value = expand_agent_plugin_placeholders(value, &root, &data_root);
}
let cwd = cwd.as_deref().unwrap_or("${PLUGIN_ROOT}");
let Some(cwd_root) = parse_agent_plugin_cwd(cwd) else {
return Err(
"Agent Plugins stdio `cwd` must be a contained `./`, `${PLUGIN_ROOT}`, or `${PLUGIN_DATA}` path"
.to_string(),
);
};
let cwd = expand_agent_plugin_placeholders(cwd, &root, &data_root);
let cwd_root = match cwd_root {
AgentPluginCwdRoot::Package => &root_path,
AgentPluginCwdRoot::Data => &data_root_path,
};
env.insert(PLUGIN_ROOT_VARIABLE.to_string(), root);
env.insert(PLUGIN_DATA_VARIABLE.to_string(), data_root);
Ok(JsonMap::from_iter([
("command".to_string(), JsonValue::String(command)),
(
"args".to_string(),
JsonValue::Array(args.into_iter().map(JsonValue::String).collect()),
),
("env".to_string(), string_map_value(env)),
(
"cwd".to_string(),
JsonValue::String(host_path_string(&resolve_contained_host_path(
&cwd, cwd_root, cwd_root,
)?)),
),
]))
}
fn reject_explicit_null(object: &JsonMap<String, JsonValue>, field: &str) -> Result<(), String> {
if object.get(field).is_some_and(JsonValue::is_null) {
return Err(format!(
"Agent Plugins MCP `{field}` must use its declared type when present"
));
}
Ok(())
}
fn environment_variable_names_match(left: &str, right: &str) -> bool {
if cfg!(windows) {
left.eq_ignore_ascii_case(right)
} else {
left == right
}
}
fn normalize_agent_plugin_http_server(
url: String,
mut headers: Option<BTreeMap<String, String>>,
) -> Result<JsonMap<String, JsonValue>, String> {
validate_agent_plugin_url(&url)?;
if let Some(configured_headers) = headers.as_mut() {
validate_agent_plugin_headers(configured_headers)?;
configured_headers.retain(|name, _| {
!CLIENT_OWNED_HTTP_HEADERS
.iter()
.any(|owned| name.eq_ignore_ascii_case(owned))
});
}
let mut object = JsonMap::from_iter([("url".to_string(), JsonValue::String(url))]);
if let Some(headers) = headers.filter(|headers| !headers.is_empty()) {
object.insert("http_headers".to_string(), string_map_value(headers));
}
Ok(object)
}
fn validate_agent_plugin_url(raw_url: &str) -> Result<(), String> {
if raw_url.is_empty() {
return Err("Agent Plugins HTTP server requires a non-empty `url`".to_string());
}
let parsed = url::Url::parse(raw_url)
.map_err(|err| format!("invalid Agent Plugins MCP URL `{raw_url}`: {err}"))?;
if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
return Err("Agent Plugins MCP URL must be absolute HTTP or HTTPS".to_string());
}
if !parsed.username().is_empty() || parsed.password().is_some() || parsed.fragment().is_some() {
return Err(
"Agent Plugins MCP URL must not contain user information or a fragment".to_string(),
);
}
let is_loopback = match parsed.host() {
Some(Host::Domain(host)) => host == "localhost",
Some(Host::Ipv4(address)) => address.is_loopback(),
Some(Host::Ipv6(address)) => address.is_loopback(),
None => false,
};
if parsed.scheme() == "http" && !is_loopback {
return Err("non-loopback Agent Plugins MCP endpoints must use HTTPS".to_string());
}
Ok(())
}
fn validate_agent_plugin_headers(headers: &BTreeMap<String, String>) -> Result<(), String> {
let mut seen = std::collections::HashSet::new();
for (name, value) in headers {
if !seen.insert(name.to_ascii_lowercase()) {
return Err(format!(
"duplicate case-insensitive Agent Plugins HTTP header `{name}`"
));
}
if !is_valid_http_header_name(name) {
return Err(format!("invalid Agent Plugins HTTP header name `{name}`"));
}
if value
.bytes()
.any(|byte| (byte < 32 && byte != b'\t') || byte == 127)
{
return Err(format!(
"invalid Agent Plugins HTTP header value for `{name}`"
));
}
}
Ok(())
}
fn string_map_value(values: BTreeMap<String, String>) -> JsonValue {
JsonValue::Object(
values
.into_iter()
.map(|(name, value)| (name, JsonValue::String(value)))
.collect(),
)
}
#[derive(Clone, Copy, Debug)]
enum AgentPluginCwdRoot {
Package,
Data,
}
fn parse_agent_plugin_cwd(value: &str) -> Option<AgentPluginCwdRoot> {
if value == "./" {
return Some(AgentPluginCwdRoot::Package);
}
if let Some(relative) = value.strip_prefix("./")
&& is_portable_path_suffix(relative)
{
return Some(AgentPluginCwdRoot::Package);
}
for (placeholder, root) in [
("${PLUGIN_ROOT}", AgentPluginCwdRoot::Package),
("${PLUGIN_DATA}", AgentPluginCwdRoot::Data),
] {
if value == placeholder {
return Some(root);
}
if let Some(relative) = value.strip_prefix(&format!("{placeholder}/"))
&& (relative.is_empty() || is_portable_path_suffix(relative))
{
return Some(root);
}
}
None
}
fn expand_agent_plugin_placeholders(value: &str, plugin_root: &str, plugin_data: &str) -> String {
const ROOT: &str = "${PLUGIN_ROOT}";
const DATA: &str = "${PLUGIN_DATA}";
let mut output = String::with_capacity(value.len());
let mut remaining = value;
loop {
let next = match (remaining.find(ROOT), remaining.find(DATA)) {
(Some(root), Some(data)) if root <= data => Some((root, ROOT, plugin_root)),
(Some(_), Some(data)) => Some((data, DATA, plugin_data)),
(Some(root), None) => Some((root, ROOT, plugin_root)),
(None, Some(data)) => Some((data, DATA, plugin_data)),
(None, None) => None,
};
let Some((index, placeholder, replacement)) = next else {
output.push_str(remaining);
break;
};
output.push_str(&remaining[..index]);
output.push_str(replacement);
remaining = &remaining[index + placeholder.len()..];
}
output
}
fn absolute_plugin_path(path: &Path) -> Result<PathBuf, String> {
let absolute = if path.is_absolute() {
Ok(path.to_path_buf())
} else {
std::env::current_dir()
.map(|cwd| cwd.join(path))
.map_err(|err| format!("failed to resolve plugin path: {err}"))
}?;
resolve_existing_path_prefix(&absolute)
}
fn resolve_contained_host_path(
value: &str,
root: &Path,
allowed_root: &Path,
) -> Result<PathBuf, String> {
let value = Path::new(value);
let path = if value.is_absolute() {
value.to_path_buf()
} else {
root.join(value)
};
let path = resolve_existing_path_prefix(&path)?;
if !path.starts_with(allowed_root) {
return Err(format!(
"expanded path `{}` must remain within `{}`",
value.display(),
allowed_root.display()
));
}
Ok(path)
}
fn resolve_existing_path_prefix(path: &Path) -> Result<PathBuf, String> {
let mut existing = path.to_path_buf();
let mut missing_components = Vec::<OsString>::new();
loop {
match std::fs::canonicalize(&existing) {
Ok(mut resolved) => {
for component in missing_components.iter().rev() {
resolved.push(component);
}
return Ok(lexical_normalize(&resolved));
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
if std::fs::symlink_metadata(&existing)
.is_ok_and(|metadata| metadata.file_type().is_symlink())
{
return Err(format!(
"failed to resolve symlinked path `{}`",
path.display()
));
}
let Some(component) = existing.components().next_back() else {
return Err(format!(
"failed to resolve path `{}`: {err}",
path.display()
));
};
if matches!(
component,
std::path::Component::Prefix(_) | std::path::Component::RootDir
) {
return Err(format!(
"failed to resolve path `{}`: {err}",
path.display()
));
}
missing_components.push(component.as_os_str().to_os_string());
if !existing.pop() {
return Err(format!(
"failed to resolve path `{}`: {err}",
path.display()
));
}
}
Err(err) => {
return Err(format!(
"failed to resolve path `{}`: {err}",
path.display()
));
}
}
}
}
fn host_path_string(path: &Path) -> String {
let rendered = path.to_string_lossy();
#[cfg(windows)]
if let Some(path) = rendered.strip_prefix(r"\\?\") {
return path
.strip_prefix(r"UNC\")
.map(|path| format!(r"\\{path}"))
.unwrap_or_else(|| path.to_string());
}
rendered.into_owned()
}
fn is_portable_relative_path(value: &str) -> bool {
value
.strip_prefix("./")
.is_some_and(is_portable_path_suffix)
}
fn is_portable_path_suffix(value: &str) -> bool {
!value.is_empty() && !value.contains('\\')
}
fn is_valid_http_header_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
}
fn lexical_normalize(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
normalized.pop();
}
component => normalized.push(component.as_os_str()),
}
}
normalized
}
fn plugin_mcp_json_error(message: impl Into<String>) -> serde_json::Error {
serde_json::Error::io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
message.into(),
))
}

View File

@@ -0,0 +1,118 @@
//! Authentication shared by requests on an MCP connection.
use std::sync::Arc;
use codex_api::AuthError;
use codex_api::SharedAuthProvider;
use codex_exec_server::RouteAwareHttpClient;
use codex_features::RuntimeAuthMode;
use codex_http_client::HttpClientFactory;
use codex_login::CodexAuth;
use codex_model_provider::ClientAuth;
use codex_rmcp_client::AuthProviderResolver;
use codex_runtime_agent_instance::RuntimeAuthSlot;
use futures::future::BoxFuture;
use http::HeaderMap;
use tokio::sync::OnceCell;
use crate::McpRuntimeContext;
/// A connection keeps its credential source across retries and reconnects. Initial runtime
/// selection happens inside the startup deadline; each HTTP request then selects fresh auth.
#[derive(Clone)]
pub(crate) enum McpAuthProvider {
Credentials(SharedAuthProvider),
Runtime(Arc<RuntimeMcpAuth>),
}
pub(crate) struct RuntimeMcpAuth {
slot: RuntimeAuthSlot,
mode: RuntimeAuthMode,
auth: CodexAuth,
client_auth: OnceCell<ClientAuth>,
}
struct RuntimeMcpRequestAuth {
auth: ClientAuth,
http_client_factory: HttpClientFactory,
}
impl McpAuthProvider {
pub(crate) fn runtime(
(slot, mode): (RuntimeAuthSlot, RuntimeAuthMode),
auth: CodexAuth,
) -> Self {
Self::Runtime(Arc::new(RuntimeMcpAuth {
slot,
mode,
auth,
client_auth: OnceCell::new(),
}))
}
pub(crate) async fn resolve(
&self,
mut context: McpRuntimeContext,
url: &str,
) -> anyhow::Result<(Arc<dyn AuthProviderResolver>, McpRuntimeContext)> {
match self {
Self::Credentials(provider) => Ok((Arc::new(Arc::clone(provider)), context)),
Self::Runtime(runtime) => {
codex_model_provider::validate_runtime_destination(Some(url))?;
let manager = runtime.slot.get().ok_or_else(|| {
AuthError::Build("runtime authentication is not initialized".to_string())
})?;
let auth = runtime
.client_auth
.get_or_try_init(|| async {
ClientAuth::for_auth(
&runtime.auth,
Some(&(Arc::clone(manager), runtime.mode)),
context.http_client_factory(),
&HeaderMap::new(),
)
.await
.map(|(auth, _)| auth)
})
.await?;
let selected = auth.resolve(&HeaderMap::new()).await?;
let factory = selected.bind_http_client_factory(context.http_client_factory())?;
context.set_local_http_client(Arc::new(
RouteAwareHttpClient::new(factory.clone()).with_tls_backend_fallback(),
));
Ok((
Arc::new(RuntimeMcpRequestAuth {
auth: auth.clone(),
http_client_factory: factory,
}),
context,
))
}
}
}
}
impl AuthProviderResolver for RuntimeMcpRequestAuth {
fn resolve<'a>(
&'a self,
headers: &'a HeaderMap,
) -> BoxFuture<'a, Result<SharedAuthProvider, AuthError>> {
Box::pin(async move {
let selected = self.auth.resolve(headers).await?;
let factory = selected.bind_http_client_factory(self.http_client_factory.clone())?;
// Reuse the connection's transport, including its original account-policy binding.
// A newly selected policy must not revive a connection that was already revoked.
if factory != self.http_client_factory {
return Err(AuthError::Build(
"runtime authentication changed the MCP connection's network policy"
.to_string(),
));
}
Ok(selected.auth)
})
}
}
#[cfg(test)]
#[path = "auth_tests.rs"]
mod tests;

View File

@@ -0,0 +1,62 @@
//! Forwards auth invalidations without credentials. The managed client owns the watcher.
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use codex_login::AuthChangeState;
use codex_rmcp_client::RmcpClient;
use rmcp::model::ServerCapabilities;
use serde_json::json;
use tokio::sync::watch;
use tokio_util::task::AbortOnDropHandle;
pub(crate) const CAPABILITY: &str = "codex/auth-change";
const NOTIFICATION: &str = "notifications/codex/authChanged";
const SEND_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) async fn start(
client: Arc<RmcpClient>,
capabilities: &ServerCapabilities,
changes: Option<watch::Receiver<AuthChangeState>>,
) -> Result<Option<Arc<AbortOnDropHandle<()>>>> {
let Some(mut changes) = changes.filter(|_| {
capabilities
.experimental
.as_ref()
.is_some_and(|capabilities| capabilities.contains_key(CAPABILITY))
}) else {
return Ok(None);
};
notify(&client, &mut changes).await?;
let task = tokio::spawn(async move {
while changes.changed().await.is_ok() {
if notify(&client, &mut changes).await.is_err() {
tracing::warn!("MCP auth invalidation delivery failed; closing connection");
client.shutdown().await;
break;
}
}
});
Ok(Some(Arc::new(AbortOnDropHandle::new(task))))
}
async fn notify(client: &RmcpClient, changes: &mut watch::Receiver<AuthChangeState>) -> Result<()> {
let state = *changes.borrow_and_update();
tokio::time::timeout(
SEND_TIMEOUT,
client.send_custom_notification(
NOTIFICATION,
Some(json!({
"generation": state.generation,
"ownerGeneration": state.owner_generation,
})),
),
)
.await?
}
#[cfg(test)]
#[path = "auth_changes_tests.rs"]
mod tests;

View File

@@ -0,0 +1,104 @@
use super::*;
use codex_rmcp_client::InProcessTransportFactory;
use futures::FutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use rmcp::ServiceExt;
use rmcp::model::ClientCapabilities;
use rmcp::model::CustomNotification;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use tokio::sync::mpsc;
use tokio::time::timeout;
#[derive(Clone)]
struct NotificationServer(mpsc::Sender<serde_json::Value>);
impl rmcp::ServerHandler for NotificationServer {
async fn on_custom_notification(
&self,
notification: CustomNotification,
_context: rmcp::service::NotificationContext<rmcp::RoleServer>,
) {
self.0.send(json!(notification)).await.unwrap();
}
}
impl InProcessTransportFactory for NotificationServer {
fn open(&self) -> BoxFuture<'static, std::io::Result<tokio::io::DuplexStream>> {
let server = self.clone();
async move {
let (client, transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
tokio::spawn(async move {
let service = server.serve(transport).await.unwrap();
service.waiting().await.unwrap();
});
Ok(client)
}
.boxed()
}
}
#[tokio::test]
async fn auth_notifications_require_opt_in_and_follow_client_lifetime() -> Result<()> {
let (notifications, mut received) = mpsc::channel(/*buffer*/ 8);
let client = Arc::new(
RmcpClient::new_in_process_client(Arc::new(NotificationServer(notifications))).await?,
);
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("test", "1"),
),
Some(SEND_TIMEOUT),
Box::new(|_, _| async { anyhow::bail!("unexpected elicitation") }.boxed()),
)
.await?;
let (changes, receiver) = watch::channel(AuthChangeState::default());
let mut capabilities = ServerCapabilities::default();
assert!(
start(Arc::clone(&client), &capabilities, Some(receiver.clone()))
.await?
.is_none()
);
capabilities.experimental = Some([(CAPABILITY.to_string(), Default::default())].into());
assert!(
start(Arc::clone(&client), &capabilities, /*changes*/ None)
.await?
.is_none()
);
assert_eq!(received.try_recv(), Err(mpsc::error::TryRecvError::Empty));
let watcher = start(Arc::clone(&client), &capabilities, Some(receiver))
.await?
.unwrap();
assert_eq!(
timeout(SEND_TIMEOUT, received.recv()).await?,
Some(
json!({"method": NOTIFICATION, "params": {"_meta": {}, "generation": 0, "ownerGeneration": 0}})
),
);
changes.send_modify(|state| state.generation += 1);
assert_eq!(
timeout(SEND_TIMEOUT, received.recv()).await?,
Some(
json!({"method": NOTIFICATION, "params": {"_meta": {}, "generation": 1, "ownerGeneration": 0}})
),
);
for _ in 0..2 {
changes.send_modify(|state| {
state.generation += 1;
state.owner_generation += 1;
});
}
assert_eq!(
timeout(SEND_TIMEOUT, received.recv()).await?,
Some(
json!({"method": NOTIFICATION, "params": {"_meta": {}, "generation": 3, "ownerGeneration": 2}})
),
);
drop(watcher);
timeout(SEND_TIMEOUT, changes.closed()).await?;
client.shutdown().await;
Ok(())
}

View File

@@ -0,0 +1,435 @@
//! Auth elicitation helpers.
//!
//! This module owns protocol-neutral auth elicitation parsing and payload shaping.
//! Session orchestration stays in `codex-core`.
use codex_protocol::mcp::CallToolResult;
use serde::Serialize;
pub const MCP_TOOL_CODEX_APPS_META_KEY: &str = "_codex_apps";
pub const CONNECTOR_AUTH_FAILURE_META_KEY: &str = "connector_auth_failure";
pub const CONNECTOR_AUTH_FAILURE_IS_AUTH_FAILURE_KEY: &str = "is_auth_failure";
pub const CONNECTOR_AUTH_FAILURE_AUTH_REASON_KEY: &str = "auth_reason";
pub const CONNECTOR_AUTH_FAILURE_CONNECTOR_ID_KEY: &str = "connector_id";
pub const CONNECTOR_AUTH_FAILURE_LINK_ID_KEY: &str = "link_id";
pub const CONNECTOR_AUTH_FAILURE_ERROR_CODE_KEY: &str = "error_code";
pub const CONNECTOR_AUTH_FAILURE_ERROR_HTTP_STATUS_CODE_KEY: &str = "error_http_status_code";
pub const CONNECTOR_AUTH_FAILURE_ERROR_ACTION_KEY: &str = "error_action";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodexAppsConnectorAuthFailure {
pub connector_id: String,
pub connector_name: String,
pub install_url: String,
pub auth_reason: Option<String>,
pub link_id: Option<String>,
pub error_code: Option<String>,
pub error_http_status_code: Option<i64>,
pub error_action: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CodexAppsAuthElicitation {
pub meta: serde_json::Value,
pub message: String,
pub url: String,
pub elicitation_id: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CodexAppsAuthElicitationPlan {
pub auth_failure: CodexAppsConnectorAuthFailure,
pub elicitation: CodexAppsAuthElicitation,
}
#[derive(Serialize)]
struct CodexAppsConnectorAuthFailureMeta<'a> {
is_auth_failure: bool,
connector_id: &'a str,
connector_name: &'a str,
install_url: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
auth_reason: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
link_id: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
error_code: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
error_http_status_code: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
error_action: Option<&'a str>,
}
pub fn connector_auth_failure_from_tool_result(
result: &CallToolResult,
connector_id: Option<&str>,
connector_name: Option<&str>,
install_url: Option<String>,
) -> Option<CodexAppsConnectorAuthFailure> {
let connector_id = connector_id
.map(str::trim)
.filter(|connector_id| !connector_id.is_empty())?;
let auth_failure = connector_auth_failure_metadata(result, connector_id)?;
let connector_name = connector_name
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or(connector_id)
.to_string();
Some(CodexAppsConnectorAuthFailure {
connector_id: connector_id.to_string(),
connector_name,
install_url: install_url?,
auth_reason: string_auth_failure_field(
auth_failure,
CONNECTOR_AUTH_FAILURE_AUTH_REASON_KEY,
),
link_id: string_auth_failure_field(auth_failure, CONNECTOR_AUTH_FAILURE_LINK_ID_KEY),
error_code: string_auth_failure_field(auth_failure, CONNECTOR_AUTH_FAILURE_ERROR_CODE_KEY),
error_http_status_code: auth_failure
.get(CONNECTOR_AUTH_FAILURE_ERROR_HTTP_STATUS_CODE_KEY)
.and_then(serde_json::Value::as_i64),
error_action: string_auth_failure_field(
auth_failure,
CONNECTOR_AUTH_FAILURE_ERROR_ACTION_KEY,
),
})
}
pub fn is_connector_auth_failure_from_tool_result(
result: &CallToolResult,
connector_id: Option<&str>,
) -> bool {
connector_id
.map(str::trim)
.filter(|connector_id| !connector_id.is_empty())
.is_some_and(|connector_id| connector_auth_failure_metadata(result, connector_id).is_some())
}
fn connector_auth_failure_metadata<'a>(
result: &'a CallToolResult,
connector_id: &str,
) -> Option<&'a serde_json::Map<String, serde_json::Value>> {
if result.is_error != Some(true) {
return None;
}
let auth_failure = result
.meta
.as_ref()?
.as_object()?
.get(MCP_TOOL_CODEX_APPS_META_KEY)?
.as_object()?
.get(CONNECTOR_AUTH_FAILURE_META_KEY)?
.as_object()?;
if auth_failure
.get(CONNECTOR_AUTH_FAILURE_IS_AUTH_FAILURE_KEY)
.and_then(serde_json::Value::as_bool)
!= Some(true)
{
return None;
}
if let Some(auth_failure_connector_id) =
string_auth_failure_field(auth_failure, CONNECTOR_AUTH_FAILURE_CONNECTOR_ID_KEY)
&& auth_failure_connector_id != connector_id
{
return None;
}
Some(auth_failure)
}
pub fn build_auth_elicitation_plan(
call_id: &str,
result: &CallToolResult,
connector_id: Option<&str>,
connector_name: Option<&str>,
install_url: Option<String>,
) -> Option<CodexAppsAuthElicitationPlan> {
let auth_failure =
connector_auth_failure_from_tool_result(result, connector_id, connector_name, install_url)?;
let elicitation = build_auth_elicitation(call_id, &auth_failure);
Some(CodexAppsAuthElicitationPlan {
auth_failure,
elicitation,
})
}
pub fn build_auth_elicitation(
call_id: &str,
auth_failure: &CodexAppsConnectorAuthFailure,
) -> CodexAppsAuthElicitation {
CodexAppsAuthElicitation {
meta: serde_json::json!({
MCP_TOOL_CODEX_APPS_META_KEY: {
CONNECTOR_AUTH_FAILURE_META_KEY: CodexAppsConnectorAuthFailureMeta {
is_auth_failure: true,
connector_id: &auth_failure.connector_id,
connector_name: &auth_failure.connector_name,
install_url: &auth_failure.install_url,
auth_reason: auth_failure.auth_reason.as_deref(),
link_id: auth_failure.link_id.as_deref(),
error_code: auth_failure.error_code.as_deref(),
error_http_status_code: auth_failure.error_http_status_code,
error_action: auth_failure.error_action.as_deref(),
},
},
}),
message: auth_elicitation_message(auth_failure),
url: auth_failure.install_url.clone(),
elicitation_id: auth_elicitation_id(call_id),
}
}
pub fn auth_elicitation_completed_result(
auth_failure: &CodexAppsConnectorAuthFailure,
meta: Option<serde_json::Value>,
) -> CallToolResult {
CallToolResult {
content: vec![serde_json::json!({
"type": "text",
"text": format!(
"Authentication for {} was requested and accepted. Retry this tool call now.",
auth_failure.connector_name
),
})],
structured_content: None,
is_error: Some(true),
meta,
}
}
pub fn auth_elicitation_id(call_id: &str) -> String {
format!("codex_apps_auth_{call_id}")
}
fn string_auth_failure_field(
auth_failure: &serde_json::Map<String, serde_json::Value>,
key: &str,
) -> Option<String> {
auth_failure
.get(key)
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToString::to_string)
}
fn auth_elicitation_message(auth_failure: &CodexAppsConnectorAuthFailure) -> String {
match auth_failure.auth_reason.as_deref() {
Some("oauth_upgrade_required") => format!(
"Reconnect {} on ChatGPT to grant the permissions needed for this request.",
auth_failure.connector_name
),
Some("reauthentication_required") => format!(
"Reconnect {} on ChatGPT to restore access for this request.",
auth_failure.connector_name
),
Some("missing_link") => format!(
"Sign in to {} on ChatGPT to use it in Codex.",
auth_failure.connector_name
),
_ => format!(
"Sign in to {} on ChatGPT to continue.",
auth_failure.connector_name
),
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
fn auth_failure_result() -> CallToolResult {
CallToolResult {
content: vec![serde_json::json!({
"type": "text",
"text": "Connector reauthentication required",
})],
structured_content: None,
is_error: Some(true),
meta: Some(serde_json::json!({
MCP_TOOL_CODEX_APPS_META_KEY: {
CONNECTOR_AUTH_FAILURE_META_KEY: {
CONNECTOR_AUTH_FAILURE_IS_AUTH_FAILURE_KEY: true,
CONNECTOR_AUTH_FAILURE_AUTH_REASON_KEY: "reauthentication_required",
CONNECTOR_AUTH_FAILURE_CONNECTOR_ID_KEY: "connector_calendar",
"connector_name": "Untrusted Calendar",
CONNECTOR_AUTH_FAILURE_LINK_ID_KEY: "link_123",
CONNECTOR_AUTH_FAILURE_ERROR_CODE_KEY: "UNAUTHORIZED",
CONNECTOR_AUTH_FAILURE_ERROR_HTTP_STATUS_CODE_KEY: 401,
CONNECTOR_AUTH_FAILURE_ERROR_ACTION_KEY: "TRIGGER_REAUTHENTICATION",
},
},
})),
}
}
#[test]
fn parses_auth_failure_from_trusted_connector_metadata() {
assert_eq!(
connector_auth_failure_from_tool_result(
&auth_failure_result(),
Some("connector_calendar"),
Some("Google Calendar"),
Some("https://chatgpt.com/apps/google-calendar/connector_calendar".to_string()),
),
Some(CodexAppsConnectorAuthFailure {
connector_id: "connector_calendar".to_string(),
connector_name: "Google Calendar".to_string(),
install_url: "https://chatgpt.com/apps/google-calendar/connector_calendar"
.to_string(),
auth_reason: Some("reauthentication_required".to_string()),
link_id: Some("link_123".to_string()),
error_code: Some("UNAUTHORIZED".to_string()),
error_http_status_code: Some(401),
error_action: Some("TRIGGER_REAUTHENTICATION".to_string()),
})
);
}
#[test]
fn rejects_missing_or_mismatched_connector_ids() {
assert_eq!(
connector_auth_failure_from_tool_result(
&auth_failure_result(),
/*connector_id*/ None,
Some("Google Calendar"),
Some("https://chatgpt.com/apps/google-calendar/connector_calendar".to_string()),
),
None
);
assert_eq!(
connector_auth_failure_from_tool_result(
&auth_failure_result(),
Some("connector_drive"),
Some("Google Drive"),
Some("https://chatgpt.com/apps/google-drive/connector_drive".to_string()),
),
None
);
}
#[test]
fn detects_auth_failure_without_an_install_url() {
let result = auth_failure_result();
assert_eq!(
is_connector_auth_failure_from_tool_result(&result, Some("connector_calendar")),
true
);
assert_eq!(
connector_auth_failure_from_tool_result(
&result,
Some("connector_calendar"),
Some("Google Calendar"),
/*install_url*/ None,
),
None
);
}
#[test]
fn auth_failure_detection_requires_trusted_connector_identity_and_auth_flag() {
let result = auth_failure_result();
assert_eq!(
is_connector_auth_failure_from_tool_result(&result, /*connector_id*/ None),
false
);
assert_eq!(
is_connector_auth_failure_from_tool_result(&result, Some("connector_drive")),
false
);
let mut ordinary_error = result.clone();
ordinary_error.meta.as_mut().expect("auth metadata")[MCP_TOOL_CODEX_APPS_META_KEY]
[CONNECTOR_AUTH_FAILURE_META_KEY][CONNECTOR_AUTH_FAILURE_IS_AUTH_FAILURE_KEY] =
serde_json::Value::Bool(false);
assert_eq!(
is_connector_auth_failure_from_tool_result(&ordinary_error, Some("connector_calendar"),),
false
);
let mut successful_result = result;
successful_result.is_error = Some(false);
assert_eq!(
is_connector_auth_failure_from_tool_result(
&successful_result,
Some("connector_calendar"),
),
false
);
}
#[test]
fn detects_each_supported_connector_auth_reason() {
for auth_reason in [
"missing_link",
"oauth_upgrade_required",
"reauthentication_required",
] {
let mut result = auth_failure_result();
result.meta.as_mut().expect("auth metadata")[MCP_TOOL_CODEX_APPS_META_KEY]
[CONNECTOR_AUTH_FAILURE_META_KEY][CONNECTOR_AUTH_FAILURE_AUTH_REASON_KEY] =
serde_json::Value::String(auth_reason.to_string());
assert_eq!(
is_connector_auth_failure_from_tool_result(&result, Some("connector_calendar")),
true
);
}
}
#[test]
fn builds_url_elicitation_payload() {
let auth_failure = connector_auth_failure_from_tool_result(
&auth_failure_result(),
Some("connector_calendar"),
Some("Google Calendar"),
Some("https://chatgpt.com/apps/google-calendar/connector_calendar".to_string()),
)
.expect("auth failure");
assert_eq!(
build_auth_elicitation("call_123", &auth_failure),
CodexAppsAuthElicitation {
meta: serde_json::json!({
MCP_TOOL_CODEX_APPS_META_KEY: {
CONNECTOR_AUTH_FAILURE_META_KEY: {
CONNECTOR_AUTH_FAILURE_IS_AUTH_FAILURE_KEY: true,
CONNECTOR_AUTH_FAILURE_CONNECTOR_ID_KEY: "connector_calendar",
"connector_name": "Google Calendar",
"install_url":
"https://chatgpt.com/apps/google-calendar/connector_calendar",
CONNECTOR_AUTH_FAILURE_AUTH_REASON_KEY: "reauthentication_required",
CONNECTOR_AUTH_FAILURE_LINK_ID_KEY: "link_123",
CONNECTOR_AUTH_FAILURE_ERROR_CODE_KEY: "UNAUTHORIZED",
CONNECTOR_AUTH_FAILURE_ERROR_HTTP_STATUS_CODE_KEY: 401,
CONNECTOR_AUTH_FAILURE_ERROR_ACTION_KEY: "TRIGGER_REAUTHENTICATION",
},
},
}),
message: "Reconnect Google Calendar on ChatGPT to restore access for this request."
.to_string(),
url: "https://chatgpt.com/apps/google-calendar/connector_calendar".to_string(),
elicitation_id: "codex_apps_auth_call_123".to_string(),
}
);
}
#[test]
fn builds_auth_elicitation_plan() {
let plan = build_auth_elicitation_plan(
"call_123",
&auth_failure_result(),
Some("connector_calendar"),
Some("Google Calendar"),
Some("https://chatgpt.com/apps/google-calendar/connector_calendar".to_string()),
)
.expect("auth elicitation plan");
assert_eq!(plan.auth_failure.connector_name, "Google Calendar");
assert_eq!(plan.elicitation.elicitation_id, "codex_apps_auth_call_123");
}
}

View File

@@ -0,0 +1,203 @@
use super::*;
use base64::Engine;
use codex_config::types::AuthKeyringBackendKind;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_features::RuntimeAuthMode;
use codex_http_client::DestinationPolicy;
use codex_http_client::HttpClientFactory;
use codex_http_client::NetworkPolicyController;
use codex_http_client::OutboundProxyPolicy;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthManager;
use codex_login::AuthRouteConfig;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::path;
struct RotatingAuth(std::sync::RwLock<CodexAuth>);
impl codex_login::ExternalAuth for RotatingAuth {
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async { Ok(self.0.read().unwrap().clone()) })
}
fn refresh(
&self,
_: codex_login::ExternalAuthRefreshContext,
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
self.resolve()
}
}
#[tokio::test]
async fn deferred_connection_keeps_runtime_source_and_captured_account_policy() -> anyhow::Result<()>
{
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
Mock::given(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-mcp", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"},
})))
.mount(&server)
.await;
Mock::given(path("/mcp"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.await;
let home = tempfile::tempdir()?;
let oauth = |session, token| {
let claims = json!({
"iss": "https://auth.openai.com/", "session_id": session, "jti": token,
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "workspace-a"}
});
let payload =
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string());
CodexAuth::from_external_chatgpt_tokens(
&format!("header.{payload}.signature"),
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap()
};
let initial = oauth("session-a", "initial");
let refreshed = oauth("session-a", "refreshed");
let source = Arc::new(RotatingAuth(std::sync::RwLock::new(initial.clone())));
let controller = NetworkPolicyController::default();
let policy = controller.policy();
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy.clone());
let credentials = Arc::new(
AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::Ephemeral,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::Direct,
AuthRouteConfig::from_http_client_factory(factory.clone()),
)
.await,
);
credentials.set_external_auth(source.clone()).await?;
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
let runtime = (
Arc::new(std::sync::OnceLock::from(Arc::new(
RuntimeAuthManager::new(
Arc::clone(&credentials),
AgentHostAuthorization::InstallationId {
installation_id: uuid::Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/agent/register", server.uri()).parse()?,
),
))),
mode,
);
let context = McpRuntimeContext::new(
Arc::new(EnvironmentManager::without_environments(factory)),
home.path().to_path_buf(),
);
let deferred = McpAuthProvider::runtime(runtime.clone(), initial.clone());
assert!(server.received_requests().await.unwrap().is_empty());
let error = deferred
.resolve(context.clone(), "https://future.openai.com/mcp")
.await
.err()
.expect("unsupported OpenAI destination must fail before registration");
assert!(
error
.downcast_ref::<codex_protocol::error::CodexErr>()
.is_some_and(|error| matches!(
error.details(),
codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_)
))
);
assert!(server.received_requests().await.unwrap().is_empty());
let (provider, selected_context) = deferred.resolve(context.clone(), &server.uri()).await?;
let first = provider
.resolve(&Default::default())
.await?
.apply_auth_headers(Default::default())
.await?;
*source.0.write().unwrap() = refreshed.clone();
let second = provider
.resolve(&Default::default())
.await?
.apply_auth_headers(Default::default())
.await?;
let assertion_header = match mode {
RuntimeAuthMode::DualHeader => "x-openai-agent-assertion",
RuntimeAuthMode::AssertionOnly => "authorization",
};
assert_ne!(first[assertion_header], second[assertion_header]);
if mode == RuntimeAuthMode::DualHeader {
assert_eq!(
first["authorization"],
format!("Bearer {}", initial.get_token()?)
);
assert_eq!(
second["authorization"],
format!("Bearer {}", refreshed.get_token()?)
);
}
let request = || HttpRequestParams {
method: "GET".into(),
url: format!("{}/mcp", server.uri()),
headers: Vec::new(),
body: None,
timeout_ms: Some(1000),
redirect_policy: HttpRedirectPolicy::Stop,
request_id: "mcp-policy-test".into(),
stream_response: false,
};
let client = selected_context.local_http_client();
assert_eq!(client.http_request(request()).await?.status, 200);
policy.invalidate();
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
assert!(client.http_request(request()).await.is_err());
// A new connection captures the new policy and reuses the same registered runtime.
let current = McpAuthProvider::runtime(runtime, refreshed);
let (_, current_context) = current.resolve(context, &server.uri()).await?;
assert_eq!(
current_context
.local_http_client()
.http_request(request())
.await?
.status,
200
);
let requests = server.received_requests().await.unwrap();
assert_eq!(
requests
.iter()
.filter(|request| request.url.path() == "/agent/register")
.count(),
1
);
*source.0.write().unwrap() = oauth("another-session", "replacement");
assert!(provider.resolve(&Default::default()).await.is_err());
assert_eq!(
requests
.iter()
.filter(|request| request.url.path() == "/mcp")
.count(),
2
);
}
Ok(())
}

View File

@@ -0,0 +1,536 @@
//! Immutable MCP catalog and execution handles.
#[path = "model_search.rs"]
mod model_search;
pub use model_search::SEARCH_CONNECTOR;
pub use model_search::SearchDiscovery;
pub use model_search::is_model_search_tool;
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use codex_config::AppToolApproval;
use codex_exec_server::FileSystemSandboxContext;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::models::PermissionProfile;
use codex_utils_absolute_path::AbsolutePathBuf;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use rmcp::model::Resource;
use rmcp::model::ResourceTemplate;
use serde_json::Value as JsonValue;
use crate::McpConfig;
use crate::McpServerPermissions;
use crate::binding_clients::McpBindingClients;
use crate::client_tool_catalog::ToolCatalogSnapshot;
use crate::connection_manager::McpConnectionSet;
use crate::rmcp_client::ManagedClient;
use crate::server::McpServerMetadata;
use crate::tools::ToolInfo;
/// The exact tool catalog and execution handles shared by compatible sampling steps.
pub struct McpBinding {
connections: Arc<McpConnectionSet>,
clients: Arc<McpBindingClients>,
config: Arc<McpConfig>,
plugins_available: bool,
tools: Arc<[ToolInfo]>,
calls: HashMap<(String, String), PreparedMcpCall>,
}
impl McpBinding {
/// Creates an empty binding for tests and callers without a materialized runtime.
pub fn empty(config: Arc<McpConfig>) -> Self {
Self::new(
Arc::new(McpConnectionSet::empty(config.prefix_mcp_tool_names)),
Arc::new(McpBindingClients::new(HashMap::new())),
config,
/*plugins_available*/ false,
Vec::new(),
HashMap::new(),
)
}
pub(crate) fn new(
connections: Arc<McpConnectionSet>,
clients: Arc<McpBindingClients>,
config: Arc<McpConfig>,
plugins_available: bool,
tools: impl Into<Arc<[ToolInfo]>>,
calls: HashMap<(String, String), PreparedMcpCall>,
) -> Self {
Self {
connections,
clients,
config,
plugins_available,
tools: tools.into(),
calls,
}
}
pub fn config(&self) -> &Arc<McpConfig> {
&self.config
}
pub fn plugins_available(&self) -> bool {
self.plugins_available
}
/// Returns the frozen model-visible catalog captured for this binding.
pub fn tools(&self) -> &[ToolInfo] {
&self.tools
}
/// Returns permitted tool metadata, including app-only tools.
pub fn tool_info(&self, server: &str, tool: &str) -> Option<&ToolInfo> {
self.calls
.get(&(server.to_string(), tool.to_string()))
.map(PreparedMcpCall::tool_info)
}
/// Binds a model-visible call to the exact client and metadata in this binding.
pub fn prepare_call(&self, server: &str, tool: &str) -> Option<PreparedMcpCall> {
self.calls
.get(&(server.to_string(), tool.to_string()))
.filter(|call| crate::tool_is_model_visible(call.tool_info()))
.cloned()
}
pub fn has_servers(&self) -> bool {
self.connections.has_servers()
}
/// The environment owning this server in the step's connection set, even if it exposes no tools.
pub fn server_environment_id(&self, server: &str) -> Option<&str> {
self.connections.server_environment_id(server)
}
pub async fn list_resources(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourcesResult> {
if self.clients.client(server).is_some() {
self.clients.list_resources(server, params).await
} else {
self.connections.list_resources(server, params).await
}
}
pub async fn list_all_resources(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<Resource>> {
self.clients.list_all_resources(include_server).await
}
pub async fn list_resource_templates(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourceTemplatesResult> {
if self.connections.skips_resource_template_listing(server) {
return Ok(ListResourceTemplatesResult::with_all_items(Vec::new()));
}
if self.clients.client(server).is_some() {
self.clients.list_resource_templates(server, params).await
} else {
self.connections
.list_resource_templates(server, params)
.await
}
}
pub async fn list_all_resource_templates(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<ResourceTemplate>> {
self.clients
.list_all_resource_templates(|server| {
include_server(server) && !self.connections.skips_resource_template_listing(server)
})
.await
}
pub async fn read_resource(
&self,
server: &str,
params: ReadResourceRequestParams,
) -> Result<ReadResourceResult> {
if self.clients.client(server).is_some() {
self.clients.read_resource(server, params).await
} else {
self.connections.read_resource(server, params).await
}
}
}
impl fmt::Debug for McpBinding {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("McpBinding")
.field("tools", &self.tools)
.field("prepared_call_count", &self.calls.len())
.finish_non_exhaustive()
}
}
/// A call bound to an exact client, catalog revision, timeout, and permission authority.
#[derive(Clone)]
pub struct PreparedMcpCall {
connections: Arc<McpConnectionSet>,
client: Arc<ManagedClient>,
config: Arc<McpConfig>,
catalog_snapshot: Arc<ToolCatalogSnapshot>,
tool_info: PreparedToolInfo,
server_name: String,
server_metadata: McpServerMetadata,
plugin_id: Option<String>,
selected_plugin_server: bool,
}
/// The rules for a prepared call and the folders used to interpret them.
pub enum McpPermissionSource<'a> {
Environment {
environment_id: &'a str,
sandbox: &'a Arc<FileSystemSandboxContext>,
},
Thread {
profile: &'a PermissionProfile,
host_cwd: &'a AbsolutePathBuf,
},
}
impl<'a> McpPermissionSource<'a> {
pub fn profile(&self) -> &'a PermissionProfile {
match self {
Self::Environment { sandbox, .. } => &sandbox.permissions,
Self::Thread { profile, .. } => profile,
}
}
}
#[derive(Clone)]
pub(crate) struct PreparedToolInfo {
catalog: Arc<[ToolInfo]>,
index: usize,
}
impl PreparedToolInfo {
pub(crate) fn from_binding_catalog(catalog: Arc<[ToolInfo]>, index: usize) -> Self {
assert!(
index < catalog.len(),
"prepared tool index must refer to its binding catalog"
);
Self { catalog, index }
}
pub(crate) fn get(&self) -> &ToolInfo {
&self.catalog[self.index]
}
}
impl From<ToolInfo> for PreparedToolInfo {
fn from(tool_info: ToolInfo) -> Self {
Self {
catalog: Arc::new([tool_info]),
index: 0,
}
}
}
impl PreparedMcpCall {
#[expect(
clippy::too_many_arguments,
reason = "the exact call authority stays together"
)]
pub(crate) fn new(
connections: Arc<McpConnectionSet>,
client: Arc<ManagedClient>,
config: Arc<McpConfig>,
catalog_snapshot: Arc<ToolCatalogSnapshot>,
tool_info: impl Into<PreparedToolInfo>,
server_metadata: McpServerMetadata,
plugin_id: Option<String>,
selected_plugin_server: bool,
) -> Option<Self> {
let tool_info = tool_info.into();
let server_name = tool_info.get().server_name.clone();
config.permission_profile_for_server(&server_name)?;
Some(Self {
connections,
client,
config,
catalog_snapshot,
tool_info,
server_name,
server_metadata,
plugin_id,
selected_plugin_server,
})
}
pub fn tool_info(&self) -> &ToolInfo {
self.tool_info.get()
}
/// Whether the server connection that issued the step's tools still owns this call.
pub fn uses_connection_from(&self, binding: &McpBinding) -> bool {
self.connections
.shares_server_connection(&binding.connections, &self.server_name)
}
/// Returns the configuration and approval authority captured with this client.
pub fn config(&self) -> &McpConfig {
&self.config
}
/// A hosted app can run through the local server but use thread rules, not local environment rules.
pub fn permission_source(&self) -> McpPermissionSource<'_> {
// The constructor only prepares calls with an entry in this immutable config.
match &self.config.server_permissions[&self.server_name] {
McpServerPermissions::Environment(sandbox) => McpPermissionSource::Environment {
environment_id: self.server_environment_id(),
sandbox,
},
McpServerPermissions::Thread => McpPermissionSource::Thread {
profile: &self.config.permission_profile,
host_cwd: &self.config.host_cwd,
},
}
}
/// Returns the owner permissions validated when this immutable call was prepared.
pub fn permission_profile(&self) -> &PermissionProfile {
self.permission_source().profile()
}
/// Attach policy aliases and the server-host launcher, replacing stale authority.
/// Callers negotiate the state capability before requesting this metadata.
pub async fn augment_sandbox_metadata(
&self,
meta: &mut Option<JsonValue>,
state: crate::SandboxState,
) -> Result<()> {
crate::sandbox_metadata::augment_metadata(
meta,
state,
self.sandbox_codex_executable().await,
)
}
/// Full CLI path usable by a local stdio server. An HTTP endpoint (even on
/// loopback) or remote executor does not establish a shared filesystem.
/// Capability probes are cached process-wide by absolute executable path.
pub async fn sandbox_codex_executable(&self) -> Option<AbsolutePathBuf> {
let server = self
.config
.mcp_server_catalog
.server(&self.server_name)?
.config();
if self.server_environment_id() != codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID
|| !server.is_local_environment()
|| !matches!(
server.transport,
codex_config::McpServerTransportConfig::Stdio { .. }
)
{
return None;
}
// Require a literal absolute path before the constructor can expand `~`.
let executable = self
.config
.codex_self_exe
.as_deref()
.filter(|path| path.is_absolute() && path.to_str().is_some())?;
let executable = AbsolutePathBuf::from_absolute_path_checked(executable).ok()?;
crate::sandbox_executable::supports_sandbox_state(&executable)
.await
.then_some(executable)
}
pub fn server_name(&self) -> &str {
&self.server_name
}
/// Returns whether this call is bound to the host-owned Codex Apps server.
pub fn is_host_owned_apps(&self) -> bool {
self.config
.mcp_server_catalog
.server(&self.server_name)
.is_some_and(|registration| {
registration
.source()
.is_host_owned_apps(&self.server_name, registration.config())
})
}
pub fn server_origin(&self) -> Option<&str> {
self.server_metadata
.origin
.as_ref()
.map(super::server::McpServerOrigin::as_str)
}
pub fn server_environment_id(&self) -> &str {
&self.server_metadata.environment_id
}
pub fn server_pollutes_memory(&self) -> bool {
self.server_metadata.pollutes_memory
}
pub fn tool_approval_mode(&self) -> AppToolApproval {
self.server_metadata
.tool_approval_mode(&self.tool_info().tool.name)
}
/// Returns the explicit output budget captured with this call's effective server config.
pub fn output_token_limit(&self) -> Option<usize> {
self.config
.mcp_server_catalog
.server(&self.server_name)?
.config()
.tools
.get(self.tool_info().tool.name.as_ref())?
.output_token_limit
.map(std::num::NonZeroUsize::get)
}
pub fn plugin_id(&self) -> Option<&str> {
self.plugin_id.as_deref()
}
pub fn is_selected_plugin_server(&self) -> bool {
self.selected_plugin_server
}
pub async fn server_supports_sandbox_state_meta_capability(&self) -> Result<bool> {
Ok(self.client.server_supports_sandbox_state_meta_capability)
}
pub async fn call(
&self,
arguments: Option<JsonValue>,
meta: Option<JsonValue>,
timeout: Option<Duration>,
) -> Result<CallToolResult> {
self.call_with_preparation(timeout, || async move { Ok((arguments, meta)) })
.await
}
/// Runs irreversible call preparation and execution under the authority of
/// this call's captured catalog and the extensions owned by the Codex session.
/// A caller-supplied timeout can further restrict the server's configured timeout.
pub async fn call_with_preparation<F, Fut>(
&self,
requested_timeout: Option<Duration>,
prepare: F,
) -> Result<CallToolResult>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<(Option<JsonValue>, Option<JsonValue>)>>,
{
let effective_timeout = match (self.client.tool_timeout, requested_timeout) {
(Some(server_timeout), Some(requested_timeout)) => {
Some(server_timeout.min(requested_timeout))
}
(server_timeout, requested_timeout) => server_timeout.or(requested_timeout),
};
let tool_name = self.tool_info().tool.name.to_string();
let operation =
self.client
.tool_catalog
.run_with_snapshot(&self.catalog_snapshot, || async {
let (arguments, meta) = prepare().await?;
let timeout_deadline =
effective_timeout.map(|timeout| tokio::time::Instant::now() + timeout);
let add_trusted_access_context = self.connections.add_trusted_access_context(
self.tool_info(),
&self.server_metadata,
arguments.as_ref(),
meta,
);
let meta = match effective_timeout.zip(timeout_deadline) {
Some((timeout, deadline)) => {
tokio::time::timeout_at(deadline, add_trusted_access_context)
.await
.map_err(|_| {
codex_rmcp_client::request_timeout_error("tools/call", timeout)
})?
}
None => add_trusted_access_context.await,
};
let remaining_timeout = match effective_timeout.zip(timeout_deadline) {
Some((timeout, deadline)) => {
let remaining =
deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
return Err(codex_rmcp_client::request_timeout_error(
"tools/call",
timeout,
));
}
Some(remaining)
}
None => None,
};
self.client
.call_tool(
tool_name.clone(),
arguments,
self.connections.network_policy_meta_for_call(
&self.client,
Some(self.permission_profile()),
self.server_environment_id(),
meta,
),
remaining_timeout,
)
.await
.with_context(|| {
format!("tool call failed for `{}/{tool_name}`", self.server_name)
})
});
self.client
.with_active_shared_lease(operation)
.await?
.ok_or_else(|| anyhow::anyhow!(
"tool call rejected because the catalog changed after `{}/{tool_name}` was prepared",
self.server_name
))?
.map(call_tool_result_from_rmcp)
}
}
pub(crate) fn call_tool_result_from_rmcp(result: rmcp::model::CallToolResult) -> CallToolResult {
let content = result
.content
.into_iter()
.map(|content| {
serde_json::to_value(content)
.unwrap_or_else(|_| JsonValue::String("<content>".to_string()))
})
.collect();
CallToolResult {
content,
structured_content: result.structured_content,
is_error: result.is_error,
meta: result.meta.and_then(|meta| serde_json::to_value(meta).ok()),
}
}
#[cfg(test)]
#[path = "binding_tests.rs"]
mod tests;

View File

@@ -0,0 +1,153 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use rmcp::model::Resource;
use rmcp::model::ResourceTemplate;
use tokio::task::JoinSet;
use tracing::warn;
use crate::pagination::collect_paginated;
use crate::rmcp_client::ManagedClient;
/// The ready clients captured for one model step.
pub(crate) struct McpBindingClients {
clients: HashMap<String, Arc<ManagedClient>>,
}
impl McpBindingClients {
pub(crate) fn new(clients: HashMap<String, Arc<ManagedClient>>) -> Self {
Self { clients }
}
pub(crate) fn client(&self, server: &str) -> Option<Arc<ManagedClient>> {
self.clients.get(server).cloned()
}
pub(crate) async fn list_resources(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourcesResult> {
let managed = self
.client(server)
.ok_or_else(|| anyhow!("MCP server '{server}' was not ready for this step"))?;
managed
.list_resources(params, managed.tool_timeout)
.await
.with_context(|| format!("resources/list failed for `{server}`"))
}
pub(crate) async fn list_resource_templates(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourceTemplatesResult> {
let managed = self
.client(server)
.ok_or_else(|| anyhow!("MCP server '{server}' was not ready for this step"))?;
managed
.list_resource_templates(params, managed.tool_timeout)
.await
.with_context(|| format!("resources/templates/list failed for `{server}`"))
}
pub(crate) async fn read_resource(
&self,
server: &str,
params: ReadResourceRequestParams,
) -> Result<ReadResourceResult> {
let managed = self
.client(server)
.ok_or_else(|| anyhow!("MCP server '{server}' was not ready for this step"))?;
let uri = params.uri.clone();
managed
.read_resource(params, managed.tool_timeout)
.await
.with_context(|| format!("resources/read failed for `{server}` ({uri})"))
}
pub(crate) async fn list_all_resources(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<Resource>> {
let mut join_set = JoinSet::new();
for (server_name, managed) in self
.clients
.iter()
.filter(|(server_name, _)| include_server(server_name))
{
let server_name = server_name.clone();
let client = Arc::clone(managed);
let timeout = managed.tool_timeout;
join_set.spawn(async move {
let resources = collect_paginated("resources/list", timeout, |params| {
let client = Arc::clone(&client);
async move {
let response = client.list_resources(params, timeout).await?;
Ok((response.resources, response.next_cursor))
}
})
.await;
(server_name, resources)
});
}
collect_resource_results(&mut join_set, "resources").await
}
pub(crate) async fn list_all_resource_templates(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<ResourceTemplate>> {
let mut join_set = JoinSet::new();
for (server_name, managed) in self
.clients
.iter()
.filter(|(server_name, _)| include_server(server_name))
{
let server_name = server_name.clone();
let client = Arc::clone(managed);
let timeout = managed.tool_timeout;
join_set.spawn(async move {
let templates = collect_paginated("resources/templates/list", timeout, |params| {
let client = Arc::clone(&client);
async move {
let response = client.list_resource_templates(params, timeout).await?;
Ok((response.resource_templates, response.next_cursor))
}
})
.await;
(server_name, templates)
});
}
collect_resource_results(&mut join_set, "resource templates").await
}
}
async fn collect_resource_results<T: Send + 'static>(
join_set: &mut JoinSet<(String, Result<Vec<T>>)>,
kind: &str,
) -> HashMap<String, Vec<T>> {
let mut resources = HashMap::new();
while let Some(result) = join_set.join_next().await {
match result {
Ok((server, Ok(server_resources))) => {
resources.insert(server, server_resources);
}
Ok((server, Err(error))) => {
warn!("Failed to list {kind} for MCP server '{server}': {error:#}");
}
Err(error) => {
warn!("Task panic when listing {kind} for MCP server: {error:#}");
}
}
}
resources
}

View File

@@ -0,0 +1,563 @@
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use codex_config::AppToolApproval;
use codex_config::Constrained;
use codex_config::types::ApprovalsReviewer;
use codex_exec_server::FileSystemSandboxContext;
use codex_protocol::mcp::McpServerInfo;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_rmcp_client::InProcessTransportFactory;
use codex_rmcp_client::RmcpClient;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use rmcp::model::JsonObject;
use rmcp::model::Tool;
use tokio::io::DuplexStream;
use tokio::sync::Notify;
use super::McpBinding;
use super::McpPermissionSource;
use super::PreparedMcpCall;
use crate::McpServerPermissions;
use crate::binding_clients::McpBindingClients;
use crate::client_tool_catalog::ClientToolCatalog;
use crate::connection_manager::McpConnectionSet;
use crate::rmcp_client::ManagedClient;
use crate::server::McpServerMetadata;
use crate::server::McpServerOrigin;
use crate::tools::ToolInfo;
const SERVER_NAME: &str = "docs";
const TOOL_NAME: &str = "search";
struct TestInProcessTransportFactory;
impl InProcessTransportFactory for TestInProcessTransportFactory {
fn open(&self) -> futures::future::BoxFuture<'static, io::Result<DuplexStream>> {
async {
let (client_stream, _server_stream) = tokio::io::duplex(1);
Ok(client_stream)
}
.boxed()
}
}
struct TestStep {
step: Arc<McpBinding>,
client: Arc<RmcpClient>,
tool_catalog: Arc<ClientToolCatalog>,
}
async fn test_step(
label: &str,
approval_mode: AppToolApproval,
supports_sandbox_state_meta: bool,
) -> TestStep {
let tool = ToolInfo {
server_name: SERVER_NAME.to_string(),
supports_parallel_tool_calls: false,
server_origin: None,
callable_name: TOOL_NAME.to_string(),
callable_namespace: SERVER_NAME.to_string(),
namespace_description: None,
tool: Tool::new(
TOOL_NAME.to_string(),
format!("{label} catalog"),
Arc::new(JsonObject::default()),
),
openai_file_input_optional_fields: Default::default(),
connector_id: None,
connector_name: None,
plugin_display_names: Vec::new(),
};
let client = Arc::new(
RmcpClient::new_in_process_client(Arc::new(TestInProcessTransportFactory))
.await
.expect("create in-process MCP client"),
);
let tool_catalog = Arc::new(ClientToolCatalog::new(
vec![tool.clone()],
/*meta*/ None,
/*updates*/ None,
));
let managed_client = Arc::new(ManagedClient {
connection_sharing: Default::default(),
shared_elicitation: None,
_auth_change_notifications: None,
client: Arc::clone(&client),
server_info: McpServerInfo {
name: label.to_string(),
title: Some(format!("{label} server")),
version: "1.0.0".to_string(),
description: None,
icons: None,
website_url: None,
},
tool_catalog: Arc::clone(&tool_catalog),
tool_timeout: None,
server_instructions: None,
server_supports_sandbox_state_meta_capability: supports_sandbox_state_meta,
client_supports_network_policy_meta_capability: false,
codex_apps_tools_cache_context: None,
});
let clients = Arc::new(McpBindingClients::new(HashMap::from([(
SERVER_NAME.to_string(),
Arc::clone(&managed_client),
)])));
let connections = Arc::new(McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true));
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
config.host_cwd = config.host_cwd.join(label);
config.environment_cwds.insert(
codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
codex_utils_path_uri::PathUri::from_abs_path(&config.host_cwd.join("executor")),
);
let server_permissions = if label == "old" {
config.approval_policy = Constrained::allow_any(AskForApproval::Never);
config.permission_profile = PermissionProfile::Disabled;
let mut sandbox = FileSystemSandboxContext::from_permission_profile(
PermissionProfile::read_only(),
PathUri::from_abs_path(&config.host_cwd.join("executor")),
);
sandbox.user_home_dir = Some(PathUri::from_abs_path(&config.host_cwd.join("home")));
sandbox.temporary_directories =
Some(vec![PathUri::from_abs_path(&config.host_cwd.join("tmp"))]);
McpServerPermissions::Environment(Arc::new(sandbox))
} else {
config.approvals_reviewer = ApprovalsReviewer::AutoReview;
McpServerPermissions::Thread
};
config
.server_permissions
.insert(SERVER_NAME.to_string(), server_permissions);
config
.environment_use_mxc
.insert(format!("{label}-environment"), label == "new");
let config = Arc::new(config);
let prepared = PreparedMcpCall::new(
Arc::clone(&connections),
managed_client,
Arc::clone(&config),
tool_catalog.read(Arc::new).await,
tool.clone(),
McpServerMetadata {
environment_id: format!("{label}-environment"),
pollutes_memory: label == "old",
origin: Some(McpServerOrigin::StreamableHttp(format!(
"https://{label}.example"
))),
supports_parallel_tool_calls: false,
default_tools_approval_mode: Some(approval_mode),
tool_approval_modes: HashMap::new(),
},
Some(format!("{label}-plugin")),
label == "old",
)
.expect("test call should have a permission source");
let calls = HashMap::from([((SERVER_NAME.to_string(), TOOL_NAME.to_string()), prepared)]);
TestStep {
step: Arc::new(McpBinding::new(
connections,
clients,
config,
/*plugins_available*/ false,
vec![tool],
calls,
)),
client,
tool_catalog,
}
}
#[tokio::test]
async fn prepared_call_keeps_captured_connection_and_authority_after_refresh() -> anyhow::Result<()>
{
let old = test_step(
"old",
AppToolApproval::Prompt,
/*supports_sandbox_state_meta*/ true,
)
.await;
let old_call = old
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("old step should prepare the advertised tool");
let old_connections = Arc::downgrade(&old.step.connections);
let new = test_step(
"new",
AppToolApproval::Approve,
/*supports_sandbox_state_meta*/ false,
)
.await;
let new_call = new
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("new step should prepare the advertised tool");
assert_eq!(
(
old.step.tools()[0].tool.description.as_deref(),
old_call.tool_info().tool.description.as_deref(),
old_call.server_origin(),
old_call.server_environment_id(),
old_call.server_pollutes_memory(),
old_call.tool_approval_mode(),
old_call.plugin_id(),
old_call.is_selected_plugin_server(),
old_call
.server_supports_sandbox_state_meta_capability()
.await?,
),
(
Some("old catalog"),
Some("old catalog"),
Some("https://old.example"),
"old-environment",
true,
AppToolApproval::Prompt,
Some("old-plugin"),
true,
true,
)
);
assert_eq!(
(
new.step.tools()[0].tool.description.as_deref(),
new_call.tool_info().tool.description.as_deref(),
new_call.server_environment_id(),
new_call.tool_approval_mode(),
),
(
Some("new catalog"),
Some("new catalog"),
"new-environment",
AppToolApproval::Approve,
)
);
assert!(Arc::ptr_eq(&old_call.client.client, &old.client));
assert!(!Arc::ptr_eq(&old.client, &new.client));
let McpPermissionSource::Environment { sandbox, .. } = old_call.permission_source() else {
anyhow::bail!("expected the old call to keep its environment permissions");
};
let old_root = AbsolutePathBuf::current_dir()?.join("old");
assert_eq!(
(
&sandbox.cwd,
&sandbox.user_home_dir,
&sandbox.temporary_directories
),
(
&PathUri::from_abs_path(&old_root.join("executor")),
&Some(PathUri::from_abs_path(&old_root.join("home"))),
&Some(vec![PathUri::from_abs_path(&old_root.join("tmp"))]),
),
);
let McpPermissionSource::Thread { host_cwd, .. } = new_call.permission_source() else {
anyhow::bail!("expected thread permissions");
};
assert_eq!(host_cwd, &AbsolutePathBuf::current_dir()?.join("new"));
assert_eq!(
(
old_call.config().approval_policy.value(),
old_call.permission_profile(),
old_call.config().approvals_reviewer,
old_call.config().environment_use_mxc.get("old-environment"),
),
(
AskForApproval::Never,
&PermissionProfile::read_only(),
ApprovalsReviewer::User,
Some(&false),
)
);
assert_eq!(
(
new_call.config().approval_policy.value(),
new_call.config().approvals_reviewer,
new_call.config().environment_use_mxc.get("new-environment"),
),
(
AskForApproval::OnRequest,
ApprovalsReviewer::AutoReview,
Some(&true)
)
);
drop(old.step);
assert!(
old_connections.upgrade().is_some(),
"the prepared call should keep its captured connection set alive"
);
drop(old_call);
assert!(
old_connections.upgrade().is_none(),
"the captured connection set should be released with the prepared call"
);
Ok(())
}
#[tokio::test]
async fn prepared_call_does_not_reroute_after_captured_connection_closes() {
let old = test_step(
"old",
AppToolApproval::Prompt,
/*supports_sandbox_state_meta*/ true,
)
.await;
let old_call = old
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("old step should prepare the advertised tool");
let new = test_step(
"new",
AppToolApproval::Approve,
/*supports_sandbox_state_meta*/ false,
)
.await;
assert!(!Arc::ptr_eq(&old.client, &new.client));
old.client.shutdown().await;
let error = old_call
.call(
Some(serde_json::json!({"query": "codex"})),
/*meta*/ None,
/*timeout*/ None,
)
.await
.expect_err("a call bound to a closed connection must fail");
assert!(
format!("{error:#}").contains("MCP client is shut down"),
"the prepared call should fail on its captured client: {error:#}"
);
}
#[tokio::test]
async fn prepared_call_is_rejected_after_catalog_refresh() {
let step = test_step(
"old",
AppToolApproval::Prompt,
/*supports_sandbox_state_meta*/ true,
)
.await;
let prepared = step
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("step should prepare the advertised tool");
step.tool_catalog
.refresh(
|| async { Ok((step.step.tools().to_vec(), None, ())) },
|_, _, ()| {},
)
.await
.expect("refresh tool catalog");
let error = prepared
.call(
Some(serde_json::json!({"query": "codex"})),
/*meta*/ None,
/*timeout*/ None,
)
.await
.expect_err("a call from an older catalog must be rejected");
assert!(
format!("{error:#}").contains("catalog changed"),
"unexpected error: {error:#}"
);
}
#[tokio::test]
async fn stale_prepared_call_does_not_run_preparation() {
let step = test_step(
"old",
AppToolApproval::Prompt,
/*supports_sandbox_state_meta*/ true,
)
.await;
let prepared = step
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("step should prepare the advertised tool");
step.tool_catalog
.refresh(
|| async { Ok((step.step.tools().to_vec(), None, ())) },
|_, _, ()| {},
)
.await
.expect("refresh tool catalog");
let prepared_side_effect_ran = Arc::new(AtomicBool::new(false));
let marker = Arc::clone(&prepared_side_effect_ran);
prepared
.call_with_preparation(/*requested_timeout*/ None, || async move {
marker.store(true, Ordering::SeqCst);
Ok((None, None))
})
.await
.expect_err("a call from an older catalog must be rejected");
assert!(!prepared_side_effect_ran.load(Ordering::SeqCst));
}
#[tokio::test]
async fn preparation_holds_catalog_authority_until_it_finishes() {
let step = test_step(
"old",
AppToolApproval::Prompt,
/*supports_sandbox_state_meta*/ true,
)
.await;
let prepared = step
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("step should prepare the advertised tool");
let preparation_started = Arc::new(Notify::new());
let finish_preparation = Arc::new(Notify::new());
let started = Arc::clone(&preparation_started);
let finish = Arc::clone(&finish_preparation);
let call = tokio::spawn(async move {
prepared
.call_with_preparation(/*requested_timeout*/ None, || async move {
started.notify_one();
finish.notified().await;
Err(anyhow::anyhow!("stop after preparation"))
})
.await
});
preparation_started.notified().await;
let refresh = step.tool_catalog.refresh(
|| async { Ok((step.step.tools().to_vec(), None, ())) },
|_, _, ()| {},
);
tokio::pin!(refresh);
assert!(
futures::poll!(&mut refresh).is_pending(),
"catalog replacement must wait for irreversible call preparation"
);
finish_preparation.notify_one();
call.await
.expect("call task should finish")
.expect_err("the test preparation should stop the call");
refresh
.await
.expect("catalog refresh should finish after preparation");
}
#[tokio::test]
async fn sandbox_executable_requires_local_stdio_and_a_full_cli() -> anyhow::Result<()> {
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
let step = test_step(
"old",
AppToolApproval::Approve,
/*supports_sandbox_state_meta*/ true,
)
.await;
let call = step
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("prepared call");
// Use a probe-capable CLI so remote/HTTP exclusions cannot pass merely
// because the supplied executable lacks the sandbox capability.
let executable = codex_utils_cargo_bin::cargo_bin("codex")?;
for (server, runtime_environment, path, expected) in [
(
serde_json::json!({"command": "mcp"}),
"local",
Some(executable.clone()),
Some(AbsolutePathBuf::from_absolute_path_checked(&executable)?),
),
// The Rust test harness accepts `sandbox --help`, but must not be
// advertised as a sandbox launcher: it lacks `--sandbox-state-json`.
(
serde_json::json!({"command": "mcp"}),
"local",
Some(std::env::current_exe()?),
None,
),
(serde_json::json!({"command": "mcp"}), "local", None, None),
#[cfg(unix)]
(
serde_json::json!({"command": "mcp"}),
"local",
Some(std::ffi::OsStr::from_bytes(b"/non-utf8-\xff/codex").into()),
None,
),
(
serde_json::json!({"command": "mcp"}),
"local",
Some("codex".into()),
None,
),
(
serde_json::json!({"command": "mcp", "environment_id": "remote"}),
"remote",
Some(executable.clone()),
None,
),
(
serde_json::json!({"command": "mcp"}),
"remote",
Some(executable.clone()),
None,
),
(
serde_json::json!({"url": "http://127.0.0.1:8080/mcp"}),
"local",
Some(executable),
None,
),
] {
let mut call = call.clone();
let config = Arc::make_mut(&mut call.config);
config.codex_self_exe = path;
let mut catalog = crate::ResolvedMcpCatalog::builder();
catalog.register(crate::McpServerRegistration::from_config(
SERVER_NAME.to_owned(),
serde_json::from_value(server)?,
));
config.mcp_server_catalog = catalog.build();
call.server_metadata.environment_id = runtime_environment.to_owned();
assert_eq!(call.sandbox_codex_executable().await, expected);
let state = crate::SandboxState {
permission_profile: PermissionProfile::default(),
codex_linux_sandbox_exe: None,
sandbox_cwd: codex_utils_path_uri::PathUri::from_host_native_path(
std::env::current_dir()?,
)?,
use_legacy_landlock: false,
use_mxc: false,
};
let expected_state = serde_json::to_value(&state)?;
let mut metadata = Some(serde_json::json!({
"unrelated": "retained",
"codex/sandbox-state": {"stale": true},
"codex/sandbox-state-meta": {"different": true},
"codex/sandbox-launcher": {"codexExecutable": "must-not-survive"},
}));
call.augment_sandbox_metadata(&mut metadata, state).await?;
let mut expected_metadata = serde_json::json!({
"unrelated": "retained",
"codex/sandbox-state": expected_state,
"codex/sandbox-state-meta": expected_state,
});
if let Some(executable) = expected {
expected_metadata["codex/sandbox-launcher"] =
serde_json::json!({"codexExecutable": executable});
}
assert_eq!(metadata, Some(expected_metadata));
}
Ok(())
}

View File

@@ -0,0 +1,739 @@
use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use codex_config::McpServerConfig;
use codex_config::McpServerDisabledReason;
use codex_config::McpServerIdpOAuthConfig;
use codex_config::McpServerTransportConfig;
use codex_config::RequirementSource;
use codex_protocol::mcp_policy::EnvironmentMcpPolicy;
use codex_utils_path_uri::PathUri;
use crate::CODEX_APPS_MCP_SERVER_NAME;
use crate::McpProtocolMode;
use crate::server::McpCredentialPolicy;
/// Plugin identity retained with an MCP registration for tool attribution.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct McpPluginAttribution {
plugin_id: String,
display_name: String,
agent_plugin: bool,
host_root: Option<PathUri>,
}
impl McpPluginAttribution {
pub fn new(plugin_id: String, display_name: String) -> Self {
Self {
plugin_id,
display_name,
agent_plugin: false,
host_root: None,
}
}
pub fn agent_plugin(plugin_id: String, display_name: String) -> Self {
Self {
plugin_id,
display_name,
agent_plugin: true,
host_root: None,
}
}
/// Records the exact host-discovered plugin root.
pub fn with_host_root(mut self, host_root: PathUri) -> Self {
self.host_root = Some(host_root);
self
}
pub fn plugin_id(&self) -> &str {
&self.plugin_id
}
pub fn display_name(&self) -> &str {
&self.display_name
}
pub fn is_agent_plugin(&self) -> bool {
self.agent_plugin
}
/// Returns the host-discovered root captured with this server registration.
pub fn host_root(&self) -> Option<&PathUri> {
self.host_root.as_ref()
}
}
/// The component that declared an MCP server registration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum McpServerSource {
/// A plugin discovered through the process-wide legacy plugin manager.
Plugin(McpPluginAttribution),
/// A plugin explicitly selected for this thread through a capability root.
SelectedPlugin(McpPluginAttribution),
Config,
Compatibility {
id: String,
},
Extension {
id: String,
host_owned_apps: bool,
},
}
impl McpServerSource {
pub fn is_agent_plugin(&self) -> bool {
match self {
Self::Plugin(attribution) | Self::SelectedPlugin(attribution) => {
attribution.is_agent_plugin()
}
Self::Config | Self::Compatibility { .. } | Self::Extension { .. } => false,
}
}
pub(crate) fn is_host_owned_apps(&self, name: &str, config: &McpServerConfig) -> bool {
name == CODEX_APPS_MCP_SERVER_NAME
&& config.is_local_environment()
&& matches!(
self,
Self::Compatibility { .. }
| Self::Extension {
host_owned_apps: true,
..
}
)
}
fn disabled_registration_is_name_veto(&self) -> bool {
// A selected package's policy applies to its registration, not to a higher runtime source
// that happens to use the same logical server name.
!matches!(self, Self::SelectedPlugin(_))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum RegistrationPrecedence {
Plugin(Reverse<usize>),
SelectedPlugin(Reverse<usize>),
Config,
Compatibility,
Extension(usize),
}
impl RegistrationPrecedence {
fn tier(self) -> u8 {
match self {
Self::Plugin(_) => 0,
Self::SelectedPlugin(_) => 1,
Self::Config => 2,
Self::Compatibility => 3,
Self::Extension(_) => 4,
}
}
}
/// One named MCP server declaration before source resolution.
#[derive(Clone, Debug, PartialEq)]
pub struct McpServerRegistration {
name: String,
source: McpServerSource,
config: McpServerConfig,
credential_policy: McpCredentialPolicy,
protocol_mode: Option<McpProtocolMode>,
precedence: RegistrationPrecedence,
}
impl McpServerRegistration {
/// Registers host-owned configuration, which may resolve credentials on the host.
pub fn from_config(name: String, config: McpServerConfig) -> Self {
Self::new(
name,
McpServerSource::Config,
config,
RegistrationPrecedence::Config,
McpCredentialPolicy::HostFallbackAllowed,
)
}
/// Registers executor-discovered configuration without authority to read
/// host environment credentials.
pub fn from_executor_config(name: String, config: McpServerConfig) -> Self {
Self::new(
name,
McpServerSource::Config,
config,
RegistrationPrecedence::Config,
McpCredentialPolicy::ExecutorOnly,
)
}
/// Registers a plugin discovered by the host's process-wide plugin manager.
pub fn from_plugin(
name: String,
attribution: McpPluginAttribution,
plugin_order: usize,
config: McpServerConfig,
) -> Self {
Self::new(
name,
McpServerSource::Plugin(attribution),
config,
RegistrationPrecedence::Plugin(Reverse(plugin_order)),
McpCredentialPolicy::HostFallbackAllowed,
)
}
/// Registers a thread-selected plugin above discovered plugins and below config.
/// HTTP credential authority comes from the selected root, not the server's execution environment.
pub fn from_selected_plugin(
name: String,
attribution: McpPluginAttribution,
selection_order: usize,
source_environment_id: &str,
config: McpServerConfig,
) -> Self {
let credential_policy = if source_environment_id != DEFAULT_MCP_SERVER_ENVIRONMENT_ID
&& matches!(
&config.transport,
McpServerTransportConfig::StreamableHttp { .. }
) {
McpCredentialPolicy::ExecutorOnly
} else {
McpCredentialPolicy::HostFallbackAllowed
};
Self::new(
name,
McpServerSource::SelectedPlugin(attribution),
config,
RegistrationPrecedence::SelectedPlugin(Reverse(selection_order)),
credential_policy,
)
}
pub fn from_compatibility(
name: String,
id: impl Into<String>,
config: McpServerConfig,
) -> Self {
Self::new(
name,
McpServerSource::Compatibility { id: id.into() },
config,
RegistrationPrecedence::Compatibility,
McpCredentialPolicy::HostFallbackAllowed,
)
}
pub fn from_extension(
name: String,
id: impl Into<String>,
contribution_order: usize,
config: McpServerConfig,
) -> Self {
Self::new(
name,
McpServerSource::Extension {
id: id.into(),
host_owned_apps: false,
},
config,
RegistrationPrecedence::Extension(contribution_order),
McpCredentialPolicy::HostFallbackAllowed,
)
}
/// Overrides the protocol for this registration if it wins HTTP server resolution.
pub fn with_protocol_mode(mut self, protocol_mode: McpProtocolMode) -> Self {
self.protocol_mode = Some(protocol_mode);
self
}
/// Registers the controller-owned Apps server contributed by a host extension.
pub fn from_hosted_apps(
id: impl Into<String>,
contribution_order: usize,
config: McpServerConfig,
) -> Self {
let host_owned_apps = config.is_local_environment();
Self::new(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
McpServerSource::Extension {
id: id.into(),
host_owned_apps,
},
config,
RegistrationPrecedence::Extension(contribution_order),
McpCredentialPolicy::HostFallbackAllowed,
)
}
fn new(
name: String,
source: McpServerSource,
config: McpServerConfig,
precedence: RegistrationPrecedence,
credential_policy: McpCredentialPolicy,
) -> Self {
Self {
name,
source,
config,
credential_policy,
protocol_mode: None,
precedence,
}
}
}
/// The authority available for MCP servers running in one environment.
#[derive(Clone, Copy, Debug)]
pub enum McpEnvironmentAuthority<'a> {
/// The selected environment adds no restrictions to the controller policy.
Unrestricted,
/// The owner supplied the final restrictions for this environment.
Restricted(&'a EnvironmentMcpPolicy),
/// An explicitly selected plugin can use its executor without attaching that executor.
SelectedPluginsOnly,
/// The attachment is pending or failed, so its owner policy is not available.
Unavailable,
}
/// One side of an MCP server conflict, including whether it registers or
/// removes the server.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum McpServerConflictAction {
Register(McpServerSource),
Remove(McpServerSource),
}
/// A same-tier name collision and the final outcome after all precedence is applied.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct McpServerConflict {
pub name: String,
pub outcome: McpServerConflictAction,
pub contenders: Vec<McpServerConflictAction>,
}
#[derive(Clone, Debug)]
enum CatalogAction {
Register(Box<McpServerRegistration>),
Remove {
name: String,
source: McpServerSource,
precedence: RegistrationPrecedence,
},
}
impl CatalogAction {
fn name(&self) -> &str {
match self {
Self::Register(registration) => &registration.name,
Self::Remove { name, .. } => name,
}
}
fn precedence(&self) -> RegistrationPrecedence {
match self {
Self::Register(registration) => registration.precedence,
Self::Remove { precedence, .. } => *precedence,
}
}
fn conflict_action(&self) -> McpServerConflictAction {
match self {
Self::Register(registration) => {
McpServerConflictAction::Register(registration.source.clone())
}
Self::Remove { source, .. } => McpServerConflictAction::Remove(source.clone()),
}
}
}
/// Mutable inputs used to produce an immutable resolved catalog.
#[derive(Clone, Debug, Default)]
pub struct McpCatalogBuilder {
actions: Vec<CatalogAction>,
disabled_server_names: BTreeSet<String>,
requirements_disabled_server_names: BTreeMap<String, RequirementSource>,
ema_idp: Option<McpServerIdpOAuthConfig>,
}
impl McpCatalogBuilder {
/// Enables EMA with the IdP selected from trusted configuration.
/// Without this policy, finalization disables EMA registrations.
pub fn enable_ema(&mut self, idp: McpServerIdpOAuthConfig) {
self.ema_idp = Some(idp);
}
pub fn register(&mut self, registration: McpServerRegistration) {
self.actions
.push(CatalogAction::Register(Box::new(registration)));
}
/// Applies the legacy name-scoped disabled veto after source resolution.
pub fn disable(&mut self, name: String) {
self.disabled_server_names.insert(name);
}
pub fn remove_compatibility(&mut self, name: String, id: impl Into<String>) {
self.actions.push(CatalogAction::Remove {
name,
source: McpServerSource::Compatibility { id: id.into() },
precedence: RegistrationPrecedence::Compatibility,
});
}
pub fn remove_extension(
&mut self,
name: String,
id: impl Into<String>,
contribution_order: usize,
) {
self.actions.push(CatalogAction::Remove {
name,
source: McpServerSource::Extension {
id: id.into(),
host_owned_apps: false,
},
precedence: RegistrationPrecedence::Extension(contribution_order),
});
}
/// Applies environment authority before resolving immutable server registrations.
pub fn build_with_environment_authority<'a>(
mut self,
mut authority_for_environment: impl FnMut(&str) -> McpEnvironmentAuthority<'a>,
) -> ResolvedMcpCatalog {
for action in &mut self.actions {
let CatalogAction::Register(registration) = action else {
continue;
};
// Controller-owned Apps and existing managed denials are not attachment-owned.
if !registration.config.enabled
|| registration
.source
.is_host_owned_apps(&registration.name, &registration.config)
{
continue;
}
let allowed = match authority_for_environment(&registration.config.environment_id) {
McpEnvironmentAuthority::Unrestricted => true,
McpEnvironmentAuthority::SelectedPluginsOnly => {
matches!(&registration.source, McpServerSource::SelectedPlugin(_))
}
McpEnvironmentAuthority::Unavailable => false,
McpEnvironmentAuthority::Restricted(policy) => match &registration.source {
McpServerSource::Config
| McpServerSource::Compatibility { .. }
| McpServerSource::Extension { .. } => {
policy.servers.as_ref().is_none_or(|requirements| {
requirements
.get(&registration.name)
.is_some_and(|requirement| {
registration.config.matches_requirement(requirement)
})
})
}
McpServerSource::Plugin(attribution)
| McpServerSource::SelectedPlugin(attribution) => {
// Empty server policy denies every plugin; otherwise use package policy.
!policy.servers.as_ref().is_some_and(BTreeMap::is_empty)
&& policy
.plugins
.as_ref()
.filter(|plugins| {
plugins.values().any(|plugin| plugin.mcp_servers.is_some())
})
.is_none_or(|plugins| {
plugins
.get(attribution.plugin_id())
.and_then(|plugin| plugin.mcp_servers.as_ref())
.and_then(|requirements| {
requirements.get(&registration.name)
})
.is_some_and(|requirement| {
registration.config.matches_requirement(requirement)
})
})
}
},
};
if !allowed {
registration.config.enabled = false;
registration.config.disabled_reason = Some(McpServerDisabledReason::Requirements {
source: RequirementSource::Unknown,
});
}
}
self.build()
}
pub fn build(mut self) -> ResolvedMcpCatalog {
// Keep source actions unbound so later catalog revisions resolve afresh.
for action in &mut self.actions {
if let CatalogAction::Register(registration) = action
&& let Some(oauth) = &mut registration.config.oauth
{
oauth.ema_registration = None;
}
}
// Stable sorting makes action order the tie-breaker when precedence is equal.
self.actions.sort_by_key(CatalogAction::precedence);
let mut winners = BTreeMap::<String, CatalogAction>::new();
let mut actions_by_name_and_tier = BTreeMap::<(String, u8), Vec<&CatalogAction>>::new();
for action in &self.actions {
winners.insert(action.name().to_string(), action.clone());
actions_by_name_and_tier
.entry((action.name().to_string(), action.precedence().tier()))
.or_default()
.push(action);
}
let mut conflicts = Vec::new();
for ((name, _), actions) in actions_by_name_and_tier {
if actions.len() < 2 {
continue;
}
let Some(outcome) = winners.get(&name).map(CatalogAction::conflict_action) else {
continue;
};
conflicts.push(McpServerConflict {
name,
outcome,
contenders: actions
.into_iter()
.map(CatalogAction::conflict_action)
.collect(),
});
}
let mut disabled_server_names = self.disabled_server_names;
let mut requirements_disabled_server_names = self.requirements_disabled_server_names;
let ema_idp = self.ema_idp;
let servers = winners
.into_iter()
.filter_map(|(name, action)| match action {
CatalogAction::Register(registration) => {
let mut registration = *registration;
let persist_disabled_name =
registration.source.disabled_registration_is_name_veto()
&& !(matches!(
registration.source,
McpServerSource::Plugin(_) | McpServerSource::SelectedPlugin(_)
) && matches!(
registration.config.auth,
codex_config::McpServerAuth::EmaAuth
));
if !registration.config.enabled && persist_disabled_name {
match &registration.config.disabled_reason {
Some(
McpServerDisabledReason::Requirements { source }
| McpServerDisabledReason::ExplicitAndRequirements { source },
) => {
requirements_disabled_server_names
.insert(name.clone(), source.clone());
if matches!(
registration.config.disabled_reason,
Some(McpServerDisabledReason::ExplicitAndRequirements { .. })
) {
disabled_server_names.insert(name.clone());
}
}
Some(McpServerDisabledReason::Unknown) | None => {
disabled_server_names.insert(name.clone());
}
}
}
if disabled_server_names.contains(&name) {
registration.config.enabled = false;
}
// Only trusted Apps may ignore a previous registration's requirements denial.
// Retain it so a later custom replacement is still blocked.
if !registration
.source
.is_host_owned_apps(&name, &registration.config)
&& let Some(source) = requirements_disabled_server_names.get(&name)
{
registration.config.disable_by_requirements(source.clone());
}
if matches!(
registration.config.auth,
codex_config::McpServerAuth::EmaAuth
) {
let allowed = matches!(&registration.source, McpServerSource::Config)
&& ema_idp.as_ref().is_some_and(|idp| {
registration.config.resolve_ema_registration(idp).is_ok()
});
// EMA denial must not become a persistent name veto.
registration.config.enabled &= allowed;
}
Some((
name,
ResolvedMcpServer {
source: registration.source,
config: registration.config,
credential_policy: registration.credential_policy,
protocol_mode: registration.protocol_mode,
},
))
}
CatalogAction::Remove { .. } => None,
})
.collect();
ResolvedMcpCatalog {
actions: self.actions,
disabled_server_names,
requirements_disabled_server_names,
ema_idp,
servers,
conflicts,
}
}
}
/// A single winning MCP registration.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedMcpServer {
source: McpServerSource,
config: McpServerConfig,
credential_policy: McpCredentialPolicy,
protocol_mode: Option<McpProtocolMode>,
}
impl ResolvedMcpServer {
pub fn source(&self) -> &McpServerSource {
&self.source
}
pub fn config(&self) -> &McpServerConfig {
&self.config
}
pub(crate) fn credential_policy(&self) -> McpCredentialPolicy {
self.credential_policy
}
pub fn protocol_mode(&self) -> Option<McpProtocolMode> {
self.protocol_mode
}
}
/// Immutable result of MCP registration resolution.
#[derive(Clone, Debug, Default)]
pub struct ResolvedMcpCatalog {
actions: Vec<CatalogAction>,
disabled_server_names: BTreeSet<String>,
requirements_disabled_server_names: BTreeMap<String, RequirementSource>,
ema_idp: Option<McpServerIdpOAuthConfig>,
servers: BTreeMap<String, ResolvedMcpServer>,
conflicts: Vec<McpServerConflict>,
}
impl ResolvedMcpCatalog {
pub fn builder() -> McpCatalogBuilder {
McpCatalogBuilder::default()
}
pub fn to_builder(&self) -> McpCatalogBuilder {
McpCatalogBuilder {
actions: self.actions.clone(),
disabled_server_names: self.disabled_server_names.clone(),
requirements_disabled_server_names: self.requirements_disabled_server_names.clone(),
ema_idp: self.ema_idp.clone(),
}
}
pub fn server(&self, name: &str) -> Option<&ResolvedMcpServer> {
self.servers.get(name)
}
pub fn configured_servers(&self) -> HashMap<String, McpServerConfig> {
self.servers
.iter()
.map(|(name, server)| (name.clone(), server.config.clone()))
.collect()
}
/// Returns whether both catalogs have the same winning servers, sources, and EMA policy.
pub fn has_same_servers(&self, other: &Self) -> bool {
self.servers == other.servers && self.ema_idp == other.ema_idp
}
/// Replaces the resolved server set while preserving known sources and EMA policy.
///
/// # Panics
///
/// Panics if a materialized server is missing from the catalog.
pub fn with_materialized_servers(&self, servers: HashMap<String, McpServerConfig>) -> Self {
let mut builder = McpCatalogBuilder {
disabled_server_names: self.disabled_server_names.clone(),
requirements_disabled_server_names: self.requirements_disabled_server_names.clone(),
ema_idp: self.ema_idp.clone(),
..Default::default()
};
for (name, config) in servers {
#[expect(
clippy::expect_used,
reason = "materialized servers must have catalog registrations"
)]
let previous = self
.server(&name)
.expect("materialized MCP server must have a catalog registration");
let source = previous.source.clone();
let precedence = match &source {
McpServerSource::Plugin(_) => RegistrationPrecedence::Plugin(Reverse(0)),
McpServerSource::SelectedPlugin(_) => {
RegistrationPrecedence::SelectedPlugin(Reverse(0))
}
McpServerSource::Config => RegistrationPrecedence::Config,
McpServerSource::Compatibility { .. } => RegistrationPrecedence::Compatibility,
McpServerSource::Extension { .. } => RegistrationPrecedence::Extension(0),
};
let credential_policy = previous.credential_policy();
let mut registration =
McpServerRegistration::new(name, source, config, precedence, credential_policy);
registration.protocol_mode = previous.protocol_mode();
builder.register(registration);
}
builder.build()
}
/// Returns package attribution for each winning plugin-owned server.
pub fn plugin_attributions_by_server_name(&self) -> HashMap<String, McpPluginAttribution> {
self.servers
.iter()
.filter_map(|(name, server)| match server.source() {
McpServerSource::Plugin(attribution)
| McpServerSource::SelectedPlugin(attribution) => {
Some((name.clone(), attribution.clone()))
}
McpServerSource::Config
| McpServerSource::Compatibility { .. }
| McpServerSource::Extension { .. } => None,
})
.collect()
}
/// Returns the names of winning servers supplied by thread-selected plugins.
pub(crate) fn selected_plugin_server_names(&self) -> impl Iterator<Item = &str> {
self.servers.iter().filter_map(|(name, server)| {
matches!(server.source(), McpServerSource::SelectedPlugin(_)).then_some(name.as_str())
})
}
pub fn conflicts(&self) -> &[McpServerConflict] {
&self.conflicts
}
}
#[cfg(test)]
#[path = "catalog_tests.rs"]
mod tests;

View File

@@ -0,0 +1,848 @@
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::time::Duration;
use codex_config::AppToolApproval;
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
use codex_config::McpServerIdpOAuthConfig;
use codex_config::McpServerToolConfig;
use codex_config::McpServerTransportConfig;
use codex_protocol::mcp_policy::EnvironmentMcpPolicy;
use codex_protocol::mcp_policy::PluginMcpRequirements;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use crate::CODEX_APPS_MCP_SERVER_NAME;
use crate::McpProtocolMode;
use crate::server::McpCredentialPolicy;
use super::McpEnvironmentAuthority;
use super::McpPluginAttribution;
use super::McpServerConflict;
use super::McpServerConflictAction;
use super::McpServerRegistration;
use super::McpServerSource;
use super::ResolvedMcpCatalog;
use super::ResolvedMcpServer;
fn server(url: &str) -> McpServerConfig {
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: url.to_string(),
bearer_token_env_var: None,
http_headers: None,
env_http_headers: None,
http_headers_helper: None,
},
environment_id: DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: true,
startup_readiness: Default::default(),
supports_parallel_tool_calls: true,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: Some(Duration::from_secs(7)),
tool_timeout_sec: Some(Duration::from_secs(11)),
default_tools_approval_mode: Some(AppToolApproval::Prompt),
enabled_tools: Some(vec!["read".to_string()]),
disabled_tools: Some(vec!["write".to_string()]),
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::from([(
"read".to_string(),
McpServerToolConfig {
approval_mode: Some(AppToolApproval::Approve),
..Default::default()
},
)]),
}
}
fn plugin(plugin_id: &str) -> McpPluginAttribution {
McpPluginAttribution::new(plugin_id.to_string(), plugin_id.to_string())
}
fn plugin_source(plugin_id: &str) -> McpServerSource {
McpServerSource::Plugin(plugin(plugin_id))
}
fn selected_plugin_source(plugin_id: &str) -> McpServerSource {
McpServerSource::SelectedPlugin(plugin(plugin_id))
}
fn compatibility_source(id: &str) -> McpServerSource {
McpServerSource::Compatibility { id: id.to_string() }
}
fn extension_source(id: &str) -> McpServerSource {
McpServerSource::Extension {
id: id.to_string(),
host_owned_apps: false,
}
}
fn register(source: McpServerSource) -> McpServerConflictAction {
McpServerConflictAction::Register(source)
}
fn remove(source: McpServerSource) -> McpServerConflictAction {
McpServerConflictAction::Remove(source)
}
#[test]
fn executor_credential_policy_survives_catalog_rebuilds_and_materialization() {
let mut config = server("https://executor.example/mcp");
config.environment_id = "remote".to_string();
let mut executor = ResolvedMcpCatalog::builder();
executor.register(McpServerRegistration::from_executor_config(
"docs".to_string(),
config.clone(),
));
let executor = executor.build();
let mut host = ResolvedMcpCatalog::builder();
host.register(McpServerRegistration::from_config(
"docs".to_string(),
config,
));
let host = host.build();
for catalog in [
executor.to_builder().build(),
executor.with_materialized_servers(executor.configured_servers()),
] {
assert_eq!(
catalog.server("docs").unwrap(),
executor.server("docs").unwrap(),
);
assert_eq!(
catalog.server("docs").unwrap().credential_policy(),
McpCredentialPolicy::ExecutorOnly,
);
assert!(!catalog.has_same_servers(&host));
}
assert_eq!(
host.server("docs").unwrap().credential_policy(),
McpCredentialPolicy::HostFallbackAllowed,
);
}
#[test]
#[should_panic(expected = "materialized MCP server must have a catalog registration")]
fn materialized_server_requires_catalog_registration() {
let catalog = ResolvedMcpCatalog::default();
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://executor.example/mcp",
"environment_id": "remote",
"bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
}))
.expect("valid MCP server config");
catalog.with_materialized_servers(HashMap::from([("unregistered".to_string(), server)]));
}
#[test]
fn selected_plugin_credential_policy_follows_origin_and_survives_catalog_rebuild() {
let mut remote_stdio: McpServerConfig =
serde_json::from_value(serde_json::json!({ "command": "remote-server" }))
.expect("valid stdio server");
remote_stdio.environment_id = "executor-1".to_string();
let mut remote_destination = server("https://executor.example/mcp");
remote_destination.environment_id = "executor-1".to_string();
for (source_environment_id, config, expected_policy) in [
(
"executor-1",
server("https://executor.example/mcp"),
McpCredentialPolicy::ExecutorOnly,
),
(
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
remote_destination,
McpCredentialPolicy::HostFallbackAllowed,
),
(
"executor-1",
remote_stdio,
McpCredentialPolicy::HostFallbackAllowed,
),
] {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_selected_plugin(
"docs".to_string(),
plugin("selected-root"),
/*selection_order*/ 0,
source_environment_id,
config,
));
let catalog = builder.build();
for rebuilt in [
catalog.to_builder().build(),
catalog.with_materialized_servers(catalog.configured_servers()),
] {
let registration = rebuilt.server("docs").unwrap();
assert_eq!(
registration.source(),
&selected_plugin_source("selected-root")
);
assert_eq!(registration.credential_policy(), expected_policy);
assert_eq!(registration, catalog.server("docs").unwrap());
}
}
}
#[test]
fn plugin_host_root_is_retained_in_catalog_identity() {
let original_root = PathUri::parse("file:///plugins/original").expect("valid plugin root URI");
let replacement_root =
PathUri::parse("file:///plugins/replacement").expect("valid plugin root URI");
let catalog_for_root = |root| {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("plugin@test").with_host_root(root),
/*plugin_order*/ 0,
server("https://plugin.example/mcp"),
));
builder.build()
};
let original = catalog_for_root(original_root.clone());
let replacement = catalog_for_root(replacement_root);
let Some(McpServerSource::Plugin(attribution)) =
original.server("docs").map(ResolvedMcpServer::source)
else {
panic!("expected host-discovered plugin registration");
};
assert_eq!(attribution.host_root(), Some(&original_root));
assert!(!original.has_same_servers(&replacement));
}
#[test]
fn ema_policy_survives_rebuilds_and_rebinds_materialized_servers() {
let idp = McpServerIdpOAuthConfig {
issuer: "https://idp.example".to_string(),
client_secret: None,
token_endpoint_auth_method: None,
client_id: "enterprise-client".to_string(),
};
let mut builder = ResolvedMcpCatalog::builder();
builder.enable_ema(idp.clone());
let enabled_empty = builder.build();
assert!(!enabled_empty.has_same_servers(&ResolvedMcpCatalog::default()));
let mut builder = enabled_empty.to_builder();
let mut config = server("https://resource.example/mcp");
config.auth = McpServerAuth::EmaAuth;
builder.register(McpServerRegistration::from_config(
"enterprise".to_string(),
config,
));
let original = builder.build();
assert!(original.has_same_servers(&original.to_builder().build()));
let mut servers = original.configured_servers();
let config = servers.get_mut("enterprise").expect("EMA server");
let McpServerTransportConfig::StreamableHttp { url, .. } = &mut config.transport else {
panic!("expected HTTP server");
};
*url = "https://resource.example/revised".to_string();
let materialized = original.with_materialized_servers(servers);
let config = materialized
.server("enterprise")
.expect("materialized EMA server")
.config();
let registration = config
.ema_registration()
.expect("finalized EMA registration");
assert_eq!(
(
config.enabled,
registration.idp(),
registration.server_url()
),
(true, &idp, "https://resource.example/revised")
);
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_config(
"enterprise".to_string(),
config.clone(),
));
let denied = builder.build();
let config = denied
.server("enterprise")
.expect("denied EMA server")
.config();
assert_eq!((config.enabled, config.ema_registration()), (false, None));
}
#[test]
fn rejected_plugin_ema_registration_does_not_veto_hosted_apps() {
let mut rejected = server("https://plugin.example/mcp");
rejected.auth = McpServerAuth::EmaAuth;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
plugin("plugin@test"),
/*plugin_order*/ 0,
rejected,
));
let catalog = builder.build();
assert!(
!catalog
.server(CODEX_APPS_MCP_SERVER_NAME)
.unwrap()
.config()
.enabled
);
let materialized = catalog.with_materialized_servers(catalog.configured_servers());
for catalog in [catalog, materialized] {
let mut builder = catalog.to_builder();
let expected = server("https://chatgpt.com/mcp");
builder.register(McpServerRegistration::from_hosted_apps(
"apps",
/*contribution_order*/ 0,
expected.clone(),
));
assert_eq!(
builder
.build()
.server(CODEX_APPS_MCP_SERVER_NAME)
.unwrap()
.config(),
&expected,
);
}
}
#[test]
fn source_precedence_preserves_the_winning_registration() {
let extension = server("https://extension.example/mcp");
let mut plugin_server = server("https://plugin.example/mcp");
plugin_server.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
extension.clone(),
));
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("plugin@test"),
/*plugin_order*/ 0,
plugin_server,
));
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("other-plugin@test"),
/*plugin_order*/ 1,
server("https://other-plugin.example/mcp"),
));
builder.register(McpServerRegistration::from_compatibility(
"docs".to_string(),
"legacy",
server("https://compatibility.example/mcp"),
));
builder.register(McpServerRegistration::from_config(
"docs".to_string(),
server("https://config.example/mcp"),
));
let catalog = builder.build();
let resolved = catalog.server("docs").expect("resolved server");
assert_eq!(
resolved.source(),
&McpServerSource::Extension {
id: "hosted".to_string(),
host_owned_apps: false,
}
);
assert_eq!(resolved.config(), &extension);
assert!(catalog.plugin_attributions_by_server_name().is_empty());
assert_eq!(
catalog.conflicts(),
&[McpServerConflict {
name: "docs".to_string(),
outcome: register(extension_source("hosted")),
contenders: vec![
register(plugin_source("other-plugin@test")),
register(plugin_source("plugin@test")),
],
}]
);
}
#[test]
fn disabled_veto_only_disables_the_winning_registration() {
let extension = server("https://extension.example/mcp");
let mut expected = extension.clone();
expected.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
extension,
));
builder.disable("docs".to_string());
let actual = builder
.build()
.server("docs")
.expect("resolved server")
.config()
.clone();
assert_eq!(actual, expected);
}
#[test]
fn disabled_winner_remains_a_veto_when_the_catalog_is_extended() {
let mut disabled = server("https://config.example/mcp");
disabled.enabled = false;
let mut expected = server("https://extension.example/mcp");
expected.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_config(
"docs".to_string(),
disabled,
));
let mut builder = builder.build().to_builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
server("https://extension.example/mcp"),
));
let resolved = builder.build();
assert_eq!(
resolved.server("docs"),
Some(&super::ResolvedMcpServer {
source: extension_source("hosted"),
config: expected,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
}
#[test]
fn disabled_discovered_plugin_remains_a_veto_for_runtime_overlays() {
let mut disabled = server("https://plugin.example/mcp");
disabled.enabled = false;
let mut expected = server("https://extension.example/mcp");
expected.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("plugin@test"),
/*plugin_order*/ 0,
disabled,
));
let mut builder = builder.build().to_builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
server("https://extension.example/mcp"),
));
let resolved = builder.build();
assert_eq!(
resolved.server("docs"),
Some(&super::ResolvedMcpServer {
source: extension_source("hosted"),
config: expected,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
}
#[test]
fn earlier_plugin_wins_with_an_explicit_conflict() {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("alpha@test"),
/*plugin_order*/ 0,
server("https://alpha.example/mcp"),
));
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("beta@test"),
/*plugin_order*/ 1,
server("https://beta.example/mcp"),
));
let catalog = builder.build();
assert_eq!(
catalog.plugin_attributions_by_server_name(),
HashMap::from([("docs".to_string(), plugin("alpha@test"))])
);
assert_eq!(
catalog.conflicts(),
&[McpServerConflict {
name: "docs".to_string(),
outcome: register(plugin_source("alpha@test")),
contenders: vec![
register(plugin_source("beta@test")),
register(plugin_source("alpha@test")),
],
}]
);
}
#[test]
fn selected_plugins_override_discovered_plugins_but_not_config() {
let selected = server("https://selected-alpha.example/mcp");
let mut discovered = server("https://local.example/mcp");
discovered.enabled = false;
discovered.default_tools_approval_mode = Some(AppToolApproval::Auto);
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("local@test"),
/*plugin_order*/ 0,
discovered,
));
builder.register(McpServerRegistration::from_selected_plugin(
"docs".to_string(),
plugin("selected-beta"),
/*selection_order*/ 1,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
server("https://selected-beta.example/mcp"),
));
builder.register(McpServerRegistration::from_selected_plugin(
"docs".to_string(),
plugin("selected-alpha"),
/*selection_order*/ 0,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
selected.clone(),
));
let catalog = builder.build();
assert_eq!(
catalog.server("docs"),
Some(&super::ResolvedMcpServer {
source: selected_plugin_source("selected-alpha"),
config: selected,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
assert_eq!(
catalog.plugin_attributions_by_server_name(),
HashMap::from([("docs".to_string(), plugin("selected-alpha"))])
);
assert_eq!(
catalog.conflicts(),
&[McpServerConflict {
name: "docs".to_string(),
outcome: register(selected_plugin_source("selected-alpha")),
contenders: vec![
register(selected_plugin_source("selected-beta")),
register(selected_plugin_source("selected-alpha")),
],
}]
);
let refreshed = server("https://refreshed.example/mcp");
let catalog =
catalog.with_materialized_servers(HashMap::from([("docs".to_string(), refreshed.clone())]));
assert_eq!(
catalog.server("docs"),
Some(&super::ResolvedMcpServer {
source: selected_plugin_source("selected-alpha"),
config: refreshed,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
let mut builder = catalog.to_builder();
let configured = server("https://config.example/mcp");
builder.register(McpServerRegistration::from_config(
"docs".to_string(),
configured.clone(),
));
let catalog = builder.build();
assert_eq!(
catalog.server("docs"),
Some(&super::ResolvedMcpServer {
source: McpServerSource::Config,
config: configured,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
}
#[test]
fn disabled_selected_plugin_does_not_veto_runtime_overlays() {
let mut disabled = server("https://selected.example/mcp");
disabled.enabled = false;
let extension = server("https://extension.example/mcp");
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_selected_plugin(
"docs".to_string(),
plugin("selected"),
/*selection_order*/ 0,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
disabled,
));
let mut builder = builder.build().to_builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
extension.clone(),
));
let resolved = builder.build();
assert_eq!(
resolved.server("docs"),
Some(&super::ResolvedMcpServer {
source: extension_source("hosted"),
config: extension,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
}
#[test]
fn equal_precedence_uses_insertion_order_not_source_identity() {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_compatibility(
"docs".to_string(),
"z-first",
server("https://first.example/mcp"),
));
builder.register(McpServerRegistration::from_compatibility(
"docs".to_string(),
"a-second",
server("https://second.example/mcp"),
));
let catalog = builder.build();
assert_eq!(
catalog.server("docs"),
Some(&super::ResolvedMcpServer {
source: compatibility_source("a-second"),
config: server("https://second.example/mcp"),
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
let mut builder = catalog.to_builder();
builder.remove_compatibility("docs".to_string(), "remove-last");
let catalog = builder.build();
assert_eq!(catalog.server("docs"), None);
assert_eq!(
catalog.conflicts(),
&[McpServerConflict {
name: "docs".to_string(),
outcome: remove(compatibility_source("remove-last")),
contenders: vec![
register(compatibility_source("z-first")),
register(compatibility_source("a-second")),
remove(compatibility_source("remove-last")),
],
}]
);
}
#[test]
fn extension_protocol_mode_follows_the_winner_through_materialization() {
let config = server("https://apps.example/mcp");
let mut builder = ResolvedMcpCatalog::builder();
builder.register(
McpServerRegistration::from_extension(
"apps".to_string(),
"loser",
/*contribution_order*/ 0,
config.clone(),
)
.with_protocol_mode(McpProtocolMode::V20260728),
);
builder.register(McpServerRegistration::from_extension(
"apps".to_string(),
"winner",
/*contribution_order*/ 1,
config.clone(),
));
let without_override = builder.build();
assert_eq!(
without_override
.server("apps")
.and_then(ResolvedMcpServer::protocol_mode),
None
);
let mut builder = ResolvedMcpCatalog::builder();
builder.register(
McpServerRegistration::from_extension(
"apps".to_string(),
"winner",
/*contribution_order*/ 1,
config,
)
.with_protocol_mode(McpProtocolMode::Legacy),
);
let with_override = builder.build();
assert!(!without_override.has_same_servers(&with_override));
let refreshed = server("https://refreshed.example/mcp");
let materialized = with_override
.with_materialized_servers(HashMap::from([("apps".to_string(), refreshed.clone())]));
assert_eq!(
materialized.server("apps"),
Some(&ResolvedMcpServer {
source: extension_source("winner"),
config: refreshed,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: Some(McpProtocolMode::Legacy),
})
);
}
#[test]
fn environment_policy_exempts_only_explicitly_host_owned_apps() {
let policy = EnvironmentMcpPolicy {
servers: Some(BTreeMap::new()),
plugins: None,
};
for (registration, expected) in [
(
McpServerRegistration::from_extension(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
"apps",
/*contribution_order*/ 0,
server("https://apps.example/mcp"),
),
false,
),
(
McpServerRegistration::from_hosted_apps(
"apps",
/*contribution_order*/ 0,
server("https://apps.example/mcp"),
),
true,
),
] {
let custom = server("https://custom.example/mcp");
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_config(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
custom.clone(),
));
let denied = builder
.build_with_environment_authority(|_| McpEnvironmentAuthority::Restricted(&policy));
let mut builder = denied.to_builder();
builder.register(registration);
let catalog = builder
.build_with_environment_authority(|_| McpEnvironmentAuthority::Restricted(&policy));
assert_eq!(
catalog
.server(CODEX_APPS_MCP_SERVER_NAME)
.expect("Apps registration")
.config()
.enabled,
expected
);
let mut builder = catalog
.with_materialized_servers(catalog.configured_servers())
.to_builder();
builder.register(McpServerRegistration::from_extension(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
"custom",
/*contribution_order*/ 1,
custom,
));
assert_eq!(
builder.build().configured_servers(),
denied.configured_servers()
);
}
}
#[test]
fn environment_policy_preserves_selected_plugin_and_empty_server_allowlist_semantics() {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_selected_plugin(
"selected".to_string(),
plugin("selected-plugin"),
/*selection_order*/ 0,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
server("https://plugin.example/mcp"),
));
let metadata_only_policy = EnvironmentMcpPolicy {
servers: None,
plugins: Some(BTreeMap::from([(
"metadata-only-plugin".to_string(),
PluginMcpRequirements { mcp_servers: None },
)])),
};
let deny_all_policy = EnvironmentMcpPolicy {
servers: Some(BTreeMap::new()),
plugins: None,
};
for (policy, expected) in [(&metadata_only_policy, true), (&deny_all_policy, false)] {
let resolved = builder
.clone()
.build_with_environment_authority(|_| McpEnvironmentAuthority::Restricted(policy));
assert_eq!(
resolved
.server("selected")
.expect("selected plugin")
.config()
.enabled,
expected
);
}
}
#[test]
fn retired_plugin_ema_does_not_veto_a_later_runtime_registration() {
let mut retired = server("https://plugin.example/mcp");
retired.auth = McpServerAuth::EmaAuth;
retired.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("plugin@test"),
/*plugin_order*/ 0,
retired,
));
let catalog = builder.build();
assert!(!catalog.server("docs").unwrap().config().enabled);
let mut builder = catalog.to_builder();
let expected = server("https://extension.example/mcp");
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
expected.clone(),
));
assert_eq!(builder.build().server("docs").unwrap().config(), &expected);
}

View File

@@ -0,0 +1,92 @@
use std::collections::HashMap;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::mcp::MCP_APP_UI_EXTENSION_ID;
use codex_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID;
use codex_protocol::mcp::OPENAI_FORM_EXTENSION_ID;
use codex_protocol::mcp::OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID;
use serde_json::Map;
use serde_json::Value;
/// Projects privileged capabilities only to their intended recipients.
/// Verification requires the host-owned plugin service; network policy requires a trusted
/// ChatGPT origin. Server names and caller-supplied capabilities do not grant either privilege.
pub(crate) fn server_mcp_extensions(
extensions: &ClientMcpExtensions,
server_name: &str,
server: Option<&crate::catalog::ResolvedMcpServer>,
advertise_network_policy: bool,
chatgpt_base_url: &str,
) -> ClientMcpExtensions {
let plugin_service = server.is_some_and(|server| {
server
.source()
.is_host_owned_apps(server_name, server.config())
});
let network_policy = advertise_network_policy
&& server.is_some_and(|server| {
crate::mcp::is_trusted_chatgpt_mcp_server(&server.config().transport, chatgpt_base_url)
});
ClientMcpExtensions::new(
extensions
.iter()
.filter(|(id, _)| *id != crate::MCP_NETWORK_POLICY_META_CAPABILITY)
.map(|(id, settings)| {
let mut settings = settings.clone();
if !plugin_service
&& id == OPENAI_ELICITATION_EXTENSION_ID
&& let Some(settings) = settings.as_object_mut()
{
settings.remove("userVerification");
}
(id.to_string(), settings)
})
.chain(network_policy.then(|| {
(
crate::MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
Value::Object(Map::new()),
)
})),
)
}
/// Selects the MCP extensions Codex supports from those declared by the app-server host.
///
/// App-server clients may declare unrelated extensions. Codex retains only the
/// trusted extension namespaces it knows how to project downstream. The
/// legacy form capability is normalized into the same extension map.
pub fn client_mcp_extensions(
extensions: Option<&HashMap<String, Value>>,
legacy_openai_form_elicitation: bool,
) -> ClientMcpExtensions {
let mut selected = extensions
.into_iter()
.flat_map(HashMap::iter)
.filter(|(id, _)| {
matches!(
id.as_str(),
OPENAI_FORM_EXTENSION_ID
| OPENAI_ELICITATION_EXTENSION_ID
| OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID
| MCP_APP_UI_EXTENSION_ID
)
})
.map(|(id, value)| (id.clone(), value.clone()))
.collect::<HashMap<_, _>>();
if let Some(settings) = selected
.get_mut(OPENAI_ELICITATION_EXTENSION_ID)
.and_then(Value::as_object_mut)
{
settings.retain(|key, _| key == "form");
}
if legacy_openai_form_elicitation {
selected
.entry(OPENAI_FORM_EXTENSION_ID.to_string())
.or_insert_with(|| Value::Object(Map::new()));
}
ClientMcpExtensions::new(selected)
}
#[cfg(test)]
#[path = "client_capabilities_tests.rs"]
mod tests;

View File

@@ -0,0 +1,157 @@
use std::collections::HashMap;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::*;
#[test]
fn selects_only_supported_mcp_extensions() {
let app_ui = json!({
"mimeTypes": [
"text/html;profile=mcp-app",
"text/x-dil;profile=mcp-app",
],
"futureField": {"preserved": true},
});
let form = json!({"futureField": {"preserved": true}});
let extensions = HashMap::from([
(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"form": form, "userVerification": {}, "unsupported": {}}),
),
(MCP_APP_UI_EXTENSION_ID.to_string(), app_ui.clone()),
(OPENAI_FORM_EXTENSION_ID.to_string(), json!({})),
(
OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(),
json!({}),
),
("example/other".to_string(), json!({"enabled": true})),
]);
assert_eq!(
client_mcp_extensions(
Some(&extensions),
/*legacy_openai_form_elicitation*/ false,
),
ClientMcpExtensions::new(HashMap::from([
(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"form": form}),
),
(MCP_APP_UI_EXTENSION_ID.to_string(), app_ui),
(OPENAI_FORM_EXTENSION_ID.to_string(), json!({})),
(
OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(),
json!({}),
),
]))
);
}
#[test]
fn normalizes_legacy_form_capability_into_extensions() {
assert_eq!(
client_mcp_extensions(
/*extensions*/ None, /*legacy_openai_form_elicitation*/ true,
),
ClientMcpExtensions::new(HashMap::from([(
OPENAI_FORM_EXTENSION_ID.to_string(),
json!({}),
)]))
);
}
#[test]
fn user_verification_is_projected_only_to_the_host_owned_plugin_service() {
use crate::catalog::McpServerRegistration;
use crate::catalog::ResolvedMcpCatalog;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::mcp::codex_apps_mcp_server_config;
use codex_rmcp_client::McpProtocolMode;
let config = codex_apps_mcp_server_config(
"https://example.com",
/*apps_mcp_product_sku*/ None,
/*originator*/ None,
);
let extensions = ClientMcpExtensions::new([
(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"form": {}, "userVerification": {}}),
),
(
crate::MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
json!({}),
),
]);
assert_eq!(
server_mcp_extensions(
&extensions,
CODEX_APPS_MCP_SERVER_NAME,
/*server*/ None,
/*advertise_network_policy*/ true,
"https://chatgpt.com",
),
ClientMcpExtensions::new([(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"form": {}}),
)]),
);
for (name, registration, settings) in [
(
CODEX_APPS_MCP_SERVER_NAME,
McpServerRegistration::from_hosted_apps(
"host",
/*contribution_order*/ 0,
config.clone(),
),
json!({"form": {}, "userVerification": {}}),
),
(
CODEX_APPS_MCP_SERVER_NAME,
McpServerRegistration::from_hosted_apps(
"host",
/*contribution_order*/ 0,
config.clone(),
)
.with_protocol_mode(McpProtocolMode::V20260728),
json!({"form": {}, "userVerification": {}}),
),
(
CODEX_APPS_MCP_SERVER_NAME,
McpServerRegistration::from_extension(
CODEX_APPS_MCP_SERVER_NAME.into(),
"ordinary",
/*contribution_order*/ 0,
config.clone(),
)
.with_protocol_mode(McpProtocolMode::V20260728),
json!({"form": {}}),
),
(
CODEX_APPS_MCP_SERVER_NAME,
McpServerRegistration::from_config(CODEX_APPS_MCP_SERVER_NAME.into(), config.clone()),
json!({"form": {}}),
),
(
"attached",
McpServerRegistration::from_config("attached".into(), config),
json!({"form": {}}),
),
] {
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(registration);
let catalog = catalog.build();
assert_eq!(
server_mcp_extensions(
&extensions,
name,
catalog.server(name),
/*advertise_network_policy*/ false,
"https://chatgpt.com",
),
ClientMcpExtensions::new([(OPENAI_ELICITATION_EXTENSION_ID.to_string(), settings)]),
);
}
}

View File

@@ -0,0 +1,350 @@
//! Client-local catalog revisions and synchronization for MCP calls.
//!
//! Apps clients read the provider's current catalog without retaining old arrays.
//! Only active readers, calls, and frozen model bindings pin earlier snapshots.
//! Explicit refreshes publish after calls using this client's current revision finish.
//! Equivalent shared publications preserve calls, but explicit refreshes invalidate them.
//! Ordinary servers coalesce list-change notifications and publish only a stable listing.
//! Notifications update discovery without waiting for admitted calls to finish.
//! Failed refreshes retain the last catalog and share a short retry cooldown.
use std::collections::HashSet;
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use codex_connectors::ConnectorRuntimeSnapshot;
use codex_rmcp_client::ToolListRevision;
use tokio::sync::Mutex;
use tokio::sync::RwLock;
use tokio::sync::RwLockReadGuard;
use tokio::sync::watch;
use tokio::time::Instant;
use crate::tools::ToolInfo;
type ToolCatalogUpdates = watch::Receiver<Option<Arc<ConnectorRuntimeSnapshot<ToolInfo>>>>;
const NOTIFICATION_REFRESH_COOLDOWN: Duration = Duration::from_secs(5);
/// The exact Apps catalog returned by an awaited refresh of one published runtime.
pub struct CodexAppsToolSnapshot {
/// Raw installed tools, including tools hidden or disabled for the model.
pub tools: Vec<ToolInfo>,
/// Raw MCP tool names allowed by the same runtime's generic MCP policy.
/// App-specific policy is applied by the caller.
pub model_visible_tool_names: HashSet<String>,
}
pub(crate) struct ClientToolCatalog {
current: RwLock<CatalogState>,
/// Explicit refreshes still wait for call preparation and execution.
calls: RwLock<()>,
/// Serialize fetches and retain the next retry time after failure or cancellation.
refresh_lock: Mutex<Option<Instant>>,
/// Starts at zero so notifications during the initial listing stay pending.
listed_notification_revision: AtomicU64,
}
struct CatalogState {
revision: u64,
/// The catalog revision installed by this client's last explicit refresh.
last_refresh_revision: u64,
source: CatalogSource,
}
/// Ordinary MCP clients own their tools; Apps clients observe the shared provider.
enum CatalogSource {
Local {
tools: Arc<[ToolInfo]>,
meta: Option<Arc<serde_json::Value>>,
},
Live {
updates: ToolCatalogUpdates,
tools_version: u64,
},
}
#[derive(Clone)]
pub(crate) struct ToolCatalogSnapshot {
pub(crate) revision: u64,
pub(crate) tools: Arc<[ToolInfo]>,
pub(crate) meta: Option<Arc<serde_json::Value>>,
}
impl ClientToolCatalog {
/// Live clients read the provider; callers publish startup tools before subscribing.
pub(crate) fn new(
tools: impl Into<Arc<[ToolInfo]>>,
meta: Option<Arc<serde_json::Value>>,
updates: Option<ToolCatalogUpdates>,
) -> Self {
let source = match updates {
Some(mut updates) => {
let tools_version = updates
.borrow_and_update()
.as_ref()
.map_or(0, |snapshot| snapshot.tools_version());
CatalogSource::Live {
updates,
tools_version,
}
}
None => CatalogSource::Local {
tools: tools.into(),
meta,
},
};
Self {
current: RwLock::new(CatalogState {
revision: 0,
last_refresh_revision: 0,
source,
}),
refresh_lock: Mutex::new(None),
calls: RwLock::new(()),
listed_notification_revision: AtomicU64::new(0),
}
}
pub(crate) async fn read<R>(&self, read: impl FnOnce(ToolCatalogSnapshot) -> R) -> R {
let (_current, snapshot) = self.read_current().await;
read(snapshot)
}
/// Captures tools and their client-local revision together, without retaining them in the client.
async fn read_current(&self) -> (RwLockReadGuard<'_, CatalogState>, ToolCatalogSnapshot) {
loop {
{
let current = self.current.read().await;
let catalog = match &current.source {
CatalogSource::Local { tools, meta } => Some((Arc::clone(tools), meta.clone())),
CatalogSource::Live { updates, .. } => {
// Hold the watch borrow while checking its version so the tools and
// revision come from the same publication.
let snapshot = updates.borrow();
(!updates.has_changed().unwrap_or(false)).then(|| {
snapshot
.as_ref()
.map(|snapshot| {
(snapshot.shared_tools(), snapshot.shared_tool_list_meta())
})
.unwrap_or_default()
})
}
};
if let Some((tools, meta)) = catalog {
let snapshot = ToolCatalogSnapshot {
revision: current.revision,
tools,
meta,
};
return (current, snapshot);
}
}
let mut current = self.current.write().await;
let changed = match &mut current.source {
CatalogSource::Live {
updates,
tools_version,
} => {
let version = updates
.borrow_and_update()
.as_ref()
.map_or(0, |snapshot| snapshot.tools_version());
let changed = *tools_version != version;
*tools_version = version;
changed
}
CatalogSource::Local { .. } => false,
};
if changed {
current.revision += 1;
}
}
}
pub(crate) fn notifications_current(&self, notifications: &ToolListRevision) -> bool {
self.listed_notification_revision.load(Ordering::Acquire) == notifications.current()
}
/// Refresh ordinary server catalogs, coalescing concurrent readers. Never mark a
/// listing current if another notification arrived while fetching its pages.
/// Retry once; persistent churn stays pending until the retry cooldown expires.
#[expect(
clippy::await_holding_invalid_type,
reason = "refreshes must remain serialized through fetching and catalog publication"
)]
pub(crate) async fn refresh_after_notifications<F, Fut>(
&self,
notifications: &ToolListRevision,
timeout: Duration,
mut fetch: F,
) -> Result<()>
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<(Vec<ToolInfo>, Option<Arc<serde_json::Value>>)>>,
{
if self.notifications_current(notifications) {
return Ok(());
}
let deadline = Instant::now() + timeout;
let mut retry_after = tokio::time::timeout_at(deadline, self.refresh_lock.lock())
.await
.context("MCP tool catalog refresh timed out")?;
if self.notifications_current(notifications)
|| retry_after.is_some_and(|deadline| Instant::now() < deadline)
{
return Ok(());
}
// Also bound retries if the caller cancels this future during the fetch.
*retry_after = Some(deadline + NOTIFICATION_REFRESH_COOLDOWN);
let result = tokio::time::timeout_at(deadline, async {
for _ in 0..2 {
let revision = notifications.current();
let tools = fetch().await;
let mut current = self.current.write().await;
if notifications.current() != revision {
continue;
}
let (tools, meta) = tools?;
current.source = CatalogSource::Local {
tools: tools.into(),
meta,
};
current.revision += 1;
self.listed_notification_revision
.store(revision, Ordering::Release);
return Ok(());
}
bail!("MCP tool list changed during catalog refresh")
})
.await
.context("MCP tool catalog refresh timed out")
.and_then(std::convert::identity);
*retry_after = result
.is_err()
.then(|| Instant::now() + NOTIFICATION_REFRESH_COOLDOWN);
result
}
/// Serialize fetching and publication, leaving the current catalog usable during the fetch.
/// The publication callback runs alongside the exact-client update under the write lock.
#[expect(
clippy::await_holding_invalid_type,
reason = "refreshes must remain serialized through fetching and catalog publication"
)]
pub(crate) async fn refresh<C, R, F, Fut, P>(&self, fetch: F, publish: P) -> Result<R>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<(Vec<ToolInfo>, Option<Arc<serde_json::Value>>, C)>>,
P: FnOnce(&[ToolInfo], Option<Arc<serde_json::Value>>, C) -> R,
{
let _refresh = self.refresh_lock.lock().await;
let (tools, meta, context) = fetch().await?;
let _calls = self.calls.write().await;
let mut current = self.current.write().await;
let result = publish(&tools, meta.clone(), context);
match &mut current.source {
CatalogSource::Local {
tools: current_tools,
meta: current_meta,
} => {
*current_tools = tools.into();
*current_meta = meta;
}
CatalogSource::Live {
updates,
tools_version,
} => {
*tools_version = updates
.borrow_and_update()
.as_ref()
.map_or(0, |snapshot| snapshot.tools_version());
}
}
current.revision += 1;
current.last_refresh_revision = current.revision;
Ok(result)
}
/// Reject stale calls before preparation. Explicit refreshes wait for execution;
/// ordinary list-change notifications may publish while an admitted call runs.
#[expect(
clippy::await_holding_invalid_type,
reason = "catalog publication must wait for call preparation and execution"
)]
pub(crate) async fn run_with_snapshot<R, F, Fut>(
&self,
expected: &ToolCatalogSnapshot,
run: F,
) -> Option<R>
where
F: FnOnce() -> Fut,
Fut: Future<Output = R>,
{
let _calls = self.calls.read().await;
let (current, snapshot) = self.read_current().await;
if current.last_refresh_revision > expected.revision
|| (snapshot.revision != expected.revision
&& !catalogs_match(&snapshot.tools, &expected.tools))
{
return None;
}
let current = match current.source {
CatalogSource::Local { .. } => {
drop(current);
None
}
CatalogSource::Live { .. } => Some(current),
};
let result = run().await;
drop(current);
Some(result)
}
}
/// Compares complete definitions independently of tool-list order. Stable sorting keeps
/// conflicting duplicate identities in their original order, since deduplication can pick the
/// first definition. This slow path runs only after the client's revision has changed.
fn catalogs_match(left: &[ToolInfo], right: &[ToolInfo]) -> bool {
if left == right {
return true;
}
if left.len() != right.len() {
return false;
}
let mut left = left.iter().collect::<Vec<_>>();
let mut right = right.iter().collect::<Vec<_>>();
for tools in [&mut left, &mut right] {
tools.sort_by_key(|tool| {
(
tool.server_name.as_str(),
tool.tool.name.as_ref(),
tool.connector_id.as_deref(),
tool.callable_namespace.as_str(),
tool.callable_name.as_str(),
)
});
}
left == right
}
/// A binding cache key includes client identity, since new clients start at zero.
#[derive(Clone)]
pub(crate) struct ClientToolCatalogRevision {
pub(crate) catalog: Arc<ClientToolCatalog>,
pub(crate) revision: u64,
}
impl PartialEq for ClientToolCatalogRevision {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.catalog, &other.catalog) && self.revision == other.revision
}
}
impl Eq for ClientToolCatalogRevision {}

View File

@@ -0,0 +1,70 @@
//! Codex Apps support for the host-owned apps MCP server.
//!
//! This module owns the normalization that turns ChatGPT-hosted app
//! connector/tool metadata into model-visible MCP callable names.
use codex_utils_plugins::mcp_connector::sanitize_name;
mod file_params;
pub use file_params::declared_openai_file_input_param_names;
pub(crate) use file_params::prepare_openai_file_params_for_model;
pub(crate) fn normalize_codex_apps_tool_title(connector_name: Option<&str>, value: &str) -> String {
let Some(connector_name) = connector_name
.map(str::trim)
.filter(|name| !name.is_empty())
else {
return value.to_string();
};
let prefix = format!("{connector_name}_");
if let Some(stripped) = value.strip_prefix(&prefix)
&& !stripped.is_empty()
{
return stripped.to_string();
}
value.to_string()
}
pub(crate) fn normalize_codex_apps_callable_name(
tool_name: &str,
connector_id: Option<&str>,
connector_name: Option<&str>,
) -> String {
let tool_name = sanitize_name(tool_name);
if let Some(connector_name) = connector_name
.map(str::trim)
.map(sanitize_name)
.filter(|name| !name.is_empty())
&& let Some(stripped) = tool_name.strip_prefix(&connector_name)
&& !stripped.is_empty()
{
return stripped.to_string();
}
if let Some(connector_id) = connector_id
.map(str::trim)
.map(sanitize_name)
.filter(|name| !name.is_empty())
&& let Some(stripped) = tool_name.strip_prefix(&connector_id)
&& !stripped.is_empty()
{
return stripped.to_string();
}
tool_name
}
pub(crate) fn normalize_codex_apps_callable_namespace(
server_name: &str,
connector_name: Option<&str>,
) -> String {
if let Some(connector_name) = connector_name {
format!("{}__{}", server_name, sanitize_name(connector_name))
} else {
server_name.to_string()
}
}

View File

@@ -0,0 +1,219 @@
//! Apps SDK `openai/fileParams` metadata and schema shaping.
//!
//! For each declared file argument, this module derives the provided-file fields
//! accepted by its input schema and records them on `ToolInfo` for execution-time
//! argument rewriting. It also presents file arguments to the model as local paths.
//!
//! See <https://developers.openai.com/apps-sdk/reference#tool-descriptor-parameters>.
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use rmcp::model::Tool;
use serde_json::Map;
use serde_json::Value as JsonValue;
use crate::tools::ToolInfo;
const META_OPENAI_FILE_PARAMS: &str = "openai/fileParams";
#[derive(Default)]
struct OpenAiFileSchemaInfo {
accepts_mime_type: bool,
accepts_file_name: bool,
}
pub fn declared_openai_file_input_param_names(
meta: Option<&Map<String, JsonValue>>,
) -> Vec<String> {
let Some(meta) = meta else {
return Vec::new();
};
meta.get(META_OPENAI_FILE_PARAMS)
.and_then(JsonValue::as_array)
.into_iter()
.flatten()
.filter_map(JsonValue::as_str)
.filter(|value| !value.is_empty())
.map(str::to_string)
.collect()
}
/// Derives execution-time file capabilities from the raw schema, then masks
/// declared file arguments as local paths for the model.
pub(crate) fn prepare_openai_file_params_for_model(tool_info: &mut ToolInfo) {
let file_params = declared_openai_file_input_param_names(tool_info.tool.meta.as_deref());
tool_info.openai_file_input_optional_fields =
supported_openai_file_input_optional_fields(&tool_info.tool, &file_params);
if file_params.is_empty() {
return;
}
let mut tool = tool_info.tool.clone();
let mut input_schema = JsonValue::Object(tool.input_schema.as_ref().clone());
rewrite_input_schema_for_local_file_paths(&mut input_schema, &file_params);
if let JsonValue::Object(input_schema) = input_schema {
tool.input_schema = Arc::new(input_schema);
}
tool_info.tool = tool;
}
fn supported_openai_file_input_optional_fields(
tool: &Tool,
file_params: &[String],
) -> HashMap<String, Vec<String>> {
let properties = tool
.input_schema
.get("properties")
.and_then(JsonValue::as_object);
file_params
.iter()
.map(|field_name| {
let optional_fields = properties
.and_then(|properties| properties.get(field_name))
.map(|schema| {
let schema_info = openai_file_schema_info(schema, tool.input_schema.as_ref());
let mut optional_fields = Vec::new();
if schema_info.accepts_mime_type {
optional_fields.push("mime_type".to_string());
}
if schema_info.accepts_file_name {
optional_fields.push("file_name".to_string());
}
optional_fields
})
.unwrap_or_default();
(field_name.clone(), optional_fields)
})
.collect()
}
fn openai_file_schema_info(
schema: &JsonValue,
root_schema: &Map<String, JsonValue>,
) -> OpenAiFileSchemaInfo {
let mut info = OpenAiFileSchemaInfo::default();
let mut pending = vec![schema];
let mut visited_refs = HashSet::new();
while let Some(schema) = pending.pop() {
let Some(schema) = schema.as_object() else {
continue;
};
if let Some(schema_ref) = schema.get("$ref").and_then(JsonValue::as_str)
&& visited_refs.insert(schema_ref)
&& let Some(referenced_schema) = resolve_local_schema_ref(root_schema, schema_ref)
{
pending.push(referenced_schema);
}
for keyword in ["anyOf", "oneOf", "allOf"] {
if let Some(variants) = schema.get(keyword).and_then(JsonValue::as_array) {
pending.extend(variants);
}
}
if schema.get("type").and_then(JsonValue::as_str) == Some("array")
|| schema.contains_key("items")
{
if let Some(items) = schema.get("items") {
pending.push(items);
}
continue;
}
let properties = schema.get("properties").and_then(JsonValue::as_object);
let is_object_schema = schema.get("type").and_then(JsonValue::as_str) == Some("object")
|| properties.is_some()
|| schema.contains_key("additionalProperties");
if !is_object_schema {
continue;
}
let accepts_additional_properties = !matches!(
schema.get("additionalProperties"),
Some(JsonValue::Bool(false) | JsonValue::Object(_))
);
info.accepts_mime_type |= accepts_additional_properties
|| properties.is_some_and(|properties| properties.contains_key("mime_type"));
info.accepts_file_name |= accepts_additional_properties
|| properties.is_some_and(|properties| properties.contains_key("file_name"));
}
info
}
fn resolve_local_schema_ref<'a>(
root_schema: &'a Map<String, JsonValue>,
schema_ref: &str,
) -> Option<&'a JsonValue> {
let pointer = schema_ref.strip_prefix("#/")?;
let mut segments = pointer.split('/');
let first_segment = segments.next()?.replace("~1", "/").replace("~0", "~");
let mut referenced_schema = root_schema.get(&first_segment)?;
for segment in segments {
let segment = segment.replace("~1", "/").replace("~0", "~");
referenced_schema = match referenced_schema {
JsonValue::Object(object) => object.get(&segment)?,
JsonValue::Array(array) => array.get(segment.parse::<usize>().ok()?)?,
_ => return None,
};
}
Some(referenced_schema)
}
fn rewrite_input_schema_for_local_file_paths(input_schema: &mut JsonValue, file_params: &[String]) {
let Some(properties) = input_schema
.as_object_mut()
.and_then(|schema| schema.get_mut("properties"))
.and_then(JsonValue::as_object_mut)
else {
return;
};
for field_name in file_params {
let Some(property_schema) = properties.get_mut(field_name) else {
continue;
};
rewrite_input_property_schema_as_local_file_path(property_schema);
}
}
fn rewrite_input_property_schema_as_local_file_path(schema: &mut JsonValue) {
let Some(object) = schema.as_object_mut() else {
return;
};
let mut description = object
.get("description")
.and_then(JsonValue::as_str)
.map(str::to_string)
.unwrap_or_default();
let guidance = "This parameter expects an absolute local file path. If you want to upload a file, provide the absolute path to that file here.";
if description.is_empty() {
description = guidance.to_string();
} else if !description.contains(guidance) {
description = format!("{description} {guidance}");
}
let is_array = object.get("type").and_then(JsonValue::as_str) == Some("array")
|| object.get("items").is_some();
object.clear();
object.insert("description".to_string(), JsonValue::String(description));
if is_array {
object.insert("type".to_string(), JsonValue::String("array".to_string()));
object.insert("items".to_string(), serde_json::json!({ "type": "string" }));
} else {
object.insert("type".to_string(), JsonValue::String("string".to_string()));
}
}
#[cfg(test)]
#[path = "file_params_tests.rs"]
mod tests;

View File

@@ -0,0 +1,284 @@
use std::collections::HashMap;
use std::sync::Arc;
use pretty_assertions::assert_eq;
use rmcp::model::JsonObject;
use rmcp::model::MetaObject;
use rmcp::model::Tool;
use super::*;
use crate::tools::ToolInfo;
fn tool_info(tool: Tool) -> ToolInfo {
ToolInfo {
server_name: "codex_apps".to_string(),
supports_parallel_tool_calls: false,
server_origin: None,
callable_name: tool.name.to_string(),
callable_namespace: "codex_apps".to_string(),
namespace_description: None,
tool,
openai_file_input_optional_fields: HashMap::new(),
connector_id: None,
connector_name: None,
plugin_display_names: Vec::new(),
}
}
fn test_tool(name: &str) -> Tool {
Tool::new(
name.to_string(),
format!("Test tool: {name}"),
Arc::new(JsonObject::default()),
)
}
#[test]
fn declared_openai_file_fields_treat_names_literally() {
let meta = serde_json::json!({
"openai/fileParams": ["file", "input_file", "attachments"]
});
let meta = meta.as_object().expect("meta object");
assert_eq!(
declared_openai_file_input_param_names(Some(meta)),
vec![
"file".to_string(),
"input_file".to_string(),
"attachments".to_string(),
]
);
}
#[test]
fn prepare_openai_file_params_for_model_masks_file_params() {
let mut tool = test_tool("upload");
tool.input_schema = Arc::new(
serde_json::json!({
"type": "object",
"properties": {
"file": {
"type": "object",
"description": "Original file payload."
},
"files": {
"type": "array",
"items": {"type": "object"}
}
}
})
.as_object()
.expect("object")
.clone(),
);
tool.meta = Some(MetaObject(
serde_json::json!({
"openai/fileParams": ["file", "files"]
})
.as_object()
.expect("object")
.clone(),
));
let mut tool_info = tool_info(tool);
prepare_openai_file_params_for_model(&mut tool_info);
assert_eq!(
*tool_info.tool.input_schema,
serde_json::json!({
"type": "object",
"properties": {
"file": {
"type": "string",
"description": "Original file payload. This parameter expects an absolute local file path. If you want to upload a file, provide the absolute path to that file here."
},
"files": {
"type": "array",
"items": {"type": "string"},
"description": "This parameter expects an absolute local file path. If you want to upload a file, provide the absolute path to that file here."
}
}
})
.as_object()
.expect("object")
.clone()
);
}
#[test]
fn prepare_openai_file_params_for_model_derives_supported_optional_fields() {
let mut tool = Tool::new(
"upload".to_string(),
"Upload files".to_string(),
Arc::new(
serde_json::json!({
"type": "object",
"$defs": {
"Rich/File": {
"type": "object",
"properties": {
"download_url": {"type": "string"},
"file_id": {"type": "string"},
"file_name": {"type": "string"}
},
"additionalProperties": false
}
},
"properties": {
"photoshop_image": {
"type": "object",
"properties": {
"download_url": {"type": "string"},
"file_id": {"type": "string"}
},
"additionalProperties": false
},
"drive_import": {
"type": "object",
"properties": {
"download_url": {"type": "string"},
"file_id": {"type": "string"},
"mime_type": {"type": "string"},
"file_name": {"type": "string"}
},
"additionalProperties": false
},
"attachments": {
"anyOf": [
{
"type": "array",
"items": {
"oneOf": [
{
"allOf": [
{
"type": "object",
"properties": {
"download_url": {"type": "string"},
"file_id": {"type": "string"}
}
},
{
"type": "object",
"properties": {
"mime_type": {"type": "string"}
}
}
]
},
{"type": "null"}
]
}
},
{"type": "null"}
]
},
"referenced_file": {
"$ref": "#/$defs/Rich~1File"
},
"custom_file": {
"type": "object",
"properties": {
"download_url": {"type": "string"},
"file_id": {"type": "string"},
"mime_type": {"type": "string"},
"uri": {"type": "string"}
},
"additionalProperties": false
},
"open_file": {
"type": "object",
"properties": {
"download_url": {"type": "string"},
"file_id": {"type": "string"}
}
},
"explicitly_open_file": {
"type": "object",
"properties": {
"download_url": {"type": "string"},
"file_id": {"type": "string"}
},
"additionalProperties": true
},
"items_only_files": {
"items": {
"type": "object",
"properties": {
"download_url": {"type": "string"},
"file_id": {"type": "string"},
"file_name": {"type": "string"}
},
"additionalProperties": false
}
}
}
})
.as_object()
.expect("object")
.clone(),
),
);
tool.meta = Some(MetaObject(
serde_json::json!({
"openai/fileParams": [
"photoshop_image",
"drive_import",
"attachments",
"referenced_file",
"custom_file",
"open_file",
"explicitly_open_file",
"items_only_files",
"missing_file"
]
})
.as_object()
.expect("object")
.clone(),
));
let mut tool_info = tool_info(tool);
prepare_openai_file_params_for_model(&mut tool_info);
assert_eq!(
tool_info.openai_file_input_optional_fields,
HashMap::from([
("photoshop_image".to_string(), Vec::new()),
(
"drive_import".to_string(),
vec!["mime_type".to_string(), "file_name".to_string()]
),
(
"attachments".to_string(),
vec!["mime_type".to_string(), "file_name".to_string()]
),
("referenced_file".to_string(), vec!["file_name".to_string()]),
("custom_file".to_string(), vec!["mime_type".to_string()]),
(
"open_file".to_string(),
vec!["mime_type".to_string(), "file_name".to_string()]
),
(
"explicitly_open_file".to_string(),
vec!["mime_type".to_string(), "file_name".to_string()]
),
(
"items_only_files".to_string(),
vec!["file_name".to_string()]
),
("missing_file".to_string(), Vec::new()),
])
);
}
#[test]
fn prepare_openai_file_params_for_model_leaves_tools_without_file_params_unchanged() {
let original_tool = test_tool("upload");
let mut tool_info = tool_info(original_tool.clone());
prepare_openai_file_params_for_model(&mut tool_info);
assert_eq!(tool_info.tool, original_tool);
assert!(tool_info.openai_file_input_optional_fields.is_empty());
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,98 @@
//! Privacy-safe size telemetry for raw MCP tool catalogs.
use rmcp::model::Tool;
use serde::Serialize;
use std::io::Write;
const RAW_DEFINITION_JSON_BYTES_METRIC: &str =
"codex.mcp.binding_catalog.raw_definition_json_bytes";
const KIB: f64 = 1024.0;
const MIB: f64 = 1024.0 * KIB;
const RAW_DEFINITION_JSON_BYTES_BUCKETS: &[f64] = &[
64.0 * KIB,
128.0 * KIB,
256.0 * KIB,
512.0 * KIB,
768.0 * KIB,
MIB,
1.5 * MIB,
2.0 * MIB,
3.0 * MIB,
4.0 * MIB,
6.0 * MIB,
8.0 * MIB,
12.0 * MIB,
16.0 * MIB,
24.0 * MIB,
32.0 * MIB,
48.0 * MIB,
64.0 * MIB,
96.0 * MIB,
128.0 * MIB,
192.0 * MIB,
256.0 * MIB,
384.0 * MIB,
512.0 * MIB,
];
pub(super) fn tool_definition_json_bytes<'a>(tools: impl Iterator<Item = &'a Tool>) -> usize {
tools.map(serialized_json_bytes).sum()
}
pub(super) fn record_binding_catalog_size(
metrics: &codex_otel::MetricsClient,
product_sku: &'static str,
raw_definition_json_bytes: usize,
) {
let _ = metrics.histogram_with_boundaries(
RAW_DEFINITION_JSON_BYTES_METRIC,
i64::try_from(raw_definition_json_bytes).unwrap_or(i64::MAX),
RAW_DEFINITION_JSON_BYTES_BUCKETS,
&[("product_sku", product_sku)],
);
}
pub(super) fn emit_binding_catalog(
product_sku: &'static str,
server_kind: &'static str,
plugin_id: Option<&str>,
catalog_source: &'static str,
tool_count: usize,
tool_definition_json_bytes: usize,
) {
tracing::event!(
target: "codex_otel.trace_safe",
tracing::Level::INFO,
event.name = "mcp.binding_catalog",
product_sku,
server_kind,
plugin_id = plugin_id.unwrap_or(""),
catalog_source,
tool_count,
tool_definition_json_bytes,
"MCP binding catalog materialized"
);
}
#[derive(Default)]
struct CountingWriter(usize);
impl Write for CountingWriter {
fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
self.0 += buffer.len();
Ok(buffer.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn serialized_json_bytes<T: Serialize + ?Sized>(value: &T) -> usize {
let mut writer = CountingWriter::default();
if serde_json::to_writer(&mut writer, value).is_ok() {
writer.0
} else {
0
}
}

View File

@@ -0,0 +1,85 @@
//! Adds negotiated policy metadata using the same publication as the MCP call.
use super::McpConnectionSet;
use crate::MCP_NETWORK_POLICY_META_CAPABILITY;
use crate::rmcp_client::ManagedClient;
use anyhow::Context;
use codex_network_proxy::NetworkMode;
use codex_protocol::models::PermissionProfile;
use rmcp::model::ServerCapabilities;
use serde::Serialize;
use serde_json::Value;
use std::sync::OnceLock;
/// Effective network restrictions delivered with an MCP call, without proxy endpoints or credentials.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkPolicyMetadata {
pub enabled: bool,
pub mode: NetworkMode,
pub allowed_domains: Vec<String>,
pub denied_domains: Vec<String>,
pub hard_deny_allowlist_misses: bool,
}
/// Produces trusted network policy metadata from an MCP publication's frozen policy sources.
/// Implementations must use the supplied call authority and capture mutable grants once per call.
pub trait NetworkPolicyMetadataProvider: Send + Sync {
fn metadata_for_call(
&self,
permission_profile: &PermissionProfile,
environment_id: &str,
) -> anyhow::Result<NetworkPolicyMetadata>;
}
impl McpConnectionSet {
pub(crate) fn network_policy_meta_for_call(
&self,
client: &ManagedClient,
permission_profile: Option<&PermissionProfile>,
environment_id: &str,
mut meta: Option<Value>,
) -> impl Fn(&ServerCapabilities) -> anyhow::Result<Option<Value>> + Send + Sync {
if let Some(Value::Object(meta)) = meta.as_mut() {
meta.remove(MCP_NETWORK_POLICY_META_CAPABILITY);
}
// A retry can negotiate policy support for the first time. Capture mutable grants
// only once, when an attempt needs them, and keep that snapshot through recovery.
let policy = OnceLock::new();
move |capabilities| {
let mut meta = meta.clone();
if client.client_supports_network_policy_meta_capability
&& capabilities
.experimental
.as_ref()
.is_some_and(|experimental| {
experimental.contains_key(MCP_NETWORK_POLICY_META_CAPABILITY)
})
{
let policy = policy.get_or_init(|| -> anyhow::Result<Value> {
let provider = self
.network_policy_metadata
.as_ref()
.context("MCP network policy metadata source is unavailable")?;
let permission_profile = permission_profile
.context("MCP server has no captured permission authority")?;
serde_json::to_value(
provider.metadata_for_call(permission_profile, environment_id)?,
)
.map_err(Into::into)
});
let policy = policy
.as_ref()
.map_err(|error| anyhow::anyhow!("{error:#}"))?;
meta.get_or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.context("MCP request metadata must be an object")?
.insert(
MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
policy.clone(),
);
}
Ok(meta)
}
}
}

View File

@@ -0,0 +1,290 @@
//! Exercises policy metadata through real in-process MCP requests on both dispatch paths.
use super::*;
use crate::MCP_NETWORK_POLICY_META_CAPABILITY;
use crate::McpServerPermissions;
use crate::NetworkPolicyMetadata;
use crate::NetworkPolicyMetadataProvider;
use crate::catalog::McpServerRegistration;
use crate::catalog::ResolvedMcpCatalog;
use codex_exec_server::FileSystemSandboxContext;
use codex_network_proxy::NetworkMode;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use rmcp::model::CallToolRequestParams;
use rmcp::model::CallToolResponse;
use serde_json::Value;
use serde_json::json;
#[derive(Clone)]
struct MetadataEchoServer {
supports_policy: bool,
}
impl ServerHandler for MetadataEchoServer {
fn get_info(&self) -> ServerConfig {
let mut capabilities = ServerCapabilities::builder().enable_tools().build();
if self.supports_policy {
capabilities.experimental = Some(std::collections::BTreeMap::from([(
MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
JsonObject::new(),
)]));
}
ServerConfig::new(capabilities)
}
async fn call_tool(
&self,
_request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, McpError> {
let mut result = rmcp::model::CallToolResult::success(Vec::new());
result.structured_content = Some(Value::Object(context.meta.0.0));
Ok(CallToolResponse::Complete(result))
}
}
impl InProcessTransportFactory for MetadataEchoServer {
fn open(&self) -> BoxFuture<'static, io::Result<DuplexStream>> {
let server = self.clone();
async move {
let (client_stream, server_stream) = tokio::io::duplex(4096);
tokio::spawn(async move {
let server = server
.serve(server_stream)
.await
.expect("serve metadata echo");
server.waiting().await
});
Ok(client_stream)
}
.boxed()
}
}
#[derive(Default)]
struct CapturedPolicy(AtomicUsize);
impl NetworkPolicyMetadataProvider for CapturedPolicy {
fn metadata_for_call(
&self,
profile: &PermissionProfile,
environment: &str,
) -> anyhow::Result<NetworkPolicyMetadata> {
assert_eq!(
(profile, environment),
(&PermissionProfile::read_only(), "owner-environment")
);
self.0.fetch_add(1, Ordering::SeqCst);
Ok(NetworkPolicyMetadata {
enabled: false,
mode: NetworkMode::Limited,
allowed_domains: vec!["allowed.example.com".to_string()],
denied_domains: vec!["blocked.example.com".to_string()],
hard_deny_allowlist_misses: true,
})
}
}
#[tokio::test]
async fn tool_calls_deliver_only_negotiated_trusted_network_policy() -> anyhow::Result<()> {
for (url, provider_available, supports_policy, delivers_policy) in [
(Some("https://chatgpt.com/mcp"), true, true, true),
(Some("https://chatgpt.com/mcp"), true, false, false),
(Some("https://chatgpt.com/mcp"), false, true, false),
(Some("https://gov.chatgpt.com/mcp"), true, true, true),
(
Some("https://chatgpt.com.attacker.example/mcp"),
true,
true,
false,
),
(Some("http://chatgpt.com/mcp"), true, true, false),
(Some("https://third-party.example/mcp"), true, true, false),
(None, true, true, false),
] {
let mut server_config = reusable_server_config(url.unwrap_or("https://chatgpt.com/mcp"));
if url.is_none() {
server_config.transport = McpServerTransportConfig::Stdio {
command: "metadata-echo".to_string(),
args: Vec::new(),
env: None,
env_vars: Vec::new(),
cwd: None,
};
}
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"docs".into(),
server_config,
));
let catalog = catalog.build();
let extensions = crate::client_capabilities::server_mcp_extensions(
&ClientMcpExtensions::new([(
MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
json!({"forged": true}),
)]),
"docs",
catalog.server("docs"),
provider_available,
"https://chatgpt.com",
);
let client_supports_policy = extensions
.iter()
.any(|(id, _)| id == MCP_NETWORK_POLICY_META_CAPABILITY);
let client = Arc::new(
RmcpClient::new_in_process_client(Arc::new(MetadataEchoServer { supports_policy }))
.await?,
);
client
.initialize(
crate::rmcp_client::mcp_initialize_request_params(
ElicitationCapability::default(),
extensions,
),
Some(Duration::from_secs(5)),
Box::new(|_, _| async { Err(anyhow!("unexpected elicitation")) }.boxed()),
)
.await?;
let mut managed = create_test_managed_client(vec![create_test_tool("docs", "echo")]).await;
managed.client = Arc::clone(&client);
managed.client_supports_network_policy_meta_capability = client_supports_policy;
let (managed, _started, release) = create_gated_async_managed_client(managed);
release.send(()).expect("release initialized client");
let policy = Arc::new(CapturedPolicy::default());
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
config.permission_profile = PermissionProfile::Disabled;
let sandbox = FileSystemSandboxContext::from_permission_profile(
PermissionProfile::read_only(),
PathUri::from_host_native_path(std::env::temp_dir())?,
);
config.server_permissions.insert(
"docs".to_string(),
McpServerPermissions::Environment(Arc::new(sandbox)),
);
let config = Arc::new(config);
let mut manager = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
manager.config = Some(Arc::clone(&config));
manager.network_policy_metadata =
provider_available.then(|| policy.clone() as Arc<dyn NetworkPolicyMetadataProvider>);
manager.insert_test_client("docs", managed);
let view = manager.servers.get_mut("docs").expect("docs server");
view.metadata.environment_id = "owner-environment".to_string();
let manager = Arc::new(manager);
let binding = manager
.capture_binding_with_metadata(
config,
/*plugins_available*/ false,
/*required_servers*/ &[],
/*required_plugins*/ &HashSet::new(),
)
.await;
let prepared = binding
.prepare_call("docs", "echo")
.expect("prepare advertised tool");
let forged_meta = || {
Some(json!({
"codex/network-policy-meta": {"enabled": true, "forged": true},
"keep": "caller metadata",
}))
};
let mut expected = json!({"keep": "caller metadata"});
if delivers_policy {
expected[MCP_NETWORK_POLICY_META_CAPABILITY] = json!({
"enabled": false,
"mode": "limited",
"allowedDomains": ["allowed.example.com"],
"deniedDomains": ["blocked.example.com"],
"hardDenyAllowlistMisses": true,
});
}
for result in [
prepared
.call(
/*arguments*/ None,
forged_meta(),
/*timeout*/ None,
)
.await?,
manager
.call_tool(
"docs",
"echo",
/*environment_id*/ None,
/*arguments*/ None,
forged_meta(),
/*requested_timeout*/ None,
/*wait_for_server*/ true,
)
.await?,
] {
let mut received = result.structured_content.expect("echoed wire metadata");
received
.as_object_mut()
.expect("metadata object")
.remove("progressToken");
assert_eq!(received, expected);
}
assert_eq!(
policy.0.load(Ordering::SeqCst),
if delivers_policy { 2 } else { 0 }
);
client.shutdown().await;
}
Ok(())
}
#[tokio::test]
async fn recovered_session_policy_keeps_one_captured_call_authority() -> anyhow::Result<()> {
let mut client = create_test_managed_client(Vec::new()).await;
client.client_supports_network_policy_meta_capability = true;
let policy = Arc::new(CapturedPolicy::default());
let mut manager = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
manager.network_policy_metadata = Some(policy.clone());
let profile = PermissionProfile::read_only();
let metadata = manager.network_policy_meta_for_call(
&client,
Some(&profile),
"owner-environment",
Some(json!({"codex/network-policy-meta": {"forged": true}, "keep": "caller"})),
);
let legacy = ServerCapabilities::default();
let mut negotiated = legacy.clone();
negotiated.experimental = Some(std::collections::BTreeMap::from([(
MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
JsonObject::new(),
)]));
assert_eq!(metadata(&legacy)?, Some(json!({"keep": "caller"})));
assert_eq!(policy.0.load(Ordering::SeqCst), 0);
let expected = Some(json!({
"keep": "caller",
"codex/network-policy-meta": {
"enabled": false,
"mode": "limited",
"allowedDomains": ["allowed.example.com"],
"deniedDomains": ["blocked.example.com"],
"hardDenyAllowlistMisses": true,
},
}));
assert_eq!(metadata(&negotiated)?, expected);
assert_eq!(metadata(&legacy)?, Some(json!({"keep": "caller"})));
assert_eq!(metadata(&negotiated)?, expected);
assert_eq!(policy.0.load(Ordering::SeqCst), 1);
let missing_provider = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
let metadata = missing_provider.network_policy_meta_for_call(
&client,
Some(&profile),
"owner-environment",
/*meta*/ None,
);
assert_eq!(metadata(&legacy)?, None);
assert!(
metadata(&negotiated)
.unwrap_err()
.to_string()
.contains("source is unavailable")
);
Ok(())
}

View File

@@ -0,0 +1,71 @@
use std::collections::HashSet;
use anyhow::Result;
use anyhow::anyhow;
use codex_protocol::protocol::McpStartupFailure;
use tracing::Instrument;
use tracing::info_span;
use super::McpConnectionSet;
use crate::rmcp_client::StartupOutcomeError;
impl McpConnectionSet {
/// Waits for required servers unless their readiness policy accepts a cached catalog.
///
/// The manager must already be reachable through [`crate::McpRuntime`] so
/// startup-time elicitation can resolve while validation waits.
pub(crate) async fn validate_required_servers(&self) -> Result<()> {
let failures = async {
self.record_startup_readiness("required_startup", &[], &HashSet::new());
let mut failures = Vec::new();
for server_name in &self.required_servers {
let Some(view) = self.servers.get(server_name) else {
failures.push(McpStartupFailure {
server: server_name.clone(),
error: format!("required MCP server `{server_name}` was not initialized"),
});
continue;
};
if view.allows_cached_startup()
&& view.cached_startup_tools(/*fallback*/ None).is_some()
{
continue;
}
match view.connection.client().await {
Ok(_) => {}
Err(error) => failures.push(McpStartupFailure {
server: server_name.clone(),
error: startup_outcome_error_message(error),
}),
}
}
failures
}
.instrument(info_span!(
"session_init.required_mcp_wait",
otel.name = "session_init.required_mcp_wait",
session_init.required_mcp_server_count = self.required_servers.len(),
))
.await;
if failures.is_empty() {
return Ok(());
}
let details = failures
.iter()
.map(|failure| format!("{}: {}", failure.server, failure.error))
.collect::<Vec<_>>()
.join("; ");
Err(anyhow!(
"required MCP servers failed to initialize: {details}"
))
}
}
fn startup_outcome_error_message(error: StartupOutcomeError) -> String {
match error {
StartupOutcomeError::Cancelled => "MCP startup cancelled".to_string(),
StartupOutcomeError::Failed { error, .. } => error,
}
}

View File

@@ -0,0 +1,283 @@
use super::McpServerConnection;
use crate::CODEX_APPS_MCP_SERVER_NAME;
use crate::McpRuntime;
use codex_rmcp_client::RmcpClient;
use rmcp::model::ServerResult;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::Ordering;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use rmcp::model::Resource;
use rmcp::model::ResourceTemplate;
use tokio::task::JoinSet;
use tracing::warn;
use super::McpConnectionSet;
use crate::pagination::collect_paginated;
use crate::resource_client::McpResourceServerCacheKey;
use crate::rmcp_client::ManagedClient;
impl McpConnectionSet {
pub(crate) fn resource_cache_key(
&self,
server: &str,
generation: u64,
) -> Option<McpResourceServerCacheKey> {
self.servers
.get(server)
.map(|view| McpResourceServerCacheKey {
connection: Arc::downgrade(&view.connection),
generation,
})
}
/// Returns resources from servers selected by `include_server`.
pub async fn list_all_resources(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<Resource>> {
let mut join_set = JoinSet::new();
for (server_name, view) in self
.servers
.iter()
.filter(|(server_name, _)| include_server(server_name))
{
let server_name = server_name.clone();
let Ok(client) = view.connection.client().await else {
continue;
};
let timeout = view.tool_timeout;
join_set.spawn(async move {
let resources = collect_paginated("resources/list", timeout, |params| {
let client = client.clone();
async move {
let response = client.list_resources(params, timeout).await?;
Ok((response.resources, response.next_cursor))
}
})
.await;
(server_name, resources)
});
}
let mut resources = HashMap::new();
while let Some(result) = join_set.join_next().await {
match result {
Ok((server_name, Ok(server_resources))) => {
resources.insert(server_name, server_resources);
}
Ok((server_name, Err(error))) => {
warn!("Failed to list resources for MCP server '{server_name}': {error:#}");
}
Err(error) => {
warn!("Task panic when listing resources for MCP server: {error:#}");
}
}
}
resources
}
/// Returns resource templates from servers selected by `include_server`.
pub async fn list_all_resource_templates(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<ResourceTemplate>> {
let mut join_set = JoinSet::new();
for (server_name, view) in self.servers.iter().filter(|(server_name, _)| {
include_server(server_name) && !self.skips_resource_template_listing(server_name)
}) {
let server_name = server_name.clone();
let Ok(client) = view.connection.client().await else {
continue;
};
let timeout = view.tool_timeout;
join_set.spawn(async move {
let templates = collect_paginated("resources/templates/list", timeout, |params| {
let client = client.clone();
async move {
let response = client.list_resource_templates(params, timeout).await?;
Ok((response.resource_templates, response.next_cursor))
}
})
.await;
(server_name, templates)
});
}
let mut templates = HashMap::new();
while let Some(result) = join_set.join_next().await {
match result {
Ok((server_name, Ok(server_templates))) => {
templates.insert(server_name, server_templates);
}
Ok((server_name, Err(error))) => {
warn!(
"Failed to list resource templates for MCP server '{server_name}': {error:#}"
);
}
Err(error) => {
warn!("Task panic when listing resource templates for MCP server: {error:#}");
}
}
}
templates
}
pub async fn list_resources(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourcesResult> {
let (managed, timeout) = self.client_by_name(server).await?;
managed
.list_resources(params, timeout)
.await
.with_context(|| format!("resources/list failed for `{server}`"))
}
pub async fn list_resource_templates(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourceTemplatesResult> {
let (managed, timeout) = self.client_by_name(server).await?;
managed
.list_resource_templates(params, timeout)
.await
.with_context(|| format!("resources/templates/list failed for `{server}`"))
}
// Hosted Apps always returns an empty list. Resume discovery if it gains templates.
pub(crate) fn skips_resource_template_listing(&self, server: &str) -> bool {
self.contains_server(server)
&& self
.config
.as_ref()
.and_then(|config| config.mcp_server_catalog.server(server))
.is_some_and(|registration| {
registration
.source()
.is_host_owned_apps(server, registration.config())
})
}
pub async fn read_resource(
&self,
server: &str,
params: ReadResourceRequestParams,
) -> Result<ReadResourceResult> {
let (managed, timeout) = self.client_by_name(server).await?;
let uri = params.uri.clone();
managed
.read_resource(params, timeout)
.await
.with_context(|| format!("resources/read failed for `{server}` ({uri})"))
}
pub(crate) fn server_environment_id(&self, server: &str) -> Option<&str> {
self.servers
.get(server)
.map(|view| view.metadata.environment_id.as_str())
}
/// Returns the first Apps startup attempt only while its inventory is pending.
pub(crate) fn early_apps_discovery(
&self,
) -> Option<(&Arc<McpServerConnection>, Option<Duration>)> {
if !self.config.as_ref()?.apps_early_resource_discovery {
return None;
}
let view = self.servers.get(CODEX_APPS_MCP_SERVER_NAME)?;
let connection = &view.connection;
if connection.initialized_apps.is_some()
&& !connection.client.startup_complete.load(Ordering::Acquire)
{
Some((connection, view.tool_timeout))
} else {
None
}
}
pub(crate) async fn client_by_name(
&self,
name: &str,
) -> Result<(ManagedClient, Option<Duration>)> {
let view = self
.servers
.get(name)
.ok_or_else(|| anyhow!("unknown MCP server '{name}'"))?;
let client = view
.connection
.client()
.await
.context("failed to get client")?;
Ok((client, view.tool_timeout))
}
}
impl McpServerConnection {
/// Borrows the authenticated transport while startup owns its inventory. Discard the page
/// if startup fails or the runtime replaces its connection, auth scope, or resource generation.
pub(crate) async fn with_early_apps_client(
self: &Arc<Self>,
runtime: &McpRuntime,
timeout: Option<Duration>,
request: impl AsyncFnOnce(Arc<RmcpClient>, Option<Duration>) -> Result<ServerResult>,
) -> Result<ServerResult> {
let auth = runtime.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME);
let key = runtime
.resource_cache_key(CODEX_APPS_MCP_SERVER_NAME)
.context("Apps registration was removed")?;
anyhow::ensure!(
key.connection.ptr_eq(&Arc::downgrade(self)),
"Apps connection was replaced"
);
let client = self.initialized_apps_client().await?;
let response = tokio::select! {
biased;
_ = self.client.cancel_token.cancelled() => anyhow::bail!("Apps startup cancelled"),
Err(error) = self.client.client.clone() => return Err(error.into()),
response = request(client, timeout) => response?,
};
anyhow::ensure!(
Some(key) == runtime.resource_cache_key(CODEX_APPS_MCP_SERVER_NAME)
&& auth == runtime.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME),
"Apps connection changed during catalog discovery"
);
Ok(response)
}
pub(super) async fn initialized_apps_client(&self) -> Result<Arc<RmcpClient>> {
let mut initialized = self
.initialized_apps
.clone()
.context("Apps discovery is disabled")?;
let initialized_transport = async {
initialized
.wait_for(Option::is_some)
.await
.ok()
.and_then(|value| value.as_ref().and_then(Weak::upgrade))
};
let acquire = async {
tokio::select! {
biased;
ready = self.client.client.clone() => Ok(ready?.client),
Some(client) = initialized_transport => Ok(client),
}
};
tokio::time::timeout(self.startup_timeout, acquire)
.await
.context("timed out waiting for the initialized Apps client")?
}
}

View File

@@ -0,0 +1,143 @@
use std::collections::HashMap;
use anyhow::Result;
use async_channel::Sender;
use codex_api::SharedAuthProvider;
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
use codex_config::McpServerTransportConfig;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::McpStartupFailureReason;
use codex_protocol::protocol::McpStartupUpdateEvent;
use codex_rmcp_client::McpAuthState;
use codex_rmcp_client::McpLoginRequirement;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::rmcp_client::DEFAULT_STARTUP_TIMEOUT;
use crate::rmcp_client::StartupOutcomeError;
use crate::server::EffectiveMcpServer;
/// Makes ChatGPT authentication available to servers that explicitly opt in.
pub(super) fn chatgpt_auth_provider_for_server(
server: &EffectiveMcpServer,
chatgpt_auth_provider: Option<SharedAuthProvider>,
) -> Option<SharedAuthProvider> {
if !matches!(&server.config().auth, McpServerAuth::ChatGpt)
|| !server.config().is_local_environment()
{
return None;
}
chatgpt_auth_provider
}
pub(super) fn should_share_codex_apps_tools_cache(
server_name: &str,
uses_env_bearer_token: bool,
) -> bool {
server_name == CODEX_APPS_MCP_SERVER_NAME && !uses_env_bearer_token
}
pub(super) async fn emit_update(
submit_id: &str,
tx_event: &Sender<Event>,
update: McpStartupUpdateEvent,
) -> Result<(), async_channel::SendError<Event>> {
tx_event
.send(Event {
id: submit_id.to_string(),
msg: EventMsg::McpStartupUpdate(update),
})
.await
}
pub(super) fn mcp_startup_failure_reason(
auth_state: Option<McpAuthState>,
error: &StartupOutcomeError,
) -> Option<McpStartupFailureReason> {
if !error.is_authentication_required() {
return None;
}
if let StartupOutcomeError::Failed {
is_ema_authentication_required: true,
..
} = error
{
return Some(McpStartupFailureReason::ReauthenticationRequired);
}
match auth_state {
Some(
McpAuthState::LoggedOut(McpLoginRequirement::Reauthentication) | McpAuthState::OAuth,
) => Some(McpStartupFailureReason::ReauthenticationRequired),
Some(
McpAuthState::Unsupported
| McpAuthState::Unknown
| McpAuthState::LoggedOut(McpLoginRequirement::Login)
| McpAuthState::BearerToken,
)
| None => None,
}
}
pub(super) fn mcp_init_error_display(
server_name: &str,
config: Option<&McpServerConfig>,
error: &StartupOutcomeError,
reason: Option<McpStartupFailureReason>,
) -> String {
let server_key = if !server_name.is_empty()
&& server_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
server_name.to_string()
} else {
serde_json::Value::String(server_name.to_string()).to_string()
};
if let Some(McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
..
}) = config.map(|config| &config.transport)
&& url == "https://api.githubcopilot.com/mcp/"
&& bearer_token_env_var.is_none()
&& http_headers.as_ref().map(HashMap::is_empty).unwrap_or(true)
{
format!(
"GitHub MCP does not support OAuth. Log in by adding a personal access token (https://github.com/settings/personal-access-tokens) to your environment and config.toml:\n[mcp_servers.{server_key}]\nbearer_token_env_var = CODEX_GITHUB_PERSONAL_ACCESS_TOKEN"
)
} else if error.is_authentication_required() {
let recovery_hint =
if config.is_some_and(|config| matches!(config.auth, McpServerAuth::EmaAuth)) {
"Sign in to your enterprise provider in Codex, then start a new thread.".to_string()
} else if config.is_some_and(|config| !config.is_local_environment()) {
"Use your client's MCP OAuth sign-in flow.".to_string()
} else {
format!("Run `codex mcp login {server_name}`.")
};
let auth_status = match reason {
Some(McpStartupFailureReason::ReauthenticationRequired) => {
"requires OAuth reauthentication"
}
None => "is not logged in",
};
format!("The {server_name} MCP server {auth_status}. {recovery_hint}")
} else if matches!(
error,
StartupOutcomeError::Failed { error, .. }
if error.contains("request timed out")
|| error.contains("timed out handshaking with MCP server")
|| error.contains("MCP client startup timed out")
) {
let startup_timeout_secs = config
.and_then(|config| config.startup_timeout_sec)
.unwrap_or(DEFAULT_STARTUP_TIMEOUT)
.as_secs();
format!(
"MCP client for `{server_name}` timed out after {startup_timeout_secs} seconds. Add or adjust `startup_timeout_sec` in your config.toml:\n[mcp_servers.{server_key}]\nstartup_timeout_sec = XX"
)
} else {
format!("MCP client for `{server_name}` failed to start: {error:#}")
}
}

View File

@@ -0,0 +1,30 @@
//! Read-only connection state; observing a server must not start it.
use std::collections::HashMap;
use codex_protocol::mcp::McpServerConnectionStatus;
use super::McpConnectionSet;
impl McpConnectionSet {
pub(crate) async fn connection_statuses(&self) -> HashMap<String, McpServerConnectionStatus> {
use McpServerConnectionStatus as Status;
let mut statuses = self
.disabled_servers
.iter()
.map(|name| (name.clone(), Status::Disabled))
.collect::<HashMap<_, _>>();
for (name, view) in &self.servers {
let connection = &view.connection;
let client = &connection.client;
let status = if connection.startup_is_dormant() && !client.cancel_token.is_cancelled() {
Status::NotStarted
} else {
client.connection_status().await
};
statuses.insert(name.clone(), status);
}
statuses
}
}

View File

@@ -0,0 +1,817 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_config::McpStartupReadiness;
use codex_connectors::ConnectorRuntimeFetchSource;
use futures::future::join_all;
use tracing::Instrument;
use tracing::instrument;
use tracing::trace;
use tracing::trace_span;
use super::McpConnectionSet;
use super::McpServerMetadata;
use super::catalog_telemetry::emit_binding_catalog;
use super::catalog_telemetry::record_binding_catalog_size;
use super::catalog_telemetry::tool_definition_json_bytes;
use crate::binding::McpBinding;
use crate::binding::PreparedMcpCall;
use crate::binding::PreparedToolInfo;
use crate::binding_clients::McpBindingClients;
use crate::client_tool_catalog::ClientToolCatalogRevision;
use crate::client_tool_catalog::CodexAppsToolSnapshot;
use crate::client_tool_catalog::ToolCatalogSnapshot;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::rmcp_client::CODEX_APPS_REFRESH_DURATION_METRIC;
use crate::rmcp_client::MCP_TOOLS_LIST_DURATION_METRIC;
use crate::rmcp_client::ManagedClient;
use crate::rmcp_client::list_tools_for_client_uncached;
use crate::rmcp_client::prepare_codex_apps_tools_for_model;
use crate::runtime::emit_duration;
use crate::tools::ToolInfo;
use crate::tools::filter_tools;
use crate::tools::normalize_tools_for_model_with_prefix;
const MCP_UI_META_KEY: &str = "ui";
const MCP_UI_VISIBILITY_META_KEY: &str = "visibility";
const MCP_UI_MODEL_VISIBILITY: &str = "model";
/// Returns whether a tool may be included in model-facing tool declarations.
///
/// Tools without visibility metadata remain visible. Tools with visibility
/// metadata are hidden unless they explicitly include `model`.
///
/// <https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#resource-discovery>
pub fn tool_is_model_visible(tool: &ToolInfo) -> bool {
let Some(visibility) = tool
.tool
.meta
.as_deref()
.and_then(|meta| meta.get(MCP_UI_META_KEY))
.and_then(serde_json::Value::as_object)
.and_then(|ui| ui.get(MCP_UI_VISIBILITY_META_KEY))
.and_then(serde_json::Value::as_array)
else {
return true;
};
visibility
.iter()
.any(|target| target.as_str() == Some(MCP_UI_MODEL_VISIBILITY))
}
/// Catalog identity within one published connection set, including cached declarations.
#[derive(Clone, PartialEq, Eq)]
pub(crate) enum BindingCatalogRevision {
Ready(ClientToolCatalogRevision),
Cached(u64),
}
enum PendingCallToolInfo {
BindingCatalog(usize),
Owned(PreparedToolInfo),
}
impl McpConnectionSet {
/// Observes opted-in servers at startup gates without waiting or cloning catalogs.
pub(crate) fn record_startup_readiness(
&self,
phase: &'static str,
required_servers: &[String],
required_plugins: &HashSet<String>,
) {
if !tracing::enabled!(tracing::Level::INFO) {
return;
}
for (server_name, view) in &self.servers {
if view.startup_readiness != McpStartupReadiness::Catalog {
continue;
}
let client = &view.connection.client;
let startup_pending = !client.startup_complete.load(Ordering::Acquire);
let cache_eligible = startup_pending
&& client
.tool_catalog_cache_context
.as_ref()
.is_some_and(|cache| {
cache
.current_revision_if(|tools| view.accepts_cached_tools(tools))
.is_some()
});
let explicitly_required = required_servers.contains(server_name)
|| (self.is_selected_plugin_mcp_server(server_name)
&& self
.plugin_id_for_mcp_server_name(server_name)
.is_some_and(|plugin_id| required_plugins.contains(plugin_id)));
tracing::info!(
event.name = "mcp.startup_readiness",
server_name = %server_name,
phase,
startup_pending,
startup_readiness = "catalog",
cache_eligible,
required = self.required_servers.binary_search(server_name).is_ok(),
explicitly_required,
"MCP startup readiness observed"
);
}
}
pub(crate) async fn stable_catalog_revisions(
&self,
required_servers: &[String],
required_plugins: &HashSet<String>,
) -> Option<HashMap<String, BindingCatalogRevision>> {
let mut revisions = HashMap::new();
for (server_name, view) in &self.servers {
let startup_complete = view
.connection
.client
.startup_complete
.load(Ordering::Acquire);
if !startup_complete
|| (view.startup_readiness == McpStartupReadiness::Catalog
&& view.connection.client.ready_client().is_none())
{
// Explicit requirements still wait for a live connection during capture.
if !view.allows_cached_startup()
|| view.connection.client.cancel_token.is_cancelled()
|| required_servers
.iter()
.any(|required| required == server_name)
|| (self.is_selected_plugin_mcp_server(server_name)
&& self
.plugin_id_for_mcp_server_name(server_name)
.is_some_and(|plugin_id| required_plugins.contains(plugin_id)))
{
return None;
}
let revision = view
.connection
.client
.tool_catalog_cache_context
.as_ref()?
.current_revision_if(|tools| view.accepts_cached_tools(tools))?;
revisions.insert(
server_name.clone(),
BindingCatalogRevision::Cached(revision),
);
continue;
}
let Some(client) = view.connection.client.ready_client() else {
if !view.connection.client.is_codex_apps_mcp_server
&& self.required_servers.binary_search(server_name).is_err()
&& matches!(view.connection.client.client.peek(), Some(Err(_)))
{
continue;
}
return None;
};
if client.client.is_closed().await
|| (view.refresh_tool_list
&& !view.connection.client.is_codex_apps_mcp_server
&& !client
.tool_catalog
.notifications_current(&client.client.tool_list_revision()))
{
return None;
}
let revision = client.tool_catalog.read(|catalog| catalog.revision).await;
revisions.insert(
server_name.clone(),
BindingCatalogRevision::Ready(ClientToolCatalogRevision {
catalog: Arc::clone(&client.tool_catalog),
revision,
}),
);
}
Some(revisions)
}
/// Returns all tools with model-visible names normalized.
pub async fn list_all_tools(&self) -> Vec<ToolInfo> {
Box::pin(self.list_tools_with_errors(|_| true)).await.0
}
#[instrument(level = "trace", skip_all, fields(mcp_server_count = self.servers.len()))]
pub(crate) async fn list_tools_with_errors(
&self,
include_server: impl Fn(&str) -> bool,
) -> (Vec<ToolInfo>, HashMap<String, String>) {
let (tools, errors, _) = self.list_catalogs_with_errors(include_server).await;
(tools, errors)
}
pub(crate) async fn list_catalogs_with_errors(
&self,
include_server: impl Fn(&str) -> bool,
) -> (
Vec<ToolInfo>,
HashMap<String, String>,
HashMap<String, Arc<serde_json::Value>>,
) {
let mut metadata = HashMap::new();
let mut tools = Vec::new();
let mut errors = HashMap::new();
let mut available_server_count = 0;
let mut unavailable_server_count = 0;
let server_results = join_all(
self.servers
.iter()
.filter(|(name, _)| include_server(name))
.map(|(server_name, view)| async move {
view.connection.client.reconnect_failed_startup().await;
let has_cached_tools = view.connection.client.has_cached_tools();
let startup_complete = view
.connection
.client
.startup_complete
.load(Ordering::Acquire);
let server_tools = view
.listed_catalog(server_name, &self.tool_plugin_context)
.instrument(trace_span!(
"list_tools_for_server",
server_name = %server_name,
has_cached_tools,
startup_complete
))
.await;
let result = match server_tools {
Ok((server_tools, meta)) => Ok((
server_tools
.into_iter()
.map(|tool| Self::with_server_metadata(tool, &view.metadata))
.collect::<Vec<_>>(),
meta,
)),
Err(error) => {
trace!(
server_name = %server_name,
has_cached_tools,
startup_complete,
"MCP server tools unavailable while building tool list"
);
Err(error)
}
};
(server_name, result)
}),
)
.await;
for (server_name, server_tools) in server_results {
match server_tools {
Ok((server_tools, meta)) => {
if let Some(meta) = meta {
metadata.insert(server_name.clone(), meta);
}
available_server_count += 1;
tools.extend(server_tools);
}
Err(error) => {
unavailable_server_count += 1;
errors.insert(server_name.clone(), error.to_string());
}
}
}
let tools = normalize_tools_for_model_with_prefix(
tools,
self.prefix_mcp_tool_names,
&self.non_prefixed_mcp_tool_servers,
);
trace!(
available_server_count,
unavailable_server_count,
tool_count = tools.len(),
"built MCP tool list"
);
(tools, errors, metadata)
}
#[instrument(level = "trace", skip_all)]
pub(crate) async fn capture_binding_with_metadata(
self: &Arc<Self>,
config: Arc<crate::McpConfig>,
plugins_available: bool,
required_servers: &[String],
required_plugins: &HashSet<String>,
) -> McpBinding {
let mut listed_tools = Vec::new();
let mut clients = HashMap::new();
let catalog_log_enabled = tracing::enabled!(
target: "codex_otel.trace_safe",
tracing::Level::INFO
);
let catalog_metrics = codex_otel::global();
let catalog_measurement_enabled = catalog_log_enabled || catalog_metrics.is_some();
let product_sku = codex_otel::bounded_product_sku(Some(
config
.apps_mcp_product_sku
.as_deref()
.unwrap_or(crate::mcp::DEFAULT_CODEX_APPS_MCP_PRODUCT_SKU),
))
.unwrap_or("unknown");
let optional_mcp_startup_grace = config.optional_mcp_startup_grace;
let server_snapshots = join_all(self.servers.iter().map(|(server_name, view)| async move {
if !view
.connection
.client
.startup_complete
.load(Ordering::Acquire)
{
let required = self.required_servers.binary_search(server_name).is_ok();
// Keep the catalog that lets us skip startup even if it expires during the wait.
let cached_tools = view.cached_startup_tools(/*fallback*/ None);
let has_cached_tools = cached_tools.is_some();
let must_wait_for_startup = (required
&& (!view.allows_cached_startup() || !has_cached_tools))
|| required_servers
.iter()
.any(|required| required == server_name)
|| (self.is_selected_plugin_mcp_server(server_name)
&& self
.plugin_id_for_mcp_server_name(server_name)
.is_some_and(|plugin_id| required_plugins.contains(plugin_id)))
|| (server_name == CODEX_APPS_MCP_SERVER_NAME && !has_cached_tools);
if !must_wait_for_startup && has_cached_tools {
trace!(server_name = %server_name, "using cached MCP catalog without waiting for startup");
return (server_name, view, cached_tools);
}
if !must_wait_for_startup && optional_mcp_startup_grace.is_zero() {
if let Some(cache) = view.connection.client.tool_catalog_cache_context.as_ref()
{
cache.optional_startup_deadline(
tokio::time::Instant::now(),
optional_mcp_startup_grace,
);
}
let _ = view.connection.client().await;
} else if !must_wait_for_startup {
let optional_startup_deadline = if view.connection.startup_is_dormant() {
tokio::time::Instant::now() + optional_mcp_startup_grace
} else {
*self.optional_startup_deadline.get_or_init(|| {
tokio::time::Instant::now() + optional_mcp_startup_grace
})
};
let startup_deadline = view
.connection
.client
.tool_catalog_cache_context
.as_ref()
.map(|cache| {
cache.optional_startup_deadline(
optional_startup_deadline,
optional_mcp_startup_grace,
)
})
.unwrap_or(optional_startup_deadline);
if tokio::time::timeout_at(startup_deadline, view.connection.client())
.await
.is_err()
{
trace!(server_name = %server_name, "omitting pending optional MCP server");
}
return (server_name, view, cached_tools);
}
let _ = view.connection.client().await;
return (server_name, view, cached_tools);
}
(server_name, view, None)
}))
.await;
let server_results = join_all(server_snapshots.into_iter().map(|(server_name, view, cached_tools)| async move {
let startup_pending = !view
.connection
.client
.startup_complete
.load(Ordering::Acquire);
// A transient Apps startup failure must not remove functions already discovered
// by the model. Keep retrying even when the cached catalog supplies this step.
view.connection.client.reconnect_failed_startup().await;
let accepts_cached_catalog = view.startup_readiness == McpStartupReadiness::Catalog
|| (view.connection.client.is_codex_apps_mcp_server
&& !view.connection.client.cancel_token.is_cancelled());
let cached_tools = if startup_pending
|| (accepts_cached_catalog && view.connection.client.ready_client().is_none())
{
view.cached_startup_tools(cached_tools)
} else {
None
};
let (client, server_tools, catalog_source) = if let Some(cached_tools) = cached_tools {
(None, cached_tools, "cached")
} else {
// A server may opt out of caching after the first pass. Required catalog
// readiness must then wait for discovery rather than silently omit its tools.
if startup_pending
&& !(accepts_cached_catalog
&& self.required_servers.binary_search(server_name).is_ok())
{
return None;
}
let Ok(mut client) = view.connection.client().await else {
trace!(server_name = %server_name, "omitting MCP server without an exact ready client");
return None;
};
view.refresh_notified_catalog(server_name, &client).await;
client.tool_timeout = view.tool_timeout;
let snapshot = client.tool_catalog.read(Arc::new).await;
let server_tools = snapshot.tools.to_vec();
(
Some((Arc::new(client), snapshot)),
server_tools,
"live",
)
};
let raw_definition_json_bytes = if catalog_measurement_enabled {
tool_definition_json_bytes(server_tools.iter().map(|tool| &tool.tool))
} else {
0
};
if catalog_log_enabled {
let plugin_id = self.plugin_id_for_mcp_server_name(server_name);
emit_binding_catalog(
product_sku,
if server_name == CODEX_APPS_MCP_SERVER_NAME {
"codex_apps"
} else if plugin_id.is_some() {
"plugin"
} else {
"configured"
},
plugin_id,
catalog_source,
server_tools.len(),
raw_definition_json_bytes,
);
}
let server_tools = filter_tools(server_tools, &view.tool_filter);
let server_tools = if server_name == CODEX_APPS_MCP_SERVER_NAME {
prepare_codex_apps_tools_for_model(server_tools, &self.tool_plugin_context)
} else {
crate::rmcp_client::prepare_regular_mcp_tools_for_model(
server_tools,
&self.tool_plugin_context,
)
};
let server_tools = server_tools
.into_iter()
.map(|mut tool| {
if client.is_none()
&& let Some(annotations) = tool.tool.annotations.as_mut()
{
annotations.read_only_hint = None;
}
Self::with_server_metadata(tool, &view.metadata)
})
.collect::<Vec<_>>();
Some((
server_name.clone(),
client,
server_tools,
raw_definition_json_bytes,
))
}))
.await;
let mut raw_definition_json_bytes = 0usize;
for (server_name, client, server_tools, server_definition_json_bytes) in
server_results.into_iter().flatten()
{
raw_definition_json_bytes =
raw_definition_json_bytes.saturating_add(server_definition_json_bytes);
if let Some((client, snapshot)) = client {
clients.insert(server_name, (client, snapshot));
}
listed_tools.extend(server_tools);
}
if let Some(metrics) = catalog_metrics.as_ref() {
record_binding_catalog_size(metrics, product_sku, raw_definition_json_bytes);
}
let listed_tools = normalize_tools_for_model_with_prefix(
listed_tools,
self.prefix_mcp_tool_names,
&self.non_prefixed_mcp_tool_servers,
);
let mut tools = Vec::with_capacity(listed_tools.len());
let mut pending_calls = Vec::with_capacity(listed_tools.len());
for tool_info in listed_tools {
let model_visible = crate::tool_is_model_visible(&tool_info);
let Some((client, snapshot)) = clients.get(&tool_info.server_name) else {
if model_visible {
tools.push(tool_info);
}
continue;
};
if config
.permission_profile_for_server(&tool_info.server_name)
.is_none()
{
trace!(
server_name = %tool_info.server_name,
tool_name = %tool_info.tool.name,
"omitting MCP tool without an exact ready client"
);
continue;
}
let pending_tool_info = if model_visible {
let tool_index = tools.len();
tools.push(tool_info);
PendingCallToolInfo::BindingCatalog(tool_index)
} else {
PendingCallToolInfo::Owned(tool_info.into())
};
pending_calls.push((pending_tool_info, Arc::clone(client), Arc::clone(snapshot)));
}
let tools: Arc<[ToolInfo]> = tools.into();
let mut calls = std::collections::HashMap::with_capacity(pending_calls.len());
for (pending_tool_info, client, snapshot) in pending_calls {
let tool_info = match pending_tool_info {
PendingCallToolInfo::BindingCatalog(tool_index) => {
PreparedToolInfo::from_binding_catalog(Arc::clone(&tools), tool_index)
}
PendingCallToolInfo::Owned(tool_info) => tool_info,
};
let Some(call) = self.prepare_call(tool_info, client, Arc::clone(&config), snapshot)
else {
continue;
};
calls.insert(
(
call.server_name().to_string(),
call.tool_info().tool.name.to_string(),
),
call,
);
}
let clients = Arc::new(McpBindingClients::new(
clients
.into_iter()
.map(|(server_name, (client, _))| (server_name, client))
.collect(),
));
McpBinding::new(
Arc::clone(self),
clients,
config,
plugins_available,
tools,
calls,
)
}
#[instrument(level = "trace", skip_all)]
pub(crate) async fn prepare_call_for_tool(
self: &Arc<Self>,
config: Arc<crate::McpConfig>,
advertised_tool: &ToolInfo,
) -> Result<PreparedMcpCall> {
let server_name = &advertised_tool.server_name;
let unavailable = || advertised_tool.unavailable_to_model_error();
let view = self.servers.get(server_name).ok_or_else(unavailable)?;
if !view.tool_filter.allows(&advertised_tool.tool.name) {
return Err(unavailable());
}
// Recovery belongs to readiness, before the caller acquires the tool execution lock.
let mut client = view
.connection
.client()
.await
.with_context(|| format!("Could not start MCP server `{server_name}`"))?;
client.tool_timeout = view.tool_timeout;
let snapshot = client.tool_catalog.read(Arc::new).await;
let current_tool = snapshot
.tools
.iter()
.find(|tool| {
tool.server_name == *server_name
&& tool.tool.name == advertised_tool.tool.name
&& tool.connector_id == advertised_tool.connector_id
})
.ok_or_else(unavailable)?;
let mut tool_info = if server_name == CODEX_APPS_MCP_SERVER_NAME {
prepare_codex_apps_tools_for_model(
vec![current_tool.clone()],
&self.tool_plugin_context,
)
} else {
crate::rmcp_client::prepare_regular_mcp_tools_for_model(
vec![current_tool.clone()],
&self.tool_plugin_context,
)
}
.pop()
.filter(tool_is_model_visible)
.ok_or_else(unavailable)?;
tool_info = Self::with_server_metadata(tool_info, &view.metadata);
// Preserve the globally normalized identity advertised to the model, while
// taking schema, annotations, and approval metadata from the current catalog.
tool_info
.callable_namespace
.clone_from(&advertised_tool.callable_namespace);
tool_info
.callable_name
.clone_from(&advertised_tool.callable_name);
self.prepare_call(tool_info, Arc::new(client), config, snapshot)
.ok_or_else(unavailable)
}
fn prepare_call(
self: &Arc<Self>,
tool_info: impl Into<PreparedToolInfo>,
client: Arc<ManagedClient>,
config: Arc<crate::McpConfig>,
tool_catalog_snapshot: Arc<ToolCatalogSnapshot>,
) -> Option<PreparedMcpCall> {
let tool_info = tool_info.into();
let (server_metadata, plugin_id, selected_plugin_server) = {
let server_name = &tool_info.get().server_name;
let view = self.servers.get(server_name)?;
(
view.metadata.clone(),
self.plugin_id_for_mcp_server_name(server_name)
.map(str::to_string),
self.is_selected_plugin_mcp_server(server_name),
)
};
PreparedMcpCall::new(
Arc::clone(self),
client,
config,
tool_catalog_snapshot,
tool_info,
server_metadata,
plugin_id,
selected_plugin_server,
)
}
/// Refreshes one exact Apps catalog, preserving the raw inventory for app policy.
pub(crate) async fn refresh_codex_apps_client_catalog(
&self,
config: &crate::McpConfig,
) -> Result<CodexAppsToolSnapshot> {
let refresh_start = Instant::now();
let view = self
.servers
.get(CODEX_APPS_MCP_SERVER_NAME)
.ok_or_else(|| anyhow!("unknown MCP server '{CODEX_APPS_MCP_SERVER_NAME}'"))?;
let (tools, _) = self.refresh_codex_apps_tool_catalog().await?;
let server_has_permission = config
.permission_profile_for_server(CODEX_APPS_MCP_SERVER_NAME)
.is_some();
let model_visible_tool_names = tools
.iter()
.filter(|tool| {
server_has_permission
&& view.tool_filter.allows(&tool.tool.name)
&& self
.tool_plugin_context
.allows_connector_id(tool.connector_id.as_deref())
&& tool_is_model_visible(tool)
})
.map(|tool| tool.tool.name.to_string())
.collect();
emit_duration(
CODEX_APPS_REFRESH_DURATION_METRIC,
refresh_start.elapsed(),
&[("path", "legacy"), ("trigger", "explicit")],
);
Ok(CodexAppsToolSnapshot {
tools,
model_visible_tool_names,
})
}
/// Refreshes Apps tools and returns the prepared shared-cache winner for discovery.
pub async fn refresh_codex_apps_tools_for_discovery(&self) -> Result<Vec<ToolInfo>> {
let refresh_start = Instant::now();
let view = self
.servers
.get(CODEX_APPS_MCP_SERVER_NAME)
.ok_or_else(|| anyhow!("unknown MCP server '{CODEX_APPS_MCP_SERVER_NAME}'"))?;
let (_, tools) = self.refresh_codex_apps_tool_catalog().await?;
let tools = prepare_codex_apps_tools_for_model(
filter_tools(tools, &view.tool_filter),
&self.tool_plugin_context,
)
.into_iter()
.map(|tool| Self::with_server_metadata(tool, &view.metadata));
let tools = normalize_tools_for_model_with_prefix(
tools,
self.prefix_mcp_tool_names,
&self.non_prefixed_mcp_tool_servers,
);
emit_duration(
CODEX_APPS_REFRESH_DURATION_METRIC,
refresh_start.elapsed(),
&[("path", "legacy"), ("trigger", "explicit")],
);
Ok(tools)
}
pub(crate) async fn apps_tools_from_mcp_client(&self) -> Vec<ToolInfo> {
let Some(client) = self
.servers
.get(crate::CODEX_APPS_MCP_SERVER_NAME)
.filter(|view| {
view.connection
.client
.codex_apps_tools_cache_context
.is_none()
})
.and_then(|view| view.connection.client.ready_client())
else {
return Vec::new();
};
client
.tool_catalog
.read(|catalog| catalog.tools.to_vec())
.await
}
/// Publishes the exact client catalog and returns both raw inventories.
async fn refresh_codex_apps_tool_catalog(&self) -> Result<(Vec<ToolInfo>, Vec<ToolInfo>)> {
let view = self
.servers
.get(CODEX_APPS_MCP_SERVER_NAME)
.ok_or_else(|| anyhow!("unknown MCP server '{CODEX_APPS_MCP_SERVER_NAME}'"))?;
let managed_client = view
.connection
.client()
.await
.context("failed to get client")?;
let (tools, list_start) = managed_client
.tool_catalog
.refresh(
|| async {
let list_start = Instant::now();
let fetch_ticket = managed_client.codex_apps_tools_cache_context.as_ref().map(
|cache_context| {
cache_context.begin_fetch(ConnectorRuntimeFetchSource::HardRefresh)
},
);
let (client_tools, meta) = list_tools_for_client_uncached(
CODEX_APPS_MCP_SERVER_NAME,
/*is_codex_apps_mcp_server*/ true,
/*codex_apps_refresh_trigger*/ "explicit",
&managed_client.client,
view.tool_timeout,
view.catalog_item_limit,
managed_client.server_instructions.as_deref(),
)
.await
.with_context(|| {
format!(
"failed to refresh tools for MCP server '{CODEX_APPS_MCP_SERVER_NAME}'"
)
})?;
Ok((client_tools, meta, (fetch_ticket, list_start)))
},
|client_tools, meta, (fetch_ticket, list_start)| {
// Discovery can accept another scope's winner; executable catalogs
// receive only the latest successful fetch from their own scope.
let tools = match (
managed_client.codex_apps_tools_cache_context.as_ref(),
fetch_ticket,
) {
(Some(cache_context), Some(fetch_ticket)) => cache_context
.publish_runtime_if_newest_accepted(
fetch_ticket,
&managed_client.server_info,
client_tools.to_vec(),
meta,
)
.tools()
.to_vec(),
(None, None) => client_tools.to_vec(),
_ => unreachable!("Codex Apps fetch ticket requires cache context"),
};
(tools, list_start)
},
)
.await?;
let client_tools = managed_client
.tool_catalog
.read(|catalog| catalog.tools.to_vec())
.await;
emit_duration(
MCP_TOOLS_LIST_DURATION_METRIC,
list_start.elapsed(),
&[("cache", "miss")],
);
Ok((client_tools, tools))
}
fn with_server_metadata(mut tool: ToolInfo, metadata: &McpServerMetadata) -> ToolInfo {
tool.supports_parallel_tool_calls = metadata.supports_parallel_tool_calls;
tool.server_origin = metadata
.origin
.as_ref()
.map(|origin| origin.as_str().to_string());
tool
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,574 @@
//! Shares MCP 2026-07-28 connections while keeping each chat's ownership separate.
//!
//! The protocol requires request-scoped context and explicit handles for application state.
//! Request continuations use the calling chat's elicitation authority. Legacy connections and
//! servers that request input during startup remain private.
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::Weak;
use std::time::Duration;
use codex_async_utils::OrCancelExt;
use codex_connectors::ConnectorRuntimeContextKey;
use codex_login::AuthChangeState;
use codex_login::AuthManager;
use codex_rmcp_client::ElicitationResponse;
use codex_rmcp_client::RequestScope;
use codex_rmcp_client::RmcpClient;
use codex_rmcp_client::SendElicitation;
use futures::FutureExt;
use futures::future::BoxFuture;
use futures::future::Shared;
use rmcp::model::ElicitationAction;
use rmcp::model::ProtocolVersion;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use uuid::Uuid;
use crate::client_tool_catalog::ClientToolCatalog;
use crate::client_tool_catalog::ToolCatalogSnapshot;
use crate::rmcp_client::ManagedClient;
use crate::rmcp_client::ManagedClientFuture;
use crate::rmcp_client::StartupOutcomeError;
use crate::rmcp_client::list_tools_for_client_uncached;
use crate::server::McpServerConnectionIdentity;
use crate::tool_catalog_cache::McpToolCatalogCacheContext;
/// Opt-in resource lifecycle for negotiated stdio connections. Tool calls and resource reads
/// carry a host-owned lease ID. Catalog requests remain independent of a particular lease.
pub(crate) const LEASE_CAPABILITY: &str = "codex/connection-lease";
/// Request metadata set by the host when a connection lease is negotiated.
pub const LEASE_META_KEY: &str = "codex/connectionLease";
const LEASE_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone)]
pub(crate) struct ServerLease {
pub(crate) id: Uuid,
pub(crate) requests: RequestScope,
opened: Shared<BoxFuture<'static, Result<(), StartupOutcomeError>>>,
}
impl ServerLease {
async fn release(self, client: &RmcpClient, entry: &Arc<Entry>) {
if self.opened.await.is_err() {
return;
}
// MCP cancellation has no acknowledgement. The server owns any handler still
// winding down after it receives these cancellation writes and then release.
self.requests.cancel_and_wait().await;
if let Err(error) = client
.send_custom_request(
"codex/connection/release",
Some(serde_json::json!({"leaseId": self.id})),
)
.await
{
entry.remove_from_pool();
tracing::warn!(%error, "failed to release a server-side MCP lease");
}
}
}
/// Process-owned registry for compatible local stdio servers using MCP 2026-07-28.
#[derive(Clone, Default)]
pub struct McpConnectionPool {
entries: Arc<Mutex<Vec<Weak<Entry>>>>,
}
#[derive(Clone)]
pub(crate) struct ConnectionKey {
pub(crate) server_name: String,
pub(crate) identity: McpServerConnectionIdentity,
pub(crate) account: ConnectorRuntimeContextKey,
pub(crate) auth_state: Option<(Arc<AuthManager>, AuthChangeState)>,
pub(crate) startup_timeout: Duration,
pub(crate) catalog_item_limit: usize,
}
impl PartialEq for ConnectionKey {
fn eq(&self, other: &Self) -> bool {
self.server_name == other.server_name
&& self.identity == other.identity
&& self.account == other.account
&& self.startup_timeout == other.startup_timeout
&& self.catalog_item_limit == other.catalog_item_limit
&& match (&self.auth_state, &other.auth_state) {
(Some((left, left_state)), Some((right, right_state))) => {
Arc::ptr_eq(left, right)
&& left_state.owner_generation == right_state.owner_generation
&& left_state.source_generation == right_state.source_generation
&& left_state.login_generation == right_state.login_generation
}
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
}
}
}
struct Entry {
runtime: tokio::runtime::Handle,
key: ConnectionKey,
client: ManagedClientFuture,
capabilities: Arc<Mutex<Option<serde_json::Value>>>,
// Share immutable definitions; every chat owns its catalog revisions and refresh locks.
catalog: Mutex<Option<ToolCatalogSnapshot>>,
cancellation: CancellationToken,
/// Wakes joiners without cancelling the creator's startup.
sharing_declined: CancellationToken,
owners: Weak<LeaseOwners>,
pool: Weak<Mutex<Vec<Weak<Entry>>>>,
}
/// One strong reference per active chat lease, independent of retained client bindings.
/// Every strong reference must be consumed by `ConnectionLease::release`.
struct LeaseOwners;
#[derive(Clone, Copy, PartialEq, Eq)]
enum AcquisitionRole {
Creator,
Joiner,
}
impl Entry {
fn remove_from_pool(self: &Arc<Self>) {
if let Some(pool) = self.pool.upgrade() {
pool.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.retain(|entry| !entry.ptr_eq(&Arc::downgrade(self)));
}
}
async fn tool_catalog_for_chat(
&self,
client: &ManagedClient,
role: AcquisitionRole,
cache_context: Option<&McpToolCatalogCacheContext>,
) -> Result<Arc<ClientToolCatalog>, StartupOutcomeError> {
// Listing must not update another chat's catalog or wait for its calls.
let listed = if role == AcquisitionRole::Creator {
client.tool_catalog.read(|snapshot| snapshot).await
} else {
let fetch_ticket = cache_context.map(|context| (context, context.begin_fetch()));
let (tools, meta) = list_tools_for_client_uncached(
&self.key.server_name,
self.key.server_name == crate::CODEX_APPS_MCP_SERVER_NAME,
"shared_connection",
&client.client,
Some(self.key.startup_timeout),
self.key.catalog_item_limit,
client.server_instructions.as_deref(),
)
.await?;
if let Some((context, mut ticket)) = fetch_ticket {
if context.track_tool_list_changes {
ticket.tool_list_revision = Some(client.client.tool_list_revision());
}
context.publish_if_newest(ticket, &tools, meta.clone());
}
ToolCatalogSnapshot {
revision: 0,
tools: tools.into(),
meta,
}
};
let mut catalog = self
.catalog
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let catalog = catalog.get_or_insert_with(|| listed.clone());
if catalog.tools != listed.tools || catalog.meta != listed.meta {
*catalog = listed;
}
Ok(Arc::new(ClientToolCatalog::new(
Arc::clone(&catalog.tools),
catalog.meta.clone(),
/*updates*/ None,
)))
}
}
/// A chat releases its lease explicitly on shutdown, even while bindings retain its client.
pub(crate) struct ConnectionLease {
entry: Arc<Entry>,
owner: Mutex<Option<Arc<LeaseOwners>>>,
cancellation: CancellationToken,
slot: Arc<ConnectionSlot>,
server_lease: OnceLock<ServerLease>,
}
/// Tracks an acquisition without retaining its lease, including before startup completes.
#[derive(Default)]
pub(crate) struct ConnectionSlot {
state: Mutex<SlotState>,
shutdown_tasks: OnceLock<TaskTracker>,
}
#[derive(Default)]
enum SlotState {
#[default]
Available,
Acquired(Weak<Entry>),
Retired,
}
impl ConnectionSlot {
pub(crate) fn retire(&self) {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let SlotState::Acquired(entry) = std::mem::replace(&mut *state, SlotState::Retired)
&& let Some(entry) = entry.upgrade()
{
entry.remove_from_pool();
}
}
pub(crate) async fn wait_for_shutdown(&self) {
if let Some(tasks) = self.shutdown_tasks.get() {
tasks.close();
tasks.wait().await;
}
}
}
#[derive(Clone, Default)]
pub(crate) enum ConnectionSharing {
#[default]
Private,
Negotiated,
/// The server declined sharing, but its creator still owns the startup entry.
Owned(Arc<ConnectionLease>),
Shared(Arc<ConnectionLease>),
}
impl ConnectionSharing {
/// Identifies this chat to servers that negotiated per-chat leases.
pub(crate) fn server_lease(&self) -> Option<&ServerLease> {
match self {
Self::Shared(lease) => lease.server_lease.get(),
_ => None,
}
}
}
impl McpConnectionPool {
pub(crate) async fn connect(
&self,
slot: Arc<ConnectionSlot>,
key: ConnectionKey,
capabilities: Arc<Mutex<Option<serde_json::Value>>>,
tool_catalog_cache_context: Option<McpToolCatalogCacheContext>,
cancellation: CancellationToken,
start: impl Fn(CancellationToken, Option<CancellationToken>) -> ManagedClientFuture + Sync,
) -> Result<ManagedClient, StartupOutcomeError> {
let (lease, role) = self
.acquire(key, &slot, Arc::clone(&capabilities), &cancellation, &start)
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
let outcome = tokio::select! {
outcome = lease.entry.client.clone() => Some(outcome),
() = lease.entry.sharing_declined.cancelled(), if role == AcquisitionRole::Joiner => None,
() = cancellation.cancelled() => return Err(StartupOutcomeError::Cancelled),
};
match outcome {
Some(Ok(mut client))
if role == AcquisitionRole::Creator
|| matches!(client.connection_sharing, ConnectionSharing::Negotiated) =>
{
let shared_capabilities = lease
.entry
.capabilities
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let server_tracks_leases = shared_capabilities
.as_ref()
.and_then(|caps| caps.get("extensions"))
.and_then(|caps| caps.get(LEASE_CAPABILITY))
.is_some();
*capabilities
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = shared_capabilities;
client.connection_sharing =
if matches!(client.connection_sharing, ConnectionSharing::Negotiated) {
client.client.enable_request_cancellation();
client.tool_catalog = lease
.entry
.tool_catalog_for_chat(
&client,
role,
tool_catalog_cache_context.as_ref(),
)
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
if server_tracks_leases {
lease
.open_on_server(Arc::clone(&client.client))
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
}
ConnectionSharing::Shared(lease)
} else {
lease.entry.remove_from_pool();
ConnectionSharing::Owned(lease)
};
Ok(client)
}
Some(Err(error)) if role == AcquisitionRole::Creator => Err(error),
_ => {
// Older or failed servers leave other chats to initialize privately
// with their own elicitation authority.
drop(lease);
start(cancellation, /*sharing_declined*/ None).await
}
}
}
async fn acquire(
&self,
key: ConnectionKey,
slot: &Arc<ConnectionSlot>,
capabilities: Arc<Mutex<Option<serde_json::Value>>>,
cancellation: &CancellationToken,
start: impl Fn(CancellationToken, Option<CancellationToken>) -> ManagedClientFuture,
) -> Result<(Arc<ConnectionLease>, AcquisitionRole), StartupOutcomeError> {
loop {
let (lease, role) = {
let mut state = slot
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if matches!(&*state, SlotState::Retired) {
return Err(StartupOutcomeError::Cancelled);
}
let mut entries = self
.entries
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
entries.retain(|entry| entry.strong_count() > 0);
let lease_cancellation = cancellation.child_token();
let existing = entries
.iter()
.filter_map(Weak::upgrade)
.filter(|entry| {
entry.key == key
&& !entry.sharing_declined.is_cancelled()
&& entry.client.peek().is_none_or(|result| {
result.as_ref().is_ok_and(|client| {
matches!(
client.connection_sharing,
ConnectionSharing::Negotiated
)
})
})
})
.find_map(|entry| entry.owners.upgrade().map(|owner| (entry, owner)));
let (entry, owner, role) = if let Some((entry, owner)) = existing {
(entry, owner, AcquisitionRole::Joiner)
} else {
let startup_cancellation = CancellationToken::new();
let sharing_declined = CancellationToken::new();
let client =
start(startup_cancellation.clone(), Some(sharing_declined.clone()));
// Startup belongs to the connection, including if its first chat is cancelled.
tokio::spawn(client.clone());
let owner = Arc::new(LeaseOwners);
let entry = Arc::new(Entry {
runtime: tokio::runtime::Handle::current(),
key: key.clone(),
client,
capabilities: Arc::clone(&capabilities),
catalog: Mutex::new(None),
cancellation: startup_cancellation,
sharing_declined,
owners: Arc::downgrade(&owner),
pool: Arc::downgrade(&self.entries),
});
entries.push(Arc::downgrade(&entry));
(entry, owner, AcquisitionRole::Creator)
};
let lease = Arc::new(ConnectionLease {
entry,
owner: Mutex::new(Some(owner)),
cancellation: lease_cancellation,
slot: Arc::clone(slot),
server_lease: OnceLock::new(),
});
*state = SlotState::Acquired(Arc::downgrade(&lease.entry));
(lease, role)
};
if let Some(Ok(client)) = lease.entry.client.peek()
&& client.client.is_closed().await
{
lease.entry.remove_from_pool();
lease.release();
continue;
}
return Ok((lease, role));
}
}
}
impl ConnectionLease {
pub(crate) fn cancellation(&self) -> &CancellationToken {
&self.cancellation
}
/// Register a unique logical owner before publishing the chat's client. Release retains
/// the same future so cancellation during open cannot reorder the two lifecycle requests.
async fn open_on_server(&self, client: Arc<RmcpClient>) -> Result<(), StartupOutcomeError> {
let id = Uuid::new_v4();
let opened = async move {
client
.send_custom_request(
"codex/connection/open",
Some(serde_json::json!({"leaseId": id})),
)
.await
.map(|_| ())
.map_err(StartupOutcomeError::from)
}
.boxed()
.shared();
let opened = {
// Publish while we still own the lease so a racing unload will wait for this open.
let owner = self
.owner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if owner.is_none() {
return Err(StartupOutcomeError::Cancelled);
}
self.server_lease
.get_or_init(|| ServerLease {
id,
opened,
requests: RequestScope::new(
self.entry.runtime.clone(),
self.cancellation.clone(),
),
})
.opened
.clone()
};
// Bound chat startup while preserving the actual reply for a racing release.
tokio::time::timeout(LEASE_REQUEST_TIMEOUT, opened)
.await
.map_err(|_| {
self.entry.remove_from_pool();
anyhow::anyhow!("timed out waiting for the MCP server to open a connection lease")
})?
}
/// Track this chat's server-side release or the final shutdown of the physical connection.
pub(crate) fn release(&self) -> Option<&ConnectionSlot> {
self.cancellation.cancel();
let mut owner = self
.owner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let server_lease = if Arc::into_inner(owner.take()?).is_some() {
self.entry.cancellation.cancel();
self.entry.remove_from_pool();
None
} else {
Some(self.server_lease.get()?.clone())
};
let entry = Arc::clone(&self.entry);
// The chat must be able to await its final release even when cancellation drops the lease.
let tasks = self.slot.shutdown_tasks.get_or_init(TaskTracker::new);
let completion = tasks.token();
self.entry.runtime.spawn(async move {
match (entry.client.clone().await, server_lease) {
(Ok(client), None) => client.client.shutdown().await,
(Ok(client), Some(lease)) => {
let release = lease
.release(&client.client, &entry)
.or_cancel(&entry.cancellation);
tokio::pin!(release);
if tokio::time::timeout(LEASE_REQUEST_TIMEOUT, &mut release)
.await
.is_err()
{
// Let the chat unload. A late open reply or cancellation write
// must still precede release while other chats own the connection.
entry.remove_from_pool();
drop(completion);
let _ = release.await;
}
}
(Err(error), _) => error.wait_for_shutdown().await,
}
});
Some(&self.slot)
}
}
impl Drop for ConnectionLease {
fn drop(&mut self) {
let _ = self.release();
}
}
/// Releases waiting chats when startup becomes private and detaches callbacks after sharing.
pub(crate) struct SharingNegotiation {
callback: Arc<Mutex<Option<SendElicitation>>>,
sharing_declined: CancellationToken,
}
impl SharingNegotiation {
pub(crate) fn new(
sender: SendElicitation,
sharing_declined: CancellationToken,
) -> (Self, SendElicitation) {
let callback = Arc::new(Mutex::new(Some(sender)));
let negotiation = Self {
callback: Arc::clone(&callback),
sharing_declined: sharing_declined.clone(),
};
let sender: SendElicitation = Box::new(move |id, request| {
let callback = callback
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(callback) = callback.as_ref() {
// Client input binds this startup to its original chat.
sharing_declined.cancel();
callback(id, request)
} else {
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: None,
}))
.boxed()
}
});
(negotiation, sender)
}
pub(crate) fn finish(self, protocol_version: &ProtocolVersion) -> ConnectionSharing {
let mut callback = self
.callback
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if *protocol_version == ProtocolVersion::V_2026_07_28
&& !self.sharing_declined.is_cancelled()
{
callback.take();
ConnectionSharing::Negotiated
} else {
self.sharing_declined.cancel();
ConnectionSharing::Private
}
}
}
#[cfg(test)]
#[path = "connection_pool_tests.rs"]
pub(crate) mod tests;

View File

@@ -0,0 +1,857 @@
//! Tests for shared MCP connection ownership and protocol negotiation.
use super::*;
use crate::McpServerPermissions;
use crate::binding_clients::McpBindingClients;
use crate::connection_manager::tests::create_ready_async_managed_client;
use crate::connection_manager::tests::create_test_tool;
use crate::connection_manager::tests::reusable_server_identity;
use crate::runtime::McpRuntimeContext;
use codex_config::McpServerConfig;
use codex_exec_server::EnvironmentManager;
use codex_login::CodexAuth;
use codex_rmcp_client::Elicitation;
use codex_rmcp_client::InProcessTransportFactory;
use codex_rmcp_client::RmcpClient;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use rmcp::ServerHandler;
use rmcp::ServiceExt;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::ListToolsResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ProtocolVersion;
use rmcp::model::ServerCapabilities;
use rmcp::model::ServerConfig;
use rmcp::model::Tool;
use rmcp::service::RequestContext;
use rmcp::service::RoleServer;
use serde_json::json;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::sync::Notify;
use tokio::sync::Semaphore;
use tokio::sync::mpsc;
#[derive(Clone)]
pub(crate) struct TestServer {
tools: Arc<Mutex<Vec<Tool>>>,
block_listing: Arc<AtomicBool>,
started_listings: Arc<Semaphore>,
cancelled_listings: Arc<Semaphore>,
}
impl Default for TestServer {
fn default() -> Self {
Self {
tools: Arc::new(Mutex::new(vec![
create_test_tool("test_server", "test").tool,
])),
block_listing: Arc::default(),
started_listings: Arc::new(Semaphore::new(/*permits*/ 0)),
cancelled_listings: Arc::new(Semaphore::new(/*permits*/ 0)),
}
}
}
impl ServerHandler for TestServer {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_tools()
.enable_resources()
.build(),
)
}
async fn call_tool(
&self,
_request: rmcp::model::CallToolRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
Ok(rmcp::model::CallToolResult::success(Vec::new()).into())
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, rmcp::ErrorData> {
if self.block_listing.load(Ordering::Acquire) {
context.ct.cancelled().await;
self.cancelled_listings.add_permits(1);
return Err(rmcp::ErrorData::internal_error(
"listing cancelled",
/*data*/ None,
));
}
Ok(ListToolsResult::with_all_items(
self.tools.lock().unwrap().clone(),
))
}
async fn list_resources(
&self,
_request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> Result<ListResourcesResult, rmcp::ErrorData> {
if self.block_listing.load(Ordering::Acquire) {
self.started_listings.add_permits(1);
context.ct.cancelled().await;
self.cancelled_listings.add_permits(1);
}
Ok(ListResourcesResult::with_all_items(Vec::new()))
}
async fn list_resource_templates(
&self,
_request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> Result<ListResourceTemplatesResult, rmcp::ErrorData> {
if self.block_listing.load(Ordering::Acquire) {
self.started_listings.add_permits(1);
context.ct.cancelled().await;
self.cancelled_listings.add_permits(1);
}
Ok(ListResourceTemplatesResult::with_all_items(Vec::new()))
}
}
impl InProcessTransportFactory for TestServer {
fn open(&self) -> BoxFuture<'static, std::io::Result<tokio::io::DuplexStream>> {
let server = self.clone();
async move {
let (client, transport) = tokio::io::duplex(4096);
tokio::spawn(async move {
server
.serve(transport)
.await
.unwrap()
.waiting()
.await
.unwrap();
});
Ok(client)
}
.boxed()
}
}
pub(crate) fn key(context: &McpRuntimeContext, config: &McpServerConfig) -> ConnectionKey {
ConnectionKey {
server_name: "test_server".to_string(),
identity: reusable_server_identity("test_server", config, context),
account: ConnectorRuntimeContextKey::personal(
/*account_id*/ None, /*chatgpt_user_id*/ None,
),
auth_state: None,
startup_timeout: Duration::from_secs(30),
catalog_item_limit: 100,
}
}
pub(crate) fn context() -> McpRuntimeContext {
McpRuntimeContext::new(
Arc::new(EnvironmentManager::default_for_tests()),
std::env::temp_dir(),
)
}
pub(crate) fn config() -> McpServerConfig {
serde_json::from_value(json!({"command": "test-server", "args": ["server.mjs"]})).unwrap()
}
pub(crate) fn startup(
sharing: ConnectionSharing,
starts: Arc<AtomicUsize>,
first_started: Arc<Notify>,
release_first: Arc<Notify>,
server: impl InProcessTransportFactory + Clone + 'static,
) -> impl Fn(CancellationToken, Option<CancellationToken>) -> ManagedClientFuture {
move |cancellation, _sharing_declined| {
let sharing = sharing.clone();
let starts = Arc::clone(&starts);
let first_started = Arc::clone(&first_started);
let release_first = Arc::clone(&release_first);
let server = server.clone();
async move {
async {
if starts.fetch_add(1, Ordering::SeqCst) == 0 {
first_started.notify_one();
release_first.notified().await;
}
let mut client = create_ready_async_managed_client(Vec::new())
.await
.client()
.await?;
client.client = Arc::new(
RmcpClient::new_in_process_client(Arc::new(server))
.await
.expect("create test MCP client"),
);
client
.client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("test", "1"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(30)),
Box::new(|_, _| {
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
}))
.boxed()
}),
)
.await?;
let (tools, meta) = list_tools_for_client_uncached(
"test_server",
/*is_codex_apps_mcp_server*/ false,
"test",
&client.client,
/*timeout*/ None,
/*catalog_item_limit*/ 100,
/*server_instructions*/ None,
)
.await?;
client.tool_catalog =
Arc::new(ClientToolCatalog::new(tools, meta, /*updates*/ None));
client.connection_sharing = sharing;
Ok(client)
}
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))
}
.boxed()
.shared()
}
}
struct LeaseFrame {
message: serde_json::Value,
replies: mpsc::UnboundedSender<serde_json::Value>,
}
impl LeaseFrame {
fn reply(&self, result: serde_json::Value) {
self.replies
.send(json!({"jsonrpc": "2.0", "id": self.message["id"], "result": result}))
.unwrap();
}
}
#[derive(Clone)]
struct LeaseTransport(mpsc::UnboundedSender<LeaseFrame>);
impl InProcessTransportFactory for LeaseTransport {
fn open(&self) -> BoxFuture<'static, std::io::Result<tokio::io::DuplexStream>> {
let (client, server) = tokio::io::duplex(4096);
let (reader, mut writer) = tokio::io::split(server);
let mut lines = BufReader::new(reader).lines();
let frames = self.0.clone();
let (replies, mut responses) = mpsc::unbounded_channel();
tokio::spawn(async move {
loop {
tokio::select! {
Some(response) = responses.recv() => {
writer.write_all(format!("{response}\n").as_bytes()).await.unwrap();
}
line = lines.next_line() => {
let Some(line) = line.unwrap() else { break };
let frame = LeaseFrame {
message: serde_json::from_str(&line).unwrap(),
replies: replies.clone(),
};
match frame.message["method"].as_str().unwrap() {
"initialize" => frame.reply(json!({
"protocolVersion": "2025-06-18", "capabilities": {"tools": {}},
"serverInfo": {"name": "test", "version": "1"}
})),
"notifications/initialized" => {}
"tools/list" => frame.reply(json!({"tools": []})),
_ => frames.send(frame).unwrap(),
}
}
}
}
});
futures::future::ready(Ok(client)).boxed()
}
}
struct LeasePeer {
pool: McpConnectionPool,
key: ConnectionKey,
transport: LeaseTransport,
frames: mpsc::UnboundedReceiver<LeaseFrame>,
}
impl LeasePeer {
fn new() -> Self {
let (tx, frames) = mpsc::unbounded_channel();
Self {
pool: McpConnectionPool::default(),
key: key(&context(), &config()),
transport: LeaseTransport(tx),
frames,
}
}
fn attach(&self) -> tokio::task::JoinHandle<Result<ManagedClient, StartupOutcomeError>> {
let pool = self.pool.clone();
let key = self.key.clone();
let transport = self.transport.clone();
tokio::spawn(async move {
let ready = Arc::<Notify>::default();
ready.notify_one();
let launch = startup(
ConnectionSharing::Negotiated,
Arc::default(),
Arc::default(),
ready,
transport,
);
pool.connect(
Arc::default(),
key,
Arc::new(Mutex::new(Some(
json!({"extensions": {LEASE_CAPABILITY: {}}}),
))),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
launch,
)
.await
})
}
async fn next(&mut self, method: &str) -> LeaseFrame {
let frame = tokio::time::timeout(Duration::from_secs(2), self.frames.recv())
.await
.expect("expected a frame from the client")
.unwrap();
assert_eq!(frame.message["method"], method);
frame
}
async fn chat(&mut self) -> (ManagedClient, serde_json::Value) {
let attach = self.attach();
let open = self.next("codex/connection/open").await;
open.reply(json!({}));
(
attach.await.unwrap().unwrap(),
open.message["params"]["leaseId"].clone(),
)
}
}
#[tokio::test(start_paused = true)]
async fn releasing_lease_cancels_pending_call_before_release() {
let mut peer = LeasePeer::new();
let (first, first_id) = peer.chat().await;
let (other, other_id) = peer.chat().await;
let call = first.call_tool(
"wait".into(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
);
tokio::pin!(call);
let request = tokio::select! {
result = &mut call => panic!("call completed without a reply: {result:?}"),
frame = peer.next("tools/call") => frame,
};
let ConnectionSharing::Shared(lease) = &first.connection_sharing else {
panic!("expected shared lease")
};
lease.release();
// Leave the caller unpolled: the release must drive the cancellation write itself.
let cancel = peer.next("notifications/cancelled").await;
assert_eq!(cancel.message["params"]["requestId"], request.message["id"]);
let release = peer.next("codex/connection/release").await;
assert_eq!(release.message["params"]["leaseId"], first_id);
release.reply(json!({}));
assert!(call.await.is_err());
let (result, ()) = tokio::join!(
other.call_tool(
"test".into(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
),
async {
let request = peer.next("tools/call").await;
assert_eq!(request.message["params"]["_meta"][LEASE_META_KEY], other_id);
request.reply(json!({"content": []}));
}
);
result.unwrap();
}
#[tokio::test(start_paused = true)]
async fn dropping_lease_outside_runtime_releases_it() {
let mut peer = LeasePeer::new();
let (_other, _) = peer.chat().await;
let (chat, id) = peer.chat().await;
std::thread::spawn(move || drop(chat)).join().unwrap();
let release = peer.next("codex/connection/release").await;
assert_eq!(release.message["params"]["leaseId"], id);
release.reply(json!({}));
}
#[tokio::test(start_paused = true)]
async fn timed_out_open_is_released_after_the_server_acknowledges_it() {
let mut peer = LeasePeer::new();
let (_other, _) = peer.chat().await;
let attach = peer.attach();
let open = peer.next("codex/connection/open").await;
tokio::time::advance(LEASE_REQUEST_TIMEOUT).await;
assert!(attach.await.unwrap().is_err());
assert!(
tokio::time::timeout(Duration::from_secs(1), peer.frames.recv())
.await
.is_err()
);
open.reply(json!({}));
let release = peer.next("codex/connection/release").await;
assert_eq!(
release.message["params"]["leaseId"],
open.message["params"]["leaseId"]
);
release.reply(json!({}));
}
#[tokio::test]
async fn shared_startup_survives_first_chat_cancellation_and_rejects_released_bindings() {
let pool = McpConnectionPool::default();
let key = key(&context(), &config());
let server = TestServer::default();
let starts = Arc::new(AtomicUsize::new(0));
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let launch = startup(
ConnectionSharing::Negotiated,
Arc::clone(&starts),
Arc::clone(&started),
Arc::clone(&release),
server.clone(),
);
let first_cancel = CancellationToken::new();
let first = pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
first_cancel.clone(),
&launch,
);
let second = pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
);
tokio::pin!(first, second);
assert!(futures::poll!(&mut first).is_pending());
assert!(futures::poll!(&mut second).is_pending());
started.notified().await;
first_cancel.cancel();
assert!(matches!(first.await, Err(StartupOutcomeError::Cancelled)));
release.notify_one();
let client = second.await.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 1);
assert!(!client.client.is_closed().await);
let other = pool
.connect(
Arc::default(),
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
)
.await
.unwrap();
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
config
.server_permissions
.insert("test_server".to_string(), McpServerPermissions::Thread);
let prepared = crate::binding::PreparedMcpCall::new(
Arc::new(crate::connection_manager::McpConnectionSet::empty(
/*prefix_mcp_tool_names*/ true,
)),
Arc::new(client.clone()),
Arc::new(config),
client.tool_catalog.read(Arc::new).await,
create_test_tool("test_server", "test"),
crate::server::McpServerMetadata {
environment_id: "local".to_string(),
pollutes_memory: false,
origin: None,
supports_parallel_tool_calls: true,
default_tools_approval_mode: None,
tool_approval_modes: Default::default(),
},
/*plugin_id*/ None,
/*selected_plugin_server*/ false,
)
.unwrap();
let bindings = McpBindingClients::new(HashMap::from([(
"test_server".to_string(),
Arc::new(client.clone()),
)]));
server.block_listing.store(true, Ordering::Release);
let waiting = async {
tokio::join!(
bindings.list_resources("test_server", /*params*/ None),
bindings.list_resource_templates("test_server", /*params*/ None),
)
};
tokio::pin!(waiting);
tokio::select! {
_ = &mut waiting => panic!("resource listings must wait for cancellation"),
permits = server.started_listings.acquire_many(2) => permits.unwrap().forget(),
}
let mut owned = create_ready_async_managed_client(Vec::new()).await;
owned.client = futures::future::ready(Ok(client.clone())).boxed().shared();
owned.shutdown().await;
let (resources, templates) = waiting.await;
assert!(resources.is_err());
assert!(templates.is_err());
tokio::time::timeout(
Duration::from_secs(1),
server.cancelled_listings.acquire_many(2),
)
.await
.expect("released resource listings must be cancelled")
.unwrap()
.forget();
let prepared_error = prepared
.call_with_preparation(/*requested_timeout*/ None, || async {
panic!("released bindings must not perform irreversible preparation")
})
.await
.unwrap_err();
assert!(
prepared_error
.to_string()
.contains("lease has been released")
);
other
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
owned.client = futures::future::ready(Ok(other)).boxed().shared();
owned.shutdown().await;
}
#[tokio::test]
async fn callback_during_startup_releases_waiting_chats_without_sharing_authority() {
let pool = McpConnectionPool::default();
let key = key(&context(), &config());
let starts = Arc::new(AtomicUsize::new(0));
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let second_callback = Arc::new(Notify::new());
let release_second = Arc::new(Notify::new());
let callbacks = Arc::new(Mutex::new(Vec::new()));
let launch = |name| {
let launch = startup(
ConnectionSharing::Private,
Arc::clone(&starts),
Arc::clone(&started),
Arc::clone(&release),
TestServer::default(),
);
let callbacks = Arc::clone(&callbacks);
let second_callback = Arc::clone(&second_callback);
let release_second = Arc::clone(&release_second);
move |cancellation, sharing_declined: Option<CancellationToken>| {
let startup = launch(cancellation, sharing_declined.clone());
let callbacks = Arc::clone(&callbacks);
let second_callback = Arc::clone(&second_callback);
let release_second = Arc::clone(&release_second);
async move {
let mut client = startup.await?;
let (negotiation, callback) = SharingNegotiation::new(
Box::new(move |_, _| {
callbacks.lock().unwrap().push(name);
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
}))
.boxed()
}),
sharing_declined.unwrap_or_default(),
);
callback(
rmcp::model::RequestId::Number(0),
Elicitation::OpenAiForm {
meta: None,
message: "startup prompt".to_string(),
requested_schema: json!({}),
},
)
.await
.unwrap();
if name == "first" {
second_callback.notified().await;
} else {
second_callback.notify_one();
release_second.notified().await;
}
client.connection_sharing = negotiation.finish(&ProtocolVersion::V_2026_07_28);
Ok(client)
}
.boxed()
.shared()
}
};
let first = pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
launch("first"),
);
let second = pool.connect(
Arc::default(),
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
launch("second"),
);
tokio::pin!(first, second);
assert!(futures::poll!(&mut first).is_pending());
assert!(futures::poll!(&mut second).is_pending());
started.notified().await;
release.notify_one();
let first = tokio::time::timeout(Duration::from_secs(10), async {
tokio::select! {
first = &mut first => first,
_ = &mut second => panic!("the joining chat should still be starting"),
}
})
.await
.expect("the joining chat must start before the first finishes")
.unwrap();
first
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
let mut owner = create_ready_async_managed_client(Vec::new()).await;
owner.client = futures::future::ready(Ok(first.clone())).boxed().shared();
tokio::time::timeout(Duration::from_secs(10), owner.shutdown())
.await
.expect("private owner shutdown must not wait for the joining chat");
assert!(first.client.is_closed().await);
release_second.notify_one();
let second = second.await.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 2);
assert_eq!(*callbacks.lock().unwrap(), ["first", "second"]);
second
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
}
#[tokio::test]
async fn connection_key_changes_with_the_owner_but_survives_credential_refresh() {
let manager =
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
let mut original = key(&context(), &config());
original.auth_state = Some((manager, AuthChangeState::default()));
let mut refreshed = original.clone();
refreshed.auth_state.as_mut().unwrap().1.generation += 1;
assert!(original == refreshed);
refreshed.auth_state.as_mut().unwrap().1.owner_generation += 1;
assert!(original != refreshed);
}
#[tokio::test(start_paused = true)]
async fn new_chat_relists_tools_without_invalidating_or_waiting_for_existing_calls() {
let pool = McpConnectionPool::default();
let key = key(&context(), &config());
let server = TestServer::default();
let starts = Arc::new(AtomicUsize::new(0));
let release = Arc::new(Notify::new());
release.notify_one();
let launch = startup(
ConnectionSharing::Negotiated,
Arc::clone(&starts),
Arc::default(),
release,
server.clone(),
);
let first = pool
.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
)
.await
.unwrap();
let before = first.tool_catalog.read(|snapshot| snapshot).await;
let release_call = Notify::new();
let call = first
.tool_catalog
.run_with_snapshot(&before, || release_call.notified());
tokio::pin!(call);
assert!(futures::poll!(&mut call).is_pending());
for tool_name in ["test", "new"] {
*server.tools.lock().unwrap() = vec![create_test_tool("test_server", tool_name).tool];
let second = tokio::time::timeout(
Duration::from_secs(1),
pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
),
)
.await
.expect("new chats must not wait for existing calls")
.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 1);
assert_eq!(
second
.tool_catalog
.read(|snapshot| snapshot.tools[0].tool.name.to_string())
.await,
tool_name
);
tokio::time::timeout(
Duration::from_secs(1),
second.tool_catalog.refresh(
|| async { Ok((vec![create_test_tool("test_server", "refreshed")], None, ())) },
|_, _, ()| {},
),
)
.await
.expect("one chat's refresh must not wait for another chat's calls")
.unwrap();
assert_eq!(
first
.tool_catalog
.read(|snapshot| snapshot.tools[0].tool.name.to_string())
.await,
"test"
);
}
release_call.notify_one();
assert_eq!(call.await, Some(()));
server.block_listing.store(true, Ordering::Release);
let failed = pool
.connect(
Arc::default(),
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
)
.await;
assert!(failed.is_err());
let _cancelled =
tokio::time::timeout(Duration::from_secs(1), server.cancelled_listings.acquire())
.await
.expect("timed-out listings must be cancelled")
.unwrap();
first
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
}
#[tokio::test]
async fn negotiation_requires_the_stateless_protocol_and_detaches_startup_callbacks() {
for (protocol_version, expected_sharing, expected_action) in [
(
ProtocolVersion::V_2025_06_18,
false,
ElicitationAction::Decline,
),
(
ProtocolVersion::V_2026_07_28,
true,
ElicitationAction::Cancel,
),
] {
let (negotiation, callback) = SharingNegotiation::new(
Box::new(|_, _| {
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
}))
.boxed()
}),
CancellationToken::new(),
);
let sharing = negotiation.finish(&protocol_version);
assert_eq!(
matches!(sharing, ConnectionSharing::Negotiated),
expected_sharing
);
let response = callback(
rmcp::model::RequestId::Number(0),
Elicitation::OpenAiForm {
meta: None,
message: "unexpected".to_string(),
requested_schema: json!({}),
},
)
.await
.unwrap();
assert_eq!(response.action, expected_action);
}
}

View File

@@ -0,0 +1,743 @@
//! MCP elicitation request tracking and policy handling.
//!
//! RMCP clients call into this module when a server asks Codex to elicit data
//! from the user. It decides whether the request can be automatically accepted,
//! must be declined by policy, or should be surfaced as a Codex protocol event
//! and later resolved through the stored responder.
//! Explicit MCP elicitation requests can be surfaced by root and non-root agents.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use crate::McpConfig;
use crate::mcp::McpPermissionPromptAutoApproveContext;
use crate::mcp::mcp_permission_prompt_is_auto_approved;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use async_channel::Sender;
use codex_protocol::approvals::ElicitationAbandonedEvent;
use codex_protocol::approvals::ElicitationRequest;
use codex_protocol::approvals::ElicitationRequestEvent;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID;
use codex_protocol::mcp::RequestId as ProtocolRequestId;
use codex_protocol::mcp_approval_meta::APPROVAL_KIND_KEY;
use codex_protocol::mcp_approval_meta::APPROVAL_KIND_TOOL_SUGGESTION;
use codex_protocol::mcp_approval_meta::APPROVALS_REVIEWER_KEY;
use codex_protocol::mcp_approval_meta::STRICT_AUTO_REVIEW_KEY;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_rmcp_client::Elicitation;
use codex_rmcp_client::ElicitationResponse;
use codex_rmcp_client::SendElicitation;
use futures::future::BoxFuture;
use futures::future::FutureExt;
use rmcp::model::ElicitationAction;
use rmcp::model::RequestId;
use serde_json::Value;
use tokio::sync::oneshot;
static NEXT_ELICITATION_REQUEST_ID: AtomicU64 = AtomicU64::new(0);
const STRICT_AUTO_REVIEW_DECLINE_MESSAGE: &str = "Automated review of this operation failed. Do not proceed without asking the user for explicit approval.";
#[path = "user_verification_elicitation.rs"]
mod user_verification_elicitation;
#[derive(Debug, Clone)]
pub struct ElicitationReviewRequest {
pub server_name: String,
pub request_id: RequestId,
pub elicitation: Elicitation,
}
pub trait ElicitationReviewer: Send + Sync {
fn review(
&self,
request: ElicitationReviewRequest,
) -> BoxFuture<'static, Result<Option<ElicitationResponse>>>;
}
pub type ElicitationReviewerHandle = Arc<dyn ElicitationReviewer>;
/// Holds an owner-provided registration while an MCP elicitation is waiting for a response.
#[derive(Clone)]
pub struct ElicitationLifecycle {
register: Arc<dyn Fn() -> Box<dyn Send + Sync> + Send + Sync>,
}
impl ElicitationLifecycle {
pub fn new<T>(register: impl Fn() -> T + Send + Sync + 'static) -> Self
where
T: Send + Sync + 'static,
{
Self {
register: Arc::new(move || Box::new(register())),
}
}
fn start(&self) -> ActiveElicitation {
ActiveElicitation {
_registration: (self.register)(),
}
}
}
struct ActiveElicitation {
_registration: Box<dyn Send + Sync>,
}
/// Routes model-visible elicitation response tokens to their exact pending responders.
///
/// One router is shared by every MCP runtime created for a thread. The public response token is
/// generated by Codex rather than copied from the MCP connection, so separate runtimes may reuse
/// the same server request ID without colliding.
#[derive(Clone, Default)]
pub(crate) struct ElicitationRequestRouter {
requests: Arc<StdMutex<PendingResponders>>,
terminal_actions_finished: Arc<tokio::sync::Notify>,
auto_deny: Arc<AtomicBool>,
full_access_form_input_enabled: Arc<AtomicBool>,
}
// Removes and abandons a published request when its native waiter is dropped.
struct ElicitationRequestGuard {
router: ElicitationRequestRouter,
key: (String, RequestId),
}
#[derive(Default, PartialEq)]
enum RouterPhase {
#[default]
Open,
Closing,
Closed,
}
#[derive(Default)]
struct PendingResponders {
pending: ResponderMap,
phase: RouterPhase,
terminal_actions: usize,
}
// Owns response delivery and the original source for abandonment notifications.
struct ElicitationResponder {
response: oneshot::Sender<ElicitationResponse>,
abandonment_events: Option<Sender<Event>>,
}
// Removal elects a winner, but shutdown must also wait for its outside-lock delivery.
struct ElicitationDeliveryGuard(ElicitationRequestRouter);
impl Drop for ElicitationDeliveryGuard {
fn drop(&mut self) {
let mut state = self
.0
.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.terminal_actions -= 1;
if state.phase == RouterPhase::Closing && state.terminal_actions == 0 {
state.phase = RouterPhase::Closed;
}
drop(state);
self.0.terminal_actions_finished.notify_waiters();
}
}
impl Drop for ElicitationRequestGuard {
fn drop(&mut self) {
if let Ok(Some((responder, _terminal_action))) = self.router.take_responder(&self.key) {
emit_abandonment(&self.key, responder.abandonment_events.as_ref());
drop(responder);
}
}
}
fn emit_abandonment(key: &(String, RequestId), events: Option<&Sender<Event>>) {
if let Some(events) = events {
let event = Event {
id: "mcp_elicitation_abandoned".to_string(),
msg: EventMsg::ElicitationAbandoned(ElicitationAbandonedEvent {
server_name: key.0.clone(),
id: match &key.1 {
RequestId::String(id) => ProtocolRequestId::String(id.to_string()),
RequestId::Number(id) => ProtocolRequestId::Integer(*id),
},
}),
};
match events.try_send(event) {
Ok(()) | Err(async_channel::TrySendError::Closed(_)) => {}
Err(async_channel::TrySendError::Full(_)) => {
unreachable!("validated unbounded elicitation event channel became full")
}
}
}
}
impl ElicitationRequestRouter {
fn take_responder(
&self,
key: &(String, RequestId),
) -> Result<Option<(ElicitationResponder, ElicitationDeliveryGuard)>> {
let mut state = self
.requests
.lock()
.map_err(|_| anyhow!("elicitation request router unavailable"))?;
Ok(state.pending.remove(key).map(|responder| {
state.terminal_actions += 1;
(responder, ElicitationDeliveryGuard(self.clone()))
}))
}
/// Fence unbounded source publication and terminal deliveries before reporting shutdown.
/// Bounded sources retain their existing request-only behavior and backpressure.
pub(crate) async fn close(&self) {
{
let (pending, _terminal_action) = {
let mut state = self
.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state.phase == RouterPhase::Closed {
return;
}
if state.phase == RouterPhase::Open {
state.phase = RouterPhase::Closing;
}
let pending = state
.pending
.extract_if(|_, responder| responder.abandonment_events.is_some())
.collect::<ResponderMap>();
state.terminal_actions += 1;
(pending, ElicitationDeliveryGuard(self.clone()))
};
// This synchronous batch completes before the first cancellation point.
for (key, responder) in pending {
emit_abandonment(&key, responder.abandonment_events.as_ref());
drop(responder);
}
}
loop {
let notified = self.terminal_actions_finished.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self
.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.phase
== RouterPhase::Closed
{
return;
}
notified.await;
}
}
pub(crate) fn auto_deny(&self) -> bool {
self.auto_deny.load(Ordering::Relaxed)
}
pub(crate) fn set_auto_deny(&self, auto_deny: bool) {
self.auto_deny.store(auto_deny, Ordering::Relaxed);
}
pub(crate) fn full_access_form_input_enabled(&self) -> bool {
self.full_access_form_input_enabled.load(Ordering::Acquire)
}
pub(crate) fn enable_full_access_form_input(&self) {
self.full_access_form_input_enabled
.store(true, Ordering::Release);
}
pub(crate) async fn resolve(
&self,
server_name: String,
id: RequestId,
response: ElicitationResponse,
) -> Result<()> {
let key = (server_name, id);
let (responder, _terminal_action) = self
.take_responder(&key)?
.ok_or_else(|| anyhow!("elicitation request not found"))?;
if responder.response.send(response).is_err() {
emit_abandonment(&key, responder.abandonment_events.as_ref());
return Err(anyhow!("elicitation response receiver closed"));
}
Ok(())
}
async fn request_user_interaction(
&self,
events: Option<Sender<Event>>,
authority: &ElicitationAuthority,
server_name: String,
request: ElicitationRequest,
) -> Result<ElicitationResponse> {
let Some(events) = events else {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
};
// Core uses an unbounded source channel, which can atomically publish a request
// and synchronously enqueue abandonment from Drop. Preserve bounded callers'
// existing request-only behavior because they require asynchronous backpressure.
let abandonment_events = events.capacity().is_none().then(|| events.clone());
let (delivery_context, response_context) =
if matches!(&request, ElicitationRequest::UserVerification { .. }) {
(
"failed to deliver user-verification request",
"user-verification response channel closed",
)
} else {
(
"failed to deliver MCP elicitation request",
"elicitation request channel closed unexpectedly",
)
};
let public_request_id = format!(
"codex-mcp-elicitation-{}",
NEXT_ELICITATION_REQUEST_ID.fetch_add(1, Ordering::Relaxed)
);
let request_key = (
server_name.clone(),
RequestId::String(public_request_id.clone().into()),
);
let (tx, rx) = oneshot::channel();
let _active_elicitation = authority
.lifecycle
.as_ref()
.map(ElicitationLifecycle::start);
let event = Event {
id: "mcp_elicitation_request".to_string(),
msg: EventMsg::ElicitationRequest(ElicitationRequestEvent {
turn_id: None,
server_name,
id: ProtocolRequestId::String(public_request_id),
request,
}),
};
let legacy_event = if abandonment_events.is_some() {
let mut state = self
.requests
.lock()
.map_err(|_| anyhow!("elicitation request router unavailable"))?;
anyhow::ensure!(
state.phase == RouterPhase::Open,
"elicitation request router closed"
);
let mut responder =
state
.pending
.entry(request_key.clone())
.insert_entry(ElicitationResponder {
response: tx,
abandonment_events: None,
});
// Resolve and close cannot observe a published request without its responder.
// The validated unbounded send cannot wait or yield while admission is locked.
if let Err(error) = events.try_send(event) {
responder.remove();
return Err(error).context(delivery_context);
}
responder.get_mut().abandonment_events = abandonment_events;
None
} else {
self.requests
.lock()
.map_err(|_| anyhow!("elicitation request router unavailable"))?
.pending
.insert(
request_key.clone(),
ElicitationResponder {
response: tx,
abandonment_events: None,
},
);
Some(event)
};
let _pending_request = ElicitationRequestGuard {
router: self.clone(),
key: request_key,
};
if let Some(event) = legacy_event {
events.send(event).await.context(delivery_context)?;
}
rx.await.context(response_context)
}
}
#[derive(Clone)]
pub(crate) struct ElicitationAuthority {
pub(crate) config: Arc<McpConfig>,
reviewer: Option<ElicitationReviewerHandle>,
lifecycle: Option<ElicitationLifecycle>,
}
#[derive(Clone, Default)]
pub(crate) struct ElicitationRequestManager {
router: ElicitationRequestRouter,
pub(crate) authority: Arc<StdMutex<Option<ElicitationAuthority>>>,
}
impl ElicitationRequestManager {
pub(crate) fn new(
config: Arc<McpConfig>,
reviewer: Option<ElicitationReviewerHandle>,
lifecycle: Option<ElicitationLifecycle>,
router: ElicitationRequestRouter,
) -> Self {
Self {
router,
authority: Arc::new(StdMutex::new(Some(ElicitationAuthority {
config,
reviewer,
lifecycle,
}))),
}
}
pub(crate) fn update(
&self,
config: Arc<McpConfig>,
reviewer: Option<ElicitationReviewerHandle>,
lifecycle: Option<ElicitationLifecycle>,
) -> bool {
let Ok(mut authority) = self.authority.lock() else {
return false;
};
*authority = Some(ElicitationAuthority {
config,
reviewer,
lifecycle,
});
true
}
pub(crate) fn make_sender(
&self,
server_name: String,
tx_event: Option<Sender<Event>>,
client_mcp_extensions: &ClientMcpExtensions,
) -> SendElicitation {
// Event receivers such as codex mcp-server do not necessarily handle verification.
// Only wait for a response when trusted host activation enabled this exact route.
let user_verification_enabled = client_mcp_extensions
.get(OPENAI_ELICITATION_EXTENSION_ID)
.and_then(|settings| settings.get("userVerification"))
.is_some_and(Value::is_object);
let router = self.router.clone();
let authority = self.authority.clone();
Box::new(move |id, elicitation| {
let router = router.clone();
let tx_event = tx_event.clone();
let server_name = server_name.clone();
let authority = authority.clone();
async move {
let authority = authority
.lock()
.ok()
.and_then(|authority| authority.clone());
if let Elicitation::UserVerification {
meta,
title,
description,
challenge,
} = elicitation
{
if !user_verification_enabled {
return Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: Some(
codex_rmcp_client::UserVerificationReason::ApprovalUnavailable
.into_meta(),
),
});
}
return user_verification_elicitation::route(
router,
tx_event,
authority,
server_name,
ElicitationRequest::UserVerification {
meta,
title,
description,
challenge,
},
)
.await;
}
if router.auto_deny() {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
}
if elicitation
.meta()
.and_then(|meta| meta.get(APPROVAL_KIND_KEY))
.and_then(serde_json::Value::as_str)
== Some(APPROVAL_KIND_TOOL_SUGGESTION)
{
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
}
let Some(authority) = authority else {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
};
let ElicitationAuthority {
config,
reviewer,
lifecycle,
..
} = &authority;
let approval_policy = config.approval_policy.value();
let Some(permission_profile) = config.permission_profile_for_server(&server_name)
else {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
};
match elicitation
.meta()
.and_then(|meta| meta.get(STRICT_AUTO_REVIEW_KEY))
{
Some(Value::Bool(true)) => {
if matches!(
approval_policy,
AskForApproval::Granular(config) if !config.allows_mcp_elicitations()
) {
return Ok(strict_auto_review_decline());
}
let Some(reviewer) = reviewer.as_ref() else {
return Ok(strict_auto_review_decline());
};
let _active_elicitation =
lifecycle.as_ref().map(ElicitationLifecycle::start);
return Ok(
match reviewer
.review(ElicitationReviewRequest {
server_name,
request_id: id,
elicitation,
})
.await
{
Ok(Some(response))
if (response.action == ElicitationAction::Accept
&& response.content == Some(serde_json::json!({}))
|| matches!(
response.action,
ElicitationAction::Decline | ElicitationAction::Cancel
) && response.content.is_none())
&& response
.meta
.as_ref()
.and_then(Value::as_object)
.and_then(|meta| meta.get(APPROVALS_REVIEWER_KEY))
.and_then(Value::as_str)
== Some("auto_review") =>
{
response
}
Ok(Some(_)) | Ok(None) | Err(_) => strict_auto_review_decline(),
},
);
}
None | Some(Value::Bool(false)) => {}
Some(_) => return Ok(strict_auto_review_decline()),
}
let permission_prompt_is_auto_approved = mcp_permission_prompt_is_auto_approved(
approval_policy,
permission_profile,
McpPermissionPromptAutoApproveContext::default(),
);
if permission_prompt_is_auto_approved && can_auto_accept_elicitation(&elicitation) {
return Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(serde_json::json!({})),
meta: None,
});
}
let should_surface_form_in_full_access = router.full_access_form_input_enabled()
&& permission_prompt_is_auto_approved
&& !elicitation
.meta()
.is_some_and(|meta| meta.contains_key(APPROVAL_KIND_KEY))
&& match &elicitation {
Elicitation::Mcp(
rmcp::model::ElicitRequestParams::FormElicitationParams {
requested_schema,
..
},
) => !requested_schema.properties.is_empty(),
Elicitation::OpenAiElicitationForm {
requested_schema, ..
} => requested_schema
.get("properties")
.and_then(Value::as_object)
.is_some_and(|properties| !properties.is_empty()),
Elicitation::Mcp(_)
| Elicitation::OpenAiForm { .. }
| Elicitation::UserVerification { .. } => false,
};
if !should_surface_form_in_full_access {
if elicitation_is_rejected_by_policy(approval_policy) {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
}
if let Some(reviewer) = reviewer {
let request = ElicitationReviewRequest {
server_name: server_name.clone(),
request_id: id.clone(),
elicitation: elicitation.clone(),
};
if let Some(response) = reviewer.review(request).await? {
return Ok(response);
}
}
}
let request = match elicitation {
Elicitation::UserVerification { .. } => {
return Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: None,
});
}
Elicitation::Mcp(rmcp::model::ElicitRequestParams::FormElicitationParams {
meta,
message,
requested_schema,
}) => ElicitationRequest::Form {
meta: meta
.map(serde_json::to_value)
.transpose()
.context("failed to serialize MCP elicitation metadata")?,
message,
requested_schema: serde_json::to_value(requested_schema)
.context("failed to serialize MCP elicitation schema")?,
},
Elicitation::Mcp(rmcp::model::ElicitRequestParams::UrlElicitationParams {
meta,
message,
url,
elicitation_id,
}) => ElicitationRequest::Url {
meta: meta
.map(serde_json::to_value)
.transpose()
.context("failed to serialize MCP elicitation metadata")?,
message,
url,
elicitation_id,
},
Elicitation::Mcp(_) => {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
}
Elicitation::OpenAiForm {
meta,
message,
requested_schema,
} => ElicitationRequest::OpenAiForm {
meta,
message,
requested_schema,
},
Elicitation::OpenAiElicitationForm {
meta,
message,
requested_schema,
} => ElicitationRequest::OpenAiElicitationForm {
meta,
message,
requested_schema,
},
};
router
.request_user_interaction(tx_event, &authority, server_name, request)
.await
}
.boxed()
})
}
}
fn strict_auto_review_decline() -> ElicitationResponse {
ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: Some(serde_json::json!({
"message": STRICT_AUTO_REVIEW_DECLINE_MESSAGE,
})),
}
}
pub(crate) fn elicitation_is_rejected_by_policy(approval_policy: AskForApproval) -> bool {
match approval_policy {
AskForApproval::Never => true,
AskForApproval::OnRequest => false,
AskForApproval::UnlessTrusted => false,
AskForApproval::Granular(granular_config) => !granular_config.allows_mcp_elicitations(),
}
}
type ResponderMap = HashMap<(String, RequestId), ElicitationResponder>;
fn can_auto_accept_elicitation(elicitation: &Elicitation) -> bool {
match elicitation {
Elicitation::Mcp(rmcp::model::ElicitRequestParams::FormElicitationParams {
requested_schema,
..
}) => {
// Auto-accept confirm/approval elicitations without schema requirements.
requested_schema.properties.is_empty()
}
Elicitation::Mcp(_)
| Elicitation::OpenAiForm { .. }
| Elicitation::OpenAiElicitationForm { .. }
| Elicitation::UserVerification { .. } => false,
}
}
#[cfg(test)]
#[path = "elicitation_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,115 @@
//! Account-grant eligibility and registration-specific sign-in requirements.
//! The MCP service owns this state across threads; it retains registration policy but no user tokens.
use std::sync::Mutex;
use codex_config::McpEmaRegistration;
use codex_config::McpServerIdpOAuthConfig;
use codex_login::AccountOAuthGrantRevision;
use codex_login::CodexAuth;
use codex_login::TokenData;
use codex_rmcp_client::account_oidc_identity_is_usable;
use codex_rmcp_client::account_oidc_issuer_hint;
/// Remembers a rejected account credential only for the affected EMA registration.
#[derive(Default)]
pub struct EmaState {
rejected: Mutex<Vec<(McpEmaRegistration, AccountOAuthGrantRevision)>>,
}
impl std::fmt::Debug for EmaState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EmaState").finish_non_exhaustive()
}
}
impl EmaState {
pub(crate) fn requires_sign_in(
&self,
registration: &McpEmaRegistration,
tokens: &TokenData,
) -> bool {
let revision = AccountOAuthGrantRevision::from(tokens);
self.rejected
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.iter()
.any(|(registered, rejected)| registered == registration && rejected == &revision)
}
pub(crate) fn reject(&self, registration: &McpEmaRegistration, tokens: &TokenData) {
let mut rejected = self
.rejected
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
// Replacing a registration's marker also bounds repeated refresh/rejection cycles.
rejected.retain(|(registered, _)| registered != registration);
rejected.push((
registration.clone(),
AccountOAuthGrantRevision::from(tokens),
));
}
pub(crate) fn account_is_usable(
&self,
auth: &CodexAuth,
registration: &McpEmaRegistration,
) -> bool {
matches!(auth, CodexAuth::Chatgpt(_))
&& auth.get_token_data().is_ok_and(|tokens| {
account_grant_is_usable(&tokens, registration.idp())
&& !self.requires_sign_in(registration, &tokens)
})
}
}
pub(crate) fn account_grant_is_usable(tokens: &TokenData, idp: &McpServerIdpOAuthConfig) -> bool {
tokens.oauth_provenance.as_ref().is_some_and(|provenance| {
provenance.issuer == idp.issuer
// A provisioned secret belongs to the configured client, not another
// primary login client at the same IdP. Use dedicated login in that case.
&& (idp.client_secret.is_none() || provenance.client_id == idp.client_id)
&& tokens
.login_owner_id
.as_ref()
.is_some_and(|id| !id.is_empty())
&& !tokens.refresh_token.trim().is_empty()
&& tokens
.id_token
.chatgpt_user_id
.as_ref()
.is_some_and(|id| !id.is_empty())
&& tokens.account_id.as_ref().is_some_and(|id| !id.is_empty())
&& tokens.id_token.chatgpt_account_id == tokens.account_id
&& account_oidc_identity_is_usable(
&tokens.id_token.raw_jwt,
&provenance.issuer,
&provenance.client_id,
)
})
}
pub(crate) fn account_configuration_issue(
auth: &CodexAuth,
idp: &McpServerIdpOAuthConfig,
) -> Option<&'static str> {
let tokens = auth.get_token_data().ok()?;
if tokens.login_owner_id.is_none()
&& (tokens
.oauth_provenance
.as_ref()
.is_some_and(|provenance| provenance.issuer == idp.issuer)
|| account_oidc_issuer_hint(&tokens.id_token.raw_jwt, &idp.issuer))
{
return Some("Sign in to your Codex account again to enable this enterprise MCP server");
}
if tokens.oauth_provenance.as_ref().is_some_and(|provenance| {
provenance.issuer != idp.issuer
&& provenance.issuer.trim_end_matches('/') == idp.issuer.trim_end_matches('/')
}) {
return Some(
"Codex sign-in and enterprise MCP issuer strings differ by a trailing slash; align their OIDC issuer configuration",
);
}
None
}

View File

@@ -0,0 +1,277 @@
//! One thread's EMA authorization lifetime and guarded HTTP dispatch.
//! Account and delivered-policy changes cancel the same owner and its admitted requests.
//! Credential selection and recovery belong to each connection's token source.
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpEmaAuthScope;
use codex_config::McpServerIdpOAuthConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_rmcp_client::EmaAuthFailure;
use codex_rmcp_client::EmaAuthenticatedHttpClient;
use codex_rmcp_client::EmaErrorDetail;
use codex_rmcp_client::EmaRequestAuthority;
use codex_rmcp_client::McpOAuthRefreshMode;
use codex_rmcp_client::McpProtocolMode;
use codex_rmcp_client::RmcpClient;
use codex_rmcp_client::StoredOAuthCredentialSnapshot;
use codex_rmcp_client::StreamableHttpBearerToken;
use codex_rmcp_client::StreamableHttpRedirectMode;
use codex_rmcp_client::stored_oauth_credential_snapshot;
use futures::future::BoxFuture;
use tokio_util::sync::CancellationToken;
use tokio_util::task::AbortOnDropHandle;
use crate::EffectiveMcpServer;
use crate::McpConfig;
use crate::McpServerSource;
use crate::ema_token_source::EnterpriseTokenSource;
use crate::rmcp_client::StartupOutcomeError;
pub(crate) type EmaAuthContext = Result<Arc<EmaAuth>, StartupOutcomeError>;
#[derive(Clone)]
pub(crate) struct EmaConnectionAuth {
pub(crate) owner: Arc<EmaAuth>,
pub(crate) authority: EmaRequestAuthority,
}
pub fn ema_auth_scope(auth: Option<&CodexAuth>) -> Option<McpEmaAuthScope> {
let auth = auth?;
McpEmaAuthScope::new(auth.get_chatgpt_user_id()?, auth.get_account_id()?)
}
/// Retained by the thread across MCP refreshes; a revoked owner cannot be replaced.
pub(crate) struct EmaAuth {
pub(crate) scope: McpEmaAuthScope,
pub(crate) config: Arc<McpConfig>,
pub(crate) manager: Arc<AuthManager>,
pub(crate) account: CodexAuth,
pub(crate) authority: EmaRequestAuthority,
_revocation: AbortOnDropHandle<()>,
}
impl EmaAuth {
pub(crate) fn new(
config: Arc<McpConfig>,
auth: Option<&CodexAuth>,
auth_manager: Option<&Arc<AuthManager>>,
) -> Result<Arc<Self>> {
let scope = ema_auth_scope(auth).ok_or(EmaAuthFailure::ReauthenticationRequired)?;
let manager = auth_manager.context("enterprise MCP requires an account owner")?;
let mut changes = manager.auth_change_state_receiver();
let login_generation = changes.borrow().login_generation;
// Never hold the watch guard while reading cached auth: writers take the auth lock first.
if ema_auth_scope(manager.auth_cached().as_ref()).as_ref() != Some(&scope)
|| changes.borrow().login_generation != login_generation
{
bail!(EmaAuthFailure::ReauthenticationRequired);
}
let cancellation = config.mcp_ema_cancellation.clone();
let policy = config.config_layer_stack.cloud_config_binding().cloned();
let authority = EmaRequestAuthority::new(cancellation.token(), {
let cancellation = cancellation.clone();
let changes = changes.clone();
move || {
!cancellation.is_cancelled()
&& changes.borrow().login_generation == login_generation
}
})
.with_policy(policy.clone());
authority.check_new_request()?;
let revocation = tokio::spawn(async move {
tokio::select! {
biased;
() = cancellation.cancelled() => {}
() = async {
match policy {
Some(policy) => policy.invalidated().await,
None => std::future::pending().await,
}
} => {}
() = async {
while changes.changed().await.is_ok() {
if changes.borrow().login_generation != login_generation {
break;
}
}
} => {}
}
cancellation.cancel();
});
Ok(Arc::new(Self {
scope,
config,
manager: Arc::clone(manager),
account: auth
.context("enterprise MCP requires an account owner")?
.clone(),
authority,
_revocation: AbortOnDropHandle::new(revocation),
}))
}
pub(crate) async fn check_account(&self) -> Result<()> {
self.authority.check()?;
if !self
.manager
.account_login_is_current(&self.account)
.await
.context(EmaErrorDetail::new(
"enterprise MCP account credential validation failed",
))?
{
self.authority.revoke();
bail!(codex_rmcp_client::EmaTokenSourceError::new(
codex_rmcp_client::EmaCredentialKind::Account,
EmaAuthFailure::ReauthenticationRequired,
));
}
self.authority.check()?;
Ok(())
}
pub(crate) async fn connect(
self: &Arc<Self>,
authority: EmaRequestAuthority,
server_name: &str,
server: &EffectiveMcpServer,
http_client: Arc<dyn HttpClient>,
protocol_mode: McpProtocolMode,
) -> Result<RmcpClient> {
self.authority.check()?;
let config = server.config();
config
.validate_ema_auth_transport()
.map_err(anyhow::Error::msg)?;
if !self.config.xaa_enabled
|| !self
.config
.mcp_server_catalog
.server(server_name)
.is_some_and(|server| matches!(server.source(), McpServerSource::Config))
{
bail!("enterprise MCP requires an enabled, directly configured server");
}
let registration = config
.ema_registration()
.context("enterprise MCP registration is missing")?
.clone();
let exchange_client: Arc<dyn HttpClient> = Arc::new(EnterpriseExchangeHttpClient {
inner: Arc::clone(&http_client),
authority: authority.clone(),
cancellation: self.config.mcp_ema_cancellation.token(),
});
let url = registration.server_url().to_owned();
let mut source =
EnterpriseTokenSource::new(registration, Arc::clone(self), exchange_client).await?;
let token = source.initial_access_token().await?;
let http_client = Arc::new(EmaAuthenticatedHttpClient::new(
http_client,
source,
token,
authority,
));
RmcpClient::new_streamable_http_client_with_protocol_mode_and_redirect_mode(
server_name,
&url,
Some(StreamableHttpBearerToken::ProvidedByHttpClient),
/*http_headers*/ None,
/*env_http_headers*/ None,
/*oauth_config*/ None,
OAuthCredentialsStoreMode::Keyring,
self.config.auth_keyring_backend_kind,
http_client,
/*auth_provider*/ None,
protocol_mode,
StreamableHttpRedirectMode::Legacy,
McpOAuthRefreshMode::Legacy,
)
.await
}
}
pub(crate) async fn stored_ema_credentials(
idp: &McpServerIdpOAuthConfig,
scope: &McpEmaAuthScope,
keyring_backend: AuthKeyringBackendKind,
) -> Result<Option<StoredOAuthCredentialSnapshot>> {
let name = idp.credential_name(scope);
let idp = idp.clone();
let originator = codex_otel::auth_storage::AuthStorageOriginator::current();
tokio::task::spawn_blocking(move || {
originator.sync_scope(|| {
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
stored_oauth_credential_snapshot(
&name,
&idp.issuer,
OAuthCredentialsStoreMode::Keyring,
keyring_backend,
)
.map_err(|_| anyhow!(EmaErrorDetail::new("failed to read enterprise credentials")))
})
})
})
.await
.map_err(|_| {
anyhow!(EmaErrorDetail::new(
"enterprise credential read task failed"
))
})?
}
// Discovery and both credential exchanges must check the owner at each dispatch,
// including when the revocation watcher has not yet been scheduled.
struct EnterpriseExchangeHttpClient {
inner: Arc<dyn HttpClient>,
authority: EmaRequestAuthority,
cancellation: CancellationToken,
}
impl HttpClient for EnterpriseExchangeHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
Box::pin(async move {
self.authority.check_new_request()?;
tokio::select! {
biased;
() = self.cancellation.cancelled() => Err(ExecServerError::HttpRequest("enterprise MCP authorization was revoked".into())),
response = self.inner.http_request(params) => {
self.authority.check()?;
response
}
}
})
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
Box::pin(async move {
self.authority.check_new_request()?;
tokio::select! {
biased;
() = self.cancellation.cancelled() => Err(ExecServerError::HttpRequest("enterprise MCP authorization was revoked".into())),
response = self.inner.http_request_stream(params) => {
self.authority.check()?;
response.map(|(response, body)| (response, body.cancel_on(self.cancellation.clone())))
}
}
})
}
}

View File

@@ -0,0 +1,429 @@
//! Pins one EMA connection to an account login or a dedicated enterprise grant.
//! Account refresh exclusion ends with the IdP exchange, before resource-server I/O.
use std::sync::Arc;
use anyhow::Result;
use anyhow::bail;
use codex_config::McpEmaRegistration;
use codex_exec_server::HttpClient;
use codex_login::AccountOAuthGrant;
use codex_login::AccountOAuthGrantLease;
use codex_login::AccountOAuthGrantRevision;
use codex_rmcp_client::EmaAccessToken;
use codex_rmcp_client::EmaAuthFailure;
use codex_rmcp_client::EmaAuthTokenExchangeRequest;
use codex_rmcp_client::EmaCredentialKind;
use codex_rmcp_client::EmaCredentialLease;
use codex_rmcp_client::EmaCredentialSnapshot;
use codex_rmcp_client::EmaErrorDetail;
use codex_rmcp_client::EmaIdpIdentityRequest;
use codex_rmcp_client::EmaInvalidGrantSource;
use codex_rmcp_client::EmaTokenSource;
use codex_rmcp_client::EmaTokenSourceError;
use codex_rmcp_client::StreamableHttpRedirectMode;
use codex_rmcp_client::exchange_ema_auth_token;
use codex_rmcp_client::resolve_ema_account_idp_identity;
use codex_rmcp_client::resolve_ema_idp_identity;
use url::Url;
use crate::ema_account::account_configuration_issue;
use crate::ema_account::account_grant_is_usable;
use crate::ema_auth::EmaAuth;
use crate::ema_auth::stored_ema_credentials;
enum CredentialSource {
Account { client_id: String },
Keyring(Box<EmaCredentialSnapshot>),
}
enum IdpLease {
Account(AccountOAuthGrantLease),
Keyring(EmaCredentialLease),
}
enum ExchangeReceipt {
Account(AccountOAuthGrant),
Keyring(EmaCredentialLease),
}
pub(crate) struct EnterpriseTokenSource {
endpoint: Url,
registration: McpEmaRegistration,
credentials: CredentialSource,
auth: Arc<EmaAuth>,
http_client: Arc<dyn HttpClient>,
}
impl EnterpriseTokenSource {
pub(crate) async fn new(
registration: McpEmaRegistration,
auth: Arc<EmaAuth>,
http_client: Arc<dyn HttpClient>,
) -> Result<Self> {
auth.check_account().await?;
let account = auth
.manager
.lease_account_oauth_grant()
.await
.map_err(|_| EmaErrorDetail::new("enterprise MCP account credential read failed"))?;
let client_id = account
.as_ref()
.filter(|lease| {
account_grant_is_usable(lease.tokens(), registration.idp())
&& !auth
.config
.ema_state
.requires_sign_in(&registration, lease.tokens())
})
.and_then(|lease| lease.tokens().oauth_provenance.as_ref())
.map(|provenance| provenance.client_id.clone());
drop(account);
let credentials = match client_id {
Some(client_id) => CredentialSource::Account { client_id },
None => {
let snapshot = stored_ema_credentials(
registration.idp(),
&auth.scope,
auth.config.auth_keyring_backend_kind,
)
.await?
.ok_or_else(|| {
anyhow::Error::new(EmaAuthFailure::ReauthenticationRequired).context(
account_configuration_issue(&auth.account, registration.idp())
.unwrap_or("Complete enterprise sign-in to use this MCP server"),
)
})?;
CredentialSource::Keyring(Box::new(snapshot.pin_ema_credentials().await?))
}
};
Ok(Self {
endpoint: Url::parse(registration.server_url())?,
registration,
credentials,
auth,
http_client,
})
}
pub(crate) async fn initial_access_token(&mut self) -> Result<EmaAccessToken> {
let error = match self.access_token().await {
Ok(token) => return Ok(token),
Err(error) => error,
};
// A restart forgets the rejection marker. A saved enterprise login can still
// satisfy step-up, but a live connection never silently changes its source.
if matches!(self.credentials, CredentialSource::Account { .. })
&& error
.downcast_ref::<EmaTokenSourceError>()
.is_some_and(EmaTokenSourceError::is_authentication_required)
&& let Some(lease) = self
.auth
.manager
.lease_account_oauth_grant()
.await
.map_err(|_| EmaErrorDetail::new("enterprise MCP account credential read failed"))?
{
let rejected = self
.auth
.config
.ema_state
.requires_sign_in(&self.registration, lease.tokens());
drop(lease);
if rejected
&& let Ok(Some(snapshot)) = stored_ema_credentials(
self.registration.idp(),
&self.auth.scope,
self.auth.config.auth_keyring_backend_kind,
)
.await
{
self.auth.check_account().await?;
self.credentials =
CredentialSource::Keyring(Box::new(snapshot.pin_ema_credentials().await?));
return self.access_token().await;
}
}
Err(error)
}
async fn account_grant(&self, client_id: &str) -> Result<AccountOAuthGrant> {
self.auth.check_account().await?;
let lease = self
.auth
.manager
.lease_account_oauth_grant()
.await
.map_err(|_| EmaErrorDetail::new("enterprise MCP account credential read failed"))?
.ok_or(EmaAuthFailure::ReauthenticationRequired)?;
if !account_grant_is_usable(lease.tokens(), self.registration.idp())
|| lease
.tokens()
.oauth_provenance
.as_ref()
.is_none_or(|provenance| provenance.client_id != client_id)
{
bail!(EmaAuthFailure::ReauthenticationRequired);
}
if self
.auth
.config
.ema_state
.requires_sign_in(&self.registration, lease.tokens())
{
bail!(EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity
});
}
Ok(lease.release())
}
async fn exchange(&self, account: Option<&AccountOAuthGrant>) -> Result<EmaAccessToken> {
let idp = self.registration.idp();
let client_id = match &self.credentials {
CredentialSource::Account { client_id } => client_id,
CredentialSource::Keyring(_) => &idp.client_id,
};
let identity = Box::pin(async {
self.auth.check_account().await?;
match &self.credentials {
CredentialSource::Account { .. } => {
let grant = account.ok_or(EmaAuthFailure::ReauthenticationRequired)?;
let tokens = grant.tokens();
// Metadata discovery must not block ordinary account refresh.
let identity = resolve_ema_account_idp_identity(
idp,
client_id,
&tokens.id_token.raw_jwt,
tokens.refresh_token.clone(),
/*credentials*/ (),
Arc::clone(&self.http_client),
StreamableHttpRedirectMode::Legacy,
)
.await?;
let lease = self
.auth
.manager
.lease_account_oauth_grant()
.await
.map_err(|_| {
EmaErrorDetail::new("enterprise MCP account credential read failed")
})?
.ok_or(EmaAuthFailure::ReauthenticationRequired)?;
if AccountOAuthGrantRevision::from(lease.tokens())
!= AccountOAuthGrantRevision::from(tokens)
|| !account_grant_is_usable(lease.tokens(), idp)
{
bail!(EmaAuthFailure::ReauthenticationRequired);
}
if self
.auth
.config
.ema_state
.requires_sign_in(&self.registration, lease.tokens())
{
bail!(EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
});
}
Ok(identity.map_credentials(|()| IdpLease::Account(lease)))
}
CredentialSource::Keyring(snapshot) => {
resolve_ema_idp_identity(EmaIdpIdentityRequest {
issuer: &idp.issuer,
client_id,
client_secret: idp.client_secret.as_ref().map(|secret| secret.as_str()),
token_endpoint_auth_method: idp.token_endpoint_auth_method,
credentials: snapshot.acquire_current_ema_credentials().await?,
http_client: Arc::clone(&self.http_client),
redirect_mode: StreamableHttpRedirectMode::Legacy,
})
.await
.map(|identity| identity.map_credentials(IdpLease::Keyring))
}
}
});
let (token, receipt) = exchange_ema_auth_token(
EmaAuthTokenExchangeRequest {
server_url: self.registration.server_url(),
resource: self.registration.resource(),
scopes: self.registration.scopes(),
mcp_client_id: self.registration.client_id(),
mcp_client_secret: self.registration.client_secret(),
token_endpoint_auth_method: self.registration.token_endpoint_auth_method(),
expected_authorization_server_issuer: self
.registration
.authorization_server_issuer(),
idp_issuer: &idp.issuer,
idp_client_id: client_id,
idp_identity: identity,
idp_http_client: Arc::clone(&self.http_client),
resource_http_client: Arc::clone(&self.http_client),
},
|lease| match lease {
IdpLease::Account(lease) => ExchangeReceipt::Account(lease.release()),
IdpLease::Keyring(lease) => ExchangeReceipt::Keyring(lease),
},
)
.await?;
match receipt {
ExchangeReceipt::Account(grant) => {
if grant
.current_tokens()
.await
.map_err(|_| {
EmaErrorDetail::new("enterprise MCP account credential validation failed")
})?
.as_ref()
.is_none_or(|tokens| {
!account_grant_is_usable(tokens, idp)
|| self
.auth
.config
.ema_state
.requires_sign_in(&self.registration, tokens)
})
{
// Discard this bearer. The bounded retry below reacquires the grant
// only if its credential changed under the same admitted owner.
bail!(EmaAuthFailure::ReauthenticationRequired);
}
}
ExchangeReceipt::Keyring(lease) => {
drop(lease);
if let CredentialSource::Keyring(snapshot) = &self.credentials {
snapshot.acquire_current_ema_credentials().await?;
}
}
}
self.auth.check_account().await?;
Ok(token)
}
async fn acquire_token(&self) -> Result<EmaAccessToken> {
self.auth.check_account().await?;
match &self.credentials {
CredentialSource::Account { client_id } => {
let mut grant = self.account_grant(client_id).await?;
for attempt in 0..2 {
let error = match self.exchange(Some(&grant)).await {
Ok(token) => return Ok(token),
Err(error) => error,
};
if idp_rejected(&error)
|| matches!(
error.downcast_ref::<EmaAuthFailure>(),
Some(EmaAuthFailure::ReauthenticationRequired)
)
{
let current = self.account_grant(client_id).await?;
if !current.same_credential(&grant) {
if attempt == 0 {
grant = current;
continue;
}
// Repeated rotation is transient; a later call can renew
// without revoking this still-current account owner.
bail!(EmaTokenSourceError::unexpected(EmaCredentialKind::Account));
}
if idp_rejected(&error)
&& let Some(lease) = self
.auth
.manager
.lease_account_oauth_grant()
.await
.map_err(|_| {
EmaErrorDetail::new(
"enterprise MCP account credential read failed",
)
})?
{
if AccountOAuthGrantRevision::from(lease.tokens())
!= AccountOAuthGrantRevision::from(grant.tokens())
{
// Refresh may also rotate after the first credential check.
bail!(EmaTokenSourceError::unexpected(EmaCredentialKind::Account));
}
// Serialize rejection publication with refresh and other leases.
// A late rejection cannot replace a newer credential's marker.
self.auth
.config
.ema_state
.reject(&self.registration, lease.tokens());
}
}
return Err(error);
}
unreachable!("each exchange returns or retries once")
}
CredentialSource::Keyring(snapshot) => {
let result = self.exchange(/*account*/ None).await;
if result.as_ref().is_err_and(|error| {
matches!(
error.downcast_ref::<EmaAuthFailure>(),
Some(EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity
})
)
}) && snapshot
.invalidate_ema_credentials_if_current(async {
self.auth.check_account().await.is_ok()
})
.await
.is_err()
{
tracing::warn!("failed to clear rejected enterprise credentials");
}
result
}
}
}
}
impl EmaTokenSource for EnterpriseTokenSource {
fn endpoint(&self) -> &Url {
&self.endpoint
}
async fn access_token(&self) -> Result<EmaAccessToken> {
let kind = match self.credentials {
CredentialSource::Account { .. } => EmaCredentialKind::Account,
CredentialSource::Keyring(_) => EmaCredentialKind::Keyring,
};
let result = tokio::select! {
biased;
() = self.auth.config.mcp_ema_cancellation.cancelled() => Err(EmaAuthFailure::ReauthenticationRequired.into()),
result = self.acquire_token() => result,
};
result.map_err(|error| {
if let Some(error) = error.downcast_ref::<EmaTokenSourceError>() {
(*error).into()
} else {
match error.downcast_ref::<EmaAuthFailure>() {
Some(failure) => EmaTokenSourceError::new(kind, *failure),
None if codex_rmcp_client::is_authentication_required_error(&error) => {
EmaTokenSourceError::new(kind, EmaAuthFailure::ReauthenticationRequired)
}
None => EmaTokenSourceError::Unexpected {
credential: kind,
detail: EmaErrorDetail::from_error(&error),
},
}
.into()
}
})
}
}
fn idp_rejected(error: &anyhow::Error) -> bool {
matches!(
error.downcast_ref::<EmaAuthFailure>(),
Some(
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity
} | EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity
} | EmaAuthFailure::IdentityClientRejected
)
)
}

View File

@@ -0,0 +1,160 @@
//! Opens MCP event streams with clients that remain connected after task unloading.
use std::sync::Arc;
use crate::auth::McpAuthProvider;
use anyhow::Result;
use anyhow::bail;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::Environment;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_rmcp_client::ElicitationResponse;
use codex_rmcp_client::McpOAuthRefreshMode;
use rmcp::model::ElicitationAction;
use rmcp::model::ElicitationCapability;
use serde_json::Map;
use serde_json::Value;
use tokio::sync::watch;
use crate::CODEX_APPS_MCP_SERVER_NAME;
use crate::EffectiveMcpServer;
use crate::McpEventStream;
use crate::McpProtocolMode;
use crate::McpRuntimeContext;
use crate::rmcp_client::DEFAULT_STARTUP_TIMEOUT;
use crate::rmcp_client::make_rmcp_client;
use crate::rmcp_client::mcp_initialize_request_params;
pub(crate) struct EventStreamConnectionSettings {
pub server: EffectiveMcpServer,
pub store_mode: OAuthCredentialsStoreMode,
pub keyring_backend_kind: AuthKeyringBackendKind,
pub oauth_refresh_mode: McpOAuthRefreshMode,
pub runtime_context: McpRuntimeContext,
pub resolved_environment: std::result::Result<Option<Arc<Environment>>, String>,
pub auth_provider: Option<McpAuthProvider>,
pub auth_manager: Option<Arc<AuthManager>>,
pub auth: Option<CodexAuth>,
pub protocol_mode: McpProtocolMode,
pub client_mcp_extensions: ClientMcpExtensions,
}
/// Opens each event stream with its own MCP client.
/// Owners watch `wait_for_access_change` to cancel streams when access changes.
#[derive(Clone)]
pub struct McpEventStreamOpener {
pub(crate) connection: Arc<EventStreamConnectionSettings>,
pub(crate) cancellation_receiver: watch::Receiver<()>,
pub(crate) cancel_event_streams_on_server_removal: watch::Sender<()>,
}
impl McpEventStreamOpener {
/// Retains cancellation for this task's subscriptions across MCP runtime replacement.
pub fn event_stream_cancellation_sender(&self) -> watch::Sender<()> {
self.cancel_event_streams_on_server_removal.clone()
}
/// Creates an MCP client and opens an event stream.
pub async fn open(
&self,
event_name: &str,
arguments: &Value,
request_meta: Option<&Map<String, Value>>,
) -> Result<McpEventStream> {
tokio::select! {
biased;
() = self.wait_for_access_change() => bail!("event subscription access changed"),
result = async {
let connection = &self.connection;
if let Some(manager) = &connection.auth_manager {
let auth = manager.auth().await;
if !self.matches_auth(auth.as_ref()) {
bail!("event subscription account changed");
}
}
let startup_timeout = connection.server.config().startup_timeout_sec
.unwrap_or(DEFAULT_STARTUP_TIMEOUT);
let client = Arc::new(tokio::time::timeout(startup_timeout, make_rmcp_client(
/*ema_auth*/ None,
CODEX_APPS_MCP_SERVER_NAME,
connection.server.clone(),
connection.store_mode,
connection.keyring_backend_kind,
connection.oauth_refresh_mode,
connection.runtime_context.clone(),
connection.resolved_environment.clone(),
connection.auth_provider.clone(),
connection.protocol_mode,
)).await??);
client.initialize(
mcp_initialize_request_params(
ElicitationCapability::default(),
connection.client_mcp_extensions.clone(),
),
Some(startup_timeout),
Box::new(|_, _| Box::pin(async {
Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
})
})),
).await?;
McpEventStream::open(
client,
self.cancellation_receiver.clone(),
event_name,
arguments,
request_meta,
).await
} => result,
}
}
/// Waits for an account change or removal of the event server from the task.
pub async fn wait_for_access_change(&self) {
let mut cancellation_receiver = self.cancellation_receiver.clone();
let auth_change = async {
let Some(manager) = &self.connection.auth_manager else {
return std::future::pending().await;
};
let mut changes = manager.auth_change_receiver();
loop {
if !self.matches_auth(manager.auth_cached().as_ref()) {
return;
}
if changes.changed().await.is_err() {
return;
}
}
};
tokio::select! {
Ok(()) = cancellation_receiver.changed() => {},
() = auth_change => {},
}
}
fn matches_auth(&self, current: Option<&CodexAuth>) -> bool {
match (self.connection.auth.as_ref(), current) {
(Some(CodexAuth::AgentIdentity(expected)), Some(CodexAuth::AgentIdentity(current))) => {
expected.record() == current.record()
}
(Some(CodexAuth::AgentIdentity(_)), _) | (_, Some(CodexAuth::AgentIdentity(_))) => {
false
}
(Some(expected), Some(current)) => {
expected.get_account_id() == current.get_account_id()
&& expected.get_chatgpt_user_id() == current.get_chatgpt_user_id()
&& expected.is_workspace_account() == current.is_workspace_account()
&& expected.is_fedramp_account() == current.is_fedramp_account()
&& (expected.get_account_id().is_some() || expected == current)
}
(None, None) => true,
_ => false,
}
}
}

View File

@@ -0,0 +1,45 @@
use std::sync::Arc;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpHeader;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use futures::future::BoxFuture;
pub(crate) struct ExecutorEnvironmentHttpClient {
pub(crate) bearer_token_env_var: String,
pub(crate) http_client: Arc<dyn HttpClient>,
}
impl ExecutorEnvironmentHttpClient {
fn attach_authorization(&self, params: &mut HttpRequestParams) {
params
.headers
.retain(|header| !header.name.eq_ignore_ascii_case("authorization"));
params.headers.push(HttpHeader {
name: "authorization".to_string(),
value: "Bearer ".to_string(),
value_env_var: Some(self.bearer_token_env_var.clone()),
});
}
}
impl HttpClient for ExecutorEnvironmentHttpClient {
fn http_request(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.attach_authorization(&mut params);
self.http_client.http_request(params)
}
fn http_request_stream(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.attach_authorization(&mut params);
self.http_client.http_request_stream(params)
}
}

View File

@@ -0,0 +1,153 @@
pub use binding::McpBinding;
pub use binding::McpPermissionSource;
pub use binding::PreparedMcpCall;
pub use binding::SEARCH_CONNECTOR;
pub use binding::SearchDiscovery;
pub use binding::is_model_search_tool;
pub use client_capabilities::client_mcp_extensions;
pub use client_tool_catalog::CodexAppsToolSnapshot;
pub use codex_rmcp_client::McpProtocolMode;
pub use connection_manager::NetworkPolicyMetadata;
pub use connection_manager::NetworkPolicyMetadataProvider;
pub use connection_manager::tool_is_model_visible;
pub use connection_pool::LEASE_META_KEY as MCP_CONNECTION_LEASE_META_KEY;
pub use connection_pool::McpConnectionPool;
pub use elicitation::ElicitationLifecycle;
pub use elicitation::ElicitationReviewRequest;
pub use elicitation::ElicitationReviewer;
pub use elicitation::ElicitationReviewerHandle;
pub use ema_auth::ema_auth_scope;
pub use event_stream::McpEventStreamOpener;
pub use resource_client::CodexAppsResourceListParams;
pub use resource_client::McpEventCatalogSnapshot;
pub use resource_client::McpEventDefinition;
pub use resource_client::McpEventNotification;
pub use resource_client::McpEventStream;
pub use resource_client::McpResourceClient;
pub use resource_client::McpResourceClientAuthKey;
pub use resource_client::McpResourceClientCacheKey;
pub use resource_client::McpResourcePage;
pub use resource_client::McpResourceReadResult;
pub use resource_client::McpResourceServerCacheKey;
pub use rmcp::model::ReadResourceRequestParams;
pub use rmcp_client::MCP_NETWORK_POLICY_META_CAPABILITY;
pub use runtime::McpRuntime;
pub use runtime::McpRuntimeContext;
pub use runtime::McpRuntimeInput;
pub use runtime::McpStartupPolicy;
pub use runtime::McpToolCallResult;
pub use runtime::apply_http_headers_helper;
pub use sandbox_metadata::MCP_SANDBOX_LAUNCHER_META_KEY;
pub use sandbox_metadata::MCP_SANDBOX_STATE_CAPABILITY;
pub use sandbox_metadata::MCP_SANDBOX_STATE_META_CAPABILITY;
pub use sandbox_metadata::SandboxState;
pub use tool_catalog_cache::McpToolCatalogCache;
pub use tool_request_meta::McpToolRequestMetaHook;
pub use tool_request_meta::McpToolRequestMetaProvider;
pub use tools::ToolInfo;
pub use trusted_access::TrustedAccessContext;
/// Backward-compatible name for the shared Codex Apps tools runtime.
pub type CodexAppsToolsCache = codex_connectors::ConnectorRuntimeManager<ToolInfo>;
/// Backward-compatible name for the Codex Apps runtime context key.
pub type CodexAppsToolsCacheKey = codex_connectors::ConnectorRuntimeContextKey;
pub use catalog::McpCatalogBuilder;
pub use catalog::McpEnvironmentAuthority;
pub use catalog::McpPluginAttribution;
pub use catalog::McpServerConflict;
pub use catalog::McpServerConflictAction;
pub use catalog::McpServerRegistration;
pub use catalog::McpServerSource;
pub use catalog::ResolvedMcpCatalog;
pub use catalog::ResolvedMcpServer;
pub use mcp::CODEX_APPS_MCP_SERVER_NAME;
pub use mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE;
pub use mcp::McpConfig;
pub use mcp::McpServerPermissions;
pub use mcp::ToolPluginContext;
pub use server::EffectiveMcpServer;
pub use auth_elicitation::CodexAppsAuthElicitation;
pub use auth_elicitation::CodexAppsAuthElicitationPlan;
pub use auth_elicitation::CodexAppsConnectorAuthFailure;
pub use auth_elicitation::MCP_TOOL_CODEX_APPS_META_KEY;
pub use auth_elicitation::auth_elicitation_completed_result;
pub use auth_elicitation::auth_elicitation_id;
pub use auth_elicitation::build_auth_elicitation;
pub use auth_elicitation::build_auth_elicitation_plan;
pub use auth_elicitation::connector_auth_failure_from_tool_result;
pub use auth_elicitation::is_connector_auth_failure_from_tool_result;
/// Backward-compatible name for the Codex Apps runtime context key builder.
pub use codex_connectors::connector_runtime_context_key as codex_apps_tools_cache_key;
pub use mcp::codex_apps_mcp_server_config;
pub use mcp::configured_mcp_servers;
pub use mcp::effective_mcp_servers;
pub use mcp::effective_mcp_servers_from_configured;
pub use mcp::host_owned_codex_apps_enabled;
pub use mcp::hosted_plugin_runtime_mcp_server_config;
pub use mcp::tool_plugin_context;
pub use plugin_config::PluginMcpConfigParseOutcome;
pub use plugin_config::PluginMcpServerParseError;
pub use plugin_config::normalize_executor_plugin_mcp_declarations;
pub use plugin_config::parse_agent_plugin_mcp_config;
pub use plugin_config::parse_executor_plugin_mcp_config;
pub use plugin_config::parse_plugin_mcp_config;
pub use plugin_config::parse_plugin_mcp_declarations;
pub use mcp::McpServerStatusSnapshot;
pub use mcp::McpSnapshotDetail;
pub use mcp::collect_mcp_server_status_snapshot_with_detail;
pub use mcp::read_mcp_resource;
pub use mcp::McpAuthStatusEntry;
pub use mcp::McpOAuthLoginConfig;
pub use mcp::McpOAuthLoginSupport;
pub use mcp::McpOAuthScopesSource;
pub use mcp::ResolvedMcpOAuthScopes;
pub use mcp::compute_auth_statuses;
pub use mcp::discover_supported_scopes;
pub use mcp::oauth_login_support;
pub use mcp::resolve_oauth_callback;
pub use mcp::resolve_oauth_scopes;
pub use mcp::should_retry_without_scopes;
pub use codex_apps::declared_openai_file_input_param_names;
pub use mcp::McpPermissionPromptAutoApproveContext;
pub use mcp::mcp_permission_prompt_is_auto_approved;
pub use mcp::qualified_mcp_tool_name_prefix;
mod auth;
mod auth_changes;
pub(crate) mod auth_elicitation;
mod binding;
pub(crate) mod binding_clients;
mod catalog;
mod client_capabilities;
mod client_tool_catalog;
pub(crate) mod codex_apps;
pub(crate) mod connection_manager;
mod connection_pool;
pub(crate) mod elicitation;
mod ema_account;
mod ema_auth;
mod ema_token_source;
pub use ema_account::EmaState;
mod event_stream;
mod executor_environment_http_client;
pub(crate) mod mcp;
mod openai_docs_source_attribution;
mod pagination;
mod plugin_config;
mod resource_client;
mod resource_origin;
pub(crate) mod rmcp_client;
pub(crate) mod runtime;
mod sandbox_executable;
mod sandbox_metadata;
pub(crate) mod server;
mod tool_catalog_cache;
mod tool_request_meta;
pub(crate) mod tools;
mod trusted_access;

View File

@@ -0,0 +1,566 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Result;
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
use codex_config::McpServerTransportConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::HttpClient;
use codex_login::AccountOAuthGrant;
use codex_login::CodexAuth;
use codex_rmcp_client::McpAuthState;
use codex_rmcp_client::McpLoginRequirement;
use codex_rmcp_client::McpOAuthCallbackMode;
use codex_rmcp_client::OAuthDiscoveryTimeout;
use codex_rmcp_client::OAuthProviderError;
use codex_rmcp_client::StreamableHttpRedirectMode;
use codex_rmcp_client::determine_streamable_http_auth_status;
use codex_rmcp_client::determine_streamable_http_auth_status_from_credentials;
use codex_rmcp_client::discover_streamable_http_oauth;
use codex_rmcp_client::resolve_mcp_oauth_callback_url;
use futures::FutureExt;
use futures::future::join_all;
use tokio::sync::OnceCell;
use tracing::warn;
use crate::runtime::McpRuntimeContext;
use crate::server::EffectiveMcpServer;
use crate::server::has_explicit_http_authorization;
#[derive(Debug, Clone)]
pub struct McpOAuthLoginConfig {
pub url: String,
pub http_headers: Option<HashMap<String, String>>,
pub env_http_headers: Option<HashMap<String, String>>,
pub discovered_scopes: Option<Vec<String>>,
pub callback_mode: McpOAuthCallbackMode,
}
#[derive(Debug)]
pub enum McpOAuthLoginSupport {
Supported(McpOAuthLoginConfig),
Unsupported,
Unknown(anyhow::Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpOAuthScopesSource {
Explicit,
Configured,
Discovered,
Empty,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedMcpOAuthScopes {
pub scopes: Vec<String>,
pub source: McpOAuthScopesSource,
}
/// Keeps registered callbacks tied to their client while preserving legacy redirects.
pub fn resolve_oauth_callback(
server: &McpServerConfig,
server_url: &str,
global_callback_url: Option<&str>,
) -> Result<Option<String>> {
if let Some(callback_url) = server
.oauth
.as_ref()
.and_then(|oauth| oauth.callback_url.as_deref())
{
return Ok(Some(callback_url.to_string()));
}
if server
.oauth_client_id()
.is_none_or(|client_id| client_id.trim().is_empty())
{
return Ok(global_callback_url.map(ToOwned::to_owned));
}
resolve_mcp_oauth_callback_url(
server_url,
global_callback_url,
McpOAuthCallbackMode::CallbackSpecific,
)
.map(Some)
}
#[derive(Debug, Clone)]
pub struct McpAuthStatusEntry {
pub config: Option<McpServerConfig>,
pub auth_state: McpAuthState,
}
pub async fn oauth_login_support(
transport: &McpServerTransportConfig,
http_client: Arc<dyn HttpClient>,
discovery_timeout: OAuthDiscoveryTimeout,
redirect_mode: StreamableHttpRedirectMode,
) -> McpOAuthLoginSupport {
let Some(mut config) = oauth_login_candidate(transport) else {
return McpOAuthLoginSupport::Unsupported;
};
match discover_streamable_http_oauth(
&config.url,
config.http_headers.clone(),
config.env_http_headers.clone(),
http_client,
discovery_timeout,
redirect_mode,
)
.await
{
Ok(Some(discovery)) => {
config.discovered_scopes = discovery.scopes_supported;
config.callback_mode = discovery.callback_mode;
McpOAuthLoginSupport::Supported(config)
}
Ok(None) => McpOAuthLoginSupport::Unsupported,
Err(err) => McpOAuthLoginSupport::Unknown(err),
}
}
fn oauth_login_candidate(transport: &McpServerTransportConfig) -> Option<McpOAuthLoginConfig> {
let McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
..
} = transport
else {
return None;
};
if bearer_token_env_var.is_some() {
return None;
}
Some(McpOAuthLoginConfig {
url: url.clone(),
http_headers: http_headers.clone(),
env_http_headers: env_http_headers.clone(),
discovered_scopes: None,
callback_mode: McpOAuthCallbackMode::CallbackSpecific,
})
}
pub async fn discover_supported_scopes(
transport: &McpServerTransportConfig,
http_client: Arc<dyn HttpClient>,
discovery_timeout: OAuthDiscoveryTimeout,
redirect_mode: StreamableHttpRedirectMode,
) -> Option<Vec<String>> {
match oauth_login_support(transport, http_client, discovery_timeout, redirect_mode).await {
McpOAuthLoginSupport::Supported(config) => config.discovered_scopes,
McpOAuthLoginSupport::Unsupported | McpOAuthLoginSupport::Unknown(_) => None,
}
}
pub fn resolve_oauth_scopes(
explicit_scopes: Option<Vec<String>>,
configured_scopes: Option<Vec<String>>,
discovered_scopes: Option<Vec<String>>,
) -> ResolvedMcpOAuthScopes {
if let Some(scopes) = explicit_scopes {
return ResolvedMcpOAuthScopes {
scopes,
source: McpOAuthScopesSource::Explicit,
};
}
if let Some(scopes) = configured_scopes {
return ResolvedMcpOAuthScopes {
scopes,
source: McpOAuthScopesSource::Configured,
};
}
if let Some(scopes) = discovered_scopes
&& !scopes.is_empty()
{
return ResolvedMcpOAuthScopes {
scopes,
source: McpOAuthScopesSource::Discovered,
};
}
ResolvedMcpOAuthScopes {
scopes: Vec::new(),
source: McpOAuthScopesSource::Empty,
}
}
pub fn should_retry_without_scopes(scopes: &ResolvedMcpOAuthScopes, error: &anyhow::Error) -> bool {
scopes.source == McpOAuthScopesSource::Discovered
&& error.downcast_ref::<OAuthProviderError>().is_some()
}
pub async fn compute_auth_statuses<'a, I>(
servers: I,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
auth: Option<&CodexAuth>,
auth_manager: Option<&std::sync::Arc<codex_login::AuthManager>>,
ema_state: &crate::EmaState,
runtime_context: &McpRuntimeContext,
) -> HashMap<String, McpAuthStatusEntry>
where
I: IntoIterator<Item = (&'a String, &'a EffectiveMcpServer)>,
{
// Share successful, missing, and failed reads without starting storage work for non-EMA servers.
let account_grant = OnceCell::new();
let futures = servers.into_iter().map(|(name, server)| {
let account_grant = &account_grant;
let name = name.clone();
let redirect_mode = if server.is_agent_plugin() {
StreamableHttpRedirectMode::AgentPluginV1
} else {
StreamableHttpRedirectMode::Legacy
};
let config = server.config().clone();
let runtime_context = runtime_context.clone();
async move {
let auth_state = match compute_auth_status(
&name,
&config,
store_mode,
keyring_backend_kind,
auth,
auth_manager,
account_grant,
ema_state,
&runtime_context,
redirect_mode,
)
.await
{
Ok(status) => status,
Err(error) => {
warn!("failed to determine auth status for MCP server `{name}`: {error:?}");
McpAuthState::Unknown
}
};
let entry = McpAuthStatusEntry {
config: Some(config),
auth_state,
};
(name, entry)
}
});
join_all(futures).await.into_iter().collect()
}
#[allow(clippy::too_many_arguments)]
async fn compute_auth_status(
server_name: &str,
config: &McpServerConfig,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
auth: Option<&CodexAuth>,
auth_manager: Option<&std::sync::Arc<codex_login::AuthManager>>,
account_grant: &OnceCell<std::io::Result<Option<AccountOAuthGrant>>>,
ema_state: &crate::EmaState,
runtime_context: &McpRuntimeContext,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<McpAuthState> {
if !config.enabled {
return Ok(McpAuthState::Unsupported);
}
if matches!(config.auth, McpServerAuth::EmaAuth) {
let Some(registration) = config.ema_registration() else {
return Ok(McpAuthState::Unsupported);
};
config
.validate_ema_auth_transport()
.map_err(anyhow::Error::msg)?;
let Some(scope) = crate::ema_auth_scope(auth) else {
return Ok(McpAuthState::LoggedOut(McpLoginRequirement::Login));
};
if matches!(auth, Some(CodexAuth::Chatgpt(_)))
&& auth
.and_then(|auth| auth.get_token_data().ok())
.is_none_or(|tokens| tokens.login_owner_id.as_ref().is_none_or(String::is_empty))
{
return Ok(McpAuthState::LoggedOut(McpLoginRequirement::Login));
}
let account_usable = match auth_manager {
Some(manager) => match account_grant
.get_or_init(|| manager.account_oauth_grant())
.await
.as_ref()
.map_err(|error| anyhow::anyhow!("{error}"))?
{
Some(grant) => {
crate::ema_account::account_grant_is_usable(grant.tokens(), registration.idp())
&& !ema_state.requires_sign_in(registration, grant.tokens())
}
None => false,
},
None => auth.is_some_and(|auth| ema_state.account_is_usable(auth, registration)),
};
if account_usable {
return Ok(McpAuthState::BearerToken);
}
return Ok(
match crate::ema_auth::stored_ema_credentials(
registration.idp(),
&scope,
keyring_backend_kind,
)
.await?
{
Some(snapshot)
if codex_rmcp_client::stored_ema_identity_is_usable(
snapshot.credentials(),
&registration.idp().issuer,
&registration.idp().client_id,
) =>
{
McpAuthState::OAuth
}
Some(_) => McpAuthState::LoggedOut(McpLoginRequirement::Reauthentication),
None => McpAuthState::LoggedOut(McpLoginRequirement::Login),
},
);
}
let has_runtime_auth = matches!(config.auth, McpServerAuth::ChatGpt)
&& auth.is_some_and(CodexAuth::uses_codex_backend)
&& matches!(
&config.transport,
McpServerTransportConfig::StreamableHttp {
bearer_token_env_var: None,
..
}
);
if matches!(config.auth, McpServerAuth::ChatGpt) && !config.is_local_environment() {
return Ok(if has_explicit_http_authorization(config) {
McpAuthState::BearerToken
} else {
McpAuthState::Unsupported
});
}
if has_runtime_auth {
return Ok(McpAuthState::BearerToken);
}
match &config.transport {
McpServerTransportConfig::Stdio { .. } => Ok(McpAuthState::Unsupported),
McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
http_headers_helper,
} => {
if http_headers_helper.is_some() {
// Status inspection must not execute an arbitrary local helper. Existing
// credentials remain reportable; otherwise discovery waits for startup/login.
return Ok(determine_streamable_http_auth_status_from_credentials(
config.oauth_credential_name(server_name).as_ref(),
url,
bearer_token_env_var.as_deref(),
http_headers.clone(),
env_http_headers.clone(),
store_mode,
keyring_backend_kind,
)?
.unwrap_or(McpAuthState::Unknown));
}
let http_client = runtime_context
.resolve_http_client(server_name, config)
.map_err(anyhow::Error::msg)?;
let discovery_timeout = if config.is_local_environment() {
OAuthDiscoveryTimeout::LOCAL
} else {
OAuthDiscoveryTimeout::Requested
};
let oauth_credential_name = config.oauth_credential_name(server_name);
determine_streamable_http_auth_status(
oauth_credential_name.as_ref(),
url,
bearer_token_env_var.as_deref(),
http_headers.clone(),
env_http_headers.clone(),
store_mode,
keyring_backend_kind,
http_client,
discovery_timeout,
redirect_mode,
)
.boxed()
.await
}
}
}
#[cfg(test)]
mod tests {
use anyhow::anyhow;
use pretty_assertions::assert_eq;
use super::McpOAuthScopesSource;
use super::OAuthProviderError;
use super::ResolvedMcpOAuthScopes;
use super::resolve_oauth_callback;
use super::resolve_oauth_scopes;
use super::should_retry_without_scopes;
#[test]
fn callback_resolution_preserves_registered_and_legacy_clients() -> anyhow::Result<()> {
for (client_id, saved_callback, global_callback, expected_callback) in [
(
Some("registered-client"),
Some("http://127.0.0.1/callback"),
Some("https://override.example/callback"),
Some("http://127.0.0.1/callback"),
),
(
Some("legacy-client"),
None,
None,
Some("http://127.0.0.1/callback/epMNJ6P1xGQ9"),
),
(
None,
Some("https://plugin.example/callback"),
Some("https://override.example/callback"),
Some("https://plugin.example/callback"),
),
(
None,
None,
Some("https://override.example/callback"),
Some("https://override.example/callback"),
),
] {
let server = serde_json::from_value(serde_json::json!({
"url": "https://mcp.example.com/mcp",
"oauth": {
"client_id": client_id,
"callback_url": saved_callback,
},
}))?;
assert_eq!(
resolve_oauth_callback(&server, "https://mcp.example.com/mcp", global_callback)?
.as_deref(),
expected_callback
);
}
Ok(())
}
#[test]
fn resolve_oauth_scopes_prefers_explicit() {
let resolved = resolve_oauth_scopes(
Some(vec!["explicit".to_string()]),
Some(vec!["configured".to_string()]),
Some(vec!["discovered".to_string()]),
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: vec!["explicit".to_string()],
source: McpOAuthScopesSource::Explicit,
}
);
}
#[test]
fn resolve_oauth_scopes_prefers_configured_over_discovered() {
let resolved = resolve_oauth_scopes(
/*explicit_scopes*/ None,
Some(vec!["configured".to_string()]),
Some(vec!["discovered".to_string()]),
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: vec!["configured".to_string()],
source: McpOAuthScopesSource::Configured,
}
);
}
#[test]
fn resolve_oauth_scopes_uses_discovered_when_needed() {
let resolved = resolve_oauth_scopes(
/*explicit_scopes*/ None,
/*configured_scopes*/ None,
Some(vec!["discovered".to_string()]),
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: vec!["discovered".to_string()],
source: McpOAuthScopesSource::Discovered,
}
);
}
#[test]
fn resolve_oauth_scopes_preserves_explicitly_empty_configured_scopes() {
let resolved = resolve_oauth_scopes(
/*explicit_scopes*/ None,
Some(Vec::new()),
Some(vec!["ignored".into()]),
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: Vec::new(),
source: McpOAuthScopesSource::Configured,
}
);
}
#[test]
fn resolve_oauth_scopes_falls_back_to_empty() {
let resolved = resolve_oauth_scopes(
/*explicit_scopes*/ None, /*configured_scopes*/ None,
/*discovered_scopes*/ None,
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: Vec::new(),
source: McpOAuthScopesSource::Empty,
}
);
}
#[test]
fn should_retry_without_scopes_only_for_discovered_provider_errors() {
let discovered = ResolvedMcpOAuthScopes {
scopes: vec!["scope".to_string()],
source: McpOAuthScopesSource::Discovered,
};
let provider_error = anyhow!(OAuthProviderError::new(
Some("invalid_scope".to_string()),
Some("scope rejected".to_string()),
));
assert!(should_retry_without_scopes(&discovered, &provider_error));
let configured = ResolvedMcpOAuthScopes {
scopes: vec!["scope".to_string()],
source: McpOAuthScopesSource::Configured,
};
assert!(!should_retry_without_scopes(&configured, &provider_error));
assert!(!should_retry_without_scopes(
&discovered,
&anyhow!("timed out waiting for OAuth callback"),
));
}
}

View File

@@ -0,0 +1,928 @@
pub use auth::McpAuthStatusEntry;
pub use auth::McpOAuthLoginConfig;
pub use auth::McpOAuthLoginSupport;
pub use auth::McpOAuthScopesSource;
pub use auth::ResolvedMcpOAuthScopes;
pub use auth::compute_auth_statuses;
pub use auth::discover_supported_scopes;
pub use auth::oauth_login_support;
pub use auth::resolve_oauth_callback;
pub use auth::resolve_oauth_scopes;
pub use auth::should_retry_without_scopes;
pub(crate) mod auth;
use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use codex_config::ConfigLayerStack;
use codex_config::Constrained;
use codex_config::McpEnterpriseManagedAuthConfig;
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
use codex_config::McpServerTransportConfig;
use codex_config::types::AppToolApproval;
use codex_config::types::ApprovalsReviewer;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_connectors::ConnectorRuntimeManager;
use codex_connectors::ConnectorSnapshot;
use codex_connectors::connector_runtime_context_key;
use codex_exec_server::FileSystemSandboxContext;
use codex_login::CodexAuth;
use codex_model_provider::CHATGPT_CODEX_BASE_URL;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::mcp::McpServerInfo;
use codex_protocol::mcp::Resource;
use codex_protocol::mcp::ResourceTemplate;
use codex_protocol::mcp::Tool;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::McpAuthStatus;
use codex_rmcp_client::McpOAuthRefreshMode;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use rmcp::model::ElicitationCapability;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use crate::McpProtocolMode;
use crate::McpServerSource;
use crate::ResolvedMcpCatalog;
use crate::connection_manager::McpConnectionSet;
use crate::runtime::McpPublicationGate;
use crate::runtime::McpRuntimeContext;
use crate::runtime::McpRuntimeInput;
use crate::runtime::McpStartupPolicy;
use crate::server::EffectiveMcpServer;
use crate::tools::ToolInfo;
pub const CODEX_APPS_MCP_SERVER_NAME: &str = "codex_apps";
pub(crate) const DEFAULT_CODEX_APPS_MCP_PRODUCT_SKU: &str = "codex";
const MCP_TOOL_NAME_PREFIX: &str = "mcp";
const MCP_TOOL_NAME_DELIMITER: &str = "__";
const CODEX_CONNECTORS_TOKEN_ENV_VAR: &str = "CODEX_CONNECTORS_TOKEN";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum McpSnapshotDetail {
#[default]
Full,
ToolsAndAuthOnly,
}
impl McpSnapshotDetail {
fn include_resources(self) -> bool {
matches!(self, Self::Full)
}
}
pub fn qualified_mcp_tool_name_prefix(server_name: &str) -> String {
sanitize_responses_api_tool_name(&format!(
"{MCP_TOOL_NAME_PREFIX}{MCP_TOOL_NAME_DELIMITER}{server_name}{MCP_TOOL_NAME_DELIMITER}"
))
}
/// Returns true when MCP permission prompts should resolve as approved instead
/// of being shown to the user.
pub fn mcp_permission_prompt_is_auto_approved(
approval_policy: AskForApproval,
permission_profile: &PermissionProfile,
context: McpPermissionPromptAutoApproveContext,
) -> bool {
if context.tool_approval_mode == Some(AppToolApproval::Approve) {
return true;
}
if approval_policy != AskForApproval::Never {
return false;
}
match permission_profile {
PermissionProfile::Disabled | PermissionProfile::External { .. } => true,
PermissionProfile::Managed { file_system, .. } => {
file_system.to_sandbox_policy().has_full_disk_write_access()
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct McpPermissionPromptAutoApproveContext {
pub tool_approval_mode: Option<AppToolApproval>,
}
/// Which rules a registered MCP server uses.
#[derive(Debug, Clone)]
pub enum McpServerPermissions {
Thread,
Environment(Arc<FileSystemSandboxContext>),
}
/// MCP runtime settings derived from `codex_core::config::Config`.
///
/// Each published runtime and prepared call owns one immutable copy of these
/// settings, so its connection, approval policy, and sandbox authority cannot
/// change independently. Auth remains separate and is supplied explicitly to
/// runtime entry points such as [`effective_mcp_servers`].
#[derive(Debug, Clone)]
pub struct McpConfig {
/// Base URL for ChatGPT-hosted app MCP servers, copied from the root config.
pub chatgpt_base_url: String,
/// Optional product SKU forwarded to the host-owned apps MCP server.
pub apps_mcp_product_sku: Option<String>,
/// Requests server-side read-only filtering and invocation checks for MCP tools.
pub requires_read_only_mcp_tools: bool,
/// Codex home directory used for MCP OAuth state and app-tool cache files.
pub codex_home: PathBuf,
/// Trusted enterprise IdP inherited after normal catalog and policy resolution.
pub mcp_enterprise_managed_auth: Option<McpEnterpriseManagedAuthConfig>,
/// Retires only EMA connections and pending exchanges for this config snapshot.
pub mcp_ema_cancellation: codex_config::McpEmaCancellation,
pub xaa_enabled: bool,
/// Shared sign-in requirements for account-backed enterprise MCP.
pub ema_state: Arc<crate::EmaState>,
/// Preferred credential store for MCP OAuth tokens.
pub mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode,
/// OAuth refresh ownership selected for new MCP connections.
pub oauth_refresh_mode: McpOAuthRefreshMode,
/// Backend used when MCP OAuth storage is configured for keyring-backed persistence.
pub auth_keyring_backend_kind: AuthKeyringBackendKind,
/// Optional fixed localhost callback port for MCP OAuth login.
pub mcp_oauth_callback_port: Option<u16>,
/// Optional OAuth redirect URI override for MCP login.
pub mcp_oauth_callback_url: Option<String>,
/// How long a tool catalog capture waits for optional MCP servers to initialize.
///
/// A zero duration disables the shared grace and waits for each server's
/// configured startup timeout instead.
pub optional_mcp_startup_grace: Duration,
/// Whether skill MCP dependency installation prompts are enabled.
pub skill_mcp_dependency_install_enabled: bool,
/// Approval policy used for MCP tool calls and MCP elicitation requests.
pub approval_policy: Constrained<AskForApproval>,
/// Permission profile captured with the connections and approval policy.
pub permission_profile: PermissionProfile,
/// Host working directory used to interpret thread permissions.
pub host_cwd: AbsolutePathBuf,
/// Configuration layers used to evaluate Apps tool policy and reviewer selection.
pub config_layer_stack: ConfigLayerStack,
pub plugins: codex_config::types::PluginsConfigToml,
/// Default reviewer used when an Apps tool has no reviewer override.
pub approvals_reviewer: ApprovalsReviewer,
/// Working directories for the exact environment handles used by this runtime.
pub environment_cwds: HashMap<String, PathUri>,
/// Effective backends captured with the environment handles, including local fallback.
pub environment_use_mxc: HashMap<String, bool>,
/// Permissions for registered servers. Unavailable servers have no entry.
pub server_permissions: HashMap<String, McpServerPermissions>,
/// Host-supplied re-exec binary. Probe its sandbox capability before advertising it.
/// Never infer this from PATH or an MCP server's configuration.
pub codex_self_exe: Option<PathBuf>,
/// Optional path to `codex-linux-sandbox` for sandboxed MCP tool execution.
pub codex_linux_sandbox_exe: Option<PathBuf>,
/// Whether to use legacy Landlock behavior in the MCP sandbox state.
// TODO(anp): Reconcile this runtime-wide copy with TurnEnvironment::sandbox_context
// for the environment that owns each MCP server.
pub use_legacy_landlock: bool,
/// Whether the app MCP integration is enabled by config.
///
/// ChatGPT auth is checked separately before a materialized host-owned Apps
/// server can be used.
pub apps_enabled: bool,
/// Allow hosted Apps catalog reads after MCP initialization, before tools are ready.
pub apps_early_resource_discovery: bool,
/// Whether model-visible MCP tool namespaces should keep the legacy
/// `mcp__` prefix.
pub prefix_mcp_tool_names: bool,
/// MCP servers whose model-visible tool namespaces omit the `mcp__` prefix.
pub non_prefixed_mcp_tool_servers: Vec<String>,
/// Protocol mode for servers other than the host-owned Codex Apps registration.
pub protocol_mode: McpProtocolMode,
/// Try protocol discovery before initializing eligible local stdio servers.
pub discover_local_stdio: bool,
/// Refresh ordinary server catalogs after tools/list_changed notifications.
pub mcp_tool_list_changed: bool,
/// Independent protocol mode for the trusted, HTTP Codex Apps registration.
pub host_owned_apps_protocol_mode: McpProtocolMode,
/// Client-side elicitation capabilities advertised during MCP initialization.
pub client_elicitation_capability: ElicitationCapability,
/// Resolved MCP registrations keyed by logical server name.
pub mcp_server_catalog: ResolvedMcpCatalog,
/// Plugin declarations used to attribute connector tools to plugin display names.
/// MCP registrations retain their own package attribution in the catalog.
pub connector_snapshot: ConnectorSnapshot,
}
/// Default amount of time a tool catalog capture waits for optional MCP servers.
pub const DEFAULT_OPTIONAL_MCP_STARTUP_GRACE: Duration = Duration::from_secs(1);
impl McpConfig {
/// Resolves enabled runtime servers against the exact attachment permissions being published.
pub fn set_server_permissions(
&mut self,
servers: &HashMap<String, EffectiveMcpServer>,
environment_sandboxes: impl IntoIterator<Item = (String, Arc<FileSystemSandboxContext>)>,
) {
let environment_sandboxes = environment_sandboxes.into_iter().collect::<HashMap<_, _>>();
self.server_permissions = servers
.iter()
.filter(|(_, server)| server.enabled())
.filter_map(|(server_name, _)| {
let server = self.mcp_server_catalog.server(server_name)?;
let permissions = if server
.source()
.is_host_owned_apps(server_name, server.config())
{
McpServerPermissions::Thread
} else if let Some(sandbox) =
environment_sandboxes.get(&server.config().environment_id)
{
McpServerPermissions::Environment(Arc::clone(sandbox))
} else if server.config().is_local_environment()
|| matches!(server.source(), McpServerSource::SelectedPlugin(_))
{
McpServerPermissions::Thread
} else {
return None;
};
Some((server_name.clone(), permissions))
})
.collect();
}
/// Returns this server's published permission authority.
pub fn permission_profile_for_server(&self, server_name: &str) -> Option<&PermissionProfile> {
Some(match self.server_permissions.get(server_name)? {
McpServerPermissions::Thread => &self.permission_profile,
McpServerPermissions::Environment(sandbox) => &sandbox.permissions,
})
}
/// Standalone discovery and resource reads must not inherit thread execution authority.
pub fn for_threadless_operations(&self, servers: &HashMap<String, EffectiveMcpServer>) -> Self {
let mut config = self.clone();
config.permission_profile = PermissionProfile::default();
config.server_permissions = servers
.iter()
.filter(|(_, server)| server.enabled())
.map(|(name, _)| (name.clone(), McpServerPermissions::Thread))
.collect();
config
}
}
/// Plugin attribution and selection data derived from the current MCP configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolPluginContext {
plugin_display_names_by_connector_id: HashMap<String, Vec<String>>,
disabled_connector_ids: HashSet<String>,
plugin_display_names_by_mcp_server_name: HashMap<String, Vec<String>>,
plugin_ids_by_mcp_server_name: HashMap<String, String>,
selected_plugin_mcp_server_names: HashSet<String>,
}
impl ToolPluginContext {
pub(crate) fn allows_connector_id(&self, connector_id: Option<&str>) -> bool {
connector_id.is_none_or(|id| !self.disabled_connector_ids.contains(id))
}
pub fn plugin_display_names_for_connector_id(&self, connector_id: &str) -> &[String] {
self.plugin_display_names_by_connector_id
.get(connector_id)
.map(Vec::as_slice)
.unwrap_or(&[])
}
pub fn plugin_display_names_for_mcp_server_name(&self, server_name: &str) -> &[String] {
self.plugin_display_names_by_mcp_server_name
.get(server_name)
.map(Vec::as_slice)
.unwrap_or(&[])
}
pub fn plugin_id_for_mcp_server_name(&self, server_name: &str) -> Option<&str> {
self.plugin_ids_by_mcp_server_name
.get(server_name)
.map(String::as_str)
}
pub(crate) fn is_selected_plugin_mcp_server(&self, server_name: &str) -> bool {
self.selected_plugin_mcp_server_names.contains(server_name)
}
fn from_config(config: &McpConfig) -> Self {
let mut tool_plugin_context = Self {
disabled_connector_ids: config.connector_snapshot.disabled_connector_ids().clone(),
..Self::default()
};
for connector_id in config.connector_snapshot.connector_ids() {
tool_plugin_context
.plugin_display_names_by_connector_id
.insert(
connector_id.0.clone(),
config
.connector_snapshot
.plugin_display_names_for_connector_id(&connector_id.0)
.to_vec(),
);
}
for (server_name, attribution) in config
.mcp_server_catalog
.plugin_attributions_by_server_name()
{
tool_plugin_context
.plugin_display_names_by_mcp_server_name
.insert(
server_name.clone(),
vec![attribution.display_name().to_string()],
);
tool_plugin_context
.plugin_ids_by_mcp_server_name
.insert(server_name, attribution.plugin_id().to_string());
}
tool_plugin_context.selected_plugin_mcp_server_names.extend(
config
.mcp_server_catalog
.selected_plugin_server_names()
.map(str::to_string),
);
for plugin_names in tool_plugin_context
.plugin_display_names_by_connector_id
.values_mut()
.chain(
tool_plugin_context
.plugin_display_names_by_mcp_server_name
.values_mut(),
)
{
plugin_names.sort_unstable();
plugin_names.dedup();
}
tool_plugin_context
}
}
pub fn host_owned_codex_apps_enabled(config: &McpConfig, auth: Option<&CodexAuth>) -> bool {
config.apps_enabled && auth.is_some_and(CodexAuth::uses_codex_backend)
}
pub fn configured_mcp_servers(config: &McpConfig) -> HashMap<String, McpServerConfig> {
config.mcp_server_catalog.configured_servers()
}
pub fn effective_mcp_servers(
config: &McpConfig,
auth: Option<&CodexAuth>,
) -> HashMap<String, EffectiveMcpServer> {
effective_mcp_servers_from_configured(configured_mcp_servers(config), config, auth)
}
pub(crate) fn is_trusted_chatgpt_mcp_server(
transport: &McpServerTransportConfig,
chatgpt_base_url: &str,
) -> bool {
let McpServerTransportConfig::StreamableHttp { url, .. } = transport else {
return false;
};
let Ok(server_url) = url::Url::parse(url) else {
return false;
};
if !matches!(server_url.scheme(), "http" | "https") {
return false;
}
if [CHATGPT_CODEX_BASE_URL, "https://gov.chatgpt.com"]
.into_iter()
.filter_map(|base_url| url::Url::parse(base_url).ok())
.any(|trusted_url| server_url.origin() == trusted_url.origin())
{
return true;
}
url::Url::parse(chatgpt_base_url)
.ok()
.is_some_and(|staging_url| {
staging_url.scheme() == "https"
&& staging_url.domain().is_some_and(|host| {
host == "chatgpt-staging.com" || host.ends_with(".chatgpt-staging.com")
})
&& server_url.origin() == staging_url.origin()
})
}
/// Converts a materialized server map to its auth-gated runtime view.
///
/// Compatibility built-ins and extension overlays must already be reflected in
/// `configured_servers`; this function does not synthesize missing servers.
///
/// # Panics
///
/// Panics if a materialized server is missing from the catalog.
pub fn effective_mcp_servers_from_configured(
configured_servers: HashMap<String, McpServerConfig>,
config: &McpConfig,
auth: Option<&CodexAuth>,
) -> HashMap<String, EffectiveMcpServer> {
let mut servers = configured_servers
.into_iter()
.map(|(name, mut server)| {
#[expect(
clippy::expect_used,
reason = "materialized servers must have catalog registrations"
)]
let registration = config
.mcp_server_catalog
.server(&name)
.expect("materialized MCP server must have a catalog registration");
match server.auth.clone() {
McpServerAuth::ChatGpt => {
if !is_trusted_chatgpt_mcp_server(&server.transport, &config.chatgpt_base_url) {
server.auth = McpServerAuth::OAuth;
}
}
McpServerAuth::OAuth | McpServerAuth::EmaAuth => {}
}
(
name,
EffectiveMcpServer::from_config_with_policy(
server,
registration.credential_policy(),
)
.with_agent_plugin(registration.source().is_agent_plugin()),
)
})
.collect::<HashMap<_, _>>();
if !host_owned_codex_apps_enabled(config, auth) {
servers.remove(CODEX_APPS_MCP_SERVER_NAME);
}
servers
}
pub fn tool_plugin_context(config: &McpConfig) -> ToolPluginContext {
ToolPluginContext::from_config(config)
}
#[allow(clippy::too_many_arguments)]
pub async fn read_mcp_resource(
config: &McpConfig,
auth: Option<&CodexAuth>,
runtime_auth: Option<(
codex_runtime_agent_instance::RuntimeAuthSlot,
codex_features::RuntimeAuthMode,
)>,
runtime_context: McpRuntimeContext,
codex_apps_tools_cache: ConnectorRuntimeManager<ToolInfo>,
tool_catalog_cache: crate::McpToolCatalogCache,
server: &str,
params: ReadResourceRequestParams,
) -> anyhow::Result<ReadResourceResult> {
let mut mcp_servers = effective_mcp_servers(config, auth);
mcp_servers.retain(|name, _| name == server);
let cancel_token = CancellationToken::new();
let runtime_config = config.for_threadless_operations(&mcp_servers);
let manager = McpConnectionSet::new(
/*ema_auth*/ None,
/*existing_ema*/ None,
/*previous*/ None,
McpPublicationGate::already_published(),
McpRuntimeInput {
network_policy_metadata: None,
runtime_auth,
startup_policy: McpStartupPolicy::Eager,
config: Arc::new(runtime_config),
plugins_available: false,
ready_selected_capability_roots: Vec::new(),
mcp_servers,
submit_id: String::new(),
tx_event: None,
startup_cancellation_token: cancel_token.clone(),
runtime_context,
codex_apps_tools_cache,
tool_catalog_cache,
codex_apps_tools_cache_key: connector_runtime_context_key(auth),
client_mcp_extensions: ClientMcpExtensions::default(),
auth: auth.cloned(),
auth_manager: None,
elicitation_reviewer: None,
elicitation_lifecycle: None,
},
crate::elicitation::ElicitationRequestRouter::default(),
)
.await;
let result = manager.read_resource(server, params).await;
cancel_token.cancel();
result
}
#[derive(Debug, Clone)]
pub struct McpServerStatusSnapshot {
pub server_infos: HashMap<String, McpServerInfo>,
pub server_capabilities: HashMap<String, serde_json::Value>,
pub tool_list_meta: HashMap<String, Arc<serde_json::Value>>,
pub tools_by_server: HashMap<String, HashMap<String, Tool>>,
pub tools_errors: HashMap<String, String>,
pub resources: HashMap<String, Vec<Resource>>,
pub resource_templates: HashMap<String, Vec<ResourceTemplate>>,
pub auth_statuses: HashMap<String, McpAuthStatus>,
pub server_names: Vec<String>,
}
#[allow(clippy::too_many_arguments)]
pub async fn collect_mcp_server_status_snapshot_with_detail(
config: &McpConfig,
auth: Option<&CodexAuth>,
auth_manager: Option<&Arc<codex_login::AuthManager>>,
runtime_auth: Option<(
codex_runtime_agent_instance::RuntimeAuthSlot,
codex_features::RuntimeAuthMode,
)>,
runtime_context: McpRuntimeContext,
codex_apps_tools_cache: ConnectorRuntimeManager<ToolInfo>,
tool_catalog_cache: crate::McpToolCatalogCache,
detail: McpSnapshotDetail,
server_name: Option<&str>,
) -> McpServerStatusSnapshot {
let mut mcp_servers = effective_mcp_servers(config, auth);
mcp_servers.retain(|name, _| server_name.is_none_or(|selected| name == selected));
if mcp_servers.is_empty() {
return McpServerStatusSnapshot {
server_infos: HashMap::new(),
server_capabilities: HashMap::new(),
tool_list_meta: HashMap::new(),
tools_by_server: HashMap::new(),
tools_errors: HashMap::new(),
resources: HashMap::new(),
resource_templates: HashMap::new(),
auth_statuses: HashMap::new(),
server_names: Vec::new(),
};
}
let auth_status_entries = compute_auth_statuses(
mcp_servers.iter(),
config.mcp_oauth_credentials_store_mode,
config.auth_keyring_backend_kind,
auth,
auth_manager,
&config.ema_state,
&runtime_context,
)
.await;
let server_names = mcp_servers.keys().cloned().collect();
let cancel_token = CancellationToken::new();
let runtime_config = config.for_threadless_operations(&mcp_servers);
let mcp_connection_manager = McpConnectionSet::new(
/*ema_auth*/ None,
/*existing_ema*/ None,
/*previous*/ None,
McpPublicationGate::already_published(),
McpRuntimeInput {
network_policy_metadata: None,
runtime_auth,
startup_policy: McpStartupPolicy::Eager,
config: Arc::new(runtime_config),
plugins_available: false,
ready_selected_capability_roots: Vec::new(),
mcp_servers,
submit_id: String::new(),
tx_event: None,
startup_cancellation_token: cancel_token.clone(),
runtime_context,
codex_apps_tools_cache,
tool_catalog_cache,
codex_apps_tools_cache_key: connector_runtime_context_key(auth),
client_mcp_extensions: ClientMcpExtensions::default(),
auth: auth.cloned(),
auth_manager: None,
elicitation_reviewer: None,
elicitation_lifecycle: None,
},
crate::elicitation::ElicitationRequestRouter::default(),
)
.await;
let snapshot = collect_mcp_server_status_snapshot_from_manager(
&mcp_connection_manager,
auth_status_entries,
server_names,
detail,
)
.await;
cancel_token.cancel();
snapshot
}
/// The Responses API requires tool names to match `^[a-zA-Z0-9_-]+$`.
/// MCP server/tool names are user-controlled, so sanitize the fully-qualified
/// name we expose to the model by replacing any disallowed character with `_`.
pub(crate) fn sanitize_responses_api_tool_name(name: &str) -> String {
let mut sanitized = String::with_capacity(name.len());
for c in name.chars() {
if c.is_ascii_alphanumeric() || c == '_' {
sanitized.push(c);
} else {
sanitized.push('_');
}
}
if sanitized.is_empty() {
"_".to_string()
} else {
sanitized
}
}
fn codex_apps_mcp_bearer_token_env_var() -> Option<String> {
match env::var(CODEX_CONNECTORS_TOKEN_ENV_VAR) {
Ok(value) if !value.trim().is_empty() => Some(CODEX_CONNECTORS_TOKEN_ENV_VAR.to_string()),
Ok(_) => None,
Err(env::VarError::NotPresent) => None,
Err(env::VarError::NotUnicode(_)) => Some(CODEX_CONNECTORS_TOKEN_ENV_VAR.to_string()),
}
}
fn normalize_codex_apps_base_url(base_url: &str) -> String {
let mut base_url = base_url.trim_end_matches('/').to_string();
if (base_url.starts_with("https://chatgpt.com")
|| base_url.starts_with("https://chat.openai.com"))
&& !base_url.contains("/backend-api")
{
base_url = format!("{base_url}/backend-api");
}
base_url
}
fn codex_apps_mcp_url_for_base_url(base_url: &str) -> String {
let base_url = normalize_codex_apps_base_url(base_url);
let base_url = if base_url.contains("/backend-api") || base_url.contains("/api/codex") {
base_url
} else {
format!("{base_url}/api/codex")
};
format!("{base_url}/ps/mcp")
}
pub fn codex_apps_mcp_server_config(
chatgpt_base_url: &str,
apps_mcp_product_sku: Option<&str>,
originator: Option<&str>,
) -> McpServerConfig {
mcp_server_config_for_url(
codex_apps_mcp_url_for_base_url(chatgpt_base_url),
apps_mcp_product_sku,
originator,
McpServerAuth::ChatGpt,
)
}
/// Builds the ChatGPT-hosted plugin runtime served by plugin-service.
pub fn hosted_plugin_runtime_mcp_server_config(
chatgpt_base_url: &str,
apps_mcp_product_sku: Option<&str>,
originator: Option<&str>,
) -> McpServerConfig {
codex_apps_mcp_server_config(chatgpt_base_url, apps_mcp_product_sku, originator)
}
fn mcp_server_config_for_url(
url: String,
apps_mcp_product_sku: Option<&str>,
originator: Option<&str>,
auth_mode: McpServerAuth,
) -> McpServerConfig {
let product_sku = apps_mcp_product_sku.unwrap_or(DEFAULT_CODEX_APPS_MCP_PRODUCT_SKU);
let mut http_headers =
HashMap::from([("X-OpenAI-Product-Sku".to_string(), product_sku.to_string())]);
if let Some(originator) = originator {
http_headers.insert("originator".to_string(), originator.to_string());
}
let env_http_headers = None;
McpServerConfig {
transport: McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var: codex_apps_mcp_bearer_token_env_var(),
http_headers: Some(http_headers),
env_http_headers,
http_headers_helper: None,
},
auth: auth_mode,
environment_id: codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: Some(Duration::from_secs(30)),
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
}
}
fn protocol_tool_from_rmcp_tool(name: &str, tool: &rmcp::model::Tool) -> Option<Tool> {
match serde_json::to_value(tool) {
Ok(value) => match Tool::from_mcp_value(value) {
Ok(tool) => Some(tool),
Err(err) => {
tracing::warn!("Failed to convert MCP tool '{name}': {err}");
None
}
},
Err(err) => {
tracing::warn!("Failed to serialize MCP tool '{name}': {err}");
None
}
}
}
fn auth_statuses_from_entries(
auth_status_entries: &HashMap<String, crate::mcp::auth::McpAuthStatusEntry>,
) -> HashMap<String, McpAuthStatus> {
auth_status_entries
.iter()
.map(|(name, entry)| (name.clone(), McpAuthStatus::from(entry.auth_state)))
.collect::<HashMap<_, _>>()
}
fn convert_mcp_resources(
resources: HashMap<String, Vec<rmcp::model::Resource>>,
) -> HashMap<String, Vec<Resource>> {
resources
.into_iter()
.map(|(name, resources)| {
let resources = resources
.into_iter()
.filter_map(|resource| match serde_json::to_value(resource) {
Ok(value) => match Resource::from_mcp_value(value.clone()) {
Ok(resource) => Some(resource),
Err(err) => {
let (uri, resource_name) = match value {
Value::Object(obj) => (
obj.get("uri")
.and_then(|v| v.as_str().map(ToString::to_string)),
obj.get("name")
.and_then(|v| v.as_str().map(ToString::to_string)),
),
_ => (None, None),
};
tracing::warn!(
"Failed to convert MCP resource (uri={uri:?}, name={resource_name:?}): {err}"
);
None
}
},
Err(err) => {
tracing::warn!("Failed to serialize MCP resource: {err}");
None
}
})
.collect::<Vec<_>>();
(name, resources)
})
.collect::<HashMap<_, _>>()
}
fn convert_mcp_resource_templates(
resource_templates: HashMap<String, Vec<rmcp::model::ResourceTemplate>>,
) -> HashMap<String, Vec<ResourceTemplate>> {
resource_templates
.into_iter()
.map(|(name, templates)| {
let templates = templates
.into_iter()
.filter_map(|template| match serde_json::to_value(template) {
Ok(value) => match ResourceTemplate::from_mcp_value(value.clone()) {
Ok(template) => Some(template),
Err(err) => {
let (uri_template, template_name) = match value {
Value::Object(obj) => (
obj.get("uriTemplate")
.or_else(|| obj.get("uri_template"))
.and_then(|v| v.as_str().map(ToString::to_string)),
obj.get("name")
.and_then(|v| v.as_str().map(ToString::to_string)),
),
_ => (None, None),
};
tracing::warn!(
"Failed to convert MCP resource template (uri_template={uri_template:?}, name={template_name:?}): {err}"
);
None
}
},
Err(err) => {
tracing::warn!("Failed to serialize MCP resource template: {err}");
None
}
})
.collect::<Vec<_>>();
(name, templates)
})
.collect::<HashMap<_, _>>()
}
pub(crate) async fn collect_mcp_server_status_snapshot_from_manager(
mcp_connection_manager: &McpConnectionSet,
auth_status_entries: HashMap<String, crate::mcp::auth::McpAuthStatusEntry>,
server_names: Vec<String>,
detail: McpSnapshotDetail,
) -> McpServerStatusSnapshot {
let selected_servers: HashSet<&str> = server_names.iter().map(String::as_str).collect();
let include_server = |name: &str| selected_servers.contains(name);
let ((server_infos, (tools, tools_errors, tool_list_meta)), resources, resource_templates) = tokio::join!(
async {
let server_infos = mcp_connection_manager
.list_available_server_infos(include_server)
.await;
let tools = mcp_connection_manager
.list_catalogs_with_errors(include_server)
.await;
(server_infos, tools)
},
async {
if detail.include_resources() {
mcp_connection_manager
.list_all_resources(include_server)
.await
} else {
HashMap::new()
}
},
async {
if detail.include_resources() {
mcp_connection_manager
.list_all_resource_templates(include_server)
.await
} else {
HashMap::new()
}
},
);
let server_capabilities =
mcp_connection_manager.list_available_server_capabilities(include_server);
let mut tools_by_server = HashMap::<String, HashMap<String, Tool>>::new();
for tool_info in tools {
let raw_tool_name = tool_info.tool.name.to_string();
let Some(tool) = protocol_tool_from_rmcp_tool(&raw_tool_name, &tool_info.tool) else {
continue;
};
let tool_name = tool.name.clone();
tools_by_server
.entry(tool_info.server_name)
.or_default()
.insert(tool_name, tool);
}
// Status-only discovery has no event channel. Report OAuth and EMA failures from the completed
// connection attempt instead of retaining the credential-presence status read beforehand.
let mut auth_statuses = auth_statuses_from_entries(&auth_status_entries);
for server_name in mcp_connection_manager.authentication_failed_servers().await {
if auth_statuses.get(&server_name) == Some(&McpAuthStatus::OAuth)
|| auth_status_entries
.get(&server_name)
.and_then(|entry| entry.config.as_ref())
.is_some_and(|config| matches!(config.auth, McpServerAuth::EmaAuth))
{
auth_statuses.insert(server_name, McpAuthStatus::NotLoggedIn);
}
}
McpServerStatusSnapshot {
server_capabilities,
tool_list_meta,
server_infos,
tools_by_server,
tools_errors,
resources: convert_mcp_resources(resources),
resource_templates: convert_mcp_resource_templates(resource_templates),
auth_statuses,
server_names,
}
}
#[cfg(test)]
#[path = "mod_tests.rs"]
pub(crate) mod tests;

View File

@@ -0,0 +1,913 @@
use super::*;
use crate::McpPluginAttribution;
use crate::McpServerPermissions;
use crate::McpServerRegistration;
use crate::connection_manager::tests::create_ready_async_managed_client;
use crate::mcp::auth::McpAuthStatusEntry;
use crate::rmcp_client::StartupOutcomeError;
use crate::server::McpCredentialPolicy;
use anyhow::Context;
use codex_config::Constrained;
use codex_config::types::AppToolApproval;
use codex_config::types::AuthKeyringBackendKind;
use codex_exec_server_test_support::environment_manager_without_environments;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_plugin::AppConnectorId;
use codex_plugin::PluginCapabilitySummary;
use codex_protocol::models::ManagedFileSystemPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::GranularApprovalConfig;
use codex_rmcp_client::McpAuthState;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
#[tokio::test]
async fn ema_auth_statuses_do_not_wait_for_account_refresh() -> anyhow::Result<()> {
let home = tempfile::tempdir()?;
// Account ID token for user/workspace, issued by idp.example to account-client.
let id_token = concat!(
"eyJhbGciOiJFUzI1NiJ9.",
"eyJpc3MiOiJodHRwczovL2lkcC5leGFtcGxlIiwic3ViIjoidXNlciIsImF1ZCI6ImFjY291bnQt",
"Y2xpZW50IiwiZXhwIjoxLCJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91",
"c2VyX2lkIjoidXNlciIsImNoYXRncHRfYWNjb3VudF9pZCI6IndvcmtzcGFjZSJ9fQ",
".signature",
);
std::fs::write(
home.path().join("auth.json"),
serde_json::to_vec(&serde_json::json!({
"auth_mode": "chatgpt",
"tokens": {
"id_token": id_token,
"access_token": "account-access",
"refresh_token": "account-refresh",
"account_id": "workspace",
"login_owner_id": "completed-login",
"oauth_provenance": {
"issuer": "https://idp.example",
"client_id": "account-client"
}
},
"last_refresh": "2099-01-01T00:00:00Z"
}))?,
)?;
let manager = AuthManager::shared(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::default(),
codex_login::test_support::transport_default_auth_route_config(),
)
.await;
let auth = manager.auth_cached().context("account auth")?;
let lease = manager
.lease_account_oauth_grant()
.await?
.context("account grant")?;
let mut servers = HashMap::new();
for name in ["first", "second"] {
let mut server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": format!("https://resource.example/{name}"),
"auth": "ema_auth"
}))?;
server
.resolve_ema_registration(&codex_config::McpServerIdpOAuthConfig {
issuer: "https://idp.example".into(),
client_id: "enterprise-client".into(),
client_secret: None,
token_endpoint_auth_method: None,
})
.map_err(anyhow::Error::msg)?;
servers.insert(
name.to_string(),
EffectiveMcpServer::from_host_config(server),
);
}
let runtime_context = McpRuntimeContext::new(
Arc::new(environment_manager_without_environments()),
home.path().to_path_buf(),
);
let statuses = tokio::time::timeout(
Duration::from_secs(5),
compute_auth_statuses(
servers.iter(),
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Some(&auth),
Some(&manager),
&crate::EmaState::default(),
&runtime_context,
),
)
.await
.context("MCP auth status waited for the held account lease")?;
assert_eq!(
statuses
.into_iter()
.map(|(name, entry)| (name, entry.auth_state))
.collect::<HashMap<_, _>>(),
HashMap::from([
("first".to_string(), McpAuthState::BearerToken),
("second".to_string(), McpAuthState::BearerToken),
]),
);
drop(lease);
Ok(())
}
#[tokio::test]
async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures() {
let auth_failure = StartupOutcomeError::Failed {
error: "OAuth refresh token was rejected".to_string(),
is_authentication_required: true,
is_ema_authentication_required: false,
shutdown: None,
};
let mut manager = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
let mut auth_status_entries = HashMap::new();
for (name, auth_state, startup_error) in [
(
"oauth-failed",
McpAuthState::OAuth,
Some(auth_failure.clone()),
),
("oauth-ready", McpAuthState::OAuth, None),
(
"oauth-provider-error",
McpAuthState::OAuth,
Some(StartupOutcomeError::Failed {
error: "provider temporarily unavailable".to_string(),
is_authentication_required: false,
is_ema_authentication_required: false,
shutdown: None,
}),
),
(
"ema-failed",
McpAuthState::BearerToken,
Some(auth_failure.clone()),
),
("ema-ready", McpAuthState::BearerToken, None),
(
"ema-provider-error",
McpAuthState::BearerToken,
Some(anyhow::anyhow!("provider temporarily unavailable").into()),
),
("bearer", McpAuthState::BearerToken, Some(auth_failure)),
] {
let mut client = create_ready_async_managed_client(Vec::new()).await;
if let Some(error) = startup_error {
client.client = futures::future::ready(Err(error)).boxed().shared();
}
manager.insert_test_client(name, client);
auth_status_entries.insert(
name.to_string(),
McpAuthStatusEntry {
config: name.starts_with("ema-").then(|| {
serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp", "auth": "ema_auth",
}))
.expect("EMA config")
}),
auth_state,
},
);
}
let server_names = auth_status_entries.keys().cloned().collect();
let snapshot = collect_mcp_server_status_snapshot_from_manager(
&manager,
auth_status_entries,
server_names,
McpSnapshotDetail::ToolsAndAuthOnly,
)
.await;
assert_eq!(
snapshot.auth_statuses,
HashMap::from([
("oauth-failed".to_string(), McpAuthStatus::NotLoggedIn),
("oauth-ready".to_string(), McpAuthStatus::OAuth),
("oauth-provider-error".to_string(), McpAuthStatus::OAuth),
("ema-failed".to_string(), McpAuthStatus::NotLoggedIn),
("ema-ready".to_string(), McpAuthStatus::BearerToken),
("ema-provider-error".to_string(), McpAuthStatus::BearerToken),
("bearer".to_string(), McpAuthStatus::BearerToken),
]),
);
}
pub(crate) fn test_mcp_config(codex_home: PathBuf) -> McpConfig {
McpConfig {
chatgpt_base_url: "https://chatgpt.com".to_string(),
apps_mcp_product_sku: None,
requires_read_only_mcp_tools: false,
codex_home,
mcp_enterprise_managed_auth: None,
ema_state: Default::default(),
mcp_ema_cancellation: codex_config::McpEmaCancellation::default(),
xaa_enabled: false,
mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode::default(),
oauth_refresh_mode: McpOAuthRefreshMode::Legacy,
auth_keyring_backend_kind: AuthKeyringBackendKind::default(),
mcp_oauth_callback_port: None,
mcp_oauth_callback_url: None,
optional_mcp_startup_grace: DEFAULT_OPTIONAL_MCP_STARTUP_GRACE,
skill_mcp_dependency_install_enabled: true,
approval_policy: Constrained::allow_any(AskForApproval::OnRequest),
permission_profile: PermissionProfile::default(),
host_cwd: AbsolutePathBuf::current_dir().expect("test working directory"),
config_layer_stack: codex_config::ConfigLayerStack::default(),
plugins: Default::default(),
approvals_reviewer: codex_config::types::ApprovalsReviewer::default(),
environment_cwds: HashMap::new(),
environment_use_mxc: HashMap::new(),
server_permissions: HashMap::new(),
codex_self_exe: None,
codex_linux_sandbox_exe: None,
use_legacy_landlock: false,
apps_enabled: false,
apps_early_resource_discovery: false,
prefix_mcp_tool_names: true,
non_prefixed_mcp_tool_servers: Vec::new(),
protocol_mode: McpProtocolMode::Legacy,
discover_local_stdio: false,
mcp_tool_list_changed: true,
host_owned_apps_protocol_mode: McpProtocolMode::Legacy,
client_elicitation_capability: ElicitationCapability::default(),
mcp_server_catalog: ResolvedMcpCatalog::default(),
connector_snapshot: codex_connectors::ConnectorSnapshot::default(),
}
}
pub(crate) fn test_elicitation_config(
server_name: &str,
approval_policy: AskForApproval,
permission_profile: PermissionProfile,
) -> Arc<McpConfig> {
let mut config = test_mcp_config(PathBuf::new());
config.approval_policy = Constrained::allow_any(approval_policy);
config.permission_profile = permission_profile;
config
.server_permissions
.insert(server_name.to_string(), McpServerPermissions::Thread);
Arc::new(config)
}
#[test]
fn ema_catalog_allows_only_configured_servers_without_widening_policy() {
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://resource.example/mcp", "auth": "ema_auth",
"oauth": { "client_id": "resource-client", "authorization_server_issuer": "https://as.example" }
})).unwrap();
let plugin = McpPluginAttribution::agent_plugin("plugin@test".into(), "Plugin".into());
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"configured".into(),
server.clone(),
));
catalog.register(McpServerRegistration::from_plugin(
"installed".into(),
plugin.clone(),
/*plugin_order*/ 0,
server.clone(),
));
catalog.register(McpServerRegistration::from_selected_plugin(
"selected".into(),
plugin,
/*selection_order*/ 0,
codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
server,
));
let mut config = test_mcp_config(PathBuf::new());
let idp = codex_config::McpServerIdpOAuthConfig {
issuer: "https://idp.example".into(),
client_secret: None,
token_endpoint_auth_method: None,
client_id: "enterprise-client".into(),
};
let deny_all = codex_protocol::mcp_policy::EnvironmentMcpPolicy {
servers: Some(Default::default()),
plugins: None,
};
for (xaa_enabled, denied) in [(true, false), (true, true), (false, false)] {
let mut catalog = catalog.clone();
if xaa_enabled {
catalog.enable_ema(idp.clone());
}
config.mcp_server_catalog = catalog.build_with_environment_authority(|_| {
if denied {
crate::McpEnvironmentAuthority::Restricted(&deny_all)
} else {
crate::McpEnvironmentAuthority::Unrestricted
}
});
let servers = effective_mcp_servers(&config, /*auth*/ None);
for name in ["configured", "installed", "selected"] {
let eligible = name == "configured" && xaa_enabled;
assert_eq!(servers[name].enabled(), eligible && !denied, "{name}");
assert_eq!(servers[name].config().oauth_idp(), eligible.then_some(&idp));
assert_eq!(servers[name].config().auth, McpServerAuth::EmaAuth);
}
}
}
#[test]
fn qualified_mcp_tool_name_prefix_sanitizes_server_names_without_lowercasing() {
assert_eq!(
qualified_mcp_tool_name_prefix("Some-Server"),
"mcp__Some_Server__".to_string()
);
}
#[test]
fn mcp_server_permissions_handle_unattached_and_threadless_servers() {
let mut config = test_mcp_config(PathBuf::new());
config.permission_profile = PermissionProfile::Disabled;
let mut missing_server = codex_apps_mcp_server_config(
"https://example.com",
/*apps_mcp_product_sku*/ None,
/*originator*/ None,
);
missing_server.environment_id = "missing".to_string();
let mut selected_server = missing_server.clone();
selected_server.environment_id = "unattached".to_string();
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"missing".to_string(),
missing_server,
));
catalog.register(McpServerRegistration::from_selected_plugin(
"selected".to_string(),
McpPluginAttribution::new("selected@test".to_string(), "Selected".to_string()),
/*selection_order*/ 0,
codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
selected_server,
));
config.mcp_server_catalog = catalog.build();
let servers = effective_mcp_servers(&config, /*auth*/ None);
assert_eq!(config.permission_profile_for_server("selected"), None);
config.set_server_permissions(&servers, std::iter::empty());
assert_eq!(
config.permission_profile_for_server("selected"),
Some(&PermissionProfile::Disabled)
);
assert_eq!(config.permission_profile_for_server("missing"), None);
let config = config.for_threadless_operations(&servers);
assert_eq!(
config.permission_profile_for_server("selected"),
Some(&PermissionProfile::default())
);
}
#[test]
fn mcp_prompt_auto_approval_honors_unrestricted_managed_profiles() {
assert!(mcp_permission_prompt_is_auto_approved(
AskForApproval::Never,
&PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Unrestricted,
network: NetworkSandboxPolicy::Enabled,
},
McpPermissionPromptAutoApproveContext::default(),
));
assert!(mcp_permission_prompt_is_auto_approved(
AskForApproval::Never,
&PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Unrestricted,
network: NetworkSandboxPolicy::Restricted,
},
McpPermissionPromptAutoApproveContext::default(),
));
assert!(!mcp_permission_prompt_is_auto_approved(
AskForApproval::Never,
&PermissionProfile::read_only(),
McpPermissionPromptAutoApproveContext::default(),
));
assert!(!mcp_permission_prompt_is_auto_approved(
AskForApproval::OnRequest,
&PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Unrestricted,
network: NetworkSandboxPolicy::Enabled,
},
McpPermissionPromptAutoApproveContext::default(),
));
}
#[test]
fn mcp_prompt_auto_approval_honors_approved_tools_in_all_permission_modes() {
for approval_policy in [
AskForApproval::UnlessTrusted,
AskForApproval::OnRequest,
AskForApproval::Granular(GranularApprovalConfig {
sandbox_approval: true,
rules: true,
skill_approval: true,
request_permissions: true,
mcp_elicitations: true,
}),
AskForApproval::Never,
] {
assert!(mcp_permission_prompt_is_auto_approved(
approval_policy,
&PermissionProfile::read_only(),
McpPermissionPromptAutoApproveContext {
tool_approval_mode: Some(AppToolApproval::Approve),
},
));
}
assert!(!mcp_permission_prompt_is_auto_approved(
AskForApproval::OnRequest,
&PermissionProfile::read_only(),
McpPermissionPromptAutoApproveContext {
tool_approval_mode: Some(AppToolApproval::Auto),
},
));
}
#[test]
fn tool_plugin_context_collects_app_and_mcp_sources() {
let mut config = test_mcp_config(PathBuf::new());
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_plugin(
"alpha".to_string(),
McpPluginAttribution::new("alpha@test".to_string(), "alpha-plugin".to_string()),
/*plugin_order*/ 0,
codex_apps_mcp_server_config(
"https://alpha.example",
/*apps_mcp_product_sku*/ None,
/*originator*/ None,
),
));
config.mcp_server_catalog = catalog.build();
config.connector_snapshot =
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(&[
PluginCapabilitySummary {
config_name: "alpha@test".to_string(),
display_name: "alpha-plugin".to_string(),
plugin_namespace: None,
app_connector_ids: vec![AppConnectorId("connector_example".to_string())],
mcp_server_names: vec!["alpha".to_string()],
..PluginCapabilitySummary::default()
},
PluginCapabilitySummary {
config_name: "beta@test".to_string(),
display_name: "beta-plugin".to_string(),
plugin_namespace: None,
app_connector_ids: vec![
AppConnectorId("connector_example".to_string()),
AppConnectorId("connector_gmail".to_string()),
],
mcp_server_names: vec!["beta".to_string()],
..PluginCapabilitySummary::default()
},
]);
let provenance = tool_plugin_context(&config);
assert_eq!(
provenance,
ToolPluginContext {
disabled_connector_ids: HashSet::new(),
plugin_display_names_by_connector_id: HashMap::from([
(
"connector_example".to_string(),
vec!["alpha-plugin".to_string(), "beta-plugin".to_string()],
),
(
"connector_gmail".to_string(),
vec!["beta-plugin".to_string()],
),
]),
plugin_display_names_by_mcp_server_name: HashMap::from([(
"alpha".to_string(),
vec!["alpha-plugin".to_string()],
)]),
plugin_ids_by_mcp_server_name: HashMap::from([(
"alpha".to_string(),
"alpha@test".to_string(),
)]),
selected_plugin_mcp_server_names: HashSet::new(),
}
);
assert_eq!(
provenance.plugin_id_for_mcp_server_name("alpha"),
Some("alpha@test")
);
assert_eq!(provenance.plugin_id_for_mcp_server_name("beta"), None);
}
#[test]
fn selected_mcp_attribution_does_not_join_an_unrelated_local_summary() {
let mut config = test_mcp_config(PathBuf::new());
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_selected_plugin(
"github".to_string(),
McpPluginAttribution::new(
"shared-plugin-id".to_string(),
"Executor GitHub".to_string(),
),
/*selection_order*/ 0,
"executor-1",
codex_apps_mcp_server_config(
"https://github.example",
/*apps_mcp_product_sku*/ None,
/*originator*/ None,
),
));
config.mcp_server_catalog = catalog.build();
config.connector_snapshot =
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(&[
PluginCapabilitySummary {
config_name: "shared-plugin-id".to_string(),
display_name: "Local GitHub".to_string(),
plugin_namespace: None,
mcp_server_names: vec!["github".to_string()],
..PluginCapabilitySummary::default()
},
]);
let provenance = tool_plugin_context(&config);
assert_eq!(
provenance,
ToolPluginContext {
disabled_connector_ids: HashSet::new(),
plugin_display_names_by_connector_id: HashMap::new(),
plugin_display_names_by_mcp_server_name: HashMap::from([(
"github".to_string(),
vec!["Executor GitHub".to_string()],
)]),
plugin_ids_by_mcp_server_name: HashMap::from([(
"github".to_string(),
"shared-plugin-id".to_string(),
)]),
selected_plugin_mcp_server_names: HashSet::from(["github".to_string()]),
}
);
assert!(provenance.is_selected_plugin_mcp_server("github"));
}
#[test]
fn codex_apps_mcp_url_for_base_url_uses_plugin_service_paths() {
assert_eq!(
codex_apps_mcp_url_for_base_url("https://chatgpt.com/backend-api"),
"https://chatgpt.com/backend-api/ps/mcp"
);
assert_eq!(
codex_apps_mcp_url_for_base_url("https://chat.openai.com"),
"https://chat.openai.com/backend-api/ps/mcp"
);
assert_eq!(
codex_apps_mcp_url_for_base_url("https://gov.chatgpt.com/backend-api/"),
"https://gov.chatgpt.com/backend-api/ps/mcp"
);
assert_eq!(
codex_apps_mcp_url_for_base_url("http://localhost:8080/api/codex"),
"http://localhost:8080/api/codex/ps/mcp"
);
assert_eq!(
codex_apps_mcp_url_for_base_url("http://localhost:8080"),
"http://localhost:8080/api/codex/ps/mcp"
);
}
#[test]
fn codex_apps_server_config_uses_plugin_service_path() {
let config = codex_apps_mcp_server_config(
"https://chatgpt.com",
/*apps_mcp_product_sku*/ None,
/*originator*/ None,
);
let url = match &config.transport {
McpServerTransportConfig::StreamableHttp { url, .. } => url,
_ => panic!("expected streamable http transport for codex apps"),
};
assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp");
}
#[test]
fn codex_apps_server_config_forwards_thread_originator_header() {
let config = codex_apps_mcp_server_config(
"https://chatgpt.com",
/*apps_mcp_product_sku*/ None,
Some("thread_originator"),
);
match &config.transport {
McpServerTransportConfig::StreamableHttp {
http_headers,
env_http_headers,
..
} => {
assert_eq!(
http_headers,
&Some(HashMap::from([
("originator".to_string(), "thread_originator".to_string()),
("X-OpenAI-Product-Sku".to_string(), "codex".to_string()),
]))
);
assert!(env_http_headers.is_none());
}
other => panic!("expected streamable http transport, got {other:?}"),
}
}
#[test]
fn codex_apps_server_config_sets_product_sku_header() {
for (configured_product_sku, expected_product_sku) in [(None, "codex"), (Some("tpp"), "tpp")] {
let config = codex_apps_mcp_server_config(
"https://chatgpt.com",
configured_product_sku,
/*originator*/ None,
);
match &config.transport {
McpServerTransportConfig::StreamableHttp {
http_headers,
env_http_headers,
..
} => {
assert_eq!(
http_headers,
&Some(HashMap::from([(
"X-OpenAI-Product-Sku".to_string(),
expected_product_sku.to_string(),
)]))
);
assert!(env_http_headers.is_none());
}
other => panic!("expected streamable http transport, got {other:?}"),
}
}
}
#[test]
fn codex_apps_server_config_forwards_originator_and_configured_product_sku_headers() {
let config = codex_apps_mcp_server_config(
"https://chatgpt.com",
Some("tpp"),
Some("thread_originator"),
);
match &config.transport {
McpServerTransportConfig::StreamableHttp {
http_headers,
env_http_headers,
..
} => {
assert_eq!(
http_headers,
&Some(HashMap::from([
("originator".to_string(), "thread_originator".to_string()),
("X-OpenAI-Product-Sku".to_string(), "tpp".to_string()),
]))
);
assert!(env_http_headers.is_none());
}
other => panic!("expected streamable http transport, got {other:?}"),
}
}
#[test]
fn effective_mcp_servers_preserve_executor_credential_policy() {
let mut config = test_mcp_config(PathBuf::new());
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://executor.example/mcp",
"environment_id": "remote",
"bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
}))
.expect("valid MCP server config");
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_executor_config(
"executor".to_string(),
server.clone(),
));
catalog.register(McpServerRegistration::from_config(
"host".to_string(),
server,
));
config.mcp_server_catalog = catalog.build();
let effective = effective_mcp_servers(&config, /*auth*/ None);
assert_eq!(
effective["executor"].credential_policy(),
McpCredentialPolicy::ExecutorOnly,
);
assert_eq!(
effective["host"].credential_policy(),
McpCredentialPolicy::HostFallbackAllowed,
);
}
#[test]
#[should_panic(expected = "materialized MCP server must have a catalog registration")]
fn effective_mcp_servers_require_catalog_registration() {
let config = test_mcp_config(PathBuf::new());
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://executor.example/mcp",
"environment_id": "remote",
"bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
}))
.expect("valid MCP server config");
effective_mcp_servers_from_configured(
HashMap::from([("unregistered".to_string(), server)]),
&config,
/*auth*/ None,
);
}
#[test]
fn effective_mcp_servers_preserve_chatgpt_auth_for_trusted_origins() {
for (base_url, server_url) in [
("https://chatgpt-staging.com", "https://chatgpt-staging.com"),
(
"https://preview.chatgpt-staging.com",
"https://preview.chatgpt-staging.com",
),
("https://gov.chatgpt.com", "https://chatgpt.com"),
(
"https://chatgpt.com",
"https://gov.chatgpt.com/backend-api/",
),
("https://chatgpt.com", "https://GOV.CHATGPT.COM:443"),
] {
let mut config = test_mcp_config(PathBuf::new());
config.chatgpt_base_url = base_url.to_string();
let server = codex_apps_mcp_server_config(
server_url, /*apps_mcp_product_sku*/ None, /*originator*/ None,
);
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"trusted".to_string(),
server,
));
config.mcp_server_catalog = catalog.build();
let effective = effective_mcp_servers(&config, /*auth*/ None);
assert_eq!(
effective["trusted"].config().auth,
McpServerAuth::ChatGpt,
"backend {base_url}, server {server_url}",
);
}
}
#[test]
fn effective_mcp_servers_reject_untrusted_origins_for_chatgpt_auth() {
for url in [
"http://gov.chatgpt.com",
"https://gov.chatgpt.com:8443",
"https://gov.chatgpt.com.evil.example",
"https://sub.gov.chatgpt.com",
"https://gov.chatgpt.com.",
"https://gov.chatgpt.com@evil.example",
"https://example.com",
] {
let mut config = test_mcp_config(PathBuf::new());
config.chatgpt_base_url = url.to_string();
let server = codex_apps_mcp_server_config(
url, /*apps_mcp_product_sku*/ None, /*originator*/ None,
);
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"untrusted".to_string(),
server,
));
config.mcp_server_catalog = catalog.build();
let effective = effective_mcp_servers(&config, /*auth*/ None);
assert_eq!(
effective["untrusted"].config().auth,
McpServerAuth::OAuth,
"server {url}",
);
}
}
#[tokio::test]
async fn effective_mcp_servers_preserve_runtime_servers() {
let codex_home = tempfile::tempdir().expect("tempdir");
let mut config = test_mcp_config(codex_home.path().to_path_buf());
config.apps_enabled = true;
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"sample".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://user.example/mcp".to_string(),
bearer_token_env_var: None,
http_headers: None,
env_http_headers: None,
http_headers_helper: None,
},
environment_id: codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
},
));
catalog.register(McpServerRegistration::from_config(
"docs".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://docs.example/mcp".to_string(),
bearer_token_env_var: None,
http_headers: None,
env_http_headers: None,
http_headers_helper: None,
},
environment_id: codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
},
));
catalog.register(McpServerRegistration::from_config(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
codex_apps_mcp_server_config(
&config.chatgpt_base_url,
config.apps_mcp_product_sku.as_deref(),
/*originator*/ None,
),
));
config.mcp_server_catalog = catalog.build();
let effective = effective_mcp_servers(&config, Some(&auth));
let sample = effective.get("sample").expect("user server should exist");
let docs = effective
.get("docs")
.expect("configured server should exist");
let codex_apps = effective
.get(CODEX_APPS_MCP_SERVER_NAME)
.expect("codex apps server should exist");
let sample = sample.config();
let docs = docs.config();
let codex_apps = codex_apps.config();
match &sample.transport {
McpServerTransportConfig::StreamableHttp { url, .. } => {
assert_eq!(url, "https://user.example/mcp");
}
other => panic!("expected streamable http transport, got {other:?}"),
}
match &docs.transport {
McpServerTransportConfig::StreamableHttp { url, .. } => {
assert_eq!(url, "https://docs.example/mcp");
}
other => panic!("expected streamable http transport, got {other:?}"),
}
match &codex_apps.transport {
McpServerTransportConfig::StreamableHttp { url, .. } => {
assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp");
}
other => panic!("expected streamable http transport, got {other:?}"),
}
}

View File

@@ -0,0 +1,143 @@
//! Resolve the model's Search profile on an already authorized Apps connection.
//! Keep the projected declaration and invocation pin private to its sampling step.
use super::McpBinding;
use crate::CODEX_APPS_MCP_SERVER_NAME;
use crate::MCP_TOOL_CODEX_APPS_META_KEY;
use crate::pagination::MAX_CODEX_APPS_TOOL_CATALOG_ITEMS;
use crate::pagination::collect_paginated_with_limit;
use rmcp::model::RequestMetaObject;
use serde_json::Value as JsonValue;
use std::sync::Arc;
use std::time::Duration;
pub const SEARCH_CONNECTOR: &str = "connector_openai_search_service";
pub fn is_model_search_tool(tool: &crate::ToolInfo) -> bool {
tool.server_name == CODEX_APPS_MCP_SERVER_NAME
&& tool.connector_id.as_deref() == Some(SEARCH_CONNECTOR)
&& tool.tool.name.rsplit('.').next() == Some("web_run")
}
pub enum SearchDiscovery {
Ready(Arc<McpBinding>),
Critical(&'static str),
Unavailable,
}
impl McpBinding {
/// Preserve the discovery pin while letting normal dispatch recheck current tool visibility,
/// account selection and approval policy. Never transfer the pin to a different transport.
pub fn search_invocation_context(&self, live: &crate::PreparedMcpCall) -> Option<&JsonValue> {
if !live.is_host_owned_apps() {
return None;
}
let tool = live.tool_info();
let scoped = self
.calls
.get(&(tool.server_name.clone(), tool.tool.name.to_string()))?;
if !Arc::ptr_eq(&scoped.client.client, &live.client.client) {
return None;
}
invocation_context(&scoped.tool_info().tool)
}
/// A catalog omission, policy denial, or untrusted registration never authorizes fallback.
pub async fn discover_model_search(&self, turn_metadata: JsonValue) -> SearchDiscovery {
let Some((index, original)) = self
.tools
.iter()
.enumerate()
.find(|(_, tool)| is_model_search_tool(tool))
else {
return SearchDiscovery::Unavailable;
};
let key = (original.server_name.clone(), original.tool.name.to_string());
let Some(call) = self
.calls
.get(&key)
.filter(|call| call.is_host_owned_apps())
else {
return SearchDiscovery::Unavailable;
};
let meta = RequestMetaObject::from(serde_json::Map::from_iter([(
"x-codex-turn-metadata".to_string(),
turn_metadata,
)]));
let client = &call.client;
let limit = Duration::from_secs(5);
let listed = collect_paginated_with_limit(
"tools/list",
/*overall_timeout*/ None,
MAX_CODEX_APPS_TOOL_CATALOG_ITEMS,
|params| {
let mut params = params.unwrap_or_default();
params.meta = Some(meta.clone());
async move {
let page = client
.client
.list_tools_with_connector_ids(Some(params), /*timeout*/ None)
.await?;
Ok((page.tools, page.next_cursor))
}
},
);
let listed = tokio::time::timeout(limit, client.with_lease_request(listed)).await;
let tools = match listed {
Err(_) => return SearchDiscovery::Critical("discovery_timeout"),
Ok(Err(err)) => {
if matches!(
codex_rmcp_client::request_error_code(&err),
Some("transport_closed" | "request_timeout")
) || codex_rmcp_client::is_retryable_transport_error(&err)
|| codex_rmcp_client::mcp_error(&err).is_some_and(|e| e.code.0 == -32603)
{
return SearchDiscovery::Critical("discovery_error");
}
return SearchDiscovery::Unavailable;
}
Ok(Ok(tools)) => tools,
};
let Some(listed) = tools.into_iter().find(|tool| {
tool.connector_id.as_deref() == Some(SEARCH_CONNECTOR)
&& tool.tool.name == original.tool.name
}) else {
return SearchDiscovery::Unavailable;
};
let mut projected = original.clone();
projected.namespace_description = listed.connector_description;
projected.tool = listed.tool;
if !crate::tool_is_model_visible(&projected)
|| invocation_context(&projected.tool).is_none()
{
return SearchDiscovery::Unavailable;
}
let mut tools = self.tools.to_vec();
tools[index] = projected.clone();
let mut calls = self.calls.clone();
let mut call = call.clone();
call.tool_info = projected.into();
calls.insert(key, call);
SearchDiscovery::Ready(Arc::new(Self::new(
Arc::clone(&self.connections),
Arc::clone(&self.clients),
Arc::clone(&self.config),
self.plugins_available,
tools,
calls,
)))
}
}
// The connector owns the contents of its invocation context.
fn invocation_context(tool: &rmcp::model::Tool) -> Option<&JsonValue> {
tool.meta
.as_ref()?
.get(MCP_TOOL_CODEX_APPS_META_KEY)?
.get("invocation_context")
.filter(|context| context.is_object())
}
#[cfg(test)]
#[path = "model_search_tests.rs"]
mod tests;

View File

@@ -0,0 +1,20 @@
#![cfg(test)]
use super::invocation_context;
use rmcp::model::Tool;
use serde_json::json;
#[test]
fn discovery_preserves_the_connectors_opaque_invocation_context() {
let mut declaration = json!({
"name": "search_service.web_run",
"inputSchema": {"type": "object"},
});
let tool: Tool = serde_json::from_value(declaration.clone()).unwrap();
assert_eq!(invocation_context(&tool), None);
let pin = json!({"revision": "connector-selected"});
declaration["_meta"] = json!({"_codex_apps": {"invocation_context": pin}});
let tool: Tool = serde_json::from_value(declaration).unwrap();
assert_eq!(invocation_context(&tool), Some(&pin));
}

View File

@@ -0,0 +1,56 @@
use std::sync::Arc;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use futures::future::BoxFuture;
const OPENAI_DEVELOPER_DOCS_MCP_URL: &str = "https://developers.openai.com/mcp";
const OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL: &str = "https://developers.openai.com/mcp?source=codex";
pub(crate) fn maybe_with_openai_docs_source_attribution(
mcp_server_url: &str,
http_client: Arc<dyn HttpClient>,
) -> Arc<dyn HttpClient> {
if mcp_server_url == OPENAI_DEVELOPER_DOCS_MCP_URL {
Arc::new(OpenAiDocsHttpClient { http_client })
} else {
http_client
}
}
struct OpenAiDocsHttpClient {
http_client: Arc<dyn HttpClient>,
}
impl OpenAiDocsHttpClient {
fn attribute_mcp_request(&self, params: &mut HttpRequestParams) {
if params.url == OPENAI_DEVELOPER_DOCS_MCP_URL {
params.url = OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL.to_string();
}
}
}
impl HttpClient for OpenAiDocsHttpClient {
fn http_request(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.attribute_mcp_request(&mut params);
self.http_client.http_request(params)
}
fn http_request_stream(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.attribute_mcp_request(&mut params);
self.http_client.http_request_stream(params)
}
}
#[cfg(test)]
#[path = "openai_docs_source_attribution_tests.rs"]
mod tests;

View File

@@ -0,0 +1,92 @@
use std::sync::Arc;
use std::sync::Mutex;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use futures::FutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use super::OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL;
use super::OPENAI_DEVELOPER_DOCS_MCP_URL;
use super::maybe_with_openai_docs_source_attribution;
#[derive(Default)]
struct RecordingHttpClient {
urls: Mutex<Vec<String>>,
}
impl HttpClient for RecordingHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.urls.lock().unwrap().push(params.url);
async { Err(ExecServerError::HttpRequest("test response".to_string())) }.boxed()
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.urls.lock().unwrap().push(params.url);
async { Err(ExecServerError::HttpRequest("test response".to_string())) }.boxed()
}
}
fn request(url: &str) -> HttpRequestParams {
HttpRequestParams {
method: "POST".to_string(),
url: url.to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "test-request".to_string(),
stream_response: true,
}
}
#[tokio::test]
async fn attributes_only_docs_mcp_requests() {
let recording_client = Arc::new(RecordingHttpClient::default());
let http_client = maybe_with_openai_docs_source_attribution(
OPENAI_DEVELOPER_DOCS_MCP_URL,
recording_client.clone(),
);
let _ = http_client
.http_request_stream(request(OPENAI_DEVELOPER_DOCS_MCP_URL))
.await;
let _ = http_client
.http_request(request(
"https://developers.openai.com/.well-known/oauth-protected-resource/mcp",
))
.await;
assert_eq!(
recording_client.urls.lock().unwrap().as_slice(),
[
OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL,
"https://developers.openai.com/.well-known/oauth-protected-resource/mcp",
]
);
}
#[test]
fn leaves_other_mcp_clients_unwrapped() {
let recording_client = Arc::new(RecordingHttpClient::default());
let http_client = maybe_with_openai_docs_source_attribution(
"https://example.com/mcp",
recording_client.clone(),
);
assert!(Arc::ptr_eq(
&http_client,
&(recording_client as Arc<dyn HttpClient>)
));
}

View File

@@ -0,0 +1,84 @@
use std::collections::HashSet;
use std::future::Future;
use std::time::Duration;
use anyhow::Result;
use anyhow::anyhow;
use rmcp::model::PaginatedRequestParams;
const MAX_MCP_CATALOG_PAGES: usize = 100;
pub(crate) const MAX_MCP_CATALOG_ITEMS: usize = 2_048;
pub(crate) const MAX_CODEX_APPS_TOOL_CATALOG_ITEMS: usize = 8_192;
const MAX_MCP_PAGINATION_CURSOR_BYTES: usize = 64 * 1024;
const DEFAULT_MCP_PAGINATION_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) async fn collect_paginated<T, F, Fut>(
method: &str,
overall_timeout: Option<Duration>,
fetch: F,
) -> Result<Vec<T>>
where
F: FnMut(Option<PaginatedRequestParams>) -> Fut,
Fut: Future<Output = Result<(Vec<T>, Option<String>)>>,
{
collect_paginated_with_limit(method, overall_timeout, MAX_MCP_CATALOG_ITEMS, fetch).await
}
pub(crate) async fn collect_paginated_with_limit<T, F, Fut>(
method: &str,
overall_timeout: Option<Duration>,
max_items: usize,
mut fetch: F,
) -> Result<Vec<T>>
where
F: FnMut(Option<PaginatedRequestParams>) -> Fut,
Fut: Future<Output = Result<(Vec<T>, Option<String>)>>,
{
let collect = async {
let mut collected = Vec::new();
let mut cursor = None;
let mut seen_cursors = HashSet::new();
let mut page_count = 0;
loop {
if page_count == MAX_MCP_CATALOG_PAGES {
return Err(anyhow!(
"{method} exceeded the pagination limit of {MAX_MCP_CATALOG_PAGES} pages"
));
}
page_count += 1;
let params = cursor.as_ref().map(|next: &String| {
PaginatedRequestParams::default().with_cursor(Some(next.clone()))
});
let (items, next_cursor) = fetch(params).await?;
if items.len() > max_items.saturating_sub(collected.len()) {
return Err(anyhow!(
"{method} exceeded the catalog limit of {max_items} items"
));
}
collected.extend(items);
let Some(next_cursor) = next_cursor else {
return Ok(collected);
};
if next_cursor.len() > MAX_MCP_PAGINATION_CURSOR_BYTES {
return Err(anyhow!(
"{method} returned a pagination cursor exceeding {MAX_MCP_PAGINATION_CURSOR_BYTES} bytes"
));
}
if !seen_cursors.insert(next_cursor.clone()) {
return Err(anyhow!("{method} returned a repeated pagination cursor"));
}
cursor = Some(next_cursor);
}
};
let timeout = overall_timeout.unwrap_or(DEFAULT_MCP_PAGINATION_TIMEOUT);
tokio::time::timeout(timeout, collect)
.await
.map_err(|_| anyhow!("{method} pagination timed out after {timeout:?}"))?
}
#[cfg(test)]
#[path = "pagination_tests.rs"]
mod tests;

View File

@@ -0,0 +1,226 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use anyhow::anyhow;
use pretty_assertions::assert_eq;
use super::MAX_MCP_CATALOG_ITEMS;
use super::MAX_MCP_CATALOG_PAGES;
use super::MAX_MCP_PAGINATION_CURSOR_BYTES;
use super::collect_paginated;
#[tokio::test]
async fn collects_all_pages_including_an_empty_cursor() {
let requests = Arc::new(Mutex::new(Vec::new()));
let observed = Arc::clone(&requests);
let pages = collect_paginated("tools/list", /*overall_timeout*/ None, move |params| {
let observed = Arc::clone(&observed);
async move {
let cursor = params.and_then(|params| params.cursor);
observed.lock().expect("request lock").push(cursor.clone());
match cursor.as_deref() {
None => Ok((vec!["first"], Some(String::new()))),
Some("") => Ok((vec!["second"], Some("last".to_string()))),
Some("last") => Ok((vec!["third"], None)),
Some(cursor) => Err(anyhow!("unexpected cursor: {cursor}")),
}
}
})
.await
.expect("paginated request succeeds");
assert_eq!(pages, vec!["first", "second", "third"]);
assert_eq!(
*requests.lock().expect("request lock"),
vec![None, Some(String::new()), Some("last".to_string())]
);
}
#[tokio::test]
async fn rejects_nonconsecutive_repeated_cursors() {
let error = collect_paginated(
"resources/list",
/*overall_timeout*/ None,
|params| async move {
let cursor = params.and_then(|params| params.cursor);
let next = match cursor.as_deref() {
None => "first",
Some("first") => "second",
Some("second") => "first",
Some(cursor) => return Err(anyhow!("unexpected cursor: {cursor}")),
};
Ok((Vec::<()>::new(), Some(next.to_string())))
},
)
.await
.expect_err("a repeated cursor must fail");
assert_eq!(
error.to_string(),
"resources/list returned a repeated pagination cursor"
);
}
#[tokio::test]
async fn rejects_excessive_pagination_before_fetching_another_page() {
let requests = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&requests);
let error = collect_paginated(
"tools/list",
/*overall_timeout*/ None,
move |_params| {
let observed = Arc::clone(&observed);
async move {
let page = observed.fetch_add(1, Ordering::Relaxed);
Ok((Vec::<()>::new(), Some(page.to_string())))
}
},
)
.await
.expect_err("unbounded pagination must fail");
assert_eq!(
error.to_string(),
format!("tools/list exceeded the pagination limit of {MAX_MCP_CATALOG_PAGES} pages")
);
assert_eq!(requests.load(Ordering::Relaxed), MAX_MCP_CATALOG_PAGES);
}
#[tokio::test]
async fn rejects_a_page_exceeding_the_catalog_item_limit() {
let error = collect_paginated(
"tools/list",
/*overall_timeout*/ None,
|_params| async { Ok((vec![(); MAX_MCP_CATALOG_ITEMS + 1], None)) },
)
.await
.expect_err("an oversized catalog page must fail");
assert_eq!(
error.to_string(),
format!("tools/list exceeded the catalog limit of {MAX_MCP_CATALOG_ITEMS} items")
);
}
#[tokio::test]
async fn rejects_a_catalog_exceeding_the_item_limit_across_pages() {
let error = collect_paginated(
"tools/list",
/*overall_timeout*/ None,
|params| async move {
match params.and_then(|params| params.cursor) {
None => Ok((vec![(); MAX_MCP_CATALOG_ITEMS], Some("last".to_string()))),
Some(cursor) if cursor == "last" => Ok((vec![()], None)),
Some(cursor) => Err(anyhow!("unexpected cursor: {cursor}")),
}
},
)
.await
.expect_err("catalog items must be bounded across pages");
assert_eq!(
error.to_string(),
format!("tools/list exceeded the catalog limit of {MAX_MCP_CATALOG_ITEMS} items")
);
}
#[tokio::test]
async fn rejects_oversized_pagination_cursors_before_following_them() {
let requests = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&requests);
let error = collect_paginated(
"resources/list",
/*overall_timeout*/ None,
move |_params| {
let observed = Arc::clone(&observed);
async move {
observed.fetch_add(1, Ordering::Relaxed);
Ok((
Vec::<()>::new(),
Some("x".repeat(MAX_MCP_PAGINATION_CURSOR_BYTES + 1)),
))
}
},
)
.await
.expect_err("an oversized pagination cursor must fail");
assert_eq!(
error.to_string(),
format!(
"resources/list returned a pagination cursor exceeding {MAX_MCP_PAGINATION_CURSOR_BYTES} bytes"
)
);
assert_eq!(requests.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn forwards_page_failures() {
let error = collect_paginated(
"resources/templates/list",
/*overall_timeout*/ None,
|_params| async { Err::<(Vec<()>, Option<String>), _>(anyhow!("page failed")) },
)
.await
.expect_err("a page error must fail");
assert_eq!(error.to_string(), "page failed");
}
#[tokio::test(start_paused = true)]
async fn applies_a_default_timeout_when_no_timeout_is_configured() {
let error = collect_paginated(
"resources/list",
/*overall_timeout*/ None,
|_params| async {
tokio::time::sleep(Duration::from_secs(31)).await;
Ok((Vec::<()>::new(), None))
},
)
.await
.expect_err("pagination without a configured timeout must still be bounded");
assert_eq!(
error.to_string(),
"resources/list pagination timed out after 30s"
);
}
#[tokio::test(start_paused = true)]
async fn applies_one_timeout_across_individually_timely_pages() {
let requests = Arc::new(Mutex::new(Vec::new()));
let observed = Arc::clone(&requests);
let error = collect_paginated("tools/list", Some(Duration::from_secs(5)), move |params| {
let observed = Arc::clone(&observed);
async move {
let cursor = params.and_then(|params| params.cursor);
observed.lock().expect("request lock").push(cursor.clone());
tokio::time::sleep(Duration::from_secs(2)).await;
match cursor.as_deref() {
None => Ok((vec!["first"], Some("second".to_string()))),
Some("second") => Ok((vec!["second"], Some("third".to_string()))),
Some("third") => Ok((vec!["third"], None)),
Some(cursor) => Err(anyhow!("unexpected cursor: {cursor}")),
}
}
})
.await
.expect_err("the combined page duration must exceed the shared timeout");
assert_eq!(
error.to_string(),
"tools/list pagination timed out after 5s"
);
assert_eq!(
*requests.lock().expect("request lock"),
vec![None, Some("second".to_string()), Some("third".to_string())]
);
}

View File

@@ -0,0 +1,338 @@
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
use codex_config::McpServerEnvVar;
use codex_config::McpServerTransportConfig;
use codex_utils_path_uri::LegacyAppPathString;
use codex_utils_path_uri::PathUri;
use serde::Deserialize;
use serde_json::Map as JsonMap;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
use std::path::Path;
use tracing::warn;
#[path = "agent_plugin_config.rs"]
mod agent_plugin_config;
pub use agent_plugin_config::parse_agent_plugin_mcp_config;
#[derive(Clone, Copy, Debug)]
enum PluginMcpSource<'a> {
Host {
root: &'a Path,
},
Environment {
root: &'a PathUri,
environment_id: &'a str,
},
}
/// One plugin MCP server that could not be normalized into runtime configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginMcpServerParseError {
pub name: String,
pub message: String,
}
/// Valid servers and per-server errors parsed from one plugin MCP file.
#[derive(Debug, Default, PartialEq)]
pub struct PluginMcpConfigParseOutcome {
pub servers: BTreeMap<String, McpServerConfig>,
pub errors: Vec<PluginMcpServerParseError>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PluginMcpServersFile {
mcp_servers: BTreeMap<String, JsonValue>,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum PluginMcpFile {
McpServersObject(PluginMcpServersFile),
ServerMap(BTreeMap<String, JsonValue>),
}
impl PluginMcpFile {
fn into_mcp_servers(self) -> BTreeMap<String, JsonValue> {
match self {
Self::McpServersObject(file) => file.mcp_servers,
Self::ServerMap(mcp_servers) => mcp_servers,
}
}
}
/// Parses wrapped or plain plugin MCP declarations without runtime normalization.
pub fn parse_plugin_mcp_declarations(
contents: &str,
) -> Result<BTreeMap<String, JsonValue>, serde_json::Error> {
serde_json::from_str::<PluginMcpFile>(contents).map(PluginMcpFile::into_mcp_servers)
}
/// Parses the two supported plugin MCP file shapes and normalizes each server.
///
/// Native plugin HTTP servers share the regular MCP transport configuration;
/// relative helper commands therefore use the session's local process cwd.
///
/// Invalid individual servers are returned as errors without discarding valid
/// siblings. A malformed top-level document fails the whole parse.
pub fn parse_plugin_mcp_config(
plugin_root: &Path,
contents: &str,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
parse_plugin_mcp_config_from(contents, PluginMcpSource::Host { root: plugin_root })
}
/// Parses executor-owned plugin MCP config without interpreting the plugin root
/// as a path on the orchestrator host.
pub fn parse_executor_plugin_mcp_config(
plugin_root: &PathUri,
contents: &str,
environment_id: &str,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
parse_plugin_mcp_config_from(
contents,
PluginMcpSource::Environment {
root: plugin_root,
environment_id,
},
)
}
/// Normalizes already-parsed declarations for one executor installation.
pub fn normalize_executor_plugin_mcp_declarations(
plugin_root: &PathUri,
declarations: BTreeMap<String, JsonValue>,
environment_id: &str,
) -> PluginMcpConfigParseOutcome {
normalize_plugin_mcp_declarations(
declarations,
PluginMcpSource::Environment {
root: plugin_root,
environment_id,
},
)
}
impl PluginMcpSource<'_> {
fn display(self) -> String {
match self {
Self::Host { root } => root.display().to_string(),
Self::Environment { root, .. } => root.to_string(),
}
}
}
fn parse_plugin_mcp_config_from(
contents: &str,
source: PluginMcpSource<'_>,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
let declarations = parse_plugin_mcp_declarations(contents)?;
Ok(normalize_plugin_mcp_declarations(declarations, source))
}
fn normalize_plugin_mcp_declarations(
declarations: BTreeMap<String, JsonValue>,
source: PluginMcpSource<'_>,
) -> PluginMcpConfigParseOutcome {
let mut outcome = PluginMcpConfigParseOutcome::default();
for (name, config_value) in declarations {
match normalize_plugin_mcp_server(config_value, source) {
Ok(config) => {
outcome.servers.insert(name, config);
}
Err(message) => outcome
.errors
.push(PluginMcpServerParseError { name, message }),
}
}
outcome
}
fn normalize_plugin_mcp_server(
value: JsonValue,
source: PluginMcpSource<'_>,
) -> Result<McpServerConfig, String> {
let mut object = normalize_plugin_mcp_server_value(value, source);
if let PluginMcpSource::Environment {
root,
environment_id,
} = source
{
object.insert(
"environment_id".to_string(),
JsonValue::String(environment_id.to_string()),
);
if object.contains_key("command") {
match object.remove("cwd") {
Some(JsonValue::String(cwd)) => object.insert(
"cwd".to_string(),
JsonValue::String(environment_cwd(root, Some(&cwd))?.into_string()),
),
Some(JsonValue::Null) | None => object.insert(
"cwd".to_string(),
JsonValue::String(
environment_cwd(root, /*configured_cwd*/ None)?.into_string(),
),
),
Some(value) => object.insert("cwd".to_string(), value),
};
}
}
let mut config = serde_json::from_value::<McpServerConfig>(JsonValue::Object(object))
.map_err(|err| err.to_string())?;
if matches!(config.auth, McpServerAuth::EmaAuth) {
return Err(
"plugin MCP declarations cannot select ema_auth; configure enterprise authentication in host policy"
.to_string(),
);
}
if matches!(source, PluginMcpSource::Environment { .. }) {
bind_environment_env_vars(&mut config)?;
}
Ok(config)
}
fn environment_cwd(
root: &PathUri,
configured_cwd: Option<&str>,
) -> Result<LegacyAppPathString, String> {
let Some(configured_cwd) = configured_cwd else {
return Ok(root.clone().into());
};
let cwd = PathUri::parse(configured_cwd)
.or_else(|_| root.join(configured_cwd))
.map_err(|err| format!("invalid cwd `{configured_cwd}`: {err}"))?;
if !cwd.starts_with(root) {
return Err(format!(
"cwd `{configured_cwd}` must remain within plugin root `{root}`"
));
}
Ok(cwd.into())
}
fn bind_environment_env_vars(config: &mut McpServerConfig) -> Result<(), String> {
let is_local_environment = config.is_local_environment();
let env_vars = match &mut config.transport {
McpServerTransportConfig::Stdio { env_vars, .. } => env_vars,
// Bearer credentials resolve on the executor; other header variables do not yet.
McpServerTransportConfig::StreamableHttp {
env_http_headers, ..
} => {
if is_local_environment {
return Ok(());
}
if env_http_headers
.as_ref()
.is_some_and(|headers| !headers.is_empty())
{
return Err(
"`env_http_headers` requires executor-side environment resolution for an executor-owned HTTP MCP"
.to_string(),
);
}
return Ok(());
}
};
for env_var in env_vars {
match env_var {
McpServerEnvVar::Name(name) if !is_local_environment => {
*env_var = McpServerEnvVar::Config {
name: std::mem::take(name),
source: Some("remote".to_string()),
};
}
McpServerEnvVar::Name(_) => {}
McpServerEnvVar::Config { name, source } => {
match (is_local_environment, source.as_deref()) {
(true, None | Some("local")) | (false, Some("remote")) => {}
(true, Some("remote")) => {
return Err(format!(
"env_vars entry `{name}` cannot use source `remote` in a local environment"
));
}
(false, None) => *source = Some("remote".to_string()),
(false, Some("local")) => {
return Err(format!(
"env_vars entry `{name}` cannot use source `local` in an executor-owned plugin"
));
}
(_, Some(source)) => unreachable!("validated env_vars source `{source}`"),
}
}
}
}
Ok(())
}
fn normalize_plugin_mcp_server_value(
value: JsonValue,
source: PluginMcpSource<'_>,
) -> JsonMap<String, JsonValue> {
let mut object = match value {
JsonValue::Object(object) => object,
_ => return JsonMap::new(),
};
if let Some(JsonValue::String(transport_type)) = object.remove("type") {
match transport_type.as_str() {
"http" | "streamable_http" | "streamable-http" | "stdio" => {}
other => {
let plugin_display = source.display();
warn!(
plugin = %plugin_display,
transport = other,
"plugin MCP server uses an unknown transport type"
);
}
}
}
if let Some(JsonValue::Object(mut oauth)) = object.remove("oauth") {
if let Some(callback_url) = oauth.remove("callbackUrl") {
oauth
.entry("callback_url".to_string())
.or_insert(callback_url);
}
if let Some(callback_port) = oauth.remove("callbackPort") {
oauth
.entry("callback_port".to_string())
.or_insert(callback_port);
}
if let Some(client_id) = oauth.remove("clientId") {
oauth.entry("client_id".to_string()).or_insert(client_id);
}
if let Some(client_secret) = oauth.remove("clientSecret") {
oauth
.entry("client_secret".to_string())
.or_insert(client_secret);
}
if !oauth.is_empty() {
object.insert("oauth".to_string(), JsonValue::Object(oauth));
}
}
if let PluginMcpSource::Host { root } = source
&& let Some(JsonValue::String(cwd)) = object.get("cwd")
&& !Path::new(cwd).is_absolute()
{
object.insert(
"cwd".to_string(),
JsonValue::String(root.join(cwd).display().to_string()),
);
}
object
}
#[cfg(test)]
#[path = "plugin_config_tests.rs"]
mod tests;

View File

@@ -0,0 +1,987 @@
use super::PluginMcpConfigParseOutcome;
use super::PluginMcpServerParseError;
use super::normalize_executor_plugin_mcp_declarations;
use super::parse_agent_plugin_mcp_config;
use super::parse_executor_plugin_mcp_config;
use super::parse_plugin_mcp_config;
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use codex_config::McpServerConfig;
use codex_config::McpServerEnvVar;
use codex_config::McpServerOAuthConfig;
use codex_config::McpServerTransportConfig;
use codex_utils_path_uri::LegacyAppPathString;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
fn plugin_root() -> PathBuf {
std::env::current_dir()
.expect("current directory")
.join("plugin-root")
}
fn plugin_root_uri(plugin_root: &Path) -> PathUri {
PathUri::from_host_native_path(plugin_root).expect("plugin root URI")
}
#[test]
fn agent_plugin_placeholder_expansion_is_single_pass() {
let plugin_root = plugin_root().join("${PLUGIN_DATA}");
let plugin_data_root = plugin_root
.parent()
.expect("plugin root parent")
.join("plugin-data");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"demo":{
"type":"stdio",
"command":"python",
"args":["${PLUGIN_ROOT}:${PLUGIN_DATA}"]
}}
}"#,
)
.expect("parse Agent Plugins MCP config");
let McpServerTransportConfig::Stdio { args, .. } = &outcome.servers["demo"].transport else {
panic!("expected stdio transport");
};
assert_eq!(
args,
&vec![format!(
"{}:{}",
plugin_root.display(),
plugin_data_root.display()
)]
);
}
#[test]
fn agent_plugin_mcp_expands_reserved_paths_and_maps_transports() {
let plugin_root = plugin_root();
let plugin_data_root = plugin_root.parent().expect("parent").join("plugin-data");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"local": {
"type":"stdio",
"command":"python",
"args":["${PLUGIN_ROOT}/server.py", "${PLUGIN_DATA}/state.json"],
"env":{"CACHE":"${PLUGIN_DATA}/cache"},
"cwd":"${PLUGIN_ROOT}/scripts"
},
"remote": {
"type":"streamable-http",
"url":"https://example.com/mcp",
"headers":{"X-Plugin":"demo"}
}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
let local = outcome.servers.get("local").expect("local server");
let McpServerTransportConfig::Stdio { args, env, cwd, .. } = &local.transport else {
panic!("expected stdio transport");
};
assert_eq!(
args,
&vec![
format!("{}/server.py", plugin_root.display()),
format!("{}/state.json", plugin_data_root.display()),
]
);
assert_eq!(
env.as_ref().expect("environment").get("PLUGIN_ROOT"),
Some(&plugin_root.display().to_string())
);
assert_eq!(
env.as_ref().expect("environment").get("PLUGIN_DATA"),
Some(&plugin_data_root.display().to_string())
);
assert_eq!(
cwd.as_ref(),
Some(&LegacyAppPathString::from_path(
&plugin_root.join("scripts")
))
);
let remote = outcome.servers.get("remote").expect("remote server");
let McpServerTransportConfig::StreamableHttp { http_headers, .. } = &remote.transport else {
panic!("expected HTTP transport");
};
assert_eq!(
http_headers
.as_ref()
.and_then(|headers| headers.get("X-Plugin")),
Some(&"demo".to_string())
);
}
#[test]
fn agent_plugin_mcp_handles_portable_path_and_http_edge_cases() {
let plugin_root = plugin_root();
let plugin_data_root = plugin_root.parent().expect("parent").join("plugin-data");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"contained":{"type":"stdio","command":"./bin/../server","cwd":"${PLUGIN_ROOT}/work/../data"},
"redundant-separator":{"type":"stdio","command":".//bin/server"},
"root-slash":{"type":"stdio","command":"python","cwd":"${PLUGIN_ROOT}/"},
"data-slash":{"type":"stdio","command":"python","cwd":"${PLUGIN_DATA}/"},
"headers":{"type":"streamable-http","url":"https://example.com/mcp","headers":{"aUtHoRiZaTiOn":"public-package-value","Content-Length":"0","HOST":"other.example.com","Proxy-Authorization":"public-package-value","Transfer-Encoding":"chunked","uSeR-aGeNt":"plugin-agent/1.0","X-Plugin":"demo","X-Plugin-Name":"café"}},
"loopback":{"type":"streamable-http","url":"http://[::1]/mcp"}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
assert_eq!(
outcome.servers.keys().collect::<Vec<_>>(),
vec![
"contained",
"data-slash",
"headers",
"loopback",
"redundant-separator",
"root-slash"
]
);
let McpServerTransportConfig::Stdio { command, cwd, .. } =
&outcome.servers["contained"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(command, &plugin_root.join("server").display().to_string());
assert_eq!(
cwd.as_ref(),
Some(&LegacyAppPathString::from_path(&plugin_root.join("data")))
);
let McpServerTransportConfig::Stdio { command, .. } =
&outcome.servers["redundant-separator"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(
command,
&plugin_root.join("bin").join("server").display().to_string()
);
for (server_name, expected_cwd) in [
("root-slash", plugin_root.as_path()),
("data-slash", plugin_data_root.as_path()),
] {
let McpServerTransportConfig::Stdio { cwd, .. } = &outcome.servers[server_name].transport
else {
panic!("expected stdio transport");
};
assert_eq!(
cwd.as_ref(),
Some(&LegacyAppPathString::from_path(expected_cwd))
);
}
let McpServerTransportConfig::StreamableHttp { http_headers, .. } =
&outcome.servers["headers"].transport
else {
panic!("expected HTTP transport");
};
assert_eq!(
http_headers,
&Some(HashMap::from([
("X-Plugin".to_string(), "demo".to_string()),
("X-Plugin-Name".to_string(), "café".to_string()),
]))
);
}
#[test]
fn agent_plugin_mcp_skips_invalid_server_without_disabling_siblings() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"valid":{"type":"stdio","command":"python"},
"reserved":{"type":"stdio","command":"python","env":{"PLUGIN_ROOT":"bad"}}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert_eq!(outcome.servers.keys().collect::<Vec<_>>(), vec!["valid"]);
assert_eq!(outcome.errors.len(), 1);
assert_eq!(outcome.errors[0].name, "reserved");
assert!(
outcome.errors[0]
.message
.contains("reserved variable `PLUGIN_ROOT`")
);
}
#[test]
fn agent_plugin_mcp_preserves_server_named_mcp_servers() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"mcpServers":{"type":"stdio","command":"first"},
"sibling":{"type":"stdio","command":"second"}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
assert_eq!(
outcome.servers.keys().collect::<Vec<_>>(),
vec!["mcpServers", "sibling"]
);
}
#[test]
fn agent_plugin_mcp_preserves_arbitrary_server_names() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"agent.smoke / local":{"type":"stdio","command":"python"}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
assert!(outcome.servers.contains_key("agent.smoke / local"));
}
#[test]
fn agent_plugin_mcp_rejects_explicit_null_optional_fields() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{
"cwd":{"type":"stdio","command":"python","cwd":null},
"headers":{"type":"streamable-http","url":"https://example.com/mcp","headers":null}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.servers.is_empty());
assert_eq!(outcome.errors.len(), 2);
assert!(
outcome
.errors
.iter()
.any(|error| error.message.contains("`cwd`"))
);
assert!(
outcome
.errors
.iter()
.any(|error| error.message.contains("`headers`"))
);
}
#[cfg(windows)]
#[test]
fn agent_plugin_mcp_rejects_reserved_environment_aliases_case_insensitively() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"reserved":{"type":"stdio","command":"python","env":{"plugin_root":"bad"}}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.servers.is_empty());
assert_eq!(outcome.errors.len(), 1);
}
#[cfg(windows)]
#[test]
fn agent_plugin_mcp_overlays_windows_environment_case_insensitively() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{
"configured":{"type":"stdio","command":"python","env":{"Path":"configured"}},
"duplicate":{"type":"stdio","command":"python","env":{"PATH":"one","Path":"two"}}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert_eq!(
outcome.servers.keys().collect::<Vec<_>>(),
vec!["configured"]
);
assert_eq!(outcome.errors.len(), 1);
let McpServerTransportConfig::Stdio { env, .. } = &outcome.servers["configured"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(
env.as_ref().and_then(|env| env.get("PATH")),
Some(&"configured".to_string())
);
}
#[cfg(unix)]
#[test]
fn agent_plugin_mcp_resolves_root_before_collapsing_parent_components() {
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir().expect("temporary directory");
let base = temp.path().join("base");
let outside = temp.path().join("outside");
let outside_directory = outside.join("directory");
let resolved_plugin_root = outside.join("plugin");
let plugin_data_root = temp.path().join("plugin-data");
std::fs::create_dir_all(&base).expect("create base directory");
std::fs::create_dir_all(&outside_directory).expect("create symlink target");
std::fs::create_dir_all(&resolved_plugin_root).expect("create resolved plugin root");
std::fs::create_dir_all(&plugin_data_root).expect("create plugin data root");
let canonical_plugin_root = resolved_plugin_root
.canonicalize()
.expect("canonical plugin root");
symlink(&outside_directory, base.join("link")).expect("create root symlink");
let plugin_root = base.join("link/../plugin");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"demo":{"type":"stdio","command":"python"}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
let McpServerTransportConfig::Stdio { env, cwd, .. } = &outcome.servers["demo"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(
env.as_ref().and_then(|env| env.get("PLUGIN_ROOT")),
Some(&canonical_plugin_root.display().to_string())
);
assert_eq!(
cwd.as_ref(),
Some(&LegacyAppPathString::from_path(&canonical_plugin_root))
);
}
#[cfg(unix)]
#[test]
fn agent_plugin_mcp_rejects_missing_descendant_below_escaping_symlink() {
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir().expect("temporary directory");
let plugin_root = temp.path().join("plugin");
let plugin_data_root = temp.path().join("plugin-data");
let outside = temp.path().join("outside");
std::fs::create_dir_all(&plugin_root).expect("create plugin root");
std::fs::create_dir_all(&plugin_data_root).expect("create plugin data root");
std::fs::create_dir_all(&outside).expect("create outside directory");
symlink(&outside, plugin_root.join("link")).expect("create escaping symlink");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"escape":{"type":"stdio","command":"./link/missing"}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.servers.is_empty());
assert_eq!(outcome.errors.len(), 1);
assert!(outcome.errors[0].message.contains("must remain within"));
}
#[test]
fn agent_plugin_mcp_enforces_closed_transport_and_path_semantics() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"valid":{"type":"stdio","command":"python"},
"command":{"type":"stdio","command":"../server"},
"escape":{"type":"stdio","command":"./../server"},
"cwd":{"type":"stdio","command":"python","cwd":"${PLUGIN_ROOT}/../outside"},
"backslash":{"type":"stdio","command":"./scripts\\..\\outside"},
"remote":{"type":"streamable-http","url":"http://example.com/mcp"},
"header":{"type":"streamable-http","url":"https://example.com/mcp","headers":{"X-Demo":"one","x-demo":"two"}},
"sse":{"type":"sse","url":"https://example.com/sse"},
"unknown":{"type":"stdio","command":"python","future":true}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert_eq!(outcome.servers.keys().collect::<Vec<_>>(), vec!["valid"]);
assert_eq!(outcome.errors.len(), 8);
}
#[cfg(windows)]
#[test]
fn agent_plugin_mcp_rejects_drive_relative_windows_command() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json","mcpServers":{"drive-relative":{"type":"stdio","command":"C:server.exe"}}}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.servers.is_empty());
assert_eq!(outcome.errors.len(), 1);
}
#[test]
fn agent_plugin_mcp_treats_args_and_env_as_opaque_after_expansion() {
let plugin_root = plugin_root();
let data_root = plugin_root.join("data");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"demo":{
"type":"stdio",
"command":"python",
"args":["${PLUGIN_ROOT}/../opaque"],
"env":{"OPAQUE":"${PLUGIN_DATA}/../opaque"}
}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
let McpServerTransportConfig::Stdio { args, env, .. } = &outcome.servers["demo"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(args, &vec![format!("{}/../opaque", plugin_root.display())]);
assert_eq!(
env.as_ref().and_then(|env| env.get("OPAQUE")),
Some(&format!("{}/../opaque", data_root.display()))
);
}
#[test]
fn agent_plugin_mcp_rejects_unsupported_schema() {
let plugin_root = plugin_root();
let error = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{"$schema":"https://agent-plugins.org/schemas/2.0.0/mcp.schema.json","mcpServers":{}}"#,
)
.expect_err("unsupported schema");
assert!(
error
.to_string()
.contains("unsupported Agent Plugins MCP schema")
);
}
fn stdio_server(
command: &str,
environment_id: &str,
cwd: LegacyAppPathString,
env_vars: Vec<McpServerEnvVar>,
) -> McpServerConfig {
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::Stdio {
command: command.to_string(),
args: Vec::new(),
env: None,
env_vars,
cwd: Some(cwd),
},
environment_id: environment_id.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
}
}
#[test]
fn declared_placement_preserves_local_plugin_normalization() {
let plugin_root = plugin_root();
let expected_stdio = stdio_server(
"demo-mcp",
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
LegacyAppPathString::from_path(&plugin_root.join("scripts")),
Vec::new(),
);
let expected_http = McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://example.com/mcp".to_string(),
bearer_token_env_var: None,
http_headers: None,
env_http_headers: None,
http_headers_helper: None,
},
environment_id: DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: Some("client-id".to_string()),
client_secret: Some("plugin-client-secret".into()),
callback_url: Some("http://127.0.0.1/callback/registered".to_string()),
callback_port: Some(9876),
..Default::default()
}),
oauth_resource: None,
tools: HashMap::new(),
};
let mut expected_helper = McpServerConfig {
oauth: None,
..expected_http.clone()
};
let McpServerTransportConfig::StreamableHttp {
http_headers_helper,
..
} = &mut expected_helper.transport
else {
unreachable!("expected HTTP transport");
};
*http_headers_helper = Some("./auth.sh".to_string());
let outcome = parse_plugin_mcp_config(
&plugin_root,
r#"{
"demo": {
"type": "stdio",
"command": "demo-mcp",
"cwd": "scripts"
},
"hosted": {
"type": "http",
"url": "https://example.com/mcp",
"oauth": {"clientId": "client-id", "clientSecret": "plugin-client-secret", "callbackUrl": "http://127.0.0.1/callback/registered", "callbackPort": 9876}
},
"helper": {"type":"http","url":"https://example.com/mcp","http_headers_helper":"./auth.sh"}
}"#,
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([
("demo".to_string(), expected_stdio),
("helper".to_string(), expected_helper),
("hosted".to_string(), expected_http),
]),
errors: Vec::new(),
}
);
}
#[test]
fn native_plugin_mcp_cannot_self_declare_ema_auth() {
let server = serde_json::json!({
"type": "http",
"url": "https://resource.example/mcp",
"auth": "ema_auth"
});
for contents in [
serde_json::json!({"enterprise": server}),
serde_json::json!({"mcpServers": {"enterprise": server}}),
] {
let outcome = parse_plugin_mcp_config(&plugin_root(), &contents.to_string())
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::new(),
errors: vec![PluginMcpServerParseError {
name: "enterprise".to_string(),
message: "plugin MCP declarations cannot select ema_auth; configure enterprise authentication in host policy".to_string(),
}],
}
);
}
}
#[test]
fn environment_placement_forces_authority_and_defaults_null_cwd() {
let plugin_root = plugin_root();
let plugin_root_uri = plugin_root_uri(&plugin_root);
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri,
r#"{
"$schema":"https://example.com/plugin-mcp.schema.json",
"mcpServers":{"demo":{
"command":"demo-mcp",
"environment_id":"local",
"cwd":null,
"env_vars":["EXECUTOR_TOKEN", {"name":"OTHER_TOKEN"}]
}}
}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
stdio_server(
"demo-mcp",
"executor-1",
plugin_root_uri.into(),
vec![
McpServerEnvVar::Config {
name: "EXECUTOR_TOKEN".to_string(),
source: Some("remote".to_string()),
},
McpServerEnvVar::Config {
name: "OTHER_TOKEN".to_string(),
source: Some("remote".to_string()),
},
],
),
)]),
errors: Vec::new(),
}
);
}
#[test]
fn environment_placement_resolves_relative_cwd_beneath_plugin_root() {
let plugin_root = plugin_root();
let plugin_root_uri = plugin_root_uri(&plugin_root);
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri,
r#"{"demo":{"command":"demo-mcp","cwd":"scripts"}}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
stdio_server(
"demo-mcp",
"executor-1",
plugin_root_uri
.join("scripts")
.expect("plugin cwd URI")
.into(),
Vec::new(),
),
)]),
errors: Vec::new(),
}
);
}
#[test]
fn executor_environment_placement_resolves_foreign_uri_cwd() {
let plugin_root = PathUri::parse("file:///C:/plugins/demo").expect("plugin root URI");
let outcome = parse_executor_plugin_mcp_config(
&plugin_root,
r#"{"demo":{"command":"demo-mcp","cwd":"scripts"}}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
normalize_executor_plugin_mcp_declarations(
&plugin_root,
BTreeMap::from([(
"demo".to_string(),
serde_json::json!({"command": "demo-mcp", "cwd": "scripts"}),
)]),
"executor-1",
),
outcome
);
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
stdio_server(
"demo-mcp",
"executor-1",
LegacyAppPathString::from(
plugin_root.join("scripts").expect("executor cwd URI"),
),
Vec::new(),
),
)]),
errors: Vec::new(),
}
);
}
#[test]
fn environment_placement_rejects_relative_cwd_that_escapes_package() {
let plugin_root = plugin_root();
let plugin_root_uri = plugin_root_uri(&plugin_root);
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri,
r#"{"demo":{"command":"demo-mcp","cwd":"../outside"}}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::new(),
errors: vec![PluginMcpServerParseError {
name: "demo".to_string(),
message: format!(
"cwd `../outside` must remain within plugin root `{plugin_root_uri}`"
),
}],
}
);
}
#[test]
fn environment_placement_rejects_orchestrator_env_vars() {
let plugin_root = plugin_root();
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri(&plugin_root),
r#"{"demo":{"command":"demo-mcp","env_vars":[{"name":"TOKEN","source":"local"}]}}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::new(),
errors: vec![PluginMcpServerParseError {
name: "demo".to_string(),
message:
"env_vars entry `TOKEN` cannot use source `local` in an executor-owned plugin"
.to_string(),
}],
}
);
}
#[test]
fn remote_environment_placement_preserves_bearer_and_rejects_header_env_references() {
let plugin_root = plugin_root();
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri(&plugin_root),
r#"{
"bearer": {
"url": "https://example.com/bearer",
"bearer_token_env_var": "TOKEN"
},
"headers": {
"url": "https://example.com/headers",
"env_http_headers": {"Authorization": "TOKEN"}
}
}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"bearer".to_string(),
serde_json::from_value(serde_json::json!({
"url": "https://example.com/bearer",
"bearer_token_env_var": "TOKEN",
"environment_id": "executor-1",
}))
.expect("executor-owned bearer configuration"),
)]),
errors: vec![PluginMcpServerParseError {
name: "headers".to_string(),
message: "`env_http_headers` requires executor-side environment resolution for an executor-owned HTTP MCP"
.to_string(),
}],
}
);
}
#[test]
fn local_environment_placement_preserves_http_env_references() {
let plugin_root = plugin_root();
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri(&plugin_root),
r#"{
"demo": {
"url": "https://example.com/mcp",
"bearer_token_env_var": "TOKEN",
"env_http_headers": {"X-Account": "ACCOUNT_ID"}
}
}"#,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://example.com/mcp".to_string(),
bearer_token_env_var: Some("TOKEN".to_string()),
http_headers: None,
env_http_headers: Some(HashMap::from([(
"X-Account".to_string(),
"ACCOUNT_ID".to_string(),
)])),
http_headers_helper: None,
},
environment_id: DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
},
)]),
errors: Vec::new(),
}
);
}
#[test]
fn local_environment_placement_preserves_local_env_vars() {
let plugin_root = plugin_root();
let plugin_root_uri = plugin_root_uri(&plugin_root);
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri,
r#"{"demo":{"command":"demo-mcp","env_vars":["TOKEN",{"name":"OTHER","source":"local"}]}}"#,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
stdio_server(
"demo-mcp",
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
plugin_root_uri.into(),
vec![
McpServerEnvVar::Name("TOKEN".to_string()),
McpServerEnvVar::Config {
name: "OTHER".to_string(),
source: Some("local".to_string()),
},
],
),
)]),
errors: Vec::new(),
}
);
}
#[test]
fn local_environment_placement_rejects_remote_env_vars() {
let plugin_root = plugin_root();
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri(&plugin_root),
r#"{"demo":{"command":"demo-mcp","env_vars":[{"name":"TOKEN","source":"remote"}]}}"#,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::new(),
errors: vec![PluginMcpServerParseError {
name: "demo".to_string(),
message: "env_vars entry `TOKEN` cannot use source `remote` in a local environment"
.to_string(),
}],
}
);
}

View File

@@ -0,0 +1,432 @@
use std::sync::Arc;
use std::sync::Weak;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_protocol::mcp::Resource;
use codex_protocol::mcp::ResourceContent;
use codex_rmcp_client::CancellableEventStreamRequest;
use codex_rmcp_client::RmcpClient;
use rmcp::model::GetMeta;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ServerResult;
use rmcp::service::ServiceError;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Map;
use serde_json::Value;
use serde_json::json;
use tokio::runtime::Handle;
use tokio::sync::watch;
use crate::McpEventStreamOpener;
use crate::McpRuntime;
use crate::connection_manager::McpConnectionSet;
use crate::connection_manager::McpServerConnection;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
/// One page of resources returned by an MCP server.
#[derive(Clone, Debug, PartialEq)]
pub struct McpResourcePage {
/// Resources advertised on this page.
pub resources: Vec<Resource>,
/// Opaque cursor to supply when requesting the next page.
pub next_cursor: Option<String>,
}
/// Parameters for one Codex Apps resource page.
///
/// Keep `mime_type` when requesting a continuation page: the server applies
/// the filter to each request separately.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CodexAppsResourceListParams {
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
pub mime_type: String,
}
/// Contents returned after reading one MCP resource.
#[derive(Clone, Debug, PartialEq)]
pub struct McpResourceReadResult {
/// Text or blob content returned for the requested resource.
pub contents: Vec<ResourceContent>,
}
/// An event advertised by an MCP server.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct McpEventDefinition {
pub name: String,
pub description: String,
pub delivery: Vec<String>,
pub input_schema: Value,
pub payload_schema: Value,
}
/// Events returned from one stable MCP connection generation.
pub struct McpEventCatalogSnapshot {
pub cache_key: McpResourceClientCacheKey,
pub events: Vec<McpEventDefinition>,
}
/// One unmodified lifecycle notification from an MCP event subscription.
#[derive(Clone, Debug, PartialEq)]
pub struct McpEventNotification {
pub method: String,
pub params: Option<Value>,
}
/// Owns an MCP event subscription and cancels its request when dropped.
pub struct McpEventStream {
request: Option<CancellableEventStreamRequest>,
runtime_handle: Handle,
client: Option<Arc<RmcpClient>>,
cancel_event_streams_on_server_removal: watch::Receiver<()>,
}
impl McpEventStream {
pub(crate) async fn open(
client: Arc<RmcpClient>,
cancel_event_streams_on_server_removal: watch::Receiver<()>,
event_name: &str,
arguments: &Value,
request_meta: Option<&Map<String, Value>>,
) -> Result<Self> {
let mut params = json!({ "name": event_name, "arguments": arguments });
if let Some(request_meta) = request_meta {
params["_meta"] = Value::Object(request_meta.clone());
}
let request = client
.send_event_stream_request(Some(params))
.await
.context("events/stream request failed")?;
Ok(Self {
request: Some(request),
runtime_handle: Handle::current(),
client: Some(client),
cancel_event_streams_on_server_removal,
})
}
/// Receives the next raw lifecycle notification for this subscription.
pub async fn recv(&mut self) -> Result<Option<McpEventNotification>> {
let Some(request) = self.request.as_mut() else {
return Ok(None);
};
tokio::select! {
biased;
Ok(()) = self.cancel_event_streams_on_server_removal.changed() => {
self.cancel();
Err(anyhow!("hosted MCP event server was removed"))
}
Some(notification) = request.notifications.recv() => {
let metadata = notification.get_meta().0.0.clone();
let mut params = notification.params;
if !metadata.is_empty() {
params.get_or_insert_with(|| json!({}))["_meta"] = Value::Object(metadata);
}
Ok(Some(McpEventNotification {
method: notification.method,
params,
}))
}
response = &mut request.handle.rx => {
self.request = None;
self.client = None;
match response {
Ok(Ok(_))
| Ok(Err(ServiceError::Cancelled { .. }))
| Ok(Err(ServiceError::TransportClosed))
| Err(_) => Ok(None),
Ok(Err(error)) => Err(error.into()),
}
}
}
}
fn cancel(&mut self) {
if let Some(CancellableEventStreamRequest {
handle,
notifications,
}) = self.request.take()
{
drop(notifications);
let client = self.client.take();
self.runtime_handle.spawn(async move {
let _ = tokio::time::timeout(
Duration::from_secs(30),
handle.cancel(Some("event subscription closed".to_string())),
)
.await;
drop(client);
});
}
}
}
impl Drop for McpEventStream {
fn drop(&mut self) {
self.cancel();
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct McpEventListResult {
events: Vec<McpEventDefinition>,
}
/// Access to MCP resources and event subscriptions through the latest runtime.
#[derive(Clone)]
pub struct McpResourceClient {
runtime: Arc<McpRuntime>,
}
/// Opaque identity for the connection set currently used by an MCP resource client.
#[derive(Clone)]
pub struct McpResourceClientCacheKey(Weak<McpConnectionSet>);
impl PartialEq for McpResourceClientCacheKey {
fn eq(&self, other: &Self) -> bool {
self.0.ptr_eq(&other.0)
}
}
impl Eq for McpResourceClientCacheKey {}
/// Identity of one server's resource cache across MCP runtime publications.
///
/// Survives publications that reuse the same connection until resource caches are explicitly
/// invalidated. The key does not keep superseded connections alive.
#[derive(Clone)]
pub struct McpResourceServerCacheKey {
pub(crate) connection: Weak<McpServerConnection>,
pub(crate) generation: u64,
}
impl PartialEq for McpResourceServerCacheKey {
fn eq(&self, other: &Self) -> bool {
self.connection.ptr_eq(&other.connection) && self.generation == other.generation
}
}
impl Eq for McpResourceServerCacheKey {}
/// Opaque auth scope and server availability, independent of connection-set rebuilds.
/// This is for fixed, host-owned sources; it does not fingerprint arbitrary server config.
#[derive(Clone)]
pub struct McpResourceClientAuthKey {
pub(crate) generation: Arc<()>,
pub(crate) server: String,
pub(crate) available: bool,
}
impl PartialEq for McpResourceClientAuthKey {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.generation, &other.generation)
&& self.server == other.server
&& self.available == other.available
}
}
impl Eq for McpResourceClientAuthKey {}
impl std::fmt::Debug for McpResourceClient {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("McpResourceClient")
.finish_non_exhaustive()
}
}
impl McpResourceClient {
/// Creates a resource client that follows the thread's latest published runtime.
pub fn new(runtime: Arc<McpRuntime>) -> Self {
Self { runtime }
}
/// Returns the identity of the connection set used by this client.
pub fn cache_key(&self) -> McpResourceClientCacheKey {
McpResourceClientCacheKey(Arc::downgrade(&self.runtime.latest_connections()))
}
/// Returns a server's resource cache identity without starting its connection.
pub fn server_cache_key(&self, server: &str) -> Option<McpResourceServerCacheKey> {
self.runtime.resource_cache_key(server)
}
/// Tracks published auth and source availability without invalidating on unrelated
/// environment changes. This key contains no credentials.
pub fn auth_cache_key_for_server(&self, server: &str) -> McpResourceClientAuthKey {
self.runtime.auth_cache_key_for_server(server)
}
/// Returns whether this client can address the named server.
///
/// This does not wait for server startup.
pub async fn has_server(&self, server: &str) -> bool {
self.runtime.latest_connections().contains_server(server)
}
/// Lists one resource page from the named server.
pub async fn list_resources(
&self,
server: &str,
cursor: Option<String>,
) -> Result<McpResourcePage> {
let params =
cursor.map(|cursor| PaginatedRequestParams::default().with_cursor(Some(cursor)));
let result = self
.runtime
.latest_connections()
.list_resources(server, params)
.await?;
let resources = result
.resources
.into_iter()
.map(resource_from_rmcp)
.collect::<Result<Vec<_>>>()?;
Ok(McpResourcePage {
resources,
next_cursor: result.next_cursor,
})
}
/// Lists one Codex Apps resource page using plugin-service's top-level `mimeType` parameter.
pub async fn list_codex_apps_resources(
&self,
params: CodexAppsResourceListParams,
) -> Result<McpResourcePage> {
let catalog = matches!(params.mime_type.as_str(), "mcp/plugin" | "mcp/skill");
let params = serde_json::to_value(params)
.context("failed to serialize Codex Apps resource params")?;
let connections = self.runtime.latest_host_owned_codex_apps_connections()?;
let list = async move |client: Arc<RmcpClient>, timeout| {
client
.send_custom_request_with_timeout("resources/list", Some(params), timeout)
.await
.context("resources/list failed for `codex_apps`")
};
let result =
if catalog && let Some((connection, timeout)) = connections.early_apps_discovery() {
connection
.with_early_apps_client(&self.runtime, timeout, list)
.await?
} else {
let (managed, timeout) = connections
.client_by_name(CODEX_APPS_MCP_SERVER_NAME)
.await?;
list(managed.client, timeout).await?
};
let result = match result {
ServerResult::ListResourcesResult(result) => result,
ServerResult::CustomResult(result) => result
.result_as::<rmcp::model::ListResourcesResult>()
.context("resources/list returned invalid resources")?,
_ => return Err(anyhow!("resources/list returned an unexpected MCP result")),
};
let resources = result
.resources
.into_iter()
.map(resource_from_rmcp)
.collect::<Result<Vec<_>>>()?;
Ok(McpResourcePage {
resources,
next_cursor: result.next_cursor,
})
}
/// Reads one resource from the named server.
pub async fn read_resource(&self, server: &str, uri: &str) -> Result<McpResourceReadResult> {
let params = ReadResourceRequestParams::new(uri.to_string());
let result = self
.runtime
.latest_connections()
.read_resource(server, params)
.await?;
let contents = result
.contents
.into_iter()
.map(resource_content_from_rmcp)
.collect::<Result<Vec<_>>>()?;
Ok(McpResourceReadResult { contents })
}
/// Lists the events advertised by the MCP event server.
pub async fn list_events(&self) -> Result<McpEventCatalogSnapshot> {
let (connections, _) = self
.runtime
.latest_connections_for_event_server(CODEX_APPS_MCP_SERVER_NAME)?;
let cache_key = McpResourceClientCacheKey(Arc::downgrade(&connections));
let (managed, request_timeout) = connections
.client_by_name(CODEX_APPS_MCP_SERVER_NAME)
.await?;
let result = managed
.client
.send_custom_request_with_timeout("events/list", /*params*/ None, request_timeout)
.await
.context("events/list request failed")?;
let ServerResult::CustomResult(result) = result else {
return Err(anyhow!("events/list returned an unexpected MCP result"));
};
let result = result
.result_as::<McpEventListResult>()
.context("events/list returned invalid event definitions")?;
Ok(McpEventCatalogSnapshot {
cache_key,
events: result.events,
})
}
/// Opens an MCP event subscription with the supplied event arguments.
pub async fn open_event_stream(
&self,
event_name: &str,
arguments: &Value,
request_meta: Option<&Map<String, Value>>,
) -> Result<McpEventStream> {
let (connections, cancel_event_streams_on_server_removal) = self
.runtime
.latest_connections_for_event_server(CODEX_APPS_MCP_SERVER_NAME)?;
let (managed, _) = connections
.client_by_name(CODEX_APPS_MCP_SERVER_NAME)
.await?;
McpEventStream::open(
managed.client,
cancel_event_streams_on_server_removal,
event_name,
arguments,
request_meta,
)
.await
}
/// Creates an event stream opener using the task's event server settings.
pub fn event_stream_opener(&self) -> Result<McpEventStreamOpener> {
self.runtime.event_stream_opener()
}
/// Forwards event server removal to the owner of the task's subscriptions.
pub fn forward_event_server_removals_to(&self, cancellation: watch::Sender<()>) {
self.runtime.forward_event_server_removals_to(cancellation);
}
}
fn resource_from_rmcp(resource: rmcp::model::Resource) -> Result<Resource> {
let value = serde_json::to_value(resource).context("failed to serialize MCP resource")?;
Resource::from_mcp_value(value).context("failed to convert MCP resource")
}
fn resource_content_from_rmcp(content: rmcp::model::ResourceContents) -> Result<ResourceContent> {
let value =
serde_json::to_value(content).context("failed to serialize MCP resource content")?;
serde_json::from_value(value).context("failed to convert MCP resource content")
}

View File

@@ -0,0 +1,315 @@
//! Thread-owned, bounded provenance for app-hosted widget resources.
use std::collections::VecDeque;
use anyhow::Context;
use codex_connectors::AppToolPolicyEvaluator;
use codex_connectors::AppToolPolicyInput;
use codex_protocol::ThreadId;
use codex_protocol::items::McpToolCallStatus;
use codex_protocol::items::TurnItem;
use codex_protocol::mcp::McpResourceOrigin;
use codex_protocol::mcp::McpResourceOriginCheckpoint;
use codex_protocol::protocol::EventMsg;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use crate::CODEX_APPS_MCP_SERVER_NAME;
use crate::McpBinding;
const MAX_ORIGINS: usize = 64;
const MAX_ORIGIN_BYTES: usize = 1024;
#[derive(Default)]
pub(crate) struct ResourceOrigins {
origins: VecDeque<ResourceOrigin>,
turns: VecDeque<String>,
current_turn_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ResourceOrigin {
call_id: String,
turn_id: Option<String>,
tool: String,
connector_id: String,
link_id: Option<String>,
uri: String,
ambiguous_account: bool,
}
impl ResourceOrigins {
pub(crate) fn checkpoint(&self) -> Option<McpResourceOriginCheckpoint> {
(!self.origins.is_empty()).then(|| McpResourceOriginCheckpoint {
origins: self
.origins
.iter()
.map(|origin| McpResourceOrigin {
call_id: origin.call_id.clone(),
turn_id: origin.turn_id.clone(),
tool: origin.tool.clone(),
connector_id: origin.connector_id.clone(),
link_id: origin.link_id.clone(),
uri: origin.uri.clone(),
ambiguous_account: origin.ambiguous_account,
})
.collect(),
turns: self.turns.iter().cloned().collect(),
current_turn_id: self.current_turn_id.clone(),
})
}
pub(crate) fn restore_checkpoint(&mut self, checkpoint: &McpResourceOriginCheckpoint) {
if checkpoint.origins.len() > MAX_ORIGINS
|| checkpoint.turns.len() > MAX_ORIGINS
|| checkpoint
.turns
.iter()
.any(|turn_id| turn_id.len() > MAX_ORIGIN_BYTES)
|| checkpoint
.current_turn_id
.as_ref()
.is_some_and(|turn_id| turn_id.len() > MAX_ORIGIN_BYTES)
{
*self = Self::default();
return;
}
let origins = checkpoint
.origins
.iter()
.map(|origin| ResourceOrigin {
call_id: origin.call_id.clone(),
turn_id: origin.turn_id.clone(),
tool: origin.tool.clone(),
connector_id: origin.connector_id.clone(),
link_id: origin.link_id.clone(),
uri: origin.uri.clone(),
ambiguous_account: origin.ambiguous_account,
})
.collect::<VecDeque<_>>();
if origins.iter().any(|origin| {
origin.byte_len() > MAX_ORIGIN_BYTES || origin.connector_id.trim().is_empty()
}) {
*self = Self::default();
return;
}
*self = Self {
origins,
turns: checkpoint.turns.iter().cloned().collect(),
current_turn_id: checkpoint.current_turn_id.clone(),
};
}
pub(crate) fn observe(&mut self, event: &EventMsg) {
match event {
EventMsg::TurnStarted(event) if event.turn_id.len() <= MAX_ORIGIN_BYTES => {
self.current_turn_id = Some(event.turn_id.clone());
if self.turns.back() != Some(&event.turn_id) {
self.turns.push_back(event.turn_id.clone());
if self.turns.len() > MAX_ORIGINS {
self.turns.pop_front();
}
}
}
EventMsg::ItemCompleted(event) => {
let TurnItem::McpToolCall(item) = &event.item else {
return;
};
if item.status == McpToolCallStatus::Completed {
self.remember(
&item.id,
Some(&event.turn_id),
&item.server,
&item.tool,
&item.arguments,
item.connector_id.as_deref(),
item.link_id.as_deref(),
item.mcp_app_resource_uri.as_deref(),
);
}
}
EventMsg::McpToolCallEnd(event)
if event
.result
.as_ref()
.is_ok_and(|result| !result.is_error.unwrap_or(false)) =>
{
let turn_id = self.current_turn_id.clone();
self.remember(
&event.call_id,
turn_id.as_deref(),
&event.invocation.server,
&event.invocation.tool,
event
.invocation
.arguments
.as_ref()
.unwrap_or(&serde_json::Value::Null),
event.connector_id.as_deref(),
event.link_id.as_deref(),
event.mcp_app_resource_uri.as_deref(),
);
}
EventMsg::ThreadRolledBack(event) => {
for _ in 0..event.num_turns {
let Some(turn_id) = self.turns.pop_back() else {
*self = Self::default();
return;
};
self.origins.retain(|origin| {
origin.turn_id.is_some()
&& origin.turn_id.as_deref() != Some(turn_id.as_str())
});
}
self.current_turn_id = self.turns.back().cloned();
}
_ => {}
}
}
pub(crate) fn find(&self, call_id: &str) -> anyhow::Result<ResourceOrigin> {
self.origins
.iter()
.rev()
.find(|origin| origin.call_id == call_id)
.cloned()
.context("originating MCP tool call was not found or did not complete successfully")
}
#[expect(
clippy::too_many_arguments,
reason = "only bounded provenance fields are retained"
)]
fn remember(
&mut self,
call_id: &str,
turn_id: Option<&str>,
server: &str,
tool: &str,
arguments: &serde_json::Value,
connector_id: Option<&str>,
link_id: Option<&str>,
uri: Option<&str>,
) {
if server != CODEX_APPS_MCP_SERVER_NAME {
return;
}
let Some(connector_id) = connector_id.filter(|value| !value.trim().is_empty()) else {
return;
};
let Some(uri) = uri else {
return;
};
let link_id = link_id.filter(|value| !value.trim().is_empty());
let ambiguous_account = arguments
.get("link_id")
.and_then(serde_json::Value::as_str)
.filter(|value| !value.trim().is_empty())
.is_some_and(|argument_link_id| Some(argument_link_id) != link_id);
let origin = ResourceOrigin {
call_id: call_id.to_owned(),
turn_id: turn_id.map(str::to_owned),
tool: tool.to_owned(),
connector_id: connector_id.to_owned(),
link_id: link_id.map(str::to_owned),
uri: uri.to_owned(),
ambiguous_account,
};
if origin.byte_len() > MAX_ORIGIN_BYTES {
return;
}
if let Some(index) = self
.origins
.iter()
.position(|existing| existing.call_id == origin.call_id)
{
self.origins.remove(index);
}
if self.origins.len() >= MAX_ORIGINS {
self.origins.pop_front();
}
self.origins.push_back(origin);
}
}
impl ResourceOrigin {
fn byte_len(&self) -> usize {
self.call_id.len()
+ self.turn_id.as_ref().map_or(0, String::len)
+ self.tool.len()
+ self.connector_id.len()
+ self.link_id.as_ref().map_or(0, String::len)
+ self.uri.len()
}
pub(crate) async fn read(
&self,
binding: &McpBinding,
thread_id: ThreadId,
mut params: ReadResourceRequestParams,
) -> anyhow::Result<ReadResourceResult> {
if self.uri != params.uri {
anyhow::bail!("originating MCP tool call does not match the requested resource");
}
if self.ambiguous_account {
anyhow::bail!("originating MCP tool call has ambiguous account selection");
}
let tool_info = binding
.tool_info(CODEX_APPS_MCP_SERVER_NAME, &self.tool)
.context("originating MCP tool is unavailable")?;
if tool_info.connector_id.as_deref() != Some(self.connector_id.as_str()) {
anyhow::bail!("originating MCP tool connector does not match its app context");
}
let tool_meta = tool_info.tool.meta.as_ref().map(|meta| &meta.0);
let current_link_id = tool_meta
.and_then(|meta| meta.get("link_id"))
.and_then(serde_json::Value::as_str)
.filter(|value| !value.trim().is_empty());
if current_link_id != self.link_id.as_deref() {
anyhow::bail!("originating MCP tool link does not match its app context");
}
if self.link_id.is_none()
&& tool_meta
.and_then(|meta| meta.get("_codex_apps"))
.and_then(|meta| meta.get("requires_explicit_link_id"))
.and_then(serde_json::Value::as_bool)
== Some(true)
{
anyhow::bail!("originating MCP tool requires an explicit account link");
}
let annotations = tool_info.tool.annotations.as_ref();
if !AppToolPolicyEvaluator::new(&binding.config().config_layer_stack)
.policy(AppToolPolicyInput {
connector_id: Some(&self.connector_id),
link_id: None,
tool_name: tool_info.tool.name.as_ref(),
tool_title: tool_info.tool.title.as_deref(),
destructive_hint: annotations.and_then(|value| value.destructive_hint),
open_world_hint: annotations.and_then(|value| value.open_world_hint),
})
.enabled
{
anyhow::bail!("originating MCP tool is disabled by app configuration");
}
let meta = params.meta.get_or_insert_default();
meta.insert("threadId".into(), serde_json::json!(thread_id));
meta.insert(
"x-codex-turn-metadata".into(),
serde_json::json!({
"mcp_request_meta": {
"selected_connector_ids": [&self.connector_id],
"link_id": &self.link_id,
}
}),
);
binding
.read_resource(CODEX_APPS_MCP_SERVER_NAME, params)
.await
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,184 @@
//! A chat's access to an initialized MCP client and its tool catalog.
//! A pooled connection honors this chat's lease and routes input requests back to it.
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use super::MCP_TOOLS_LIST_DURATION_METRIC;
use crate::client_tool_catalog::ClientToolCatalog;
use crate::connection_pool::ConnectionSharing;
use crate::runtime::emit_duration;
use crate::tools::ToolInfo;
use anyhow::Result;
use anyhow::anyhow;
use codex_connectors::ConnectorRuntimeContext;
use codex_protocol::mcp::McpServerInfo;
use codex_rmcp_client::RmcpClient;
use codex_rmcp_client::SendElicitation;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ServerCapabilities;
use serde_json::Value;
use tokio_util::task::AbortOnDropHandle;
#[derive(Clone)]
pub(crate) struct ManagedClient {
pub(crate) connection_sharing: ConnectionSharing,
/// The calling chat's input handler, separate from the shared transport's startup handler.
pub(crate) shared_elicitation: Option<Arc<SendElicitation>>,
pub(crate) _auth_change_notifications: Option<Arc<AbortOnDropHandle<()>>>,
pub(crate) client: Arc<RmcpClient>,
pub(crate) server_info: McpServerInfo,
pub(crate) tool_catalog: Arc<ClientToolCatalog>,
pub(crate) tool_timeout: Option<Duration>,
pub(crate) server_instructions: Option<String>,
pub(crate) server_supports_sandbox_state_meta_capability: bool,
pub(crate) client_supports_network_policy_meta_capability: bool,
pub(crate) codex_apps_tools_cache_context: Option<ConnectorRuntimeContext<ToolInfo>>,
}
impl ManagedClient {
pub(crate) async fn with_active_shared_lease<T>(
&self,
operation: impl Future<Output = T>,
) -> Result<T> {
match &self.connection_sharing {
ConnectionSharing::Shared(lease) => tokio::select! {
biased;
() = lease.cancellation().cancelled() => {
Err(anyhow!("MCP connection lease has been released"))
}
result = operation => Ok(result),
},
ConnectionSharing::Private
| ConnectionSharing::Negotiated
| ConnectionSharing::Owned(_) => Ok(operation.await),
}
}
pub(crate) async fn with_lease_request<T>(
&self,
operation: impl Future<Output = Result<T>>,
) -> Result<T> {
// Keep one copy of the request future as it passes through both lease scopes.
let operation = std::pin::pin!(operation);
self.with_active_shared_lease(async {
match self.connection_sharing.server_lease() {
Some(lease) => lease.requests.scope(operation).await,
None => operation.await,
}
})
.await?
}
pub(crate) async fn call_tool(
&self,
name: String,
arguments: Option<Value>,
meta_for_session: impl Fn(&ServerCapabilities) -> Result<Option<Value>> + Send + Sync,
timeout: Option<Duration>,
) -> Result<rmcp::model::CallToolResult> {
let meta_for_session = |caps: &ServerCapabilities| {
let mut meta = meta_for_session(caps)?;
if let Some(lease) = self.connection_sharing.server_lease() {
meta.get_or_insert_with(|| serde_json::json!({}))
.as_object_mut()
.ok_or_else(|| anyhow!("MCP tool metadata must be an object"))?
.insert(
crate::connection_pool::LEASE_META_KEY.to_owned(),
serde_json::json!(lease.id),
);
}
Ok(meta)
};
self.with_lease_request(async {
if let Some(send_elicitation) = &self.shared_elicitation {
self.client
.call_tool_with_elicitation(
name,
arguments,
meta_for_session,
timeout,
Arc::clone(send_elicitation),
)
.await
} else {
self.client
.call_tool(name, arguments, meta_for_session, timeout)
.await
}
})
.await
}
/// Lists resources within this chat's lease lifetime.
pub(crate) async fn list_resources(
&self,
params: Option<PaginatedRequestParams>,
timeout: Option<Duration>,
) -> Result<ListResourcesResult> {
self.with_active_shared_lease(self.client.list_resources(params, timeout))
.await?
}
/// Lists resource templates within this chat's lease lifetime.
pub(crate) async fn list_resource_templates(
&self,
params: Option<PaginatedRequestParams>,
timeout: Option<Duration>,
) -> Result<ListResourceTemplatesResult> {
self.with_active_shared_lease(self.client.list_resource_templates(params, timeout))
.await?
}
/// Reads a resource using this chat's input authority and lease lifetime.
pub(crate) async fn read_resource(
&self,
mut params: rmcp::model::ReadResourceRequestParams,
timeout: Option<Duration>,
) -> Result<rmcp::model::ReadResourceResult> {
if let Some(lease) = self.connection_sharing.server_lease() {
params.meta.get_or_insert_default().insert(
crate::connection_pool::LEASE_META_KEY.to_owned(),
serde_json::json!(lease.id),
);
}
self.with_lease_request(async {
if let Some(send_elicitation) = &self.shared_elicitation {
self.client
.read_resource_with_elicitation(params, timeout, Arc::clone(send_elicitation))
.await
} else {
self.client.read_resource(params, timeout).await
}
})
.await
}
pub(crate) async fn listed_catalog(&self) -> (Vec<ToolInfo>, Option<Arc<serde_json::Value>>) {
let total_start = Instant::now();
self.tool_catalog
.read(|catalog| {
// Discovery may use the shared cache until this client is refreshed.
// Executable bindings always capture this client's own catalog.
if catalog.revision == 0
&& let Some(cache_context) = &self.codex_apps_tools_cache_context
{
let tools = cache_context.current_catalog_snapshot();
emit_duration(
MCP_TOOLS_LIST_DURATION_METRIC,
total_start.elapsed(),
&[("cache", if tools.is_some() { "hit" } else { "miss" })],
);
if let Some(tools) = tools {
return (tools.tools().to_vec(), tools.shared_tool_list_meta());
}
}
(catalog.tools.to_vec(), catalog.meta)
})
.await
}
}

View File

@@ -0,0 +1,84 @@
//! Plugin attribution stays bounded without changing tool definitions or membership.
use super::*;
use pretty_assertions::assert_eq;
fn app_tool(description: &str) -> ToolInfo {
tool_info_from_listed_tool(
CODEX_APPS_MCP_SERVER_NAME,
/*is_codex_apps_mcp_server*/ true,
/*server_instructions*/ None,
ToolWithConnectorId {
tool: RmcpTool::new("search", description.to_string(), Arc::default()),
connector_id: Some("shared-connector".to_string()),
connector_name: None,
connector_description: None,
},
)
}
#[test]
fn provenance_preserves_short_descriptions_and_membership() {
for (description, names, expected_description) in [
("Search", vec![], "Search"),
("", vec!["Alpha"], "This tool is part of plugin `Alpha`."),
(
"Search",
vec!["Alpha"],
"Search. This tool is part of plugin `Alpha`.",
),
(
"Search!",
vec!["Alpha", "Beta"],
"Search! This tool is part of plugins `Alpha`, `Beta`.",
),
] {
let names = names.into_iter().map(str::to_string).collect::<Vec<_>>();
let mut tool = app_tool(description);
let mut expected = tool.clone();
expected.tool.description = Some(expected_description.to_string().into());
expected.plugin_display_names = names.clone();
add_plugin_provenance_to_tool(&mut tool, &names);
assert_eq!(tool, expected);
}
}
#[test]
fn provenance_bounds_aggregate_names_and_retains_all_associations() {
let exact_name =
"a".repeat(MAX_PLUGIN_PROVENANCE_BYTES - "This tool is part of plugin ``.".len());
for names in [
vec![exact_name.clone()],
vec![format!("{exact_name}a")],
vec!["界".repeat(MAX_PLUGIN_PROVENANCE_BYTES)],
(0..512)
.map(|index| format!("{index:03}{}", "界".repeat(61)))
.collect(),
] {
let mut tool = app_tool("Search.");
let original = tool.clone();
add_plugin_provenance_to_tool(&mut tool, &names);
let note = tool
.tool
.description
.as_deref()
.unwrap()
.strip_prefix("Search. ")
.unwrap();
assert!(note.len() <= MAX_PLUGIN_PROVENANCE_BYTES);
if names[0] == exact_name {
assert_eq!(note.len(), MAX_PLUGIN_PROVENANCE_BYTES);
} else if names.len() == 1 {
assert_eq!(note, "This tool is part of 1 plugin.");
} else {
let shown = note.matches('`').count() / 2;
assert!(shown > 0 && shown < names.len());
assert!(note.starts_with(&format!("This tool is part of plugins `{}`", names[0])));
assert!(note.ends_with(&format!(", and {} more.", names.len() - shown)));
}
let mut expected = original;
expected.tool.description = tool.tool.description.clone();
expected.plugin_display_names = names;
assert_eq!(tool, expected);
}
}

View File

@@ -0,0 +1,46 @@
//! Observe the latest startup attempt without polling it or initiating a retry.
use codex_protocol::mcp::McpServerConnectionStatus as Status;
use super::AsyncManagedClient;
use super::StartupOutcomeError;
impl AsyncManagedClient {
pub(crate) async fn connection_status(&self) -> Status {
if self.cancel_token.is_cancelled() {
return Status::Cancelled;
}
let reconnect_outcome = if let Some(reconnect) = &self.startup_reconnect {
let state = reconnect
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state.reconnect_in_flight.is_some() {
return Status::Starting;
}
state
.current_client
.clone()
.map(Ok)
.or_else(|| state.last_error.clone().map(Err))
} else {
None
};
let outcome = reconnect_outcome.or_else(|| self.client.peek().cloned());
match outcome {
Some(Ok(client)) => {
if client.client.is_closed().await {
Status::Failed
} else {
Status::Connected
}
}
Some(Err(error)) if error.is_authentication_required() => {
Status::AuthenticationRequired
}
Some(Err(StartupOutcomeError::Failed { .. })) => Status::Failed,
Some(Err(StartupOutcomeError::Cancelled)) => Status::Cancelled,
None => Status::Starting,
}
}
}

View File

@@ -0,0 +1,59 @@
//! Credential resolution must retain executor provenance when host fallback is considered.
use super::resolve_bearer_token;
use crate::server::McpCredentialPolicy;
use pretty_assertions::assert_eq;
#[test]
fn executor_credentials_reject_host_fallback_for_arbitrary_environment_names() {
for env_var in ["PATH", "MCP_UNPROTECTED_TEST_TOKEN"] {
let error = resolve_bearer_token("docs", Some(env_var), McpCredentialPolicy::ExecutorOnly)
.expect_err("executor credential names must never resolve on the host");
assert_eq!(
error.to_string(),
"MCP server 'docs' requires executor-side environment credential resolution; update the executor to a version that supports it (host fallback is disabled)",
);
}
}
#[test]
fn servers_without_environment_credentials_do_not_require_host_fallback() {
for policy in [
McpCredentialPolicy::ExecutorOnly,
McpCredentialPolicy::HostFallbackAllowed,
] {
assert_eq!(
resolve_bearer_token("docs", /*bearer_token_env_var*/ None, policy)
.expect("a server without an environment credential needs no resolution"),
None,
);
}
}
#[test]
fn configured_credentials_retain_host_environment_resolution() {
// PATH is nonsecret and read without changing the process environment.
let expected = match std::env::var("PATH") {
Ok(value) if value.is_empty() => {
Err("Environment variable PATH for MCP server 'docs' is empty".to_string())
}
Ok(value) => Ok(Some(value)),
Err(std::env::VarError::NotPresent) => {
Err("Environment variable PATH for MCP server 'docs' is not set".to_string())
}
Err(std::env::VarError::NotUnicode(_)) => Err(
"Environment variable PATH for MCP server 'docs' contains invalid Unicode".to_string(),
),
};
assert_eq!(
resolve_bearer_token(
"docs",
Some("PATH"),
McpCredentialPolicy::HostFallbackAllowed
)
.map_err(|error| error.to_string()),
expected,
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,73 @@
//! Read selected-server metadata from one published thread runtime.
use std::sync::Arc;
use super::McpRuntime;
use super::McpRuntimeContext;
use crate::McpConfig;
use crate::McpServerStatusSnapshot;
use crate::McpSnapshotDetail;
use crate::ResolvedMcpServer;
use crate::mcp::collect_mcp_server_status_snapshot_from_manager;
use crate::mcp::compute_auth_statuses;
use crate::mcp::effective_mcp_servers;
impl McpRuntime {
/// Reuses the selected connection and catalog without starting unrelated servers.
/// Configuration and metadata belong to the same captured runtime publication.
/// An expected registration excludes mismatched connections before discovery.
pub async fn server_status_snapshot(
&self,
server: &str,
detail: McpSnapshotDetail,
expected_registration: Option<&ResolvedMcpServer>,
runtime_context: &McpRuntimeContext,
) -> anyhow::Result<(Arc<McpConfig>, McpServerStatusSnapshot)> {
let current = self.current.load_full();
let runtime_context = runtime_context.clone().with_selected_environments(
Arc::clone(&current.environment_selections),
current.ready_environments.clone(),
);
let config = Arc::clone(
current
.config
.as_ref()
.ok_or_else(|| anyhow::anyhow!("MCP runtime is not configured"))?,
);
let mut servers = effective_mcp_servers(&config, current.auth.as_ref());
servers.retain(|name, _| {
name == server
&& expected_registration
.is_none_or(|expected| config.mcp_server_catalog.server(name) == Some(expected))
});
if config.xaa_enabled
&& servers
.values()
.any(|server| matches!(server.config().auth, codex_config::McpServerAuth::EmaAuth))
{
// Finish selected startup and any rejected-grant cleanup before reading auth.
current
.connections
.list_available_server_infos(|name| name == server)
.await;
}
let auth_statuses = compute_auth_statuses(
servers.iter(),
config.mcp_oauth_credentials_store_mode,
config.auth_keyring_backend_kind,
current.auth.as_ref(),
current.auth_manager.as_ref(),
&config.ema_state,
&runtime_context,
)
.await;
let snapshot = collect_mcp_server_status_snapshot_from_manager(
&current.connections,
auth_statuses,
servers.into_keys().collect(),
detail,
)
.await;
Ok((config, snapshot))
}
}

View File

@@ -0,0 +1,173 @@
use super::*;
use crate::connection_manager::tests::create_ready_async_managed_client;
use crate::connection_pool::ConnectionSharing;
use crate::connection_pool::ConnectionSlot;
use crate::connection_pool::McpConnectionPool;
use crate::connection_pool::tests as fixture;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use std::sync::atomic::AtomicUsize;
use tokio::sync::Notify;
#[tokio::test]
async fn forced_refresh_replaces_pending_connection_without_interrupting_other_chats() {
let pool = McpConnectionPool::default();
let key = fixture::key(&fixture::context(), &fixture::config());
let starts = Arc::new(AtomicUsize::new(0));
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let launch = Arc::new(fixture::startup(
ConnectionSharing::Negotiated,
Arc::clone(&starts),
Arc::clone(&started),
Arc::clone(&release),
fixture::TestServer::default(),
));
let slot = Arc::new(ConnectionSlot::default());
let first = {
let pool = pool.clone();
let key = key.clone();
let slot = Arc::clone(&slot);
let launch = Arc::clone(&launch);
async move {
pool.connect(
slot,
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&*launch,
)
.await
}
.boxed()
.shared()
};
let mut poll_first = first.clone();
assert!(futures::poll!(&mut poll_first).is_pending());
let other = pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&*launch,
);
tokio::pin!(other);
assert!(futures::poll!(&mut other).is_pending());
started.notified().await;
let mut owner = create_ready_async_managed_client(Vec::new()).await;
owner.client = first;
owner.connection_slot = Some(slot);
let mut connections = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
connections.insert_test_client("test_server", owner);
let connections = Arc::new(connections);
let config = Arc::new(crate::mcp::tests::test_mcp_config(std::env::temp_dir()));
let runtime = McpRuntime::empty(/*prefix_mcp_tool_names*/ true);
runtime.current.store(Arc::new(PublishedMcpRuntime {
connections: Arc::clone(&connections),
config: Some(Arc::clone(&config)),
auth: None,
auth_manager: None,
auth_token: None,
auth_owner: None,
auth_generation: Arc::new(()),
plugins_available: false,
ready_selected_capability_roots: Vec::new(),
environment_selections: Arc::default(),
ready_environments: HashMap::new(),
cached_binding: Mutex::new(None),
}));
let input = McpRuntimeInput {
network_policy_metadata: None,
runtime_auth: None,
startup_policy: McpStartupPolicy::Eager,
config,
plugins_available: false,
ready_selected_capability_roots: Vec::new(),
mcp_servers: HashMap::new(),
submit_id: "refresh".to_string(),
tx_event: None,
startup_cancellation_token: CancellationToken::new(),
runtime_context: fixture::context(),
codex_apps_tools_cache: ConnectorRuntimeManager::default(),
tool_catalog_cache: McpToolCatalogCache::default(),
codex_apps_tools_cache_key: ConnectorRuntimeContextKey::personal(
/*account_id*/ None, /*chatgpt_user_id*/ None,
),
client_mcp_extensions: ClientMcpExtensions::default(),
auth: None,
auth_manager: None,
elicitation_reviewer: None,
elicitation_lifecycle: None,
};
let binding = runtime.current_binding_for_call("test_server");
tokio::pin!(binding);
assert!(futures::poll!(&mut binding).is_pending());
runtime.reconnect_on_next_refresh();
runtime.replace(input).await;
let _replacement = tokio::time::timeout(
Duration::from_secs(1),
pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&*launch,
),
)
.await
.expect("forced refresh must not wait for the old startup")
.unwrap();
release.notify_one();
let other = other.await.unwrap();
other
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
// A second refresh of the old owner must not evict the newer replacement.
connections.retire_shared_connections();
let _joined = pool
.connect(
Arc::default(),
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&*launch,
)
.await
.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 2);
let binding = binding.await.expect("binding from the old publication");
runtime.shutdown().await;
assert!(
binding
.list_resources("test_server", /*params*/ None)
.await
.is_err()
);
other
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
let transport = Arc::clone(&other.client);
let mut other_owner = create_ready_async_managed_client(Vec::new()).await;
other_owner.client = futures::future::ready(Ok(other)).boxed().shared();
other_owner.shutdown().await;
assert!(transport.is_closed().await);
drop(binding);
}

View File

@@ -0,0 +1,50 @@
//! Verify that the host's re-exec binary supports the sandbox metadata contract.
//! Cache completed probes per absolute executable path; never infer capability from its name or PATH.
use std::collections::HashMap;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::Duration;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_process::background_command;
use tokio::sync::Mutex;
use tokio::sync::OnceCell;
const PROBE_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
static PROBES: LazyLock<Mutex<HashMap<AbsolutePathBuf, Arc<OnceCell<bool>>>>> =
LazyLock::new(Mutex::default);
pub(crate) async fn supports_sandbox_state(executable: &AbsolutePathBuf) -> bool {
let probe = {
let mut probes = PROBES.lock().await;
Arc::clone(probes.entry(executable.clone()).or_default())
};
*probe
.get_or_init(|| async {
matches!(
tokio::time::timeout(PROBE_TIMEOUT, probe_sandbox_state(executable)).await,
Ok(Ok(true))
)
})
.await
}
/// Check that the binary accepts the sandbox-state option without launching a sandbox.
///
/// Plain `sandbox --help` can also succeed for unrelated binaries, including Rust test
/// harnesses. Put `--sandbox-state-json` before `--help` so those parsers reject the
/// unknown option. Codex handles help before interpreting the placeholder `{}` policy
/// or loading configuration; only its exit status matters, not the help text.
async fn probe_sandbox_state(executable: &AbsolutePathBuf) -> std::io::Result<bool> {
let status = tokio::process::Command::from(background_command(executable.as_os_str()))
.args(["sandbox", "--sandbox-state-json", "{}", "--help"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.status()
.await?;
Ok(status.success())
}

View File

@@ -0,0 +1,82 @@
//! Keep opaque sandbox policy separate from the launcher used to apply it.
//! Both state names carry identical values during migration; neither contains
//! executable discovery data or deprecation messages.
use codex_protocol::models::PermissionProfile;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Map;
use serde_json::Value;
use std::path::PathBuf;
/// Servers advertise this experimental capability to receive opaque sandbox state
/// in tool-call `_meta`, along with a local launcher when one is available.
pub const MCP_SANDBOX_STATE_CAPABILITY: &str = "codex/sandbox-state";
/// Deprecated capability and metadata spelling, retained as an identical alias.
/// Deprecation guidance is outside the opaque policy object.
pub const MCP_SANDBOX_STATE_META_CAPABILITY: &str = "codex/sandbox-state-meta";
/// Tool-call metadata describing a sandbox launcher on the MCP server's host.
pub const MCP_SANDBOX_LAUNCHER_META_KEY: &str = "codex/sandbox-launcher";
/// Opaque policy forwarded unchanged to `codex sandbox --sandbox-state-json`.
///
/// Servers advertise `codex/sandbox-state` (or its deprecated `-meta` alias) to
/// receive the same object under both state keys. Consumers must preserve unknown
/// fields, not deserialize and reconstruct the policy. Launcher information lives
/// separately under `codex/sandbox-launcher`; only its documented fields may be
/// interpreted. Long-lived subprocesses retain both their state and launcher and
/// must not be reused under different authority without a lifecycle decision.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SandboxState {
pub permission_profile: PermissionProfile,
pub codex_linux_sandbox_exe: Option<PathBuf>,
pub sandbox_cwd: PathUri,
#[serde(default)]
pub use_legacy_landlock: bool,
#[serde(default)]
pub use_mxc: bool,
}
/// The known launcher envelope is distinct from the opaque policy. Absence never
/// authorizes searching PATH or falling back to an unsandboxed process.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct SandboxLauncher {
/// A full CLI on the MCP server's host, supporting `sandbox --sandbox-state-json`.
/// Remote/HTTP servers and hosts without a verified, UTF-8 CLI path omit the envelope.
codex_executable: AbsolutePathBuf,
}
pub(crate) fn augment_metadata(
meta: &mut Option<Value>,
state: SandboxState,
executable: Option<AbsolutePathBuf>,
) -> anyhow::Result<()> {
let state = serde_json::to_value(state)?;
let launcher = executable
.map(|codex_executable| serde_json::to_value(SandboxLauncher { codex_executable }))
.transpose()?;
let Some(metadata) = meta
.get_or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()
else {
return Ok(());
};
metadata.insert(MCP_SANDBOX_STATE_CAPABILITY.to_owned(), state.clone());
metadata.insert(MCP_SANDBOX_STATE_META_CAPABILITY.to_owned(), state);
// Reserved launcher metadata must not survive from a previous/local call
// when this server's execution environment has no verified executable.
metadata.remove(MCP_SANDBOX_LAUNCHER_META_KEY);
if let Some(launcher) = launcher {
metadata.insert(MCP_SANDBOX_LAUNCHER_META_KEY.to_owned(), launcher);
}
Ok(())
}
#[cfg(test)]
#[path = "sandbox_metadata_tests.rs"]
mod tests;

View File

@@ -0,0 +1,62 @@
//! Preserve sandbox policy wire semantics while launcher metadata evolves separately.
use super::*;
use pretty_assertions::assert_eq;
use serde_json::Value;
#[test]
fn sandbox_state_serializes_skip_missing_entries_as_missing_path_behavior() {
let sandbox_cwd = PathUri::from_host_native_path(
std::env::current_dir().expect("current directory should be available"),
)
.expect("current directory should convert to a URI");
let sandbox_state = SandboxState {
permission_profile: PermissionProfile::workspace_write(),
codex_linux_sandbox_exe: None,
sandbox_cwd,
use_legacy_landlock: false,
use_mxc: false,
};
let serialized = serde_json::to_value(&sandbox_state).expect("serialize sandbox state");
let serialized_text = serde_json::to_string(&serialized).expect("serialize JSON text");
assert!(
!serialized_text.contains("generated_default_path"),
"MCP sandbox metadata must preserve FileSystemPath's stable wire variants"
);
assert!(
!serialized_text.contains("generated_default_special"),
"MCP sandbox metadata must preserve FileSystemPath's stable wire variants"
);
let entries = serialized
.pointer("/permissionProfile/file_system/entries")
.and_then(Value::as_array)
.expect("workspace-write profile should contain filesystem entries");
let skip_missing_entries = entries
.iter()
.filter(|entry| entry.get("missing_path_behavior").and_then(Value::as_str) == Some("skip"))
.collect::<Vec<_>>();
assert!(
!skip_missing_entries.is_empty(),
"skip-missing entries should be represented as optional missing_path_behavior"
);
assert!(
skip_missing_entries.iter().all(|entry| {
matches!(
entry.pointer("/path/type").and_then(Value::as_str),
Some("path" | "special")
)
}),
"skip-missing entries should use the stable path/special variants"
);
let deserialized: SandboxState =
serde_json::from_value(serialized.clone()).expect("deserialize legacy sandbox state");
assert_eq!(deserialized, sandbox_state);
let mut extended = serialized;
extended["futureField"] = serde_json::json!({"preservedByOpaqueConsumers": true});
let deserialized: SandboxState = serde_json::from_value(extended).expect("extended state");
assert_eq!(deserialized, sandbox_state);
}

View File

@@ -0,0 +1,528 @@
use std::collections::HashMap;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::Arc;
use crate::auth::McpAuthProvider;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::runtime::McpRuntimeContext;
use codex_config::AppToolApproval;
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
use codex_config::McpServerOAuthConfig;
use codex_config::McpServerTransportConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_connectors::ConnectorRuntimeContextKey;
use codex_exec_server::Environment;
use codex_login::CodexAuth;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_rmcp_client::McpOAuthRefreshMode;
use codex_rmcp_client::McpProtocolMode;
use codex_rmcp_client::StoredOAuthCredentialSnapshot;
use codex_rmcp_client::StoredOAuthTokens;
use codex_utils_path_uri::PathUri;
use rmcp::model::ElicitationCapability;
use tracing::warn;
/// Authority to resolve environment-variable credentials, retained independently of
/// executor capabilities so a reconnect cannot promote guest configuration to host access.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum McpCredentialPolicy {
/// Host-configured servers retain local and legacy remote credential resolution.
HostFallbackAllowed,
/// Executor-discovered names must never be looked up in the host environment.
ExecutorOnly,
}
/// MCP server after runtime additions have been applied.
#[derive(Debug, Clone)]
pub struct EffectiveMcpServer {
config: McpServerConfig,
credential_policy: McpCredentialPolicy,
agent_plugin: bool,
requires_read_only_mcp_tools: bool,
}
impl EffectiveMcpServer {
/// Constructs an effective server from host-owned configuration.
pub fn from_host_config(config: McpServerConfig) -> Self {
Self::from_config_with_policy(config, McpCredentialPolicy::HostFallbackAllowed)
}
pub(crate) fn from_config_with_policy(
config: McpServerConfig,
credential_policy: McpCredentialPolicy,
) -> Self {
Self {
config,
credential_policy,
agent_plugin: false,
requires_read_only_mcp_tools: false,
}
}
pub(crate) fn credential_policy(&self) -> McpCredentialPolicy {
self.credential_policy
}
pub fn with_agent_plugin(mut self, agent_plugin: bool) -> Self {
self.agent_plugin = agent_plugin;
self
}
pub(crate) fn with_read_only_mcp_tools(mut self, requires_read_only_mcp_tools: bool) -> Self {
self.requires_read_only_mcp_tools = requires_read_only_mcp_tools;
self
}
pub(crate) fn requires_read_only_mcp_tools(&self) -> bool {
self.requires_read_only_mcp_tools
}
pub fn config(&self) -> &McpServerConfig {
&self.config
}
/// Checks whether Core can discover the protocol of a local stdio server.
///
/// The reserved `codex_apps` server has a per-chat catalog. Servers with runtime or
/// enterprise-managed credentials need that chat's authentication state.
pub(crate) fn can_discover_local_stdio(
&self,
server_name: &str,
runtime_auth_provider: Option<&McpAuthProvider>,
) -> bool {
server_name != CODEX_APPS_MCP_SERVER_NAME
&& self.config.is_local_environment()
&& runtime_auth_provider.is_none()
&& !matches!(self.config.auth, McpServerAuth::EmaAuth)
&& self
.stdio_protocol_mode(McpProtocolMode::DiscoverLocalStdio)
.is_some()
}
/// Returns the handshake a stdio launch would use, or `None` for HTTP or an invalid version.
pub(crate) fn stdio_protocol_mode(&self, mode: McpProtocolMode) -> Option<McpProtocolMode> {
let McpServerTransportConfig::Stdio { env, .. } = &self.config.transport else {
return None;
};
let version = env
.as_ref()
.and_then(|env| env.get("CODEX_MCP_PROTOCOL_VERSION"));
mode.stdio_mode(version.map(OsStr::new)).ok()
}
pub fn enabled(&self) -> bool {
self.config.enabled
}
pub fn required(&self) -> bool {
self.config.required
}
pub fn is_agent_plugin(&self) -> bool {
self.agent_plugin
}
}
pub(crate) fn has_explicit_http_authorization(config: &McpServerConfig) -> bool {
let McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
http_headers,
env_http_headers,
..
} = &config.transport
else {
return false;
};
if bearer_token_env_var.is_some()
|| env_http_headers
.as_ref()
.is_some_and(|headers| !headers.is_empty())
{
return false;
}
http_headers.as_ref().is_some_and(|headers| {
headers.iter().any(|(name, value)| {
name.eq_ignore_ascii_case("authorization")
&& !value.trim().is_empty()
&& value
.bytes()
.all(|byte| byte == b'\t' || (byte >= b' ' && byte != 0x7f))
})
})
}
/// Inputs that determine the identity of a live MCP connection.
///
/// Tool policy and presentation metadata intentionally do not appear here:
/// those belong to a publication and can change without reconnecting.
#[derive(Clone)]
pub(crate) struct McpServerConnectionIdentity {
auth: McpServerAuth,
pub(crate) credential_policy: McpCredentialPolicy,
transport: McpServerTransportConfig,
environment_id: String,
host_plugin_root: Option<PathUri>,
oauth_store: Option<(OAuthCredentialsStoreMode, AuthKeyringBackendKind)>,
oauth_refresh_mode: Option<McpOAuthRefreshMode>,
oauth_config: Option<McpServerOAuthConfig>,
oauth_credentials: Result<Option<StoredOAuthCredentialSnapshot>, String>,
pub(crate) oauth_store_was_contended: bool,
resolved_environment: Result<Option<Arc<Environment>>, String>,
local_stdio_fallback_cwd: Option<PathBuf>,
referenced_environment_variables: Vec<(String, Option<OsString>)>,
runtime_auth: Option<CodexAuth>,
runtime_auth_token: Option<String>,
runtime_auth_mode: Option<codex_features::RuntimeAuthMode>,
codex_apps_cache_identity: Option<(PathBuf, ConnectorRuntimeContextKey)>,
client_elicitation_capability: ElicitationCapability,
client_mcp_extensions: ClientMcpExtensions,
agent_plugin: bool,
requires_read_only_mcp_tools: bool,
}
impl McpServerConnectionIdentity {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
server_name: &str,
server: &EffectiveMcpServer,
host_plugin_root: Option<&PathUri>,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
oauth_refresh_mode: McpOAuthRefreshMode,
resolved_environment: &Result<Option<Arc<Environment>>, String>,
runtime_context: &McpRuntimeContext,
runtime_auth_provider: Option<&McpAuthProvider>,
runtime_auth_mode: Option<codex_features::RuntimeAuthMode>,
auth: Option<&CodexAuth>,
codex_apps_cache_identity: Option<(PathBuf, ConnectorRuntimeContextKey)>,
client_elicitation_capability: ElicitationCapability,
client_mcp_extensions: ClientMcpExtensions,
previous_identity: Option<&Self>,
) -> Self {
let config = server.config();
let valid_http_header_value = |value: &str| {
value
.bytes()
.all(|byte| byte == b'\t' || (byte >= b' ' && byte != 0x7f))
};
let stored_oauth_url = if runtime_auth_provider.is_none()
&& !matches!(config.auth, McpServerAuth::EmaAuth)
&& (!matches!(config.auth, McpServerAuth::ChatGpt) || config.is_local_environment())
{
match &config.transport {
McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var: None,
http_headers,
env_http_headers,
http_headers_helper: _,
} if !http_headers.as_ref().is_some_and(|headers| {
headers.iter().any(|(name, value)| {
name.eq_ignore_ascii_case("authorization") && valid_http_header_value(value)
})
}) && !env_http_headers.as_ref().is_some_and(|headers| {
server.credential_policy() == McpCredentialPolicy::HostFallbackAllowed
&& headers.iter().any(|(name, env_var)| {
name.eq_ignore_ascii_case("authorization")
&& std::env::var(env_var).is_ok_and(|value| {
!value.trim().is_empty() && valid_http_header_value(&value)
})
})
}) =>
{
Some(url)
}
McpServerTransportConfig::StreamableHttp { .. }
| McpServerTransportConfig::Stdio { .. } => None,
}
} else {
None
};
let oauth_credentials = stored_oauth_url.map_or(Ok(None), |url| {
let credential_name = config.oauth_credential_name(server_name);
StoredOAuthCredentialSnapshot::for_runtime_refresh(
previous_identity.and_then(|previous_identity| {
previous_identity
.oauth_credentials
.as_ref()
.ok()
.and_then(Option::as_ref)
.filter(|_| {
previous_identity.oauth_store
== Some((store_mode, keyring_backend_kind))
})
}),
credential_name.as_ref(),
url,
store_mode,
keyring_backend_kind,
)
.map_err(|error| {
warn!(server_name, %error, "failed to read stored MCP OAuth credentials");
error.to_string()
})
});
let local_stdio_fallback_cwd = (config.is_local_environment()
&& matches!(
config.transport,
McpServerTransportConfig::Stdio { cwd: None, .. }
| McpServerTransportConfig::StreamableHttp {
http_headers_helper: Some(_),
..
}
))
.then(|| runtime_context.local_process_cwd());
let referenced_environment_variables = match server.credential_policy() {
McpCredentialPolicy::HostFallbackAllowed => referenced_environment_variables(config),
McpCredentialPolicy::ExecutorOnly => Vec::new(),
};
let runtime_auth = runtime_auth_provider.and(auth).cloned();
let runtime_auth_token = runtime_auth.as_ref().and_then(|auth| auth.get_token().ok());
let oauth_store_was_contended = oauth_credentials
.as_ref()
.ok()
.and_then(Option::as_ref)
.is_some_and(StoredOAuthCredentialSnapshot::store_was_contended);
Self {
auth: config.auth.clone(),
credential_policy: server.credential_policy(),
transport: config.transport.clone(),
environment_id: config.environment_id.clone(),
host_plugin_root: host_plugin_root.cloned(),
oauth_store: stored_oauth_url
.is_some()
.then_some((store_mode, keyring_backend_kind)),
oauth_refresh_mode: stored_oauth_url.is_some().then_some(oauth_refresh_mode),
oauth_config: stored_oauth_url.and(config.oauth.clone()),
oauth_credentials,
oauth_store_was_contended,
resolved_environment: resolved_environment.clone(),
local_stdio_fallback_cwd,
referenced_environment_variables,
runtime_auth,
runtime_auth_token,
runtime_auth_mode,
codex_apps_cache_identity,
client_elicitation_capability,
client_mcp_extensions,
agent_plugin: server.is_agent_plugin(),
requires_read_only_mcp_tools: server.requires_read_only_mcp_tools(),
}
}
pub(crate) fn has_same_connection_config(&self, other: &Self) -> bool {
let same_runtime_auth = match (&self.runtime_auth, &other.runtime_auth) {
(Some(CodexAuth::AgentIdentity(left)), Some(CodexAuth::AgentIdentity(right))) => {
left.record() == right.record()
}
(Some(left), Some(right)) => {
left == right
&& left.get_account_id() == right.get_account_id()
&& left.get_chatgpt_user_id() == right.get_chatgpt_user_id()
&& left.is_fedramp_account() == right.is_fedramp_account()
}
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
};
self.auth == other.auth
&& self.credential_policy == other.credential_policy
&& self.transport == other.transport
&& self.environment_id == other.environment_id
&& self.host_plugin_root == other.host_plugin_root
&& self.oauth_store == other.oauth_store
&& self.oauth_refresh_mode == other.oauth_refresh_mode
// Callback settings only affect a future login, not the live connection.
&& self.oauth_config.as_ref().and_then(|oauth| oauth.client_id.as_ref())
== other.oauth_config.as_ref().and_then(|oauth| oauth.client_id.as_ref())
&& self.oauth_config.as_ref().and_then(|oauth| oauth.client_secret.as_ref())
== other.oauth_config.as_ref().and_then(|oauth| oauth.client_secret.as_ref())
&& same_resolved_environment(&self.resolved_environment, &other.resolved_environment)
&& self.local_stdio_fallback_cwd == other.local_stdio_fallback_cwd
&& self.referenced_environment_variables == other.referenced_environment_variables
&& same_runtime_auth
&& self.runtime_auth_token == other.runtime_auth_token
&& self.runtime_auth_mode == other.runtime_auth_mode
&& self.codex_apps_cache_identity == other.codex_apps_cache_identity
&& self.client_elicitation_capability == other.client_elicitation_capability
&& self.client_mcp_extensions == other.client_mcp_extensions
&& self.agent_plugin == other.agent_plugin
&& self.requires_read_only_mcp_tools == other.requires_read_only_mcp_tools
}
pub(crate) fn oauth_credentials(&self) -> Result<Option<&StoredOAuthTokens>, &String> {
self.oauth_credentials.as_ref().map(|credentials| {
credentials
.as_ref()
.map(StoredOAuthCredentialSnapshot::credentials)
})
}
pub(crate) fn oauth_credentials_changed(
&self,
server_name: &str,
config: &McpServerConfig,
) -> bool {
let Some((store_mode, keyring_backend_kind)) = self.oauth_store else {
return false;
};
let McpServerTransportConfig::StreamableHttp { url, .. } = &self.transport else {
return false;
};
let credential_name = config.oauth_credential_name(server_name);
let current_credentials = match self.oauth_credentials.as_ref() {
Ok(Some(credentials)) => credentials.reload(
credential_name.as_ref(),
url,
store_mode,
keyring_backend_kind,
),
Ok(None) | Err(_) => StoredOAuthCredentialSnapshot::for_runtime_refresh(
/*previous*/ None,
credential_name.as_ref(),
url,
store_mode,
keyring_backend_kind,
)
.map(|snapshot| snapshot.map(|snapshot| snapshot.credentials().clone())),
};
match current_credentials {
Ok(Some(current_credentials)) => {
self.oauth_credentials() != Ok(Some(&current_credentials))
}
Ok(None) => false,
Err(error) => {
warn!(server_name, %error, "failed to read stored MCP OAuth credentials");
false
}
}
}
}
impl PartialEq for McpServerConnectionIdentity {
fn eq(&self, other: &Self) -> bool {
self.has_same_connection_config(other) && self.oauth_credentials == other.oauth_credentials
}
}
fn same_resolved_environment(
left: &Result<Option<Arc<Environment>>, String>,
right: &Result<Option<Arc<Environment>>, String>,
) -> bool {
match (left, right) {
(Ok(Some(left)), Ok(Some(right))) => Arc::ptr_eq(left, right),
(Ok(None), Ok(None)) => true,
(Err(left), Err(right)) => left == right,
(Ok(_), Ok(_)) | (Ok(_), Err(_)) | (Err(_), Ok(_)) => false,
}
}
fn referenced_environment_variables(config: &McpServerConfig) -> Vec<(String, Option<OsString>)> {
let mut names = match &config.transport {
McpServerTransportConfig::Stdio { env_vars, .. } => env_vars
.iter()
.filter(|env_var| !env_var.is_remote_source())
.map(|env_var| env_var.name().to_string())
.collect::<Vec<_>>(),
McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
env_http_headers,
..
} => bearer_token_env_var
.iter()
.filter(|name| config.is_local_environment() || std::env::var_os(name).is_some())
.chain(env_http_headers.iter().flat_map(|headers| headers.values()))
.cloned()
.collect(),
};
names.sort();
names.dedup();
names
.into_iter()
.map(|name| {
let value = std::env::var_os(&name);
(name, value)
})
.collect()
}
/// Transport origin retained for metrics and diagnostics after server launch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum McpServerOrigin {
Stdio,
StreamableHttp(String),
}
impl McpServerOrigin {
pub fn as_str(&self) -> &str {
match self {
Self::Stdio => "stdio",
Self::StreamableHttp(origin) => origin,
}
}
fn from_transport(transport: &McpServerTransportConfig) -> Option<Self> {
match transport {
McpServerTransportConfig::StreamableHttp { url, .. } => {
let parsed = url::Url::parse(url).ok()?;
Some(Self::StreamableHttp(parsed.origin().ascii_serialization()))
}
McpServerTransportConfig::Stdio { .. } => Some(Self::Stdio),
}
}
}
/// Semantic metadata that must survive after the server is launched.
#[derive(Debug, Clone)]
pub(crate) struct McpServerMetadata {
pub environment_id: String,
pub pollutes_memory: bool,
pub origin: Option<McpServerOrigin>,
pub supports_parallel_tool_calls: bool,
pub default_tools_approval_mode: Option<AppToolApproval>,
pub tool_approval_modes: HashMap<String, AppToolApproval>,
}
impl McpServerMetadata {
pub fn tool_approval_mode(&self, tool_name: &str) -> AppToolApproval {
self.tool_approval_modes
.get(tool_name)
.copied()
.or(self.default_tools_approval_mode)
.unwrap_or_default()
}
}
impl From<&EffectiveMcpServer> for McpServerMetadata {
fn from(server: &EffectiveMcpServer) -> Self {
let config = server.config();
Self {
environment_id: config.environment_id.clone(),
pollutes_memory: true,
origin: McpServerOrigin::from_transport(&config.transport),
supports_parallel_tool_calls: config.supports_parallel_tool_calls,
default_tools_approval_mode: config.default_tools_approval_mode,
tool_approval_modes: config
.tools
.iter()
.filter_map(|(name, config)| {
config
.approval_mode
.map(|approval_mode| (name.clone(), approval_mode))
})
.collect(),
}
}
}
#[cfg(test)]
#[path = "server_tests.rs"]
mod tests;

View File

@@ -0,0 +1,179 @@
use super::EffectiveMcpServer;
use super::McpCredentialPolicy;
use super::McpServerConnectionIdentity;
use super::referenced_environment_variables;
use crate::McpProtocolMode;
use crate::runtime::McpRuntimeContext;
use crate::tool_catalog_cache::McpToolCatalogCache;
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use codex_config::McpServerConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server_test_support::environment_manager_without_environments;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_rmcp_client::McpOAuthRefreshMode;
use pretty_assertions::assert_eq;
use rmcp::model::ElicitationCapability;
use std::sync::Arc;
#[test]
fn remote_http_connections_track_host_headers_but_not_executor_bearer_tokens() {
let mut config: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp",
"environment_id": "executor-1",
"bearer_token_env_var": "NODE_REPL_AUTH_TOKEN",
"env_http_headers": {"X-Api-Key": "PATH"},
}))
.expect("remote MCP configuration should deserialize");
assert_eq!(
referenced_environment_variables(&config),
vec![("PATH".to_string(), std::env::var_os("PATH"))],
);
let remote_host_bearer: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp",
"environment_id": "executor-1",
"bearer_token_env_var": "PATH",
}))
.expect("host-resolved remote MCP configuration should deserialize");
assert_eq!(
referenced_environment_variables(&remote_host_bearer),
vec![("PATH".to_string(), std::env::var_os("PATH"))],
);
config.environment_id = DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string();
assert_eq!(
referenced_environment_variables(&config),
vec![
(
"NODE_REPL_AUTH_TOKEN".to_string(),
std::env::var_os("NODE_REPL_AUTH_TOKEN"),
),
("PATH".to_string(), std::env::var_os("PATH")),
],
);
}
fn runtime_context() -> McpRuntimeContext {
McpRuntimeContext::new(
Arc::new(environment_manager_without_environments()),
std::env::temp_dir(),
)
}
fn connection_identity(
server: &EffectiveMcpServer,
runtime_context: &McpRuntimeContext,
) -> McpServerConnectionIdentity {
McpServerConnectionIdentity::new(
"docs",
server,
/*host_plugin_root*/ None,
OAuthCredentialsStoreMode::default(),
AuthKeyringBackendKind::default(),
McpOAuthRefreshMode::Legacy,
&Ok(None),
runtime_context,
/*runtime_auth_provider*/ None,
/*runtime_auth_mode*/ None,
/*auth*/ None,
/*codex_apps_cache_identity*/ None,
ElicitationCapability::default(),
ClientMcpExtensions::default(),
/*previous_identity*/ None,
)
}
fn explicit_authorization_server() -> EffectiveMcpServer {
EffectiveMcpServer::from_host_config(
serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp",
"environment_id": "executor-1",
"http_headers": {"Authorization": "Bearer test-canary"},
}))
.expect("remote MCP configuration should deserialize"),
)
}
#[test]
fn connection_identity_does_not_reuse_connections_across_credential_policies() {
let runtime_context = runtime_context();
let host_server = explicit_authorization_server();
let executor_server = EffectiveMcpServer::from_config_with_policy(
host_server.config().clone(),
McpCredentialPolicy::ExecutorOnly,
);
let host_identity = connection_identity(&host_server, &runtime_context);
let executor_identity = connection_identity(&executor_server, &runtime_context);
assert!(
host_identity
.has_same_connection_config(&connection_identity(&host_server, &runtime_context,))
);
assert!(
executor_identity
.has_same_connection_config(&connection_identity(&executor_server, &runtime_context,))
);
assert!(!host_identity.has_same_connection_config(&executor_identity));
assert!(!executor_identity.has_same_connection_config(&host_identity));
}
#[test]
fn executor_connection_identity_does_not_capture_host_environment_values() {
let runtime_context = runtime_context();
let host_server = EffectiveMcpServer::from_host_config(
serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp",
"environment_id": "executor-1",
"bearer_token_env_var": "PATH",
}))
.expect("remote MCP configuration should deserialize"),
);
let executor_server = EffectiveMcpServer::from_config_with_policy(
host_server.config().clone(),
McpCredentialPolicy::ExecutorOnly,
);
assert_eq!(
connection_identity(&host_server, &runtime_context).referenced_environment_variables,
vec![("PATH".to_string(), std::env::var_os("PATH"))],
);
assert_eq!(
connection_identity(&executor_server, &runtime_context).referenced_environment_variables,
Vec::new(),
);
}
#[test]
fn tool_catalog_cache_does_not_reuse_catalogs_across_credential_policies() {
let runtime_context = runtime_context();
let host_server = explicit_authorization_server();
let executor_server = EffectiveMcpServer::from_config_with_policy(
host_server.config().clone(),
McpCredentialPolicy::ExecutorOnly,
);
let host_identity = connection_identity(&host_server, &runtime_context);
let executor_identity = connection_identity(&executor_server, &runtime_context);
let cache = McpToolCatalogCache::default();
let context = |identity| {
cache
.context(
"docs",
host_server.config(),
&runtime_context,
/*resolved_environment*/ None,
(
&ElicitationCapability::default(),
&ClientMcpExtensions::default(),
),
Some((identity, McpProtocolMode::Legacy, false)),
)
.expect("explicit authorization permits catalog caching")
};
let host_context = context(&host_identity);
host_context.publish_if_newest(host_context.begin_fetch(), &[], /*meta*/ None);
assert_eq!(context(&host_identity).current_tools(), Some(Vec::new()));
assert_eq!(context(&executor_identity).current_tools(), None);
}

View File

@@ -0,0 +1,19 @@
---
source: codex-mcp/src/connection_manager_tests.rs
expression: "displays.join(\"\\n\\n\")"
---
MCP client for `npm:@scope/package.name` timed out after 30 seconds. Add or adjust `startup_timeout_sec` in your config.toml:
[mcp_servers."npm:@scope/package.name"]
startup_timeout_sec = XX
GitHub MCP does not support OAuth. Log in by adding a personal access token (https://github.com/settings/personal-access-tokens) to your environment and config.toml:
[mcp_servers."npm:@scope/package.name"]
bearer_token_env_var = CODEX_GITHUB_PERSONAL_ACCESS_TOKEN
MCP client for `server.name` timed out after 30 seconds. Add or adjust `startup_timeout_sec` in your config.toml:
[mcp_servers."server.name"]
startup_timeout_sec = XX
GitHub MCP does not support OAuth. Log in by adding a personal access token (https://github.com/settings/personal-access-tokens) to your environment and config.toml:
[mcp_servers."server.name"]
bearer_token_env_var = CODEX_GITHUB_PERSONAL_ACCESS_TOKEN

View File

@@ -0,0 +1,491 @@
use std::collections::BTreeMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::Weak;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
use codex_config::McpServerTransportConfig;
use codex_exec_server::Environment;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_rmcp_client::ToolListRevision;
use lru::LruCache;
use rmcp::model::ElicitationCapability;
use sha1::Digest;
use sha1::Sha1;
use tokio::time::Instant;
use crate::McpProtocolMode;
use crate::McpRuntimeContext;
use crate::ToolInfo;
use crate::server::McpCredentialPolicy;
use crate::server::McpServerConnectionIdentity;
use crate::server::has_explicit_http_authorization;
const TOOL_CATALOG_CACHE_CAPACITY: usize = 32;
const TOOL_CATALOG_CACHE_TTL: Duration = Duration::from_secs(30 * 60);
/// Process-scoped cache of recent reusable tool definitions for MCP servers.
#[derive(Clone)]
pub struct McpToolCatalogCache {
entries: Arc<Mutex<LruCache<ToolCatalogIdentity, Arc<ToolCatalogCacheEntry>>>>,
}
impl Default for McpToolCatalogCache {
fn default() -> Self {
Self {
entries: Arc::new(Mutex::new(LruCache::new(
NonZeroUsize::new(TOOL_CATALOG_CACHE_CAPACITY).unwrap_or(NonZeroUsize::MIN),
))),
}
}
}
struct ToolCatalogCacheEntry {
state: Mutex<ToolCatalogCacheState>,
next_fetch_generation: AtomicU64,
}
#[derive(Default)]
struct ToolCatalogCacheState {
snapshot: Option<ToolCatalogSnapshot>,
optional_startup_deadline: Option<OptionalStartupDeadline>,
last_catalog_generation: u64,
last_modern_discovery_generation: u64,
disabled_by_server: bool,
}
struct OptionalStartupDeadline {
grace: Duration,
deadline: Instant,
}
struct ToolCatalogSnapshot {
tools: Vec<ToolInfo>,
meta: Option<Arc<serde_json::Value>>,
published_at: Instant,
tool_list_revision: Option<ToolListRevision>,
}
#[derive(Clone)]
pub(crate) struct McpToolCatalogCacheContext {
pub(crate) track_tool_list_changes: bool,
pub(crate) before_stdio_discovery: bool,
entry: Arc<ToolCatalogCacheEntry>,
}
pub(crate) struct McpToolCatalogFetchTicket {
pub(crate) tool_list_revision: Option<ToolListRevision>,
generation: u64,
}
impl McpToolCatalogCache {
pub(crate) fn context(
&self,
server_name: &str,
config: &McpServerConfig,
runtime_context: &McpRuntimeContext,
resolved_environment: Option<&Arc<Environment>>,
client_context: (&ElicitationCapability, &ClientMcpExtensions),
connection_identity: Option<(&McpServerConnectionIdentity, McpProtocolMode, bool)>,
) -> Option<McpToolCatalogCacheContext> {
let identity = ToolCatalogIdentity::new(
server_name,
config,
runtime_context,
resolved_environment,
client_context,
connection_identity,
)?;
let entry = lock_unpoisoned(&self.entries)
.get_or_insert(identity, || Arc::new(ToolCatalogCacheEntry::default()))
.clone();
Some(McpToolCatalogCacheContext {
entry,
track_tool_list_changes: false,
before_stdio_discovery: false,
})
}
}
impl Default for ToolCatalogCacheEntry {
fn default() -> Self {
Self {
state: Mutex::new(ToolCatalogCacheState::default()),
next_fetch_generation: AtomicU64::new(0),
}
}
}
impl McpToolCatalogCacheContext {
fn accepts_snapshot(
&self,
state: &ToolCatalogCacheState,
snapshot: &ToolCatalogSnapshot,
) -> bool {
if self.before_stdio_discovery
&& state.last_modern_discovery_generation > state.last_catalog_generation
{
return false;
}
// Enabling refresh must not reuse a catalog published without notification tracking.
snapshot
.tool_list_revision
.as_ref()
.map_or(!self.track_tool_list_changes, |revision| {
revision.current() == 0
})
}
pub(crate) fn has_tools(&self) -> bool {
self.current_revision_if(|_| true).is_some()
}
/// Checks eligibility and reads the revision under one lock without cloning tools.
/// The predicate borrows the current catalog while the cache entry is locked.
pub(crate) fn current_revision_if(
&self,
accepts_tools: impl FnOnce(&[ToolInfo]) -> bool,
) -> Option<u64> {
let state = lock_unpoisoned(&self.entry.state);
let snapshot = state.snapshot.as_ref()?;
(!state.disabled_by_server
&& self.accepts_snapshot(&state, snapshot)
&& !snapshot.tools.is_empty()
&& snapshot.published_at.elapsed() <= TOOL_CATALOG_CACHE_TTL
&& accepts_tools(&snapshot.tools))
.then_some(state.last_catalog_generation)
}
pub(crate) fn optional_startup_deadline(
&self,
default_deadline: Instant,
startup_grace: Duration,
) -> Instant {
let mut state = lock_unpoisoned(&self.entry.state);
if state.disabled_by_server
|| state.snapshot.as_ref().is_some_and(|snapshot| {
self.accepts_snapshot(&state, snapshot)
&& snapshot.published_at.elapsed() <= TOOL_CATALOG_CACHE_TTL
})
{
return default_deadline;
}
let cached_deadline =
state
.optional_startup_deadline
.get_or_insert(OptionalStartupDeadline {
grace: startup_grace,
deadline: default_deadline,
});
if cached_deadline.grace != startup_grace {
*cached_deadline = OptionalStartupDeadline {
grace: startup_grace,
deadline: default_deadline,
};
}
cached_deadline.deadline
}
#[cfg(test)]
pub(crate) fn current_tools(&self) -> Option<Vec<ToolInfo>> {
self.current_tools_or(/*fallback*/ None)
}
/// Prefers the current catalog, retaining a capture's fallback across expiry but not opt-out.
pub(crate) fn current_tools_or(
&self,
fallback: Option<Vec<ToolInfo>>,
) -> Option<Vec<ToolInfo>> {
self.current_catalog_or(fallback.map(|tools| (tools, None)))
.map(|(tools, _)| tools)
}
pub(crate) fn current_catalog_or(
&self,
fallback: Option<(Vec<ToolInfo>, Option<Arc<serde_json::Value>>)>,
) -> Option<(Vec<ToolInfo>, Option<Arc<serde_json::Value>>)> {
let state = lock_unpoisoned(&self.entry.state);
if state.disabled_by_server
|| state
.snapshot
.as_ref()
.is_some_and(|snapshot| !self.accepts_snapshot(&state, snapshot))
{
return None;
}
state
.snapshot
.as_ref()
.filter(|snapshot| snapshot.published_at.elapsed() <= TOOL_CATALOG_CACHE_TTL)
.map(|snapshot| (snapshot.tools.clone(), snapshot.meta.clone()))
.or(fallback)
}
pub(crate) fn begin_fetch(&self) -> McpToolCatalogFetchTicket {
McpToolCatalogFetchTicket {
tool_list_revision: None,
generation: self
.entry
.next_fetch_generation
.fetch_add(1, Ordering::Relaxed)
+ 1,
}
}
pub(crate) fn disable(&self) {
let mut state = lock_unpoisoned(&self.entry.state);
state.disabled_by_server = true;
state.snapshot = None;
}
/// A modern handshake rules out older legacy catalogs for discovery. Clients forced to use
/// the legacy protocol can still use those catalogs, including legacy fetches in flight.
pub(crate) fn record_modern_stdio_discovery(&self, ticket: &McpToolCatalogFetchTicket) {
let mut state = lock_unpoisoned(&self.entry.state);
if ticket.generation
> state
.last_catalog_generation
.max(state.last_modern_discovery_generation)
{
state.last_modern_discovery_generation = ticket.generation;
state.optional_startup_deadline = None;
}
}
pub(crate) fn publish_if_newest(
&self,
ticket: McpToolCatalogFetchTicket,
tools: &[ToolInfo],
meta: Option<Arc<serde_json::Value>>,
) {
let mut state = lock_unpoisoned(&self.entry.state);
if state.disabled_by_server || ticket.generation <= state.last_catalog_generation {
return;
}
state.last_catalog_generation = ticket.generation;
state.optional_startup_deadline = None;
let mut tools = tools.to_vec();
for tool in &mut tools {
// Tool annotations affect approval and parallelism decisions, so only the live
// connection may supply them.
tool.tool.annotations = None;
}
state.snapshot = Some(ToolCatalogSnapshot {
tools,
meta,
published_at: Instant::now(),
tool_list_revision: ticket.tool_list_revision,
});
}
}
fn lock_unpoisoned<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
struct ToolCatalogIdentity {
server_name: String,
transport: ToolCatalogTransportIdentity,
environment: Option<Weak<Environment>>,
local_stdio_fallback_cwd: Option<PathBuf>,
}
impl PartialEq for ToolCatalogIdentity {
fn eq(&self, other: &Self) -> bool {
self.server_name == other.server_name
&& self.transport == other.transport
&& self.local_stdio_fallback_cwd == other.local_stdio_fallback_cwd
&& match (&self.environment, &other.environment) {
(Some(environment), Some(other)) => Weak::ptr_eq(environment, other),
(None, None) => true,
_ => false,
}
}
}
impl Eq for ToolCatalogIdentity {}
impl Hash for ToolCatalogIdentity {
fn hash<H: Hasher>(&self, state: &mut H) {
self.server_name.hash(state);
self.transport.hash(state);
self.local_stdio_fallback_cwd.hash(state);
self.environment
.as_ref()
.map(|environment| Weak::as_ptr(environment) as usize)
.hash(state);
}
}
impl ToolCatalogIdentity {
fn new(
server_name: &str,
config: &McpServerConfig,
runtime_context: &McpRuntimeContext,
environment: Option<&Arc<Environment>>,
client_context: (&ElicitationCapability, &ClientMcpExtensions),
connection_identity: Option<(&McpServerConnectionIdentity, McpProtocolMode, bool)>,
) -> Option<Self> {
let transport =
ToolCatalogTransportIdentity::new(config, client_context, connection_identity)?;
Some(Self {
server_name: server_name.to_string(),
transport,
environment: environment.map(Arc::downgrade),
local_stdio_fallback_cwd: matches!(
&config.transport,
McpServerTransportConfig::Stdio { cwd: None, .. }
)
.then(|| runtime_context.local_process_cwd()),
})
}
}
#[derive(PartialEq, Eq, Hash)]
enum ToolCatalogTransportIdentity {
Stdio { fingerprint: [u8; 20] },
StreamableHttp { fingerprint: [u8; 20] },
}
impl ToolCatalogTransportIdentity {
fn new(
config: &McpServerConfig,
client_context: (&ElicitationCapability, &ClientMcpExtensions),
connection_identity: Option<(&McpServerConnectionIdentity, McpProtocolMode, bool)>,
) -> Option<Self> {
let (client_elicitation_capability, client_mcp_extensions) = client_context;
if let McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
http_headers_helper,
} = &config.transport
{
// Helper output is a dynamic credential identity that cannot be represented by config.
if http_headers_helper.is_some() {
return None;
}
let (connection_identity, protocol_mode, agent_plugin) = connection_identity?;
if config.oauth.is_some()
|| config.scopes.is_some()
|| config.oauth_resource.is_some()
|| (matches!(config.auth, McpServerAuth::ChatGpt)
&& !has_explicit_http_authorization(config))
|| (!has_explicit_http_authorization(config)
&& connection_identity.oauth_credentials().ok()?.is_some())
{
return None;
}
let mut hasher = Sha1::new();
hasher.update(match connection_identity.credential_policy {
McpCredentialPolicy::HostFallbackAllowed => b"host-fallback".as_slice(),
McpCredentialPolicy::ExecutorOnly => b"executor-only".as_slice(),
});
hasher.update(
serde_json::to_vec(&(
url,
bearer_token_env_var,
http_headers
.as_ref()
.map(|headers| headers.iter().collect::<BTreeMap<_, _>>()),
env_http_headers
.as_ref()
.map(|headers| headers.iter().collect::<BTreeMap<_, _>>()),
&config.auth,
&config.environment_id,
agent_plugin,
protocol_mode.preferred_protocol_version().as_str(),
client_elicitation_capability,
client_mcp_extensions.iter().collect::<BTreeMap<_, _>>(),
))
.ok()?,
);
let mut env_vars = bearer_token_env_var
.iter()
.chain(env_http_headers.iter().flat_map(|headers| headers.values()))
.collect::<Vec<_>>();
env_vars.sort_unstable();
env_vars.dedup();
for name in env_vars {
hasher.update(name.as_bytes());
if connection_identity.credential_policy == McpCredentialPolicy::HostFallbackAllowed
{
let mut value_hasher = DefaultHasher::new();
std::env::var_os(name).hash(&mut value_hasher);
hasher.update(value_hasher.finish().to_le_bytes());
}
}
return Some(Self::StreamableHttp {
fingerprint: hasher.finalize().into(),
});
}
let McpServerTransportConfig::Stdio {
command,
args,
env,
env_vars,
cwd,
} = &config.transport
else {
return None;
};
// An unmarked helper can expose different tools after a legacy fallback.
if matches!(
connection_identity,
Some((_, McpProtocolMode::DiscoverLocalStdio, _))
) {
return None;
}
if env_vars
.iter()
.any(codex_config::McpServerEnvVar::is_remote_source)
{
return None;
}
let mut hasher = Sha1::new();
let env = env.as_ref().map(|env| {
env.iter()
.map(|(key, value)| (key.as_str(), value.as_str()))
.collect::<BTreeMap<_, _>>()
});
hasher.update(
serde_json::to_vec(&(
command,
args,
env,
env_vars,
cwd,
&config.environment_id,
connection_identity.map(|(_, mode, _)| mode.preferred_protocol_version()),
client_elicitation_capability,
client_mcp_extensions.iter().collect::<BTreeMap<_, _>>(),
))
.ok()?,
);
for env_var in env_vars {
hasher.update(env_var.name().as_bytes());
let mut value_hasher = DefaultHasher::new();
std::env::var_os(env_var.name()).hash(&mut value_hasher);
hasher.update(value_hasher.finish().to_le_bytes());
}
Some(Self::Stdio {
fingerprint: hasher.finalize().into(),
})
}
}

View File

@@ -0,0 +1,70 @@
//! Host-provided metadata for a specific tool on a specific MCP registration.
use std::sync::Arc;
use crate::McpServerSource;
use crate::PreparedMcpCall;
use anyhow::Context;
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use codex_config::McpServerTransportConfig;
use codex_protocol::ThreadId;
use futures::future::BoxFuture;
use serde_json::Value;
/// Supplies one MCP request metadata value for a live tool invocation. An error
/// fails the tool call before dispatch and is reported to the tool caller.
pub trait McpToolRequestMetaProvider: Send + Sync {
fn value<'a>(
&'a self,
thread_id: ThreadId,
turn_id: &'a str,
call_id: &'a str,
) -> BoxFuture<'a, anyhow::Result<Value>>;
}
/// Install in thread extension data to add a private `_meta` field to one remote
/// tool on the selected local MCP registration. Bind the source and full transport
/// supplied by the trusted host, including routing headers for a proxied endpoint.
pub struct McpToolRequestMetaHook {
pub server_name: String,
pub source: McpServerSource,
pub transport: McpServerTransportConfig,
pub tool_name: String,
/// A metadata key owned by the provider. Existing metadata cannot be overwritten.
pub key: String,
pub provider: Arc<dyn McpToolRequestMetaProvider>,
}
impl McpToolRequestMetaHook {
/// Adds the provider’s value only when the immutable call matches the selected registration.
pub async fn apply(
&self,
call: &PreparedMcpCall,
thread_id: ThreadId,
turn_id: &str,
call_id: &str,
meta: &mut Option<Value>,
) -> anyhow::Result<()> {
if call.server_name() == self.server_name
&& call.tool_info().tool.name.as_ref() == self.tool_name
&& call.server_environment_id() == DEFAULT_MCP_SERVER_ENVIRONMENT_ID
&& let Some(server) = call.config().mcp_server_catalog.server(call.server_name())
&& server.config().is_local_environment()
&& server.source() == &self.source
&& server.config().transport == self.transport
{
let meta = meta
.as_mut()
.and_then(Value::as_object_mut)
.context("missing MCP request metadata object")?;
anyhow::ensure!(
!meta.contains_key(&self.key),
"MCP request metadata already contains {}",
self.key
);
let value = self.provider.value(thread_id, turn_id, call_id).await?;
meta.insert(self.key.clone(), value);
}
Ok(())
}
}

View File

@@ -0,0 +1,325 @@
//! MCP tool metadata, filtering, and name normalization.
//!
//! Raw MCP tool identities must be preserved for protocol calls, while
//! model-visible tool names must be sanitized, deduplicated, and kept within API
//! limits. This module owns that translation as well as the shared [`ToolInfo`]
//! type.
use std::collections::HashMap;
use std::collections::HashSet;
use codex_config::McpServerConfig;
use codex_protocol::ToolName;
use rmcp::model::Tool;
use serde::Deserialize;
use serde::Serialize;
use sha1::Digest;
use sha1::Sha1;
use tracing::warn;
use crate::mcp::sanitize_responses_api_tool_name;
const LEGACY_MCP_TOOL_NAME_PREFIX: &str = "mcp__";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolInfo {
/// Raw MCP server name used for routing the tool call.
pub server_name: String,
/// Whether calls routed to this server may run in parallel.
#[serde(default)]
pub supports_parallel_tool_calls: bool,
/// MCP server origin used for telemetry and diagnostics, when known.
#[serde(default)]
pub server_origin: Option<String>,
/// Model-visible tool name used in Responses API tool declarations.
#[serde(rename = "tool_name", alias = "callable_name")]
pub callable_name: String,
/// Model-visible namespace used for deferred tool loading.
#[serde(rename = "tool_namespace", alias = "callable_namespace")]
pub callable_namespace: String,
/// Model-visible namespace description.
// Keep the old serialized field name readable for cached ToolInfo values.
#[serde(default, alias = "connector_description")]
pub namespace_description: Option<String>,
/// Raw MCP tool definition; `tool.name` is sent back to the MCP server.
pub tool: Tool,
/// Optional provided-file fields accepted by each declared `openai/fileParams`
/// argument. This is derived from the raw MCP schema before file arguments are
/// masked as local paths for the model.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub openai_file_input_optional_fields: HashMap<String, Vec<String>>,
pub connector_id: Option<String>,
pub connector_name: Option<String>,
#[serde(default)]
pub plugin_display_names: Vec<String>,
}
impl ToolInfo {
/// The model-facing error when this advertised tool cannot be called.
pub fn unavailable_to_model_error(&self) -> anyhow::Error {
anyhow::anyhow!(
"MCP tool `{}/{}` is not available to the model",
self.server_name,
self.tool.name
)
}
pub fn canonical_tool_name(&self) -> ToolName {
ToolName::namespaced(self.callable_namespace.clone(), self.callable_name.clone())
}
}
/// A tool is allowed to be used if both are true:
/// 1. enabled is None (no allowlist is set) or the tool is explicitly enabled.
/// 2. The tool is not explicitly disabled.
#[derive(Default, Clone)]
pub(crate) struct ToolFilter {
pub(crate) enabled: Option<HashSet<String>>,
pub(crate) disabled: HashSet<String>,
}
impl ToolFilter {
pub(crate) fn from_config(cfg: &McpServerConfig) -> Self {
let enabled = cfg
.enabled_tools
.as_ref()
.map(|tools| tools.iter().cloned().collect::<HashSet<_>>());
let disabled = cfg
.disabled_tools
.as_ref()
.map(|tools| tools.iter().cloned().collect::<HashSet<_>>())
.unwrap_or_default();
Self { enabled, disabled }
}
pub(crate) fn allows(&self, tool_name: &str) -> bool {
if let Some(enabled) = &self.enabled
&& !enabled.contains(tool_name)
{
return false;
}
!self.disabled.contains(tool_name)
}
}
pub(crate) fn filter_tools(tools: Vec<ToolInfo>, filter: &ToolFilter) -> Vec<ToolInfo> {
tools
.into_iter()
.filter(|tool| filter.allows(&tool.tool.name))
.collect()
}
/// Returns MCP tools with model-visible names normalized.
///
/// Raw MCP server/tool names are kept on each [`ToolInfo`] for protocol calls, while
/// `callable_namespace` / `callable_name` are sanitized and, when necessary, hashed so
/// every model-visible name is unique and <= 128 bytes.
///
/// When `prefix_mcp_tool_names` is true, the historical `mcp__` namespace
/// prefix is added except for tools from `non_prefixed_mcp_tool_servers`.
pub(crate) fn normalize_tools_for_model_with_prefix<I>(
tools: I,
prefix_mcp_tool_names: bool,
non_prefixed_mcp_tool_servers: &[String],
) -> Vec<ToolInfo>
where
I: IntoIterator<Item = ToolInfo>,
{
let mut seen_raw_names = HashSet::new();
let mut candidates = Vec::new();
for tool in tools {
let raw_namespace_identity = format!(
"{}\0{}\0{}",
tool.server_name,
tool.callable_namespace,
tool.connector_id.as_deref().unwrap_or_default()
);
let raw_tool_identity = format!(
"{}\0{}\0{}",
raw_namespace_identity, tool.callable_name, tool.tool.name
);
if !seen_raw_names.insert(raw_tool_identity.clone()) {
warn!("skipping duplicated tool {}", tool.tool.name);
continue;
}
let callable_namespace = callable_namespace_with_prefix(
&sanitize_responses_api_tool_name(&tool.callable_namespace),
prefix_mcp_tool_names && !non_prefixed_mcp_tool_servers.contains(&tool.server_name),
);
candidates.push(CallableToolCandidate {
callable_namespace,
callable_name: sanitize_responses_api_tool_name(&tool.callable_name),
raw_namespace_identity,
raw_tool_identity,
tool,
});
}
let mut namespace_identities_by_base = HashMap::<String, HashSet<String>>::new();
for candidate in &candidates {
namespace_identities_by_base
.entry(candidate.callable_namespace.clone())
.or_default()
.insert(candidate.raw_namespace_identity.clone());
}
let colliding_namespaces = namespace_identities_by_base
.into_iter()
.filter_map(|(namespace, identities)| (identities.len() > 1).then_some(namespace))
.collect::<HashSet<_>>();
for candidate in &mut candidates {
if colliding_namespaces.contains(&candidate.callable_namespace) {
candidate.callable_namespace = append_namespace_hash_suffix(
&candidate.callable_namespace,
&candidate.raw_namespace_identity,
);
}
}
let mut tool_identities_by_base = HashMap::<(String, String), HashSet<String>>::new();
for candidate in &candidates {
tool_identities_by_base
.entry((
candidate.callable_namespace.clone(),
candidate.callable_name.clone(),
))
.or_default()
.insert(candidate.raw_tool_identity.clone());
}
let colliding_tools = tool_identities_by_base
.into_iter()
.filter_map(|(key, identities)| (identities.len() > 1).then_some(key))
.collect::<HashSet<_>>();
for candidate in &mut candidates {
if colliding_tools.contains(&(
candidate.callable_namespace.clone(),
candidate.callable_name.clone(),
)) {
candidate.callable_name =
append_hash_suffix(&candidate.callable_name, &candidate.raw_tool_identity);
}
}
candidates.sort_by(|left, right| left.raw_tool_identity.cmp(&right.raw_tool_identity));
let mut used_names = HashSet::new();
let mut model_tools = Vec::new();
for mut candidate in candidates {
let (callable_namespace, callable_name) = unique_callable_parts(
&candidate.callable_namespace,
&candidate.callable_name,
&candidate.raw_tool_identity,
&mut used_names,
MCP_TOOL_NAME_DELIMITER.len(),
);
candidate.tool.callable_namespace = callable_namespace;
candidate.tool.callable_name = callable_name;
model_tools.push(candidate.tool);
}
model_tools
}
#[derive(Debug)]
struct CallableToolCandidate {
tool: ToolInfo,
raw_namespace_identity: String,
raw_tool_identity: String,
callable_namespace: String,
callable_name: String,
}
const MCP_TOOL_NAME_DELIMITER: &str = "__";
const MAX_TOOL_NAME_LENGTH: usize = 128;
const CALLABLE_NAME_HASH_LEN: usize = 12;
fn callable_namespace_with_prefix(namespace: &str, prefix_mcp_tool_names: bool) -> String {
if !prefix_mcp_tool_names || namespace.starts_with(LEGACY_MCP_TOOL_NAME_PREFIX) {
namespace.to_string()
} else {
format!("{LEGACY_MCP_TOOL_NAME_PREFIX}{namespace}")
}
}
fn sha1_hex(s: &str) -> String {
let mut hasher = Sha1::new();
hasher.update(s.as_bytes());
let sha1 = hasher.finalize();
format!("{sha1:x}")
}
fn callable_name_hash_suffix(raw_identity: &str) -> String {
let hash = sha1_hex(raw_identity);
format!("_{}", &hash[..CALLABLE_NAME_HASH_LEN])
}
fn append_hash_suffix(value: &str, raw_identity: &str) -> String {
format!("{value}{}", callable_name_hash_suffix(raw_identity))
}
fn append_namespace_hash_suffix(namespace: &str, raw_identity: &str) -> String {
if let Some(namespace) = namespace.strip_suffix(MCP_TOOL_NAME_DELIMITER) {
format!(
"{}{}{}",
namespace,
callable_name_hash_suffix(raw_identity),
MCP_TOOL_NAME_DELIMITER
)
} else {
append_hash_suffix(namespace, raw_identity)
}
}
fn truncate_name(value: &str, max_len: usize) -> String {
value.chars().take(max_len).collect()
}
fn fit_callable_parts_with_hash(
namespace: &str,
tool_name: &str,
raw_identity: &str,
reserved_len: usize,
) -> (String, String) {
let suffix = callable_name_hash_suffix(raw_identity);
let max_tool_len = MAX_TOOL_NAME_LENGTH.saturating_sub(namespace.len() + reserved_len);
if max_tool_len >= suffix.len() {
let prefix_len = max_tool_len - suffix.len();
return (
namespace.to_string(),
format!("{}{}", truncate_name(tool_name, prefix_len), suffix),
);
}
let max_namespace_len = MAX_TOOL_NAME_LENGTH.saturating_sub(suffix.len() + reserved_len);
(truncate_name(namespace, max_namespace_len), suffix)
}
fn unique_callable_parts(
namespace: &str,
tool_name: &str,
raw_identity: &str,
used_names: &mut HashSet<String>,
reserved_len: usize,
) -> (String, String) {
let model_name = format!("{namespace}{tool_name}");
if model_name.len() + reserved_len <= MAX_TOOL_NAME_LENGTH && used_names.insert(model_name) {
return (namespace.to_string(), tool_name.to_string());
}
let mut attempt = 0_u32;
loop {
let hash_input = if attempt == 0 {
raw_identity.to_string()
} else {
format!("{raw_identity}\0{attempt}")
};
let (namespace, tool_name) =
fit_callable_parts_with_hash(namespace, tool_name, &hash_input, reserved_len);
let model_name = format!("{namespace}{tool_name}");
if used_names.insert(model_name) {
return (namespace, tool_name);
}
attempt = attempt.saturating_add(1);
}
}

View File

@@ -0,0 +1,330 @@
use std::sync::Arc;
use std::time::Duration;
use crate::connection_manager::McpConnectionSet;
use crate::runtime::McpRuntimeInput;
use crate::server::McpServerMetadata;
use crate::server::McpServerOrigin;
use crate::tools::ToolInfo;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpHeader;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_protocol::auth::AuthMode;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Map;
use serde_json::Value;
use serde_json::json;
pub(crate) const ENTITLEMENT_CONTEXT_KEY: &str = "openai/entitlementContext";
const MAX_VERIFIED_ACCESS_RESPONSE_BYTES: usize = 1024 * 1024;
const REQUESTED_ENTITLEMENTS_KEY: &str = "openai/requestedEntitlements";
const CYBER_TRUSTED_ACCESS_ENTITLEMENT: &str = "cyber_trusted_access";
const TRUSTED_ACCESS_TIMEOUT: Duration = Duration::from_millis(2_500);
impl McpConnectionSet {
/// Installed and task-selected plugins may request supported advisory entitlement metadata.
/// Model calls use the local, read-only, zero-argument boundary.
pub(crate) async fn add_trusted_access_context(
&self,
tool: &ToolInfo,
server: &McpServerMetadata,
arguments: Option<&Value>,
meta: Option<Value>,
) -> Option<Value> {
if tool
.tool
.meta
.as_deref()
.and_then(|meta| meta.get(REQUESTED_ENTITLEMENTS_KEY))
.and_then(Value::as_array)
.is_some_and(|entitlements| {
entitlements.iter().all(Value::is_string)
&& entitlements.iter().any(|entitlement| {
entitlement.as_str() == Some(CYBER_TRUSTED_ACCESS_ENTITLEMENT)
})
})
&& self
.plugin_id_for_mcp_server_name(&tool.server_name)
.is_some()
&& arguments.is_none_or(|arguments| arguments.as_object().is_some_and(Map::is_empty))
&& server.environment_id == codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID
&& matches!(server.origin, Some(McpServerOrigin::Stdio))
&& tool
.tool
.annotations
.as_ref()
.and_then(|annotations| annotations.read_only_hint)
== Some(true)
&& let Some(context) = self.trusted_access.as_ref()
{
context.add_context(meta).await
} else {
meta
}
}
}
#[derive(Deserialize)]
struct VerifiedAccessResponse {
programs: Vec<Value>,
}
#[derive(Deserialize)]
struct VerifiedAccessProgram {
state: VerifiedAccessState,
grants: Vec<VerifiedAccessGrant>,
}
#[derive(Clone, Copy, Deserialize)]
#[serde(rename_all = "snake_case")]
enum VerifiedAccessState {
Active,
Inactive,
Unavailable,
}
#[derive(Deserialize)]
struct VerifiedAccessGrant {
level: TrustedAccessLevel,
source: VerifiedAccessSource,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
enum TrustedAccessLevel {
Tac1,
Tac2,
Tac3,
Government,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum VerifiedAccessSource {
Individual,
Organization,
}
/// Fetches account-bound verified access for trusted, host-owned MCP metadata.
/// Callers must authorize the receiving plugin and tool before attaching it.
pub struct TrustedAccessContext {
auth: CodexAuth,
auth_manager: Arc<AuthManager>,
chatgpt_base_url: String,
http_client: Arc<dyn HttpClient>,
runtime_auth: Option<(crate::auth::McpAuthProvider, crate::McpRuntimeContext)>,
}
impl TrustedAccessContext {
pub(crate) fn from_runtime(input: &McpRuntimeInput) -> Option<Self> {
let auth = input.auth.as_ref()?;
if !matches!(
auth.api_auth_mode(),
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens
) {
return None;
}
let mut context = Self::new(
auth.clone(),
input.auth_manager.clone()?,
input.config.chatgpt_base_url.clone(),
input.runtime_context.local_http_client(),
);
context.runtime_auth = input
.runtime_auth
.as_ref()
.filter(|_| {
codex_http_client::classify_openai_api_url(&input.config.chatgpt_base_url)
!= codex_http_client::OpenAiDestination::Other
})
.map(|runtime| {
(
crate::auth::McpAuthProvider::runtime(runtime.clone(), auth.clone()),
input.runtime_context.clone(),
)
});
Some(context)
}
pub fn new(
auth: CodexAuth,
auth_manager: Arc<AuthManager>,
chatgpt_base_url: String,
http_client: Arc<dyn HttpClient>,
) -> Self {
Self {
auth,
auth_manager,
chatgpt_base_url,
http_client,
runtime_auth: None,
}
}
/// Replaces caller-supplied entitlement metadata with a fresh verified result.
pub async fn add_context(&self, meta: Option<Value>) -> Option<Value> {
let mut meta = match meta {
Some(Value::Object(meta)) => meta,
None => Map::new(),
other => return other,
};
meta.remove(ENTITLEMENT_CONTEXT_KEY);
let status = tokio::time::timeout(TRUSTED_ACCESS_TIMEOUT, self.fetch_status())
.await
.ok()
.flatten()
.unwrap_or_else(|| {
json!({
"schemaVersion": 1,
"status": "unknown",
"grants": [],
"stale": false
})
});
meta.insert(
ENTITLEMENT_CONTEXT_KEY.to_string(),
json!({
"schemaVersion": 1,
"entitlements": { "cyber_trusted_access": status }
}),
);
Some(Value::Object(meta))
}
async fn fetch_status(&self) -> Option<Value> {
let auth = self.auth_manager.auth().await?;
let expected_account_id = self
.auth
.get_account_id()
.filter(|account_id| !account_id.trim().is_empty())?;
let account_id = auth
.get_account_id()
.filter(|account_id| !account_id.trim().is_empty())?;
if !matches!(
self.auth.api_auth_mode(),
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens
) || !matches!(
auth.api_auth_mode(),
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens
) || account_id != expected_account_id
|| auth.get_chatgpt_user_id() != self.auth.get_chatgpt_user_id()
|| auth.is_workspace_account() != self.auth.is_workspace_account()
|| auth.is_fedramp_account() != self.auth.is_fedramp_account()
{
return None;
}
let (provider, http_client) = match &self.runtime_auth {
Some((resolver, context)) => {
let (resolver, context) = resolver
.resolve(context.clone(), &self.chatgpt_base_url)
.await
.ok()?;
(
resolver.resolve(&Default::default()).await.ok()?,
context.local_http_client(),
)
}
None => (
codex_model_provider::auth_provider_from_auth(&auth),
Arc::clone(&self.http_client),
),
};
let headers = provider
.apply_auth_headers(Default::default())
.await
.ok()?
.iter()
.map(|(name, value)| {
Some(HttpHeader {
name: name.as_str().to_string(),
value: value.to_str().ok()?.to_string(),
value_env_var: None,
})
})
.collect::<Option<Vec<_>>>()?;
let (response, mut response_body) = http_client
.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: format!(
"{}/accounts/verified_access",
self.chatgpt_base_url.trim_end_matches('/')
),
headers,
body: None,
timeout_ms: Some(TRUSTED_ACCESS_TIMEOUT.as_millis() as u64),
redirect_policy: HttpRedirectPolicy::Stop,
request_id: "trusted-access-status".to_string(),
stream_response: true,
})
.await
.ok()?;
if response.status != 200 {
return None;
}
let mut response_bytes = Vec::new();
while let Some(chunk) = response_body.recv().await.ok()? {
if chunk.len() > MAX_VERIFIED_ACCESS_RESPONSE_BYTES - response_bytes.len() {
return None;
}
response_bytes.extend_from_slice(&chunk);
}
let response: VerifiedAccessResponse = serde_json::from_slice(&response_bytes).ok()?;
let mut programs = response
.programs
.into_iter()
.filter(|program| program.get("program").and_then(Value::as_str) == Some("cyber"));
let program = programs.next()?;
if programs.next().is_some() {
return None;
}
let program: VerifiedAccessProgram = serde_json::from_value(program).ok()?;
if self.auth_manager.auth_cached().is_none_or(|current| {
!matches!(
current.api_auth_mode(),
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens
) || current.get_account_id().as_deref() != Some(account_id.as_str())
|| current.get_chatgpt_user_id() != auth.get_chatgpt_user_id()
|| current.is_workspace_account() != auth.is_workspace_account()
|| current.is_fedramp_account() != auth.is_fedramp_account()
}) {
return None;
}
let status = match program.state {
VerifiedAccessState::Active if !program.grants.is_empty() => "granted",
VerifiedAccessState::Inactive if program.grants.is_empty() => "not_granted",
VerifiedAccessState::Unavailable if program.grants.is_empty() => "unknown",
VerifiedAccessState::Active
| VerifiedAccessState::Inactive
| VerifiedAccessState::Unavailable => return None,
};
let grants = program
.grants
.into_iter()
.map(|grant| {
let source = match grant.source {
VerifiedAccessSource::Individual => "user",
VerifiedAccessSource::Organization => "current_account",
};
json!({ "level": grant.level, "source": source })
})
.collect::<Vec<_>>();
Some(json!({
"schemaVersion": 1,
"status": status,
"grants": grants,
"stale": false
}))
}
}
#[cfg(test)]
#[path = "trusted_access_tests.rs"]
mod tests;

View File

@@ -0,0 +1,658 @@
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use codex_exec_server::ByteChunk;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpHeader;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthHeaders;
use codex_login::AuthKeyringBackendKind;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::ExternalAuth;
use codex_login::ExternalAuthFuture;
use codex_login::ExternalAuthRefreshContext;
use futures::FutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tokio::sync::Notify;
use super::MAX_VERIFIED_ACCESS_RESPONSE_BYTES;
use super::TrustedAccessContext;
struct RecordingHttpClient {
requests: Mutex<Vec<HttpRequestParams>>,
status: u16,
response: Vec<u8>,
response_chunks: Option<Vec<Vec<u8>>>,
response_gate: Option<(Notify, Notify)>,
}
impl RecordingHttpClient {
fn new(status: u16, response: Value) -> Self {
Self {
requests: Mutex::new(Vec::new()),
status,
response: serde_json::to_vec(&response).expect("serialize response"),
response_chunks: None,
response_gate: None,
}
}
}
impl HttpClient for RecordingHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.requests.lock().expect("record request").push(params);
let response = HttpRequestResponse {
status: self.status,
headers: Vec::new(),
body: ByteChunk::from(self.response.clone()),
};
async move {
if let Some((requested, release)) = &self.response_gate {
requested.notify_one();
release.notified().await;
}
Ok(response)
}
.boxed()
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.requests.lock().expect("record request").push(params);
let response = HttpRequestResponse {
status: self.status,
headers: Vec::new(),
body: ByteChunk::from(Vec::new()),
};
let chunks = self
.response_chunks
.clone()
.unwrap_or_else(|| vec![self.response.clone()]);
async move {
if let Some((requested, release)) = &self.response_gate {
requested.notify_one();
release.notified().await;
}
Ok((response, HttpResponseBodyStream::from_chunks(chunks)))
}
.boxed()
}
}
struct StaticExternalAuth(CodexAuth);
impl ExternalAuth for StaticExternalAuth {
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async { Ok(self.0.clone()) })
}
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
self.resolve()
}
}
struct SequencedExternalAuth(Mutex<VecDeque<CodexAuth>>);
impl ExternalAuth for SequencedExternalAuth {
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async {
let mut sequence = self.0.lock().expect("auth sequence");
Ok(if sequence.len() > 1 {
sequence.pop_front().expect("next auth")
} else {
sequence.front().expect("last auth").clone()
})
})
}
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
self.resolve()
}
}
fn header_auth() -> CodexAuth {
CodexAuth::Headers(AuthHeaders::new(
[
(
"authorization".parse().unwrap(),
"Bearer synthetic-pat".parse().unwrap(),
),
(
"chatgpt-account-id".parse().unwrap(),
"account-a".parse().unwrap(),
),
]
.into_iter()
.collect(),
))
}
fn chatgpt_auth(account_id: &str) -> CodexAuth {
CodexAuth::from_external_chatgpt_tokens(
"header.e30.same",
account_id,
/*chatgpt_plan_type*/ None,
)
.expect("test auth")
}
fn fedramp_chatgpt_auth(account_id: &str) -> CodexAuth {
CodexAuth::from_external_chatgpt_tokens(
"header.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9hY2NvdW50X2lzX2ZlZHJhbXAiOnRydWV9fQ.same",
account_id,
/*chatgpt_plan_type*/ None,
)
.expect("FedRAMP test auth")
}
fn context(auth: CodexAuth, client: Arc<RecordingHttpClient>) -> TrustedAccessContext {
TrustedAccessContext::new(
auth.clone(),
AuthManager::from_auth_for_testing(auth),
"https://chatgpt.com/backend-api".to_string(),
client,
)
}
fn cyber_response(state: &str, grants: Value) -> Value {
json!({ "programs": [{ "program": "cyber", "state": state, "grants": grants }] })
}
fn expected_metadata(status: &str, grants: Value) -> Value {
json!({ "openai/entitlementContext": {
"schemaVersion": 1,
"entitlements": { "cyber_trusted_access": {
"schemaVersion": 1,
"status": status,
"grants": grants,
"stale": false
} }
} })
}
#[tokio::test]
async fn delivers_account_bound_verified_access_to_the_calling_plugin() {
let client = Arc::new(RecordingHttpClient::new(
/*status*/ 200,
cyber_response(
"active",
json!([
{ "level": "tac2", "source": "individual" },
{ "level": "government", "source": "organization" }
]),
),
));
let mut context = context(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
client.clone(),
);
context.chatgpt_base_url.push('/');
let metadata = context
.add_context(Some(json!({ "threadId": "thread-1" })))
.await;
let mut expected = expected_metadata(
"granted",
json!([
{ "level": "tac2", "source": "user" },
{ "level": "government", "source": "current_account" }
]),
);
expected["threadId"] = json!("thread-1");
assert_eq!(metadata, Some(expected));
let mut requests = client.requests.lock().expect("inspect recorded requests");
for request in requests.iter_mut() {
request
.headers
.sort_by(|left, right| left.name.cmp(&right.name));
}
assert_eq!(
*requests,
vec![HttpRequestParams {
method: "GET".to_string(),
url: "https://chatgpt.com/backend-api/accounts/verified_access".to_string(),
headers: vec![
HttpHeader {
name: "authorization".to_string(),
value: "Bearer Access Token".to_string(),
value_env_var: None,
},
HttpHeader {
name: "chatgpt-account-id".to_string(),
value: "account_id".to_string(),
value_env_var: None,
},
],
body: None,
timeout_ms: Some(2_500),
redirect_policy: HttpRedirectPolicy::Stop,
request_id: "trusted-access-status".to_string(),
stream_response: true,
}]
);
}
#[tokio::test]
async fn rejects_auth_without_a_nonempty_account_id() -> anyhow::Result<()> {
for account_id in [None, Some(""), Some(" ")] {
let home = tempfile::tempdir()?;
std::fs::write(
home.path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"tokens": {
"id_token": "header.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lkIjoidXNlci1hIn19.signature",
"access_token": "synthetic-access-token",
"refresh_token": "synthetic-refresh-token",
"account_id": account_id
},
"last_refresh": "2099-01-01T00:00:00Z"
}))?,
)?;
let auth = CodexAuth::from_auth_storage(
home.path(),
AuthCredentialsStoreMode::File,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::default(),
&codex_login::test_support::transport_default_auth_route_config(),
)
.await?
.expect("managed ChatGPT auth");
let client = Arc::new(RecordingHttpClient::new(
/*status*/ 200,
cyber_response(
"active",
json!([{ "level": "tac1", "source": "individual" }]),
),
));
assert_eq!(
context(auth, client.clone())
.add_context(/*meta*/ None)
.await,
Some(expected_metadata("unknown", json!([]))),
"account_id={account_id:?}"
);
assert!(client.requests.lock().expect("inspect requests").is_empty());
}
Ok(())
}
#[tokio::test]
async fn rejects_api_key_authentication_without_sending_credentials() {
let client = Arc::new(RecordingHttpClient::new(
/*status*/ 200,
json!({ "programs": [] }),
));
let context = context(CodexAuth::from_api_key("test-api-key"), client.clone());
let metadata = context
.add_context(Some(json!({
"threadId": "thread-1",
"openai/entitlementContext": { "forged": true }
})))
.await;
let mut expected = expected_metadata("unknown", json!([]));
expected["threadId"] = json!("thread-1");
assert_eq!(metadata, Some(expected));
assert!(client.requests.lock().expect("inspect requests").is_empty());
}
#[tokio::test]
async fn rejects_initial_unsupported_auth_after_switch_to_chatgpt() {
let client = Arc::new(RecordingHttpClient::new(
/*status*/ 200,
cyber_response(
"active",
json!([{ "level": "tac1", "source": "individual" }]),
),
));
let mut context = context(header_auth(), client.clone());
context.auth_manager = AuthManager::from_auth_for_testing(chatgpt_auth("account-a"));
assert_eq!(
context.add_context(/*meta*/ None).await,
Some(expected_metadata("unknown", json!([])))
);
assert!(client.requests.lock().expect("inspect requests").is_empty());
}
#[tokio::test]
async fn maps_verified_access_states_and_rejects_invalid_provider_responses() {
let cases = [
(
200,
json!({ "programs": [
{ "program": "future", "state": "pending", "grants": [{ "level": "premium", "source": "subscription" }] },
{ "program": "cyber", "state": "active", "grants": [{ "level": "tac1", "source": "individual" }] }
] }),
expected_metadata("granted", json!([{ "level": "tac1", "source": "user" }])),
),
(
200,
cyber_response("inactive", json!([])),
expected_metadata("not_granted", json!([])),
),
(
200,
cyber_response("unavailable", json!([])),
expected_metadata("unknown", json!([])),
),
(
200,
json!({ "programs": [{ "program": "other", "state": "active", "grants": [] }] }),
expected_metadata("unknown", json!([])),
),
(
200,
cyber_response(
"active",
json!([{ "level": "admin", "source": "individual" }]),
),
expected_metadata("unknown", json!([])),
),
(
200,
cyber_response("active", json!([])),
expected_metadata("unknown", json!([])),
),
(
403,
json!({ "error": "forbidden" }),
expected_metadata("unknown", json!([])),
),
];
for (response_status, response, expected) in cases {
let response_description = response.to_string();
let context = context(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
Arc::new(RecordingHttpClient::new(response_status, response)),
);
let metadata = context.add_context(/*meta*/ None).await.expect("metadata");
assert_eq!(
metadata, expected,
"HTTP {response_status}: {response_description}"
);
}
}
#[tokio::test]
async fn replaces_untrusted_entitlements_on_malformed_response() {
let mut client = RecordingHttpClient::new(/*status*/ 200, Value::Null);
client.response = b"{\"programs\":[".to_vec();
let context = context(chatgpt_auth("account-a"), Arc::new(client));
let mut expected = expected_metadata("unknown", json!([]));
expected["threadId"] = json!("thread-1");
assert_eq!(
context
.add_context(Some(json!({
"threadId": "thread-1",
"openai/entitlementContext": { "forged": true }
})))
.await,
Some(expected)
);
}
#[tokio::test]
async fn rejects_verified_access_response_larger_than_one_mebibyte() {
let valid_response = serde_json::to_vec(&cyber_response(
"active",
json!([{ "level": "tac1", "source": "individual" }]),
))
.expect("serialize response");
let mut client = RecordingHttpClient::new(/*status*/ 200, Value::Null);
client.response_chunks = Some(vec![
vec![b' '; MAX_VERIFIED_ACCESS_RESPONSE_BYTES],
valid_response,
]);
client.response = client
.response_chunks
.as_ref()
.expect("response chunks")
.concat();
assert_eq!(
context(chatgpt_auth("account-a"), Arc::new(client))
.add_context(/*meta*/ None)
.await,
Some(expected_metadata("unknown", json!([])))
);
}
#[tokio::test(start_paused = true)]
async fn returns_unknown_at_the_lookup_deadline() {
let mut client = RecordingHttpClient::new(/*status*/ 200, Value::Null);
client.response_gate = Some((Notify::new(), Notify::new()));
let client = Arc::new(client);
let context = context(chatgpt_auth("account-a"), client.clone());
let lookup = context.add_context(/*meta*/ None);
tokio::pin!(lookup);
assert!(futures::poll!(lookup.as_mut()).is_pending());
assert_eq!(client.requests.lock().expect("recorded requests").len(), 1);
tokio::time::advance(Duration::from_millis(2_499)).await;
assert!(futures::poll!(lookup.as_mut()).is_pending());
tokio::time::advance(Duration::from_millis(1)).await;
assert_eq!(
lookup
.now_or_never()
.expect("lookup must finish at the deadline"),
Some(expected_metadata("unknown", json!([])))
);
}
#[tokio::test]
async fn rejects_duplicate_cyber_programs() {
let active = json!({
"program": "cyber", "state": "active",
"grants": [{ "level": "tac1", "source": "individual" }]
});
for other in [
active.clone(),
json!({ "program": "cyber", "state": "inactive", "grants": [] }),
json!({ "program": "cyber" }),
] {
for programs in [json!([active, other]), json!([other, active])] {
let context = context(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
Arc::new(RecordingHttpClient::new(
/*status*/ 200,
json!({ "programs": programs }),
)),
);
assert_eq!(
context.add_context(/*meta*/ None).await,
Some(expected_metadata("unknown", json!([]))),
"duplicate programs: {programs}"
);
}
}
}
#[tokio::test]
async fn rejects_identity_changes_before_sending_credentials() {
for (description, initial_auth, selected_auth) in [
(
"account switch",
chatgpt_auth("account-a"),
chatgpt_auth("account-b"),
),
(
"standard to FedRAMP",
chatgpt_auth("account-a"),
fedramp_chatgpt_auth("account-a"),
),
(
"FedRAMP to standard",
fedramp_chatgpt_auth("account-a"),
chatgpt_auth("account-a"),
),
] {
let client = Arc::new(RecordingHttpClient::new(
/*status*/ 200,
cyber_response(
"active",
json!([{ "level": "tac1", "source": "individual" }]),
),
));
let mut context = context(initial_auth, client.clone());
context.auth_manager = AuthManager::from_auth_for_testing(selected_auth);
assert_eq!(
context.add_context(/*meta*/ None).await,
Some(expected_metadata("unknown", json!([]))),
"identity change before the request: {description}"
);
assert!(
client.requests.lock().expect("inspect requests").is_empty(),
"identity change before the request: {description}"
);
}
}
#[tokio::test]
async fn uses_the_checked_auth_snapshot_for_request_headers() -> anyhow::Result<()> {
let client = Arc::new(RecordingHttpClient::new(
/*status*/ 200,
cyber_response("inactive", json!([])),
));
let context = context(chatgpt_auth("account-a"), client.clone());
let refreshed = CodexAuth::from_external_chatgpt_tokens(
"header.e30.refreshed",
"account-a",
/*chatgpt_plan_type*/ None,
)?;
context
.auth_manager
.set_external_auth(Arc::new(SequencedExternalAuth(Mutex::new(VecDeque::from(
[context.auth.clone(), refreshed, header_auth()],
)))))
.await?;
assert_eq!(
context.add_context(/*meta*/ None).await,
Some(expected_metadata("not_granted", json!([])))
);
let requests = client.requests.lock().expect("recorded requests");
assert_eq!(requests.len(), 1);
let authorization = requests[0]
.headers
.iter()
.find(|header| header.name == "authorization");
assert_eq!(
authorization,
Some(&HttpHeader {
name: "authorization".to_string(),
value: "Bearer header.e30.refreshed".to_string(),
value_env_var: None,
})
);
Ok(())
}
#[tokio::test]
async fn rejects_identity_changes_while_request_is_in_flight() -> anyhow::Result<()> {
let personal = chatgpt_auth("account-a");
let workspace =
CodexAuth::from_external_chatgpt_tokens("header.e30.same", "account-a", Some("team"))?;
for (description, initial_auth, selected_auth) in [
(
"account switch",
personal.clone(),
Some(chatgpt_auth("account-b")),
),
("logout", personal.clone(), None),
(
"personal to workspace",
personal.clone(),
Some(workspace.clone()),
),
("workspace to personal", workspace, Some(personal)),
(
"auth mode change",
chatgpt_auth("account-a"),
Some(header_auth()),
),
(
"standard to FedRAMP",
chatgpt_auth("account-a"),
Some(fedramp_chatgpt_auth("account-a")),
),
(
"FedRAMP to standard",
fedramp_chatgpt_auth("account-a"),
Some(chatgpt_auth("account-a")),
),
] {
let mut client = RecordingHttpClient::new(
/*status*/ 200,
cyber_response(
"active",
json!([{ "level": "tac1", "source": "individual" }]),
),
);
client.response_gate = Some((Notify::new(), Notify::new()));
let client = Arc::new(client);
let request_is_fedramp = initial_auth.is_fedramp_account();
let context = context(initial_auth, client.clone());
let auth_manager = &context.auth_manager;
auth_manager
.set_external_auth(Arc::new(StaticExternalAuth(context.auth.clone())))
.await?;
let (metadata, auth_change) = tokio::join!(context.add_context(/*meta*/ None), async {
let (requested, release) = client.response_gate.as_ref().expect("gated response");
tokio::time::timeout(Duration::from_secs(5), requested.notified()).await?;
{
let requests = client.requests.lock().expect("inspect request");
assert_eq!(requests.len(), 1);
assert!(requests[0].headers.iter().any(|header| {
header.name.eq_ignore_ascii_case("chatgpt-account-id")
&& header.value == "account-a"
}));
assert_eq!(
requests[0]
.headers
.iter()
.any(|header| header.name.eq_ignore_ascii_case("x-openai-fedramp")),
request_is_fedramp
);
}
if let Some(auth) = selected_auth {
auth_manager
.set_external_auth(Arc::new(StaticExternalAuth(auth)))
.await?;
} else {
auth_manager.clear_external_auth();
}
release.notify_one();
Ok::<(), anyhow::Error>(())
});
auth_change?;
assert_eq!(
metadata,
Some(expected_metadata("unknown", json!([]))),
"auth change after the request: {description}"
);
}
Ok(())
}

View File

@@ -0,0 +1,36 @@
//! Routes device verification directly to the app, outside automated approval policy.
use super::*;
pub(super) async fn route(
router: ElicitationRequestRouter,
events: Option<Sender<Event>>,
authority: Option<ElicitationAuthority>,
server_name: String,
request: ElicitationRequest,
) -> Result<ElicitationResponse> {
let plugin_service = authority.as_ref().is_some_and(|authority| {
authority
.config
.mcp_server_catalog
.server(&server_name)
.is_some_and(|server| {
server
.source()
.is_host_owned_apps(&server_name, server.config())
})
});
let Some((events, authority)) = events
.zip(authority)
.filter(|_| plugin_service && !router.auto_deny())
else {
return Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: Some(codex_rmcp_client::UserVerificationReason::ApprovalUnavailable.into_meta()),
});
};
router
.request_user_interaction(Some(events), &authority, server_name, request)
.await
}