aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,20 @@
//! Measures published cloud and V2 executor plugin catalogs, excluding cached reads.
use akode_core_plugins::PluginCatalog;
use akode_extension_api::ExtensionMetrics;
use akode_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(),
);
}

View File

@@ -0,0 +1,17 @@
mod catalog_observability;
mod plugin;
mod plugin_contributor;
mod plugin_contributor_state;
mod plugin_lifecycle;
mod plugin_providers;
pub use akode_core_plugins::PluginListQuery;
pub use akode_core_plugins::PluginProvider;
pub use akode_core_plugins::PluginProviderError;
pub use akode_core_plugins::PluginProviderFuture;
pub use akode_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;

View File

@@ -0,0 +1,394 @@
use akode_config::types::PluginsConfigToml;
use akode_core::config::Config;
use akode_core_plugins::ExecutorPluginProviderError;
use akode_core_plugins::PluginIdentity;
use akode_core_plugins::PluginRootOwnership;
use akode_core_plugins::PluginSourceLocation;
use akode_core_plugins::configured_plugins_from_stack;
use akode_core_plugins::loader::apply_configured_plugin_mcp_server_policies;
use akode_core_plugins::merge_catalogs;
use akode_exec_server::CapabilityRootDiscovery;
use akode_exec_server::FileSystemSandboxContext;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::McpServerContribution;
use akode_extension_api::McpServerContributionContext;
use akode_extension_api::McpServerContributor;
use akode_extension_api::SelectedPlugin;
use akode_extension_api::SelectedPluginContribution;
use akode_features::Feature;
use akode_protocol::capabilities::CapabilityRootLocation;
use akode_protocol::capabilities::SelectedCapabilityRoot;
use std::collections::HashMap;
use self::provider::PluginMcpProvider;
use crate::PluginsThreadState;
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) => {
// ChatGPT app declarations are ignored in aKode; only MCP servers load.
let servers = PluginMcpProvider.load(&plugin).await.unwrap_or_else(|err| {
tracing::warn!(
selected_root = selected_root.id,
error = %err,
"failed to load selected plugin MCP servers"
);
Vec::new()
});
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,
})
}
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 { Vec::new() })
}
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);
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);
merge_catalogs(cache.executor_catalog.as_ref(), /*cloud*/ None)
};
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,
};
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(),
};
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 }
}

View File

@@ -0,0 +1,186 @@
/// Bounds the plugin display name projected into MCP tool attribution.
const MAX_PLUGIN_DISPLAY_NAME_CHARS: usize = 64;
use crate::plugin_contributor_state::SelectedPluginMetadata;
use akode_core_plugins::PluginCatalogEntry;
use akode_core_plugins::PluginSourceLocation;
use akode_core_plugins::manifest::UriPluginManifest;
use akode_core_plugins::manifest::parse_plugin_manifest_uri;
use akode_exec_server::CapabilityRootDiscovery;
use akode_exec_server::DiscoveredPluginFiles;
use akode_extension_api::SelectedPluginContribution;
use akode_mcp::PluginMcpConfigParseOutcome;
use akode_mcp::normalize_executor_plugin_mcp_declarations;
use akode_mcp::parse_executor_plugin_mcp_config;
use akode_plugin::manifest::PluginManifestMcpServers;
use akode_protocol::capabilities::CapabilityRootLocation;
use akode_protocol::capabilities::SelectedCapabilityRoot;
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(),
};
SelectedPluginContribution {
plugin_display_name: manifest.display_name().to_string(),
source_environment_id: environment_id.clone(),
servers,
}
}
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 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,
};
projections.push((root_id, metadata));
}
projections
}
fn parse_mcp_servers(
selected_root: &SelectedCapabilityRoot,
plugin_root: &akode_utils_path_uri::PathUri,
contents: &str,
environment_id: &str,
) -> Vec<(String, akode_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, akode_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;

View File

@@ -0,0 +1,111 @@
//! Verifies merged MCPs use the first retained installation while preserving all package identities.
use super::*;
use akode_config::McpServerTransportConfig;
use akode_config::types::PluginsConfigToml;
use akode_core::config::ConfigBuilder;
use akode_core_plugins::PluginIdentity;
use akode_extension_api::SelectedPluginContribution;
use akode_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"}),
)]),
locations: vec![PluginSourceLocation::Cloud {
resource_uri: "plugin://plugin_example".to_string(),
bundle_uri: None,
}],
};
// Cloud locations no longer project hosted metadata.
let projections = v2_metadata_from_catalog(&entry);
assert!(projections.is_empty());
// 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());
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(),
},
);
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(akode_utils_path_uri::LegacyAppPathString::as_str),
Some(format!("{root}/mcp").as_str())
);
}
// Bound projected metadata without mutating the source catalog or losing installations.
entry.display_name = "界".repeat(MAX_PLUGIN_DISPLAY_NAME_CHARS + 1);
entry.mcp_servers.clear();
let projections = v2_metadata_from_catalog(&entry);
assert_eq!(projections.len(), installations.len());
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!(
entry.display_name.chars().count(),
MAX_PLUGIN_DISPLAY_NAME_CHARS + 1
);
Ok(())
}

