Base: codex-main originale (prima del fork aKode)
This commit is contained in:
566
codex-rs/codex-mcp/src/mcp/auth.rs
Normal file
566
codex-rs/codex-mcp/src/mcp/auth.rs
Normal file
@@ -0,0 +1,566 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_config::McpServerAuth;
|
||||
use codex_config::McpServerConfig;
|
||||
use codex_config::McpServerTransportConfig;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_config::types::OAuthCredentialsStoreMode;
|
||||
use codex_exec_server::HttpClient;
|
||||
use codex_login::AccountOAuthGrant;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_rmcp_client::McpAuthState;
|
||||
use codex_rmcp_client::McpLoginRequirement;
|
||||
use codex_rmcp_client::McpOAuthCallbackMode;
|
||||
use codex_rmcp_client::OAuthDiscoveryTimeout;
|
||||
use codex_rmcp_client::OAuthProviderError;
|
||||
use codex_rmcp_client::StreamableHttpRedirectMode;
|
||||
use codex_rmcp_client::determine_streamable_http_auth_status;
|
||||
use codex_rmcp_client::determine_streamable_http_auth_status_from_credentials;
|
||||
use codex_rmcp_client::discover_streamable_http_oauth;
|
||||
use codex_rmcp_client::resolve_mcp_oauth_callback_url;
|
||||
use futures::FutureExt;
|
||||
use futures::future::join_all;
|
||||
use tokio::sync::OnceCell;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::runtime::McpRuntimeContext;
|
||||
use crate::server::EffectiveMcpServer;
|
||||
use crate::server::has_explicit_http_authorization;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct McpOAuthLoginConfig {
|
||||
pub url: String,
|
||||
pub http_headers: Option<HashMap<String, String>>,
|
||||
pub env_http_headers: Option<HashMap<String, String>>,
|
||||
pub discovered_scopes: Option<Vec<String>>,
|
||||
pub callback_mode: McpOAuthCallbackMode,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum McpOAuthLoginSupport {
|
||||
Supported(McpOAuthLoginConfig),
|
||||
Unsupported,
|
||||
Unknown(anyhow::Error),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum McpOAuthScopesSource {
|
||||
Explicit,
|
||||
Configured,
|
||||
Discovered,
|
||||
Empty,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResolvedMcpOAuthScopes {
|
||||
pub scopes: Vec<String>,
|
||||
pub source: McpOAuthScopesSource,
|
||||
}
|
||||
|
||||
/// Keeps registered callbacks tied to their client while preserving legacy redirects.
|
||||
pub fn resolve_oauth_callback(
|
||||
server: &McpServerConfig,
|
||||
server_url: &str,
|
||||
global_callback_url: Option<&str>,
|
||||
) -> Result<Option<String>> {
|
||||
if let Some(callback_url) = server
|
||||
.oauth
|
||||
.as_ref()
|
||||
.and_then(|oauth| oauth.callback_url.as_deref())
|
||||
{
|
||||
return Ok(Some(callback_url.to_string()));
|
||||
}
|
||||
|
||||
if server
|
||||
.oauth_client_id()
|
||||
.is_none_or(|client_id| client_id.trim().is_empty())
|
||||
{
|
||||
return Ok(global_callback_url.map(ToOwned::to_owned));
|
||||
}
|
||||
|
||||
resolve_mcp_oauth_callback_url(
|
||||
server_url,
|
||||
global_callback_url,
|
||||
McpOAuthCallbackMode::CallbackSpecific,
|
||||
)
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct McpAuthStatusEntry {
|
||||
pub config: Option<McpServerConfig>,
|
||||
pub auth_state: McpAuthState,
|
||||
}
|
||||
|
||||
pub async fn oauth_login_support(
|
||||
transport: &McpServerTransportConfig,
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
discovery_timeout: OAuthDiscoveryTimeout,
|
||||
redirect_mode: StreamableHttpRedirectMode,
|
||||
) -> McpOAuthLoginSupport {
|
||||
let Some(mut config) = oauth_login_candidate(transport) else {
|
||||
return McpOAuthLoginSupport::Unsupported;
|
||||
};
|
||||
match discover_streamable_http_oauth(
|
||||
&config.url,
|
||||
config.http_headers.clone(),
|
||||
config.env_http_headers.clone(),
|
||||
http_client,
|
||||
discovery_timeout,
|
||||
redirect_mode,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(discovery)) => {
|
||||
config.discovered_scopes = discovery.scopes_supported;
|
||||
config.callback_mode = discovery.callback_mode;
|
||||
McpOAuthLoginSupport::Supported(config)
|
||||
}
|
||||
Ok(None) => McpOAuthLoginSupport::Unsupported,
|
||||
Err(err) => McpOAuthLoginSupport::Unknown(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn oauth_login_candidate(transport: &McpServerTransportConfig) -> Option<McpOAuthLoginConfig> {
|
||||
let McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
bearer_token_env_var,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
..
|
||||
} = transport
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if bearer_token_env_var.is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(McpOAuthLoginConfig {
|
||||
url: url.clone(),
|
||||
http_headers: http_headers.clone(),
|
||||
env_http_headers: env_http_headers.clone(),
|
||||
discovered_scopes: None,
|
||||
callback_mode: McpOAuthCallbackMode::CallbackSpecific,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn discover_supported_scopes(
|
||||
transport: &McpServerTransportConfig,
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
discovery_timeout: OAuthDiscoveryTimeout,
|
||||
redirect_mode: StreamableHttpRedirectMode,
|
||||
) -> Option<Vec<String>> {
|
||||
match oauth_login_support(transport, http_client, discovery_timeout, redirect_mode).await {
|
||||
McpOAuthLoginSupport::Supported(config) => config.discovered_scopes,
|
||||
McpOAuthLoginSupport::Unsupported | McpOAuthLoginSupport::Unknown(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve_oauth_scopes(
|
||||
explicit_scopes: Option<Vec<String>>,
|
||||
configured_scopes: Option<Vec<String>>,
|
||||
discovered_scopes: Option<Vec<String>>,
|
||||
) -> ResolvedMcpOAuthScopes {
|
||||
if let Some(scopes) = explicit_scopes {
|
||||
return ResolvedMcpOAuthScopes {
|
||||
scopes,
|
||||
source: McpOAuthScopesSource::Explicit,
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(scopes) = configured_scopes {
|
||||
return ResolvedMcpOAuthScopes {
|
||||
scopes,
|
||||
source: McpOAuthScopesSource::Configured,
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(scopes) = discovered_scopes
|
||||
&& !scopes.is_empty()
|
||||
{
|
||||
return ResolvedMcpOAuthScopes {
|
||||
scopes,
|
||||
source: McpOAuthScopesSource::Discovered,
|
||||
};
|
||||
}
|
||||
|
||||
ResolvedMcpOAuthScopes {
|
||||
scopes: Vec::new(),
|
||||
source: McpOAuthScopesSource::Empty,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn should_retry_without_scopes(scopes: &ResolvedMcpOAuthScopes, error: &anyhow::Error) -> bool {
|
||||
scopes.source == McpOAuthScopesSource::Discovered
|
||||
&& error.downcast_ref::<OAuthProviderError>().is_some()
|
||||
}
|
||||
|
||||
pub async fn compute_auth_statuses<'a, I>(
|
||||
servers: I,
|
||||
store_mode: OAuthCredentialsStoreMode,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
auth: Option<&CodexAuth>,
|
||||
auth_manager: Option<&std::sync::Arc<codex_login::AuthManager>>,
|
||||
ema_state: &crate::EmaState,
|
||||
runtime_context: &McpRuntimeContext,
|
||||
) -> HashMap<String, McpAuthStatusEntry>
|
||||
where
|
||||
I: IntoIterator<Item = (&'a String, &'a EffectiveMcpServer)>,
|
||||
{
|
||||
// Share successful, missing, and failed reads without starting storage work for non-EMA servers.
|
||||
let account_grant = OnceCell::new();
|
||||
let futures = servers.into_iter().map(|(name, server)| {
|
||||
let account_grant = &account_grant;
|
||||
let name = name.clone();
|
||||
let redirect_mode = if server.is_agent_plugin() {
|
||||
StreamableHttpRedirectMode::AgentPluginV1
|
||||
} else {
|
||||
StreamableHttpRedirectMode::Legacy
|
||||
};
|
||||
let config = server.config().clone();
|
||||
let runtime_context = runtime_context.clone();
|
||||
async move {
|
||||
let auth_state = match compute_auth_status(
|
||||
&name,
|
||||
&config,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
auth,
|
||||
auth_manager,
|
||||
account_grant,
|
||||
ema_state,
|
||||
&runtime_context,
|
||||
redirect_mode,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(status) => status,
|
||||
Err(error) => {
|
||||
warn!("failed to determine auth status for MCP server `{name}`: {error:?}");
|
||||
McpAuthState::Unknown
|
||||
}
|
||||
};
|
||||
let entry = McpAuthStatusEntry {
|
||||
config: Some(config),
|
||||
auth_state,
|
||||
};
|
||||
(name, entry)
|
||||
}
|
||||
});
|
||||
|
||||
join_all(futures).await.into_iter().collect()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn compute_auth_status(
|
||||
server_name: &str,
|
||||
config: &McpServerConfig,
|
||||
store_mode: OAuthCredentialsStoreMode,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
auth: Option<&CodexAuth>,
|
||||
auth_manager: Option<&std::sync::Arc<codex_login::AuthManager>>,
|
||||
account_grant: &OnceCell<std::io::Result<Option<AccountOAuthGrant>>>,
|
||||
ema_state: &crate::EmaState,
|
||||
runtime_context: &McpRuntimeContext,
|
||||
redirect_mode: StreamableHttpRedirectMode,
|
||||
) -> Result<McpAuthState> {
|
||||
if !config.enabled {
|
||||
return Ok(McpAuthState::Unsupported);
|
||||
}
|
||||
if matches!(config.auth, McpServerAuth::EmaAuth) {
|
||||
let Some(registration) = config.ema_registration() else {
|
||||
return Ok(McpAuthState::Unsupported);
|
||||
};
|
||||
config
|
||||
.validate_ema_auth_transport()
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let Some(scope) = crate::ema_auth_scope(auth) else {
|
||||
return Ok(McpAuthState::LoggedOut(McpLoginRequirement::Login));
|
||||
};
|
||||
if matches!(auth, Some(CodexAuth::Chatgpt(_)))
|
||||
&& auth
|
||||
.and_then(|auth| auth.get_token_data().ok())
|
||||
.is_none_or(|tokens| tokens.login_owner_id.as_ref().is_none_or(String::is_empty))
|
||||
{
|
||||
return Ok(McpAuthState::LoggedOut(McpLoginRequirement::Login));
|
||||
}
|
||||
let account_usable = match auth_manager {
|
||||
Some(manager) => match account_grant
|
||||
.get_or_init(|| manager.account_oauth_grant())
|
||||
.await
|
||||
.as_ref()
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?
|
||||
{
|
||||
Some(grant) => {
|
||||
crate::ema_account::account_grant_is_usable(grant.tokens(), registration.idp())
|
||||
&& !ema_state.requires_sign_in(registration, grant.tokens())
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
None => auth.is_some_and(|auth| ema_state.account_is_usable(auth, registration)),
|
||||
};
|
||||
if account_usable {
|
||||
return Ok(McpAuthState::BearerToken);
|
||||
}
|
||||
return Ok(
|
||||
match crate::ema_auth::stored_ema_credentials(
|
||||
registration.idp(),
|
||||
&scope,
|
||||
keyring_backend_kind,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(snapshot)
|
||||
if codex_rmcp_client::stored_ema_identity_is_usable(
|
||||
snapshot.credentials(),
|
||||
®istration.idp().issuer,
|
||||
®istration.idp().client_id,
|
||||
) =>
|
||||
{
|
||||
McpAuthState::OAuth
|
||||
}
|
||||
Some(_) => McpAuthState::LoggedOut(McpLoginRequirement::Reauthentication),
|
||||
None => McpAuthState::LoggedOut(McpLoginRequirement::Login),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let has_runtime_auth = matches!(config.auth, McpServerAuth::ChatGpt)
|
||||
&& auth.is_some_and(CodexAuth::uses_codex_backend)
|
||||
&& matches!(
|
||||
&config.transport,
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
bearer_token_env_var: None,
|
||||
..
|
||||
}
|
||||
);
|
||||
|
||||
if matches!(config.auth, McpServerAuth::ChatGpt) && !config.is_local_environment() {
|
||||
return Ok(if has_explicit_http_authorization(config) {
|
||||
McpAuthState::BearerToken
|
||||
} else {
|
||||
McpAuthState::Unsupported
|
||||
});
|
||||
}
|
||||
|
||||
if has_runtime_auth {
|
||||
return Ok(McpAuthState::BearerToken);
|
||||
}
|
||||
|
||||
match &config.transport {
|
||||
McpServerTransportConfig::Stdio { .. } => Ok(McpAuthState::Unsupported),
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
bearer_token_env_var,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
http_headers_helper,
|
||||
} => {
|
||||
if http_headers_helper.is_some() {
|
||||
// Status inspection must not execute an arbitrary local helper. Existing
|
||||
// credentials remain reportable; otherwise discovery waits for startup/login.
|
||||
return Ok(determine_streamable_http_auth_status_from_credentials(
|
||||
config.oauth_credential_name(server_name).as_ref(),
|
||||
url,
|
||||
bearer_token_env_var.as_deref(),
|
||||
http_headers.clone(),
|
||||
env_http_headers.clone(),
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
)?
|
||||
.unwrap_or(McpAuthState::Unknown));
|
||||
}
|
||||
let http_client = runtime_context
|
||||
.resolve_http_client(server_name, config)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let discovery_timeout = if config.is_local_environment() {
|
||||
OAuthDiscoveryTimeout::LOCAL
|
||||
} else {
|
||||
OAuthDiscoveryTimeout::Requested
|
||||
};
|
||||
let oauth_credential_name = config.oauth_credential_name(server_name);
|
||||
determine_streamable_http_auth_status(
|
||||
oauth_credential_name.as_ref(),
|
||||
url,
|
||||
bearer_token_env_var.as_deref(),
|
||||
http_headers.clone(),
|
||||
env_http_headers.clone(),
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
http_client,
|
||||
discovery_timeout,
|
||||
redirect_mode,
|
||||
)
|
||||
.boxed()
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use anyhow::anyhow;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::McpOAuthScopesSource;
|
||||
use super::OAuthProviderError;
|
||||
use super::ResolvedMcpOAuthScopes;
|
||||
use super::resolve_oauth_callback;
|
||||
use super::resolve_oauth_scopes;
|
||||
use super::should_retry_without_scopes;
|
||||
|
||||
#[test]
|
||||
fn callback_resolution_preserves_registered_and_legacy_clients() -> anyhow::Result<()> {
|
||||
for (client_id, saved_callback, global_callback, expected_callback) in [
|
||||
(
|
||||
Some("registered-client"),
|
||||
Some("http://127.0.0.1/callback"),
|
||||
Some("https://override.example/callback"),
|
||||
Some("http://127.0.0.1/callback"),
|
||||
),
|
||||
(
|
||||
Some("legacy-client"),
|
||||
None,
|
||||
None,
|
||||
Some("http://127.0.0.1/callback/epMNJ6P1xGQ9"),
|
||||
),
|
||||
(
|
||||
None,
|
||||
Some("https://plugin.example/callback"),
|
||||
Some("https://override.example/callback"),
|
||||
Some("https://plugin.example/callback"),
|
||||
),
|
||||
(
|
||||
None,
|
||||
None,
|
||||
Some("https://override.example/callback"),
|
||||
Some("https://override.example/callback"),
|
||||
),
|
||||
] {
|
||||
let server = serde_json::from_value(serde_json::json!({
|
||||
"url": "https://mcp.example.com/mcp",
|
||||
"oauth": {
|
||||
"client_id": client_id,
|
||||
"callback_url": saved_callback,
|
||||
},
|
||||
}))?;
|
||||
assert_eq!(
|
||||
resolve_oauth_callback(&server, "https://mcp.example.com/mcp", global_callback)?
|
||||
.as_deref(),
|
||||
expected_callback
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_oauth_scopes_prefers_explicit() {
|
||||
let resolved = resolve_oauth_scopes(
|
||||
Some(vec!["explicit".to_string()]),
|
||||
Some(vec!["configured".to_string()]),
|
||||
Some(vec!["discovered".to_string()]),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
ResolvedMcpOAuthScopes {
|
||||
scopes: vec!["explicit".to_string()],
|
||||
source: McpOAuthScopesSource::Explicit,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_oauth_scopes_prefers_configured_over_discovered() {
|
||||
let resolved = resolve_oauth_scopes(
|
||||
/*explicit_scopes*/ None,
|
||||
Some(vec!["configured".to_string()]),
|
||||
Some(vec!["discovered".to_string()]),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
ResolvedMcpOAuthScopes {
|
||||
scopes: vec!["configured".to_string()],
|
||||
source: McpOAuthScopesSource::Configured,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_oauth_scopes_uses_discovered_when_needed() {
|
||||
let resolved = resolve_oauth_scopes(
|
||||
/*explicit_scopes*/ None,
|
||||
/*configured_scopes*/ None,
|
||||
Some(vec!["discovered".to_string()]),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
ResolvedMcpOAuthScopes {
|
||||
scopes: vec!["discovered".to_string()],
|
||||
source: McpOAuthScopesSource::Discovered,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_oauth_scopes_preserves_explicitly_empty_configured_scopes() {
|
||||
let resolved = resolve_oauth_scopes(
|
||||
/*explicit_scopes*/ None,
|
||||
Some(Vec::new()),
|
||||
Some(vec!["ignored".into()]),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
ResolvedMcpOAuthScopes {
|
||||
scopes: Vec::new(),
|
||||
source: McpOAuthScopesSource::Configured,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_oauth_scopes_falls_back_to_empty() {
|
||||
let resolved = resolve_oauth_scopes(
|
||||
/*explicit_scopes*/ None, /*configured_scopes*/ None,
|
||||
/*discovered_scopes*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
ResolvedMcpOAuthScopes {
|
||||
scopes: Vec::new(),
|
||||
source: McpOAuthScopesSource::Empty,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_retry_without_scopes_only_for_discovered_provider_errors() {
|
||||
let discovered = ResolvedMcpOAuthScopes {
|
||||
scopes: vec!["scope".to_string()],
|
||||
source: McpOAuthScopesSource::Discovered,
|
||||
};
|
||||
let provider_error = anyhow!(OAuthProviderError::new(
|
||||
Some("invalid_scope".to_string()),
|
||||
Some("scope rejected".to_string()),
|
||||
));
|
||||
|
||||
assert!(should_retry_without_scopes(&discovered, &provider_error));
|
||||
|
||||
let configured = ResolvedMcpOAuthScopes {
|
||||
scopes: vec!["scope".to_string()],
|
||||
source: McpOAuthScopesSource::Configured,
|
||||
};
|
||||
assert!(!should_retry_without_scopes(&configured, &provider_error));
|
||||
assert!(!should_retry_without_scopes(
|
||||
&discovered,
|
||||
&anyhow!("timed out waiting for OAuth callback"),
|
||||
));
|
||||
}
|
||||
}
|
||||
928
codex-rs/codex-mcp/src/mcp/mod.rs
Normal file
928
codex-rs/codex-mcp/src/mcp/mod.rs
Normal file
@@ -0,0 +1,928 @@
|
||||
pub use auth::McpAuthStatusEntry;
|
||||
pub use auth::McpOAuthLoginConfig;
|
||||
pub use auth::McpOAuthLoginSupport;
|
||||
pub use auth::McpOAuthScopesSource;
|
||||
pub use auth::ResolvedMcpOAuthScopes;
|
||||
pub use auth::compute_auth_statuses;
|
||||
pub use auth::discover_supported_scopes;
|
||||
pub use auth::oauth_login_support;
|
||||
pub use auth::resolve_oauth_callback;
|
||||
pub use auth::resolve_oauth_scopes;
|
||||
pub use auth::should_retry_without_scopes;
|
||||
|
||||
pub(crate) mod auth;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::Constrained;
|
||||
use codex_config::McpEnterpriseManagedAuthConfig;
|
||||
use codex_config::McpServerAuth;
|
||||
use codex_config::McpServerConfig;
|
||||
use codex_config::McpServerTransportConfig;
|
||||
use codex_config::types::AppToolApproval;
|
||||
use codex_config::types::ApprovalsReviewer;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_config::types::OAuthCredentialsStoreMode;
|
||||
use codex_connectors::ConnectorRuntimeManager;
|
||||
use codex_connectors::ConnectorSnapshot;
|
||||
use codex_connectors::connector_runtime_context_key;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::CHATGPT_CODEX_BASE_URL;
|
||||
use codex_protocol::mcp::ClientMcpExtensions;
|
||||
use codex_protocol::mcp::McpServerInfo;
|
||||
use codex_protocol::mcp::Resource;
|
||||
use codex_protocol::mcp::ResourceTemplate;
|
||||
use codex_protocol::mcp::Tool;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::McpAuthStatus;
|
||||
use codex_rmcp_client::McpOAuthRefreshMode;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use rmcp::model::ElicitationCapability;
|
||||
use rmcp::model::ReadResourceRequestParams;
|
||||
use rmcp::model::ReadResourceResult;
|
||||
use serde_json::Value;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::McpProtocolMode;
|
||||
use crate::McpServerSource;
|
||||
use crate::ResolvedMcpCatalog;
|
||||
use crate::connection_manager::McpConnectionSet;
|
||||
use crate::runtime::McpPublicationGate;
|
||||
use crate::runtime::McpRuntimeContext;
|
||||
use crate::runtime::McpRuntimeInput;
|
||||
use crate::runtime::McpStartupPolicy;
|
||||
use crate::server::EffectiveMcpServer;
|
||||
use crate::tools::ToolInfo;
|
||||
|
||||
pub const CODEX_APPS_MCP_SERVER_NAME: &str = "codex_apps";
|
||||
pub(crate) const DEFAULT_CODEX_APPS_MCP_PRODUCT_SKU: &str = "codex";
|
||||
const MCP_TOOL_NAME_PREFIX: &str = "mcp";
|
||||
const MCP_TOOL_NAME_DELIMITER: &str = "__";
|
||||
const CODEX_CONNECTORS_TOKEN_ENV_VAR: &str = "CODEX_CONNECTORS_TOKEN";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum McpSnapshotDetail {
|
||||
#[default]
|
||||
Full,
|
||||
ToolsAndAuthOnly,
|
||||
}
|
||||
|
||||
impl McpSnapshotDetail {
|
||||
fn include_resources(self) -> bool {
|
||||
matches!(self, Self::Full)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn qualified_mcp_tool_name_prefix(server_name: &str) -> String {
|
||||
sanitize_responses_api_tool_name(&format!(
|
||||
"{MCP_TOOL_NAME_PREFIX}{MCP_TOOL_NAME_DELIMITER}{server_name}{MCP_TOOL_NAME_DELIMITER}"
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns true when MCP permission prompts should resolve as approved instead
|
||||
/// of being shown to the user.
|
||||
pub fn mcp_permission_prompt_is_auto_approved(
|
||||
approval_policy: AskForApproval,
|
||||
permission_profile: &PermissionProfile,
|
||||
context: McpPermissionPromptAutoApproveContext,
|
||||
) -> bool {
|
||||
if context.tool_approval_mode == Some(AppToolApproval::Approve) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if approval_policy != AskForApproval::Never {
|
||||
return false;
|
||||
}
|
||||
|
||||
match permission_profile {
|
||||
PermissionProfile::Disabled | PermissionProfile::External { .. } => true,
|
||||
PermissionProfile::Managed { file_system, .. } => {
|
||||
file_system.to_sandbox_policy().has_full_disk_write_access()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct McpPermissionPromptAutoApproveContext {
|
||||
pub tool_approval_mode: Option<AppToolApproval>,
|
||||
}
|
||||
|
||||
/// Which rules a registered MCP server uses.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum McpServerPermissions {
|
||||
Thread,
|
||||
Environment(Arc<FileSystemSandboxContext>),
|
||||
}
|
||||
|
||||
/// MCP runtime settings derived from `codex_core::config::Config`.
|
||||
///
|
||||
/// Each published runtime and prepared call owns one immutable copy of these
|
||||
/// settings, so its connection, approval policy, and sandbox authority cannot
|
||||
/// change independently. Auth remains separate and is supplied explicitly to
|
||||
/// runtime entry points such as [`effective_mcp_servers`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct McpConfig {
|
||||
/// Base URL for ChatGPT-hosted app MCP servers, copied from the root config.
|
||||
pub chatgpt_base_url: String,
|
||||
/// Optional product SKU forwarded to the host-owned apps MCP server.
|
||||
pub apps_mcp_product_sku: Option<String>,
|
||||
/// Requests server-side read-only filtering and invocation checks for MCP tools.
|
||||
pub requires_read_only_mcp_tools: bool,
|
||||
/// Codex home directory used for MCP OAuth state and app-tool cache files.
|
||||
pub codex_home: PathBuf,
|
||||
/// Trusted enterprise IdP inherited after normal catalog and policy resolution.
|
||||
pub mcp_enterprise_managed_auth: Option<McpEnterpriseManagedAuthConfig>,
|
||||
/// Retires only EMA connections and pending exchanges for this config snapshot.
|
||||
pub mcp_ema_cancellation: codex_config::McpEmaCancellation,
|
||||
pub xaa_enabled: bool,
|
||||
/// Shared sign-in requirements for account-backed enterprise MCP.
|
||||
pub ema_state: Arc<crate::EmaState>,
|
||||
/// Preferred credential store for MCP OAuth tokens.
|
||||
pub mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode,
|
||||
/// OAuth refresh ownership selected for new MCP connections.
|
||||
pub oauth_refresh_mode: McpOAuthRefreshMode,
|
||||
/// Backend used when MCP OAuth storage is configured for keyring-backed persistence.
|
||||
pub auth_keyring_backend_kind: AuthKeyringBackendKind,
|
||||
/// Optional fixed localhost callback port for MCP OAuth login.
|
||||
pub mcp_oauth_callback_port: Option<u16>,
|
||||
/// Optional OAuth redirect URI override for MCP login.
|
||||
pub mcp_oauth_callback_url: Option<String>,
|
||||
/// How long a tool catalog capture waits for optional MCP servers to initialize.
|
||||
///
|
||||
/// A zero duration disables the shared grace and waits for each server's
|
||||
/// configured startup timeout instead.
|
||||
pub optional_mcp_startup_grace: Duration,
|
||||
/// Whether skill MCP dependency installation prompts are enabled.
|
||||
pub skill_mcp_dependency_install_enabled: bool,
|
||||
/// Approval policy used for MCP tool calls and MCP elicitation requests.
|
||||
pub approval_policy: Constrained<AskForApproval>,
|
||||
/// Permission profile captured with the connections and approval policy.
|
||||
pub permission_profile: PermissionProfile,
|
||||
/// Host working directory used to interpret thread permissions.
|
||||
pub host_cwd: AbsolutePathBuf,
|
||||
/// Configuration layers used to evaluate Apps tool policy and reviewer selection.
|
||||
pub config_layer_stack: ConfigLayerStack,
|
||||
pub plugins: codex_config::types::PluginsConfigToml,
|
||||
/// Default reviewer used when an Apps tool has no reviewer override.
|
||||
pub approvals_reviewer: ApprovalsReviewer,
|
||||
/// Working directories for the exact environment handles used by this runtime.
|
||||
pub environment_cwds: HashMap<String, PathUri>,
|
||||
/// Effective backends captured with the environment handles, including local fallback.
|
||||
pub environment_use_mxc: HashMap<String, bool>,
|
||||
/// Permissions for registered servers. Unavailable servers have no entry.
|
||||
pub server_permissions: HashMap<String, McpServerPermissions>,
|
||||
/// Host-supplied re-exec binary. Probe its sandbox capability before advertising it.
|
||||
/// Never infer this from PATH or an MCP server's configuration.
|
||||
pub codex_self_exe: Option<PathBuf>,
|
||||
/// Optional path to `codex-linux-sandbox` for sandboxed MCP tool execution.
|
||||
pub codex_linux_sandbox_exe: Option<PathBuf>,
|
||||
/// Whether to use legacy Landlock behavior in the MCP sandbox state.
|
||||
// TODO(anp): Reconcile this runtime-wide copy with TurnEnvironment::sandbox_context
|
||||
// for the environment that owns each MCP server.
|
||||
pub use_legacy_landlock: bool,
|
||||
/// Whether the app MCP integration is enabled by config.
|
||||
///
|
||||
/// ChatGPT auth is checked separately before a materialized host-owned Apps
|
||||
/// server can be used.
|
||||
pub apps_enabled: bool,
|
||||
/// Allow hosted Apps catalog reads after MCP initialization, before tools are ready.
|
||||
pub apps_early_resource_discovery: bool,
|
||||
/// Whether model-visible MCP tool namespaces should keep the legacy
|
||||
/// `mcp__` prefix.
|
||||
pub prefix_mcp_tool_names: bool,
|
||||
/// MCP servers whose model-visible tool namespaces omit the `mcp__` prefix.
|
||||
pub non_prefixed_mcp_tool_servers: Vec<String>,
|
||||
/// Protocol mode for servers other than the host-owned Codex Apps registration.
|
||||
pub protocol_mode: McpProtocolMode,
|
||||
/// Try protocol discovery before initializing eligible local stdio servers.
|
||||
pub discover_local_stdio: bool,
|
||||
/// Refresh ordinary server catalogs after tools/list_changed notifications.
|
||||
pub mcp_tool_list_changed: bool,
|
||||
/// Independent protocol mode for the trusted, HTTP Codex Apps registration.
|
||||
pub host_owned_apps_protocol_mode: McpProtocolMode,
|
||||
/// Client-side elicitation capabilities advertised during MCP initialization.
|
||||
pub client_elicitation_capability: ElicitationCapability,
|
||||
/// Resolved MCP registrations keyed by logical server name.
|
||||
pub mcp_server_catalog: ResolvedMcpCatalog,
|
||||
/// Plugin declarations used to attribute connector tools to plugin display names.
|
||||
/// MCP registrations retain their own package attribution in the catalog.
|
||||
pub connector_snapshot: ConnectorSnapshot,
|
||||
}
|
||||
|
||||
/// Default amount of time a tool catalog capture waits for optional MCP servers.
|
||||
pub const DEFAULT_OPTIONAL_MCP_STARTUP_GRACE: Duration = Duration::from_secs(1);
|
||||
|
||||
impl McpConfig {
|
||||
/// Resolves enabled runtime servers against the exact attachment permissions being published.
|
||||
pub fn set_server_permissions(
|
||||
&mut self,
|
||||
servers: &HashMap<String, EffectiveMcpServer>,
|
||||
environment_sandboxes: impl IntoIterator<Item = (String, Arc<FileSystemSandboxContext>)>,
|
||||
) {
|
||||
let environment_sandboxes = environment_sandboxes.into_iter().collect::<HashMap<_, _>>();
|
||||
self.server_permissions = servers
|
||||
.iter()
|
||||
.filter(|(_, server)| server.enabled())
|
||||
.filter_map(|(server_name, _)| {
|
||||
let server = self.mcp_server_catalog.server(server_name)?;
|
||||
let permissions = if server
|
||||
.source()
|
||||
.is_host_owned_apps(server_name, server.config())
|
||||
{
|
||||
McpServerPermissions::Thread
|
||||
} else if let Some(sandbox) =
|
||||
environment_sandboxes.get(&server.config().environment_id)
|
||||
{
|
||||
McpServerPermissions::Environment(Arc::clone(sandbox))
|
||||
} else if server.config().is_local_environment()
|
||||
|| matches!(server.source(), McpServerSource::SelectedPlugin(_))
|
||||
{
|
||||
McpServerPermissions::Thread
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some((server_name.clone(), permissions))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
/// Returns this server's published permission authority.
|
||||
pub fn permission_profile_for_server(&self, server_name: &str) -> Option<&PermissionProfile> {
|
||||
Some(match self.server_permissions.get(server_name)? {
|
||||
McpServerPermissions::Thread => &self.permission_profile,
|
||||
McpServerPermissions::Environment(sandbox) => &sandbox.permissions,
|
||||
})
|
||||
}
|
||||
|
||||
/// Standalone discovery and resource reads must not inherit thread execution authority.
|
||||
pub fn for_threadless_operations(&self, servers: &HashMap<String, EffectiveMcpServer>) -> Self {
|
||||
let mut config = self.clone();
|
||||
config.permission_profile = PermissionProfile::default();
|
||||
config.server_permissions = servers
|
||||
.iter()
|
||||
.filter(|(_, server)| server.enabled())
|
||||
.map(|(name, _)| (name.clone(), McpServerPermissions::Thread))
|
||||
.collect();
|
||||
config
|
||||
}
|
||||
}
|
||||
|
||||
/// Plugin attribution and selection data derived from the current MCP configuration.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ToolPluginContext {
|
||||
plugin_display_names_by_connector_id: HashMap<String, Vec<String>>,
|
||||
disabled_connector_ids: HashSet<String>,
|
||||
plugin_display_names_by_mcp_server_name: HashMap<String, Vec<String>>,
|
||||
plugin_ids_by_mcp_server_name: HashMap<String, String>,
|
||||
selected_plugin_mcp_server_names: HashSet<String>,
|
||||
}
|
||||
|
||||
impl ToolPluginContext {
|
||||
pub(crate) fn allows_connector_id(&self, connector_id: Option<&str>) -> bool {
|
||||
connector_id.is_none_or(|id| !self.disabled_connector_ids.contains(id))
|
||||
}
|
||||
|
||||
pub fn plugin_display_names_for_connector_id(&self, connector_id: &str) -> &[String] {
|
||||
self.plugin_display_names_by_connector_id
|
||||
.get(connector_id)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
pub fn plugin_display_names_for_mcp_server_name(&self, server_name: &str) -> &[String] {
|
||||
self.plugin_display_names_by_mcp_server_name
|
||||
.get(server_name)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
pub fn plugin_id_for_mcp_server_name(&self, server_name: &str) -> Option<&str> {
|
||||
self.plugin_ids_by_mcp_server_name
|
||||
.get(server_name)
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
pub(crate) fn is_selected_plugin_mcp_server(&self, server_name: &str) -> bool {
|
||||
self.selected_plugin_mcp_server_names.contains(server_name)
|
||||
}
|
||||
|
||||
fn from_config(config: &McpConfig) -> Self {
|
||||
let mut tool_plugin_context = Self {
|
||||
disabled_connector_ids: config.connector_snapshot.disabled_connector_ids().clone(),
|
||||
..Self::default()
|
||||
};
|
||||
for connector_id in config.connector_snapshot.connector_ids() {
|
||||
tool_plugin_context
|
||||
.plugin_display_names_by_connector_id
|
||||
.insert(
|
||||
connector_id.0.clone(),
|
||||
config
|
||||
.connector_snapshot
|
||||
.plugin_display_names_for_connector_id(&connector_id.0)
|
||||
.to_vec(),
|
||||
);
|
||||
}
|
||||
|
||||
for (server_name, attribution) in config
|
||||
.mcp_server_catalog
|
||||
.plugin_attributions_by_server_name()
|
||||
{
|
||||
tool_plugin_context
|
||||
.plugin_display_names_by_mcp_server_name
|
||||
.insert(
|
||||
server_name.clone(),
|
||||
vec![attribution.display_name().to_string()],
|
||||
);
|
||||
tool_plugin_context
|
||||
.plugin_ids_by_mcp_server_name
|
||||
.insert(server_name, attribution.plugin_id().to_string());
|
||||
}
|
||||
tool_plugin_context.selected_plugin_mcp_server_names.extend(
|
||||
config
|
||||
.mcp_server_catalog
|
||||
.selected_plugin_server_names()
|
||||
.map(str::to_string),
|
||||
);
|
||||
|
||||
for plugin_names in tool_plugin_context
|
||||
.plugin_display_names_by_connector_id
|
||||
.values_mut()
|
||||
.chain(
|
||||
tool_plugin_context
|
||||
.plugin_display_names_by_mcp_server_name
|
||||
.values_mut(),
|
||||
)
|
||||
{
|
||||
plugin_names.sort_unstable();
|
||||
plugin_names.dedup();
|
||||
}
|
||||
tool_plugin_context
|
||||
}
|
||||
}
|
||||
|
||||
pub fn host_owned_codex_apps_enabled(config: &McpConfig, auth: Option<&CodexAuth>) -> bool {
|
||||
config.apps_enabled && auth.is_some_and(CodexAuth::uses_codex_backend)
|
||||
}
|
||||
|
||||
pub fn configured_mcp_servers(config: &McpConfig) -> HashMap<String, McpServerConfig> {
|
||||
config.mcp_server_catalog.configured_servers()
|
||||
}
|
||||
|
||||
pub fn effective_mcp_servers(
|
||||
config: &McpConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> HashMap<String, EffectiveMcpServer> {
|
||||
effective_mcp_servers_from_configured(configured_mcp_servers(config), config, auth)
|
||||
}
|
||||
|
||||
pub(crate) fn is_trusted_chatgpt_mcp_server(
|
||||
transport: &McpServerTransportConfig,
|
||||
chatgpt_base_url: &str,
|
||||
) -> bool {
|
||||
let McpServerTransportConfig::StreamableHttp { url, .. } = transport else {
|
||||
return false;
|
||||
};
|
||||
let Ok(server_url) = url::Url::parse(url) else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(server_url.scheme(), "http" | "https") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if [CHATGPT_CODEX_BASE_URL, "https://gov.chatgpt.com"]
|
||||
.into_iter()
|
||||
.filter_map(|base_url| url::Url::parse(base_url).ok())
|
||||
.any(|trusted_url| server_url.origin() == trusted_url.origin())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
url::Url::parse(chatgpt_base_url)
|
||||
.ok()
|
||||
.is_some_and(|staging_url| {
|
||||
staging_url.scheme() == "https"
|
||||
&& staging_url.domain().is_some_and(|host| {
|
||||
host == "chatgpt-staging.com" || host.ends_with(".chatgpt-staging.com")
|
||||
})
|
||||
&& server_url.origin() == staging_url.origin()
|
||||
})
|
||||
}
|
||||
|
||||
/// Converts a materialized server map to its auth-gated runtime view.
|
||||
///
|
||||
/// Compatibility built-ins and extension overlays must already be reflected in
|
||||
/// `configured_servers`; this function does not synthesize missing servers.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if a materialized server is missing from the catalog.
|
||||
pub fn effective_mcp_servers_from_configured(
|
||||
configured_servers: HashMap<String, McpServerConfig>,
|
||||
config: &McpConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> HashMap<String, EffectiveMcpServer> {
|
||||
let mut servers = configured_servers
|
||||
.into_iter()
|
||||
.map(|(name, mut server)| {
|
||||
#[expect(
|
||||
clippy::expect_used,
|
||||
reason = "materialized servers must have catalog registrations"
|
||||
)]
|
||||
let registration = config
|
||||
.mcp_server_catalog
|
||||
.server(&name)
|
||||
.expect("materialized MCP server must have a catalog registration");
|
||||
match server.auth.clone() {
|
||||
McpServerAuth::ChatGpt => {
|
||||
if !is_trusted_chatgpt_mcp_server(&server.transport, &config.chatgpt_base_url) {
|
||||
server.auth = McpServerAuth::OAuth;
|
||||
}
|
||||
}
|
||||
McpServerAuth::OAuth | McpServerAuth::EmaAuth => {}
|
||||
}
|
||||
(
|
||||
name,
|
||||
EffectiveMcpServer::from_config_with_policy(
|
||||
server,
|
||||
registration.credential_policy(),
|
||||
)
|
||||
.with_agent_plugin(registration.source().is_agent_plugin()),
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
if !host_owned_codex_apps_enabled(config, auth) {
|
||||
servers.remove(CODEX_APPS_MCP_SERVER_NAME);
|
||||
}
|
||||
servers
|
||||
}
|
||||
|
||||
pub fn tool_plugin_context(config: &McpConfig) -> ToolPluginContext {
|
||||
ToolPluginContext::from_config(config)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn read_mcp_resource(
|
||||
config: &McpConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
runtime_auth: Option<(
|
||||
codex_runtime_agent_instance::RuntimeAuthSlot,
|
||||
codex_features::RuntimeAuthMode,
|
||||
)>,
|
||||
runtime_context: McpRuntimeContext,
|
||||
codex_apps_tools_cache: ConnectorRuntimeManager<ToolInfo>,
|
||||
tool_catalog_cache: crate::McpToolCatalogCache,
|
||||
server: &str,
|
||||
params: ReadResourceRequestParams,
|
||||
) -> anyhow::Result<ReadResourceResult> {
|
||||
let mut mcp_servers = effective_mcp_servers(config, auth);
|
||||
mcp_servers.retain(|name, _| name == server);
|
||||
let cancel_token = CancellationToken::new();
|
||||
let runtime_config = config.for_threadless_operations(&mcp_servers);
|
||||
let manager = McpConnectionSet::new(
|
||||
/*ema_auth*/ None,
|
||||
/*existing_ema*/ None,
|
||||
/*previous*/ None,
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(runtime_config),
|
||||
plugins_available: false,
|
||||
ready_selected_capability_roots: Vec::new(),
|
||||
mcp_servers,
|
||||
submit_id: String::new(),
|
||||
tx_event: None,
|
||||
startup_cancellation_token: cancel_token.clone(),
|
||||
runtime_context,
|
||||
codex_apps_tools_cache,
|
||||
tool_catalog_cache,
|
||||
codex_apps_tools_cache_key: connector_runtime_context_key(auth),
|
||||
client_mcp_extensions: ClientMcpExtensions::default(),
|
||||
auth: auth.cloned(),
|
||||
auth_manager: None,
|
||||
elicitation_reviewer: None,
|
||||
elicitation_lifecycle: None,
|
||||
},
|
||||
crate::elicitation::ElicitationRequestRouter::default(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let result = manager.read_resource(server, params).await;
|
||||
cancel_token.cancel();
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct McpServerStatusSnapshot {
|
||||
pub server_infos: HashMap<String, McpServerInfo>,
|
||||
pub server_capabilities: HashMap<String, serde_json::Value>,
|
||||
pub tool_list_meta: HashMap<String, Arc<serde_json::Value>>,
|
||||
pub tools_by_server: HashMap<String, HashMap<String, Tool>>,
|
||||
pub tools_errors: HashMap<String, String>,
|
||||
pub resources: HashMap<String, Vec<Resource>>,
|
||||
pub resource_templates: HashMap<String, Vec<ResourceTemplate>>,
|
||||
pub auth_statuses: HashMap<String, McpAuthStatus>,
|
||||
pub server_names: Vec<String>,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn collect_mcp_server_status_snapshot_with_detail(
|
||||
config: &McpConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
auth_manager: Option<&Arc<codex_login::AuthManager>>,
|
||||
runtime_auth: Option<(
|
||||
codex_runtime_agent_instance::RuntimeAuthSlot,
|
||||
codex_features::RuntimeAuthMode,
|
||||
)>,
|
||||
runtime_context: McpRuntimeContext,
|
||||
codex_apps_tools_cache: ConnectorRuntimeManager<ToolInfo>,
|
||||
tool_catalog_cache: crate::McpToolCatalogCache,
|
||||
detail: McpSnapshotDetail,
|
||||
server_name: Option<&str>,
|
||||
) -> McpServerStatusSnapshot {
|
||||
let mut mcp_servers = effective_mcp_servers(config, auth);
|
||||
mcp_servers.retain(|name, _| server_name.is_none_or(|selected| name == selected));
|
||||
if mcp_servers.is_empty() {
|
||||
return McpServerStatusSnapshot {
|
||||
server_infos: HashMap::new(),
|
||||
server_capabilities: HashMap::new(),
|
||||
tool_list_meta: HashMap::new(),
|
||||
tools_by_server: HashMap::new(),
|
||||
tools_errors: HashMap::new(),
|
||||
resources: HashMap::new(),
|
||||
resource_templates: HashMap::new(),
|
||||
auth_statuses: HashMap::new(),
|
||||
server_names: Vec::new(),
|
||||
};
|
||||
}
|
||||
|
||||
let auth_status_entries = compute_auth_statuses(
|
||||
mcp_servers.iter(),
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind,
|
||||
auth,
|
||||
auth_manager,
|
||||
&config.ema_state,
|
||||
&runtime_context,
|
||||
)
|
||||
.await;
|
||||
|
||||
let server_names = mcp_servers.keys().cloned().collect();
|
||||
|
||||
let cancel_token = CancellationToken::new();
|
||||
let runtime_config = config.for_threadless_operations(&mcp_servers);
|
||||
let mcp_connection_manager = McpConnectionSet::new(
|
||||
/*ema_auth*/ None,
|
||||
/*existing_ema*/ None,
|
||||
/*previous*/ None,
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(runtime_config),
|
||||
plugins_available: false,
|
||||
ready_selected_capability_roots: Vec::new(),
|
||||
mcp_servers,
|
||||
submit_id: String::new(),
|
||||
tx_event: None,
|
||||
startup_cancellation_token: cancel_token.clone(),
|
||||
runtime_context,
|
||||
codex_apps_tools_cache,
|
||||
tool_catalog_cache,
|
||||
codex_apps_tools_cache_key: connector_runtime_context_key(auth),
|
||||
client_mcp_extensions: ClientMcpExtensions::default(),
|
||||
auth: auth.cloned(),
|
||||
auth_manager: None,
|
||||
elicitation_reviewer: None,
|
||||
elicitation_lifecycle: None,
|
||||
},
|
||||
crate::elicitation::ElicitationRequestRouter::default(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let snapshot = collect_mcp_server_status_snapshot_from_manager(
|
||||
&mcp_connection_manager,
|
||||
auth_status_entries,
|
||||
server_names,
|
||||
detail,
|
||||
)
|
||||
.await;
|
||||
|
||||
cancel_token.cancel();
|
||||
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// The Responses API requires tool names to match `^[a-zA-Z0-9_-]+$`.
|
||||
/// MCP server/tool names are user-controlled, so sanitize the fully-qualified
|
||||
/// name we expose to the model by replacing any disallowed character with `_`.
|
||||
pub(crate) fn sanitize_responses_api_tool_name(name: &str) -> String {
|
||||
let mut sanitized = String::with_capacity(name.len());
|
||||
for c in name.chars() {
|
||||
if c.is_ascii_alphanumeric() || c == '_' {
|
||||
sanitized.push(c);
|
||||
} else {
|
||||
sanitized.push('_');
|
||||
}
|
||||
}
|
||||
|
||||
if sanitized.is_empty() {
|
||||
"_".to_string()
|
||||
} else {
|
||||
sanitized
|
||||
}
|
||||
}
|
||||
|
||||
fn codex_apps_mcp_bearer_token_env_var() -> Option<String> {
|
||||
match env::var(CODEX_CONNECTORS_TOKEN_ENV_VAR) {
|
||||
Ok(value) if !value.trim().is_empty() => Some(CODEX_CONNECTORS_TOKEN_ENV_VAR.to_string()),
|
||||
Ok(_) => None,
|
||||
Err(env::VarError::NotPresent) => None,
|
||||
Err(env::VarError::NotUnicode(_)) => Some(CODEX_CONNECTORS_TOKEN_ENV_VAR.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_codex_apps_base_url(base_url: &str) -> String {
|
||||
let mut base_url = base_url.trim_end_matches('/').to_string();
|
||||
if (base_url.starts_with("https://chatgpt.com")
|
||||
|| base_url.starts_with("https://chat.openai.com"))
|
||||
&& !base_url.contains("/backend-api")
|
||||
{
|
||||
base_url = format!("{base_url}/backend-api");
|
||||
}
|
||||
base_url
|
||||
}
|
||||
|
||||
fn codex_apps_mcp_url_for_base_url(base_url: &str) -> String {
|
||||
let base_url = normalize_codex_apps_base_url(base_url);
|
||||
let base_url = if base_url.contains("/backend-api") || base_url.contains("/api/codex") {
|
||||
base_url
|
||||
} else {
|
||||
format!("{base_url}/api/codex")
|
||||
};
|
||||
format!("{base_url}/ps/mcp")
|
||||
}
|
||||
|
||||
pub fn codex_apps_mcp_server_config(
|
||||
chatgpt_base_url: &str,
|
||||
apps_mcp_product_sku: Option<&str>,
|
||||
originator: Option<&str>,
|
||||
) -> McpServerConfig {
|
||||
mcp_server_config_for_url(
|
||||
codex_apps_mcp_url_for_base_url(chatgpt_base_url),
|
||||
apps_mcp_product_sku,
|
||||
originator,
|
||||
McpServerAuth::ChatGpt,
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds the ChatGPT-hosted plugin runtime served by plugin-service.
|
||||
pub fn hosted_plugin_runtime_mcp_server_config(
|
||||
chatgpt_base_url: &str,
|
||||
apps_mcp_product_sku: Option<&str>,
|
||||
originator: Option<&str>,
|
||||
) -> McpServerConfig {
|
||||
codex_apps_mcp_server_config(chatgpt_base_url, apps_mcp_product_sku, originator)
|
||||
}
|
||||
|
||||
fn mcp_server_config_for_url(
|
||||
url: String,
|
||||
apps_mcp_product_sku: Option<&str>,
|
||||
originator: Option<&str>,
|
||||
auth_mode: McpServerAuth,
|
||||
) -> McpServerConfig {
|
||||
let product_sku = apps_mcp_product_sku.unwrap_or(DEFAULT_CODEX_APPS_MCP_PRODUCT_SKU);
|
||||
let mut http_headers =
|
||||
HashMap::from([("X-OpenAI-Product-Sku".to_string(), product_sku.to_string())]);
|
||||
if let Some(originator) = originator {
|
||||
http_headers.insert("originator".to_string(), originator.to_string());
|
||||
}
|
||||
let env_http_headers = None;
|
||||
|
||||
McpServerConfig {
|
||||
transport: McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
bearer_token_env_var: codex_apps_mcp_bearer_token_env_var(),
|
||||
http_headers: Some(http_headers),
|
||||
env_http_headers,
|
||||
http_headers_helper: None,
|
||||
},
|
||||
auth: auth_mode,
|
||||
environment_id: codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
|
||||
enabled: true,
|
||||
required: false,
|
||||
startup_readiness: Default::default(),
|
||||
supports_parallel_tool_calls: false,
|
||||
tool_input_schema_max_bytes: None,
|
||||
omit_tools_from: None,
|
||||
disabled_reason: None,
|
||||
startup_timeout_sec: Some(Duration::from_secs(30)),
|
||||
tool_timeout_sec: None,
|
||||
default_tools_approval_mode: None,
|
||||
enabled_tools: None,
|
||||
disabled_tools: None,
|
||||
scopes: None,
|
||||
oauth: None,
|
||||
oauth_resource: None,
|
||||
tools: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_tool_from_rmcp_tool(name: &str, tool: &rmcp::model::Tool) -> Option<Tool> {
|
||||
match serde_json::to_value(tool) {
|
||||
Ok(value) => match Tool::from_mcp_value(value) {
|
||||
Ok(tool) => Some(tool),
|
||||
Err(err) => {
|
||||
tracing::warn!("Failed to convert MCP tool '{name}': {err}");
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
tracing::warn!("Failed to serialize MCP tool '{name}': {err}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_statuses_from_entries(
|
||||
auth_status_entries: &HashMap<String, crate::mcp::auth::McpAuthStatusEntry>,
|
||||
) -> HashMap<String, McpAuthStatus> {
|
||||
auth_status_entries
|
||||
.iter()
|
||||
.map(|(name, entry)| (name.clone(), McpAuthStatus::from(entry.auth_state)))
|
||||
.collect::<HashMap<_, _>>()
|
||||
}
|
||||
|
||||
fn convert_mcp_resources(
|
||||
resources: HashMap<String, Vec<rmcp::model::Resource>>,
|
||||
) -> HashMap<String, Vec<Resource>> {
|
||||
resources
|
||||
.into_iter()
|
||||
.map(|(name, resources)| {
|
||||
let resources = resources
|
||||
.into_iter()
|
||||
.filter_map(|resource| match serde_json::to_value(resource) {
|
||||
Ok(value) => match Resource::from_mcp_value(value.clone()) {
|
||||
Ok(resource) => Some(resource),
|
||||
Err(err) => {
|
||||
let (uri, resource_name) = match value {
|
||||
Value::Object(obj) => (
|
||||
obj.get("uri")
|
||||
.and_then(|v| v.as_str().map(ToString::to_string)),
|
||||
obj.get("name")
|
||||
.and_then(|v| v.as_str().map(ToString::to_string)),
|
||||
),
|
||||
_ => (None, None),
|
||||
};
|
||||
|
||||
tracing::warn!(
|
||||
"Failed to convert MCP resource (uri={uri:?}, name={resource_name:?}): {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
tracing::warn!("Failed to serialize MCP resource: {err}");
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
(name, resources)
|
||||
})
|
||||
.collect::<HashMap<_, _>>()
|
||||
}
|
||||
|
||||
fn convert_mcp_resource_templates(
|
||||
resource_templates: HashMap<String, Vec<rmcp::model::ResourceTemplate>>,
|
||||
) -> HashMap<String, Vec<ResourceTemplate>> {
|
||||
resource_templates
|
||||
.into_iter()
|
||||
.map(|(name, templates)| {
|
||||
let templates = templates
|
||||
.into_iter()
|
||||
.filter_map(|template| match serde_json::to_value(template) {
|
||||
Ok(value) => match ResourceTemplate::from_mcp_value(value.clone()) {
|
||||
Ok(template) => Some(template),
|
||||
Err(err) => {
|
||||
let (uri_template, template_name) = match value {
|
||||
Value::Object(obj) => (
|
||||
obj.get("uriTemplate")
|
||||
.or_else(|| obj.get("uri_template"))
|
||||
.and_then(|v| v.as_str().map(ToString::to_string)),
|
||||
obj.get("name")
|
||||
.and_then(|v| v.as_str().map(ToString::to_string)),
|
||||
),
|
||||
_ => (None, None),
|
||||
};
|
||||
|
||||
tracing::warn!(
|
||||
"Failed to convert MCP resource template (uri_template={uri_template:?}, name={template_name:?}): {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
tracing::warn!("Failed to serialize MCP resource template: {err}");
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
(name, templates)
|
||||
})
|
||||
.collect::<HashMap<_, _>>()
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_mcp_server_status_snapshot_from_manager(
|
||||
mcp_connection_manager: &McpConnectionSet,
|
||||
auth_status_entries: HashMap<String, crate::mcp::auth::McpAuthStatusEntry>,
|
||||
server_names: Vec<String>,
|
||||
detail: McpSnapshotDetail,
|
||||
) -> McpServerStatusSnapshot {
|
||||
let selected_servers: HashSet<&str> = server_names.iter().map(String::as_str).collect();
|
||||
let include_server = |name: &str| selected_servers.contains(name);
|
||||
let ((server_infos, (tools, tools_errors, tool_list_meta)), resources, resource_templates) = tokio::join!(
|
||||
async {
|
||||
let server_infos = mcp_connection_manager
|
||||
.list_available_server_infos(include_server)
|
||||
.await;
|
||||
let tools = mcp_connection_manager
|
||||
.list_catalogs_with_errors(include_server)
|
||||
.await;
|
||||
(server_infos, tools)
|
||||
},
|
||||
async {
|
||||
if detail.include_resources() {
|
||||
mcp_connection_manager
|
||||
.list_all_resources(include_server)
|
||||
.await
|
||||
} else {
|
||||
HashMap::new()
|
||||
}
|
||||
},
|
||||
async {
|
||||
if detail.include_resources() {
|
||||
mcp_connection_manager
|
||||
.list_all_resource_templates(include_server)
|
||||
.await
|
||||
} else {
|
||||
HashMap::new()
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let server_capabilities =
|
||||
mcp_connection_manager.list_available_server_capabilities(include_server);
|
||||
let mut tools_by_server = HashMap::<String, HashMap<String, Tool>>::new();
|
||||
for tool_info in tools {
|
||||
let raw_tool_name = tool_info.tool.name.to_string();
|
||||
let Some(tool) = protocol_tool_from_rmcp_tool(&raw_tool_name, &tool_info.tool) else {
|
||||
continue;
|
||||
};
|
||||
let tool_name = tool.name.clone();
|
||||
tools_by_server
|
||||
.entry(tool_info.server_name)
|
||||
.or_default()
|
||||
.insert(tool_name, tool);
|
||||
}
|
||||
|
||||
// Status-only discovery has no event channel. Report OAuth and EMA failures from the completed
|
||||
// connection attempt instead of retaining the credential-presence status read beforehand.
|
||||
let mut auth_statuses = auth_statuses_from_entries(&auth_status_entries);
|
||||
for server_name in mcp_connection_manager.authentication_failed_servers().await {
|
||||
if auth_statuses.get(&server_name) == Some(&McpAuthStatus::OAuth)
|
||||
|| auth_status_entries
|
||||
.get(&server_name)
|
||||
.and_then(|entry| entry.config.as_ref())
|
||||
.is_some_and(|config| matches!(config.auth, McpServerAuth::EmaAuth))
|
||||
{
|
||||
auth_statuses.insert(server_name, McpAuthStatus::NotLoggedIn);
|
||||
}
|
||||
}
|
||||
|
||||
McpServerStatusSnapshot {
|
||||
server_capabilities,
|
||||
tool_list_meta,
|
||||
server_infos,
|
||||
tools_by_server,
|
||||
tools_errors,
|
||||
resources: convert_mcp_resources(resources),
|
||||
resource_templates: convert_mcp_resource_templates(resource_templates),
|
||||
auth_statuses,
|
||||
server_names,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mod_tests.rs"]
|
||||
pub(crate) mod tests;
|
||||
913
codex-rs/codex-mcp/src/mcp/mod_tests.rs
Normal file
913
codex-rs/codex-mcp/src/mcp/mod_tests.rs
Normal file
@@ -0,0 +1,913 @@
|
||||
use super::*;
|
||||
use crate::McpPluginAttribution;
|
||||
use crate::McpServerPermissions;
|
||||
use crate::McpServerRegistration;
|
||||
use crate::connection_manager::tests::create_ready_async_managed_client;
|
||||
use crate::mcp::auth::McpAuthStatusEntry;
|
||||
use crate::rmcp_client::StartupOutcomeError;
|
||||
use crate::server::McpCredentialPolicy;
|
||||
use anyhow::Context;
|
||||
use codex_config::Constrained;
|
||||
use codex_config::types::AppToolApproval;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_exec_server_test_support::environment_manager_without_environments;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::AppConnectorId;
|
||||
use codex_plugin::PluginCapabilitySummary;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::GranularApprovalConfig;
|
||||
use codex_rmcp_client::McpAuthState;
|
||||
use futures::FutureExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn ema_auth_statuses_do_not_wait_for_account_refresh() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
// Account ID token for user/workspace, issued by idp.example to account-client.
|
||||
let id_token = concat!(
|
||||
"eyJhbGciOiJFUzI1NiJ9.",
|
||||
"eyJpc3MiOiJodHRwczovL2lkcC5leGFtcGxlIiwic3ViIjoidXNlciIsImF1ZCI6ImFjY291bnQt",
|
||||
"Y2xpZW50IiwiZXhwIjoxLCJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91",
|
||||
"c2VyX2lkIjoidXNlciIsImNoYXRncHRfYWNjb3VudF9pZCI6IndvcmtzcGFjZSJ9fQ",
|
||||
".signature",
|
||||
);
|
||||
std::fs::write(
|
||||
home.path().join("auth.json"),
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {
|
||||
"id_token": id_token,
|
||||
"access_token": "account-access",
|
||||
"refresh_token": "account-refresh",
|
||||
"account_id": "workspace",
|
||||
"login_owner_id": "completed-login",
|
||||
"oauth_provenance": {
|
||||
"issuer": "https://idp.example",
|
||||
"client_id": "account-client"
|
||||
}
|
||||
},
|
||||
"last_refresh": "2099-01-01T00:00:00Z"
|
||||
}))?,
|
||||
)?;
|
||||
let manager = AuthManager::shared(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::default(),
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await;
|
||||
let auth = manager.auth_cached().context("account auth")?;
|
||||
let lease = manager
|
||||
.lease_account_oauth_grant()
|
||||
.await?
|
||||
.context("account grant")?;
|
||||
let mut servers = HashMap::new();
|
||||
for name in ["first", "second"] {
|
||||
let mut server: McpServerConfig = serde_json::from_value(serde_json::json!({
|
||||
"url": format!("https://resource.example/{name}"),
|
||||
"auth": "ema_auth"
|
||||
}))?;
|
||||
server
|
||||
.resolve_ema_registration(&codex_config::McpServerIdpOAuthConfig {
|
||||
issuer: "https://idp.example".into(),
|
||||
client_id: "enterprise-client".into(),
|
||||
client_secret: None,
|
||||
token_endpoint_auth_method: None,
|
||||
})
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
servers.insert(
|
||||
name.to_string(),
|
||||
EffectiveMcpServer::from_host_config(server),
|
||||
);
|
||||
}
|
||||
let runtime_context = McpRuntimeContext::new(
|
||||
Arc::new(environment_manager_without_environments()),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let statuses = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
compute_auth_statuses(
|
||||
servers.iter(),
|
||||
OAuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
Some(&auth),
|
||||
Some(&manager),
|
||||
&crate::EmaState::default(),
|
||||
&runtime_context,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.context("MCP auth status waited for the held account lease")?;
|
||||
assert_eq!(
|
||||
statuses
|
||||
.into_iter()
|
||||
.map(|(name, entry)| (name, entry.auth_state))
|
||||
.collect::<HashMap<_, _>>(),
|
||||
HashMap::from([
|
||||
("first".to_string(), McpAuthState::BearerToken),
|
||||
("second".to_string(), McpAuthState::BearerToken),
|
||||
]),
|
||||
);
|
||||
drop(lease);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures() {
|
||||
let auth_failure = StartupOutcomeError::Failed {
|
||||
error: "OAuth refresh token was rejected".to_string(),
|
||||
is_authentication_required: true,
|
||||
is_ema_authentication_required: false,
|
||||
shutdown: None,
|
||||
};
|
||||
let mut manager = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
|
||||
let mut auth_status_entries = HashMap::new();
|
||||
for (name, auth_state, startup_error) in [
|
||||
(
|
||||
"oauth-failed",
|
||||
McpAuthState::OAuth,
|
||||
Some(auth_failure.clone()),
|
||||
),
|
||||
("oauth-ready", McpAuthState::OAuth, None),
|
||||
(
|
||||
"oauth-provider-error",
|
||||
McpAuthState::OAuth,
|
||||
Some(StartupOutcomeError::Failed {
|
||||
error: "provider temporarily unavailable".to_string(),
|
||||
is_authentication_required: false,
|
||||
is_ema_authentication_required: false,
|
||||
shutdown: None,
|
||||
}),
|
||||
),
|
||||
(
|
||||
"ema-failed",
|
||||
McpAuthState::BearerToken,
|
||||
Some(auth_failure.clone()),
|
||||
),
|
||||
("ema-ready", McpAuthState::BearerToken, None),
|
||||
(
|
||||
"ema-provider-error",
|
||||
McpAuthState::BearerToken,
|
||||
Some(anyhow::anyhow!("provider temporarily unavailable").into()),
|
||||
),
|
||||
("bearer", McpAuthState::BearerToken, Some(auth_failure)),
|
||||
] {
|
||||
let mut client = create_ready_async_managed_client(Vec::new()).await;
|
||||
if let Some(error) = startup_error {
|
||||
client.client = futures::future::ready(Err(error)).boxed().shared();
|
||||
}
|
||||
manager.insert_test_client(name, client);
|
||||
auth_status_entries.insert(
|
||||
name.to_string(),
|
||||
McpAuthStatusEntry {
|
||||
config: name.starts_with("ema-").then(|| {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"url": "https://example.com/mcp", "auth": "ema_auth",
|
||||
}))
|
||||
.expect("EMA config")
|
||||
}),
|
||||
auth_state,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let server_names = auth_status_entries.keys().cloned().collect();
|
||||
let snapshot = collect_mcp_server_status_snapshot_from_manager(
|
||||
&manager,
|
||||
auth_status_entries,
|
||||
server_names,
|
||||
McpSnapshotDetail::ToolsAndAuthOnly,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
snapshot.auth_statuses,
|
||||
HashMap::from([
|
||||
("oauth-failed".to_string(), McpAuthStatus::NotLoggedIn),
|
||||
("oauth-ready".to_string(), McpAuthStatus::OAuth),
|
||||
("oauth-provider-error".to_string(), McpAuthStatus::OAuth),
|
||||
("ema-failed".to_string(), McpAuthStatus::NotLoggedIn),
|
||||
("ema-ready".to_string(), McpAuthStatus::BearerToken),
|
||||
("ema-provider-error".to_string(), McpAuthStatus::BearerToken),
|
||||
("bearer".to_string(), McpAuthStatus::BearerToken),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn test_mcp_config(codex_home: PathBuf) -> McpConfig {
|
||||
McpConfig {
|
||||
chatgpt_base_url: "https://chatgpt.com".to_string(),
|
||||
apps_mcp_product_sku: None,
|
||||
requires_read_only_mcp_tools: false,
|
||||
codex_home,
|
||||
mcp_enterprise_managed_auth: None,
|
||||
ema_state: Default::default(),
|
||||
mcp_ema_cancellation: codex_config::McpEmaCancellation::default(),
|
||||
xaa_enabled: false,
|
||||
mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode::default(),
|
||||
oauth_refresh_mode: McpOAuthRefreshMode::Legacy,
|
||||
auth_keyring_backend_kind: AuthKeyringBackendKind::default(),
|
||||
mcp_oauth_callback_port: None,
|
||||
mcp_oauth_callback_url: None,
|
||||
optional_mcp_startup_grace: DEFAULT_OPTIONAL_MCP_STARTUP_GRACE,
|
||||
skill_mcp_dependency_install_enabled: true,
|
||||
approval_policy: Constrained::allow_any(AskForApproval::OnRequest),
|
||||
permission_profile: PermissionProfile::default(),
|
||||
host_cwd: AbsolutePathBuf::current_dir().expect("test working directory"),
|
||||
config_layer_stack: codex_config::ConfigLayerStack::default(),
|
||||
plugins: Default::default(),
|
||||
approvals_reviewer: codex_config::types::ApprovalsReviewer::default(),
|
||||
environment_cwds: HashMap::new(),
|
||||
environment_use_mxc: HashMap::new(),
|
||||
server_permissions: HashMap::new(),
|
||||
codex_self_exe: None,
|
||||
codex_linux_sandbox_exe: None,
|
||||
use_legacy_landlock: false,
|
||||
apps_enabled: false,
|
||||
apps_early_resource_discovery: false,
|
||||
prefix_mcp_tool_names: true,
|
||||
non_prefixed_mcp_tool_servers: Vec::new(),
|
||||
protocol_mode: McpProtocolMode::Legacy,
|
||||
discover_local_stdio: false,
|
||||
mcp_tool_list_changed: true,
|
||||
host_owned_apps_protocol_mode: McpProtocolMode::Legacy,
|
||||
client_elicitation_capability: ElicitationCapability::default(),
|
||||
mcp_server_catalog: ResolvedMcpCatalog::default(),
|
||||
connector_snapshot: codex_connectors::ConnectorSnapshot::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn test_elicitation_config(
|
||||
server_name: &str,
|
||||
approval_policy: AskForApproval,
|
||||
permission_profile: PermissionProfile,
|
||||
) -> Arc<McpConfig> {
|
||||
let mut config = test_mcp_config(PathBuf::new());
|
||||
config.approval_policy = Constrained::allow_any(approval_policy);
|
||||
config.permission_profile = permission_profile;
|
||||
config
|
||||
.server_permissions
|
||||
.insert(server_name.to_string(), McpServerPermissions::Thread);
|
||||
Arc::new(config)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ema_catalog_allows_only_configured_servers_without_widening_policy() {
|
||||
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
|
||||
"url": "https://resource.example/mcp", "auth": "ema_auth",
|
||||
"oauth": { "client_id": "resource-client", "authorization_server_issuer": "https://as.example" }
|
||||
})).unwrap();
|
||||
let plugin = McpPluginAttribution::agent_plugin("plugin@test".into(), "Plugin".into());
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_config(
|
||||
"configured".into(),
|
||||
server.clone(),
|
||||
));
|
||||
catalog.register(McpServerRegistration::from_plugin(
|
||||
"installed".into(),
|
||||
plugin.clone(),
|
||||
/*plugin_order*/ 0,
|
||||
server.clone(),
|
||||
));
|
||||
catalog.register(McpServerRegistration::from_selected_plugin(
|
||||
"selected".into(),
|
||||
plugin,
|
||||
/*selection_order*/ 0,
|
||||
codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
|
||||
server,
|
||||
));
|
||||
let mut config = test_mcp_config(PathBuf::new());
|
||||
let idp = codex_config::McpServerIdpOAuthConfig {
|
||||
issuer: "https://idp.example".into(),
|
||||
client_secret: None,
|
||||
token_endpoint_auth_method: None,
|
||||
client_id: "enterprise-client".into(),
|
||||
};
|
||||
let deny_all = codex_protocol::mcp_policy::EnvironmentMcpPolicy {
|
||||
servers: Some(Default::default()),
|
||||
plugins: None,
|
||||
};
|
||||
for (xaa_enabled, denied) in [(true, false), (true, true), (false, false)] {
|
||||
let mut catalog = catalog.clone();
|
||||
if xaa_enabled {
|
||||
catalog.enable_ema(idp.clone());
|
||||
}
|
||||
config.mcp_server_catalog = catalog.build_with_environment_authority(|_| {
|
||||
if denied {
|
||||
crate::McpEnvironmentAuthority::Restricted(&deny_all)
|
||||
} else {
|
||||
crate::McpEnvironmentAuthority::Unrestricted
|
||||
}
|
||||
});
|
||||
let servers = effective_mcp_servers(&config, /*auth*/ None);
|
||||
for name in ["configured", "installed", "selected"] {
|
||||
let eligible = name == "configured" && xaa_enabled;
|
||||
assert_eq!(servers[name].enabled(), eligible && !denied, "{name}");
|
||||
assert_eq!(servers[name].config().oauth_idp(), eligible.then_some(&idp));
|
||||
assert_eq!(servers[name].config().auth, McpServerAuth::EmaAuth);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qualified_mcp_tool_name_prefix_sanitizes_server_names_without_lowercasing() {
|
||||
assert_eq!(
|
||||
qualified_mcp_tool_name_prefix("Some-Server"),
|
||||
"mcp__Some_Server__".to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_server_permissions_handle_unattached_and_threadless_servers() {
|
||||
let mut config = test_mcp_config(PathBuf::new());
|
||||
config.permission_profile = PermissionProfile::Disabled;
|
||||
let mut missing_server = codex_apps_mcp_server_config(
|
||||
"https://example.com",
|
||||
/*apps_mcp_product_sku*/ None,
|
||||
/*originator*/ None,
|
||||
);
|
||||
missing_server.environment_id = "missing".to_string();
|
||||
let mut selected_server = missing_server.clone();
|
||||
selected_server.environment_id = "unattached".to_string();
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_config(
|
||||
"missing".to_string(),
|
||||
missing_server,
|
||||
));
|
||||
catalog.register(McpServerRegistration::from_selected_plugin(
|
||||
"selected".to_string(),
|
||||
McpPluginAttribution::new("selected@test".to_string(), "Selected".to_string()),
|
||||
/*selection_order*/ 0,
|
||||
codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
|
||||
selected_server,
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
let servers = effective_mcp_servers(&config, /*auth*/ None);
|
||||
assert_eq!(config.permission_profile_for_server("selected"), None);
|
||||
config.set_server_permissions(&servers, std::iter::empty());
|
||||
|
||||
assert_eq!(
|
||||
config.permission_profile_for_server("selected"),
|
||||
Some(&PermissionProfile::Disabled)
|
||||
);
|
||||
assert_eq!(config.permission_profile_for_server("missing"), None);
|
||||
|
||||
let config = config.for_threadless_operations(&servers);
|
||||
assert_eq!(
|
||||
config.permission_profile_for_server("selected"),
|
||||
Some(&PermissionProfile::default())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_prompt_auto_approval_honors_unrestricted_managed_profiles() {
|
||||
assert!(mcp_permission_prompt_is_auto_approved(
|
||||
AskForApproval::Never,
|
||||
&PermissionProfile::Managed {
|
||||
file_system: ManagedFileSystemPermissions::Unrestricted,
|
||||
network: NetworkSandboxPolicy::Enabled,
|
||||
},
|
||||
McpPermissionPromptAutoApproveContext::default(),
|
||||
));
|
||||
assert!(mcp_permission_prompt_is_auto_approved(
|
||||
AskForApproval::Never,
|
||||
&PermissionProfile::Managed {
|
||||
file_system: ManagedFileSystemPermissions::Unrestricted,
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
},
|
||||
McpPermissionPromptAutoApproveContext::default(),
|
||||
));
|
||||
assert!(!mcp_permission_prompt_is_auto_approved(
|
||||
AskForApproval::Never,
|
||||
&PermissionProfile::read_only(),
|
||||
McpPermissionPromptAutoApproveContext::default(),
|
||||
));
|
||||
assert!(!mcp_permission_prompt_is_auto_approved(
|
||||
AskForApproval::OnRequest,
|
||||
&PermissionProfile::Managed {
|
||||
file_system: ManagedFileSystemPermissions::Unrestricted,
|
||||
network: NetworkSandboxPolicy::Enabled,
|
||||
},
|
||||
McpPermissionPromptAutoApproveContext::default(),
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_prompt_auto_approval_honors_approved_tools_in_all_permission_modes() {
|
||||
for approval_policy in [
|
||||
AskForApproval::UnlessTrusted,
|
||||
AskForApproval::OnRequest,
|
||||
AskForApproval::Granular(GranularApprovalConfig {
|
||||
sandbox_approval: true,
|
||||
rules: true,
|
||||
skill_approval: true,
|
||||
request_permissions: true,
|
||||
mcp_elicitations: true,
|
||||
}),
|
||||
AskForApproval::Never,
|
||||
] {
|
||||
assert!(mcp_permission_prompt_is_auto_approved(
|
||||
approval_policy,
|
||||
&PermissionProfile::read_only(),
|
||||
McpPermissionPromptAutoApproveContext {
|
||||
tool_approval_mode: Some(AppToolApproval::Approve),
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
assert!(!mcp_permission_prompt_is_auto_approved(
|
||||
AskForApproval::OnRequest,
|
||||
&PermissionProfile::read_only(),
|
||||
McpPermissionPromptAutoApproveContext {
|
||||
tool_approval_mode: Some(AppToolApproval::Auto),
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_plugin_context_collects_app_and_mcp_sources() {
|
||||
let mut config = test_mcp_config(PathBuf::new());
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_plugin(
|
||||
"alpha".to_string(),
|
||||
McpPluginAttribution::new("alpha@test".to_string(), "alpha-plugin".to_string()),
|
||||
/*plugin_order*/ 0,
|
||||
codex_apps_mcp_server_config(
|
||||
"https://alpha.example",
|
||||
/*apps_mcp_product_sku*/ None,
|
||||
/*originator*/ None,
|
||||
),
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
config.connector_snapshot =
|
||||
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(&[
|
||||
PluginCapabilitySummary {
|
||||
config_name: "alpha@test".to_string(),
|
||||
display_name: "alpha-plugin".to_string(),
|
||||
plugin_namespace: None,
|
||||
app_connector_ids: vec![AppConnectorId("connector_example".to_string())],
|
||||
mcp_server_names: vec!["alpha".to_string()],
|
||||
..PluginCapabilitySummary::default()
|
||||
},
|
||||
PluginCapabilitySummary {
|
||||
config_name: "beta@test".to_string(),
|
||||
display_name: "beta-plugin".to_string(),
|
||||
plugin_namespace: None,
|
||||
app_connector_ids: vec![
|
||||
AppConnectorId("connector_example".to_string()),
|
||||
AppConnectorId("connector_gmail".to_string()),
|
||||
],
|
||||
mcp_server_names: vec!["beta".to_string()],
|
||||
..PluginCapabilitySummary::default()
|
||||
},
|
||||
]);
|
||||
let provenance = tool_plugin_context(&config);
|
||||
|
||||
assert_eq!(
|
||||
provenance,
|
||||
ToolPluginContext {
|
||||
disabled_connector_ids: HashSet::new(),
|
||||
plugin_display_names_by_connector_id: HashMap::from([
|
||||
(
|
||||
"connector_example".to_string(),
|
||||
vec!["alpha-plugin".to_string(), "beta-plugin".to_string()],
|
||||
),
|
||||
(
|
||||
"connector_gmail".to_string(),
|
||||
vec!["beta-plugin".to_string()],
|
||||
),
|
||||
]),
|
||||
plugin_display_names_by_mcp_server_name: HashMap::from([(
|
||||
"alpha".to_string(),
|
||||
vec!["alpha-plugin".to_string()],
|
||||
)]),
|
||||
plugin_ids_by_mcp_server_name: HashMap::from([(
|
||||
"alpha".to_string(),
|
||||
"alpha@test".to_string(),
|
||||
)]),
|
||||
selected_plugin_mcp_server_names: HashSet::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
provenance.plugin_id_for_mcp_server_name("alpha"),
|
||||
Some("alpha@test")
|
||||
);
|
||||
assert_eq!(provenance.plugin_id_for_mcp_server_name("beta"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_mcp_attribution_does_not_join_an_unrelated_local_summary() {
|
||||
let mut config = test_mcp_config(PathBuf::new());
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_selected_plugin(
|
||||
"github".to_string(),
|
||||
McpPluginAttribution::new(
|
||||
"shared-plugin-id".to_string(),
|
||||
"Executor GitHub".to_string(),
|
||||
),
|
||||
/*selection_order*/ 0,
|
||||
"executor-1",
|
||||
codex_apps_mcp_server_config(
|
||||
"https://github.example",
|
||||
/*apps_mcp_product_sku*/ None,
|
||||
/*originator*/ None,
|
||||
),
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
config.connector_snapshot =
|
||||
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(&[
|
||||
PluginCapabilitySummary {
|
||||
config_name: "shared-plugin-id".to_string(),
|
||||
display_name: "Local GitHub".to_string(),
|
||||
plugin_namespace: None,
|
||||
mcp_server_names: vec!["github".to_string()],
|
||||
..PluginCapabilitySummary::default()
|
||||
},
|
||||
]);
|
||||
|
||||
let provenance = tool_plugin_context(&config);
|
||||
|
||||
assert_eq!(
|
||||
provenance,
|
||||
ToolPluginContext {
|
||||
disabled_connector_ids: HashSet::new(),
|
||||
plugin_display_names_by_connector_id: HashMap::new(),
|
||||
plugin_display_names_by_mcp_server_name: HashMap::from([(
|
||||
"github".to_string(),
|
||||
vec!["Executor GitHub".to_string()],
|
||||
)]),
|
||||
plugin_ids_by_mcp_server_name: HashMap::from([(
|
||||
"github".to_string(),
|
||||
"shared-plugin-id".to_string(),
|
||||
)]),
|
||||
selected_plugin_mcp_server_names: HashSet::from(["github".to_string()]),
|
||||
}
|
||||
);
|
||||
assert!(provenance.is_selected_plugin_mcp_server("github"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_mcp_url_for_base_url_uses_plugin_service_paths() {
|
||||
assert_eq!(
|
||||
codex_apps_mcp_url_for_base_url("https://chatgpt.com/backend-api"),
|
||||
"https://chatgpt.com/backend-api/ps/mcp"
|
||||
);
|
||||
assert_eq!(
|
||||
codex_apps_mcp_url_for_base_url("https://chat.openai.com"),
|
||||
"https://chat.openai.com/backend-api/ps/mcp"
|
||||
);
|
||||
assert_eq!(
|
||||
codex_apps_mcp_url_for_base_url("https://gov.chatgpt.com/backend-api/"),
|
||||
"https://gov.chatgpt.com/backend-api/ps/mcp"
|
||||
);
|
||||
assert_eq!(
|
||||
codex_apps_mcp_url_for_base_url("http://localhost:8080/api/codex"),
|
||||
"http://localhost:8080/api/codex/ps/mcp"
|
||||
);
|
||||
assert_eq!(
|
||||
codex_apps_mcp_url_for_base_url("http://localhost:8080"),
|
||||
"http://localhost:8080/api/codex/ps/mcp"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_server_config_uses_plugin_service_path() {
|
||||
let config = codex_apps_mcp_server_config(
|
||||
"https://chatgpt.com",
|
||||
/*apps_mcp_product_sku*/ None,
|
||||
/*originator*/ None,
|
||||
);
|
||||
let url = match &config.transport {
|
||||
McpServerTransportConfig::StreamableHttp { url, .. } => url,
|
||||
_ => panic!("expected streamable http transport for codex apps"),
|
||||
};
|
||||
|
||||
assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_server_config_forwards_thread_originator_header() {
|
||||
let config = codex_apps_mcp_server_config(
|
||||
"https://chatgpt.com",
|
||||
/*apps_mcp_product_sku*/ None,
|
||||
Some("thread_originator"),
|
||||
);
|
||||
|
||||
match &config.transport {
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
http_headers,
|
||||
&Some(HashMap::from([
|
||||
("originator".to_string(), "thread_originator".to_string()),
|
||||
("X-OpenAI-Product-Sku".to_string(), "codex".to_string()),
|
||||
]))
|
||||
);
|
||||
assert!(env_http_headers.is_none());
|
||||
}
|
||||
other => panic!("expected streamable http transport, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_server_config_sets_product_sku_header() {
|
||||
for (configured_product_sku, expected_product_sku) in [(None, "codex"), (Some("tpp"), "tpp")] {
|
||||
let config = codex_apps_mcp_server_config(
|
||||
"https://chatgpt.com",
|
||||
configured_product_sku,
|
||||
/*originator*/ None,
|
||||
);
|
||||
|
||||
match &config.transport {
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
http_headers,
|
||||
&Some(HashMap::from([(
|
||||
"X-OpenAI-Product-Sku".to_string(),
|
||||
expected_product_sku.to_string(),
|
||||
)]))
|
||||
);
|
||||
assert!(env_http_headers.is_none());
|
||||
}
|
||||
other => panic!("expected streamable http transport, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_apps_server_config_forwards_originator_and_configured_product_sku_headers() {
|
||||
let config = codex_apps_mcp_server_config(
|
||||
"https://chatgpt.com",
|
||||
Some("tpp"),
|
||||
Some("thread_originator"),
|
||||
);
|
||||
|
||||
match &config.transport {
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
http_headers,
|
||||
&Some(HashMap::from([
|
||||
("originator".to_string(), "thread_originator".to_string()),
|
||||
("X-OpenAI-Product-Sku".to_string(), "tpp".to_string()),
|
||||
]))
|
||||
);
|
||||
assert!(env_http_headers.is_none());
|
||||
}
|
||||
other => panic!("expected streamable http transport, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_mcp_servers_preserve_executor_credential_policy() {
|
||||
let mut config = test_mcp_config(PathBuf::new());
|
||||
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
|
||||
"url": "https://executor.example/mcp",
|
||||
"environment_id": "remote",
|
||||
"bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
|
||||
}))
|
||||
.expect("valid MCP server config");
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_executor_config(
|
||||
"executor".to_string(),
|
||||
server.clone(),
|
||||
));
|
||||
catalog.register(McpServerRegistration::from_config(
|
||||
"host".to_string(),
|
||||
server,
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
let effective = effective_mcp_servers(&config, /*auth*/ None);
|
||||
|
||||
assert_eq!(
|
||||
effective["executor"].credential_policy(),
|
||||
McpCredentialPolicy::ExecutorOnly,
|
||||
);
|
||||
assert_eq!(
|
||||
effective["host"].credential_policy(),
|
||||
McpCredentialPolicy::HostFallbackAllowed,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "materialized MCP server must have a catalog registration")]
|
||||
fn effective_mcp_servers_require_catalog_registration() {
|
||||
let config = test_mcp_config(PathBuf::new());
|
||||
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
|
||||
"url": "https://executor.example/mcp",
|
||||
"environment_id": "remote",
|
||||
"bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
|
||||
}))
|
||||
.expect("valid MCP server config");
|
||||
|
||||
effective_mcp_servers_from_configured(
|
||||
HashMap::from([("unregistered".to_string(), server)]),
|
||||
&config,
|
||||
/*auth*/ None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_mcp_servers_preserve_chatgpt_auth_for_trusted_origins() {
|
||||
for (base_url, server_url) in [
|
||||
("https://chatgpt-staging.com", "https://chatgpt-staging.com"),
|
||||
(
|
||||
"https://preview.chatgpt-staging.com",
|
||||
"https://preview.chatgpt-staging.com",
|
||||
),
|
||||
("https://gov.chatgpt.com", "https://chatgpt.com"),
|
||||
(
|
||||
"https://chatgpt.com",
|
||||
"https://gov.chatgpt.com/backend-api/",
|
||||
),
|
||||
("https://chatgpt.com", "https://GOV.CHATGPT.COM:443"),
|
||||
] {
|
||||
let mut config = test_mcp_config(PathBuf::new());
|
||||
config.chatgpt_base_url = base_url.to_string();
|
||||
let server = codex_apps_mcp_server_config(
|
||||
server_url, /*apps_mcp_product_sku*/ None, /*originator*/ None,
|
||||
);
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_config(
|
||||
"trusted".to_string(),
|
||||
server,
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
|
||||
let effective = effective_mcp_servers(&config, /*auth*/ None);
|
||||
|
||||
assert_eq!(
|
||||
effective["trusted"].config().auth,
|
||||
McpServerAuth::ChatGpt,
|
||||
"backend {base_url}, server {server_url}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_mcp_servers_reject_untrusted_origins_for_chatgpt_auth() {
|
||||
for url in [
|
||||
"http://gov.chatgpt.com",
|
||||
"https://gov.chatgpt.com:8443",
|
||||
"https://gov.chatgpt.com.evil.example",
|
||||
"https://sub.gov.chatgpt.com",
|
||||
"https://gov.chatgpt.com.",
|
||||
"https://gov.chatgpt.com@evil.example",
|
||||
"https://example.com",
|
||||
] {
|
||||
let mut config = test_mcp_config(PathBuf::new());
|
||||
config.chatgpt_base_url = url.to_string();
|
||||
let server = codex_apps_mcp_server_config(
|
||||
url, /*apps_mcp_product_sku*/ None, /*originator*/ None,
|
||||
);
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_config(
|
||||
"untrusted".to_string(),
|
||||
server,
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
|
||||
let effective = effective_mcp_servers(&config, /*auth*/ None);
|
||||
|
||||
assert_eq!(
|
||||
effective["untrusted"].config().auth,
|
||||
McpServerAuth::OAuth,
|
||||
"server {url}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn effective_mcp_servers_preserve_runtime_servers() {
|
||||
let codex_home = tempfile::tempdir().expect("tempdir");
|
||||
let mut config = test_mcp_config(codex_home.path().to_path_buf());
|
||||
config.apps_enabled = true;
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_config(
|
||||
"sample".to_string(),
|
||||
McpServerConfig {
|
||||
auth: Default::default(),
|
||||
transport: McpServerTransportConfig::StreamableHttp {
|
||||
url: "https://user.example/mcp".to_string(),
|
||||
bearer_token_env_var: None,
|
||||
http_headers: None,
|
||||
env_http_headers: None,
|
||||
http_headers_helper: None,
|
||||
},
|
||||
environment_id: codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
|
||||
enabled: true,
|
||||
required: false,
|
||||
startup_readiness: Default::default(),
|
||||
supports_parallel_tool_calls: false,
|
||||
tool_input_schema_max_bytes: None,
|
||||
omit_tools_from: None,
|
||||
disabled_reason: None,
|
||||
startup_timeout_sec: None,
|
||||
tool_timeout_sec: None,
|
||||
default_tools_approval_mode: None,
|
||||
enabled_tools: None,
|
||||
disabled_tools: None,
|
||||
scopes: None,
|
||||
oauth: None,
|
||||
oauth_resource: None,
|
||||
tools: HashMap::new(),
|
||||
},
|
||||
));
|
||||
catalog.register(McpServerRegistration::from_config(
|
||||
"docs".to_string(),
|
||||
McpServerConfig {
|
||||
auth: Default::default(),
|
||||
transport: McpServerTransportConfig::StreamableHttp {
|
||||
url: "https://docs.example/mcp".to_string(),
|
||||
bearer_token_env_var: None,
|
||||
http_headers: None,
|
||||
env_http_headers: None,
|
||||
http_headers_helper: None,
|
||||
},
|
||||
environment_id: codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
|
||||
enabled: true,
|
||||
required: false,
|
||||
startup_readiness: Default::default(),
|
||||
supports_parallel_tool_calls: false,
|
||||
tool_input_schema_max_bytes: None,
|
||||
omit_tools_from: None,
|
||||
disabled_reason: None,
|
||||
startup_timeout_sec: None,
|
||||
tool_timeout_sec: None,
|
||||
default_tools_approval_mode: None,
|
||||
enabled_tools: None,
|
||||
disabled_tools: None,
|
||||
scopes: None,
|
||||
oauth: None,
|
||||
oauth_resource: None,
|
||||
tools: HashMap::new(),
|
||||
},
|
||||
));
|
||||
catalog.register(McpServerRegistration::from_config(
|
||||
CODEX_APPS_MCP_SERVER_NAME.to_string(),
|
||||
codex_apps_mcp_server_config(
|
||||
&config.chatgpt_base_url,
|
||||
config.apps_mcp_product_sku.as_deref(),
|
||||
/*originator*/ None,
|
||||
),
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
|
||||
let effective = effective_mcp_servers(&config, Some(&auth));
|
||||
|
||||
let sample = effective.get("sample").expect("user server should exist");
|
||||
let docs = effective
|
||||
.get("docs")
|
||||
.expect("configured server should exist");
|
||||
let codex_apps = effective
|
||||
.get(CODEX_APPS_MCP_SERVER_NAME)
|
||||
.expect("codex apps server should exist");
|
||||
|
||||
let sample = sample.config();
|
||||
let docs = docs.config();
|
||||
let codex_apps = codex_apps.config();
|
||||
|
||||
match &sample.transport {
|
||||
McpServerTransportConfig::StreamableHttp { url, .. } => {
|
||||
assert_eq!(url, "https://user.example/mcp");
|
||||
}
|
||||
other => panic!("expected streamable http transport, got {other:?}"),
|
||||
}
|
||||
match &docs.transport {
|
||||
McpServerTransportConfig::StreamableHttp { url, .. } => {
|
||||
assert_eq!(url, "https://docs.example/mcp");
|
||||
}
|
||||
other => panic!("expected streamable http transport, got {other:?}"),
|
||||
}
|
||||
match &codex_apps.transport {
|
||||
McpServerTransportConfig::StreamableHttp { url, .. } => {
|
||||
assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp");
|
||||
}
|
||||
other => panic!("expected streamable http transport, got {other:?}"),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user