Persist MCP OAuth callback URL on add

This commit is contained in:
Steven Lee
2026-06-17 18:11:38 +00:00
parent 18b3cfcb60
commit 77ee5ee7a2
15 changed files with 212 additions and 31 deletions
@@ -169,7 +169,9 @@ impl McpRequestProcessor {
server.oauth_resource.as_deref(),
timeout_secs,
config.mcp_oauth_callback_port,
config.mcp_oauth_callback_url.as_deref(),
server
.oauth_callback_url()
.or(config.mcp_oauth_callback_url.as_deref()),
)
.await
.map_err(|err| internal_error(format!("failed to login to MCP server '{name}': {err}")))?;
@@ -1737,7 +1737,10 @@ impl PluginRequestProcessor {
let store_mode = config.mcp_oauth_credentials_store_mode;
let keyring_backend_kind = config.auth_keyring_backend_kind();
let callback_port = config.mcp_oauth_callback_port;
let callback_url = config.mcp_oauth_callback_url.clone();
let callback_url = server
.oauth_callback_url()
.map(str::to_string)
.or_else(|| config.mcp_oauth_callback_url.clone());
let outgoing = Arc::clone(&self.outgoing);
let notification_name = name.clone();
+56 -11
View File
@@ -1,3 +1,4 @@
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::sync::Arc;
@@ -239,7 +240,7 @@ async fn perform_oauth_login_retry_without_scopes(
callback_port: Option<u16>,
callback_url: Option<&str>,
callback_url_output: OAuthCallbackUrlOutput,
) -> Result<()> {
) -> Result<Option<String>> {
match run_oauth_login(
name,
url,
@@ -256,7 +257,7 @@ async fn perform_oauth_login_retry_without_scopes(
)
.await
{
Ok(()) => Ok(()),
Ok(callback_url) => Ok(callback_url),
Err(err) if should_retry_without_scopes(resolved_scopes, &err) => {
println!("OAuth provider rejected discovered scopes. Retrying without scopes…");
run_oauth_login(
@@ -293,10 +294,10 @@ async fn run_oauth_login(
callback_port: Option<u16>,
callback_url: Option<&str>,
callback_url_output: OAuthCallbackUrlOutput,
) -> Result<()> {
) -> Result<Option<String>> {
match callback_url_output {
OAuthCallbackUrlOutput::Print => {
perform_oauth_login_print_callback_url(
let output = perform_oauth_login_print_callback_url(
name,
url,
store_mode,
@@ -309,7 +310,8 @@ async fn run_oauth_login(
callback_port,
callback_url,
)
.await
.await?;
Ok(Some(output.callback_url))
}
OAuthCallbackUrlOutput::Suppress => {
perform_oauth_login(
@@ -325,7 +327,8 @@ async fn run_oauth_login(
callback_port,
callback_url,
)
.await
.await?;
Ok(None)
}
}
}
@@ -433,6 +436,7 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re
.clone()
.map(|client_id| McpServerOAuthConfig {
client_id: Some(client_id),
callback_url: None,
}),
oauth_resource: oauth_resource.clone(),
tools: HashMap::new(),
@@ -443,7 +447,9 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re
match resolve_mcp_oauth_callback_url(
url,
config.mcp_oauth_callback_port,
config.mcp_oauth_callback_url.as_deref(),
new_entry
.oauth_callback_url()
.or(config.mcp_oauth_callback_url.as_deref()),
) {
Ok(callback_url) => Some(Ok(callback_url)),
Err(err)
@@ -477,7 +483,7 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re
/*configured_scopes*/ None,
oauth_config.discovered_scopes.clone(),
);
perform_oauth_login_retry_without_scopes(
let persisted_callback_url = perform_oauth_login_retry_without_scopes(
&name,
&oauth_config.url,
config.mcp_oauth_credentials_store_mode,
@@ -488,10 +494,17 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re
oauth_client_id.as_deref(),
oauth_resource.as_deref(),
config.mcp_oauth_callback_port,
config.mcp_oauth_callback_url.as_deref(),
servers
.get(&name)
.and_then(McpServerConfig::oauth_callback_url)
.or(config.mcp_oauth_callback_url.as_deref()),
OAuthCallbackUrlOutput::Print,
)
.await?;
if let Some(callback_url) = persisted_callback_url {
persist_server_oauth_callback_url(&codex_home, &mut servers, &name, callback_url)
.await?;
}
println!("Successfully logged in.");
}
McpOAuthLoginSupport::Unsupported => print_precomputed_oauth_callback_url(&callback_url),
@@ -512,6 +525,34 @@ fn print_precomputed_oauth_callback_url(callback_url: &Option<Result<String>>) {
}
}
async fn persist_server_oauth_callback_url(
codex_home: &std::path::Path,
servers: &mut BTreeMap<String, McpServerConfig>,
name: &str,
callback_url: String,
) -> Result<()> {
let server = servers
.get_mut(name)
.ok_or_else(|| anyhow!("No MCP server named '{name}' found."))?;
let oauth = server.oauth.get_or_insert_with(|| McpServerOAuthConfig {
client_id: None,
callback_url: None,
});
if oauth.callback_url.as_deref() == Some(callback_url.as_str()) {
return Ok(());
}
oauth.callback_url = Some(callback_url);
ConfigEditsBuilder::new(codex_home)
.replace_mcp_servers(servers)
.apply()
.await
.with_context(|| format!("failed to write MCP servers to {}", codex_home.display()))?;
Ok(())
}
async fn run_remove(config_overrides: &CliConfigOverrides, remove_args: RemoveArgs) -> Result<()> {
config_overrides
.parse_overrides()
@@ -593,7 +634,9 @@ async fn run_login(config_overrides: &CliConfigOverrides, login_args: LoginArgs)
server.oauth_client_id(),
server.oauth_resource.as_deref(),
config.mcp_oauth_callback_port,
config.mcp_oauth_callback_url.as_deref(),
server
.oauth_callback_url()
.or(config.mcp_oauth_callback_url.as_deref()),
OAuthCallbackUrlOutput::Suppress,
)
.await?;
@@ -630,7 +673,9 @@ async fn run_callback_url(
let callback_url = resolve_mcp_oauth_callback_url(
url,
config.mcp_oauth_callback_port,
config.mcp_oauth_callback_url.as_deref(),
server
.oauth_callback_url()
.or(config.mcp_oauth_callback_url.as_deref()),
)?;
println!("{callback_url}");
Ok(())
@@ -79,6 +79,7 @@ fn declared_placement_preserves_local_plugin_normalization() {
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: Some("client-id".to_string()),
callback_url: None,
}),
oauth_resource: None,
tools: HashMap::new(),
+14 -6
View File
@@ -212,14 +212,22 @@ fn serialize_mcp_server(config: &McpServerConfig) -> TomlItem {
{
entry["scopes"] = array_from_strings(scopes);
}
if let Some(oauth) = &config.oauth
&& let Some(client_id) = &oauth.client_id
&& !client_id.is_empty()
{
if let Some(oauth) = &config.oauth {
let mut oauth_table = TomlTable::new();
oauth_table.set_implicit(false);
oauth_table["client_id"] = value(client_id.clone());
entry["oauth"] = TomlItem::Table(oauth_table);
if let Some(client_id) = &oauth.client_id
&& !client_id.is_empty()
{
oauth_table["client_id"] = value(client_id.clone());
}
if let Some(callback_url) = &oauth.callback_url
&& !callback_url.is_empty()
{
oauth_table["callback_url"] = value(callback_url.clone());
}
if !oauth_table.is_empty() {
entry["oauth"] = TomlItem::Table(oauth_table);
}
}
if let Some(resource) = &config.oauth_resource
&& !resource.is_empty()
+62
View File
@@ -114,6 +114,7 @@ async fn replace_mcp_servers_serializes_oauth_client_id() -> anyhow::Result<()>
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: Some("eci-prd-pub-codex-123".to_string()),
callback_url: None,
}),
oauth_resource: None,
tools: HashMap::new(),
@@ -144,3 +145,64 @@ client_id = "eci-prd-pub-codex-123"
Ok(())
}
#[tokio::test]
async fn replace_mcp_servers_serializes_oauth_callback_url() -> anyhow::Result<()> {
let unique_suffix = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
let codex_home = std::env::temp_dir().join(format!(
"codex-config-mcp-oauth-callback-edit-test-{}-{unique_suffix}",
std::process::id()
));
let servers = BTreeMap::from([(
"notion".to_string(),
McpServerConfig {
transport: McpServerTransportConfig::StreamableHttp {
url: "https://mcp.notion.com/mcp".to_string(),
bearer_token_env_var: None,
http_headers: None,
env_http_headers: None,
},
environment_id: crate::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
supports_parallel_tool_calls: false,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: None,
callback_url: Some("http://127.0.0.1:55250/callback".to_string()),
}),
oauth_resource: None,
tools: HashMap::new(),
},
)]);
ConfigEditsBuilder::new(&codex_home)
.replace_mcp_servers(&servers)
.apply()
.await?;
let config_path = codex_home.join(CONFIG_TOML_FILE);
let serialized = std::fs::read_to_string(&config_path)?;
assert_eq!(
serialized,
r#"[mcp_servers.notion]
url = "https://mcp.notion.com/mcp"
[mcp_servers.notion.oauth]
callback_url = "http://127.0.0.1:55250/callback"
"#
);
let loaded = load_global_mcp_servers(&codex_home).await?;
assert_eq!(loaded, servers);
std::fs::remove_dir_all(&codex_home)?;
Ok(())
}
+12
View File
@@ -124,6 +124,12 @@ pub struct McpServerOAuthConfig {
/// Explicit OAuth client identifier to present during authorization and token exchange.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
/// OAuth callback URL base to use for this server.
///
/// Codex appends the deterministic callback ID suffix derived from the MCP server URL.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub callback_url: Option<String>,
}
#[derive(Serialize, Debug, Clone, PartialEq)]
@@ -201,6 +207,12 @@ impl McpServerConfig {
.as_ref()
.and_then(|oauth| oauth.client_id.as_deref())
}
pub fn oauth_callback_url(&self) -> Option<&str> {
self.oauth
.as_ref()
.and_then(|oauth| oauth.callback_url.as_deref())
}
}
/// Raw MCP config shape used for deserialization and supported-field JSON
+22
View File
@@ -355,6 +355,28 @@ fn deserialize_streamable_http_server_config_with_oauth_client_id() {
cfg.oauth,
Some(McpServerOAuthConfig {
client_id: Some("eci-prd-pub-codex-123".to_string()),
callback_url: None,
})
);
}
#[test]
fn deserialize_streamable_http_server_config_with_oauth_callback_url() {
let cfg: McpServerConfig = toml::from_str(
r#"
url = "https://example.com/mcp"
[oauth]
callback_url = "http://127.0.0.1:4321/callback"
"#,
)
.expect("should deserialize http config with oauth callback url");
assert_eq!(
cfg.oauth,
Some(McpServerOAuthConfig {
client_id: None,
callback_url: Some("http://127.0.0.1:4321/callback".to_string()),
})
);
}
@@ -647,6 +647,7 @@ async fn load_plugins_loads_default_skills_and_mcp_servers() {
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: Some("client-id".to_string()),
callback_url: None,
}),
oauth_resource: None,
tools: HashMap::new(),
+5 -1
View File
@@ -1323,6 +1323,10 @@
"additionalProperties": false,
"description": "OAuth client settings used when Codex launches an MCP OAuth flow.",
"properties": {
"callback_url": {
"description": "OAuth callback URL base to use for this server.\n\nCodex appends the deterministic callback ID suffix derived from the MCP server URL.",
"type": "string"
},
"client_id": {
"description": "Explicit OAuth client identifier to present during authorization and token exchange.",
"type": "string"
@@ -5280,4 +5284,4 @@
},
"title": "ConfigToml",
"type": "object"
}
}
+1
View File
@@ -6376,6 +6376,7 @@ async fn replace_mcp_servers_streamable_http_serializes_oauth_resource() -> anyh
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: Some("eci-prd-pub-codex-123".to_string()),
callback_url: None,
}),
oauth_resource: Some("https://resource.example.com".to_string()),
tools: HashMap::new(),
+1
View File
@@ -930,6 +930,7 @@ fn blocking_replace_mcp_servers_round_trips() {
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: Some("eci-prd-pub-codex-123".to_string()),
callback_url: None,
}),
oauth_resource: Some("https://resource.example.com".to_string()),
tools: HashMap::new(),
+6 -2
View File
@@ -159,7 +159,9 @@ pub(crate) async fn maybe_install_mcp_dependencies(
oauth_client_id,
server_config.oauth_resource.as_deref(),
config.mcp_oauth_callback_port,
config.mcp_oauth_callback_url.as_deref(),
server_config
.oauth_callback_url()
.or(config.mcp_oauth_callback_url.as_deref()),
)
.await;
@@ -176,7 +178,9 @@ pub(crate) async fn maybe_install_mcp_dependencies(
oauth_client_id,
server_config.oauth_resource.as_deref(),
config.mcp_oauth_callback_port,
config.mcp_oauth_callback_url.as_deref(),
server_config
.oauth_callback_url()
.or(config.mcp_oauth_callback_url.as_deref()),
)
.await
{
+1
View File
@@ -22,6 +22,7 @@ pub use oauth::WrappedOAuthTokenResponse;
pub use oauth::delete_oauth_tokens;
pub(crate) use oauth::load_oauth_tokens;
pub use oauth::save_oauth_tokens;
pub use perform_oauth_login::OAuthLoginOutput;
pub use perform_oauth_login::OAuthProviderError;
pub use perform_oauth_login::OauthLoginHandle;
pub use perform_oauth_login::perform_oauth_login;
@@ -107,6 +107,7 @@ pub async fn perform_oauth_login(
CallbackUrlOutput::Suppress,
)
.await
.map(|_| ())
}
#[allow(clippy::too_many_arguments)]
@@ -139,6 +140,7 @@ pub async fn perform_oauth_login_silent(
CallbackUrlOutput::Suppress,
)
.await
.map(|_| ())
}
#[allow(clippy::too_many_arguments)]
@@ -154,7 +156,7 @@ pub async fn perform_oauth_login_print_callback_url(
oauth_resource: Option<&str>,
callback_port: Option<u16>,
callback_url: Option<&str>,
) -> Result<()> {
) -> Result<OAuthLoginOutput> {
perform_oauth_login_with_browser_output(
server_name,
server_url,
@@ -173,6 +175,11 @@ pub async fn perform_oauth_login_print_callback_url(
.await
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthLoginOutput {
pub callback_url: String,
}
#[allow(clippy::too_many_arguments)]
async fn perform_oauth_login_with_browser_output(
server_name: &str,
@@ -188,7 +195,7 @@ async fn perform_oauth_login_with_browser_output(
callback_url: Option<&str>,
emit_browser_url: bool,
callback_url_output: CallbackUrlOutput,
) -> Result<()> {
) -> Result<OAuthLoginOutput> {
let headers = OauthHeaders {
http_headers,
env_http_headers,
@@ -394,6 +401,7 @@ impl OauthLoginHandle {
struct OauthLoginFlow {
auth_url: String,
redirect_uri_base: String,
redirect_uri: String,
oauth_state: OAuthState,
rx: oneshot::Receiver<CallbackResult>,
@@ -473,12 +481,13 @@ fn resolve_redirect_uri(
server: &Server,
server_url: &str,
callback_url: Option<&str>,
) -> Result<String> {
let redirect_uri = match callback_url {
) -> Result<(String, String)> {
let redirect_uri_base = match callback_url {
Some(callback_url) => configured_redirect_uri(callback_url)?,
None => local_redirect_uri(server)?,
};
append_callback_id_to_redirect_uri(server_url, &redirect_uri)
let redirect_uri = append_callback_id_to_redirect_uri(server_url, &redirect_uri_base)?;
Ok((redirect_uri_base, redirect_uri))
}
fn callback_id_from_server_url(server_url: &str) -> Result<String> {
@@ -558,7 +567,8 @@ impl OauthLoginFlow {
server: Arc::clone(&server),
};
let redirect_uri = resolve_redirect_uri(&server, server_url, callback_url)?;
let (redirect_uri_base, redirect_uri) =
resolve_redirect_uri(&server, server_url, callback_url)?;
let callback_path = callback_path_from_redirect_uri(&redirect_uri)?;
let (tx, rx) = oneshot::channel();
@@ -590,6 +600,7 @@ impl OauthLoginFlow {
Ok(Self {
auth_url,
redirect_uri_base,
redirect_uri,
oauth_state,
rx,
@@ -611,7 +622,7 @@ impl OauthLoginFlow {
mut self,
emit_browser_url: bool,
callback_url_output: CallbackUrlOutput,
) -> Result<()> {
) -> Result<OAuthLoginOutput> {
if self.launch_browser {
let server_name = &self.server_name;
let auth_url = &self.auth_url;
@@ -676,7 +687,9 @@ impl OauthLoginFlow {
self.keyring_backend_kind,
)?;
Ok(())
Ok(OAuthLoginOutput {
callback_url: self.redirect_uri_base.clone(),
})
}
.await;
@@ -691,7 +704,8 @@ impl OauthLoginFlow {
tokio::spawn(async move {
let result = self
.finish(/*emit_browser_url*/ false, CallbackUrlOutput::Suppress)
.await;
.await
.map(|_| ());
if let Err(err) = &result {
eprintln!(