View File

@@ -0,0 +1,144 @@
use akode_config::McpServerConfig;
use akode_core_plugins::ResolvedExecutorPlugin;
use akode_exec_server::ExecutorFileSystem;
use akode_exec_server::ReadFileOptions;
use akode_mcp::parse_executor_plugin_mcp_config;
use akode_plugin::PluginResourceLocator;
use akode_plugin::ResolvedPlugin;
use akode_plugin::ResolvedPluginLocation;
use akode_plugin::manifest::PluginManifestMcpServers;
use akode_utils_path_uri::PathUri;
use akode_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;

View File

@@ -0,0 +1,448 @@
use super::DEFAULT_MCP_CONFIG_FILE;
use super::PluginMcpProviderError;
use super::load_from_file_system;
use akode_config::McpServerConfig;
use akode_config::McpServerTransportConfig;
use akode_exec_server::CopyOptions;
use akode_exec_server::CreateDirectoryOptions;
use akode_exec_server::ExecutorFileSystem;
use akode_exec_server::ExecutorFileSystemFuture;
use akode_exec_server::FileMetadata;
use akode_exec_server::FileSystemReadStream;
use akode_exec_server::FileSystemResult;
use akode_exec_server::FileSystemSandboxContext;
use akode_exec_server::GetMetadataOptions;
use akode_exec_server::ReadDirectoryEntry;
use akode_exec_server::ReadFileOptions;
use akode_exec_server::RemoveOptions;
use akode_exec_server::WalkOptions;
use akode_exec_server::WalkOutcome;
use akode_exec_server::WriteFileOptions;
use akode_plugin::ResolvedPlugin;
use akode_plugin::manifest::PluginManifest;
use akode_plugin::manifest::PluginManifestMcpServers;
use akode_plugin::manifest::PluginManifestPaths;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::LegacyAppPathString;
use akode_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,
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()
}

View File

@@ -0,0 +1,37 @@
//! Coordinates executor MCP contributions with thread-owned catalogs.
//!
//! Provider instances are shared, while catalogs and executor metadata live in thread extension
//! data.
use crate::PluginProviders;
use akode_core::config::Config;
use akode_core_plugins::ExecutorPluginProvider;
use akode_exec_server::EnvironmentManager;
use akode_extension_api::ExtensionRegistryBuilder;
use std::sync::Arc;
pub(crate) struct PluginContributor {
pub(crate) providers: PluginProviders,
}
/// Installs one coordinator for executor MCP callbacks; Core's plugin policy applies to it.
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.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))),
);
}

View File

@@ -0,0 +1,101 @@
//! Thread-owned executor plugin catalog and stable selected-root metadata, guarded by a short-lived mutex.
use crate::catalog_observability::record_catalog;
use akode_core_plugins::PluginCatalog;
use akode_core_plugins::PluginRootOwnership;
use akode_core_plugins::catalog_from_snapshots;
use akode_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
use akode_exec_server::FileSystemSandboxContext;
use akode_extension_api::ExtensionMetrics;
use akode_extension_api::SelectedPluginContribution;
use akode_protocol::capabilities::SelectedCapabilityRoot;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
/// Plugin configuration and caches owned by one thread; mutable state stays extension-private.
#[derive(Default)]
pub struct PluginsThreadState {
state: Mutex<PluginContributorState>,
}
impl PluginsThreadState {
/// Locks the thread's contributor state, recovering it if a holder panicked.
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) executor_catalog: Option<PluginCatalog>,
executor_snapshots: Vec<ExecutorCapabilityDiscoveryV2Snapshot>,
pub(crate) executor_cache: Vec<CachedSelectedRoot>,
}
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();
}
}
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, akode_config::McpServerConfig)>,
}
#[cfg(test)]
#[path = "plugin_contributor_state_tests.rs"]
mod tests;

