aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT

- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser,
  device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity,
  runtime agent instance, backend-client e openapi-models, workspace routing.
- Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin
  remoti (catalogo, sync, share), cyber access program, daybreak, cloud config
  e requirements (config_server ora fail-closed), attestation, frozen cloud
  skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/
  routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime.
- Messaggi d'errore senza link a chatgpt.com.
- Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed.
- Test: cancellati solo quelli del codice rimosso; test di sicurezza
  (sandbox estensioni, permessi, redazione, auth storage, requirements)
  adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents).
- Istruzioni di sistema invariate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:20:15 +01:00
parent 82347a58ed
commit 6089fbde91
1573 changed files with 10289 additions and 177679 deletions

View File

@@ -1,118 +0,0 @@
//! 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

@@ -1,435 +0,0 @@
//! 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

@@ -1,203 +0,0 @@
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

@@ -1,11 +1,5 @@
//! 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;
@@ -139,9 +133,6 @@ impl McpBinding {
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 {
@@ -156,9 +147,7 @@ impl McpBinding {
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)
})
.list_all_resource_templates(include_server)
.await
}
@@ -364,18 +353,6 @@ impl PreparedMcpCall {
&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
@@ -456,22 +433,6 @@ impl PreparedMcpCall {
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 =

View File

@@ -20,7 +20,6 @@ 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;
@@ -72,8 +71,6 @@ async fn test_step(
format!("{label} catalog"),
Arc::new(JsonObject::default()),
),
connector_id: None,
connector_name: None,
plugin_display_names: Vec::new(),
};
let client = Arc::new(
@@ -83,9 +80,7 @@ async fn test_step(
);
let tool_catalog = Arc::new(ClientToolCatalog::new(
vec![tool.clone()],
/*meta*/ None,
/*updates*/ None,
));
/*meta*/ None));
let managed_client = Arc::new(ManagedClient {
connection_sharing: Default::default(),
shared_elicitation: None,
@@ -104,7 +99,6 @@ async fn test_step(
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(),
@@ -352,13 +346,9 @@ async fn prepared_call_is_rejected_after_catalog_refresh() {
.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 mut changed_tools = step.step.tools().to_vec();
changed_tools[0].tool.description = Some("changed".into());
step.tool_catalog.replace_for_test(changed_tools).await;
let error = prepared
.call(
@@ -386,13 +376,9 @@ async fn stale_prepared_call_does_not_run_preparation() {
.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 mut changed_tools = step.step.tools().to_vec();
changed_tools[0].tool.description = Some("changed".into());
step.tool_catalog.replace_for_test(changed_tools).await;
let prepared_side_effect_ran = Arc::new(AtomicBool::new(false));
let marker = Arc::clone(&prepared_side_effect_ran);
@@ -407,51 +393,6 @@ async fn stale_prepared_call_does_not_run_preparation() {
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)]

View File

@@ -6,13 +6,11 @@ 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;
@@ -81,7 +79,6 @@ pub enum McpServerSource {
},
Extension {
id: String,
host_owned_apps: bool,
},
}
@@ -95,19 +92,6 @@ impl McpServerSource {
}
}
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.
@@ -236,10 +220,7 @@ impl McpServerRegistration {
) -> Self {
Self::new(
name,
McpServerSource::Extension {
id: id.into(),
host_owned_apps: false,
},
McpServerSource::Extension { id: id.into() },
config,
RegistrationPrecedence::Extension(contribution_order),
McpCredentialPolicy::HostFallbackAllowed,
@@ -252,25 +233,6 @@ impl McpServerRegistration {
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,
@@ -359,15 +321,9 @@ 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
@@ -395,10 +351,7 @@ impl McpCatalogBuilder {
) {
self.actions.push(CatalogAction::Remove {
name,
source: McpServerSource::Extension {
id: id.into(),
host_owned_apps: false,
},
source: McpServerSource::Extension { id: id.into() },
precedence: RegistrationPrecedence::Extension(contribution_order),
});
}
@@ -412,12 +365,8 @@ impl McpCatalogBuilder {
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)
{
// Existing managed denials are not attachment-owned.
if !registration.config.enabled {
continue;
}
@@ -475,14 +424,6 @@ impl McpCatalogBuilder {
}
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);
@@ -516,7 +457,6 @@ impl McpCatalogBuilder {
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 {
@@ -554,25 +494,18 @@ impl McpCatalogBuilder {
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)
{
// Retain a previous registration's requirements denial so a later
// replacement is still blocked.
if 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;
// Enterprise-managed authorization was removed. Never start these
// servers, but do not turn the denial into a persistent name veto.
registration.config.enabled = false;
}
Some((
name,
@@ -592,7 +525,6 @@ impl McpCatalogBuilder {
actions: self.actions,
disabled_server_names,
requirements_disabled_server_names,
ema_idp,
servers,
conflicts,
}
@@ -632,7 +564,6 @@ 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>,
}
@@ -647,7 +578,6 @@ impl ResolvedMcpCatalog {
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(),
}
}
@@ -662,12 +592,12 @@ impl ResolvedMcpCatalog {
.collect()
}
/// Returns whether both catalogs have the same winning servers, sources, and EMA policy.
/// Returns whether both catalogs have the same winning servers and sources.
pub fn has_same_servers(&self, other: &Self) -> bool {
self.servers == other.servers && self.ema_idp == other.ema_idp
self.servers == other.servers
}
/// Replaces the resolved server set while preserving known sources and EMA policy.
/// Replaces the resolved server set while preserving known sources.
///
/// # Panics
///
@@ -676,7 +606,6 @@ impl ResolvedMcpCatalog {
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 {

View File

@@ -6,7 +6,6 @@ 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;
@@ -14,7 +13,6 @@ 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;
@@ -80,10 +78,7 @@ fn compatibility_source(id: &str) -> McpServerSource {
}
fn extension_source(id: &str) -> McpServerSource {
McpServerSource::Extension {
id: id.to_string(),
host_owned_apps: false,
}
McpServerSource::Extension { id: id.to_string() }
}
fn register(source: McpServerSource) -> McpServerConflictAction {
@@ -223,101 +218,19 @@ fn plugin_host_root_is_retained_in_catalog_identity() {
}
#[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();
fn removed_ema_auth_servers_are_never_enabled() {
let mut config = server("https://resource.example/mcp");
config.auth = McpServerAuth::EmaAuth;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_config(
"enterprise".to_string(),
config,
));
let original = builder.build();
assert!(original.has_same_servers(&original.to_builder().build()));
assert!(!original.server("enterprise").unwrap().config().enabled);
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,
);
}
let materialized = original.with_materialized_servers(original.configured_servers());
assert!(!materialized.server("enterprise").unwrap().config().enabled);
}
#[test]
@@ -361,7 +274,6 @@ fn source_precedence_preserves_the_winning_registration() {
resolved.source(),
&McpServerSource::Extension {
id: "hosted".to_string(),
host_owned_apps: false,
}
);
assert_eq!(resolved.config(), &extension);
@@ -725,64 +637,48 @@ fn extension_protocol_mode_follows_the_winner_through_materialization() {
}
#[test]
fn environment_policy_exempts_only_explicitly_host_owned_apps() {
fn environment_policy_denies_extension_registrations_named_like_hosted_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()
);
}
let custom = server("https://custom.example/mcp");
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_config(
"codex_apps".to_string(),
custom.clone(),
));
let denied =
builder.build_with_environment_authority(|_| McpEnvironmentAuthority::Restricted(&policy));
let mut builder = denied.to_builder();
builder.register(McpServerRegistration::from_extension(
"codex_apps".to_string(),
"apps",
/*contribution_order*/ 0,
server("https://apps.example/mcp"),
));
let catalog =
builder.build_with_environment_authority(|_| McpEnvironmentAuthority::Restricted(&policy));
assert!(
!catalog
.server("codex_apps")
.expect("extension registration")
.config()
.enabled
);
let mut builder = catalog
.with_materialized_servers(catalog.configured_servers())
.to_builder();
builder.register(McpServerRegistration::from_extension(
"codex_apps".to_string(),
"custom",
/*contribution_order*/ 1,
custom,
));
assert_eq!(
builder.build().configured_servers(),
denied.configured_servers()
);
}
#[test]

View File

@@ -9,44 +9,23 @@ 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)
});
/// User verification required the hosted plugin service and network policy metadata was only
/// offered to trusted hosted origins; aKode never connects to either, so both are stripped for
/// every server. Server names and caller-supplied capabilities grant neither.
pub(crate) fn server_mcp_extensions(extensions: &ClientMcpExtensions) -> ClientMcpExtensions {
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
if 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()),
)
})),
}),
)
}

View File

