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:
6
akode-rs/ext/mcp/BUILD.bazel
Normal file
6
akode-rs/ext/mcp/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "mcp",
|
||||
crate_name = "akode_mcp_extension",
|
||||
)
|
||||
43
akode-rs/ext/mcp/Cargo.toml
Normal file
43
akode-rs/ext/mcp/Cargo.toml
Normal file
@@ -0,0 +1,43 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-mcp-extension"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "akode_mcp_extension"
|
||||
path = "src/lib.rs"
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
akode-core = { workspace = true }
|
||||
akode-core-plugins = { workspace = true }
|
||||
akode-config = { workspace = true }
|
||||
akode-exec-server = { workspace = true }
|
||||
akode-extension-api = { workspace = true }
|
||||
akode-features = { workspace = true }
|
||||
akode-mcp = { workspace = true }
|
||||
akode-plugin = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
akode-utils-path-uri = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tokio = { workspace = true, features = ["sync"] }
|
||||
|
||||
[dev-dependencies]
|
||||
core_test_support = { workspace = true }
|
||||
axum = { workspace = true }
|
||||
akode-exec-server-test-support = { workspace = true }
|
||||
akode-login = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util"] }
|
||||
tokio-util = { workspace = true, features = ["rt"] }
|
||||
wiremock = { workspace = true }
|
||||
20
akode-rs/ext/mcp/src/catalog_observability.rs
Normal file
20
akode-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 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(),
|
||||
);
|
||||
}
|
||||
17
akode-rs/ext/mcp/src/lib.rs
Normal file
17
akode-rs/ext/mcp/src/lib.rs
Normal 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;
|
||||
|
||||
394
akode-rs/ext/mcp/src/plugin.rs
Normal file
394
akode-rs/ext/mcp/src/plugin.rs
Normal 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 }
|
||||
}
|
||||
186
akode-rs/ext/mcp/src/plugin/discovery.rs
Normal file
186
akode-rs/ext/mcp/src/plugin/discovery.rs
Normal 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;
|
||||
111
akode-rs/ext/mcp/src/plugin/discovery_tests.rs
Normal file
111
akode-rs/ext/mcp/src/plugin/discovery_tests.rs
Normal 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(())
|
||||
}
|
||||
144
akode-rs/ext/mcp/src/plugin/provider.rs
Normal file
144
akode-rs/ext/mcp/src/plugin/provider.rs
Normal 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;
|
||||
448
akode-rs/ext/mcp/src/plugin/provider_tests.rs
Normal file
448
akode-rs/ext/mcp/src/plugin/provider_tests.rs
Normal 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()
|
||||
}
|
||||
37
akode-rs/ext/mcp/src/plugin_contributor.rs
Normal file
37
akode-rs/ext/mcp/src/plugin_contributor.rs
Normal 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))),
|
||||
);
|
||||
}
|
||||
101
akode-rs/ext/mcp/src/plugin_contributor_state.rs
Normal file
101
akode-rs/ext/mcp/src/plugin_contributor_state.rs
Normal 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;
|
||||
309
akode-rs/ext/mcp/src/plugin_contributor_state_tests.rs
Normal file
309
akode-rs/ext/mcp/src/plugin_contributor_state_tests.rs
Normal 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(())
|
||||
}
|
||||
43
akode-rs/ext/mcp/src/plugin_lifecycle.rs
Normal file
43
akode-rs/ext/mcp/src/plugin_lifecycle.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
16
akode-rs/ext/mcp/src/plugin_providers.rs
Normal file
16
akode-rs/ext/mcp/src/plugin_providers.rs
Normal 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 }
|
||||
}
|
||||
}
|
||||
848
akode-rs/ext/mcp/tests/plugin_mcp.rs
Normal file
848
akode-rs/ext/mcp/tests/plugin_mcp.rs
Normal file
@@ -0,0 +1,848 @@
|
||||
use anyhow::Context;
|
||||
use akode_config::AppToolApproval;
|
||||
use akode_config::McpServerToolConfig;
|
||||
use akode_config::test_support::ManagedConfigFixture;
|
||||
use akode_core::EnvironmentConfig;
|
||||
use akode_core::config::Config;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use akode_core::windows_sandbox::WindowsSandboxLevelExt;
|
||||
use akode_core_plugins::ExecutorPluginProvider;
|
||||
use akode_exec_server::CapabilityRootDiscovery;
|
||||
use akode_exec_server::EnvironmentManager;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoveryCache;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoverySnapshot;
|
||||
use akode_exec_server::FileSystemSandboxContext;
|
||||
use akode_exec_server::LOCAL_ENVIRONMENT_ID;
|
||||
use akode_extension_api::ExtensionData;
|
||||
use akode_extension_api::ExtensionDataInit;
|
||||
use akode_extension_api::ExtensionRegistryBuilder;
|
||||
use akode_extension_api::McpServerContributionContext;
|
||||
use akode_extension_api::SelectedPluginContribution;
|
||||
use akode_features::Feature;
|
||||
use akode_login::CodexAuth;
|
||||
use akode_mcp_extension::PluginProviders;
|
||||
use akode_mcp_extension::install_plugin_providers;
|
||||
use akode_protocol::capabilities::CapabilityRootLocation;
|
||||
use akode_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use akode_protocol::config_types::WindowsSandboxLevel;
|
||||
use akode_protocol::models::PermissionProfileSnapshot;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use core_test_support::mcp_test_server::McpTestServer;
|
||||
use core_test_support::mcp_test_server::recorded_mcp_tool_calls;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
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::responses::start_mock_server;
|
||||
use core_test_support::skip_if_no_network;
|
||||
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::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
|
||||
type TestResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct ContributionSummary {
|
||||
name: String,
|
||||
plugin_id: String,
|
||||
plugin_display_name: String,
|
||||
source_environment_id: String,
|
||||
selection_order: usize,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct PackageSummary {
|
||||
plugin_id: String,
|
||||
plugin_display_name: String,
|
||||
source_environment_id: String,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selected_plugin_servers_use_managed_requirements_for_the_selected_root_id() -> TestResult {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let plugin_root = tempfile::tempdir()?;
|
||||
std::fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?;
|
||||
std::fs::write(
|
||||
plugin_root.path().join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"different-manifest-name","interface":{"displayName":"Selected Demo"}}"#,
|
||||
)?;
|
||||
std::fs::write(
|
||||
plugin_root.path().join(".mcp.json"),
|
||||
r#"{
|
||||
"mcpServers": {
|
||||
"allowed": {"command":"allowed-command"},
|
||||
"mismatched": {"command":"wrong-command"},
|
||||
"unlisted": {"command":"unlisted-command"}
|
||||
}
|
||||
}"#,
|
||||
)?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
"[plugins.\"selected-root\".mcp_servers.mismatched]\nenabled = true\n[plugins.\"selected-root\".mcp_servers.unlisted]\nenabled = true",
|
||||
)?;
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.loader_overrides(
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"
|
||||
[plugins."selected-root".mcp_servers.allowed.identity]
|
||||
command = "allowed-command"
|
||||
|
||||
[plugins."selected-root".mcp_servers.mismatched.identity]
|
||||
command = "expected-command"
|
||||
"#,
|
||||
))
|
||||
.loader_overrides_for_tests(codex_home.path())
|
||||
.expect("write managed config fixture"),
|
||||
)
|
||||
.build()
|
||||
.await?;
|
||||
|
||||
let contributions = selected_plugin_contributions(&config, plugin_root.path()).await?;
|
||||
|
||||
assert_eq!(
|
||||
contributions,
|
||||
vec![
|
||||
ContributionSummary {
|
||||
name: "allowed".to_string(),
|
||||
plugin_id: "selected-root".to_string(),
|
||||
plugin_display_name: "Selected Demo".to_string(),
|
||||
source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
selection_order: 0,
|
||||
enabled: true,
|
||||
},
|
||||
ContributionSummary {
|
||||
name: "mismatched".to_string(),
|
||||
plugin_id: "selected-root".to_string(),
|
||||
plugin_display_name: "Selected Demo".to_string(),
|
||||
source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
selection_order: 0,
|
||||
enabled: false,
|
||||
},
|
||||
ContributionSummary {
|
||||
name: "unlisted".to_string(),
|
||||
plugin_id: "selected-root".to_string(),
|
||||
plugin_display_name: "Selected Demo".to_string(),
|
||||
source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
selection_order: 0,
|
||||
enabled: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selected_plugin_package_is_contributed_without_servers() -> TestResult {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let plugin_root = tempfile::tempdir()?;
|
||||
std::fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?;
|
||||
std::fs::create_dir_all(plugin_root.path().join("skills/deploy"))?;
|
||||
std::fs::write(
|
||||
plugin_root.path().join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"skill-only","interface":{"displayName":"Skill Only"}}"#,
|
||||
)?;
|
||||
std::fs::write(
|
||||
plugin_root.path().join("skills/deploy/SKILL.md"),
|
||||
"---\nname: deploy\ndescription: Deploy the project.\n---\n",
|
||||
)?;
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
|
||||
let contributions = raw_selected_plugin_contributions(&config, plugin_root.path()).await?;
|
||||
let package = contributions
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|(_, plugin_id, contribution)| PackageSummary {
|
||||
plugin_id,
|
||||
plugin_display_name: contribution.plugin_display_name,
|
||||
source_environment_id: contribution.source_environment_id,
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
package,
|
||||
Some(PackageSummary {
|
||||
plugin_id: "selected-root".to_string(),
|
||||
plugin_display_name: "Skill Only".to_string(),
|
||||
source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn denied_malformed_plugin_retains_identity_without_capabilities() -> TestResult {
|
||||
let default_off = "[plugins._default]\nenabled = false\n";
|
||||
for (manifest, discovery_enabled, expected_denied) in [
|
||||
(Some(b"{".as_slice()), false, true),
|
||||
(None, false, false),
|
||||
(None, true, false),
|
||||
(
|
||||
Some(br#"{"name":"denied","mcpServers":{"unexpected":{"command":"unexpected-command"}}}"#.as_slice()),
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(Some(b"{".as_slice()), true, true),
|
||||
(Some(b"\xff".as_slice()), true, true),
|
||||
] {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let plugin_root = tempfile::tempdir()?;
|
||||
let skills_root = plugin_root.path().join("skills");
|
||||
fs::create_dir_all(&skills_root)?;
|
||||
if let Some(manifest) = manifest {
|
||||
fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?;
|
||||
fs::write(plugin_root.path().join(".codex-plugin/plugin.json"), manifest)?;
|
||||
} else {
|
||||
// A nested package does not own its containing skill root.
|
||||
fs::create_dir_all(plugin_root.path().join("nested/.codex-plugin"))?;
|
||||
fs::write(
|
||||
plugin_root.path().join("nested/.codex-plugin/plugin.json"),
|
||||
r#"{"name":"nested"}"#,
|
||||
)?;
|
||||
}
|
||||
fs::write(codex_home.path().join("config.toml"), default_off)?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
config.features.set_enabled(Feature::ExecutorCapabilityDiscovery, discovery_enabled)?;
|
||||
|
||||
let expected = if expected_denied {
|
||||
vec![(
|
||||
("selected-root".to_string(), "selected-root".to_string()),
|
||||
Vec::new(),
|
||||
)]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for selected_root in [plugin_root.path(), skills_root.as_path()] {
|
||||
let contributions = raw_selected_plugin_contributions(&config, selected_root).await?;
|
||||
assert_eq!(
|
||||
contributions
|
||||
.into_iter()
|
||||
.map(|(root_id, plugin_id, contribution)| (
|
||||
(root_id, plugin_id),
|
||||
contribution.servers,
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selected_root_ownership_retries_errors_and_caches_success() -> TestResult {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let plugin_root = tempfile::tempdir()?;
|
||||
let standalone_root = tempfile::tempdir()?;
|
||||
let skills_root = plugin_root.path().join("skills");
|
||||
fs::create_dir_all(&skills_root)?;
|
||||
fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?;
|
||||
let manifest = plugin_root.path().join(".codex-plugin/plugin.json");
|
||||
fs::write(&manifest, r#"{"name":"example"}"#)?;
|
||||
fs::write(plugin_root.path().join(".mcp.json"), "{")?;
|
||||
let selected_roots = [
|
||||
("selected-root", plugin_root.path()),
|
||||
("owned-subfolder", skills_root.as_path()),
|
||||
("standalone", standalone_root.path()),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(id, path)| {
|
||||
Ok(SelectedCapabilityRoot {
|
||||
id: id.to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
path: PathUri::from_host_native_path(path)?,
|
||||
},
|
||||
})
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
akode_mcp_extension::install_plugins(
|
||||
&mut builder,
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
);
|
||||
let registry = builder.build();
|
||||
let thread_init = ExtensionDataInit::new();
|
||||
let thread_store = ExtensionData::new_with_init("test-thread", thread_init.clone());
|
||||
let default_off = "[plugins._default]\nenabled = false\n";
|
||||
let standalone = &selected_roots[2];
|
||||
let CapabilityRootLocation::Environment { path, .. } = &standalone.location;
|
||||
let sandbox_contexts = HashMap::from([(
|
||||
LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
FileSystemSandboxContext::from_permission_profile(Default::default(), path.clone()),
|
||||
)]);
|
||||
|
||||
for (phase, enabled_root, expected) in [
|
||||
(0, None, vec![("standalone", vec![])]),
|
||||
(1, None, vec![]),
|
||||
(2, Some("owned-subfolder"), vec![("selected-root", vec![])]),
|
||||
(
|
||||
3,
|
||||
None,
|
||||
vec![("selected-root", vec![]), ("owned-subfolder", vec![])],
|
||||
),
|
||||
(
|
||||
4,
|
||||
None,
|
||||
vec![("selected-root", vec![]), ("owned-subfolder", vec![])],
|
||||
),
|
||||
(
|
||||
5,
|
||||
Some("selected-root"),
|
||||
vec![
|
||||
("selected-root", vec!["probe"]),
|
||||
("owned-subfolder", vec![]),
|
||||
],
|
||||
),
|
||||
] {
|
||||
if phase == 4 {
|
||||
// Stable ownership must survive refresh without probing these files again.
|
||||
fs::remove_file(&manifest)?;
|
||||
fs::create_dir_all(standalone_root.path().join(".codex-plugin"))?;
|
||||
fs::write(
|
||||
standalone_root.path().join(".codex-plugin/plugin.json"),
|
||||
"{",
|
||||
)?;
|
||||
} else if phase == 5 {
|
||||
fs::write(&manifest, r#"{"name":"example"}"#)?;
|
||||
fs::write(
|
||||
plugin_root.path().join(".mcp.json"),
|
||||
r#"{"mcpServers":{"probe":{"command":"probe-command"}}}"#,
|
||||
)?;
|
||||
fs::remove_file(standalone_root.path().join(".codex-plugin/plugin.json"))?;
|
||||
}
|
||||
let policy = enabled_root.map_or_else(
|
||||
|| default_off.to_string(),
|
||||
|id| format!("{default_off}[plugins.{id}]\nenabled = true\n"),
|
||||
);
|
||||
fs::write(codex_home.path().join("config.toml"), policy)?;
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
// A warning requires metadata probing, which the test filesystem cannot sandbox.
|
||||
// Complete discovery retries ownership under the same sandbox, root, and policy.
|
||||
let discovery = (phase < 2).then(|| {
|
||||
ExecutorCapabilityDiscoverySnapshot::new(
|
||||
std::slice::from_ref(standalone),
|
||||
vec![Ok(Arc::new(CapabilityRootDiscovery {
|
||||
id: standalone.id.clone(),
|
||||
path: path.clone(),
|
||||
plugin: None,
|
||||
skills: Vec::new(),
|
||||
namespace_manifests: Vec::new(),
|
||||
warnings: if phase == 0 {
|
||||
vec!["ownership metadata unavailable".to_string()]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
error: None,
|
||||
}))],
|
||||
sandbox_contexts.clone(),
|
||||
)
|
||||
});
|
||||
let selected = registry.mcp_server_contributors()[0]
|
||||
.selected_plugins(
|
||||
McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&thread_init,
|
||||
&thread_store,
|
||||
"test_originator",
|
||||
&selected_roots,
|
||||
discovery.as_ref(),
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
),
|
||||
&config.plugins,
|
||||
)
|
||||
.await;
|
||||
let mut actual = Vec::new();
|
||||
for plugin in selected {
|
||||
let contribution = plugin.mcp.await;
|
||||
actual.push((
|
||||
plugin.selected_root_id,
|
||||
contribution
|
||||
.servers
|
||||
.into_iter()
|
||||
.map(|(name, _)| name)
|
||||
.collect::<Vec<_>>(),
|
||||
));
|
||||
}
|
||||
assert_eq!(
|
||||
actual,
|
||||
expected
|
||||
.into_iter()
|
||||
.map(|(id, servers)| (
|
||||
id.to_string(),
|
||||
servers.into_iter().map(str::to_string).collect::<Vec<_>>(),
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
"phase {phase}",
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_plugins_requirement_disables_selected_plugin_capabilities() -> TestResult {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let plugin_root = tempfile::tempdir()?;
|
||||
std::fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?;
|
||||
std::fs::write(
|
||||
plugin_root.path().join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"selected-root","interface":{"displayName":"Selected Root"}}"#,
|
||||
)?;
|
||||
std::fs::write(
|
||||
plugin_root.path().join(".mcp.json"),
|
||||
r#"{"mcpServers":{"probe":{"command":"probe-command"}}}"#,
|
||||
)?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.loader_overrides(
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"
|
||||
[features]
|
||||
plugins = false
|
||||
"#,
|
||||
))
|
||||
.loader_overrides_for_tests(codex_home.path())
|
||||
.expect("write managed config fixture"),
|
||||
)
|
||||
.build()
|
||||
.await?;
|
||||
assert!(!config.features.enabled(Feature::Plugins));
|
||||
|
||||
let direct = raw_selected_plugin_contributions(&config, plugin_root.path()).await?;
|
||||
assert!(
|
||||
matches!(
|
||||
direct.as_slice(),
|
||||
[(selected_root_id, _, contribution)]
|
||||
if selected_root_id == "selected-root"
|
||||
&& contribution.source_environment_id == LOCAL_ENVIRONMENT_ID
|
||||
&& contribution.servers.is_empty()
|
||||
),
|
||||
"managed Plugins disable should preserve only the direct selected-root identity"
|
||||
);
|
||||
|
||||
config
|
||||
.features
|
||||
.enable(Feature::ExecutorCapabilityDiscovery)
|
||||
.expect("test config should allow feature update");
|
||||
let discovered = raw_selected_plugin_contributions(&config, plugin_root.path()).await?;
|
||||
assert!(
|
||||
matches!(
|
||||
discovered.as_slice(),
|
||||
[(selected_root_id, _, contribution)]
|
||||
if selected_root_id == "selected-root"
|
||||
&& contribution.source_environment_id == LOCAL_ENVIRONMENT_ID
|
||||
&& contribution.servers.is_empty()
|
||||
),
|
||||
"managed Plugins disable should preserve only the discovered selected-root identity"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn high_level_discovery_matches_the_existing_plugin_provider() -> TestResult {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let plugin_root = tempfile::tempdir()?;
|
||||
std::fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?;
|
||||
std::fs::write(
|
||||
plugin_root.path().join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"demo","interface":{"displayName":"Demo"},"mcpServers":"./servers.json"}"#,
|
||||
)?;
|
||||
std::fs::write(
|
||||
plugin_root.path().join("servers.json"),
|
||||
r#"{
|
||||
"mcpServers": {
|
||||
"first": {
|
||||
"command": "first",
|
||||
"default_tools_approval_mode": "writes",
|
||||
"enabled_tools": ["read", "deploy", "trusted", "package-only"],
|
||||
"disabled_tools": ["package-denied"],
|
||||
"tools": {
|
||||
"read": {"approval_mode": "prompt", "output_token_limit": 12000},
|
||||
"deploy": {"approval_mode": "approve", "output_token_limit": 4000},
|
||||
"trusted": {"approval_mode": "approve"}
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"command": "second",
|
||||
"enabled": false,
|
||||
"default_tools_approval_mode": "prompt"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"
|
||||
[plugins."selected-root".mcp_servers.first]
|
||||
enabled = false
|
||||
default_tools_approval_mode = "prompt"
|
||||
enabled_tools = ["read", "deploy", "trusted", "host-only"]
|
||||
disabled_tools = ["write"]
|
||||
|
||||
[plugins."selected-root".mcp_servers.first.tools.read]
|
||||
approval_mode = "approve"
|
||||
output_token_limit = 8000
|
||||
|
||||
[plugins."selected-root".mcp_servers.first.tools.deploy]
|
||||
output_token_limit = 9000
|
||||
|
||||
[plugins."selected-root".mcp_servers.first.tools.trusted]
|
||||
approval_mode = "approve"
|
||||
|
||||
[plugins."selected-root".mcp_servers.second]
|
||||
enabled = true
|
||||
default_tools_approval_mode = "auto"
|
||||
"#,
|
||||
)?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
let existing = selected_plugin_contributions(&config, plugin_root.path()).await?;
|
||||
let mut servers = raw_selected_plugin_contributions(&config, plugin_root.path())
|
||||
.await?
|
||||
.into_iter()
|
||||
.flat_map(|(_, _, contribution)| contribution.servers)
|
||||
.collect::<HashMap<_, _>>();
|
||||
let server = servers
|
||||
.remove("first")
|
||||
.expect("disabled selected server remains registered");
|
||||
let declared_disabled_server = servers
|
||||
.remove("second")
|
||||
.expect("package-disabled server remains registered");
|
||||
assert_eq!(
|
||||
(
|
||||
server.enabled,
|
||||
server.default_tools_approval_mode,
|
||||
server.enabled_tools,
|
||||
server.disabled_tools,
|
||||
server.tools,
|
||||
declared_disabled_server.enabled,
|
||||
declared_disabled_server.default_tools_approval_mode,
|
||||
),
|
||||
(
|
||||
false,
|
||||
Some(AppToolApproval::Prompt),
|
||||
Some(vec![
|
||||
"read".to_string(),
|
||||
"deploy".to_string(),
|
||||
"trusted".to_string(),
|
||||
]),
|
||||
Some(vec!["package-denied".to_string(), "write".to_string()]),
|
||||
HashMap::from([
|
||||
(
|
||||
"read".to_string(),
|
||||
McpServerToolConfig {
|
||||
approval_mode: Some(AppToolApproval::Prompt),
|
||||
output_token_limit: std::num::NonZeroUsize::new(8_000),
|
||||
},
|
||||
),
|
||||
(
|
||||
"deploy".to_string(),
|
||||
McpServerToolConfig {
|
||||
approval_mode: Some(AppToolApproval::Prompt),
|
||||
output_token_limit: std::num::NonZeroUsize::new(4_000),
|
||||
},
|
||||
),
|
||||
(
|
||||
"trusted".to_string(),
|
||||
McpServerToolConfig {
|
||||
approval_mode: Some(AppToolApproval::Approve),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]),
|
||||
false,
|
||||
Some(AppToolApproval::Prompt),
|
||||
)
|
||||
);
|
||||
config
|
||||
.features
|
||||
.enable(Feature::ExecutorCapabilityDiscovery)
|
||||
.expect("test config should allow feature update");
|
||||
let high_level = selected_plugin_contributions(&config, plugin_root.path()).await?;
|
||||
|
||||
assert_eq!(
|
||||
existing
|
||||
.iter()
|
||||
.map(|contribution| contribution.source_environment_id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![LOCAL_ENVIRONMENT_ID, LOCAL_ENVIRONMENT_ID]
|
||||
);
|
||||
assert_eq!(high_level, existing);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn selected_plugin_contributions(
|
||||
config: &Config,
|
||||
plugin_root: &std::path::Path,
|
||||
) -> Result<Vec<ContributionSummary>, Box<dyn std::error::Error>> {
|
||||
Ok(raw_selected_plugin_contributions(config, plugin_root)
|
||||
.await?
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(selection_order, (_, plugin_id, contribution))| {
|
||||
contribution
|
||||
.servers
|
||||
.into_iter()
|
||||
.map(move |(name, config)| ContributionSummary {
|
||||
name,
|
||||
plugin_id: plugin_id.clone(),
|
||||
plugin_display_name: contribution.plugin_display_name.clone(),
|
||||
source_environment_id: contribution.source_environment_id.clone(),
|
||||
selection_order,
|
||||
enabled: config.enabled,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn raw_selected_plugin_contributions(
|
||||
config: &Config,
|
||||
plugin_root: &std::path::Path,
|
||||
) -> Result<Vec<(String, String, SelectedPluginContribution)>, Box<dyn std::error::Error>> {
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
let environment_manager = Arc::new(EnvironmentManager::default_for_tests());
|
||||
akode_mcp_extension::install_plugins(&mut builder, Arc::clone(&environment_manager));
|
||||
let registry = builder.build();
|
||||
let thread_init = ExtensionDataInit::new();
|
||||
let selected_capability_roots = vec![SelectedCapabilityRoot {
|
||||
id: "selected-root".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
path: PathUri::from_host_native_path(plugin_root)?,
|
||||
},
|
||||
}];
|
||||
let thread_store = ExtensionData::new_with_init("test-thread", thread_init.clone());
|
||||
let executor_capability_discovery = if config
|
||||
.features
|
||||
.enabled(Feature::ExecutorCapabilityDiscovery)
|
||||
{
|
||||
let resolved_roots = environment_manager
|
||||
.resolve_selected_capability_roots(
|
||||
&selected_capability_roots,
|
||||
&HashMap::from([(
|
||||
LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
environment_manager.get_environment(LOCAL_ENVIRONMENT_ID),
|
||||
)]),
|
||||
)
|
||||
.await;
|
||||
Some(
|
||||
ExecutorCapabilityDiscoveryCache::default()
|
||||
.snapshot(&resolved_roots, &Default::default())
|
||||
.await,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let selected = registry.mcp_server_contributors()[0]
|
||||
.selected_plugins(
|
||||
McpServerContributionContext::for_step(
|
||||
config,
|
||||
&thread_init,
|
||||
&thread_store,
|
||||
"test_originator",
|
||||
&selected_capability_roots,
|
||||
executor_capability_discovery.as_ref(),
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
),
|
||||
&config.plugins,
|
||||
)
|
||||
.await;
|
||||
let mut contributions = Vec::new();
|
||||
for plugin in selected {
|
||||
contributions.push((plugin.selected_root_id, plugin.plugin_id, plugin.mcp.await));
|
||||
}
|
||||
Ok(contributions)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_executor_plugin_exposes_and_calls_its_mcp_tools() -> anyhow::Result<()> {
|
||||
run_test_with_large_stack(
|
||||
"executor-plugin-projection",
|
||||
run_executor_plugin_projection_scenarios,
|
||||
)
|
||||
}
|
||||
|
||||
async fn run_executor_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
core_test_support::skip_if_remote!(Ok(()), "V1 plugin fixtures use host-local files");
|
||||
// Uninstalled plugins must not start MCPs; installed ones expose and run their tools.
|
||||
for (case, installed) in [("not_installed", false), ("installed", true)] {
|
||||
let server = start_mock_server().await;
|
||||
let plugin_server = start_mock_server().await;
|
||||
let plugin_mcp = McpTestServer::mount_with_tools(
|
||||
&plugin_server,
|
||||
Arc::new(std::sync::Mutex::new(vec![json!({
|
||||
"name": "echo", "description": "Echo a note.",
|
||||
"annotations": {"readOnlyHint": true},
|
||||
"inputSchema": {"type": "object", "properties": {"title": {"type": "string"}}}
|
||||
})])),
|
||||
)
|
||||
.await?;
|
||||
wiremock::Mock::given(wiremock::matchers::method("POST"))
|
||||
.and(wiremock::matchers::body_partial_json(json!({"method": "tools/call"})))
|
||||
.respond_with(|request: &wiremock::Request| {
|
||||
let body: serde_json::Value = serde_json::from_slice(&request.body)
|
||||
.unwrap_or_else(|error| panic!("invalid MCP request JSON: {error}"));
|
||||
wiremock::ResponseTemplate::new(200).set_body_json(json!({
|
||||
"jsonrpc": "2.0", "id": body["id"],
|
||||
"result": {"content": [], "structuredContent": {"echo": body["params"]["arguments"]["title"]}, "isError": false}
|
||||
}))
|
||||
})
|
||||
.with_priority(1)
|
||||
.mount(&plugin_server).await;
|
||||
let declaration = json!({"url": plugin_mcp.mcp_url()});
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
let providers = PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))));
|
||||
install_plugin_providers(&mut extensions, providers);
|
||||
let mut builder = test_codex()
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_auth(CodexAuth::from_api_key("Test API Key"))
|
||||
.with_model_info_override("gpt-5.5", |model| model.supports_search_tool = false)
|
||||
.with_config(move |config| {
|
||||
assert!(config.features.enable(Feature::Plugins).is_ok());
|
||||
assert!(
|
||||
config
|
||||
.features
|
||||
.enable(Feature::ExecutorCapabilityDiscovery)
|
||||
.is_ok()
|
||||
);
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
if installed {
|
||||
let selection = test
|
||||
.akode
|
||||
.environment_selections()
|
||||
.await
|
||||
.into_iter()
|
||||
.next()
|
||||
.context("selected environment missing")?;
|
||||
let root = selection.cwd.join("notes")?;
|
||||
let root_path = root.to_abs_path()?;
|
||||
fs::create_dir_all(root_path.join(".codex-plugin"))?;
|
||||
fs::write(root_path.join(".codex-plugin/plugin.json"), json!({
|
||||
"name": "notes", "version": "1", "interface": {"displayName": "Installed Notes"},
|
||||
"mcpServers": "./.mcp.json"
|
||||
}).to_string())?;
|
||||
fs::write(
|
||||
root_path.join(".mcp.json"),
|
||||
json!({"mcpServers": {"notes": declaration}}).to_string(),
|
||||
)?;
|
||||
test.codex
|
||||
.environment_ready(
|
||||
&selection,
|
||||
EnvironmentConfig {
|
||||
environment_hooks: Default::default(),
|
||||
allow_login_shell: false,
|
||||
workspace_roots: selection.workspace_roots.clone(),
|
||||
permission_profile: PermissionProfileSnapshot::legacy(
|
||||
test.config.permissions.permission_profile().clone(),
|
||||
),
|
||||
shell_environment_policy: Default::default(),
|
||||
windows_sandbox_level: WindowsSandboxLevel::from_config(&test.config),
|
||||
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
|
||||
use_legacy_landlock: test.config.features.use_legacy_landlock(),
|
||||
exec_policy: None,
|
||||
mcp_policy: None,
|
||||
network_policy: None,
|
||||
selected_capability_roots: vec![SelectedCapabilityRoot {
|
||||
id: "notes@marketplace".into(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: selection.environment_id.clone(),
|
||||
path: root,
|
||||
},
|
||||
}],
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let response = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_response_created("call"),
|
||||
ev_function_call_with_namespace(
|
||||
"notes-call",
|
||||
"mcp__notes",
|
||||
"echo",
|
||||
r#"{"title":"release check"}"#,
|
||||
),
|
||||
ev_completed("call"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_assistant_message("done", "Finished checking Notes."),
|
||||
ev_completed("done"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
test.submit_turn("Use the Notes MCP to check the release.")
|
||||
.await?;
|
||||
let requests = response.requests();
|
||||
assert_eq!(requests.len(), 2, "{case}");
|
||||
let tool = requests[0].tool_by_name("mcp__notes", "echo");
|
||||
assert_eq!(tool.is_some(), installed, "{case}");
|
||||
let output = requests[1].function_call_output("notes-call");
|
||||
if installed {
|
||||
assert!(
|
||||
tool.context("Notes tool missing")?["description"]
|
||||
.as_str()
|
||||
.context("tool description missing")?
|
||||
.contains("Installed Notes")
|
||||
);
|
||||
assert!(
|
||||
output.to_string().contains("release check"),
|
||||
"{case}: {output}"
|
||||
);
|
||||
}
|
||||
let calls = recorded_mcp_tool_calls(&plugin_server).await;
|
||||
assert_eq!(calls.len(), usize::from(installed), "{case}");
|
||||
if installed {
|
||||
assert_eq!(calls[0]["params"]["name"], "echo");
|
||||
assert_eq!(
|
||||
calls[0]["params"]["arguments"],
|
||||
json!({"title": "release check"})
|
||||
);
|
||||
}
|
||||
let initialized = plugin_server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("MCP requests missing")?
|
||||
.iter()
|
||||
.any(|request| {
|
||||
serde_json::from_slice::<serde_json::Value>(&request.body)
|
||||
.is_ok_and(|body| body["method"] == "initialize")
|
||||
});
|
||||
assert_eq!(
|
||||
initialized, installed,
|
||||
"{case}: uninstalled declarations must not start MCPs"
|
||||
);
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user