View File

@@ -0,0 +1,309 @@
//! Tests thread-owned discovery caching, installation ordering, and contribution projection.
use super::*;
use crate::PluginProviders;
use crate::plugin_contributor::PluginContributor;
use akode_core::config::ConfigBuilder;
use akode_core_plugins::ExecutorPluginProvider;
use akode_exec_server::CapabilityTextFile;
use akode_exec_server::DiscoverV2CapabilitiesResponse;
use akode_exec_server::DiscoveredPluginFiles;
use akode_exec_server::EnvironmentManager;
use akode_exec_server::ExecutorCapabilityDiscoveryCache;
use akode_exec_server::ExecutorPlugin;
use akode_exec_server::LOCAL_ENVIRONMENT_ID;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionDataInit;
use akode_extension_api::McpServerContributionContext;
use akode_extension_api::McpServerContributor;
use akode_features::Feature;
use akode_protocol::capabilities::CapabilityRootLocation;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::sync::Arc;
async fn contribution_labels(
contributor: &PluginContributor,
context: McpServerContributionContext<'_, akode_core::config::Config>,
) -> Vec<String> {
let mut labels = Vec::new();
let policy = akode_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);
}
// Plugins no longer contribute hosted servers outside their selected roots.
assert!(contributor.contribute(context).await.is_empty());
labels
}
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(),
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 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<()> {
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 contributor = PluginContributor {
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(environments))),
};
let thread = ExtensionData::new("projection-test");
let init = ExtensionDataInit::default();
let state = thread.get_or_init(PluginsThreadState::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 local = [
executor_snapshot("executor-a")?,
executor_snapshot("executor-b")?,
];
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!["disabled:example@marketplace"],
),
("legacy", false, None, vec!["mcp:legacy", "legacy-root"]),
(
"no V2 snapshot",
true,
None,
vec!["mcp:legacy", "legacy-root"],
),
(
"empty snapshots",
true,
Some([].as_slice()),
Vec::<&str>::new(),
),
(
"empty inventory",
true,
Some(empty.as_slice()),
Vec::<&str>::new(),
),
("failed", true, Some(failed.as_slice()), Vec::<&str>::new()),
(
"valid",
true,
Some(valid.as_slice()),
vec!["disabled:example@marketplace"],
),
(
"unconfigured local",
true,
Some(local.as_slice()),
vec![
"disabled:example@marketplace",
"disabled:example@marketplace",
],
),
] {
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)?;
// Executor installations are local and enabled by configuration alone.
for (case, snapshots, expected) in [
(
"configured",
&valid[..],
vec!["mcp:executor-only", "executor-a:example@marketplace"],
),
(
"configured without MCP config",
&local[..1],
vec!["executor-a:example@marketplace"],
),
] {
let contributions = contribution_labels(
&contributor,
McpServerContributionContext::for_step(
&config,
&init,
&thread,
case,
&roots,
/*executor_capability_discovery*/ None,
Some(snapshots),
),
)
.await;
assert_eq!(contributions, expected, "{case}");
assert_eq!(
state.contributor_state().executor_catalog,
Some(catalog_from_snapshots(snapshots)),
"{case}"
);
}
Ok(())
}

View File

@@ -0,0 +1,43 @@
//! Tracks plugin enablement and shares the thread's MCP resource client.
use crate::PluginsThreadState;
use crate::plugin_contributor::PluginContributor;
use akode_core::config::Config;
use akode_extension_api::ConfigContributor;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::ThreadLifecycleContributor;
use akode_extension_api::ThreadStartInput;
use akode_features::Feature;
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 state = thread_store.get_or_init(PluginsThreadState::default);
state.contributor_state().plugins_enabled = new_config.features.enabled(Feature::Plugins);
}
}

View File

@@ -0,0 +1,16 @@
//! Host-assembled plugin sources; discovery results belong to the active thread, not this registry.
use akode_core_plugins::ExecutorPluginProvider;
use std::sync::Arc;
/// Plugin providers available to a host.
pub struct PluginProviders {
// 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 { executor }
}
}