@@ -63,13 +63,7 @@ fn normalizes_legacy_form_capability_into_extensions() {
}
#[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 codex_rmcp_client::McpProtocolMode;
let config = crate::mcp::test_http_mcp_server_config("https://example.com");
fn user_verification_and_network_policy_are_never_projected_to_servers() {
let extensions = ClientMcpExtensions::new([
(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
@@ -80,73 +74,13 @@ fn user_verification_is_projected_only_to_the_host_owned_plugin_service() {
json!({}),
),
]);
// Server names and registrations, including the formerly reserved `codex_apps` name, never
// grant user verification or network policy metadata.
assert_eq!(
server_mcp_extensions(
&extensions,
CODEX_APPS_MCP_SERVER_NAME,
/*server*/ None,
/*advertise_network_policy*/ true,
"https://chatgpt.com",
),
server_mcp_extensions(&extensions),
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

@@ -1,14 +1,10 @@
//! 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.
//! 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;
@@ -18,32 +14,17 @@ 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.
@@ -52,21 +33,8 @@ pub(crate) struct ClientToolCatalog {
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,
},
tools: Arc<[ToolInfo]>,
meta: Option<Arc<serde_json::Value>>,
}
#[derive(Clone)]
@@ -77,97 +45,32 @@ pub(crate) struct ToolCatalogSnapshot {
}
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,
tools: tools.into(),
meta,
}),
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;
let current = self.current.read().await;
let snapshot = ToolCatalogSnapshot {
revision: current.revision,
tools: Arc::clone(&current.tools),
meta: current.meta.clone(),
};
drop(current);
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()
}
@@ -212,10 +115,8 @@ impl ClientToolCatalog {
continue;
}
let (tools, meta) = tools?;
current.source = CatalogSource::Local {
tools: tools.into(),
meta,
};
current.tools = tools.into();
current.meta = meta;
current.revision += 1;
self.listed_notification_revision
.store(revision, Ordering::Release);
@@ -232,52 +133,16 @@ impl ClientToolCatalog {
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;
/// Installs a new catalog as a list-change refresh would.
#[cfg(test)]
pub(crate) async fn replace_for_test(&self, tools: Vec<ToolInfo>) {
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.tools = tools.into();
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"
)]
/// Reject stale calls before preparation. List-change notifications may publish while an
/// admitted call runs.
pub(crate) async fn run_with_snapshot<R, F, Fut>(
&self,
expected: &ToolCatalogSnapshot,
@@ -287,24 +152,13 @@ impl ClientToolCatalog {
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))
let current = self.read(|snapshot| snapshot).await;
if current.revision != expected.revision
&& !catalogs_match(&current.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)
Some(run().await)
}
}
@@ -325,7 +179,6 @@ fn catalogs_match(left: &[ToolInfo], right: &[ToolInfo]) -> bool {
(
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(),
)

View File

@@ -1,65 +0,0 @@
//! 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;
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

@@ -22,15 +22,12 @@ mod status;
#[path = "connection_manager/tool_catalog.rs"]
mod tool_catalog;
use startup::chatgpt_auth_provider_for_server;
use startup::emit_update;
use startup::mcp_init_error_display;
use startup::mcp_startup_failure_reason;
use startup::should_share_codex_apps_tools_cache;
pub(crate) use tool_catalog::BindingCatalogRevision;
pub use tool_catalog::tool_is_model_visible;
use codex_config::McpServerAuth;
use std::cell::LazyCell;
use std::collections::HashMap;
use std::sync::Arc;
@@ -45,17 +42,13 @@ use crate::connection_pool::ConnectionKey;
use crate::connection_pool::ConnectionSharing;
use crate::elicitation::ElicitationRequestManager;
use crate::elicitation::ElicitationRequestRouter;
use crate::event_stream::EventStreamConnectionSettings;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::mcp::ToolPluginContext;
use crate::pagination::MAX_CODEX_APPS_TOOL_CATALOG_ITEMS;
use crate::pagination::MAX_MCP_CATALOG_ITEMS;
use crate::rmcp_client::AsyncManagedClient;
use crate::rmcp_client::DEFAULT_STARTUP_TIMEOUT;
use crate::rmcp_client::DEFAULT_TOOL_TIMEOUT;
use crate::rmcp_client::ManagedClient;
use crate::rmcp_client::StartupOutcomeError;
use crate::rmcp_client::prepare_codex_apps_tools_for_model;
use crate::rmcp_client::prepare_regular_mcp_tools_for_model;
use crate::runtime::McpPublicationGate;
use crate::runtime::McpRuntimeInput;
@@ -65,8 +58,6 @@ use crate::server::McpServerMetadata;
use crate::tools::ToolFilter;
use crate::tools::ToolInfo;
use crate::tools::filter_tools;
use crate::trusted_access::ENTITLEMENT_CONTEXT_KEY;
use crate::trusted_access::TrustedAccessContext;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
@@ -77,8 +68,6 @@ use codex_diagnostics::Gauge;
use codex_diagnostics::GaugeGuard;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::mcp::ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID;
use codex_protocol::mcp::McpServerInfo;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
@@ -94,6 +83,9 @@ use tokio::sync::watch;
use tokio::task::JoinSet;
use tracing::warn;
/// Host-owned entitlement metadata that direct callers may never supply.
const ENTITLEMENT_CONTEXT_KEY: &str = "openai/entitlementContext";
static LIVE_CONNECTIONS: Gauge = Gauge::new("mcp.connections.live");
pub(crate) struct McpServerConnection {
@@ -103,9 +95,6 @@ pub(crate) struct McpServerConnection {
// Startup-only budget; changing it must not replace a ready connection.
startup_timeout: Duration,
startup_trigger: Option<watch::Sender<bool>>,
// Only the initial host-owned Apps attempt publishes here. A retry uses normal readiness.
initialized_apps:
Option<watch::Receiver<Option<std::sync::Weak<codex_rmcp_client::RmcpClient>>>>,
_diagnostics_guard: GaugeGuard,
}
@@ -203,18 +192,7 @@ impl McpServerConnection {
}
async fn client_for_call(&self) -> Result<ManagedClient, StartupOutcomeError> {
let result = self.client().await;
if matches!(result, Err(StartupOutcomeError::Failed { .. }))
&& !self.client.cancel_token.is_cancelled()
&& let Some(reconnect) = &self.client.startup_reconnect
{
if let Some(attempt) = reconnect.reconnect_in_background() {
return attempt.await;
}
// Recovery may have finished between reading the client and joining it.
return self.client().await;
}
result
self.client().await
}
async fn shutdown(&self) {
@@ -267,18 +245,17 @@ impl McpServerView {
}
fn accepts_cached_tools(&self, tools: &[ToolInfo]) -> bool {
self.connection.client.is_codex_apps_mcp_server
|| match self.startup_readiness {
McpStartupReadiness::Connection => !tools.is_empty(),
McpStartupReadiness::Catalog => tools.iter().any(|tool| {
self.tool_filter.allows(&tool.tool.name)
&& (self.connection.startup_is_dormant() || tool_is_model_visible(tool))
}),
}
match self.startup_readiness {
McpStartupReadiness::Connection => !tools.is_empty(),
McpStartupReadiness::Catalog => tools.iter().any(|tool| {
self.tool_filter.allows(&tool.tool.name)
&& (self.connection.startup_is_dormant() || tool_is_model_visible(tool))
}),
}
}
async fn refresh_notified_catalog(&self, server_name: &str, client: &ManagedClient) {
if !self.refresh_tool_list || self.connection.client.is_codex_apps_mcp_server {
if !self.refresh_tool_list {
return;
}
let timeout = self.refresh_timeout;
@@ -287,8 +264,6 @@ impl McpServerView {
.refresh_after_notifications(&client.client.tool_list_revision(), timeout, || async {
let relist = crate::rmcp_client::list_tools_for_client_uncached(
server_name,
/*is_codex_apps_mcp_server*/ false,
"list_changed",
&client.client,
Some(timeout),
self.catalog_item_limit,
@@ -317,11 +292,7 @@ impl McpServerView {
self.connection.client.listed_catalog().await?
};
let tools = filter_tools(tools, &self.tool_filter);
let tools = if self.connection.client.is_codex_apps_mcp_server {
prepare_codex_apps_tools_for_model(tools, tool_plugin_context)
} else {
prepare_regular_mcp_tools_for_model(tools, tool_plugin_context)
};
let tools = prepare_regular_mcp_tools_for_model(tools, tool_plugin_context);
Ok((tools, meta))
}
}
@@ -336,7 +307,6 @@ pub(crate) struct McpConnectionSet {
config: Option<Arc<crate::McpConfig>>,
network_policy_metadata: Option<Arc<dyn NetworkPolicyMetadataProvider>>,
servers: HashMap<String, McpServerView>,
pub(crate) event_stream_connection: Option<Arc<EventStreamConnectionSettings>>,
disabled_servers: Vec<String>,
required_servers: Vec<String>,
optional_startup_deadline: OnceLock<tokio::time::Instant>,
@@ -344,15 +314,13 @@ pub(crate) struct McpConnectionSet {
prefix_mcp_tool_names: bool,
non_prefixed_mcp_tool_servers: Vec<String>,
elicitation_requests: ElicitationRequestManager,
pub(crate) trusted_access: Option<TrustedAccessContext>,
}
impl McpConnectionSet {
/// Creates an MCP connection manager. Threadless callers can pass no `tx_event`; startup
/// notifications are then skipped and interactive elicitations are declined.
pub async fn new(
ema_auth: Option<crate::ema_auth::EmaAuthContext>,
existing_ema: Option<&Self>,
predecessor: Option<&Self>,
previous: Option<PreviousMcpConnections<'_>>,
publication_gate: McpPublicationGate,
input: McpRuntimeInput,
@@ -360,7 +328,6 @@ impl McpConnectionSet {
) -> Self {
let same_owner = previous.as_ref().is_some_and(|state| state.same_owner);
let previous = previous.map(|state| state.connections);
let trusted_access = TrustedAccessContext::from_runtime(&input);
let McpRuntimeInput {
startup_policy,
config,
@@ -372,29 +339,23 @@ impl McpConnectionSet {
tx_event,
startup_cancellation_token,
runtime_context,
codex_apps_tools_cache,
tool_catalog_cache,
codex_apps_tools_cache_key,
client_mcp_extensions,
auth,
auth_manager,
runtime_auth,
elicitation_reviewer,
elicitation_lifecycle,
} = input;
let store_mode = config.mcp_oauth_credentials_store_mode;
let keyring_backend_kind = config.auth_keyring_backend_kind;
let oauth_refresh_mode = config.oauth_refresh_mode;
let codex_home = config.codex_home.clone();
let prefix_mcp_tool_names = config.prefix_mcp_tool_names;
let non_prefixed_mcp_tool_servers = config.non_prefixed_mcp_tool_servers.clone();
let default_protocol_mode = config.protocol_mode;
let host_owned_apps_protocol_mode = config.host_owned_apps_protocol_mode;
let client_elicitation_capability = config.client_elicitation_capability.clone();
let tool_plugin_context = crate::mcp::tool_plugin_context(&config);
let auth = auth.as_ref();
let mut servers = HashMap::new();
let mut event_stream_connection = None;
let disabled_servers = mcp_servers
.iter()
.filter(|(_, server)| !server.enabled())
@@ -410,18 +371,7 @@ impl McpConnectionSet {
let mut eager_starts = Vec::new();
let mut eager_workers = Vec::new();
let mut deferred_workers = Vec::new();
// Retained EMA clients keep callbacks attached to this manager even when
// an explicit reconnect replaces the ordinary clients.
let elicitation_previous = previous
.or_else(|| {
existing_ema.filter(|previous| {
previous
.servers
.values()
.any(|view| view.connection.client.ema_authority.is_some())
})
})
.filter(|previous| {
let elicitation_previous = previous.filter(|previous| {
!previous.servers.is_empty()
&& previous.elicitation_requests.update(
Arc::clone(&config),
@@ -442,35 +392,14 @@ impl McpConnectionSet {
};
let tool_plugin_context = Arc::new(tool_plugin_context);
let startup_submit_id = submit_id;
let static_chatgpt_auth_provider = auth
.filter(|auth| auth.uses_codex_backend())
.map(codex_model_provider::auth_provider_from_auth);
let codex_apps_auth_provider = auth_manager.as_ref().and_then(|auth_manager| {
auth.filter(|auth| auth.uses_codex_backend()).map(|auth| {
codex_model_provider::auth_provider_from_auth_manager(
Arc::clone(auth_manager),
auth,
)
})
});
for (server_name, server) in mcp_servers
.into_iter()
.filter(|(_, server)| server.enabled())
{
let server = server.with_read_only_mcp_tools(config.requires_read_only_mcp_tools);
let registration = config.mcp_server_catalog.server(&server_name);
let client_mcp_extensions = crate::client_capabilities::server_mcp_extensions(
&client_mcp_extensions,
&server_name,
registration,
network_policy_metadata.is_some(),
&config.chatgpt_base_url,
);
let is_host_owned_codex_apps = registration.is_some_and(|server| {
server
.source()
.is_host_owned_apps(&server_name, server.config())
});
let client_mcp_extensions =
crate::client_capabilities::server_mcp_extensions(&client_mcp_extensions);
let host_plugin_root = registration.and_then(|server| match server.source() {
McpServerSource::Plugin(plugin) => plugin.host_root(),
McpServerSource::SelectedPlugin(_)
@@ -478,11 +407,7 @@ impl McpConnectionSet {
| McpServerSource::Compatibility { .. }
| McpServerSource::Extension { .. } => None,
});
let catalog_item_limit = if is_host_owned_codex_apps {
MAX_CODEX_APPS_TOOL_CATALOG_ITEMS
} else {
MAX_MCP_CATALOG_ITEMS
};
let catalog_item_limit = MAX_MCP_CATALOG_ITEMS;
let metadata = McpServerMetadata::from(&server);
let configured_config = server.config().clone();
let protocol_mode = if matches!(
@@ -491,34 +416,10 @@ impl McpConnectionSet {
) {
registration
.and_then(crate::ResolvedMcpServer::protocol_mode)
.unwrap_or(if is_host_owned_codex_apps {
host_owned_apps_protocol_mode
} else {
default_protocol_mode
})
.unwrap_or(default_protocol_mode)
} else {
default_protocol_mode
};
let uses_ema_auth =
config.xaa_enabled && matches!(configured_config.auth, McpServerAuth::EmaAuth);
let protocol_mode = if uses_ema_auth {
McpProtocolMode::V20260728
} else {
protocol_mode
};
let client_mcp_extensions = if uses_ema_auth {
ClientMcpExtensions::new(
client_mcp_extensions
.iter()
.map(|(id, settings)| (id.to_string(), settings.clone()))
.chain(std::iter::once((
ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID.to_string(),
serde_json::json!({}),
))),
)
} else {
client_mcp_extensions
};
let configured_tool_filter = ToolFilter::from_config(&configured_config);
let startup_timeout = configured_config
.startup_timeout_sec
@@ -530,109 +431,13 @@ impl McpConnectionSet {
);
let resolved_environment =
runtime_context.resolve_server_environment(&server_name, &configured_config);
// For built-in Codex Apps, `CODEX_CONNECTORS_TOKEN` is a debug
// override: it supplies runtime auth but bypasses the shared tools
// cache.
let uses_env_bearer_token = match &configured_config.transport {
McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
..
} => bearer_token_env_var.is_some(),
McpServerTransportConfig::Stdio { .. } => false,
};
// Filtered catalogs must not read or populate an unrestricted shared cache.
let eligible_for_apps_cache = is_host_owned_codex_apps
&& !server.requires_read_only_mcp_tools()
&& should_share_codex_apps_tools_cache(&server_name, uses_env_bearer_token);
let shares_codex_apps_tools_cache =
eligible_for_apps_cache && codex_apps_tools_cache.shares_snapshot();
let openai_runtime = runtime_auth.as_ref().filter(|_| {
!uses_env_bearer_token
&& configured_config.is_local_environment()
&& matches!(configured_config.auth, codex_config::McpServerAuth::ChatGpt)
&& auth.is_some_and(codex_login::CodexAuth::uses_codex_backend)
&& matches!(&configured_config.transport,
McpServerTransportConfig::StreamableHttp { url, .. }
if codex_http_client::classify_openai_api_url(url)
!= codex_http_client::OpenAiDestination::Other)
});
let runtime_auth_mode = openai_runtime.map(|(_, mode)| *mode);
let codex_apps_tools_cache_context = shares_codex_apps_tools_cache.then(|| {
// Only equivalent discovery inputs may share executable Apps tools.
let mut transport = configured_config.transport.clone();
if let McpServerTransportConfig::StreamableHttp {
http_headers: Some(headers),
..
} = &mut transport
{
// mcp_server_config_for_url in codex-rs/codex-mcp/src/mcp/mod.rs
// adds thread attribution that threadless discovery does not carry.
headers.retain(|name, _| !name.eq_ignore_ascii_case("originator"));
}
let mut scope = serde_json::json!([
transport,
&configured_config.auth,
runtime_auth_mode,
protocol_mode.preferred_protocol_version().as_str(),
catalog_item_limit,
&client_elicitation_capability,
client_mcp_extensions
.iter()
.collect::<std::collections::BTreeMap<_, _>>(),
]);
scope.sort_all_objects();
codex_apps_tools_cache
.context(codex_home.clone(), codex_apps_tools_cache_key.clone())
.with_live_scope(scope.to_string())
});
// The reserved Codex Apps registration follows the shared
// AuthManager across refreshes. In the hosted-plugin path, this
// is the ChatGPT /ps/mcp connection. User-configured MCP
// registrations keep their existing configured auth path.
let chatgpt_auth_provider = if server_name == CODEX_APPS_MCP_SERVER_NAME {
codex_apps_auth_provider
.clone()
.or_else(|| static_chatgpt_auth_provider.clone())
} else {
static_chatgpt_auth_provider.clone()
};
// If Codex Apps has an env bearer token, that is its auth path. Do
// not also attach the ambient CodexAuth provider.
let runtime_auth_provider =
if server_name == CODEX_APPS_MCP_SERVER_NAME && uses_env_bearer_token {
None
} else {
chatgpt_auth_provider_for_server(&server, chatgpt_auth_provider).map(
|provider| match (openai_runtime, auth) {
(Some(runtime), Some(auth)) => {
crate::auth::McpAuthProvider::runtime(runtime.clone(), auth.clone())
}
_ => crate::auth::McpAuthProvider::Credentials(provider),
},
)
};
let discover_local_stdio = config.discover_local_stdio
&& server.can_discover_local_stdio(&server_name, runtime_auth_provider.as_ref());
let discover_local_stdio =
config.discover_local_stdio && server.can_discover_local_stdio();
let protocol_mode = if discover_local_stdio {
McpProtocolMode::DiscoverLocalStdio
} else {
protocol_mode
};
if is_host_owned_codex_apps {
event_stream_connection = Some(Arc::new(EventStreamConnectionSettings {
server: server.clone(),
store_mode,
keyring_backend_kind,
oauth_refresh_mode,
runtime_context: runtime_context.clone(),
resolved_environment: resolved_environment.clone(),
auth_provider: runtime_auth_provider.clone(),
auth_manager: auth_manager.clone(),
auth: auth.cloned(),
protocol_mode,
client_mcp_extensions: client_mcp_extensions.clone(),
}));
}
let connection_identity = McpServerConnectionIdentity::new(
&server_name,
&server,
@@ -642,11 +447,6 @@ impl McpConnectionSet {
oauth_refresh_mode,
&resolved_environment,
&runtime_context,
runtime_auth_provider.as_ref(),
runtime_auth_mode,
auth,
eligible_for_apps_cache
.then(|| (codex_home.clone(), codex_apps_tools_cache_key.clone())),
client_elicitation_capability.clone(),
client_mcp_extensions.clone(),
previous
@@ -658,10 +458,7 @@ impl McpConnectionSet {
McpServerTransportConfig::Stdio { .. } => server.stdio_protocol_mode(protocol_mode),
};
let mut tool_catalog_cache_context = LazyCell::new(|| {
if server_name == CODEX_APPS_MCP_SERVER_NAME
|| server.requires_read_only_mcp_tools()
|| matches!(configured_config.auth, McpServerAuth::EmaAuth)
{
if server.requires_read_only_mcp_tools() {
return None;
}
let environment = resolved_environment.as_ref().ok()?;
@@ -710,62 +507,6 @@ impl McpConnectionSet {
&& protocol_mode != McpProtocolMode::Legacy
&& (auth.is_none() || auth_manager.is_some())
});
if matches!(configured_config.auth, McpServerAuth::EmaAuth) && existing_ema.is_some() {
if let Some(previous_view) = existing_ema
.filter(|_| elicitation_previous.is_some())
.and_then(|previous| previous.servers.get(&server_name))
{
let connection = &previous_view.connection;
let authority_is_current = || {
connection
.client
.ema_authority
.as_ref()
.is_some_and(|authority| authority.check_new_request().is_ok())
};
let same_identity = connection.identity.as_ref() == Some(&connection_identity)
&& previous_view.catalog_item_limit == catalog_item_limit
&& previous_view.protocol_mode == protocol_mode;
let pending = same_identity
&& !connection.client.startup_complete.load(Ordering::Acquire)
&& connection.startup_timeout == startup_timeout
&& !connection.startup_is_dormant()
&& !connection.client.cancel_token.is_cancelled();
let ready = same_identity
&& !pending
&& connection
.reusable_client(&connection_identity)
.await
.is_some_and(|client| {
expected_protocol_mode == Some(client.client.protocol_mode())
});
if authority_is_current() && (pending || ready) {
servers.insert(
server_name.clone(),
McpServerView {
connection: Arc::clone(connection),
protocol_mode,
startup_readiness: configured_config.startup_readiness,
refresh_tool_list: config.mcp_tool_list_changed,
refresh_timeout: startup_timeout,
metadata,
tool_filter: configured_tool_filter,
tool_timeout: configured_tool_timeout,
catalog_item_limit,
},
);
if pending {
let client = connection.client.clone();
eager_workers
.push(async move { (server_name, client.client().await) }.boxed());
} else {
reused_ready.push(server_name);
}
}
}
// Post-start publications may only retain the original EMA connection.
continue;
}
let mut legacy_to_upgrade = None;
if let Some(previous_view) =
reusable_previous.and_then(|previous| previous.servers.get(&server_name))
@@ -888,14 +629,12 @@ impl McpConnectionSet {
}
let cancel_token = startup_cancellation_token.child_token();
let tool_catalog_cache_context = tool_catalog_cache_context.take();
let has_runtime_auth = runtime_auth_provider.is_some();
let connection_pool = connection_pool.map(|pool| {
(
pool.clone(),
ConnectionKey {
server_name: server_name.clone(),
identity: connection_identity.clone(),
account: codex_apps_tools_cache_key.clone(),
auth_state: auth_manager.as_ref().map(|manager| {
(
Arc::clone(manager),
@@ -907,17 +646,8 @@ impl McpConnectionSet {
},
)
});
let (publish_apps, initialized_apps) =
if is_host_owned_codex_apps && config.apps_early_resource_discovery {
let (tx, rx) = watch::channel(None);
(Some(tx), Some(rx))
} else {
(None, None)
};
let mut async_managed_client = AsyncManagedClient::new(
ema_auth.clone(),
server_name.clone(),
startup_submit_id.clone(),
server,
store_mode,
keyring_backend_kind,
@@ -925,11 +655,9 @@ impl McpConnectionSet {
cancel_token.clone(),
tx_event.clone(),
elicitation_requests.clone(),
codex_apps_tools_cache_context,
tool_catalog_cache_context,
runtime_context.clone(),
resolved_environment,
runtime_auth_provider,
client_elicitation_capability.clone(),
client_mcp_extensions.clone(),
auth_manager
@@ -945,10 +673,9 @@ impl McpConnectionSet {
defer_startup,
catalog_item_limit,
connection_pool,
publish_apps,
);
// A forced reconnect must also wait for the previously published helper to exit.
if let Some(previous) = existing_ema.and_then(|set| set.servers.get(&server_name)) {
if let Some(previous) = predecessor.and_then(|set| set.servers.get(&server_name)) {
async_managed_client.wait_for_failed_predecessor(&previous.connection.client);
}
let legacy_fallback = legacy_to_upgrade
@@ -968,7 +695,6 @@ impl McpConnectionSet {
legacy_fallback,
startup_timeout,
startup_trigger,
initialized_apps,
_diagnostics_guard: LIVE_CONNECTIONS.track(),
}),
protocol_mode,
@@ -1013,10 +739,7 @@ impl McpConnectionSet {
}
if let Some(tx_event) = tx_event.as_ref() {
let auth_state = match &outcome {
Err(error)
if error.is_authentication_required()
&& !has_runtime_auth
&& !matches!(configured_config.auth, McpServerAuth::EmaAuth) =>
Err(error) if error.is_authentication_required() =>
{
match &configured_config.transport {
McpServerTransportConfig::StreamableHttp {
@@ -1086,10 +809,6 @@ impl McpConnectionSet {
outcome = Err(StartupOutcomeError::Cancelled);
}
if matches!(&outcome, Err(StartupOutcomeError::Failed { .. })) {
async_managed_client.reconnect_failed_startup().await;
}
(server_name, outcome)
};
let startup = AuthStorageOriginator::current().scope(startup);
@@ -1104,7 +823,6 @@ impl McpConnectionSet {
config: Some(config),
network_policy_metadata,
servers,
event_stream_connection,
disabled_servers,
required_servers,
optional_startup_deadline: OnceLock::new(),
@@ -1112,7 +830,6 @@ impl McpConnectionSet {
prefix_mcp_tool_names,
non_prefixed_mcp_tool_servers,
elicitation_requests: elicitation_requests.clone(),
trusted_access,
};
tokio::spawn(async move {
if !publication_gate.wait().await {
@@ -1181,7 +898,6 @@ impl McpConnectionSet {
config: None,
network_policy_metadata: None,
servers: HashMap::new(),
event_stream_connection: None,
disabled_servers: Vec::new(),
required_servers: Vec::new(),
optional_startup_deadline: OnceLock::new(),
@@ -1189,7 +905,6 @@ impl McpConnectionSet {
prefix_mcp_tool_names,
non_prefixed_mcp_tool_servers: Vec::new(),
elicitation_requests: ElicitationRequestManager::default(),
trusted_access: None,
}
}
@@ -1450,30 +1165,15 @@ impl McpConnectionSet {
}
/// Returns presentation metadata from the current connection.
/// Codex Apps metadata may come from its existing cache; regular MCP server information is
/// connection-specific, so pending regular clients are awaited.
/// Server information is connection-specific, so pending clients are awaited.
pub(crate) async fn list_available_server_infos(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, McpServerInfo> {
let mut server_infos = HashMap::new();
for (server_name, view) in self.servers.iter().filter(|(name, _)| include_server(name)) {
let client = &view.connection.client;
if !client.startup_complete.load(Ordering::Acquire)
&& let Some(server_info) = client.cached_server_info.clone()
{
server_infos.insert(server_name.clone(), server_info);
continue;
}
match view.connection.client().await {
Ok(managed_client) => {
server_infos.insert(server_name.clone(), managed_client.server_info);
}
Err(_) => {
if let Some(server_info) = client.cached_server_info.clone() {
server_infos.insert(server_name.clone(), server_info);
}
}
if let Ok(managed_client) = view.connection.client().await {
server_infos.insert(server_name.clone(), managed_client.server_info);
}
}
server_infos

View File

@@ -87,12 +87,14 @@ impl NetworkPolicyMetadataProvider for CapturedPolicy {
}
#[tokio::test]
async fn tool_calls_deliver_only_negotiated_trusted_network_policy() -> anyhow::Result<()> {
async fn tool_calls_never_deliver_network_policy_and_strip_forged_metadata() -> anyhow::Result<()> {
// Network policy metadata was only offered to trusted ChatGPT origins, which aKode never
// connects to, so no server receives it and forged caller metadata is always stripped.
for (url, provider_available, supports_policy, delivers_policy) in [
(Some("https://chatgpt.com/mcp"), true, true, true),
(Some("https://chatgpt.com/mcp"), true, true, false),
(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://gov.chatgpt.com/mcp"), true, true, false),
(
Some("https://chatgpt.com.attacker.example/mcp"),
true,
@@ -119,15 +121,12 @@ async fn tool_calls_deliver_only_negotiated_trusted_network_policy() -> anyhow::
server_config,
));
let catalog = catalog.build();
assert!(catalog.server("docs").is_some());
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()

View File

@@ -1,12 +1,5 @@
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;
@@ -93,9 +86,11 @@ impl McpConnectionSet {
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)
}) {
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;
@@ -157,20 +152,6 @@ impl McpConnectionSet {
.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,
@@ -190,24 +171,6 @@ impl McpConnectionSet {
.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,
@@ -224,60 +187,3 @@ impl McpConnectionSet {
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

@@ -2,8 +2,6 @@ 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;
@@ -13,30 +11,8 @@ 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,
@@ -58,13 +34,6 @@ pub(super) fn mcp_startup_failure_reason(
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,
@@ -108,14 +77,11 @@ pub(super) fn mcp_init_error_display(
"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 recovery_hint = 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"

View File

@@ -2,13 +2,10 @@ 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;
@@ -25,15 +22,8 @@ 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;
@@ -163,8 +153,7 @@ impl McpConnectionSet {
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()
if self.required_servers.binary_search(server_name).is_err()
&& matches!(view.connection.client.client.peek(), Some(Err(_)))
{
continue;
@@ -173,7 +162,6 @@ impl McpConnectionSet {
};
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()))
@@ -224,7 +212,6 @@ impl McpConnectionSet {
.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
@@ -307,13 +294,8 @@ impl McpConnectionSet {
);
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 product_sku = codex_otel::bounded_product_sku(Some(crate::mcp::MCP_CATALOG_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
@@ -334,8 +316,7 @@ impl McpConnectionSet {
|| (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);
.is_some_and(|plugin_id| required_plugins.contains(plugin_id)));
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);
@@ -389,12 +370,7 @@ impl McpConnectionSet {
.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 accepts_cached_catalog = view.startup_readiness == McpStartupReadiness::Catalog;
let cached_tools = if startup_pending
|| (accepts_cached_catalog && view.connection.client.ready_client().is_none())
{
@@ -436,9 +412,7 @@ impl McpConnectionSet {
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() {
if plugin_id.is_some() {
"plugin"
} else {
"configured"
@@ -450,14 +424,10 @@ impl McpConnectionSet {
);
}
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 = 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| {
@@ -589,20 +559,12 @@ impl McpConnectionSet {
.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,
)
}
let mut tool_info = 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)?;
@@ -649,163 +611,6 @@ impl McpConnectionSet {
)
}
/// 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

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,6 @@ 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;
@@ -81,7 +80,6 @@ pub struct McpConnectionPool {
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,
@@ -91,7 +89,6 @@ 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) {
@@ -153,8 +150,6 @@ impl Entry {
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,
@@ -184,7 +179,6 @@ impl Entry {
Ok(Arc::new(ClientToolCatalog::new(
Arc::clone(&catalog.tools),
catalog.meta.clone(),
/*updates*/ None,
)))
}
}

View File

@@ -150,9 +150,6 @@ pub(crate) fn key(context: &McpRuntimeContext, config: &McpServerConfig) -> Conn
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,
@@ -219,8 +216,6 @@ pub(crate) fn startup(
.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,
@@ -228,7 +223,7 @@ pub(crate) fn startup(
)
.await?;
client.tool_catalog =
Arc::new(ClientToolCatalog::new(tools, meta, /*updates*/ None));
Arc::new(ClientToolCatalog::new(tools, meta));
client.connection_sharing = sharing;
Ok(client)
}
@@ -694,8 +689,7 @@ async fn callback_during_startup_releases_waiting_chats_without_sharing_authorit
#[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 manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
let mut original = key(&context(), &config());
original.auth_state = Some((manager, AuthChangeState::default()));
let mut refreshed = original.clone();
@@ -765,14 +759,12 @@ async fn new_chat_relists_tools_without_invalidating_or_waiting_for_existing_cal
);
tokio::time::timeout(
Duration::from_secs(1),
second.tool_catalog.refresh(
|| async { Ok((vec![create_test_tool("test_server", "refreshed")], None, ())) },
|_, _, ()| {},
),
second
.tool_catalog
.replace_for_test(vec![create_test_tool("test_server", "refreshed")]),
)
.await
.expect("one chat's refresh must not wait for another chat's calls")
.unwrap();
.expect("one chat's refresh must not wait for another chat's calls");
assert_eq!(
first
.tool_catalog

View File

@@ -23,8 +23,6 @@ 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;
@@ -47,8 +45,6 @@ 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 {
@@ -429,14 +425,7 @@ impl ElicitationRequestManager {
&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| {
@@ -449,36 +438,17 @@ impl ElicitationRequestManager {
.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;
// User verification was only honored for the hosted plugin service, which aKode
// never connects to. Cancel it for every server, outside approval policy.
if matches!(elicitation, Elicitation::UserVerification { .. }) {
return Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: Some(
codex_rmcp_client::UserVerificationReason::ApprovalUnavailable
.into_meta(),
),
});
}
if router.auto_deny() {
return Ok(ElicitationResponse {

View File

@@ -403,7 +403,6 @@ fn elicitation_fixture(
let sender = manager.make_sender(
"independent-mcp".to_string(),
Some(tx_event),
&ClientMcpExtensions::default(),
);
(manager, events, sender)
}
@@ -665,8 +664,7 @@ async fn strict_auto_review_respects_explicit_elicitation_denials() {
let sender = manager.make_sender(
server_name.into(),
/*tx_event*/ None,
&ClientMcpExtensions::default(),
);
);
assert_eq!(
send_elicitation(&sender, marker).await,
ElicitationResponse {
@@ -757,8 +755,7 @@ async fn reused_elicitation_senders_follow_each_servers_latest_permission_author
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
config.approval_policy = codex_config::Constrained::allow_any(AskForApproval::Never);
config.permission_profile = PermissionProfile::Disabled;
config.apps_enabled = true;
let auth = codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing();
let auth = codex_login::CodexAuth::from_api_key("test-api-key");
let hosted_server = crate::mcp::test_http_mcp_server_config("https://example.com");
let mut attached_server = hosted_server.clone();
@@ -795,12 +792,10 @@ async fn reused_elicitation_senders_follow_each_servers_latest_permission_author
let attached = manager.make_sender(
"attached".to_string(),
/*tx_event*/ None,
&ClientMcpExtensions::default(),
);
let hosted = manager.make_sender(
"local".to_string(),
/*tx_event*/ None,
&ClientMcpExtensions::default(),
);
assert_eq!(
@@ -869,12 +864,13 @@ fn verification_fixture(
reviewer: Option<Arc<RecordingReviewer>>,
) -> (ElicitationRequestManager, Receiver<Event>, SendElicitation) {
let mut config = test_elicitation_config(
crate::CODEX_APPS_MCP_SERVER_NAME,
"codex_apps",
approval_policy,
PermissionProfile::Disabled,
);
let mut catalog = crate::catalog::ResolvedMcpCatalog::builder();
catalog.register(crate::catalog::McpServerRegistration::from_hosted_apps(
catalog.register(crate::catalog::McpServerRegistration::from_extension(
"codex_apps".to_string(),
"verification-test",
/*contribution_order*/ 0,
crate::mcp::test_http_mcp_server_config("https://example.com"),
@@ -888,83 +884,18 @@ fn verification_fixture(
);
let (tx, events) = async_channel::bounded(1);
let sender = manager.make_sender(
crate::CODEX_APPS_MCP_SERVER_NAME.into(),
"codex_apps".into(),
Some(tx),
&ClientMcpExtensions::new([(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"userVerification": {}}),
)]),
);
(manager, events, sender)
}
#[tokio::test]
async fn user_verification_requires_the_app_even_when_policy_would_approve_or_decline() {
for approval_policy in [AskForApproval::Never, AskForApproval::OnRequest] {
let reviewer = RecordingReviewer::new(Ok(Some(approved_response())));
let (manager, events, sender) =
verification_fixture(approval_policy, Some(reviewer.clone()));
let pending = tokio::spawn(sender(
RequestId::Number(7),
Elicitation::UserVerification {
meta: Some(json!({"example/display": {"label": "Operation"}})),
title: "Approve purchase".into(),
description: "Pay $200".into(),
challenge: "AQID".into(),
},
));
let event = events.recv().await.unwrap();
let EventMsg::ElicitationRequest(request) = event.msg else {
panic!("expected typed elicitation");
};
assert_eq!(
request.request,
ElicitationRequest::UserVerification {
meta: Some(json!({"example/display": {"label": "Operation"}})),
title: "Approve purchase".into(),
description: "Pay $200".into(),
challenge: "AQID".into(),
}
);
assert_eq!(reviewer.calls.load(Relaxed), 0);
let ProtocolRequestId::String(id) = request.id else {
panic!("expected routed request id");
};
let proof = ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({"credentialId": "AQID", "signature": "BAUG"})),
meta: None,
};
manager
.router
.resolve(
request.server_name.clone(),
RequestId::String(id.clone().into()),
proof.clone(),
)
.await
.unwrap();
assert_eq!(pending.await.unwrap().unwrap(), proof);
assert!(
manager
.router
.resolve(request.server_name, RequestId::String(id.into()), proof)
.await
.is_err()
);
}
}
#[tokio::test]
async fn user_verification_cancels_when_no_app_can_receive_the_request() {
let (manager, _, _) = verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let sender = manager.make_sender(
crate::CODEX_APPS_MCP_SERVER_NAME.into(),
"codex_apps".into(),
/*tx_event*/ None,
&ClientMcpExtensions::new([(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"userVerification": {}}),
)]),
);
assert_eq!(
sender(
@@ -991,9 +922,8 @@ async fn user_verification_cancels_for_an_event_receiver_without_host_activation
let (manager, _, _) = verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let (tx, events) = async_channel::bounded(1);
let sender = manager.make_sender(
crate::CODEX_APPS_MCP_SERVER_NAME.into(),
"codex_apps".into(),
Some(tx),
&ClientMcpExtensions::default(),
);
let response = tokio::time::timeout(
std::time::Duration::from_secs(1),
@@ -1022,42 +952,9 @@ async fn user_verification_cancels_for_an_event_receiver_without_host_activation
assert!(manager.router.requests.lock().unwrap().pending.is_empty());
}
#[tokio::test]
async fn user_verification_drops_pending_response_when_the_request_is_cancelled() {
let (manager, events, sender) =
verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let active_elicitations = Arc::new(AtomicUsize::new(0));
let registrations = active_elicitations.clone();
manager
.authority
.lock()
.unwrap()
.as_mut()
.unwrap()
.lifecycle = Some(ElicitationLifecycle::new(move || {
registrations.fetch_add(/*val*/ 1, Relaxed);
LifecycleRegistration(registrations.clone())
}));
let pending = tokio::spawn(sender(
RequestId::Number(7),
Elicitation::UserVerification {
meta: None,
title: "Approve".into(),
description: String::new(),
challenge: "AQID".into(),
},
));
events.recv().await.unwrap();
assert_eq!(active_elicitations.load(Relaxed), 1);
pending.abort();
assert!(pending.await.unwrap_err().is_cancelled());
assert!(manager.router.requests.lock().unwrap().pending.is_empty());
assert_eq!(active_elicitations.load(Relaxed), 0);
}
#[tokio::test]
async fn user_verification_rejects_attached_servers_even_if_they_use_the_plugin_service_name() {
for name in ["attached", crate::CODEX_APPS_MCP_SERVER_NAME] {
for name in ["attached", "codex_apps"] {
let (manager, _, _) =
verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
{
@@ -1074,11 +971,7 @@ async fn user_verification_rejects_attached_servers_even_if_they_use_the_plugin_
let sender = manager.make_sender(
name.into(),
Some(tx),
&ClientMcpExtensions::new([(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"userVerification": {}}),
)]),
);
);
assert_eq!(
sender(
RequestId::Number(7),

View File

@@ -1,115 +0,0 @@
//! 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

@@ -1,277 +0,0 @@
//! 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

@@ -1,429 +0,0 @@
//! 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

@@ -1,160 +0,0 @@
//! 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

@@ -1,11 +1,7 @@
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;
@@ -16,13 +12,6 @@ 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;
@@ -45,12 +34,6 @@ 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;
@@ -62,25 +45,12 @@ 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::configured_mcp_servers;
pub use mcp::effective_mcp_servers;
pub use mcp::effective_mcp_servers_from_configured;
@@ -114,30 +84,21 @@ 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;
@@ -146,4 +107,3 @@ pub(crate) mod server;
mod tool_catalog_cache;
mod tool_request_meta;
pub(crate) mod tools;
mod trusted_access;

View File

@@ -8,10 +8,8 @@ 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;
@@ -22,7 +20,6 @@ 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;
@@ -202,17 +199,12 @@ pub async fn compute_auth_statuses<'a, 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
@@ -228,9 +220,6 @@ where
store_mode,
keyring_backend_kind,
auth,
auth_manager,
account_grant,
ema_state,
&runtime_context,
redirect_mode,
)
@@ -259,10 +248,7 @@ async fn compute_auth_status(
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,
_auth: Option<&CodexAuth>,
runtime_context: &McpRuntimeContext,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<McpAuthState> {
@@ -270,73 +256,10 @@ async fn compute_auth_status(
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),
},
);
// Enterprise-managed authorization was removed; these servers never start.
return Ok(McpAuthState::Unsupported);
}
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
@@ -345,10 +268,6 @@ async fn compute_auth_status(
});
}
if has_runtime_auth {
return Ok(McpAuthState::BearerToken);
}
match &config.transport {
McpServerTransportConfig::Stdio { .. } => Ok(McpAuthState::Unsupported),
McpServerTransportConfig::StreamableHttp {

View File

@@ -20,20 +20,14 @@ 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;
@@ -60,10 +54,9 @@ 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";
/// Product SKU reported in MCP catalog telemetry.
pub(crate) const MCP_CATALOG_PRODUCT_SKU: &str = "codex";
const MCP_TOOL_NAME_PREFIX: &str = "mcp";
const MCP_TOOL_NAME_DELIMITER: &str = "__";
@@ -129,21 +122,10 @@ pub enum McpServerPermissions {
/// 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.
@@ -187,33 +169,21 @@ pub struct McpConfig {
// 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.
/// Protocol mode for MCP servers.
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.
@@ -232,12 +202,7 @@ impl McpConfig {
.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) =
let permissions = if let Some(sandbox) =
environment_sandboxes.get(&server.config().environment_id)
{
McpServerPermissions::Environment(Arc::clone(sandbox))
@@ -277,25 +242,12 @@ impl McpConfig {
/// 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)
@@ -314,21 +266,7 @@ impl ToolPluginContext {
}
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(),
);
}
let mut tool_plugin_context = Self::default();
for (server_name, attribution) in config
.mcp_server_catalog
@@ -352,13 +290,8 @@ impl ToolPluginContext {
);
for plugin_names in tool_plugin_context
.plugin_display_names_by_connector_id
.plugin_display_names_by_mcp_server_name
.values_mut()
.chain(
tool_plugin_context
.plugin_display_names_by_mcp_server_name
.values_mut(),
)
{
plugin_names.sort_unstable();
plugin_names.dedup();
@@ -378,39 +311,6 @@ pub fn effective_mcp_servers(
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
@@ -424,7 +324,7 @@ pub fn effective_mcp_servers_from_configured(
config: &McpConfig,
_auth: Option<&CodexAuth>,
) -> HashMap<String, EffectiveMcpServer> {
let mut servers = configured_servers
configured_servers
.into_iter()
.map(|(name, mut server)| {
#[expect(
@@ -435,13 +335,11 @@ pub fn effective_mcp_servers_from_configured(
.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 => {}
// ChatGPT credentials are never available, so local servers that ask for them use
// their own OAuth flow. Executor-owned servers keep `ChatGpt` so they never consult
// orchestrator OAuth stores and are rejected unless they carry explicit authorization.
if matches!(server.auth, McpServerAuth::ChatGpt) && server.is_local_environment() {
server.auth = McpServerAuth::OAuth;
}
(
name,
@@ -452,10 +350,7 @@ pub fn effective_mcp_servers_from_configured(
.with_agent_plugin(registration.source().is_agent_plugin()),
)
})
.collect::<HashMap<_, _>>();
// aKode never connects to the ChatGPT-hosted apps MCP server.
servers.remove(CODEX_APPS_MCP_SERVER_NAME);
servers
.collect::<HashMap<_, _>>()
}
pub fn tool_plugin_context(config: &McpConfig) -> ToolPluginContext {
@@ -466,12 +361,7 @@ pub fn tool_plugin_context(config: &McpConfig) -> ToolPluginContext {
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,
@@ -481,13 +371,11 @@ pub async fn read_mcp_resource(
let cancel_token = CancellationToken::new();
let runtime_config = config.for_threadless_operations(&mcp_servers);
let manager = McpConnectionSet::new(
/*ema_auth*/ None,
/*existing_ema*/ None,
/*predecessor*/ 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,
@@ -497,9 +385,7 @@ pub async fn read_mcp_resource(
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,
@@ -532,13 +418,7 @@ pub struct McpServerStatusSnapshot {
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>,
@@ -564,8 +444,6 @@ pub async fn collect_mcp_server_status_snapshot_with_detail(
config.mcp_oauth_credentials_store_mode,
config.auth_keyring_backend_kind,
auth,
auth_manager,
&config.ema_state,
&runtime_context,
)
.await;
@@ -575,13 +453,11 @@ pub async fn collect_mcp_server_status_snapshot_with_detail(
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,
/*predecessor*/ 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,
@@ -591,9 +467,7 @@ pub async fn collect_mcp_server_status_snapshot_with_detail(
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,
@@ -794,16 +668,11 @@ pub(crate) async fn collect_mcp_server_status_snapshot_from_manager(
.insert(tool_name, tool);
}
// Status-only discovery has no event channel. Report OAuth and EMA failures from the completed
// Status-only discovery has no event channel. Report OAuth 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))
{
if auth_statuses.get(&server_name) == Some(&McpAuthStatus::OAuth) {
auth_statuses.insert(server_name, McpAuthStatus::NotLoggedIn);
}
}
@@ -829,7 +698,7 @@ pub(crate) mod tests;
#[cfg(test)]
pub(crate) fn test_http_mcp_server_config(url: &str) -> McpServerConfig {
McpServerConfig {
transport: McpServerTransportConfig::StreamableHttp {
transport: codex_config::McpServerTransportConfig::StreamableHttp {
url: url.to_string(),
bearer_token_env_var: None,
http_headers: None,

View File

@@ -11,16 +11,13 @@ 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_config::McpServerTransportConfig;
use codex_rmcp_client::McpAuthState;
use futures::FutureExt;
use pretty_assertions::assert_eq;
@@ -31,63 +28,15 @@ use std::sync::Arc;
use std::time::Duration;
#[tokio::test]
async fn ema_auth_statuses_do_not_wait_for_account_refresh() -> anyhow::Result<()> {
async fn removed_ema_auth_servers_report_unsupported_auth() -> 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 auth = CodexAuth::from_api_key("test-api-key");
let mut servers = HashMap::new();
for name in ["first", "second"] {
let mut server: McpServerConfig = serde_json::from_value(serde_json::json!({
let 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),
@@ -104,33 +53,30 @@ async fn ema_auth_statuses_do_not_wait_for_account_refresh() -> anyhow::Result<(
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Some(&auth),
Some(&manager),
&crate::EmaState::default(),
&runtime_context,
),
)
.await
.context("MCP auth status waited for the held account lease")?;
.context("MCP auth status should not block")?;
// Enterprise-managed authorization was removed; never borrow another credential.
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),
("first".to_string(), McpAuthState::Unsupported),
("second".to_string(), McpAuthState::Unsupported),
]),
);
drop(lease);
Ok(())
}
#[tokio::test]
async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures() {
async fn status_snapshot_only_downgrades_oauth_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);
@@ -148,21 +94,9 @@ async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures()
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;
@@ -173,12 +107,7 @@ async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures()
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")
}),
config: None,
auth_state,
},
);
@@ -199,9 +128,6 @@ async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures()
("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),
]),
);
@@ -209,14 +135,8 @@ async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures()
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(),
@@ -236,17 +156,13 @@ pub(crate) fn test_mcp_config(codex_home: PathBuf) -> McpConfig {
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(),
}
}
@@ -265,7 +181,7 @@ pub(crate) fn test_elicitation_config(
}
#[test]
fn ema_catalog_allows_only_configured_servers_without_widening_policy() {
fn removed_ema_auth_servers_stay_disabled_for_every_source_and_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" }
@@ -290,21 +206,12 @@ fn ema_catalog_allows_only_configured_servers_without_widening_policy() {
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());
}
for denied in [false, true] {
let catalog = catalog.clone();
config.mcp_server_catalog = catalog.build_with_environment_authority(|_| {
if denied {
crate::McpEnvironmentAuthority::Restricted(&deny_all)
@@ -314,9 +221,7 @@ fn ema_catalog_allows_only_configured_servers_without_widening_policy() {
});
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!(!servers[name].enabled(), "{name}");
assert_eq!(servers[name].config().auth, McpServerAuth::EmaAuth);
}
}
@@ -434,7 +339,7 @@ fn mcp_prompt_auto_approval_honors_approved_tools_in_all_permission_modes() {
}
#[test]
fn tool_plugin_context_collects_app_and_mcp_sources() {
fn tool_plugin_context_collects_mcp_sources() {
let mut config = test_mcp_config(PathBuf::new());
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_plugin(
@@ -444,44 +349,11 @@ fn tool_plugin_context_collects_app_and_mcp_sources() {
test_http_mcp_server_config("https://alpha.example"),
));
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()],
@@ -515,24 +387,12 @@ fn selected_mcp_attribution_does_not_join_an_unrelated_local_summary() {
test_http_mcp_server_config("https://github.example"),
));
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()],
@@ -597,7 +457,7 @@ fn effective_mcp_servers_require_catalog_registration() {
}
#[test]
fn effective_mcp_servers_preserve_chatgpt_auth_for_trusted_origins() {
fn effective_mcp_servers_never_grant_chatgpt_auth_even_for_chatgpt_origins() {
for (base_url, server_url) in [
("https://chatgpt-staging.com", "https://chatgpt-staging.com"),
(
@@ -612,7 +472,6 @@ fn effective_mcp_servers_preserve_chatgpt_auth_for_trusted_origins() {
("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 mut server = test_http_mcp_server_config(server_url);
server.auth = McpServerAuth::ChatGpt;
let mut catalog = ResolvedMcpCatalog::builder();
@@ -626,7 +485,7 @@ fn effective_mcp_servers_preserve_chatgpt_auth_for_trusted_origins() {
assert_eq!(
effective["trusted"].config().auth,
McpServerAuth::ChatGpt,
McpServerAuth::OAuth,
"backend {base_url}, server {server_url}",
);
}
@@ -644,7 +503,6 @@ fn effective_mcp_servers_reject_untrusted_origins_for_chatgpt_auth() {
"https://example.com",
] {
let mut config = test_mcp_config(PathBuf::new());
config.chatgpt_base_url = url.to_string();
let mut server = test_http_mcp_server_config(url);
server.auth = McpServerAuth::ChatGpt;
let mut catalog = ResolvedMcpCatalog::builder();
@@ -668,8 +526,7 @@ fn effective_mcp_servers_reject_untrusted_origins_for_chatgpt_auth() {
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 auth = CodexAuth::from_api_key("test-api-key");
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
@@ -733,8 +590,8 @@ async fn effective_mcp_servers_preserve_runtime_servers() {
},
));
catalog.register(McpServerRegistration::from_config(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
test_http_mcp_server_config("https://chatgpt.com/backend-api/ps/mcp"),
"codex_apps".to_string(),
test_http_mcp_server_config("https://apps.example/mcp"),
));
config.mcp_server_catalog = catalog.build();
@@ -744,8 +601,8 @@ async fn effective_mcp_servers_preserve_runtime_servers() {
let docs = effective
.get("docs")
.expect("configured server should exist");
// aKode never connects to the ChatGPT-hosted apps MCP server.
assert!(!effective.contains_key(CODEX_APPS_MCP_SERVER_NAME));
// The formerly reserved hosted Apps name is now an ordinary configured server.
assert!(effective.contains_key("codex_apps"));
let sample = sample.config();
let docs = docs.config();

View File

@@ -1,143 +0,0 @@
//! 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

@@ -1,20 +0,0 @@
#![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

@@ -8,7 +8,6 @@ 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);

View File

@@ -187,7 +187,7 @@ fn normalize_plugin_mcp_server(
.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"
"plugin MCP declarations cannot select ema_auth; enterprise-managed authorization is not supported"
.to_string(),
);
}

View File

@@ -659,7 +659,7 @@ fn native_plugin_mcp_cannot_self_declare_ema_auth() {
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(),
message: "plugin MCP declarations cannot select ema_auth; enterprise-managed authorization is not supported".to_string(),
}],
}
);

View File

@@ -1,32 +1,16 @@
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)]
@@ -37,18 +21,6 @@ pub struct McpResourcePage {
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 {
@@ -56,134 +28,7 @@ pub struct McpResourceReadResult {
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.
/// Access to MCP resources through the latest runtime.
#[derive(Clone)]
pub struct McpResourceClient {
runtime: Arc<McpRuntime>,
@@ -299,50 +144,6 @@ impl McpResourceClient {
})
}
/// 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());
@@ -358,66 +159,6 @@ impl McpResourceClient {
.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> {

View File

@@ -1,315 +0,0 @@
//! 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
}
}

View File

@@ -1,10 +1,8 @@
//! RMCP client lifecycle for MCP server connections.
//!
//! This module owns startup of individual RMCP clients: building the transport,
//! initializing the server, listing raw tools, applying per-server tool filters,
//! and exposing cached Codex Apps tools while a client is still connecting.
//! initializing the server, listing raw tools, and applying per-server tool filters.
//! Initialization capabilities survive tool-discovery failures and reset on a new attempt.
//! Apps discovery stays nonblocking; invocations can join the shared startup retry.
//! Executor-discovered environment credentials remain executor-bound across those attempts.
//! Higher-level aggregation and resource/tool APIs live in
//! [`crate::connection_manager`].
@@ -32,11 +30,7 @@ use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use crate::auth::McpAuthProvider;
use crate::client_tool_catalog::ClientToolCatalog;
use crate::codex_apps::normalize_codex_apps_callable_name;
use crate::codex_apps::normalize_codex_apps_callable_namespace;
use crate::codex_apps::normalize_codex_apps_tool_title;
use crate::connection_pool::ConnectionKey;
use crate::connection_pool::ConnectionSharing;
use crate::connection_pool::ConnectionSlot;
@@ -44,7 +38,6 @@ use crate::connection_pool::LEASE_CAPABILITY;
use crate::connection_pool::SharingNegotiation;
use crate::elicitation::ElicitationRequestManager;
use crate::executor_environment_http_client::ExecutorEnvironmentHttpClient;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::mcp::ToolPluginContext;
use crate::openai_docs_source_attribution::maybe_with_openai_docs_source_attribution;
use crate::pagination::collect_paginated_with_limit;
@@ -66,19 +59,12 @@ use codex_config::McpServerConfig;
use codex_config::McpServerTransportConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_connectors::ConnectorRuntimeContext;
use codex_connectors::ConnectorRuntimeFetchSource;
use codex_exec_server::Environment;
use codex_login::AuthChangeState;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::mcp::McpServerInfo;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::McpStartupStatus;
use codex_protocol::protocol::McpStartupUpdateEvent;
use codex_rmcp_client::EmaAuthFailure;
use codex_rmcp_client::EmaTokenSourceError;
use codex_rmcp_client::ExecutorStdioServerLauncher;
use codex_rmcp_client::LocalStdioServerLauncher;
use codex_rmcp_client::McpOAuthRefreshMode;
@@ -100,7 +86,6 @@ use rmcp::model::ProtocolVersion;
use rmcp::model::ServerPeerInfo;
use rmcp::model::Tool as RmcpTool;
use tokio::sync::watch;
use tokio::time::Instant as TokioInstant;
use tokio_util::sync::CancellationToken;
use tracing::Instrument;
use tracing::instrument;
@@ -117,13 +102,9 @@ const MAX_PLUGIN_PROVENANCE_BYTES: usize = 1_024;
pub(crate) const MCP_TOOLS_LIST_DURATION_METRIC: &str = "codex.mcp.tools.list.duration_ms";
pub(crate) const MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC: &str =
"codex.mcp.tools.fetch_uncached.duration_ms";
pub(crate) const CODEX_APPS_REFRESH_DURATION_METRIC: &str = "codex.apps.refresh.duration_ms";
pub(crate) const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(300);
pub(crate) const CODEX_APPS_RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
const CODEX_APPS_RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
const UNTRUSTED_CONNECTOR_META_KEYS: &[&str] = &[
"connector_id",
"connector_name",
@@ -136,142 +117,8 @@ pub(crate) type ManagedClientFuture =
Shared<BoxFuture<'static, Result<ManagedClient, StartupOutcomeError>>>;
type StartupShutdown = Shared<BoxFuture<'static, Result<(), String>>>;
#[derive(Default)]
struct CodexAppsStartupReconnectState {
current_client: Option<ManagedClient>,
last_error: Option<StartupOutcomeError>,
reconnect_in_flight: Option<ManagedClientFuture>,
consecutive_failures: u32,
retry_not_before: Option<TokioInstant>,
}
#[derive(Clone)]
struct CodexAppsStartupStatusContext {
submit_id: String,
server_name: String,
tx_event: Sender<Event>,
}
pub(crate) struct CodexAppsStartupReconnect {
factory: Arc<dyn Fn() -> ManagedClientFuture + Send + Sync>,
state: StdMutex<CodexAppsStartupReconnectState>,
startup_status_context: Option<CodexAppsStartupStatusContext>,
}
impl CodexAppsStartupReconnect {
pub(crate) fn new(factory: Arc<dyn Fn() -> ManagedClientFuture + Send + Sync>) -> Self {
Self {
factory,
state: StdMutex::new(CodexAppsStartupReconnectState::default()),
startup_status_context: None,
}
}
fn with_startup_status_context(
mut self,
submit_id: String,
server_name: String,
tx_event: Option<Sender<Event>>,
) -> Self {
self.startup_status_context = tx_event.map(|tx_event| CodexAppsStartupStatusContext {
submit_id,
server_name,
tx_event,
});
self
}
fn current_client(&self) -> Option<ManagedClient> {
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.current_client
.clone()
}
pub(crate) fn reconnect_in_background(self: &Arc<Self>) -> Option<ManagedClientFuture> {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(attempt) = &state.reconnect_in_flight {
return Some(attempt.clone());
}
if state.current_client.is_some()
|| state
.retry_not_before
.is_some_and(|retry_not_before| TokioInstant::now() < retry_not_before)
{
return None;
}
let reconnect = Arc::clone(self);
let attempt = async move {
let result = (reconnect.factory)().await;
let startup_status_context = reconnect.startup_status_context.clone();
let recovered = {
let mut state = reconnect
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.reconnect_in_flight = None;
match &result {
Ok(client) => {
state.current_client = Some(client.clone());
state.last_error = None;
state.consecutive_failures = 0;
state.retry_not_before = None;
true
}
Err(error) => {
state.last_error = Some(error.clone());
state.consecutive_failures = state.consecutive_failures.saturating_add(1);
let retry_after = codex_apps_reconnect_backoff(state.consecutive_failures);
state.retry_not_before = Some(TokioInstant::now() + retry_after);
warn!(
error = %error,
retry_after_ms = retry_after.as_millis(),
"Apps MCP startup reconnect failed; continuing with cached tools"
);
false
}
}
};
if recovered && let Some(context) = startup_status_context {
let _ = context
.tx_event
.send(Event {
id: context.submit_id,
msg: EventMsg::McpStartupUpdate(McpStartupUpdateEvent {
server: context.server_name,
status: McpStartupStatus::Ready,
}),
})
.await;
}
result
}
.boxed()
.shared();
state.reconnect_in_flight = Some(attempt.clone());
drop(state);
// Keep recovery running if the invocation waiting for it is cancelled.
tokio::spawn(attempt.clone());
Some(attempt)
}
}
fn codex_apps_reconnect_backoff(consecutive_failures: u32) -> Duration {
let exponent = consecutive_failures.saturating_sub(1).min(5);
CODEX_APPS_RECONNECT_INITIAL_BACKOFF
.saturating_mul(1 << exponent)
.min(CODEX_APPS_RECONNECT_MAX_BACKOFF)
}
#[derive(Clone)]
struct ManagedClientStartup {
ema_auth: Option<Result<crate::ema_auth::EmaConnectionAuth, StartupOutcomeError>>,
originator: AuthStorageOriginator,
server_name: String,
server: EffectiveMcpServer,
@@ -280,11 +127,9 @@ struct ManagedClientStartup {
oauth_refresh_mode: McpOAuthRefreshMode,
tx_event: Option<Sender<Event>>,
elicitation_requests: ElicitationRequestManager,
codex_apps_tools_cache_context: Option<ConnectorRuntimeContext<ToolInfo>>,
tool_catalog_cache_context: Option<McpToolCatalogCacheContext>,
runtime_context: McpRuntimeContext,
resolved_environment: std::result::Result<Option<Arc<Environment>>, String>,
runtime_auth_provider: Option<McpAuthProvider>,
client_elicitation_capability: ElicitationCapability,
client_mcp_extensions: ClientMcpExtensions,
auth_changes: Option<watch::Receiver<AuthChangeState>>,
@@ -299,7 +144,6 @@ impl ManagedClientStartup {
fn start(
&self,
sharing_declined: Option<CancellationToken>,
publish_apps: Option<watch::Sender<Option<std::sync::Weak<RmcpClient>>>>,
) -> ManagedClientFuture {
// A new attempt must not expose capabilities from an earlier connection.
*self
@@ -307,7 +151,6 @@ impl ManagedClientStartup {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
let Self {
ema_auth,
originator,
server_name,
server,
@@ -316,11 +159,9 @@ impl ManagedClientStartup {
oauth_refresh_mode,
tx_event,
elicitation_requests,
codex_apps_tools_cache_context,
tool_catalog_cache_context,
runtime_context,
resolved_environment,
runtime_auth_provider,
client_elicitation_capability,
client_mcp_extensions,
auth_changes,
@@ -330,7 +171,6 @@ impl ManagedClientStartup {
startup_complete,
server_capabilities,
} = self.clone();
let is_codex_apps_mcp_server = server_name == CODEX_APPS_MCP_SERVER_NAME;
let startup_timeout = server
.config()
.startup_timeout_sec
@@ -340,7 +180,6 @@ impl ManagedClientStartup {
let tool_catalog_fetch_ticket = tool_catalog_cache_context
.as_ref()
.map(McpToolCatalogCacheContext::begin_fetch);
let refresh_start = is_codex_apps_mcp_server.then(Instant::now);
let mut discovery_client = None;
let outcome = match async {
if let Err(error) = validate_mcp_server_name(&server_name) {
@@ -350,7 +189,6 @@ impl ManagedClientStartup {
let client = match tokio::time::timeout(
startup_timeout,
make_rmcp_client(
ema_auth,
&server_name,
server.clone(),
store_mode,
@@ -358,8 +196,7 @@ impl ManagedClientStartup {
oauth_refresh_mode,
runtime_context,
resolved_environment,
runtime_auth_provider,
protocol_mode,
protocol_mode,
),
)
.await
@@ -381,12 +218,9 @@ impl ManagedClientStartup {
client,
StartServerTaskParams {
sharing_declined,
publish_apps,
is_codex_apps_mcp_server,
startup_timeout: Some(startup_timeout),
tx_event,
elicitation_requests,
codex_apps_tools_cache_context,
tool_catalog_cache_context,
tool_catalog_fetch_ticket,
client_elicitation_capability,
@@ -432,15 +266,6 @@ impl ManagedClientStartup {
if let Err(StartupOutcomeError::Failed { error, .. }) = &outcome {
warn!(server_name, %error, "MCP server startup failed");
}
if outcome.is_ok()
&& let Some(refresh_start) = refresh_start
{
emit_duration(
CODEX_APPS_REFRESH_DURATION_METRIC,
refresh_start.elapsed(),
&[("path", "legacy"), ("trigger", "initial")],
);
}
startup_complete.store(true, Ordering::Release);
outcome
@@ -455,16 +280,11 @@ impl ManagedClientStartup {
#[derive(Clone)]
pub(crate) struct AsyncManagedClient {
pub(crate) ema_authority: Option<codex_rmcp_client::EmaRequestAuthority>,
pub(crate) client: ManagedClientFuture,
pub(crate) is_codex_apps_mcp_server: bool,
pub(crate) cached_server_info: Option<McpServerInfo>,
/// Retained after initialization even if subsequent tool discovery fails.
pub(crate) server_capabilities: Arc<StdMutex<Option<serde_json::Value>>>,
pub(crate) codex_apps_tools_cache_context: Option<ConnectorRuntimeContext<ToolInfo>>,
pub(crate) tool_catalog_cache_context: Option<McpToolCatalogCacheContext>,
pub(crate) startup_complete: Arc<AtomicBool>,
pub(crate) startup_reconnect: Option<Arc<CodexAppsStartupReconnect>>,
pub(crate) connection_slot: Option<Arc<ConnectionSlot>>,
pub(crate) cancel_token: CancellationToken,
}
@@ -475,9 +295,7 @@ impl AsyncManagedClient {
#[instrument(level = "trace", skip_all, fields(server_name = %server_name))]
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
ema_auth: Option<crate::ema_auth::EmaAuthContext>,
server_name: String,
startup_submit_id: String,
server: EffectiveMcpServer,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
@@ -485,11 +303,9 @@ impl AsyncManagedClient {
cancel_token: CancellationToken,
tx_event: Option<Sender<Event>>,
elicitation_requests: ElicitationRequestManager,
codex_apps_tools_cache_context: Option<ConnectorRuntimeContext<ToolInfo>>,
tool_catalog_cache_context: Option<McpToolCatalogCacheContext>,
runtime_context: McpRuntimeContext,
resolved_environment: std::result::Result<Option<Arc<Environment>>, String>,
runtime_auth_provider: Option<McpAuthProvider>,
client_elicitation_capability: ElicitationCapability,
client_mcp_extensions: ClientMcpExtensions,
auth_changes: Option<watch::Receiver<AuthChangeState>>,
@@ -497,32 +313,9 @@ impl AsyncManagedClient {
defer_startup: bool,
catalog_item_limit: usize,
connection_pool: Option<(crate::McpConnectionPool, ConnectionKey)>,
publish_apps: Option<watch::Sender<Option<std::sync::Weak<RmcpClient>>>>,
) -> Self {
let is_codex_apps_mcp_server = server_name == CODEX_APPS_MCP_SERVER_NAME;
let reconnect_server_name = server_name.clone();
let reconnect_tx_event = tx_event.clone();
let cached_server_info = if is_codex_apps_mcp_server {
codex_apps_tools_cache_context
.as_ref()
.and_then(ConnectorRuntimeContext::cached_server_info)
} else {
None
};
let startup_complete = Arc::new(AtomicBool::new(false));
let server_capabilities = Arc::new(StdMutex::new(None));
let ema_auth = ema_auth
.filter(|_| matches!(server.config().auth, McpServerAuth::EmaAuth))
.map(|auth| {
auth.map(|owner| crate::ema_auth::EmaConnectionAuth {
authority: owner.authority.child(),
owner,
})
});
let ema_authority = ema_auth
.as_ref()
.and_then(|auth| auth.as_ref().ok())
.map(|auth| auth.authority.clone());
// Startup may publish a legacy catalog after negotiation. Only a dormant chat can
// advertise it beforehand, and the pool must never put modern tools in that catalog.
let pool_catalog = tool_catalog_cache_context
@@ -535,7 +328,6 @@ impl AsyncManagedClient {
pool_catalog.clone()
};
let startup = Arc::new(ManagedClientStartup {
ema_auth,
originator: AuthStorageOriginator::current(),
server_name,
server,
@@ -544,11 +336,9 @@ impl AsyncManagedClient {
oauth_refresh_mode,
tx_event,
elicitation_requests,
codex_apps_tools_cache_context: codex_apps_tools_cache_context.clone(),
tool_catalog_cache_context,
runtime_context,
resolved_environment,
runtime_auth_provider,
client_elicitation_capability,
client_mcp_extensions,
auth_changes,
@@ -576,7 +366,7 @@ impl AsyncManagedClient {
|cancellation, sharing_declined| {
let mut shared_startup = (*startup).clone();
shared_startup.cancel_token = cancellation;
shared_startup.start(sharing_declined, /*publish_apps*/ None)
shared_startup.start(sharing_declined)
},
)
.await
@@ -586,7 +376,6 @@ impl AsyncManagedClient {
Some(Arc::new(startup.elicitation_requests.make_sender(
startup.server_name.clone(),
startup.tx_event.clone(),
&startup.client_mcp_extensions,
)));
}
client
@@ -598,59 +387,29 @@ impl AsyncManagedClient {
.shared();
(client, Some(connection_slot))
} else {
(startup.start(/*sharing_declined*/ None, publish_apps), None)
(startup.start(/*sharing_declined*/ None), None)
};
let startup_reconnect = is_codex_apps_mcp_server.then(|| {
let startup = Arc::clone(&startup);
Arc::new(
CodexAppsStartupReconnect::new(Arc::new(move || {
startup.start(/*sharing_declined*/ None, /*publish_apps*/ None)
}))
.with_startup_status_context(
startup_submit_id,
reconnect_server_name,
reconnect_tx_event,
),
)
});
Self {
client,
ema_authority,
is_codex_apps_mcp_server,
cached_server_info,
server_capabilities,
codex_apps_tools_cache_context,
tool_catalog_cache_context: advertised_catalog,
startup_complete,
startup_reconnect,
connection_slot,
cancel_token,
}
}
pub(crate) async fn client(&self) -> Result<ManagedClient, StartupOutcomeError> {
if let Some(client) = self
.startup_reconnect
.as_ref()
.and_then(|reconnect| reconnect.current_client())
{
return Ok(client);
}
self.client.clone().await
}
/// Returns the current ready client, including its tool catalog and metadata,
/// without waiting for startup or initiating a reconnection.
pub(crate) fn ready_client(&self) -> Option<ManagedClient> {
self.startup_reconnect
.as_ref()
.and_then(|reconnect| reconnect.current_client())
.or_else(|| {
self.client
.peek()
.and_then(|result| result.as_ref().ok())
.cloned()
})
self.client
.peek()
.and_then(|result| result.as_ref().ok())
.cloned()
}
pub(crate) fn ready_transport(&self) -> Option<Arc<RmcpClient>> {
@@ -684,18 +443,6 @@ impl AsyncManagedClient {
.shared();
}
pub(crate) async fn reconnect_failed_startup(&self) {
let Some(startup_reconnect) = self.startup_reconnect.as_ref() else {
return;
};
if !self.startup_complete.load(Ordering::Acquire) {
return;
}
if matches!(self.client().await, Err(StartupOutcomeError::Failed { .. })) {
let _ = startup_reconnect.reconnect_in_background();
}
}
pub(crate) async fn shutdown(&self) {
self.cancel_token.cancel();
match self.client().await {
@@ -725,41 +472,21 @@ impl AsyncManagedClient {
}
pub(crate) fn has_cached_tools(&self) -> bool {
self.codex_apps_tools_cache_context
self.tool_catalog_cache_context
.as_ref()
.is_some_and(ConnectorRuntimeContext::has_current_tools)
|| self
.tool_catalog_cache_context
.as_ref()
.is_some_and(McpToolCatalogCacheContext::has_tools)
.is_some_and(McpToolCatalogCacheContext::has_tools)
}
pub(crate) fn cached_tools_or(&self, fallback: Option<Vec<ToolInfo>>) -> Option<Vec<ToolInfo>> {
self.codex_apps_tools_cache_context
self.tool_catalog_cache_context
.as_ref()
.and_then(ConnectorRuntimeContext::current_tools)
.or_else(|| {
self.tool_catalog_cache_context
.as_ref()
.and_then(|cache| cache.current_tools_or(fallback))
})
.and_then(|cache| cache.current_tools_or(fallback))
}
pub(crate) fn cached_catalog(&self) -> Option<(Vec<ToolInfo>, Option<Arc<serde_json::Value>>)> {
self.codex_apps_tools_cache_context
self.tool_catalog_cache_context
.as_ref()
.and_then(|context| {
context
.current_catalog_snapshot()
.map(|snapshot| (snapshot.tools().to_vec(), snapshot.shared_tool_list_meta()))
// Older caches still supply tools without discovery-scoped metadata.
.or_else(|| context.current_tools().map(|tools| (tools, None)))
})
.or_else(|| {
self.tool_catalog_cache_context
.as_ref()
.and_then(|cache| cache.current_catalog_or(/*fallback*/ None))
})
.and_then(|cache| cache.current_catalog_or(/*fallback*/ None))
}
pub(crate) async fn listed_catalog(
@@ -772,7 +499,6 @@ impl AsyncManagedClient {
} else {
match self.client().await {
Ok(client) => Ok(client.listed_catalog().await),
Err(error) if self.is_codex_apps_mcp_server => self.cached_catalog().ok_or(error),
Err(error) => Err(error),
}
}
@@ -789,7 +515,6 @@ pub(crate) enum StartupOutcomeError {
Failed {
error: String,
is_authentication_required: bool,
is_ema_authentication_required: bool,
shutdown: Option<StartupShutdown>,
},
}
@@ -824,9 +549,6 @@ impl From<anyhow::Error> for StartupOutcomeError {
Self::Failed {
error: format!("{error:#}"),
is_authentication_required,
is_ema_authentication_required: is_authentication_required
&& (error.downcast_ref::<EmaTokenSourceError>().is_some()
|| error.downcast_ref::<EmaAuthFailure>().is_some()),
shutdown: None,
}
}
@@ -835,8 +557,6 @@ impl From<anyhow::Error> for StartupOutcomeError {
#[instrument(level = "trace", skip_all, fields(server_name = %server_name))]
pub(crate) async fn list_tools_for_client_uncached(
server_name: &str,
is_codex_apps_mcp_server: bool,
codex_apps_refresh_trigger: &'static str,
client: &Arc<RmcpClient>,
timeout: Option<Duration>,
catalog_item_limit: usize,
@@ -863,54 +583,19 @@ pub(crate) async fn list_tools_for_client_uncached(
})
.await?
.into_iter()
.map(|tool| {
tool_info_from_listed_tool(
server_name,
is_codex_apps_mcp_server,
server_instructions,
tool,
)
})
.map(|tool| regular_mcp_tool_info_from_listed_tool(server_name, server_instructions, tool))
.collect();
if is_codex_apps_mcp_server {
emit_duration(
MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC,
fetch_start.elapsed(),
&[("trigger", codex_apps_refresh_trigger)],
);
} else {
emit_duration(
MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC,
fetch_start.elapsed(),
&[],
);
}
emit_duration(
MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC,
fetch_start.elapsed(),
&[],
);
let meta = meta
.into_inner()
.unwrap_or_else(std::sync::PoisonError::into_inner);
Ok((tools, meta))
}
/// Filters disabled connectors and adds plugin names to each tool. Plugin membership is resolved by
/// connector ID, falling back to the MCP server when absent.
pub(crate) fn prepare_codex_apps_tools_for_model(
mut tools: Vec<ToolInfo>,
tool_plugin_context: &ToolPluginContext,
) -> Vec<ToolInfo> {
tools.retain(|tool| tool_plugin_context.allows_connector_id(tool.connector_id.as_deref()));
for tool in &mut tools {
let plugin_names = match tool.connector_id.as_deref() {
Some(connector_id) => {
tool_plugin_context.plugin_display_names_for_connector_id(connector_id)
}
None => tool_plugin_context
.plugin_display_names_for_mcp_server_name(tool.server_name.as_str()),
};
add_plugin_provenance_to_tool(tool, plugin_names);
}
tools
}
/// Stores plugin names on the tool and appends a model-visible plugin membership note.
fn add_plugin_provenance_to_tool(tool: &mut ToolInfo, plugin_names: &[String]) {
tool.plugin_display_names = plugin_names.to_vec();
@@ -980,64 +665,6 @@ pub(crate) fn prepare_regular_mcp_tools_for_model(
tools
}
fn tool_info_from_listed_tool(
server_name: &str,
is_codex_apps_mcp_server: bool,
server_instructions: Option<&str>,
tool: ToolWithConnectorId,
) -> ToolInfo {
if is_codex_apps_mcp_server {
codex_apps_tool_info_from_listed_tool(server_name, server_instructions, tool)
} else {
regular_mcp_tool_info_from_listed_tool(server_name, server_instructions, tool)
}
}
/// Converts a Codex Apps tool by preserving connector fields, removing connector prefixes from
/// model-visible names and titles, and using the connector description for its tool namespace.
fn codex_apps_tool_info_from_listed_tool(
server_name: &str,
server_instructions: Option<&str>,
tool: ToolWithConnectorId,
) -> ToolInfo {
let mut tool_def = tool.tool;
let connector_id = tool.connector_id;
let connector_name = tool.connector_name;
let connector_description = tool.connector_description;
let callable_name = normalize_codex_apps_callable_name(
&tool_def.name,
connector_id.as_deref(),
connector_name.as_deref(),
);
let callable_namespace =
normalize_codex_apps_callable_namespace(server_name, connector_name.as_deref());
if let Some(title) = tool_def.title.as_deref() {
let normalized_title = normalize_codex_apps_tool_title(connector_name.as_deref(), title);
if tool_def.title.as_deref() != Some(normalized_title.as_str()) {
tool_def.title = Some(normalized_title);
}
}
let has_connector_metadata =
connector_id.is_some() || connector_name.is_some() || connector_description.is_some();
let namespace_description = if has_connector_metadata {
connector_description
} else {
server_instructions.map(str::to_string)
};
ToolInfo {
server_name: server_name.to_owned(),
supports_parallel_tool_calls: false,
server_origin: None,
callable_name,
callable_namespace,
namespace_description,
tool: tool_def,
connector_id,
connector_name,
plugin_display_names: Vec::new(),
}
}
/// Converts a regular MCP tool by removing reserved connector metadata, keeping its raw tool name,
/// and using the MCP server name and instructions for the model-visible namespace.
fn regular_mcp_tool_info_from_listed_tool(
@@ -1055,8 +682,6 @@ fn regular_mcp_tool_info_from_listed_tool(
callable_namespace: server_name.to_string(),
namespace_description: server_instructions.map(str::to_string),
tool: tool_def,
connector_id: None,
connector_name: None,
plugin_display_names: Vec::new(),
}
}
@@ -1124,12 +749,9 @@ async fn start_server_task(
) -> Result<ManagedClient, StartupOutcomeError> {
let StartServerTaskParams {
sharing_declined,
publish_apps,
is_codex_apps_mcp_server,
startup_timeout,
tx_event,
elicitation_requests,
codex_apps_tools_cache_context,
mut tool_catalog_cache_context,
tool_catalog_fetch_ticket,
client_elicitation_capability,
@@ -1139,7 +761,7 @@ async fn start_server_task(
server_capabilities,
} = params;
let send_elicitation =
elicitation_requests.make_sender(server_name.clone(), tx_event, &client_mcp_extensions);
elicitation_requests.make_sender(server_name.clone(), tx_event);
let client_supports_network_policy_meta =
client_mcp_extensions.contains(MCP_NETWORK_POLICY_META_CAPABILITY);
let (sharing_negotiation, send_elicitation) = if let Some(sharing_declined) = sharing_declined {
@@ -1168,14 +790,12 @@ async fn start_server_task(
);
}
let requested_capabilities = params.capabilities.clone();
let started_at = Instant::now();
let initialize_result = client
.initialize(params, startup_timeout, send_elicitation)
.await;
record_protocol_discovery_metrics(
client.protocol_mode(),
is_codex_apps_mcp_server,
started_at,
&initialize_result,
);
@@ -1224,36 +844,11 @@ async fn start_server_task(
exp.contains_key(crate::MCP_SANDBOX_STATE_CAPABILITY)
|| exp.contains_key(crate::MCP_SANDBOX_STATE_META_CAPABILITY)
});
let codex_apps_tools_cache_context = codex_apps_tools_cache_context.map(|context| {
if server_disables_tool_catalog_cache {
context.without_live_scope()
} else {
// Converted tools can inherit these instructions. Server capabilities and the
// negotiated protocol can also differ between otherwise identical connections.
let mut scope = serde_json::json!([
requested_capabilities,
initialize_result.protocol_version,
initialize_result.capabilities,
initialize_result.instructions,
initialize_result.server_info,
]);
scope.sort_all_objects();
context.with_live_scope(scope.to_string())
}
});
let list_start = Instant::now();
let server_info =
mcp_server_info_from_implementation(&server_name, initialize_result.server_info);
let fetch_ticket = codex_apps_tools_cache_context
.as_ref()
.map(|context| context.begin_fetch(ConnectorRuntimeFetchSource::Startup));
if let Some(tx) = &publish_apps {
tx.send_replace(Some(Arc::downgrade(&client)));
}
let (tools, meta) = list_tools_for_client_uncached(
&server_name,
is_codex_apps_mcp_server,
/*codex_apps_refresh_trigger*/ "initial",
&client,
startup_timeout,
catalog_item_limit,
@@ -1261,23 +856,7 @@ async fn start_server_task(
)
.await
.map_err(StartupOutcomeError::from)?;
let client_tools: Arc<[ToolInfo]> =
match (codex_apps_tools_cache_context.as_ref(), fetch_ticket) {
(Some(context), Some(ticket)) if server_disables_tool_catalog_cache => {
context.publish_runtime_if_newest_accepted(
ticket,
&server_info,
tools.clone(),
meta.clone(),
);
tools.into()
}
(Some(context), Some(ticket)) => context
.publish_runtime_if_newest_accepted(ticket, &server_info, tools, meta.clone())
.shared_tools(),
(None, None) => tools.into(),
_ => unreachable!("Codex Apps fetch ticket requires cache context"),
};
let client_tools: Arc<[ToolInfo]> = tools.into();
if let (Some(cache_context), Some(mut fetch_ticket)) = (
tool_catalog_cache_context.as_ref(),
tool_catalog_fetch_ticket,
@@ -1289,7 +868,7 @@ async fn start_server_task(
}
cache_context.publish_if_newest(fetch_ticket, &client_tools, meta.clone());
}
if is_codex_apps_mcp_server || tool_catalog_cache_context.is_some() {
if tool_catalog_cache_context.is_some() {
emit_duration(
MCP_TOOLS_LIST_DURATION_METRIC,
list_start.elapsed(),
@@ -1302,18 +881,11 @@ async fn start_server_task(
_auth_change_notifications: auth_change_notifications,
client: Arc::clone(&client),
server_info,
tool_catalog: Arc::new(ClientToolCatalog::new(
client_tools,
meta,
codex_apps_tools_cache_context
.as_ref()
.and_then(ConnectorRuntimeContext::subscribe),
)),
tool_catalog: Arc::new(ClientToolCatalog::new(client_tools, meta)),
tool_timeout: None,
server_instructions: initialize_result.instructions,
server_supports_sandbox_state_meta_capability,
client_supports_network_policy_meta_capability: client_supports_network_policy_meta,
codex_apps_tools_cache_context,
};
Ok(managed)
@@ -1321,7 +893,6 @@ async fn start_server_task(
fn record_protocol_discovery_metrics(
mode: McpProtocolMode,
is_codex_apps_mcp_server: bool,
started_at: Instant,
result: &Result<ServerPeerInfo>,
) {
@@ -1338,10 +909,7 @@ fn record_protocol_discovery_metrics(
Ok(_) => "legacy",
Err(_) => "failure",
};
let mut tags = vec![("mode", mode), ("outcome", outcome)];
if is_codex_apps_mcp_server {
tags.push(("server_kind", "openai_codex_apps"));
}
let tags = [("mode", mode), ("outcome", outcome)];
let _ = metrics.counter("codex.mcp.protocol_discovery", /*inc*/ 1, &tags);
let _ = metrics.record_duration(
"codex.mcp.protocol_discovery.duration_ms",
@@ -1404,14 +972,11 @@ fn mcp_server_info_from_implementation(
}
struct StartServerTaskParams {
publish_apps: Option<watch::Sender<Option<std::sync::Weak<RmcpClient>>>>,
sharing_declined: Option<CancellationToken>,
server_capabilities: Arc<StdMutex<Option<serde_json::Value>>>,
is_codex_apps_mcp_server: bool,
startup_timeout: Option<Duration>, // TODO: cancel_token should handle this.
tx_event: Option<Sender<Event>>,
elicitation_requests: ElicitationRequestManager,
codex_apps_tools_cache_context: Option<ConnectorRuntimeContext<ToolInfo>>,
tool_catalog_cache_context: Option<McpToolCatalogCacheContext>,
tool_catalog_fetch_ticket: Option<McpToolCatalogFetchTicket>,
client_elicitation_capability: ElicitationCapability,
@@ -1423,7 +988,6 @@ struct StartServerTaskParams {
#[allow(clippy::too_many_arguments)]
#[instrument(level = "trace", skip_all, fields(server_name = %server_name))]
pub(crate) async fn make_rmcp_client(
ema_auth: Option<Result<crate::ema_auth::EmaConnectionAuth, StartupOutcomeError>>,
server_name: &str,
server: EffectiveMcpServer,
store_mode: OAuthCredentialsStoreMode,
@@ -1431,7 +995,6 @@ pub(crate) async fn make_rmcp_client(
oauth_refresh_mode: McpOAuthRefreshMode,
runtime_context: McpRuntimeContext,
resolved_environment: std::result::Result<Option<Arc<Environment>>, String>,
runtime_auth_provider: Option<McpAuthProvider>,
protocol_mode: McpProtocolMode,
) -> Result<RmcpClient, StartupOutcomeError> {
let config = server.config().clone();
@@ -1453,22 +1016,10 @@ pub(crate) async fn make_rmcp_client(
}
}
if matches!(config.auth, McpServerAuth::EmaAuth) {
let auth = ema_auth.ok_or_else(|| {
StartupOutcomeError::from(anyhow!(
"enterprise MCP requires a thread with an account owner"
))
})??;
return auth
.owner
.connect(
auth.authority,
server_name,
&server,
runtime_context.local_http_client(),
protocol_mode,
)
.await
.map_err(Into::into);
// Never fall back to another credential for a server that required EMA.
return Err(StartupOutcomeError::from(anyhow!(
"MCP server '{server_name}' uses enterprise-managed authorization (`auth = \"ema_auth\"`), which is not supported"
)));
}
if matches!(config.auth, McpServerAuth::ChatGpt)
&& !config.is_local_environment()
@@ -1537,13 +1088,6 @@ pub(crate) async fn make_rmcp_client(
bearer_token_env_var,
http_headers_helper: _,
} => {
let (runtime_auth_provider, runtime_context) = match runtime_auth_provider {
Some(provider) => {
let (provider, context) = provider.resolve(runtime_context, &url).await?;
(Some(provider), context)
}
None => (None, runtime_context),
};
let http_client = runtime_context
.http_client_for_server(server.config(), resolved_environment.as_ref())
.map_err(|error| StartupOutcomeError::from(anyhow!(error)))?;
@@ -1600,7 +1144,7 @@ pub(crate) async fn make_rmcp_client(
store_mode,
keyring_backend_kind,
http_client,
runtime_auth_provider,
/*auth_provider*/ None,
protocol_mode,
redirect_mode,
oauth_refresh_mode,
@@ -1762,40 +1306,6 @@ mod tests {
);
}
#[test]
fn codex_apps_connector_metadata_is_preserved() {
let tool = tool_with_connector_meta();
let expected_tool = tool.clone();
let tool_info = tool_info_from_listed_tool(
CODEX_APPS_MCP_SERVER_NAME,
/*is_codex_apps_mcp_server*/ true,
/*server_instructions*/ None,
ToolWithConnectorId {
tool,
connector_id: Some("connector_gmail".to_string()),
connector_name: Some("Gmail".to_string()),
connector_description: Some("Mail connector".to_string()),
},
);
let expected = ToolInfo {
server_name: CODEX_APPS_MCP_SERVER_NAME.to_string(),
supports_parallel_tool_calls: false,
server_origin: None,
callable_name: "capture_file_upload".to_string(),
callable_namespace: "codex_apps__gmail".to_string(),
namespace_description: Some("Mail connector".to_string()),
tool: expected_tool,
connector_id: Some("connector_gmail".to_string()),
connector_name: Some("Gmail".to_string()),
plugin_display_names: Vec::new(),
};
assert_eq!(
serde_json::to_value(tool_info).expect("serialize actual tool info"),
serde_json::to_value(expected).expect("serialize expected tool info")
);
}
}
#[cfg(test)]

View File

@@ -4,16 +4,12 @@
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;
@@ -37,7 +33,6 @@ pub(crate) struct ManagedClient {
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 {
@@ -159,26 +154,8 @@ impl ManagedClient {
}
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)
})
.read(|catalog| (catalog.tools.to_vec(), catalog.meta))
.await
}
}

View File

@@ -4,13 +4,12 @@ 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,
regular_mcp_tool_info_from_listed_tool(
"docs",
/*server_instructions*/ None,
ToolWithConnectorId {
tool: RmcpTool::new("search", description.to_string(), Arc::default()),
connector_id: Some("shared-connector".to_string()),
connector_id: None,
connector_name: None,
connector_description: None,
},

View File

@@ -10,23 +10,7 @@ impl AsyncManagedClient {
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());
let outcome = self.client.peek().cloned();
match outcome {
Some(Ok(client)) => {
if client.client.is_closed().await {

View File

@@ -3,8 +3,7 @@
//! This module contains the thread-owned MCP runtime and data that describes the
//! environment in which MCP servers execute. Transport startup lives in
//! [`crate::rmcp_client`] and connection-set behavior lives in
//! [`crate::connection_manager`]. Registry removal revokes EMA authority before
//! the thread becomes untracked.
//! [`crate::connection_manager`].
mod status;
@@ -17,7 +16,6 @@ use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
@@ -27,21 +25,16 @@ use std::time::Duration;
use arc_swap::ArcSwap;
use async_channel::Sender;
use codex_config::types::McpServerDisabledReason;
use codex_connectors::ConnectorRuntimeContextKey;
use codex_connectors::ConnectorRuntimeManager;
use codex_exec_server::Environment;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::HttpClient;
use codex_exec_server::RouteAwareHttpClient;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_protocol::ThreadId;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::mcp::McpResourceOriginCheckpoint;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_rmcp_client::ElicitationResponse;
use codex_rmcp_client::with_http_headers_helper;
@@ -55,7 +48,6 @@ use tracing::warn;
use crate::McpConfig;
use crate::binding::McpBinding;
use crate::binding::PreparedMcpCall;
use crate::client_tool_catalog::CodexAppsToolSnapshot;
use crate::connection_manager::BindingCatalogRevision;
use crate::connection_manager::McpConnectionSet;
use crate::connection_manager::PreviousMcpConnections;
@@ -63,10 +55,7 @@ use crate::connection_pool::McpConnectionPool;
use crate::elicitation::ElicitationLifecycle;
use crate::elicitation::ElicitationRequestRouter;
use crate::elicitation::ElicitationReviewerHandle;
use crate::event_stream::McpEventStreamOpener;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::resource_client::McpResourceServerCacheKey;
use crate::resource_origin::ResourceOrigins;
use crate::server::EffectiveMcpServer;
use crate::tool_catalog_cache::McpToolCatalogCache;
use crate::tools::ToolInfo;
@@ -104,16 +93,10 @@ pub struct McpRuntimeInput {
pub tx_event: Option<Sender<Event>>,
pub startup_cancellation_token: CancellationToken,
pub runtime_context: McpRuntimeContext,
pub codex_apps_tools_cache: ConnectorRuntimeManager<ToolInfo>,
pub tool_catalog_cache: McpToolCatalogCache,
pub codex_apps_tools_cache_key: ConnectorRuntimeContextKey,
pub client_mcp_extensions: ClientMcpExtensions,
pub auth: Option<CodexAuth>,
pub auth_manager: Option<Arc<AuthManager>>,
pub runtime_auth: Option<(
codex_runtime_agent_instance::RuntimeAuthSlot,
codex_features::RuntimeAuthMode,
)>,
pub elicitation_reviewer: Option<ElicitationReviewerHandle>,
pub elicitation_lifecycle: Option<ElicitationLifecycle>,
}
@@ -126,18 +109,9 @@ pub struct McpRuntime {
current: ArcSwap<PublishedMcpRuntime>,
// Old bindings keep leases alive after publication; cancellation alone does not release them.
superseded_connections: Mutex<Vec<Weak<McpConnectionSet>>>,
event_stream_cancellation: Mutex<EventStreamCancellation>,
reconnect_pending: AtomicBool,
resource_cache_generation: AtomicU64,
elicitation_router: ElicitationRequestRouter,
resource_origins: Mutex<ResourceOrigins>,
ema_auth: OnceLock<crate::ema_auth::EmaAuthContext>,
}
struct EventStreamCancellation {
event_server_available: bool,
cancel_event_streams_on_server_removal: watch::Sender<()>,
retained_subscription_cancellation: Option<watch::Sender<()>>,
}
struct PublishedMcpRuntime {
@@ -172,35 +146,12 @@ impl AuthOwner {
}
}
fn ensure_host_owned_apps_registration(
current: &PublishedMcpRuntime,
server: &str,
) -> anyhow::Result<()> {
if !current
.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())
})
{
anyhow::bail!("MCP server '{server}' is not registered by the hosted runtime");
}
Ok(())
}
impl PublishedMcpRuntime {
// Shared by dirty detection and cache-key publication so their auth rules agree.
fn auth_matches(&self, auth: Option<&CodexAuth>) -> bool {
match (self.auth.as_ref(), auth) {
(Some(previous), Some(latest)) => {
previous == latest
&& previous.get_account_id() == latest.get_account_id()
&& previous.get_chatgpt_user_id() == latest.get_chatgpt_user_id()
&& previous.is_fedramp_account() == latest.is_fedramp_account()
&& self.auth_token == latest.get_token().ok()
previous == latest && self.auth_token == latest.get_token().ok()
}
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
@@ -284,72 +235,12 @@ impl McpRuntime {
cached_binding: Mutex::new(None),
}),
superseded_connections: Mutex::default(),
event_stream_cancellation: Mutex::new(EventStreamCancellation {
event_server_available: false,
cancel_event_streams_on_server_removal: watch::channel(()).0,
retained_subscription_cancellation: None,
}),
reconnect_pending: AtomicBool::new(false),
resource_cache_generation: AtomicU64::new(0),
elicitation_router: ElicitationRequestRouter::default(),
resource_origins: Mutex::default(),
ema_auth: OnceLock::new(),
}
}
/// Updates this thread's bounded resource provenance from a live or restored event.
pub fn observe_event(&self, event: &EventMsg) {
if !matches!(
event,
EventMsg::TurnStarted(_)
| EventMsg::ItemCompleted(_)
| EventMsg::McpToolCallEnd(_)
| EventMsg::ThreadRolledBack(_)
) {
return;
}
self.resource_origins
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.observe(event);
}
/// Captures bounded widget provenance for the next compaction checkpoint.
pub fn resource_origin_checkpoint(&self) -> Option<McpResourceOriginCheckpoint> {
self.resource_origins
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.checkpoint()
}
/// Restores widget provenance retained by a compaction checkpoint.
pub fn restore_resource_origin_checkpoint(&self, checkpoint: &McpResourceOriginCheckpoint) {
self.resource_origins
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.restore_checkpoint(checkpoint);
}
/// Reads a widget through the current binding of the app tool that produced it.
pub async fn read_resource_for_call(
&self,
thread_id: ThreadId,
call_id: &str,
params: ReadResourceRequestParams,
) -> anyhow::Result<ReadResourceResult> {
let origin = self
.resource_origins
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.find(call_id)?;
let binding = self
.current_binding_for_call(crate::CODEX_APPS_MCP_SERVER_NAME)
.await
.ok_or_else(|| anyhow::anyhow!("codex_apps MCP server is unavailable"))?;
origin.read(&binding, thread_id, params).await
}
pub async fn new(input: McpRuntimeInput) -> Self {
let runtime = Self::empty(input.config.prefix_mcp_tool_names);
runtime.replace(input).await;
@@ -367,47 +258,9 @@ impl McpRuntime {
reconnect.claimed = false;
}
/// Starts fresh connections and returns their complete, refreshed Apps catalog.
pub async fn replace_fresh(&self, input: McpRuntimeInput) -> anyhow::Result<Vec<ToolInfo>> {
self.publish(input, /*reuse_previous*/ false).await;
self.latest_hard_refresh_codex_apps_tools_cache().await
}
/// Revoke a removed thread's EMA access before releasing the registry lock.
pub fn revoke_ema(&self) {
if let Some(Ok(auth)) = self.ema_auth.get() {
auth.authority.revoke();
}
}
/// Drain EMA responses after its configuration binding has been revoked.
pub async fn quiesce_ema(&self) {
if let Some(Ok(auth)) = self.ema_auth.get() {
auth.authority.revoke();
auth.authority.quiesce().await;
}
}
async fn publish(&self, input: McpRuntimeInput, reuse_previous: bool) {
let current = self.current.load_full();
let retain_ema = current.config.is_some();
let ema_auth = (input.config.xaa_enabled
&& input.mcp_servers.values().any(|server| {
server.config().enabled
&& matches!(server.config().auth, codex_config::McpServerAuth::EmaAuth)
}))
.then(|| {
self.ema_auth
.get_or_init(|| {
crate::ema_auth::EmaAuth::new(
Arc::clone(&input.config),
input.auth.as_ref(),
input.auth_manager.as_ref(),
)
.map_err(Into::into)
})
.clone()
});
let has_predecessor = current.config.is_some();
let (publish, publication_gate) = McpPublicationGate::pending();
let config = Arc::clone(&input.config);
let auth = input.auth.clone();
@@ -442,8 +295,7 @@ impl McpRuntime {
// Keep MCP startup state out of the caller's nested session-initialization future.
let connections = Arc::new(
Box::pin(McpConnectionSet::new(
ema_auth,
retain_ema.then_some(current.connections.as_ref()),
has_predecessor.then_some(current.connections.as_ref()),
reuse_previous.then_some(PreviousMcpConnections {
connections: &current.connections,
same_owner,
@@ -454,19 +306,6 @@ impl McpRuntime {
))
.await,
);
let hosted_event_server_retained = connections.contains_server(CODEX_APPS_MCP_SERVER_NAME)
&& config
.mcp_server_catalog
.server(CODEX_APPS_MCP_SERVER_NAME)
.is_some_and(|registration| {
registration
.source()
.is_host_owned_apps(CODEX_APPS_MCP_SERVER_NAME, registration.config())
});
let mut cancellation = self
.event_stream_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
{
let mut superseded = self
.superseded_connections
@@ -490,15 +329,6 @@ impl McpRuntime {
cached_binding: Mutex::new(None),
}));
let _ = publish.send(true);
cancellation.event_server_available = hosted_event_server_retained;
if !hosted_event_server_retained {
cancellation
.cancel_event_streams_on_server_removal
.send_replace(());
if let Some(retained) = &cancellation.retained_subscription_cancellation {
retained.send_replace(());
}
}
}
/// Ensures the next refresh creates fresh connections for every configured server.
@@ -732,34 +562,6 @@ impl McpRuntime {
.await
}
pub async fn latest_hard_refresh_codex_apps_tools_cache(
&self,
) -> anyhow::Result<Vec<ToolInfo>> {
self.latest_connections()
.refresh_codex_apps_tools_for_discovery()
.await
}
/// Refreshes the published Apps client and returns its exact inventory and MCP eligibility.
pub async fn refresh_codex_apps_tools(&self) -> anyhow::Result<CodexAppsToolSnapshot> {
let current = self.current.load_full();
let config = current
.config
.as_deref()
.ok_or_else(|| anyhow::anyhow!("MCP runtime is not configured"))?;
current
.connections
.refresh_codex_apps_client_catalog(config)
.await
}
/// Returns tools from this thread’s ready, unshared Apps MCP client.
/// Returns an empty list if the client is absent, still starting, or uses
/// a shared catalog. Does not start or wait for discovery.
pub async fn apps_tools_from_mcp_client(&self) -> Vec<ToolInfo> {
self.latest_connections().apps_tools_from_mcp_client().await
}
/// Lists the latest known tools for non-model discovery surfaces.
///
/// Unlike [`Self::current_binding`], this may return cached tools while their
@@ -917,70 +719,6 @@ impl McpRuntime {
Arc::clone(&self.current.load().connections)
}
pub(crate) fn latest_host_owned_codex_apps_connections(
&self,
) -> anyhow::Result<Arc<McpConnectionSet>> {
let current = self.current.load();
ensure_host_owned_apps_registration(&current, CODEX_APPS_MCP_SERVER_NAME)?;
Ok(Arc::clone(&current.connections))
}
pub(crate) fn latest_connections_for_event_server(
&self,
server: &str,
) -> anyhow::Result<(Arc<McpConnectionSet>, watch::Receiver<()>)> {
let cancellation = self
.event_stream_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let cancel_event_streams_on_server_removal = cancellation
.cancel_event_streams_on_server_removal
.subscribe();
let current = self.current.load();
if server == CODEX_APPS_MCP_SERVER_NAME {
ensure_host_owned_apps_registration(&current, server)?;
}
Ok((
Arc::clone(&current.connections),
cancel_event_streams_on_server_removal,
))
}
pub(crate) fn event_stream_opener(&self) -> anyhow::Result<McpEventStreamOpener> {
let cancellation = self
.event_stream_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let connection = self
.current
.load()
.connections
.event_stream_connection
.clone()
.ok_or_else(|| anyhow::anyhow!("Event subscriptions are unavailable for this task"))?;
let cancel_event_streams_on_server_removal = cancellation
.retained_subscription_cancellation
.as_ref()
.unwrap_or(&cancellation.cancel_event_streams_on_server_removal)
.clone();
Ok(McpEventStreamOpener {
connection,
cancellation_receiver: cancel_event_streams_on_server_removal.subscribe(),
cancel_event_streams_on_server_removal,
})
}
pub(crate) fn forward_event_server_removals_to(&self, retained: watch::Sender<()>) {
let mut cancellation = self
.event_stream_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !cancellation.event_server_available {
retained.send_replace(());
}
cancellation.retained_subscription_cancellation = Some(retained);
}
pub async fn shutdown(&self) {
self.elicitation_router.close().await;
let superseded = std::mem::take(
@@ -1091,14 +829,6 @@ impl McpRuntimeContext {
self.local_process_cwd.clone()
}
pub(crate) fn http_client_factory(&self) -> codex_http_client::HttpClientFactory {
self.environment_manager.http_client_factory().clone()
}
pub(crate) fn set_local_http_client(&mut self, client: Arc<dyn HttpClient>) {
self.local_http_client = client;
}
pub(crate) fn local_http_client(&self) -> Arc<dyn HttpClient> {
Arc::clone(&self.local_http_client)
}
@@ -1231,27 +961,16 @@ mod tests {
#[tokio::test]
async fn cached_bindings_follow_the_clients_catalog_revision() -> anyhow::Result<()> {
let codex_home = tempfile::tempdir()?;
let cache_context = ConnectorRuntimeManager::<ToolInfo>::default().context(
codex_home.path().to_path_buf(),
ConnectorRuntimeContextKey::personal(
/*account_id*/ None, /*chatgpt_user_id*/ None,
),
);
let connections =
crate::connection_manager::tests::create_test_manager_with_ready_apps_client(
cache_context,
"search",
/*list_started*/ None,
/*release_list*/ None,
)
.await?;
let connections = crate::connection_manager::tests::create_test_manager_with_ready_client(
"docs", "search", /*list_started*/ None, /*release_list*/ None,
)
.await?;
// Complete the fixture's shared startup future before testing stable reuse.
connections.list_all_tools().await;
let mut config = crate::mcp::tests::test_mcp_config(codex_home.path().to_path_buf());
config.server_permissions.insert(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
McpServerPermissions::Thread,
);
config
.server_permissions
.insert("docs".to_string(), McpServerPermissions::Thread);
let published = Arc::new(PublishedMcpRuntime {
connections: Arc::clone(&connections),
config: Some(Arc::new(config)),
@@ -1270,10 +989,7 @@ mod tests {
runtime.current.store(Arc::clone(&published));
runtime
.latest_call_tool_without_attribution(
CODEX_APPS_MCP_SERVER_NAME,
"search",
/*arguments*/ None,
/*meta*/ None,
"docs", "search", /*arguments*/ None, /*meta*/ None,
)
.await?;
assert!(published.cached_binding.lock().unwrap().is_none());
@@ -1293,7 +1009,16 @@ mod tests {
.expect("cached initial binding");
assert!(Arc::ptr_eq(&before, &repeated));
connections.refresh_codex_apps_tools_for_discovery().await?;
let client = connections
.test_client("docs")
.ready_client()
.expect("ready test client");
let mut refreshed_tool = crate::connection_manager::tests::create_test_tool("docs", "search");
refreshed_tool.tool.description = Some("refreshed".into());
client
.tool_catalog
.replace_for_test(vec![refreshed_tool])
.await;
let refreshed = McpRuntime::binding_from_published_runtime(
Arc::clone(&published),
@@ -1304,7 +1029,7 @@ mod tests {
.expect("refreshed binding");
assert!(!Arc::ptr_eq(&before, &refreshed));
let call = refreshed
.prepare_call(CODEX_APPS_MCP_SERVER_NAME, "search")
.prepare_call("docs", "search")
.expect("refreshed call");
let error = call
.call_with_preparation(/*requested_timeout*/ None, || async {

View File

@@ -40,24 +40,11 @@ impl McpRuntime {
&& 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;

View File

@@ -80,7 +80,6 @@ async fn forced_refresh_replaces_pending_connection_without_interrupting_other_c
}));
let input = McpRuntimeInput {
network_policy_metadata: None,
runtime_auth: None,
startup_policy: McpStartupPolicy::Eager,
config,
plugins_available: false,
@@ -90,11 +89,7 @@ async fn forced_refresh_replaces_pending_connection_without_interrupting_other_c
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,

View File

@@ -4,8 +4,6 @@ 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;
@@ -14,9 +12,7 @@ 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;
@@ -87,16 +83,9 @@ impl EffectiveMcpServer {
/// 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()
/// Servers that selected the removed enterprise-managed authorization never start.
pub(crate) fn can_discover_local_stdio(&self) -> bool {
self.config.is_local_environment()
&& !matches!(self.config.auth, McpServerAuth::EmaAuth)
&& self
.stdio_protocol_mode(McpProtocolMode::DiscoverLocalStdio)
@@ -176,10 +165,6 @@ pub(crate) struct McpServerConnectionIdentity {
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,
@@ -197,11 +182,7 @@ impl McpServerConnectionIdentity {
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_elicitation_capability: ElicitationCapability,
client_mcp_extensions: ClientMcpExtensions,
previous_identity: Option<&Self>,
) -> Self {
@@ -211,8 +192,7 @@ impl McpServerConnectionIdentity {
.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)
let stored_oauth_url = if !matches!(config.auth, McpServerAuth::EmaAuth)
&& (!matches!(config.auth, McpServerAuth::ChatGpt) || config.is_local_environment())
{
match &config.transport {
@@ -282,8 +262,6 @@ impl McpServerConnectionIdentity {
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()
@@ -306,10 +284,6 @@ impl McpServerConnectionIdentity {
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(),
@@ -318,19 +292,6 @@ impl McpServerConnectionIdentity {
}
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
@@ -346,10 +307,6 @@ impl McpServerConnectionIdentity {
&& 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

View File

@@ -75,10 +75,6 @@ fn connection_identity(
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,

View File

@@ -43,8 +43,6 @@ pub struct ToolInfo {
pub namespace_description: Option<String>,
/// Raw MCP tool definition; `tool.name` is sent back to the MCP server.
pub tool: Tool,
pub connector_id: Option<String>,
pub connector_name: Option<String>,
#[serde(default)]
pub plugin_display_names: Vec<String>,
}
@@ -125,12 +123,9 @@ where
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()
);
// The trailing separator keeps hashed names stable across catalog versions.
let raw_namespace_identity =
format!("{}\0{}\0", tool.server_name, tool.callable_namespace);
let raw_tool_identity = format!(
"{}\0{}\0{}",
raw_namespace_identity, tool.callable_name, tool.tool.name

View File

@@ -1,330 +0,0 @@
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

@@ -1,658 +0,0 @@
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

@@ -1,36 +0,0 @@
//! 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
}