Base: codex-main originale (prima del fork aKode)
This commit is contained in:
20
codex-rs/ext/mcp/src/catalog_observability.rs
Normal file
20
codex-rs/ext/mcp/src/catalog_observability.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
//! Measures published cloud and V2 executor plugin catalogs, excluding cached reads.
|
||||
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_extension_api::record_catalog_entries;
|
||||
|
||||
pub(crate) fn record_catalog(
|
||||
metrics: Option<&dyn ExtensionMetrics>,
|
||||
stage: &'static str,
|
||||
catalog: &PluginCatalog,
|
||||
) {
|
||||
record_catalog_entries(
|
||||
metrics,
|
||||
"codex.plugins.catalog.entries",
|
||||
stage,
|
||||
catalog.entries.len(),
|
||||
catalog.is_partial,
|
||||
catalog.warnings.len(),
|
||||
);
|
||||
}
|
||||
249
codex-rs/ext/mcp/src/cloud_plugin.rs
Normal file
249
codex-rs/ext/mcp/src/cloud_plugin.rs
Normal file
@@ -0,0 +1,249 @@
|
||||
//! Refreshes cloud plugins each turn and after auth changes.
|
||||
|
||||
use crate::PluginListQuery;
|
||||
use crate::PluginsThreadState;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use codex_core::config::Config;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_extension_api::CatalogRefreshBackoff;
|
||||
use codex_extension_api::CatalogRefreshInput;
|
||||
use codex_extension_api::ConfigContributor;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_extension_api::TurnLifecycleContributor;
|
||||
use codex_extension_api::TurnStartInput;
|
||||
use codex_extension_api::TurnStartPhase;
|
||||
use codex_features::Feature;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpResourceClientAuthKey;
|
||||
use std::collections::HashSet;
|
||||
|
||||
const MAX_PROJECTED_CLOUD_PLUGINS: usize = 100;
|
||||
pub(crate) const MAX_PLUGIN_DISPLAY_NAME_CHARS: usize = 64;
|
||||
pub(crate) const MAX_CONNECTOR_IDS_PER_PLUGIN: usize = 64;
|
||||
|
||||
/// Auth scope of the latest catalog accepted for this turn.
|
||||
struct LatestCloudPluginAuth(Option<McpResourceClientAuthKey>);
|
||||
|
||||
impl PluginContributor {
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "cloud discovery must remain serialized through fetching and catalog publication"
|
||||
)]
|
||||
async fn refresh_cloud_catalog(&self, input: CatalogRefreshInput<'_>) -> bool {
|
||||
let Some(provider) = &self.providers.cloud else {
|
||||
return false;
|
||||
};
|
||||
let Some(state) = input.thread_store.get::<PluginsThreadState>() else {
|
||||
return false;
|
||||
};
|
||||
// Wait without holding catalog state or the MCP runtime permit, then recheck the cache.
|
||||
let (mut refresh_succeeded, waited) = match state.cloud_refresh_lock.try_lock() {
|
||||
Ok(guard) => (guard, false),
|
||||
Err(_) => (state.cloud_refresh_lock.lock().await, true),
|
||||
};
|
||||
let query = PluginListQuery {
|
||||
thread_id: input.thread_store.level_id().to_string(),
|
||||
turn_id: input.turn_id.to_string(),
|
||||
mcp_resources: input.session_store.get::<McpResourceClient>(),
|
||||
snapshots: Vec::new(),
|
||||
};
|
||||
let (auth_cache_key, resource_cache_key, catalog_cleared) =
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
if !state.plugins_enabled {
|
||||
return false;
|
||||
}
|
||||
let auth = query
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.map(|client| client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME));
|
||||
let resource_cache_key = query
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.and_then(|client| client.server_cache_key(CODEX_APPS_MCP_SERVER_NAME));
|
||||
if ((waited && *refresh_succeeded)
|
||||
|| input
|
||||
.turn_store
|
||||
.get::<LatestCloudPluginAuth>()
|
||||
.is_some_and(|previous| previous.0 == auth))
|
||||
&& state
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.is_some_and(|generation| generation.auth_cache_key == auth)
|
||||
&& state.cloud_catalog().is_some()
|
||||
{
|
||||
input.turn_store.insert(LatestCloudPluginAuth(auth));
|
||||
return false;
|
||||
}
|
||||
if state.cloud_retry.as_ref().is_some_and(|retry| {
|
||||
retry.is_pending(auth.as_ref(), resource_cache_key.as_ref())
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
// Waiting callers must not reuse a failed or cancelled refresh.
|
||||
*refresh_succeeded = false;
|
||||
input.turn_store.remove::<LatestCloudPluginAuth>();
|
||||
let previous_catalog_auth = state
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.filter(|generation| generation.catalog.is_some())
|
||||
.map(|generation| generation.auth_cache_key.clone());
|
||||
let auth_cache_key =
|
||||
state.prepare_cloud_generation(query.mcp_resources.as_deref().cloned());
|
||||
let catalog_cleared =
|
||||
previous_catalog_auth.is_some_and(|previous| previous != auth_cache_key);
|
||||
(auth_cache_key, resource_cache_key, catalog_cleared)
|
||||
};
|
||||
let result = provider.list(query).await;
|
||||
let mut state = state.contributor_state();
|
||||
let catalog_published = match result {
|
||||
Ok(catalog) => {
|
||||
let published = state.publish_cloud_catalog(auth_cache_key.as_ref(), catalog);
|
||||
if published {
|
||||
state.cloud_retry = None;
|
||||
input
|
||||
.turn_store
|
||||
.insert(LatestCloudPluginAuth(auth_cache_key));
|
||||
*refresh_succeeded = true;
|
||||
} else {
|
||||
tracing::debug!("cloud plugin discovery finished after auth changed");
|
||||
}
|
||||
published
|
||||
}
|
||||
Err(_) => {
|
||||
if state.cloud_generation.as_ref().is_some_and(|generation| {
|
||||
generation.auth_cache_key == auth_cache_key && generation.is_auth_current()
|
||||
}) {
|
||||
state.cloud_retry = Some(CatalogRefreshBackoff::after_failure(
|
||||
auth_cache_key,
|
||||
resource_cache_key,
|
||||
state.cloud_retry.as_ref(),
|
||||
));
|
||||
}
|
||||
tracing::warn!("cloud plugin discovery failed");
|
||||
false
|
||||
}
|
||||
};
|
||||
catalog_cleared || catalog_published
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for PluginContributor {
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let state = input.thread_store.get_or_init(PluginsThreadState::default);
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
state.plugins_enabled = input.config.features.enabled(Feature::Plugins);
|
||||
state.extension_metrics = input.extension_metrics;
|
||||
}
|
||||
if let Some(resources) = &input.mcp_resource_client {
|
||||
input.session_store.insert(resources.as_ref().clone());
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigContributor<Config> for PluginContributor {
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &Config,
|
||||
new_config: &Config,
|
||||
) {
|
||||
let plugins_enabled = new_config.features.enabled(Feature::Plugins);
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
let mut state = state.contributor_state();
|
||||
if state.plugins_enabled != plugins_enabled {
|
||||
state.cloud_retry = None;
|
||||
}
|
||||
state.plugins_enabled = plugins_enabled;
|
||||
if self.providers.cloud.is_none() || !plugins_enabled {
|
||||
state.cloud_generation = None;
|
||||
state.cloud_retry = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TurnLifecycleContributor for PluginContributor {
|
||||
fn turn_start_phase(&self, thread_store: &ExtensionData) -> TurnStartPhase {
|
||||
if self.providers.cloud.is_some()
|
||||
&& thread_store
|
||||
.get::<PluginsThreadState>()
|
||||
.is_some_and(|state| state.contributor_state().plugins_enabled)
|
||||
{
|
||||
TurnStartPhase::RegularTaskStart
|
||||
} else {
|
||||
TurnStartPhase::BeforeTaskRegistration
|
||||
}
|
||||
}
|
||||
|
||||
fn requires_mcp_runtime(&self, thread_store: &ExtensionData) -> bool {
|
||||
self.turn_start_phase(thread_store) == TurnStartPhase::RegularTaskStart
|
||||
}
|
||||
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
input.turn_store.remove::<LatestCloudPluginAuth>();
|
||||
self.refresh_cloud_catalog(CatalogRefreshInput {
|
||||
turn_id: input.turn_id,
|
||||
session_store: input.session_store,
|
||||
thread_store: input.thread_store,
|
||||
turn_store: input.turn_store,
|
||||
})
|
||||
.await;
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh_catalog_for_step<'a>(
|
||||
&'a self,
|
||||
input: CatalogRefreshInput<'a>,
|
||||
) -> ExtensionFuture<'a, bool> {
|
||||
Box::pin(self.refresh_cloud_catalog(input))
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloud packages contribute Apps attribution, never executor MCP declarations.
|
||||
pub(crate) fn hosted_plugin_connectors(catalog: &PluginCatalog) -> Vec<McpServerContribution> {
|
||||
catalog
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|entry| entry.enabled)
|
||||
.filter_map(|entry| {
|
||||
let PluginIdentity::Remote { remote_plugin_id } = &entry.id else {
|
||||
return None;
|
||||
};
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
Some(McpServerContribution::HostedPluginConnectors {
|
||||
plugin_id: remote_plugin_id.clone(),
|
||||
plugin_display_name: entry
|
||||
.display_name
|
||||
.chars()
|
||||
.take(MAX_PLUGIN_DISPLAY_NAME_CHARS)
|
||||
.collect(),
|
||||
connector_ids: entry
|
||||
.connector_ids
|
||||
.iter()
|
||||
.filter(|connector_id| seen_connector_ids.insert((*connector_id).clone()))
|
||||
.take(MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.cloned()
|
||||
.collect(),
|
||||
})
|
||||
})
|
||||
.take(MAX_PROJECTED_CLOUD_PLUGINS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "cloud_plugin_tests.rs"]
|
||||
mod tests;
|
||||
874
codex-rs/ext/mcp/src/cloud_plugin_tests.rs
Normal file
874
codex-rs/ext/mcp/src/cloud_plugin_tests.rs
Normal file
@@ -0,0 +1,874 @@
|
||||
//! Tests per-turn cloud plugin discovery, auth recovery, tool calls, and plugin policy.
|
||||
|
||||
use super::*;
|
||||
use crate::PluginProvider;
|
||||
use crate::PluginProviderError;
|
||||
use crate::PluginProviderFuture;
|
||||
use crate::PluginProviders;
|
||||
use crate::PluginsThreadState;
|
||||
use crate::install_plugin_providers;
|
||||
use anyhow::Context;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_extension_api::ContextContributor;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_extension_api::McpServerContributor;
|
||||
use codex_extension_api::SelectedPluginSnapshot;
|
||||
use codex_extension_api::WorldStateContributionInput;
|
||||
use codex_extension_api::WorldStateSectionContribution;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::config_types::Settings;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use core_test_support::apps_test_server::AppsTestServer;
|
||||
use core_test_support::apps_test_server::recorded_apps_tool_calls;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_function_call_with_namespace;
|
||||
use core_test_support::responses::ev_response_created;
|
||||
use core_test_support::responses::mount_sse_sequence;
|
||||
use core_test_support::responses::sse;
|
||||
use core_test_support::test_codex::run_test_with_large_stack;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cloud_discovery_selects_regular_task_phase() {
|
||||
struct ExistingContributor;
|
||||
impl TurnLifecycleContributor for ExistingContributor {}
|
||||
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
builder.turn_lifecycle_contributor(Arc::new(ExistingContributor));
|
||||
let executor = Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
)));
|
||||
install_plugin_providers(&mut builder, PluginProviders::new(executor.clone()));
|
||||
install_plugin_providers(
|
||||
&mut builder,
|
||||
PluginProviders::new(executor).with_cloud_provider(Arc::new(CloudProvider::default())),
|
||||
);
|
||||
let registry = builder.build();
|
||||
let thread = ExtensionData::new("thread");
|
||||
for plugins_enabled in [false, true] {
|
||||
thread
|
||||
.get_or_init(PluginsThreadState::default)
|
||||
.contributor_state()
|
||||
.plugins_enabled = plugins_enabled;
|
||||
let dependencies = registry
|
||||
.turn_lifecycle_contributors()
|
||||
.iter()
|
||||
.map(|contributor| contributor.requires_mcp_runtime(&thread))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(dependencies, vec![false, false, plugins_enabled]);
|
||||
let phases = registry
|
||||
.turn_lifecycle_contributors()
|
||||
.iter()
|
||||
.map(|contributor| contributor.turn_start_phase(&thread))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
phases,
|
||||
vec![
|
||||
TurnStartPhase::BeforeTaskRegistration,
|
||||
TurnStartPhase::BeforeTaskRegistration,
|
||||
if plugins_enabled {
|
||||
TurnStartPhase::RegularTaskStart
|
||||
} else {
|
||||
TurnStartPhase::BeforeTaskRegistration
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabling_plugins_clears_cloud_catalog_and_skips_discovery() -> anyhow::Result<()> {
|
||||
let config_home = tempfile::tempdir()?;
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(config_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(config_home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
let mode = CollaborationMode {
|
||||
mode: ModeKind::Default,
|
||||
settings: Settings {
|
||||
model: "test".to_string(),
|
||||
reasoning_effort: None,
|
||||
developer_instructions: None,
|
||||
},
|
||||
};
|
||||
let provider = Arc::new(CloudProvider::default());
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
let providers = PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))))
|
||||
.with_cloud_provider(provider.clone());
|
||||
install_plugin_providers(&mut builder, providers);
|
||||
let registry = builder.build();
|
||||
let session = ExtensionData::new("session");
|
||||
let thread = ExtensionData::new("thread");
|
||||
let thread_init = codex_extension_api::ExtensionDataInit::default();
|
||||
for (turn_id, plugins_enabled, reply) in [
|
||||
("off", false, Ok(cloud_catalog())),
|
||||
("on", true, Ok(cloud_catalog())),
|
||||
("plugins-off", false, Ok(cloud_catalog())),
|
||||
(
|
||||
"re-enabled-failed",
|
||||
true,
|
||||
Err("discovery unavailable".to_string()),
|
||||
),
|
||||
("failed-plugins-off", false, Ok(cloud_catalog())),
|
||||
("re-enabled", true, Ok(cloud_catalog())),
|
||||
] {
|
||||
let expected_catalog = if plugins_enabled {
|
||||
reply.clone().ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let previous_discoveries = provider.calls.load(Ordering::SeqCst);
|
||||
provider.set_reply(reply);
|
||||
let previous = config.clone();
|
||||
config
|
||||
.features
|
||||
.set_enabled(Feature::Plugins, plugins_enabled)?;
|
||||
for contributor in registry.config_contributors() {
|
||||
contributor.on_config_changed(&session, &thread, &previous, &config);
|
||||
}
|
||||
if !plugins_enabled && let Some(state) = thread.get::<PluginsThreadState>() {
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
}
|
||||
for contributor in registry.turn_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_turn_start(TurnStartInput {
|
||||
turn_id,
|
||||
collaboration_mode: &mode,
|
||||
token_usage_at_turn_start: None,
|
||||
session_store: &session,
|
||||
thread_store: &thread,
|
||||
turn_store: &ExtensionData::new(turn_id),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
registry.mcp_server_contributors()[0]
|
||||
.contribute(codex_extension_api::McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&thread_init,
|
||||
&thread,
|
||||
"test",
|
||||
&[],
|
||||
/*executor_capability_discovery*/ None,
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
))
|
||||
.await;
|
||||
if let Some(state) = thread.get::<PluginsThreadState>() {
|
||||
assert_eq!(state.cloud_catalog(), expected_catalog, "turn {turn_id}");
|
||||
}
|
||||
assert_eq!(
|
||||
provider.calls.load(Ordering::SeqCst),
|
||||
previous_discoveries + usize::from(plugins_enabled),
|
||||
"turn {turn_id}",
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_change_clears_hosted_plugins_before_waiting_for_executor() -> anyhow::Result<()> {
|
||||
struct UnreadyExecutor;
|
||||
impl codex_exec_server::NoiseRendezvousConnectProvider for UnreadyExecutor {
|
||||
fn connect_bundle(
|
||||
&self,
|
||||
_: codex_exec_server::NoiseChannelPublicKey,
|
||||
) -> futures::future::BoxFuture<
|
||||
'_,
|
||||
Result<
|
||||
codex_exec_server::NoiseRendezvousConnectBundle,
|
||||
codex_exec_server::ExecServerError,
|
||||
>,
|
||||
> {
|
||||
Box::pin(futures::future::pending())
|
||||
}
|
||||
}
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.fallback_cwd(Some(home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
config.features.enable(Feature::Plugins)?;
|
||||
let manager = Arc::new(EnvironmentManager::default_for_tests());
|
||||
manager
|
||||
.materialize_pending_noise_environment("unready".to_string(), Arc::new(UnreadyExecutor))?;
|
||||
let contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(manager)))
|
||||
.with_cloud_provider(Arc::new(CloudProvider::default())),
|
||||
};
|
||||
let thread = ExtensionData::new("thread");
|
||||
let state = thread.get_or_init(PluginsThreadState::default);
|
||||
let old_auth = state
|
||||
.contributor_state()
|
||||
.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
assert!(
|
||||
state
|
||||
.contributor_state()
|
||||
.publish_cloud_catalog(old_auth.as_ref(), cloud_catalog())
|
||||
);
|
||||
let roots = [SelectedCapabilityRoot {
|
||||
id: "plugin".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "unready".to_string(),
|
||||
path: PathUri::parse("file:///plugins/demo")?,
|
||||
},
|
||||
}];
|
||||
let init = codex_extension_api::ExtensionDataInit::default();
|
||||
let context = McpServerContributionContext::for_step(
|
||||
&config, &init, &thread, "test", &roots, /*executor_capability_discovery*/ None,
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
)
|
||||
.with_auth_changed(/*auth_changed*/ true);
|
||||
let mut loading = std::pin::pin!(contributor.selected_plugins(context, &config.plugins));
|
||||
assert!(futures::poll!(&mut loading).is_pending());
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn cloud_refresh_serializes_waiters_and_retries() {
|
||||
let new_catalog = PluginCatalog::default();
|
||||
for (reply, cancelled) in [
|
||||
(Ok(cloud_catalog()), false),
|
||||
(Err("discovery failed".to_string()), false),
|
||||
(Ok(cloud_catalog()), true),
|
||||
] {
|
||||
let succeeded = reply.is_ok() && !cancelled;
|
||||
let expected_catalog = if succeeded {
|
||||
cloud_catalog()
|
||||
} else {
|
||||
new_catalog.clone()
|
||||
};
|
||||
let provider = Arc::new(CloudProvider::default());
|
||||
provider.set_reply(reply);
|
||||
let contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))))
|
||||
.with_cloud_provider(provider.clone()),
|
||||
};
|
||||
let session = ExtensionData::new("session");
|
||||
let thread = ExtensionData::new("thread");
|
||||
let turn = ExtensionData::new("turn");
|
||||
let prewarm_turn = ExtensionData::new("prewarm");
|
||||
let input = CatalogRefreshInput {
|
||||
turn_id: "turn",
|
||||
session_store: &session,
|
||||
thread_store: &thread,
|
||||
turn_store: &turn,
|
||||
};
|
||||
let state = thread.get_or_init(PluginsThreadState::default);
|
||||
state.contributor_state().plugins_enabled = true;
|
||||
|
||||
// A delayed prewarm waits without superseding the real turn's request.
|
||||
provider.pause_discovery.store(true, Ordering::SeqCst);
|
||||
let mut turn_start = contributor.refresh_catalog_for_step(input);
|
||||
assert!(futures::poll!(&mut turn_start).is_pending());
|
||||
let prewarm_input = CatalogRefreshInput {
|
||||
turn_id: "prewarm",
|
||||
turn_store: &prewarm_turn,
|
||||
..input
|
||||
};
|
||||
let mut prewarm = contributor.refresh_catalog_for_step(prewarm_input);
|
||||
assert!(futures::poll!(&mut prewarm).is_pending());
|
||||
let mut cancelled_waiter = contributor.refresh_catalog_for_step(prewarm_input);
|
||||
assert!(futures::poll!(&mut cancelled_waiter).is_pending());
|
||||
drop(cancelled_waiter);
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
|
||||
|
||||
provider.set_reply(Ok(new_catalog.clone()));
|
||||
if cancelled {
|
||||
drop(turn_start);
|
||||
} else {
|
||||
provider.resume_discovery.notify_one();
|
||||
assert_eq!(turn_start.await, succeeded);
|
||||
}
|
||||
// Waiting turns share failure cooldowns; cancellation still allows immediate retry.
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(5), prewarm)
|
||||
.await
|
||||
.expect("waiting discovery should complete after its predecessor stops"),
|
||||
cancelled,
|
||||
);
|
||||
if !succeeded && !cancelled {
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
assert!(contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
}
|
||||
assert_eq!(state.cloud_catalog(), Some(expected_catalog.clone()));
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert_eq!(
|
||||
provider.calls.load(Ordering::SeqCst),
|
||||
1 + usize::from(!succeeded),
|
||||
);
|
||||
|
||||
// Retained catalogs do not need MCP rebuilding after failed retries.
|
||||
prewarm_turn.remove::<LatestCloudPluginAuth>();
|
||||
provider.set_reply(Err("discovery failed".to_string()));
|
||||
let previous_calls = provider.calls.load(Ordering::SeqCst);
|
||||
for _ in 0..2 {
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert_eq!(state.cloud_catalog(), Some(expected_catalog.clone()));
|
||||
}
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), previous_calls + 1);
|
||||
|
||||
// Clearing an old auth scope still requires rebuilding, even on failure.
|
||||
session.insert(McpResourceClient::new(Arc::new(
|
||||
codex_mcp::McpRuntime::empty(/*prefix_mcp_tool_names*/ false),
|
||||
)));
|
||||
assert!(contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
provider.set_reply(Ok(new_catalog.clone()));
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
assert!(contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
}
|
||||
}
|
||||
|
||||
struct CloudProvider {
|
||||
reply: Mutex<Result<PluginCatalog, String>>,
|
||||
calls: AtomicUsize,
|
||||
resources: Mutex<Option<Arc<McpResourceClient>>>,
|
||||
pause_discovery: AtomicBool,
|
||||
discovery_started: Notify,
|
||||
resume_discovery: Notify,
|
||||
}
|
||||
|
||||
type ObservedPackages = Vec<(String, Option<String>)>;
|
||||
|
||||
#[derive(Default)]
|
||||
struct StepPackages(Mutex<Option<ObservedPackages>>);
|
||||
|
||||
impl ContextContributor for StepPackages {
|
||||
fn contribute_world_state<'a>(
|
||||
&'a self,
|
||||
input: WorldStateContributionInput<'a>,
|
||||
) -> ExtensionFuture<'a, Vec<WorldStateSectionContribution>> {
|
||||
Box::pin(async move {
|
||||
*self
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = input
|
||||
.thread_store
|
||||
.get::<SelectedPluginSnapshot>()
|
||||
.map(|snapshot| {
|
||||
snapshot
|
||||
.plugins
|
||||
.iter()
|
||||
.map(|plugin| {
|
||||
(
|
||||
plugin.plugin_id.as_str().to_string(),
|
||||
plugin.selected_root_id.clone(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CloudProvider {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
reply: Mutex::new(Ok(PluginCatalog::default())),
|
||||
calls: AtomicUsize::new(0),
|
||||
resources: Mutex::new(None),
|
||||
pause_discovery: AtomicBool::new(false),
|
||||
discovery_started: Notify::new(),
|
||||
resume_discovery: Notify::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CloudProvider {
|
||||
fn set_reply(&self, reply: Result<PluginCatalog, String>) {
|
||||
*self
|
||||
.reply
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = reply;
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginProvider for CloudProvider {
|
||||
fn list(&self, query: PluginListQuery) -> PluginProviderFuture<'_, PluginCatalog> {
|
||||
*self
|
||||
.resources
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = query.mcp_resources;
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
let reply = self
|
||||
.reply
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
let pause = self.pause_discovery.swap(false, Ordering::SeqCst);
|
||||
Box::pin(async move {
|
||||
if pause {
|
||||
self.discovery_started.notify_one();
|
||||
self.resume_discovery.notified().await;
|
||||
}
|
||||
reply.map_err(PluginProviderError::Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn cloud_catalog() -> PluginCatalog {
|
||||
PluginCatalog {
|
||||
entries: vec![PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: "plugin_remote".to_string(),
|
||||
},
|
||||
display_name: "Cloud Demo".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: Default::default(),
|
||||
connector_ids: vec!["calendar".to_string()],
|
||||
locations: vec![codex_core_plugins::PluginSourceLocation::Cloud {
|
||||
resource_uri: "plugin://plugin_remote".to_string(),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn app_tool(connector: &str, action: &str) -> serde_json::Value {
|
||||
json!({
|
||||
"name": format!("{connector}_{action}"),
|
||||
"description": format!("Run {action} in {connector}."),
|
||||
"annotations": {"readOnlyHint": true},
|
||||
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": false},
|
||||
"_meta": {
|
||||
"connector_id": connector,
|
||||
"connector_name": connector,
|
||||
"_codex_apps": {
|
||||
"resource_uri": format!("connector://{connector}/tools/{connector}_{action}"),
|
||||
"contains_mcp_source": true,
|
||||
"connector_id": connector,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloud_catalog_refreshes_per_turn_and_invalidates_on_auth_change() -> anyhow::Result<()> {
|
||||
run_test_with_large_stack(
|
||||
"cloud-plugin-lifecycle",
|
||||
run_cloud_catalog_refresh_lifecycle,
|
||||
)
|
||||
}
|
||||
|
||||
async fn run_cloud_catalog_refresh_lifecycle() -> anyhow::Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
// Each account has a fixed inventory; only the auth switch changes the server's tools.
|
||||
let apps_tools = Arc::new(Mutex::new(vec![app_tool("calendar", "list_events")]));
|
||||
let apps_server = AppsTestServer::mount_with_tools(&server, apps_tools.clone()).await?;
|
||||
let mut gmail_catalog = cloud_catalog();
|
||||
gmail_catalog.entries[0].id = PluginIdentity::Remote {
|
||||
remote_plugin_id: "plugin_gmail".to_string(),
|
||||
};
|
||||
gmail_catalog.entries[0].display_name = "Gmail Demo".to_string();
|
||||
gmail_catalog.entries[0].connector_ids = vec!["gmail".to_string()];
|
||||
let mut disabled_catalog = cloud_catalog();
|
||||
disabled_catalog.entries[0].enabled = false;
|
||||
let mut partial_catalog = gmail_catalog.clone();
|
||||
partial_catalog.is_partial = true;
|
||||
let partial_empty_catalog = PluginCatalog {
|
||||
is_partial: true,
|
||||
warnings: vec!["resource listing was truncated".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
let provider = Arc::new(CloudProvider::default());
|
||||
let step_packages = Arc::new(StepPackages::default());
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
crate::install(&mut extensions);
|
||||
extensions.prompt_contributor(step_packages.clone());
|
||||
install_plugin_providers(
|
||||
&mut extensions,
|
||||
PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))))
|
||||
.with_cloud_provider(provider.clone()),
|
||||
);
|
||||
let mut builder = test_codex()
|
||||
.with_cloud_config_bundle(
|
||||
CloudConfigBundleFixture::enterprise_config(
|
||||
"[mcp_servers.codex_apps]\nurl = 'https://example.com/custom'",
|
||||
)
|
||||
.add_enterprise_requirement("[mcp_servers]")
|
||||
.into_loader(),
|
||||
)
|
||||
.with_exec_server_url("none")
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_auth(codex_login::CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.initial",
|
||||
"account-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?)
|
||||
.with_model_info_override("gpt-5.5", |model| {
|
||||
model.supports_search_tool = false;
|
||||
})
|
||||
.with_config(move |config| {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::Plugins)
|
||||
.expect("enable plugins in fixture");
|
||||
config
|
||||
.features
|
||||
.enable(Feature::Apps)
|
||||
.expect("enable apps in fixture");
|
||||
config.chatgpt_base_url = apps_server.chatgpt_base_url;
|
||||
});
|
||||
let test = builder.build_with_auto_env(&server).await?;
|
||||
assert!(!test.config.mcp_servers.get()[codex_mcp::CODEX_APPS_MCP_SERVER_NAME].enabled);
|
||||
let calendar = ("calendar", "list_events", "Cloud Demo");
|
||||
let gmail = ("gmail", "search_email", "Gmail Demo");
|
||||
for (turn, reply, expected_plugin, new_account, tool_call) in [
|
||||
(
|
||||
"initial-partial",
|
||||
Ok(partial_catalog.clone()),
|
||||
Some("plugin_gmail"),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"partial-replaces-partial",
|
||||
Ok(PluginCatalog {
|
||||
is_partial: true,
|
||||
..cloud_catalog()
|
||||
}),
|
||||
Some("plugin_remote"),
|
||||
None,
|
||||
Some(calendar),
|
||||
),
|
||||
(
|
||||
"partial-empty-replaces-partial",
|
||||
Ok(partial_empty_catalog.clone()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"empty",
|
||||
Ok(PluginCatalog::default()),
|
||||
None,
|
||||
None,
|
||||
Some(calendar),
|
||||
),
|
||||
(
|
||||
"partial-after-complete-empty",
|
||||
Ok(partial_catalog.clone()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"discovered",
|
||||
Ok(cloud_catalog()),
|
||||
Some("plugin_remote"),
|
||||
None,
|
||||
Some(calendar),
|
||||
),
|
||||
(
|
||||
"partial-refresh",
|
||||
Ok(partial_catalog.clone()),
|
||||
Some("plugin_remote"),
|
||||
None,
|
||||
Some(calendar),
|
||||
),
|
||||
(
|
||||
"partial-empty-refresh",
|
||||
Ok(partial_empty_catalog),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"same-account-failure",
|
||||
Err("temporarily unavailable".to_string()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"complete-with-warning-disables-plugin",
|
||||
Ok(PluginCatalog {
|
||||
warnings: vec!["optional bundle hint ignored".to_string()],
|
||||
..disabled_catalog
|
||||
}),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"partial-after-disable",
|
||||
Ok(partial_catalog.clone()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"re-enabled",
|
||||
Ok(cloud_catalog()),
|
||||
Some("plugin_remote"),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
("removed", Ok(PluginCatalog::default()), None, None, None),
|
||||
(
|
||||
"restored",
|
||||
Ok(cloud_catalog()),
|
||||
Some("plugin_remote"),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"auth-changed-failure",
|
||||
Err("unavailable after auth changed".to_string()),
|
||||
None,
|
||||
Some("account-b"),
|
||||
None,
|
||||
),
|
||||
(
|
||||
"new-account-partial",
|
||||
Ok(partial_catalog),
|
||||
Some("plugin_gmail"),
|
||||
None,
|
||||
Some(gmail),
|
||||
),
|
||||
(
|
||||
"new-account-discovered",
|
||||
Ok(gmail_catalog),
|
||||
Some("plugin_gmail"),
|
||||
None,
|
||||
Some(gmail),
|
||||
),
|
||||
(
|
||||
"in-flight-auth-change",
|
||||
Ok(cloud_catalog()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let previous_discoveries = provider.calls.load(Ordering::SeqCst);
|
||||
let retry_discovery = turn == "in-flight-auth-change";
|
||||
if let Some(account) = new_account {
|
||||
// Do not manually refresh MCP: the auth transition must pick up this new inventory.
|
||||
*apps_tools
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) =
|
||||
vec![app_tool("gmail", "search_email")];
|
||||
let resources = provider
|
||||
.resources
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone()
|
||||
.context("cloud provider resource client missing")?;
|
||||
let previous_auth =
|
||||
resources.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME);
|
||||
codex_login::auth::login_with_chatgpt_auth_tokens(
|
||||
test.codex_home_path(),
|
||||
"header.e30.changed",
|
||||
account,
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
test.thread_manager.auth_manager().reload().await;
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
loop {
|
||||
if resources.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME)
|
||||
!= previous_auth
|
||||
&& test
|
||||
.codex
|
||||
.thread_extension_data()
|
||||
.get::<SelectedPluginSnapshot>()
|
||||
.is_some_and(|snapshot| snapshot.plugins.is_empty())
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), previous_discoveries);
|
||||
}
|
||||
if matches!(
|
||||
turn,
|
||||
"complete-with-warning-disables-plugin" | "new-account-partial"
|
||||
) {
|
||||
// Reconnecting permits recovery before the thread's cooldown expires.
|
||||
test.codex
|
||||
.submit(codex_protocol::protocol::Op::RefreshMcpServers)
|
||||
.await?;
|
||||
}
|
||||
provider.set_reply(reply);
|
||||
let previous_calls = recorded_apps_tool_calls(&server).await.len();
|
||||
let call_id = format!("{turn}-call");
|
||||
let mut events = vec![ev_response_created("resp")];
|
||||
if let Some((connector, action, _)) = tool_call {
|
||||
events.push(ev_function_call_with_namespace(
|
||||
&call_id,
|
||||
&format!("mcp__codex_apps__{connector}"),
|
||||
&format!("_{action}"),
|
||||
"{}",
|
||||
));
|
||||
}
|
||||
events.push(ev_completed("resp"));
|
||||
let mut responses = vec![sse(events)];
|
||||
if tool_call.is_some() {
|
||||
responses.push(sse(vec![
|
||||
ev_response_created("after-tool"),
|
||||
ev_completed("after-tool"),
|
||||
]));
|
||||
}
|
||||
let response = mount_sse_sequence(&server, responses).await;
|
||||
*step_packages
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
|
||||
if turn == "in-flight-auth-change" {
|
||||
provider.pause_discovery.store(true, Ordering::SeqCst);
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
tokio::try_join!(
|
||||
test.submit_turn("What capabilities are available?"),
|
||||
async {
|
||||
provider.discovery_started.notified().await;
|
||||
let resources = provider
|
||||
.resources
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone()
|
||||
.context("cloud provider resource client missing")?;
|
||||
let previous_auth = resources
|
||||
.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME);
|
||||
// Rotate credentials without replacing the captured runtime/client.
|
||||
codex_login::auth::login_with_chatgpt_auth_tokens(
|
||||
test.codex_home_path(),
|
||||
"header.e30.rotated",
|
||||
"account-b",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
test.thread_manager.auth_manager().reload().await;
|
||||
// Auth must be published while cloud discovery remains paused.
|
||||
while resources
|
||||
.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME)
|
||||
== previous_auth
|
||||
{
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
provider.set_reply(Err("new-scope discovery failed".to_string()));
|
||||
provider.resume_discovery.notify_one();
|
||||
anyhow::Ok(())
|
||||
}
|
||||
)
|
||||
})
|
||||
.await??;
|
||||
// Refresh under the new auth without retaining the old catalog.
|
||||
let state = test
|
||||
.codex
|
||||
.thread_extension_data()
|
||||
.get::<PluginsThreadState>()
|
||||
.context("plugin state missing")?;
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
assert_eq!(
|
||||
state
|
||||
.contributor_state()
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.and_then(|generation| generation.catalog.clone()),
|
||||
None,
|
||||
);
|
||||
} else {
|
||||
test.submit_turn("What capabilities are available?").await?;
|
||||
}
|
||||
let requests = response.requests();
|
||||
let request = &requests[0];
|
||||
if let Some((connector, action, plugin_name)) = tool_call {
|
||||
assert_eq!(requests.len(), 2);
|
||||
let calls = recorded_apps_tool_calls(&server).await;
|
||||
let output = requests[1].function_call_output(&call_id);
|
||||
assert_eq!(calls.len(), previous_calls + 1, "turn {turn}: {output}");
|
||||
let call = calls.last().context("expected an Apps tool call")?;
|
||||
assert_eq!(
|
||||
call["params"]["name"],
|
||||
json!(format!("{connector}_{action}"))
|
||||
);
|
||||
assert_eq!(call["params"]["arguments"], json!({}));
|
||||
let (other_namespace, other_tool) = if connector == "calendar" {
|
||||
("mcp__codex_apps__gmail", "_search_email")
|
||||
} else {
|
||||
("mcp__codex_apps__calendar", "_list_events")
|
||||
};
|
||||
assert!(request.tool_by_name(other_namespace, other_tool).is_none());
|
||||
let tool = request
|
||||
.tool_by_name(
|
||||
&format!("mcp__codex_apps__{connector}"),
|
||||
&format!("_{action}"),
|
||||
)
|
||||
.expect("the current account's tool should be advertised");
|
||||
assert_eq!(
|
||||
tool["description"]
|
||||
.as_str()
|
||||
.context("tool description missing")?
|
||||
.contains(plugin_name),
|
||||
expected_plugin.is_some(),
|
||||
"cloud discovery should attribute tools to the current account's plugin"
|
||||
);
|
||||
// The server echoes this URI in its result; it must reach the next model step.
|
||||
assert!(
|
||||
output["output"]
|
||||
.as_str()
|
||||
.context("tool output missing")?
|
||||
.contains(&format!(
|
||||
"connector://{connector}/tools/{connector}_{action}"
|
||||
)),
|
||||
"turn {turn}: {output}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
*step_packages
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
Some(
|
||||
expected_plugin
|
||||
.into_iter()
|
||||
.map(|id| (id.to_owned(), None))
|
||||
.collect()
|
||||
),
|
||||
"turn {turn}"
|
||||
);
|
||||
assert_eq!(
|
||||
provider.calls.load(Ordering::SeqCst),
|
||||
previous_discoveries + 1 + if retry_discovery { requests.len() } else { 0 },
|
||||
"turn {turn}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
652
codex-rs/ext/mcp/src/event_stream_tests.rs
Normal file
652
codex-rs/ext/mcp/src/event_stream_tests.rs
Normal file
@@ -0,0 +1,652 @@
|
||||
//! Exercises independent event connections through the real MCP HTTP transport.
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::convert::Infallible;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use axum::Json;
|
||||
use axum::Router;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::response::sse::Event;
|
||||
use axum::response::sse::Sse;
|
||||
use axum::routing::post;
|
||||
use codex_config::McpServerTransportConfig;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::plugins_manager_for_config;
|
||||
use codex_exec_server_test_support::environment_manager_without_environments;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::CodexAppsResourceListParams;
|
||||
use codex_mcp::EffectiveMcpServer;
|
||||
use codex_mcp::McpEventNotification;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpRuntime;
|
||||
use codex_mcp::McpRuntimeContext;
|
||||
use codex_mcp::McpRuntimeInput;
|
||||
use codex_mcp::McpServerRegistration;
|
||||
use codex_mcp::McpStartupPolicy;
|
||||
use codex_mcp::ResolvedMcpCatalog;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(super) const WAIT: Duration = Duration::from_secs(/*secs*/ 5);
|
||||
|
||||
pub(super) struct TestStream {
|
||||
pub request: Value,
|
||||
pub headers: HeaderMap,
|
||||
pub notifications: mpsc::UnboundedSender<Value>,
|
||||
}
|
||||
|
||||
impl TestStream {
|
||||
pub fn notify(&self, method: &str) -> McpEventNotification {
|
||||
let params = json!({
|
||||
"data": {"text": "hello"},
|
||||
"_meta": {"io.modelcontextprotocol/subscriptionId": self.request["id"], "connector": "test"},
|
||||
});
|
||||
self.notifications
|
||||
.send(json!({"jsonrpc": "2.0", "method": method, "params": params}))
|
||||
.unwrap();
|
||||
McpEventNotification {
|
||||
method: method.into(),
|
||||
params: Some(params),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct BlockedTools {
|
||||
started: Notify,
|
||||
release: Notify,
|
||||
handshakes: AtomicUsize,
|
||||
inventories: AtomicUsize,
|
||||
inventory_returned: AtomicBool,
|
||||
inventory_error: Option<&'static str>,
|
||||
stalled_initialize_timeout: Option<Duration>,
|
||||
modern_with_sharing: bool,
|
||||
held_mime_type: Option<&'static str>,
|
||||
session_id: Option<&'static str>,
|
||||
resource_started: Notify,
|
||||
release_resource: Notify,
|
||||
}
|
||||
|
||||
pub(super) struct Fixture {
|
||||
_home: tempfile::TempDir,
|
||||
_server: tokio_util::task::AbortOnDropHandle<std::io::Result<()>>,
|
||||
pub runtime: Arc<McpRuntime>,
|
||||
pub runtime_input: McpRuntimeInput,
|
||||
pub auth: Arc<AuthManager>,
|
||||
pub opened: mpsc::UnboundedReceiver<TestStream>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
pub async fn new() -> Result<Self> {
|
||||
let fixture = Self::start(/*blocked_tools*/ None, /*early_resources*/ false).await?;
|
||||
assert!(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT)
|
||||
.await
|
||||
);
|
||||
Ok(fixture)
|
||||
}
|
||||
|
||||
async fn start(
|
||||
blocked_tools: Option<Arc<BlockedTools>>,
|
||||
early_resources: bool,
|
||||
) -> Result<Self> {
|
||||
let (opened_tx, opened) = mpsc::unbounded_channel();
|
||||
let modern_with_sharing = blocked_tools
|
||||
.as_ref()
|
||||
.is_some_and(|blocked| blocked.modern_with_sharing);
|
||||
let stalled_initialize_timeout = blocked_tools
|
||||
.as_ref()
|
||||
.and_then(|blocked| blocked.stalled_initialize_timeout);
|
||||
let router = Router::new().fallback(post(
|
||||
move |headers: HeaderMap, Json(request): Json<Value>| {
|
||||
let opened = opened_tx.clone();
|
||||
let blocked_tools = blocked_tools.clone();
|
||||
async move {
|
||||
let method = request["method"].as_str();
|
||||
let session_id = blocked_tools.as_ref().and_then(|blocked| blocked.session_id);
|
||||
if let Some(session_id) = session_id && method != Some("initialize") {
|
||||
assert_eq!(headers["mcp-session-id"], session_id);
|
||||
}
|
||||
let mut result = match method {
|
||||
Some("server/discover") if modern_with_sharing => {
|
||||
blocked_tools.as_ref().unwrap().handshakes.fetch_add(1, Ordering::SeqCst);
|
||||
json!({
|
||||
"supportedVersions": ["2026-07-28"],
|
||||
"capabilities": {"tools": {}, "resources": {}},
|
||||
"_meta": {"io.modelcontextprotocol/serverInfo": {"name": "test", "version": "1"}},
|
||||
"ttlMs": 0, "cacheScope": "private",
|
||||
})
|
||||
}
|
||||
Some("initialize") if !modern_with_sharing => {
|
||||
if let Some(blocked) = &blocked_tools {
|
||||
blocked.handshakes.fetch_add(1, Ordering::SeqCst);
|
||||
if stalled_initialize_timeout.is_some() {
|
||||
blocked.started.notify_one();
|
||||
blocked.release.notified().await;
|
||||
}
|
||||
}
|
||||
json!({
|
||||
"protocolVersion": "2025-06-18", "capabilities": {"tools": {}, "resources": {}},
|
||||
"serverInfo": {"name": "test", "version": "1"},
|
||||
})
|
||||
}
|
||||
Some("tools/list") => {
|
||||
if let Some(blocked) = &blocked_tools {
|
||||
blocked.inventories.fetch_add(1, Ordering::SeqCst);
|
||||
blocked.started.notify_one();
|
||||
blocked.release.notified().await;
|
||||
blocked.inventory_returned.store(true, Ordering::SeqCst);
|
||||
if let Some(message) = blocked.inventory_error {
|
||||
return Json(json!({
|
||||
"jsonrpc": "2.0", "id": request["id"],
|
||||
"error": {"code": -32603, "message": message}
|
||||
})).into_response();
|
||||
}
|
||||
}
|
||||
json!({"tools": []})
|
||||
}
|
||||
Some("resources/list") => {
|
||||
if let Some(blocked) = &blocked_tools {
|
||||
assert_eq!(blocked.inventory_returned.load(Ordering::SeqCst), !early_resources,
|
||||
"unexpected catalog request ordering relative to the initial inventory");
|
||||
}
|
||||
let mime_type = request["params"]["mimeType"].as_str().unwrap();
|
||||
let cursor = match mime_type {
|
||||
"mcp/plugin" => "plugin-page-two",
|
||||
"mcp/skill" => "skill-page-two",
|
||||
other => panic!("unexpected resource type: {other}"),
|
||||
};
|
||||
if let Some(blocked) = &blocked_tools && blocked.held_mime_type == Some(mime_type) {
|
||||
blocked.resource_started.notify_one();
|
||||
blocked.release_resource.notified().await;
|
||||
}
|
||||
json!({"resources": [], "nextCursor": cursor})
|
||||
}
|
||||
Some("notifications/initialized") => {
|
||||
return StatusCode::ACCEPTED.into_response();
|
||||
}
|
||||
Some("events/stream") => {
|
||||
let (notifications, receive) = mpsc::unbounded_channel();
|
||||
opened
|
||||
.send(TestStream {
|
||||
request,
|
||||
headers,
|
||||
notifications,
|
||||
})
|
||||
.unwrap();
|
||||
let events = futures::stream::unfold(receive, |mut receive| async {
|
||||
receive.recv().await.map(|value| (value, receive))
|
||||
})
|
||||
.map(|value: Value| {
|
||||
Ok::<_, Infallible>(
|
||||
Event::default().event("message").data(value.to_string()),
|
||||
)
|
||||
});
|
||||
return Sse::new(events).into_response();
|
||||
}
|
||||
method => panic!("unexpected request: {method:?}"),
|
||||
};
|
||||
if modern_with_sharing {
|
||||
result["resultType"] = "complete".into();
|
||||
}
|
||||
let response = Json(json!({"jsonrpc": "2.0", "id": request["id"], "result": result}));
|
||||
if method == Some("initialize") && let Some(session_id) = session_id {
|
||||
return ([("mcp-session-id", session_id)], response).into_response();
|
||||
}
|
||||
response.into_response()
|
||||
}
|
||||
},
|
||||
));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let url = format!("http://{}", listener.local_addr()?);
|
||||
let server = tokio::spawn(async move { axum::serve(listener, router).await });
|
||||
let home = tempfile::tempdir()?;
|
||||
let auth_value = CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.first",
|
||||
"account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing_with_home(auth_value.clone(), home.path().into());
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().into())
|
||||
.fallback_cwd(Some(home.path().into()))
|
||||
.cli_overrides(vec![
|
||||
(
|
||||
"features.apps_early_resource_discovery".into(),
|
||||
early_resources.into(),
|
||||
),
|
||||
(
|
||||
"features.mcp_connection_sharing".into(),
|
||||
modern_with_sharing.into(),
|
||||
),
|
||||
(
|
||||
"features.codex_apps_mcp_2026_07_28".into(),
|
||||
modern_with_sharing.into(),
|
||||
),
|
||||
])
|
||||
.build()
|
||||
.await?;
|
||||
let plugins = plugins_manager_for_config(&config, Arc::clone(&auth));
|
||||
let mut config = config.to_mcp_config(&plugins).await;
|
||||
let mut server_config = codex_mcp::hosted_plugin_runtime_mcp_server_config(
|
||||
&url, /*apps_mcp_product_sku*/ None, /*originator*/ None,
|
||||
);
|
||||
let McpServerTransportConfig::StreamableHttp {
|
||||
bearer_token_env_var,
|
||||
..
|
||||
} = &mut server_config.transport
|
||||
else {
|
||||
panic!("HTTP server");
|
||||
};
|
||||
*bearer_token_env_var = None;
|
||||
if let Some(timeout) = stalled_initialize_timeout {
|
||||
server_config.startup_timeout_sec = Some(timeout);
|
||||
}
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_hosted_apps(
|
||||
"test",
|
||||
/*contribution_order*/ 0,
|
||||
server_config.clone(),
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
let config = Arc::new(config);
|
||||
let startup_cancellation_token = CancellationToken::new();
|
||||
let runtime_input = || McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::clone(&config),
|
||||
plugins_available: false,
|
||||
ready_selected_capability_roots: Vec::new(),
|
||||
mcp_servers: HashMap::from([(
|
||||
CODEX_APPS_MCP_SERVER_NAME.into(),
|
||||
EffectiveMcpServer::from_host_config(server_config.clone()),
|
||||
)]),
|
||||
submit_id: "test".into(),
|
||||
tx_event: None,
|
||||
startup_cancellation_token: startup_cancellation_token.clone(),
|
||||
runtime_context: McpRuntimeContext::new(
|
||||
Arc::new(environment_manager_without_environments()),
|
||||
home.path().into(),
|
||||
)
|
||||
.with_connection_pool(Default::default()),
|
||||
codex_apps_tools_cache: Default::default(),
|
||||
tool_catalog_cache: Default::default(),
|
||||
codex_apps_tools_cache_key: codex_mcp::codex_apps_tools_cache_key(Some(&auth_value)),
|
||||
client_mcp_extensions: Default::default(),
|
||||
auth: Some(auth_value.clone()),
|
||||
auth_manager: Some(Arc::clone(&auth)),
|
||||
elicitation_reviewer: None,
|
||||
elicitation_lifecycle: None,
|
||||
};
|
||||
let runtime = Arc::new(McpRuntime::new(runtime_input()).await);
|
||||
let runtime_input = runtime_input();
|
||||
Ok(Self {
|
||||
_home: home,
|
||||
_server: tokio_util::task::AbortOnDropHandle::new(server),
|
||||
runtime,
|
||||
runtime_input,
|
||||
auth,
|
||||
opened,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_during_initial_tools_list() -> Result<()> {
|
||||
for (early_resources, modern_with_sharing) in [(false, false), (true, false), (true, true)] {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
modern_with_sharing,
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), early_resources).await?;
|
||||
timeout(WAIT, blocked.started.notified())
|
||||
.await
|
||||
.context("initial tools/list did not start")?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
if early_resources {
|
||||
assert_eq!(
|
||||
timeout(WAIT, &mut page)
|
||||
.await
|
||||
.context("gated catalog read waited for the blocked inventory")??
|
||||
.next_cursor
|
||||
.as_deref(),
|
||||
Some("plugin-page-two")
|
||||
);
|
||||
} else {
|
||||
assert!(futures::poll!(&mut page).is_pending());
|
||||
// A read already using the early client would now fail its generation check.
|
||||
// A read waiting for startup can still fetch the page after inventory returns.
|
||||
fixture.runtime.invalidate_resource_caches();
|
||||
}
|
||||
let mut ready = Box::pin(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT),
|
||||
);
|
||||
assert!(futures::poll!(&mut ready).is_pending());
|
||||
blocked.release.notify_one();
|
||||
assert!(ready.await);
|
||||
if !early_resources {
|
||||
assert_eq!(
|
||||
timeout(WAIT, page).await??.next_cursor.as_deref(),
|
||||
Some("plugin-page-two")
|
||||
);
|
||||
}
|
||||
assert_eq!(blocked.handshakes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(blocked.inventories.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_times_out_during_stalled_initialization() -> Result<()> {
|
||||
let startup_timeout = Duration::from_secs(/*secs*/ 1);
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
stalled_initialize_timeout: Some(startup_timeout),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
assert!(futures::poll!(&mut page).is_pending());
|
||||
timeout(WAIT, blocked.started.notified())
|
||||
.await
|
||||
.context("initialize did not reach the server")?;
|
||||
let error = timeout(WAIT, page)
|
||||
.await
|
||||
.context("reader outlived its startup deadline")?
|
||||
.unwrap_err();
|
||||
// The handshake and early borrow each enforce the configured startup timeout.
|
||||
let message = format!("{error:#}");
|
||||
assert!(message.contains("timed out"), "{message}");
|
||||
assert_eq!(blocked.inventories.load(Ordering::SeqCst), 0);
|
||||
blocked.release.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_multiplexes_catalogs_while_tools_list_is_pending() -> Result<()> {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/plugin"),
|
||||
session_id: Some("apps-session"),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let plugin_reader = reader.clone();
|
||||
let plugin = tokio::spawn(async move {
|
||||
plugin_reader
|
||||
.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
timeout(WAIT, blocked.resource_started.notified())
|
||||
.await
|
||||
.context("plugin request did not reach the server while tools/list was pending")?;
|
||||
let skill = timeout(
|
||||
WAIT,
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/skill".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.context("skill request queued behind the pending plugin or inventory request")??;
|
||||
assert_eq!(skill.next_cursor.as_deref(), Some("skill-page-two"));
|
||||
assert!(!plugin.is_finished());
|
||||
|
||||
blocked.release_resource.notify_one();
|
||||
let plugin = timeout(WAIT, plugin).await???;
|
||||
assert_eq!(plugin.next_cursor.as_deref(), Some("plugin-page-two"));
|
||||
|
||||
let mut ready = Box::pin(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT),
|
||||
);
|
||||
assert!(futures::poll!(&mut ready).is_pending());
|
||||
blocked.release.notify_one();
|
||||
assert!(ready.await);
|
||||
assert_eq!(blocked.handshakes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(blocked.inventories.load(Ordering::SeqCst), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_propagates_initial_tools_list_failure() -> Result<()> {
|
||||
const INVENTORY_ERROR: &str = "initial inventory unavailable";
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/plugin"),
|
||||
inventory_error: Some(INVENTORY_ERROR),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
result = &mut page => panic!("catalog returned before inventory failed: {result:?}"),
|
||||
result = timeout(WAIT, blocked.resource_started.notified()) => result?,
|
||||
}
|
||||
|
||||
blocked.release.notify_one();
|
||||
let error = timeout(WAIT, page)
|
||||
.await
|
||||
.context("catalog reader kept waiting after tools/list failed")?
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.starts_with("MCP startup failed:"), "{error}");
|
||||
assert!(error.contains(INVENTORY_ERROR), "{error}");
|
||||
assert!(
|
||||
!fixture
|
||||
.runtime_input
|
||||
.startup_cancellation_token
|
||||
.is_cancelled()
|
||||
);
|
||||
blocked.release_resource.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_observes_cancellation_after_inventory_finishes() -> Result<()> {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/plugin"),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
result = &mut page => panic!("catalog returned before release: {result:?}"),
|
||||
result = timeout(WAIT, blocked.resource_started.notified()) => result?,
|
||||
}
|
||||
blocked.release.notify_one();
|
||||
assert!(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT)
|
||||
.await
|
||||
);
|
||||
assert!(futures::poll!(&mut page).is_pending());
|
||||
fixture.runtime_input.startup_cancellation_token.cancel();
|
||||
let error = timeout(WAIT, page)
|
||||
.await
|
||||
.context("catalog ignored cancellation after startup")?
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().to_lowercase().contains("cancel"));
|
||||
blocked.release_resource.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_discards_invalidated_page() -> Result<()> {
|
||||
for cancel_startup in [false, true] {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/skill"),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let page = tokio::spawn(async move {
|
||||
reader
|
||||
.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/skill".into(),
|
||||
cursor: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
timeout(WAIT, blocked.resource_started.notified()).await?;
|
||||
let expected = if cancel_startup {
|
||||
fixture.runtime.cancel_startup();
|
||||
"cancel"
|
||||
} else {
|
||||
fixture.runtime.invalidate_resource_caches();
|
||||
blocked.release_resource.notify_one();
|
||||
"changed during catalog discovery"
|
||||
};
|
||||
let error = timeout(WAIT, page).await??.unwrap_err();
|
||||
assert!(error.to_string().to_lowercase().contains(expected));
|
||||
blocked.release.notify_one();
|
||||
blocked.release_resource.notify_one();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_discards_page_after_account_switch() -> Result<()> {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/skill"),
|
||||
..Default::default()
|
||||
});
|
||||
let mut fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/skill".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
result = &mut page => panic!("catalog returned before account switch: {result:?}"),
|
||||
result = timeout(WAIT, blocked.resource_started.notified()) => result?,
|
||||
}
|
||||
|
||||
let previous_auth = reader.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME);
|
||||
let next_auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.second",
|
||||
"second-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
fixture
|
||||
.auth
|
||||
.set_external_auth(Arc::new(StaticAuth(next_auth.clone())))
|
||||
.await?;
|
||||
fixture.runtime_input.codex_apps_tools_cache_key =
|
||||
codex_mcp::codex_apps_tools_cache_key(Some(&next_auth));
|
||||
fixture.runtime_input.auth = Some(next_auth);
|
||||
timeout(WAIT, fixture.runtime.replace(fixture.runtime_input)).await?;
|
||||
assert!(previous_auth != reader.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME));
|
||||
blocked.release_resource.notify_one();
|
||||
let error = timeout(WAIT, page).await?.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"Apps connection changed during catalog discovery"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) struct StaticAuth(pub CodexAuth);
|
||||
|
||||
impl ExternalAuth for StaticAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
fn refresh(&self, _: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn event_connections_open_after_runtime_shutdown_with_current_auth() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
fixture.runtime.shutdown().await;
|
||||
drop(fixture.runtime);
|
||||
|
||||
fixture
|
||||
.auth
|
||||
.set_external_auth(Arc::new(StaticAuth(
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.refreshed",
|
||||
"account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
)))
|
||||
.await?;
|
||||
let mut stream = opener
|
||||
.open("test.event", &json!({}), /*request_meta*/ None)
|
||||
.await?;
|
||||
let remote = timeout(WAIT, fixture.opened.recv()).await?.unwrap();
|
||||
assert_eq!(
|
||||
remote.headers["authorization"],
|
||||
"Bearer header.e30.refreshed"
|
||||
);
|
||||
let expected = remote.notify("notifications/events/active");
|
||||
assert_eq!(timeout(WAIT, stream.recv()).await??, Some(expected));
|
||||
drop(stream);
|
||||
timeout(WAIT, remote.notifications.closed()).await?;
|
||||
Ok(())
|
||||
}
|
||||
66
codex-rs/ext/mcp/src/lib.rs
Normal file
66
codex-rs/ext/mcp/src/lib.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use codex_core::config::Config;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_extension_api::McpServerContributor;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::hosted_plugin_runtime_mcp_server_config;
|
||||
|
||||
mod catalog_observability;
|
||||
mod cloud_plugin;
|
||||
mod plugin;
|
||||
mod plugin_contributor;
|
||||
mod plugin_contributor_state;
|
||||
mod plugin_providers;
|
||||
mod stream_manager;
|
||||
|
||||
pub use codex_core_plugins::PluginListQuery;
|
||||
pub use codex_core_plugins::PluginProvider;
|
||||
pub use codex_core_plugins::PluginProviderError;
|
||||
pub use codex_core_plugins::PluginProviderFuture;
|
||||
pub use codex_core_plugins::PluginProviderResult;
|
||||
pub use plugin_contributor::install_plugin_providers;
|
||||
pub use plugin_contributor::install_plugins;
|
||||
pub use plugin_contributor_state::PluginsThreadState;
|
||||
pub use plugin_providers::PluginProviders;
|
||||
pub use stream_manager::McpEventStreamManager;
|
||||
pub use stream_manager::McpEventStreamUpdate;
|
||||
|
||||
struct HostedPluginRuntimeExtension;
|
||||
|
||||
impl McpServerContributor<Config> for HostedPluginRuntimeExtension {
|
||||
fn id(&self) -> &'static str {
|
||||
"hosted_plugin_runtime"
|
||||
}
|
||||
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
context: McpServerContributionContext<'a, Config>,
|
||||
) -> ExtensionFuture<'a, Vec<McpServerContribution>> {
|
||||
Box::pin(async move {
|
||||
let config = context.config();
|
||||
let name = CODEX_APPS_MCP_SERVER_NAME.to_string();
|
||||
if !config.features.enabled(codex_features::Feature::Apps) {
|
||||
return vec![McpServerContribution::Remove { name }];
|
||||
}
|
||||
|
||||
vec![McpServerContribution::HostedApps {
|
||||
config: Box::new(hosted_plugin_runtime_mcp_server_config(
|
||||
&config.chatgpt_base_url,
|
||||
config.apps_mcp_product_sku.as_deref(),
|
||||
context.originator(),
|
||||
)),
|
||||
protocol_mode: None,
|
||||
}]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn install(builder: &mut ExtensionRegistryBuilder<Config>) {
|
||||
builder.mcp_server_contributor(std::sync::Arc::new(HostedPluginRuntimeExtension));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
61
codex-rs/ext/mcp/src/lib_tests.rs
Normal file
61
codex-rs/ext/mcp/src/lib_tests.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
use super::*;
|
||||
use codex_config::McpServerTransportConfig;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn hosted_plugin_runtime_forwards_thread_originator() -> Result<(), Box<dyn std::error::Error>>
|
||||
{
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.cli_overrides(vec![
|
||||
("features.apps".to_string(), true.into()),
|
||||
("chatgpt_base_url".to_string(), "https://chatgpt.com".into()),
|
||||
])
|
||||
.build()
|
||||
.await?;
|
||||
let thread_init = ExtensionDataInit::new();
|
||||
let thread_store = ExtensionData::new("thread");
|
||||
|
||||
let contributions = HostedPluginRuntimeExtension
|
||||
.contribute(McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&thread_init,
|
||||
&thread_store,
|
||||
"codex_work_desktop",
|
||||
/*ready_selected_capability_roots*/ &[],
|
||||
/*executor_capability_discovery*/ None,
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
))
|
||||
.await;
|
||||
let [
|
||||
McpServerContribution::HostedApps {
|
||||
config: server,
|
||||
protocol_mode: None,
|
||||
},
|
||||
] = contributions.as_slice()
|
||||
else {
|
||||
panic!("hosted plugin runtime should contribute one server");
|
||||
};
|
||||
let McpServerTransportConfig::StreamableHttp { http_headers, .. } = &server.transport else {
|
||||
panic!("hosted plugin runtime should use streamable HTTP");
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
http_headers
|
||||
.as_ref()
|
||||
.and_then(|headers| headers.get("originator")),
|
||||
Some(&"codex_work_desktop".to_string())
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[path = "event_stream_tests.rs"]
|
||||
mod event_stream_tests;
|
||||
#[path = "stream_manager_tests.rs"]
|
||||
mod stream_manager_tests;
|
||||
472
codex-rs/ext/mcp/src/plugin.rs
Normal file
472
codex-rs/ext/mcp/src/plugin.rs
Normal file
@@ -0,0 +1,472 @@
|
||||
use codex_config::types::PluginsConfigToml;
|
||||
use codex_connectors_extension::PluginAppProvider;
|
||||
use codex_core::config::Config;
|
||||
use codex_core_plugins::ExecutorPluginProviderError;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_core_plugins::PluginRootOwnership;
|
||||
use codex_core_plugins::PluginSourceLocation;
|
||||
use codex_core_plugins::configured_plugins_from_stack;
|
||||
use codex_core_plugins::loader::apply_configured_plugin_mcp_server_policies;
|
||||
use codex_core_plugins::merge_catalogs;
|
||||
use codex_exec_server::CapabilityRootDiscovery;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_extension_api::McpServerContributor;
|
||||
use codex_extension_api::SelectedPlugin;
|
||||
use codex_extension_api::SelectedPluginContribution;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use self::provider::PluginMcpProvider;
|
||||
use crate::PluginsThreadState;
|
||||
use crate::cloud_plugin::hosted_plugin_connectors;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use crate::plugin_contributor_state::CachedPluginMetadata;
|
||||
use crate::plugin_contributor_state::CachedSelectedRoot;
|
||||
|
||||
mod discovery;
|
||||
mod provider;
|
||||
|
||||
impl PluginContributor {
|
||||
async fn ownership_for_root(
|
||||
&self,
|
||||
state: &PluginsThreadState,
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
discovery: Option<&CapabilityRootDiscovery>,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> Result<PluginRootOwnership, ExecutorPluginProviderError> {
|
||||
if let Some(ownership) = state
|
||||
.contributor_state()
|
||||
.executor_cache
|
||||
.iter()
|
||||
.find(|cached| {
|
||||
cached.root == *selected_root && cached.ownership_sandbox.as_deref() == sandbox
|
||||
})
|
||||
.and_then(|cached| cached.ownership)
|
||||
{
|
||||
return Ok(ownership);
|
||||
}
|
||||
let ownership = self
|
||||
.providers
|
||||
.executor
|
||||
.root_ownership(selected_root, discovery, sandbox)
|
||||
.await
|
||||
.inspect_err(|error| {
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } =
|
||||
&selected_root.location;
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
environment_id,
|
||||
error = %error,
|
||||
"failed to resolve selected root plugin ownership"
|
||||
);
|
||||
})?;
|
||||
let mut state = state.contributor_state();
|
||||
if let Some(cached) = state
|
||||
.executor_cache
|
||||
.iter_mut()
|
||||
.find(|cached| cached.root == *selected_root)
|
||||
{
|
||||
if cached.ownership_sandbox.as_deref() == sandbox
|
||||
&& let Some(ownership) = cached.ownership
|
||||
{
|
||||
return Ok(ownership);
|
||||
}
|
||||
cached.ownership = Some(ownership);
|
||||
cached.ownership_sandbox = sandbox.cloned().map(Box::new);
|
||||
} else {
|
||||
state.executor_cache.push(CachedSelectedRoot {
|
||||
root: selected_root.clone(),
|
||||
ownership: Some(ownership),
|
||||
ownership_sandbox: sandbox.cloned().map(Box::new),
|
||||
metadata: CachedPluginMetadata::Unloaded,
|
||||
});
|
||||
}
|
||||
Ok(ownership)
|
||||
}
|
||||
|
||||
/// Returns metadata for one stable selected root.
|
||||
///
|
||||
/// Successful resolution, including a root that is not a plugin or declares no capabilities,
|
||||
/// is cached until the thread state is dropped. Environment availability never invalidates
|
||||
/// this cache; it only controls whether the cached metadata is projected into a model step.
|
||||
#[tracing::instrument(name = "mcp.plugin.metadata.load", skip_all)]
|
||||
async fn metadata_for_root(
|
||||
&self,
|
||||
state: &PluginsThreadState,
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
) -> Option<SelectedPluginContribution> {
|
||||
if let Some(CachedSelectedRoot {
|
||||
metadata: CachedPluginMetadata::Loaded(metadata),
|
||||
..
|
||||
}) = state
|
||||
.contributor_state()
|
||||
.executor_cache
|
||||
.iter()
|
||||
.find(|cached| cached.root == *selected_root)
|
||||
{
|
||||
return metadata.clone();
|
||||
}
|
||||
|
||||
let plugin = match self.providers.executor.resolve_bound(selected_root).await {
|
||||
Ok(plugin) => plugin,
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
error = %err,
|
||||
"failed to resolve selected plugin"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let metadata = match plugin {
|
||||
Some(plugin) => {
|
||||
// MCP server and app declarations are separate
|
||||
// executor-owned files. Read them together so a remote environment only
|
||||
// pays for the slower read instead of both reads back-to-back.
|
||||
let (servers, app_declarations) = tokio::join!(
|
||||
PluginMcpProvider.load(&plugin),
|
||||
PluginAppProvider.load(&plugin)
|
||||
);
|
||||
let servers = servers.unwrap_or_else(|err| {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
error = %err,
|
||||
"failed to load selected plugin MCP servers"
|
||||
);
|
||||
Vec::new()
|
||||
});
|
||||
let connector_ids = app_declarations
|
||||
.unwrap_or_else(|err| {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
error = %err,
|
||||
"failed to load selected plugin apps"
|
||||
);
|
||||
Vec::new()
|
||||
})
|
||||
.into_iter()
|
||||
.map(|declaration| declaration.connector_id.0)
|
||||
.collect();
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } =
|
||||
&selected_root.location;
|
||||
Some(SelectedPluginContribution {
|
||||
plugin_display_name: plugin.plugin().manifest().display_name().to_string(),
|
||||
source_environment_id: environment_id.clone(),
|
||||
servers,
|
||||
connector_ids,
|
||||
})
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let mut state = state.contributor_state();
|
||||
let cache = &mut state.executor_cache;
|
||||
if let Some(cached) = cache
|
||||
.iter_mut()
|
||||
.find(|cached| cached.root == *selected_root)
|
||||
{
|
||||
if let CachedPluginMetadata::Loaded(metadata) = &cached.metadata {
|
||||
return metadata.clone();
|
||||
}
|
||||
cached.metadata = CachedPluginMetadata::Loaded(metadata.clone());
|
||||
} else {
|
||||
cache.push(CachedSelectedRoot {
|
||||
root: selected_root.clone(),
|
||||
ownership: None,
|
||||
ownership_sandbox: None,
|
||||
metadata: CachedPluginMetadata::Loaded(metadata.clone()),
|
||||
});
|
||||
}
|
||||
metadata
|
||||
}
|
||||
}
|
||||
|
||||
impl McpServerContributor<Config> for PluginContributor {
|
||||
fn id(&self) -> &'static str {
|
||||
"plugin"
|
||||
}
|
||||
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
context: McpServerContributionContext<'a, Config>,
|
||||
) -> ExtensionFuture<'a, Vec<McpServerContribution>> {
|
||||
Box::pin(async move {
|
||||
let Some(thread_store) = context.thread_store() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let cloud_plugins_enabled = self.providers.cloud.is_some()
|
||||
&& context.config().features.enabled(Feature::Plugins);
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
if !cloud_plugins_enabled {
|
||||
state.contributor_state().cloud_generation = None;
|
||||
return Vec::new();
|
||||
}
|
||||
// Core reads hosted connectors after finishing the executor registrations.
|
||||
state
|
||||
.cloud_catalog()
|
||||
.as_ref()
|
||||
.map(hosted_plugin_connectors)
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
fn hosted_plugin_ids(&self, context: McpServerContributionContext<'_, Config>) -> Vec<String> {
|
||||
if self.providers.cloud.is_none() || !context.config().features.enabled(Feature::Plugins) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(state) = context
|
||||
.thread_store()
|
||||
.and_then(codex_extension_api::ExtensionData::get::<PluginsThreadState>)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
state
|
||||
.contributor_state()
|
||||
.cloud_catalog()
|
||||
.map(|catalog| {
|
||||
hosted_plugin_connectors(catalog)
|
||||
.into_iter()
|
||||
.filter_map(|contribution| {
|
||||
if let McpServerContribution::HostedPluginConnectors { plugin_id, .. } =
|
||||
contribution
|
||||
{
|
||||
Some(plugin_id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn selected_plugins<'a>(
|
||||
&'a self,
|
||||
context: McpServerContributionContext<'a, Config>,
|
||||
plugins_config: &'a PluginsConfigToml,
|
||||
) -> ExtensionFuture<'a, Vec<SelectedPlugin<'a>>> {
|
||||
Box::pin(async move {
|
||||
let Some(thread_store) = context.thread_store() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
if context.auth_changed() {
|
||||
// Clear the old account before executor loading can yield to other work.
|
||||
state.contributor_state().cloud_generation = None;
|
||||
}
|
||||
let selected_roots = context
|
||||
.ready_selected_capability_roots()
|
||||
.unwrap_or_default();
|
||||
let mut plugins = Vec::new();
|
||||
if let Some(snapshots) = context.executor_capability_discovery_v2() {
|
||||
let merged = {
|
||||
let mut cache = state.contributor_state();
|
||||
cache.update_executor_catalog(snapshots);
|
||||
let cloud = (self.providers.cloud.is_some()
|
||||
&& context.config().features.enabled(Feature::Plugins))
|
||||
.then(|| cache.cloud_catalog())
|
||||
.flatten();
|
||||
merge_catalogs(cache.executor_catalog.as_ref(), cloud)
|
||||
};
|
||||
for warning in &merged.warnings {
|
||||
tracing::warn!(%warning, "plugin catalog merge reported a warning");
|
||||
}
|
||||
let configured = configured_plugins_from_stack(
|
||||
&context.config().config_layer_stack,
|
||||
context.config().codex_home.as_path(),
|
||||
);
|
||||
for entry in merged.entries {
|
||||
for location in &entry.locations {
|
||||
let PluginSourceLocation::Executor {
|
||||
environment_id,
|
||||
plugin_id,
|
||||
..
|
||||
} = location
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let selected_root_id = format!("{environment_id}:{plugin_id}");
|
||||
let root_id = selected_root_id.clone();
|
||||
let plugin_id = plugin_id.clone();
|
||||
let metadata_plugin_id = plugin_id.clone();
|
||||
let environment_id = environment_id.clone();
|
||||
let captured = entry.clone();
|
||||
plugins.push(SelectedPlugin {
|
||||
selected_root_id,
|
||||
plugin_id,
|
||||
identity: entry.id.clone(),
|
||||
enabled: entry.is_enabled(&configured),
|
||||
mcp: Box::pin(async move {
|
||||
let metadata = discovery::v2_metadata_from_catalog(&captured)
|
||||
.into_iter()
|
||||
.find(|(id, _)| id == &root_id)
|
||||
.map(|(_, metadata)| metadata)
|
||||
.unwrap_or_default();
|
||||
let contribution = SelectedPluginContribution {
|
||||
plugin_display_name: metadata.plugin_display_name,
|
||||
source_environment_id: environment_id,
|
||||
servers: metadata.servers,
|
||||
connector_ids: metadata.connector_ids,
|
||||
};
|
||||
project_metadata(
|
||||
context.config(),
|
||||
plugins_config,
|
||||
&metadata_plugin_id,
|
||||
contribution,
|
||||
)
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
return plugins;
|
||||
}
|
||||
state.contributor_state().clear_executor_catalog();
|
||||
|
||||
if let Some(snapshot) = context.executor_capability_discovery() {
|
||||
for root in snapshot.roots() {
|
||||
let discovery = match &root.result {
|
||||
Ok(discovery) => discovery.as_ref(),
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
selected_root = root.selected_root.id,
|
||||
error,
|
||||
"exec-server capability discovery request failed"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } =
|
||||
&root.selected_root.location;
|
||||
// Ownership survives capability parse failures; an unresolved root cannot
|
||||
// bypass a denying policy.
|
||||
if !plugins_config.allows_plugin(&root.selected_root.id)
|
||||
&& discovery.error.is_none()
|
||||
&& !matches!(
|
||||
self.ownership_for_root(
|
||||
&state,
|
||||
&root.selected_root,
|
||||
Some(discovery),
|
||||
snapshot.sandbox_contexts().get(environment_id),
|
||||
)
|
||||
.await,
|
||||
Ok(PluginRootOwnership::Standalone)
|
||||
)
|
||||
{
|
||||
plugins.push(denied_plugin(&root.selected_root));
|
||||
continue;
|
||||
}
|
||||
let Some((manifest, plugin_files)) =
|
||||
discovery::manifest_from_discovery(&root.selected_root, discovery)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
plugins.push(SelectedPlugin {
|
||||
selected_root_id: root.selected_root.id.clone(),
|
||||
plugin_id: root.selected_root.id.clone(),
|
||||
identity: PluginIdentity::Local {
|
||||
plugin_id: root.selected_root.id.clone(),
|
||||
},
|
||||
enabled: true,
|
||||
mcp: Box::pin(async move {
|
||||
let metadata = discovery::metadata_from_discovery(
|
||||
&root.selected_root,
|
||||
discovery,
|
||||
plugin_files,
|
||||
manifest,
|
||||
);
|
||||
project_metadata(
|
||||
context.config(),
|
||||
plugins_config,
|
||||
&root.selected_root.id,
|
||||
metadata,
|
||||
)
|
||||
}),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
for selected_root in selected_roots {
|
||||
if !plugins_config.allows_plugin(&selected_root.id) {
|
||||
if !matches!(
|
||||
self.ownership_for_root(
|
||||
&state,
|
||||
selected_root,
|
||||
/*discovery*/ None,
|
||||
/*sandbox*/ None
|
||||
)
|
||||
.await,
|
||||
Ok(PluginRootOwnership::Standalone)
|
||||
) {
|
||||
plugins.push(denied_plugin(selected_root));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(metadata) = self.metadata_for_root(&state, selected_root).await else {
|
||||
continue;
|
||||
};
|
||||
plugins.push(SelectedPlugin {
|
||||
selected_root_id: selected_root.id.clone(),
|
||||
plugin_id: selected_root.id.clone(),
|
||||
identity: PluginIdentity::Local {
|
||||
plugin_id: selected_root.id.clone(),
|
||||
},
|
||||
enabled: true,
|
||||
mcp: Box::pin(async move {
|
||||
project_metadata(
|
||||
context.config(),
|
||||
plugins_config,
|
||||
&selected_root.id,
|
||||
metadata,
|
||||
)
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
plugins
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn denied_plugin(selected_root: &SelectedCapabilityRoot) -> SelectedPlugin<'static> {
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location;
|
||||
let metadata = SelectedPluginContribution {
|
||||
plugin_display_name: selected_root.id.clone(),
|
||||
source_environment_id: environment_id.clone(),
|
||||
servers: Vec::new(),
|
||||
connector_ids: Vec::new(),
|
||||
};
|
||||
SelectedPlugin {
|
||||
selected_root_id: selected_root.id.clone(),
|
||||
plugin_id: selected_root.id.clone(),
|
||||
identity: PluginIdentity::Local {
|
||||
plugin_id: selected_root.id.clone(),
|
||||
},
|
||||
enabled: false,
|
||||
mcp: Box::pin(async move { metadata }),
|
||||
}
|
||||
}
|
||||
|
||||
fn project_metadata(
|
||||
config: &Config,
|
||||
plugins_config: &PluginsConfigToml,
|
||||
plugin_id: &str,
|
||||
plugin: SelectedPluginContribution,
|
||||
) -> SelectedPluginContribution {
|
||||
let mut servers = if config.features.enabled(Feature::Plugins) {
|
||||
plugin.servers.into_iter().collect::<HashMap<_, _>>()
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
if !servers.is_empty() {
|
||||
if let Some(plugin_policy) = plugins_config.plugins.get(plugin_id) {
|
||||
apply_configured_plugin_mcp_server_policies(&plugin_policy.mcp_servers, &mut servers);
|
||||
}
|
||||
config.apply_plugin_mcp_server_requirements(plugin_id, &mut servers);
|
||||
}
|
||||
let mut servers = servers.into_iter().collect::<Vec<_>>();
|
||||
servers.sort_unstable_by(|left, right| left.0.cmp(&right.0));
|
||||
SelectedPluginContribution { servers, ..plugin }
|
||||
}
|
||||
247
codex-rs/ext/mcp/src/plugin/discovery.rs
Normal file
247
codex-rs/ext/mcp/src/plugin/discovery.rs
Normal file
@@ -0,0 +1,247 @@
|
||||
use crate::cloud_plugin::MAX_CONNECTOR_IDS_PER_PLUGIN;
|
||||
use crate::cloud_plugin::MAX_PLUGIN_DISPLAY_NAME_CHARS;
|
||||
use crate::plugin_contributor_state::SelectedPluginMetadata;
|
||||
use codex_connectors::parse_plugin_app_config;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginSourceLocation;
|
||||
use codex_core_plugins::manifest::UriPluginManifest;
|
||||
use codex_core_plugins::manifest::parse_plugin_manifest_uri;
|
||||
use codex_exec_server::CapabilityRootDiscovery;
|
||||
use codex_exec_server::DiscoveredPluginFiles;
|
||||
use codex_extension_api::SelectedPluginContribution;
|
||||
use codex_mcp::PluginMcpConfigParseOutcome;
|
||||
use codex_mcp::normalize_executor_plugin_mcp_declarations;
|
||||
use codex_mcp::parse_executor_plugin_mcp_config;
|
||||
use codex_plugin::manifest::PluginManifestMcpServers;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(super) fn manifest_from_discovery<'a>(
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
discovery: &'a CapabilityRootDiscovery,
|
||||
) -> Option<(UriPluginManifest, &'a DiscoveredPluginFiles)> {
|
||||
for warning in &discovery.warnings {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
warning,
|
||||
"exec-server capability discovery warning"
|
||||
);
|
||||
}
|
||||
if let Some(error) = &discovery.error {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
error,
|
||||
"exec-server capability discovery failed"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let plugin_files = discovery.plugin.as_ref()?;
|
||||
match parse_plugin_manifest_uri(
|
||||
&discovery.path,
|
||||
&plugin_files.manifest.path,
|
||||
&plugin_files.manifest.contents,
|
||||
) {
|
||||
Ok(manifest) => Some((manifest, plugin_files)),
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
path = %plugin_files.manifest.path,
|
||||
%error,
|
||||
"failed to parse exec-server-discovered plugin manifest"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn metadata_from_discovery(
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
discovery: &CapabilityRootDiscovery,
|
||||
plugin_files: &DiscoveredPluginFiles,
|
||||
manifest: UriPluginManifest,
|
||||
) -> SelectedPluginContribution {
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location;
|
||||
let servers = match manifest.paths.mcp_servers.as_ref() {
|
||||
Some(PluginManifestMcpServers::Object(contents)) => {
|
||||
parse_mcp_servers(selected_root, &discovery.path, contents, environment_id)
|
||||
}
|
||||
Some(PluginManifestMcpServers::Path(path)) => plugin_files
|
||||
.mcp_config
|
||||
.as_ref()
|
||||
.filter(|file| file.path == *path)
|
||||
.map(|file| {
|
||||
parse_mcp_servers(
|
||||
selected_root,
|
||||
&discovery.path,
|
||||
&file.contents,
|
||||
environment_id,
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
path = %path,
|
||||
"exec-server capability bundle omitted declared MCP config"
|
||||
);
|
||||
Vec::new()
|
||||
}),
|
||||
None => plugin_files
|
||||
.mcp_config
|
||||
.as_ref()
|
||||
.map(|file| {
|
||||
parse_mcp_servers(
|
||||
selected_root,
|
||||
&discovery.path,
|
||||
&file.contents,
|
||||
environment_id,
|
||||
)
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let connector_ids = manifest
|
||||
.paths
|
||||
.apps
|
||||
.as_ref()
|
||||
.and_then(|path| {
|
||||
plugin_files
|
||||
.apps_config
|
||||
.as_ref()
|
||||
.filter(|file| file.path == *path)
|
||||
.or_else(|| {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
path = %path,
|
||||
"exec-server capability bundle omitted declared connector config"
|
||||
);
|
||||
None
|
||||
})
|
||||
})
|
||||
.and_then(|file| match parse_plugin_app_config(&file.contents) {
|
||||
Ok(declarations) => Some(declarations),
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
path = %file.path,
|
||||
%error,
|
||||
"failed to parse exec-server-discovered connector config"
|
||||
);
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|declaration| declaration.connector_id.0)
|
||||
.collect();
|
||||
|
||||
SelectedPluginContribution {
|
||||
plugin_display_name: manifest.display_name().to_string(),
|
||||
source_environment_id: environment_id.clone(),
|
||||
servers,
|
||||
connector_ids,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn v2_metadata_from_catalog(
|
||||
entry: &PluginCatalogEntry,
|
||||
) -> Vec<(String, SelectedPluginMetadata)> {
|
||||
let plugin_display_name: String = entry
|
||||
.display_name
|
||||
.chars()
|
||||
.take(MAX_PLUGIN_DISPLAY_NAME_CHARS)
|
||||
.collect();
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
let connector_ids: Vec<String> = entry
|
||||
.connector_ids
|
||||
.iter()
|
||||
.filter(|id| seen_connector_ids.insert(id.as_str()))
|
||||
.take(MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.cloned()
|
||||
.collect();
|
||||
let installations = entry
|
||||
.locations
|
||||
.iter()
|
||||
.filter_map(|location| match location {
|
||||
PluginSourceLocation::Executor {
|
||||
environment_id,
|
||||
plugin_id,
|
||||
root,
|
||||
} => Some((environment_id, plugin_id, root)),
|
||||
PluginSourceLocation::Cloud { .. } => None,
|
||||
});
|
||||
let mut projections = Vec::new();
|
||||
for (index, (environment_id, plugin_id, root)) in installations.enumerate() {
|
||||
let root_id = format!("{environment_id}:{plugin_id}");
|
||||
// Only the first retained installation supplies MCPs; the others retain package attribution.
|
||||
let servers = if index == 0 {
|
||||
let parsed = normalize_executor_plugin_mcp_declarations(
|
||||
root,
|
||||
entry.mcp_servers.clone(),
|
||||
environment_id,
|
||||
);
|
||||
servers_from_outcome(&root_id, parsed)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let metadata = SelectedPluginMetadata {
|
||||
plugin_display_name: plugin_display_name.clone(),
|
||||
servers,
|
||||
connector_ids: connector_ids.clone(),
|
||||
};
|
||||
projections.push((root_id, metadata));
|
||||
}
|
||||
if entry
|
||||
.locations
|
||||
.iter()
|
||||
.any(|location| matches!(location, PluginSourceLocation::Cloud { .. }))
|
||||
{
|
||||
projections.push((
|
||||
format!("cloud:{}", entry.id.as_str()),
|
||||
SelectedPluginMetadata {
|
||||
plugin_display_name,
|
||||
servers: Vec::new(),
|
||||
connector_ids,
|
||||
},
|
||||
));
|
||||
}
|
||||
projections
|
||||
}
|
||||
|
||||
fn parse_mcp_servers(
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
plugin_root: &codex_utils_path_uri::PathUri,
|
||||
contents: &str,
|
||||
environment_id: &str,
|
||||
) -> Vec<(String, codex_config::McpServerConfig)> {
|
||||
let parsed = match parse_executor_plugin_mcp_config(plugin_root, contents, environment_id) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
%error,
|
||||
"failed to parse exec-server-discovered MCP config"
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
servers_from_outcome(&selected_root.id, parsed)
|
||||
}
|
||||
|
||||
fn servers_from_outcome(
|
||||
selected_root_id: &str,
|
||||
parsed: PluginMcpConfigParseOutcome,
|
||||
) -> Vec<(String, codex_config::McpServerConfig)> {
|
||||
for error in parsed.errors {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root_id,
|
||||
server = error.name,
|
||||
error = error.message,
|
||||
"ignoring invalid exec-server-discovered MCP server"
|
||||
);
|
||||
}
|
||||
parsed.servers.into_iter().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "discovery_tests.rs"]
|
||||
mod tests;
|
||||
134
codex-rs/ext/mcp/src/plugin/discovery_tests.rs
Normal file
134
codex-rs/ext/mcp/src/plugin/discovery_tests.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
//! Verifies merged MCPs use the first retained installation while preserving all package identities.
|
||||
|
||||
use super::*;
|
||||
use codex_config::McpServerTransportConfig;
|
||||
use codex_config::types::PluginsConfigToml;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_extension_api::SelectedPluginContribution;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Result<()> {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.cli_overrides(vec![("features.plugins".to_string(), true.into())])
|
||||
.build()
|
||||
.await?;
|
||||
let mut entry = PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: "plugin_example".to_string(),
|
||||
},
|
||||
display_name: "Example".to_string(),
|
||||
version: "1".to_string(),
|
||||
mcp_servers: std::collections::BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command":"node","args":["server.js"],"cwd":"mcp"}),
|
||||
)]),
|
||||
connector_ids: vec!["connector_example".to_string()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: "plugin://plugin_example".to_string(),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
};
|
||||
let projections = v2_metadata_from_catalog(&entry);
|
||||
let [(root_id, metadata)] = projections.as_slice() else {
|
||||
panic!("one cloud projection expected");
|
||||
};
|
||||
assert_eq!(root_id, "cloud:plugin_example");
|
||||
assert!(metadata.servers.is_empty());
|
||||
assert_eq!(metadata.connector_ids, vec!["connector_example"]);
|
||||
|
||||
// Attribution keeps the installation key; server configs distinguish the executors.
|
||||
let installations = [
|
||||
("executor-b", "example@acme", "/other/example/1"),
|
||||
("executor-a", "example@acme", "/plugins/example/1"),
|
||||
];
|
||||
// Retained catalog order, not lexical environment order, chooses the executor.
|
||||
for (environment_id, plugin_id, root) in installations {
|
||||
entry.locations.push(PluginSourceLocation::Executor {
|
||||
environment_id: environment_id.to_string(),
|
||||
plugin_id: plugin_id.to_string(),
|
||||
root: PathUri::parse(&format!("file://{root}"))?,
|
||||
});
|
||||
}
|
||||
let projections = v2_metadata_from_catalog(&entry);
|
||||
assert_eq!(projections.len(), installations.len() + 1);
|
||||
for (index, ((root_id, metadata), (environment_id, plugin_id, root))) in
|
||||
projections.iter().zip(installations).enumerate()
|
||||
{
|
||||
assert_eq!(root_id, &format!("{environment_id}:{plugin_id}"));
|
||||
let contribution = super::super::project_metadata(
|
||||
&config,
|
||||
&PluginsConfigToml::default(),
|
||||
plugin_id,
|
||||
SelectedPluginContribution {
|
||||
plugin_display_name: metadata.plugin_display_name.clone(),
|
||||
source_environment_id: environment_id.to_string(),
|
||||
servers: metadata.servers.clone(),
|
||||
connector_ids: metadata.connector_ids.clone(),
|
||||
},
|
||||
);
|
||||
assert_eq!(contribution.connector_ids, entry.connector_ids);
|
||||
if index != 0 {
|
||||
assert!(contribution.servers.is_empty());
|
||||
continue;
|
||||
}
|
||||
let [(name, mcp_config)] = contribution.servers.as_slice() else {
|
||||
panic!("one MCP contribution expected");
|
||||
};
|
||||
assert_eq!(mcp_config.environment_id, environment_id);
|
||||
assert_eq!(name, "example");
|
||||
let McpServerTransportConfig::Stdio { command, cwd, .. } = &mcp_config.transport else {
|
||||
panic!("stdio expected");
|
||||
};
|
||||
assert_eq!(command, "node");
|
||||
assert_eq!(
|
||||
cwd.as_ref()
|
||||
.map(codex_utils_path_uri::LegacyAppPathString::as_str),
|
||||
Some(format!("{root}/mcp").as_str())
|
||||
);
|
||||
}
|
||||
|
||||
let (root_id, metadata) = &projections[installations.len()];
|
||||
assert_eq!(root_id, "cloud:plugin_example");
|
||||
assert!(metadata.servers.is_empty());
|
||||
assert_eq!(metadata.connector_ids, vec!["connector_example"]);
|
||||
|
||||
// Bound projected metadata without mutating the source catalog or losing installations.
|
||||
entry.display_name = "界".repeat(MAX_PLUGIN_DISPLAY_NAME_CHARS + 1);
|
||||
entry.connector_ids = (0..=MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.flat_map(|index| vec![format!("connector_{index}"); 2])
|
||||
.collect();
|
||||
let expected_connectors = (0..MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.map(|index| format!("connector_{index}"))
|
||||
.collect::<Vec<_>>();
|
||||
entry.mcp_servers.clear();
|
||||
let projections = v2_metadata_from_catalog(&entry);
|
||||
assert_eq!(projections.len(), installations.len() + 1);
|
||||
assert!(
|
||||
projections
|
||||
.iter()
|
||||
.all(|(_, metadata)| metadata.servers.is_empty())
|
||||
);
|
||||
for (_, metadata) in projections {
|
||||
assert_eq!(
|
||||
metadata.plugin_display_name,
|
||||
"界".repeat(MAX_PLUGIN_DISPLAY_NAME_CHARS)
|
||||
);
|
||||
assert_eq!(metadata.connector_ids, expected_connectors);
|
||||
}
|
||||
assert_eq!(
|
||||
entry.display_name.chars().count(),
|
||||
MAX_PLUGIN_DISPLAY_NAME_CHARS + 1
|
||||
);
|
||||
assert_eq!(
|
||||
entry.connector_ids.len(),
|
||||
(MAX_CONNECTOR_IDS_PER_PLUGIN + 1) * 2
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
144
codex-rs/ext/mcp/src/plugin/provider.rs
Normal file
144
codex-rs/ext/mcp/src/plugin/provider.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
use codex_config::McpServerConfig;
|
||||
use codex_core_plugins::ResolvedExecutorPlugin;
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_mcp::parse_executor_plugin_mcp_config;
|
||||
use codex_plugin::PluginResourceLocator;
|
||||
use codex_plugin::ResolvedPlugin;
|
||||
use codex_plugin::ResolvedPluginLocation;
|
||||
use codex_plugin::manifest::PluginManifestMcpServers;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_path_uri::PathUriParseError;
|
||||
use std::io;
|
||||
use thiserror::Error;
|
||||
|
||||
const DEFAULT_MCP_CONFIG_FILE: &str = ".mcp.json";
|
||||
|
||||
/// Loads MCP declarations from resolved plugins.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(super) struct PluginMcpProvider;
|
||||
|
||||
/// Failure to load a plugin's MCP declarations.
|
||||
#[derive(Debug, Error)]
|
||||
pub(super) enum PluginMcpProviderError {
|
||||
#[error("failed to read MCP config for selected plugin `{plugin_id}` at `{path}`: {source}")]
|
||||
ReadConfig {
|
||||
plugin_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
#[error(
|
||||
"failed to resolve MCP config path `{relative_path}` below selected plugin `{plugin_id}` at `{root}`: {source}"
|
||||
)]
|
||||
InvalidConfigPath {
|
||||
plugin_id: String,
|
||||
root: PathUri,
|
||||
relative_path: &'static str,
|
||||
#[source]
|
||||
source: PathUriParseError,
|
||||
},
|
||||
#[error("failed to parse MCP config for selected plugin `{plugin_id}` at `{path}`: {source}")]
|
||||
ParseConfig {
|
||||
plugin_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
}
|
||||
|
||||
impl PluginMcpProvider {
|
||||
/// Returns MCP servers declared by `plugin`, bound to its environment.
|
||||
#[tracing::instrument(name = "mcp.plugin.servers.load", skip_all)]
|
||||
pub(super) async fn load(
|
||||
&self,
|
||||
plugin: &ResolvedExecutorPlugin,
|
||||
) -> Result<Vec<(String, McpServerConfig)>, PluginMcpProviderError> {
|
||||
let ResolvedPluginLocation::Environment { root, .. } = plugin.plugin().location();
|
||||
|
||||
load_from_file_system(plugin.plugin(), root, plugin.file_system()).await
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_from_file_system(
|
||||
plugin: &ResolvedPlugin,
|
||||
plugin_root: &PathUri,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
) -> Result<Vec<(String, McpServerConfig)>, PluginMcpProviderError> {
|
||||
let ResolvedPluginLocation::Environment { environment_id, .. } = plugin.location();
|
||||
let plugin_id = plugin.selected_root_id();
|
||||
let (contents, config_path) = match plugin.manifest().paths.mcp_servers.as_ref() {
|
||||
Some(PluginManifestMcpServers::Path(PluginResourceLocator::Environment {
|
||||
path, ..
|
||||
})) => {
|
||||
(
|
||||
file_system
|
||||
.read_file_text(path, ReadFileOptions::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.map_err(|source| PluginMcpProviderError::ReadConfig {
|
||||
plugin_id: plugin_id.to_string(),
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?,
|
||||
path.clone(),
|
||||
)
|
||||
}
|
||||
Some(PluginManifestMcpServers::Object(object_config)) => {
|
||||
let PluginResourceLocator::Environment { path, .. } = plugin.manifest_path();
|
||||
(object_config.clone(), path.clone())
|
||||
}
|
||||
None => {
|
||||
let config_path = plugin_root
|
||||
.join(DEFAULT_MCP_CONFIG_FILE)
|
||||
.map_err(|source| PluginMcpProviderError::InvalidConfigPath {
|
||||
plugin_id: plugin_id.to_string(),
|
||||
root: plugin_root.clone(),
|
||||
relative_path: DEFAULT_MCP_CONFIG_FILE,
|
||||
source,
|
||||
})?;
|
||||
let contents = match file_system
|
||||
.read_file_text(
|
||||
&config_path,
|
||||
ReadFileOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(contents) => contents,
|
||||
Err(source) if source.kind() == io::ErrorKind::NotFound => {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Err(source) => {
|
||||
return Err(PluginMcpProviderError::ReadConfig {
|
||||
plugin_id: plugin_id.to_string(),
|
||||
path: config_path.clone(),
|
||||
source,
|
||||
});
|
||||
}
|
||||
};
|
||||
(contents, config_path)
|
||||
}
|
||||
};
|
||||
let parsed = parse_executor_plugin_mcp_config(plugin_root, &contents, environment_id).map_err(
|
||||
|source| PluginMcpProviderError::ParseConfig {
|
||||
plugin_id: plugin_id.to_string(),
|
||||
path: config_path,
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
|
||||
for error in parsed.errors {
|
||||
tracing::warn!(
|
||||
plugin = plugin_id,
|
||||
server = error.name,
|
||||
error = error.message,
|
||||
"ignoring invalid plugin MCP server"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(parsed.servers.into_iter().collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "provider_tests.rs"]
|
||||
mod tests;
|
||||
449
codex-rs/ext/mcp/src/plugin/provider_tests.rs
Normal file
449
codex-rs/ext/mcp/src/plugin/provider_tests.rs
Normal file
@@ -0,0 +1,449 @@
|
||||
use super::DEFAULT_MCP_CONFIG_FILE;
|
||||
use super::PluginMcpProviderError;
|
||||
use super::load_from_file_system;
|
||||
use codex_config::McpServerConfig;
|
||||
use codex_config::McpServerTransportConfig;
|
||||
use codex_exec_server::CopyOptions;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::ExecutorFileSystemFuture;
|
||||
use codex_exec_server::FileMetadata;
|
||||
use codex_exec_server::FileSystemReadStream;
|
||||
use codex_exec_server::FileSystemResult;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_exec_server::GetMetadataOptions;
|
||||
use codex_exec_server::ReadDirectoryEntry;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_exec_server::RemoveOptions;
|
||||
use codex_exec_server::WalkOptions;
|
||||
use codex_exec_server::WalkOutcome;
|
||||
use codex_exec_server::WriteFileOptions;
|
||||
use codex_plugin::ResolvedPlugin;
|
||||
use codex_plugin::manifest::PluginManifest;
|
||||
use codex_plugin::manifest::PluginManifestMcpServers;
|
||||
use codex_plugin::manifest::PluginManifestPaths;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const MCP_CONFIG_CONTENTS: &str = r#"{
|
||||
"mcpServers": {
|
||||
"demo": {"command": "demo-mcp", "environment_id": "local"},
|
||||
"hosted": {"url": "https://example.com/mcp"}
|
||||
}
|
||||
}"#;
|
||||
|
||||
struct SyntheticExecutorFileSystem {
|
||||
config_path: AbsolutePathBuf,
|
||||
config_contents: Option<&'static str>,
|
||||
reads: Mutex<Vec<AbsolutePathBuf>>,
|
||||
}
|
||||
|
||||
impl SyntheticExecutorFileSystem {
|
||||
fn unsupported<T>() -> FileSystemResult<T> {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"operation is not used by plugin MCP provider tests",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutorFileSystem for SyntheticExecutorFileSystem {
|
||||
fn canonicalize<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, PathUri> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn read_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
_options: ReadFileOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
|
||||
Box::pin(async move {
|
||||
let path = path.to_abs_path()?;
|
||||
self.reads
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(path.clone());
|
||||
if path != self.config_path {
|
||||
return Err(io::Error::new(io::ErrorKind::NotFound, "not found"));
|
||||
}
|
||||
self.config_contents
|
||||
.map(|contents| contents.as_bytes().to_vec())
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "not found"))
|
||||
})
|
||||
}
|
||||
|
||||
fn read_file_stream<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileSystemReadStream> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn write_file<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_contents: Vec<u8>,
|
||||
_options: WriteFileOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn create_directory<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: CreateDirectoryOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn get_metadata<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: GetMetadataOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn read_directory<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn walk<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: WalkOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, WalkOutcome> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn remove<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: RemoveOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn copy<'a>(
|
||||
&'a self,
|
||||
_source_path: &'a PathUri,
|
||||
_destination_path: &'a PathUri,
|
||||
_options: CopyOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_declared_config_only_through_executor_file_system() {
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let plugin_root =
|
||||
AbsolutePathBuf::from_absolute_path_checked(temp_dir.path().join("executor-only-plugin"))
|
||||
.expect("absolute plugin root");
|
||||
assert!(!plugin_root.as_path().exists());
|
||||
let config_path = plugin_root.join("config/mcp.json");
|
||||
let plugin = resolved_plugin(
|
||||
&plugin_root,
|
||||
Some(PluginManifestMcpServers::Path(config_path.clone())),
|
||||
);
|
||||
let file_system = SyntheticExecutorFileSystem {
|
||||
config_path: config_path.clone(),
|
||||
config_contents: Some(MCP_CONFIG_CONTENTS),
|
||||
reads: Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
let plugin_root_uri = PathUri::from_abs_path(&plugin_root);
|
||||
let servers = load_from_file_system(&plugin, &plugin_root_uri, &file_system)
|
||||
.await
|
||||
.expect("load plugin MCP config");
|
||||
|
||||
assert_eq!(
|
||||
servers,
|
||||
vec![
|
||||
(
|
||||
"demo".to_string(),
|
||||
McpServerConfig {
|
||||
auth: Default::default(),
|
||||
transport: McpServerTransportConfig::Stdio {
|
||||
command: "demo-mcp".to_string(),
|
||||
args: Vec::new(),
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: Some(LegacyAppPathString::from_path(plugin_root.as_path())),
|
||||
},
|
||||
environment_id: "executor-test".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(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"hosted".to_string(),
|
||||
McpServerConfig {
|
||||
auth: Default::default(),
|
||||
transport: McpServerTransportConfig::StreamableHttp {
|
||||
url: "https://example.com/mcp".to_string(),
|
||||
bearer_token_env_var: None,
|
||||
http_headers: None,
|
||||
env_http_headers: None,
|
||||
http_headers_helper: None,
|
||||
},
|
||||
environment_id: "executor-test".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(),
|
||||
},
|
||||
),
|
||||
]
|
||||
);
|
||||
assert_eq!(reads(&file_system), vec![config_path]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_manifest_object_config_without_executor_file_system_access() {
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path_checked(temp_dir.path().join("plugin"))
|
||||
.expect("absolute plugin root");
|
||||
let config_path = plugin_root.join(DEFAULT_MCP_CONFIG_FILE);
|
||||
let plugin = resolved_plugin(
|
||||
&plugin_root,
|
||||
Some(PluginManifestMcpServers::Object(
|
||||
r#"{"counter":{"command":"counter-mcp","environment_id":"local"}}"#.to_string(),
|
||||
)),
|
||||
);
|
||||
let file_system = SyntheticExecutorFileSystem {
|
||||
config_path,
|
||||
config_contents: None,
|
||||
reads: Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
let plugin_root_uri = PathUri::from_abs_path(&plugin_root);
|
||||
let servers = load_from_file_system(&plugin, &plugin_root_uri, &file_system)
|
||||
.await
|
||||
.expect("load manifest object plugin MCP config");
|
||||
|
||||
assert_eq!(
|
||||
servers,
|
||||
vec![(
|
||||
"counter".to_string(),
|
||||
McpServerConfig {
|
||||
auth: Default::default(),
|
||||
transport: McpServerTransportConfig::Stdio {
|
||||
command: "counter-mcp".to_string(),
|
||||
args: Vec::new(),
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: Some(LegacyAppPathString::from_path(plugin_root.as_path())),
|
||||
},
|
||||
environment_id: "executor-test".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(),
|
||||
},
|
||||
)]
|
||||
);
|
||||
assert_eq!(reads(&file_system), Vec::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_default_config_is_empty() {
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path_checked(temp_dir.path().join("plugin"))
|
||||
.expect("absolute plugin root");
|
||||
let config_path = plugin_root.join(DEFAULT_MCP_CONFIG_FILE);
|
||||
let plugin = resolved_plugin(&plugin_root, /*mcp_servers*/ None);
|
||||
let file_system = SyntheticExecutorFileSystem {
|
||||
config_path: config_path.clone(),
|
||||
config_contents: None,
|
||||
reads: Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
let plugin_root_uri = PathUri::from_abs_path(&plugin_root);
|
||||
let servers = load_from_file_system(&plugin, &plugin_root_uri, &file_system)
|
||||
.await
|
||||
.expect("missing default config should be ignored");
|
||||
|
||||
assert_eq!(servers, Vec::new());
|
||||
assert_eq!(reads(&file_system), vec![config_path]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_declared_config_is_an_error() {
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path_checked(temp_dir.path().join("plugin"))
|
||||
.expect("absolute plugin root");
|
||||
let config_path = plugin_root.join("mcp.json");
|
||||
let plugin = resolved_plugin(
|
||||
&plugin_root,
|
||||
Some(PluginManifestMcpServers::Path(config_path.clone())),
|
||||
);
|
||||
let file_system = SyntheticExecutorFileSystem {
|
||||
config_path: config_path.clone(),
|
||||
config_contents: Some("{not-json"),
|
||||
reads: Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
let plugin_root_uri = PathUri::from_abs_path(&plugin_root);
|
||||
let err = load_from_file_system(&plugin, &plugin_root_uri, &file_system)
|
||||
.await
|
||||
.expect_err("malformed declared config should fail");
|
||||
|
||||
let PluginMcpProviderError::ParseConfig {
|
||||
plugin_id,
|
||||
path,
|
||||
source: _,
|
||||
} = err
|
||||
else {
|
||||
panic!("expected parse error");
|
||||
};
|
||||
assert_eq!(
|
||||
(plugin_id, path),
|
||||
(
|
||||
"selected-root".to_string(),
|
||||
PathUri::from_abs_path(&config_path)
|
||||
)
|
||||
);
|
||||
assert_eq!(reads(&file_system), vec![config_path]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_manifest_object_config_reports_actual_manifest_path() {
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path_checked(temp_dir.path().join("plugin"))
|
||||
.expect("absolute plugin root");
|
||||
let plugin = resolved_plugin(
|
||||
&plugin_root,
|
||||
Some(PluginManifestMcpServers::Object("{not-json".to_string())),
|
||||
);
|
||||
let file_system = SyntheticExecutorFileSystem {
|
||||
config_path: plugin_root.join(DEFAULT_MCP_CONFIG_FILE),
|
||||
config_contents: None,
|
||||
reads: Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
let plugin_root_uri = PathUri::from_abs_path(&plugin_root);
|
||||
let err = load_from_file_system(&plugin, &plugin_root_uri, &file_system)
|
||||
.await
|
||||
.expect_err("malformed manifest object config should fail");
|
||||
|
||||
let PluginMcpProviderError::ParseConfig {
|
||||
plugin_id,
|
||||
path,
|
||||
source: _,
|
||||
} = err
|
||||
else {
|
||||
panic!("expected parse error");
|
||||
};
|
||||
assert_eq!(
|
||||
(plugin_id, path),
|
||||
(
|
||||
"selected-root".to_string(),
|
||||
PathUri::from_abs_path(&plugin_root.join(".claude-plugin/plugin.json"))
|
||||
)
|
||||
);
|
||||
assert_eq!(reads(&file_system), Vec::new());
|
||||
}
|
||||
|
||||
fn resolved_plugin(
|
||||
plugin_root: &AbsolutePathBuf,
|
||||
mcp_servers: Option<PluginManifestMcpServers<AbsolutePathBuf>>,
|
||||
) -> ResolvedPlugin {
|
||||
let plugin_root_uri = PathUri::from_abs_path(plugin_root);
|
||||
let mcp_servers = mcp_servers.map(|mcp_servers| match mcp_servers {
|
||||
PluginManifestMcpServers::Path(path) => {
|
||||
PluginManifestMcpServers::Path(PathUri::from_abs_path(&path))
|
||||
}
|
||||
PluginManifestMcpServers::Object(config) => PluginManifestMcpServers::Object(config),
|
||||
});
|
||||
ResolvedPlugin::from_environment(
|
||||
"selected-root".to_string(),
|
||||
"executor-test".to_string(),
|
||||
plugin_root_uri.clone(),
|
||||
plugin_root_uri
|
||||
.join(".claude-plugin/plugin.json")
|
||||
.expect("manifest URI"),
|
||||
PluginManifest {
|
||||
name: "demo-plugin".to_string(),
|
||||
version: None,
|
||||
description: None,
|
||||
keywords: Vec::new(),
|
||||
paths: PluginManifestPaths {
|
||||
onboarding_skill: None,
|
||||
skills: Vec::new(),
|
||||
mcp_servers,
|
||||
apps: None,
|
||||
hooks: None,
|
||||
},
|
||||
interface: None,
|
||||
},
|
||||
)
|
||||
.expect("valid plugin descriptor")
|
||||
}
|
||||
|
||||
fn reads(file_system: &SyntheticExecutorFileSystem) -> Vec<AbsolutePathBuf> {
|
||||
file_system
|
||||
.reads
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone()
|
||||
}
|
||||
40
codex-rs/ext/mcp/src/plugin_contributor.rs
Normal file
40
codex-rs/ext/mcp/src/plugin_contributor.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
//! Coordinates cloud turn refreshes and executor MCP contributions with thread-owned catalogs.
|
||||
//!
|
||||
//! One contributor is registered for both lifecycles. Provider instances are shared, while
|
||||
//! catalogs and executor metadata live together in thread extension data.
|
||||
|
||||
use crate::PluginProviders;
|
||||
use codex_core::config::Config;
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) struct PluginContributor {
|
||||
pub(crate) providers: PluginProviders,
|
||||
}
|
||||
|
||||
/// Installs one coordinator for cloud turn-start and executor MCP callbacks.
|
||||
/// The optional cloud provider never disables executor plugins, and Core's plugin policy applies
|
||||
/// to both paths.
|
||||
pub fn install_plugin_providers(
|
||||
builder: &mut ExtensionRegistryBuilder<Config>,
|
||||
providers: PluginProviders,
|
||||
) {
|
||||
let contributor = Arc::new(PluginContributor { providers });
|
||||
builder.thread_lifecycle_contributor(contributor.clone());
|
||||
builder.config_contributor(contributor.clone());
|
||||
builder.turn_lifecycle_contributor(contributor.clone());
|
||||
builder.mcp_server_contributor(contributor);
|
||||
}
|
||||
|
||||
/// Installs plugin support backed by selected environment roots.
|
||||
pub fn install_plugins(
|
||||
builder: &mut ExtensionRegistryBuilder<Config>,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
) {
|
||||
install_plugin_providers(
|
||||
builder,
|
||||
PluginProviders::new(Arc::new(ExecutorPluginProvider::new(environment_manager))),
|
||||
);
|
||||
}
|
||||
193
codex-rs/ext/mcp/src/plugin_contributor_state.rs
Normal file
193
codex-rs/ext/mcp/src/plugin_contributor_state.rs
Normal file
@@ -0,0 +1,193 @@
|
||||
//! Thread-owned cloud catalog and stable selected-root metadata, guarded by a short-lived mutex.
|
||||
|
||||
use crate::catalog_observability::record_catalog;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginRootOwnership;
|
||||
use codex_core_plugins::catalog_from_snapshots;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_extension_api::CatalogRefreshBackoff;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_extension_api::SelectedPluginContribution;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpResourceClientAuthKey;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::MutexGuard;
|
||||
use tokio::sync::Mutex as AsyncMutex;
|
||||
|
||||
/// Plugin configuration and caches owned by one thread; mutable state stays extension-private.
|
||||
#[derive(Default)]
|
||||
pub struct PluginsThreadState {
|
||||
/// Serializes discovery; true only when the last refresh published successfully.
|
||||
pub(crate) cloud_refresh_lock: AsyncMutex<bool>,
|
||||
state: Mutex<PluginContributorState>,
|
||||
}
|
||||
|
||||
impl PluginsThreadState {
|
||||
/// Returns an owned cloud snapshot only while its auth generation is current.
|
||||
pub fn cloud_catalog(&self) -> Option<PluginCatalog> {
|
||||
self.contributor_state().cloud_catalog().cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn contributor_state(&self) -> MutexGuard<'_, PluginContributorState> {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
/// `None` is unpublished; an empty catalog is a successful discovery result.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PluginContributorState {
|
||||
pub(crate) extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
|
||||
pub(crate) plugins_enabled: bool,
|
||||
pub(crate) cloud_generation: Option<CloudPluginGeneration>,
|
||||
pub(crate) cloud_retry: Option<CatalogRefreshBackoff>,
|
||||
pub(crate) executor_catalog: Option<PluginCatalog>,
|
||||
executor_snapshots: Vec<ExecutorCapabilityDiscoveryV2Snapshot>,
|
||||
pub(crate) executor_cache: Vec<CachedSelectedRoot>,
|
||||
}
|
||||
|
||||
/// Keeps cloud plugin metadata within one published auth scope and Apps availability state.
|
||||
pub(crate) struct CloudPluginGeneration {
|
||||
pub(crate) auth_cache_key: Option<McpResourceClientAuthKey>,
|
||||
pub(crate) mcp_resources: Option<McpResourceClient>,
|
||||
pub(crate) catalog: Option<PluginCatalog>,
|
||||
}
|
||||
|
||||
impl CloudPluginGeneration {
|
||||
pub(crate) fn is_auth_current(&self) -> bool {
|
||||
self.auth_cache_key
|
||||
== self
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.map(|client| client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME))
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginContributorState {
|
||||
/// Reuses unchanged discovery and preserves surviving installations' order on refresh.
|
||||
pub(crate) fn update_executor_catalog(
|
||||
&mut self,
|
||||
snapshots: &[ExecutorCapabilityDiscoveryV2Snapshot],
|
||||
) {
|
||||
if self.executor_catalog.is_some() && self.executor_snapshots == snapshots {
|
||||
return;
|
||||
}
|
||||
let mut catalog = catalog_from_snapshots(snapshots);
|
||||
if let Some(previous) = &self.executor_catalog {
|
||||
// Preserve installation order to keep MCPs on the same executor while it remains available.
|
||||
let mut previous_ranks = HashMap::with_capacity(previous.entries.len());
|
||||
for (rank, entry) in previous.entries.iter().enumerate() {
|
||||
previous_ranks
|
||||
.entry((&entry.id, entry.locations.as_slice()))
|
||||
.or_insert(rank);
|
||||
}
|
||||
catalog.entries.sort_by_key(|entry| {
|
||||
previous_ranks
|
||||
.get(&(&entry.id, entry.locations.as_slice()))
|
||||
.copied()
|
||||
.unwrap_or(usize::MAX)
|
||||
});
|
||||
}
|
||||
record_catalog(self.extension_metrics.as_deref(), "executor", &catalog);
|
||||
self.executor_catalog = Some(catalog);
|
||||
self.executor_snapshots = snapshots.to_vec();
|
||||
}
|
||||
|
||||
pub(crate) fn clear_executor_catalog(&mut self) {
|
||||
self.executor_catalog = None;
|
||||
self.executor_snapshots.clear();
|
||||
}
|
||||
|
||||
/// Returns the cloud catalog only while it belongs to the live auth generation.
|
||||
pub(crate) fn cloud_catalog(&self) -> Option<&PluginCatalog> {
|
||||
self.cloud_generation
|
||||
.as_ref()
|
||||
.filter(|generation| generation.is_auth_current())
|
||||
.and_then(|generation| generation.catalog.as_ref())
|
||||
}
|
||||
|
||||
/// Establishes the auth scope and returns the key used by that generation.
|
||||
pub(crate) fn prepare_cloud_generation(
|
||||
&mut self,
|
||||
mcp_resources: Option<McpResourceClient>,
|
||||
) -> Option<McpResourceClientAuthKey> {
|
||||
let auth_cache_key = mcp_resources
|
||||
.as_ref()
|
||||
.map(|client| client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME));
|
||||
if self
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.is_none_or(|generation| generation.auth_cache_key != auth_cache_key)
|
||||
{
|
||||
self.cloud_generation = Some(CloudPluginGeneration {
|
||||
auth_cache_key: auth_cache_key.clone(),
|
||||
mcp_resources,
|
||||
catalog: None,
|
||||
});
|
||||
}
|
||||
auth_cache_key
|
||||
}
|
||||
|
||||
/// Accepts current-auth results, retaining prior complete entries as partial after an incomplete refresh.
|
||||
/// Returns false only when the result belongs to a stale auth generation.
|
||||
pub(crate) fn publish_cloud_catalog(
|
||||
&mut self,
|
||||
auth_cache_key: Option<&McpResourceClientAuthKey>,
|
||||
mut catalog: PluginCatalog,
|
||||
) -> bool {
|
||||
let Some(generation) = self
|
||||
.cloud_generation
|
||||
.as_mut()
|
||||
.filter(|generation| generation.auth_cache_key.as_ref() == auth_cache_key)
|
||||
.filter(|generation| generation.is_auth_current())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if catalog.is_partial
|
||||
&& let Some(previous) = generation
|
||||
.catalog
|
||||
.as_ref()
|
||||
.filter(|previous| !previous.is_partial)
|
||||
{
|
||||
catalog = previous.clone();
|
||||
catalog.is_partial = true;
|
||||
tracing::warn!(
|
||||
"cloud plugin discovery was partial; retaining prior auth-scoped entries as partial"
|
||||
);
|
||||
}
|
||||
record_catalog(self.extension_metrics.as_deref(), "cloud", &catalog);
|
||||
generation.catalog = Some(catalog);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CachedSelectedRoot {
|
||||
pub(crate) root: SelectedCapabilityRoot,
|
||||
pub(crate) ownership: Option<PluginRootOwnership>,
|
||||
pub(crate) ownership_sandbox: Option<Box<FileSystemSandboxContext>>,
|
||||
pub(crate) metadata: CachedPluginMetadata,
|
||||
}
|
||||
|
||||
/// Denied roots retain ownership without loading their capabilities.
|
||||
pub(crate) enum CachedPluginMetadata {
|
||||
Unloaded,
|
||||
Loaded(Option<SelectedPluginContribution>),
|
||||
}
|
||||
|
||||
/// Bounded declarations projected from merged plugin metadata.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct SelectedPluginMetadata {
|
||||
pub(crate) plugin_display_name: String,
|
||||
pub(crate) servers: Vec<(String, codex_config::McpServerConfig)>,
|
||||
pub(crate) connector_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_contributor_state_tests.rs"]
|
||||
mod tests;
|
||||
507
codex-rs/ext/mcp/src/plugin_contributor_state_tests.rs
Normal file
507
codex-rs/ext/mcp/src/plugin_contributor_state_tests.rs
Normal file
@@ -0,0 +1,507 @@
|
||||
//! Tests thread-owned discovery caching, installation ordering, and contribution projection.
|
||||
|
||||
use super::*;
|
||||
use crate::PluginProviders;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_core_plugins::PluginProvider;
|
||||
use codex_core_plugins::PluginSourceLocation;
|
||||
use codex_exec_server::CapabilityTextFile;
|
||||
use codex_exec_server::DiscoverV2CapabilitiesResponse;
|
||||
use codex_exec_server::DiscoveredPluginFiles;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryCache;
|
||||
use codex_exec_server::ExecutorPlugin;
|
||||
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_extension_api::McpServerContributor;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
async fn contribution_labels(
|
||||
contributor: &PluginContributor,
|
||||
context: McpServerContributionContext<'_, codex_core::config::Config>,
|
||||
) -> Vec<String> {
|
||||
let mut labels = Vec::new();
|
||||
let policy = codex_config::types::PluginsConfigToml::default();
|
||||
for plugin in contributor.selected_plugins(context, &policy).await {
|
||||
if !plugin.enabled {
|
||||
labels.push(format!("disabled:{}", plugin.plugin_id));
|
||||
continue;
|
||||
}
|
||||
let contribution = plugin.mcp.await;
|
||||
labels.extend(
|
||||
contribution
|
||||
.servers
|
||||
.into_iter()
|
||||
.map(|(name, _)| format!("mcp:{name}")),
|
||||
);
|
||||
labels.push(plugin.selected_root_id);
|
||||
}
|
||||
for contribution in contributor.contribute(context).await {
|
||||
if let McpServerContribution::HostedPluginConnectors { plugin_id, .. } = contribution {
|
||||
labels.push(format!("cloud:{plugin_id}"));
|
||||
} else {
|
||||
panic!("unexpected contribution: {contribution:?}");
|
||||
}
|
||||
}
|
||||
labels
|
||||
}
|
||||
|
||||
fn cloud_plugin(remote_id: &str) -> PluginCatalogEntry {
|
||||
PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: remote_id.to_string(),
|
||||
},
|
||||
display_name: "Example".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command":"node","args":["server.js"]}),
|
||||
)]),
|
||||
connector_ids: vec!["connector_example".to_string()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: format!("plugin://{remote_id}"),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn executor_snapshot(
|
||||
environment_id: &str,
|
||||
) -> anyhow::Result<ExecutorCapabilityDiscoveryV2Snapshot> {
|
||||
let root = PathUri::parse("file:///plugins/example/1.0.0")?;
|
||||
Ok(ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: environment_id.to_string(),
|
||||
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse {
|
||||
plugins: vec![ExecutorPlugin {
|
||||
id: "example@marketplace".to_string(),
|
||||
display_name: "Example".to_string(),
|
||||
remote_plugin_id: Some("plugin_a".to_string()),
|
||||
version: "1.0.0".to_string(),
|
||||
files: DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
path: root.join(".codex-plugin/plugin.json")?,
|
||||
contents: r#"{"name":"example"}"#.to_string(),
|
||||
},
|
||||
mcp_config: None,
|
||||
apps_config: None,
|
||||
},
|
||||
root,
|
||||
skills: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_refresh_retains_entries_without_excluding_new_executor_plugins() -> anyhow::Result<()> {
|
||||
let mut state = PluginContributorState::default();
|
||||
let auth_key = state.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
let original = PluginCatalog {
|
||||
entries: vec![cloud_plugin("old_plugin")],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(state.publish_cloud_catalog(auth_key.as_ref(), original.clone()));
|
||||
assert!(state.publish_cloud_catalog(
|
||||
auth_key.as_ref(),
|
||||
PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
is_partial: true,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
let mut expected = original;
|
||||
expected.is_partial = true;
|
||||
assert_eq!(state.cloud_catalog(), Some(&expected));
|
||||
|
||||
state.update_executor_catalog(&[executor_snapshot("executor-a")?]);
|
||||
let merged =
|
||||
codex_core_plugins::merge_catalogs(state.executor_catalog.as_ref(), state.cloud_catalog());
|
||||
assert!(
|
||||
merged
|
||||
.entries
|
||||
.iter()
|
||||
.any(|entry| { entry.id.as_str() == "plugin_a" && entry.enabled })
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executor_refresh_preserves_order_and_removes_stale_entries() -> anyhow::Result<()> {
|
||||
let mut state = PluginContributorState::default();
|
||||
// Reuse equal snapshots, including equal responses allocated by a later discovery.
|
||||
let b = executor_snapshot("executor-b")?;
|
||||
let c = executor_snapshot("executor-c")?;
|
||||
state.update_executor_catalog(&[b.clone(), c.clone()]);
|
||||
state.update_executor_catalog(&[executor_snapshot("executor-b")?, c.clone()]);
|
||||
assert!(Arc::ptr_eq(
|
||||
state.executor_snapshots[0].result.as_ref().unwrap(),
|
||||
b.result.as_ref().unwrap(),
|
||||
));
|
||||
|
||||
// Keep B ahead of C even when discovery reverses them and adds an earlier-named A.
|
||||
let a = executor_snapshot("executor-a")?;
|
||||
let mut updated_b = b;
|
||||
Arc::make_mut(updated_b.result.as_mut().unwrap()).plugins[0].display_name =
|
||||
"Updated".to_string();
|
||||
state.update_executor_catalog(&[a.clone(), c.clone(), updated_b.clone()]);
|
||||
assert_eq!(
|
||||
state.executor_catalog.as_ref().unwrap(),
|
||||
&catalog_from_snapshots(&[updated_b.clone(), c.clone(), a.clone()]),
|
||||
);
|
||||
// Removing B promotes C; B returning later appends it rather than displacing C.
|
||||
state.update_executor_catalog(&[a.clone(), c.clone()]);
|
||||
state.update_executor_catalog(&[updated_b.clone(), a.clone(), c.clone()]);
|
||||
assert_eq!(
|
||||
state.executor_catalog.as_ref().unwrap(),
|
||||
&catalog_from_snapshots(&[c.clone(), a.clone(), updated_b]),
|
||||
);
|
||||
// A failed scan removes that environment's entries, and recovery rebuilds them.
|
||||
let failed = ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: c.environment_id.clone(),
|
||||
result: Err("discovery failed".to_string()),
|
||||
};
|
||||
state.update_executor_catalog(&[failed.clone(), a.clone()]);
|
||||
assert_eq!(
|
||||
state.executor_catalog.as_ref().unwrap(),
|
||||
&catalog_from_snapshots(&[failed, a.clone()]),
|
||||
);
|
||||
state.update_executor_catalog(&[c.clone(), a.clone()]);
|
||||
assert_eq!(
|
||||
state.executor_catalog.as_ref().unwrap(),
|
||||
&catalog_from_snapshots(&[a, c]),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> anyhow::Result<()> {
|
||||
struct CloudProvider;
|
||||
impl PluginProvider for CloudProvider {}
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let root = home.path().join("legacy");
|
||||
std::fs::create_dir_all(root.join(".codex-plugin"))?;
|
||||
std::fs::write(
|
||||
root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"legacy","mcpServers":{"legacy":{"command":"legacy-command"}}}"#,
|
||||
)?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.fallback_cwd(Some(home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
config.features.enable(Feature::Plugins)?;
|
||||
let environments = Arc::new(EnvironmentManager::default_for_tests());
|
||||
let roots = vec![SelectedCapabilityRoot {
|
||||
id: "legacy-root".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
path: PathUri::from_host_native_path(&root)?,
|
||||
},
|
||||
}];
|
||||
let resolved_roots = environments
|
||||
.resolve_selected_capability_roots(
|
||||
&roots,
|
||||
&std::collections::HashMap::from([(
|
||||
LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
environments.get_environment(LOCAL_ENVIRONMENT_ID),
|
||||
)]),
|
||||
)
|
||||
.await;
|
||||
let v1 = ExecutorCapabilityDiscoveryCache::default()
|
||||
.snapshot(&resolved_roots, &Default::default())
|
||||
.await;
|
||||
let mut contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(environments)))
|
||||
.with_cloud_provider(Arc::new(CloudProvider)),
|
||||
};
|
||||
let thread = ExtensionData::new("projection-test");
|
||||
let init = ExtensionDataInit::default();
|
||||
let state = thread.get_or_init(PluginsThreadState::default);
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
let key = state.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
assert!(state.publish_cloud_catalog(
|
||||
key.as_ref(),
|
||||
PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
..Default::default()
|
||||
}
|
||||
));
|
||||
}
|
||||
// A different environment ensures per-root filtering cannot hide a legacy fallback.
|
||||
let mut valid = [executor_snapshot("executor-a")?];
|
||||
Arc::make_mut(valid[0].result.as_mut().unwrap()).plugins[0]
|
||||
.files
|
||||
.mcp_config = Some(CapabilityTextFile {
|
||||
path: PathUri::parse("file:///plugins/example/1.0.0/.mcp.json")?,
|
||||
contents: r#"{"executor-only":{"command":"node"}}"#.to_string(),
|
||||
});
|
||||
let mut local = [
|
||||
executor_snapshot("executor-a")?,
|
||||
executor_snapshot("executor-b")?,
|
||||
];
|
||||
for snapshot in &mut local {
|
||||
Arc::make_mut(snapshot.result.as_mut().unwrap()).plugins[0].remote_plugin_id = None;
|
||||
}
|
||||
let empty = [ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-a".to_string(),
|
||||
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse::default())),
|
||||
}];
|
||||
let failed = [ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-a".to_string(),
|
||||
result: Err("discovery failed".to_string()),
|
||||
}];
|
||||
for (case, v2_enabled, snapshots, expected) in [
|
||||
(
|
||||
"snapshot selects V2 independently of the acquisition flag",
|
||||
false,
|
||||
Some(valid.as_slice()),
|
||||
vec![
|
||||
"mcp:example",
|
||||
"executor-a:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
],
|
||||
),
|
||||
(
|
||||
"legacy",
|
||||
false,
|
||||
None,
|
||||
vec!["mcp:legacy", "legacy-root", "cloud:plugin_a"],
|
||||
),
|
||||
(
|
||||
"no V2 snapshot",
|
||||
true,
|
||||
None,
|
||||
vec!["mcp:legacy", "legacy-root", "cloud:plugin_a"],
|
||||
),
|
||||
(
|
||||
"empty snapshots",
|
||||
true,
|
||||
Some([].as_slice()),
|
||||
vec!["cloud:plugin_a"],
|
||||
),
|
||||
(
|
||||
"empty inventory",
|
||||
true,
|
||||
Some(empty.as_slice()),
|
||||
vec!["cloud:plugin_a"],
|
||||
),
|
||||
(
|
||||
"failed",
|
||||
true,
|
||||
Some(failed.as_slice()),
|
||||
vec!["cloud:plugin_a"],
|
||||
),
|
||||
(
|
||||
"valid",
|
||||
true,
|
||||
Some(valid.as_slice()),
|
||||
vec![
|
||||
"mcp:example",
|
||||
"executor-a:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
],
|
||||
),
|
||||
(
|
||||
"unconfigured local",
|
||||
true,
|
||||
Some(local.as_slice()),
|
||||
vec![
|
||||
"disabled:example@marketplace",
|
||||
"disabled:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
],
|
||||
),
|
||||
] {
|
||||
config
|
||||
.features
|
||||
.set_enabled(Feature::ExecutorCapabilityDiscoveryV2, v2_enabled)?;
|
||||
for legacy_snapshot in [None, Some(&v1)] {
|
||||
state.contributor_state().update_executor_catalog(&valid);
|
||||
let contributions = contribution_labels(
|
||||
&contributor,
|
||||
McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&init,
|
||||
&thread,
|
||||
"test",
|
||||
&roots,
|
||||
legacy_snapshot,
|
||||
snapshots,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
contributions,
|
||||
expected,
|
||||
"{case}, V2={v2_enabled}, V1={}",
|
||||
legacy_snapshot.is_some()
|
||||
);
|
||||
let expected_catalog = snapshots.map(catalog_from_snapshots);
|
||||
assert_eq!(
|
||||
state.contributor_state().executor_catalog.as_ref(),
|
||||
expected_catalog.as_ref(),
|
||||
"{case}"
|
||||
);
|
||||
}
|
||||
}
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"[plugins.\"example@marketplace\"]\nenabled = true\n",
|
||||
)?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.fallback_cwd(Some(home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
config.features.enable(Feature::Plugins)?;
|
||||
config
|
||||
.features
|
||||
.enable(Feature::ExecutorCapabilityDiscoveryV2)?;
|
||||
|
||||
// Cloud counterparts control enablement without deleting the executor installation.
|
||||
let mut disabled_cloud = cloud_plugin("plugin_a");
|
||||
disabled_cloud.enabled = false;
|
||||
for (case, cloud_enabled, catalog, enabled) in [
|
||||
("no cloud provider", false, None, true),
|
||||
("no cloud catalog", true, None, true),
|
||||
("absent", true, Some(PluginCatalog::default()), false),
|
||||
(
|
||||
"partial absent",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
is_partial: true,
|
||||
warnings: vec!["partial cloud listing".to_string()],
|
||||
..Default::default()
|
||||
}),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"disabled",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
entries: vec![disabled_cloud],
|
||||
..Default::default()
|
||||
}),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"re-enabled",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
..Default::default()
|
||||
}),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"partial counterpart",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
is_partial: true,
|
||||
warnings: vec!["partial cloud listing".to_string()],
|
||||
}),
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let has_cloud_counterpart = catalog
|
||||
.as_ref()
|
||||
.is_some_and(|catalog| !catalog.entries.is_empty());
|
||||
contributor.providers.cloud = if cloud_enabled {
|
||||
Some(Arc::new(CloudProvider))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
{
|
||||
let mut cache = state.contributor_state();
|
||||
cache.cloud_generation = None;
|
||||
let key = cache.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
if let Some(catalog) = catalog {
|
||||
assert!(cache.publish_cloud_catalog(key.as_ref(), catalog));
|
||||
}
|
||||
}
|
||||
let contributions = contribution_labels(
|
||||
&contributor,
|
||||
McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&init,
|
||||
&thread,
|
||||
case,
|
||||
&roots,
|
||||
/*executor_capability_discovery*/ None,
|
||||
Some(&valid),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let expected = if enabled && !has_cloud_counterpart {
|
||||
vec!["mcp:executor-only", "executor-a:example@marketplace"]
|
||||
} else if enabled {
|
||||
vec![
|
||||
"mcp:example",
|
||||
"executor-a:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
]
|
||||
} else {
|
||||
vec!["disabled:example@marketplace"]
|
||||
};
|
||||
assert_eq!(contributions, expected, "{case}");
|
||||
assert_eq!(
|
||||
state.contributor_state().executor_catalog,
|
||||
Some(catalog_from_snapshots(&valid)),
|
||||
"{case}"
|
||||
);
|
||||
}
|
||||
|
||||
// A full Cloud catalog must not crowd out enabled executor-local plugins.
|
||||
let cloud_plugin_count = 100;
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
let key = state.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
let entries = (0..cloud_plugin_count)
|
||||
.map(|index| cloud_plugin(&format!("plugin_{index}")))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(state.publish_cloud_catalog(
|
||||
key.as_ref(),
|
||||
PluginCatalog {
|
||||
entries,
|
||||
..Default::default()
|
||||
}
|
||||
));
|
||||
}
|
||||
let contributions = contribution_labels(
|
||||
&contributor,
|
||||
McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&init,
|
||||
&thread,
|
||||
"merged",
|
||||
&roots,
|
||||
/*executor_capability_discovery*/ None,
|
||||
Some(&local[..1]),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(contributions.len(), cloud_plugin_count + 1);
|
||||
assert_eq!(contributions[0], "executor-a:example@marketplace");
|
||||
for (index, contribution) in contributions[1..].iter().enumerate() {
|
||||
assert_eq!(contribution, &format!("cloud:plugin_{index}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
27
codex-rs/ext/mcp/src/plugin_providers.rs
Normal file
27
codex-rs/ext/mcp/src/plugin_providers.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
//! Host-assembled plugin sources; discovery results belong to the active thread, not this registry.
|
||||
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginProvider;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Cloud discovery is optional and never replaces executor plugin support.
|
||||
pub struct PluginProviders {
|
||||
// CCA owns and supplies the cloud provider implementation.
|
||||
pub(crate) cloud: Option<Arc<dyn PluginProvider>>,
|
||||
// Keep concrete access to resolve_bound so loaders retain the exact executor filesystem.
|
||||
pub(crate) executor: Arc<ExecutorPluginProvider>,
|
||||
}
|
||||
|
||||
impl PluginProviders {
|
||||
pub fn new(executor: Arc<ExecutorPluginProvider>) -> Self {
|
||||
Self {
|
||||
cloud: None,
|
||||
executor,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_cloud_provider(mut self, provider: Arc<dyn PluginProvider>) -> Self {
|
||||
self.cloud = Some(provider);
|
||||
self
|
||||
}
|
||||
}
|
||||
290
codex-rs/ext/mcp/src/stream_manager.rs
Normal file
290
codex-rs/ext/mcp/src/stream_manager.rs
Normal file
@@ -0,0 +1,290 @@
|
||||
//! Owns task-scoped MCP event streams without retaining their thread or runtime.
|
||||
//! Each subscription has one worker, and cancellation never waits for output capacity.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadReadyInput;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_mcp::McpEventNotification;
|
||||
use codex_mcp::McpEventStreamOpener;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_protocol::ThreadId;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::timeout_at;
|
||||
|
||||
const EVENT_UPDATE_CAPACITY: usize = 64;
|
||||
const ACTIVATION_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 90);
|
||||
|
||||
/// A notification or stream ending, identified by task, subscription, and stream attempt.
|
||||
pub enum McpEventStreamUpdate {
|
||||
Notification {
|
||||
thread_id: ThreadId,
|
||||
subscription_id: String,
|
||||
stream_attempt_id: u64,
|
||||
notification: McpEventNotification,
|
||||
},
|
||||
Ended {
|
||||
thread_id: ThreadId,
|
||||
subscription_id: String,
|
||||
stream_attempt_id: u64,
|
||||
result: Result<()>,
|
||||
},
|
||||
}
|
||||
|
||||
struct ManagedEventStream {
|
||||
stream_attempt_id: u64,
|
||||
active: Arc<AtomicBool>,
|
||||
worker: JoinHandle<()>,
|
||||
cancel_event_streams_on_server_removal: watch::Sender<()>,
|
||||
}
|
||||
|
||||
/// Tracks event streams by thread and subscription ID.
|
||||
///
|
||||
/// Notifications and stream endings go into a queue. Cancelling a
|
||||
/// stream does not require adding an `Ended` update, so it still works when the queue is full.
|
||||
pub struct McpEventStreamManager {
|
||||
streams: Mutex<HashMap<(ThreadId, String), ManagedEventStream>>,
|
||||
next_stream_attempt_id: AtomicU64,
|
||||
updates: mpsc::Sender<McpEventStreamUpdate>,
|
||||
shutdown: AtomicBool,
|
||||
}
|
||||
|
||||
impl McpEventStreamManager {
|
||||
pub fn new() -> (Self, mpsc::Receiver<McpEventStreamUpdate>) {
|
||||
let (updates, receiver) = mpsc::channel(EVENT_UPDATE_CAPACITY);
|
||||
(
|
||||
Self {
|
||||
streams: Mutex::default(),
|
||||
next_stream_attempt_id: AtomicU64::new(/*v*/ 1),
|
||||
updates,
|
||||
shutdown: AtomicBool::new(/*v*/ false),
|
||||
},
|
||||
receiver,
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens a stream and returns its attempt ID after the server confirms activation.
|
||||
pub async fn start(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
subscription_id: String,
|
||||
opener: McpEventStreamOpener,
|
||||
event_name: String,
|
||||
arguments: Value,
|
||||
request_meta: Option<Map<String, Value>>,
|
||||
) -> Result<u64> {
|
||||
let key = (thread_id, subscription_id.clone());
|
||||
let (ready_tx, ready_rx) = oneshot::channel();
|
||||
{
|
||||
let mut streams = self.streams.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if self.shutdown.load(Ordering::Acquire) {
|
||||
return Err(anyhow!("MCP event stream manager is shut down"));
|
||||
}
|
||||
streams.retain(|_, stream| !stream.worker.is_finished());
|
||||
if let Some(stream) = streams.get(&key) {
|
||||
if stream.active.load(Ordering::Acquire) {
|
||||
return Ok(stream.stream_attempt_id);
|
||||
}
|
||||
return Err(anyhow!(
|
||||
"MCP event subscription is already starting or finishing"
|
||||
));
|
||||
}
|
||||
|
||||
let stream_attempt_id = self
|
||||
.next_stream_attempt_id
|
||||
.fetch_add(/*val*/ 1, Ordering::Relaxed);
|
||||
let active = Arc::new(AtomicBool::new(/*v*/ false));
|
||||
let worker_active = Arc::clone(&active);
|
||||
let cancel_event_streams_on_server_removal = opener.event_stream_cancellation_sender();
|
||||
let updates = self.updates.clone();
|
||||
let deadline = Instant::now() + ACTIVATION_TIMEOUT;
|
||||
// Keep the stream running if the caller stops waiting for activation.
|
||||
let worker = tokio::spawn(async move {
|
||||
let mut ready = Some(ready_tx);
|
||||
let forward = async {
|
||||
let mut stream = timeout_at(
|
||||
deadline,
|
||||
opener.open(&event_name, &arguments, request_meta.as_ref()),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream activation timed out"))??;
|
||||
|
||||
loop {
|
||||
let notification = if ready.is_some() {
|
||||
timeout_at(deadline, stream.recv())
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream activation timed out"))??
|
||||
} else {
|
||||
stream.recv().await?
|
||||
};
|
||||
let Some(notification) = notification else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let activates = notification.method == "notifications/events/active";
|
||||
let terminates = notification.method == "notifications/events/terminated";
|
||||
if activates {
|
||||
worker_active.store(/*val*/ true, Ordering::Release);
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Ok(stream_attempt_id));
|
||||
}
|
||||
}
|
||||
|
||||
let send = updates.send(McpEventStreamUpdate::Notification {
|
||||
thread_id,
|
||||
subscription_id: subscription_id.clone(),
|
||||
stream_attempt_id,
|
||||
notification,
|
||||
});
|
||||
let sent = if ready.is_some() {
|
||||
timeout_at(deadline, send)
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream activation timed out"))?
|
||||
} else {
|
||||
send.await
|
||||
};
|
||||
sent.map_err(|_| anyhow!("MCP event stream receiver was dropped"))?;
|
||||
|
||||
if terminates {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = opener.wait_for_access_change() => {
|
||||
Err(anyhow!("MCP event stream access changed"))
|
||||
}
|
||||
() = updates.closed() => {
|
||||
Err(anyhow!("MCP event stream receiver was dropped"))
|
||||
}
|
||||
result = forward => result,
|
||||
};
|
||||
|
||||
worker_active.store(/*val*/ false, Ordering::Release);
|
||||
drop(opener);
|
||||
if let Some(ready) = ready {
|
||||
let error = match &result {
|
||||
Ok(()) => anyhow!("MCP event stream ended before becoming active"),
|
||||
Err(error) => anyhow!("{error:#}"),
|
||||
};
|
||||
let _ = ready.send(Err(error));
|
||||
}
|
||||
|
||||
let _ = updates
|
||||
.send(McpEventStreamUpdate::Ended {
|
||||
thread_id,
|
||||
subscription_id,
|
||||
stream_attempt_id,
|
||||
result,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
streams.insert(
|
||||
key,
|
||||
ManagedEventStream {
|
||||
stream_attempt_id,
|
||||
active,
|
||||
worker,
|
||||
cancel_event_streams_on_server_removal,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
ready_rx
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream ended before becoming active"))?
|
||||
}
|
||||
|
||||
/// Await cancellation before starting the same subscription again.
|
||||
pub async fn cancel(&self, thread_id: ThreadId, subscription_id: &str) {
|
||||
let stream = self
|
||||
.streams
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&(thread_id, subscription_id.to_owned()));
|
||||
if let Some(stream) = stream {
|
||||
stream.worker.abort();
|
||||
let _ = stream.worker.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Permanently rejects new starts and waits for all current workers to release their streams.
|
||||
pub async fn shutdown(&self) {
|
||||
self.shutdown.store(/*val*/ true, Ordering::Release);
|
||||
let streams = self
|
||||
.streams
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.drain()
|
||||
.map(|(_, stream)| stream)
|
||||
.collect::<Vec<_>>();
|
||||
for stream in &streams {
|
||||
stream.worker.abort();
|
||||
}
|
||||
for stream in streams {
|
||||
let _ = stream.worker.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Sync> ThreadLifecycleContributor<C> for McpEventStreamManager {
|
||||
fn on_thread_start<'a>(&'a self, input: ThreadStartInput<'a, C>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
if let Some(client) = input.mcp_resource_client {
|
||||
input.thread_store.insert(client.as_ref().clone());
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_thread_ready<'a>(&'a self, input: ThreadReadyInput<'a, C>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(client) = input.thread_store.get::<McpResourceClient>() else {
|
||||
return;
|
||||
};
|
||||
let Ok(thread_id) = ThreadId::from_string(input.thread_store.level_id()) else {
|
||||
return;
|
||||
};
|
||||
let cancellation = self
|
||||
.streams
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.iter()
|
||||
.find(|((owner, _), stream)| {
|
||||
let belongs_to_task = *owner == thread_id;
|
||||
let worker_is_running = !stream.worker.is_finished();
|
||||
belongs_to_task && worker_is_running
|
||||
})
|
||||
.map(|(_, stream)| stream.cancel_event_streams_on_server_removal.clone());
|
||||
if let Some(cancellation) = cancellation {
|
||||
client.forward_event_server_removals_to(cancellation);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for McpEventStreamManager {
|
||||
fn drop(&mut self) {
|
||||
let mut streams = self.streams.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for (_, stream) in streams.drain() {
|
||||
stream.worker.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
357
codex-rs/ext/mcp/src/stream_manager_tests.rs
Normal file
357
codex-rs/ext/mcp/src/stream_manager_tests.rs
Normal file
@@ -0,0 +1,357 @@
|
||||
//! Exercises stream activation, task ownership, and cancellation.
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadReadyInput;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_mcp::McpEventStreamOpener;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::event_stream_tests::Fixture;
|
||||
use super::event_stream_tests::StaticAuth;
|
||||
use super::event_stream_tests::WAIT;
|
||||
use crate::McpEventStreamManager;
|
||||
use crate::McpEventStreamUpdate;
|
||||
|
||||
async fn start_subscription(
|
||||
manager: &McpEventStreamManager,
|
||||
opener: &McpEventStreamOpener,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<u64> {
|
||||
manager
|
||||
.start(
|
||||
thread_id,
|
||||
"sub".into(),
|
||||
opener.clone(),
|
||||
"test.event".into(),
|
||||
json!({}),
|
||||
/*request_meta*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn connect_loaded_task(
|
||||
manager: &McpEventStreamManager,
|
||||
thread_id: ThreadId,
|
||||
client: Arc<McpResourceClient>,
|
||||
) {
|
||||
let session_store = ExtensionData::new("test");
|
||||
let thread_store = ExtensionData::new(thread_id.to_string());
|
||||
manager
|
||||
.on_thread_start(ThreadStartInput {
|
||||
config: &(),
|
||||
session_source: &SessionSource::Exec,
|
||||
persistent_thread_state_available: false,
|
||||
environments: &[],
|
||||
mcp_resource_client: Some(client),
|
||||
extension_metrics: None,
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
})
|
||||
.await;
|
||||
manager
|
||||
.on_thread_ready(ThreadReadyInput {
|
||||
config: &(),
|
||||
session_source: &SessionSource::Exec,
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reloaded_tasks_can_cancel_surviving_streams() -> Result<()> {
|
||||
for removed_before_ready in [false, true] {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let (result, stream) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
result?;
|
||||
timeout(WAIT, updates.recv()).await?.unwrap();
|
||||
fixture.runtime.shutdown().await;
|
||||
drop(fixture.runtime);
|
||||
|
||||
let mut replacement = Fixture::new().await?;
|
||||
let client = Arc::new(McpResourceClient::new(Arc::clone(&replacement.runtime)));
|
||||
replacement.runtime_input.mcp_servers.clear();
|
||||
if removed_before_ready {
|
||||
replacement.runtime.replace(replacement.runtime_input).await;
|
||||
connect_loaded_task(&manager, thread_id, client).await;
|
||||
} else {
|
||||
connect_loaded_task(&manager, thread_id, client).await;
|
||||
let expected = stream.notify("notifications/events/event");
|
||||
let McpEventStreamUpdate::Notification { notification, .. } =
|
||||
timeout(WAIT, updates.recv()).await?.unwrap()
|
||||
else {
|
||||
panic!("event expected after task reload");
|
||||
};
|
||||
assert_eq!(notification, expected);
|
||||
replacement.runtime.replace(replacement.runtime_input).await;
|
||||
}
|
||||
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
let McpEventStreamUpdate::Ended { result, .. } =
|
||||
timeout(WAIT, updates.recv()).await?.unwrap()
|
||||
else {
|
||||
panic!("stream should end after the event server is removed");
|
||||
};
|
||||
assert!(result.is_err());
|
||||
manager.shutdown().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn streams_outlive_tasks_and_activate_with_full_output() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let first_thread = ThreadId::new();
|
||||
let second_thread = ThreadId::new();
|
||||
let mut streams = Vec::new();
|
||||
for thread_id in [first_thread, second_thread] {
|
||||
let start = manager.start(
|
||||
thread_id,
|
||||
"sub".into(),
|
||||
opener.clone(),
|
||||
"test.event".into(),
|
||||
json!({"resource_id": "resource-123"}),
|
||||
Some(serde_json::Map::from_iter([(
|
||||
"saved_id".into(),
|
||||
json!("sub"),
|
||||
)])),
|
||||
);
|
||||
tokio::pin!(start);
|
||||
let stream = tokio::select! {
|
||||
result = &mut start => panic!("start returned before activation: {result:?}"),
|
||||
stream = timeout(WAIT, fixture.opened.recv()) => stream?.unwrap(),
|
||||
};
|
||||
let mut params = stream.request["params"].clone();
|
||||
params["_meta"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("progressToken");
|
||||
assert_eq!(
|
||||
params,
|
||||
json!({"name": "test.event", "arguments": {"resource_id": "resource-123"}, "_meta": {"saved_id": "sub"}})
|
||||
);
|
||||
stream.notify("notifications/events/active");
|
||||
timeout(WAIT, start).await??;
|
||||
timeout(WAIT, updates.recv()).await?.unwrap();
|
||||
streams.push(stream);
|
||||
}
|
||||
start_subscription(&manager, &opener, first_thread).await?;
|
||||
assert!(fixture.opened.try_recv().is_err());
|
||||
|
||||
fixture.runtime.shutdown().await;
|
||||
let expected = streams[1].notify("notifications/events/event");
|
||||
let McpEventStreamUpdate::Notification {
|
||||
thread_id,
|
||||
subscription_id,
|
||||
notification,
|
||||
..
|
||||
} = timeout(WAIT, updates.recv()).await?.unwrap()
|
||||
else {
|
||||
panic!("event expected");
|
||||
};
|
||||
assert_eq!(
|
||||
(thread_id, subscription_id, notification),
|
||||
(second_thread, "sub".into(), expected)
|
||||
);
|
||||
for _ in 0..=updates.max_capacity() {
|
||||
streams[0].notify("notifications/events/event");
|
||||
}
|
||||
timeout(WAIT, async {
|
||||
while updates.capacity() != 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let third_thread = ThreadId::new();
|
||||
let (started, stream) = tokio::join!(
|
||||
timeout(WAIT, start_subscription(&manager, &opener, third_thread)),
|
||||
async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
}
|
||||
);
|
||||
started??;
|
||||
assert_eq!(updates.capacity(), 0);
|
||||
manager.cancel(third_thread, "sub").await;
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
|
||||
manager.cancel(first_thread, "sub").await;
|
||||
timeout(WAIT, streams[0].notifications.closed()).await?;
|
||||
manager.shutdown().await;
|
||||
timeout(WAIT, streams[1].notifications.closed()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_updates_keep_their_stream_attempt_after_replacement() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let (first_attempt, stream) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
let first_attempt = first_attempt?;
|
||||
assert_eq!(
|
||||
start_subscription(&manager, &opener, thread_id).await?,
|
||||
first_attempt
|
||||
);
|
||||
|
||||
stream.notify("notifications/events/terminated");
|
||||
// Leave activation, termination, and the ending queued while opening a replacement.
|
||||
timeout(WAIT, async {
|
||||
while updates.len() < 3 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
manager.cancel(thread_id, "sub").await;
|
||||
|
||||
let (second_attempt, replacement) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
let second_attempt = second_attempt?;
|
||||
assert_ne!(first_attempt, second_attempt);
|
||||
|
||||
let mut queued_attempts = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let stream_attempt_id = match timeout(WAIT, updates.recv()).await?.unwrap() {
|
||||
McpEventStreamUpdate::Notification {
|
||||
stream_attempt_id, ..
|
||||
} => stream_attempt_id,
|
||||
McpEventStreamUpdate::Ended {
|
||||
stream_attempt_id,
|
||||
result,
|
||||
..
|
||||
} => {
|
||||
result?;
|
||||
assert_eq!(stream_attempt_id, first_attempt);
|
||||
stream_attempt_id
|
||||
}
|
||||
};
|
||||
queued_attempts.push(stream_attempt_id);
|
||||
}
|
||||
assert_eq!(
|
||||
queued_attempts,
|
||||
vec![first_attempt, first_attempt, first_attempt, second_attempt]
|
||||
);
|
||||
manager.shutdown().await;
|
||||
timeout(WAIT, replacement.notifications.closed()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_before_activation_releases_the_subscription_id() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, _updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let start = start_subscription(&manager, &opener, thread_id);
|
||||
tokio::pin!(start);
|
||||
let stream = tokio::select! {
|
||||
result = &mut start => panic!("start returned before activation: {result:?}"),
|
||||
stream = timeout(WAIT, fixture.opened.recv()) => stream?.unwrap(),
|
||||
};
|
||||
manager.cancel(thread_id, "sub").await;
|
||||
assert!(timeout(WAIT, start).await?.is_err());
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
let (result, replacement) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
result?;
|
||||
manager.shutdown().await;
|
||||
timeout(WAIT, replacement.notifications.closed()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn access_changes_cancel_streams_with_full_output() -> Result<()> {
|
||||
for remove_server in [false, true] {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let (result, stream) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
result?;
|
||||
timeout(WAIT, updates.recv()).await?.unwrap();
|
||||
for _ in 0..=updates.max_capacity() {
|
||||
stream.notify("notifications/events/event");
|
||||
}
|
||||
timeout(WAIT, async {
|
||||
while updates.capacity() != 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
if remove_server {
|
||||
fixture.runtime_input.mcp_servers.clear();
|
||||
fixture.runtime.replace(fixture.runtime_input).await;
|
||||
} else {
|
||||
fixture
|
||||
.auth
|
||||
.set_external_auth(Arc::new(StaticAuth(
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.other",
|
||||
"other-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
)))
|
||||
.await?;
|
||||
}
|
||||
// Access changes close the stream even while its output is blocked.
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
let result = timeout(WAIT, async {
|
||||
loop {
|
||||
if let McpEventStreamUpdate::Ended { result, .. } = updates.recv().await.unwrap() {
|
||||
break result;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
opener
|
||||
.open("test.event", &json!({}), /*request_meta*/ None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user