Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,8 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "akode-mcp",
crate_name = "akode_mcp",
extra_binaries = ["//akode-rs/cli:codex"],
test_data_extra = glob(["src/**/snapshots/**"]),
)

View File

@@ -0,0 +1,57 @@
[package]
edition.workspace = true
license.workspace = true
name = "akode-mcp"
version.workspace = true
[lib]
name = "akode_mcp"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
arc-swap = { workspace = true }
async-channel = { workspace = true }
akode-async-utils = { workspace = true }
akode-config = { workspace = true }
akode-diagnostics = { workspace = true }
akode-exec-server = { workspace = true }
akode-login = { workspace = true }
akode-model-provider = { workspace = true }
akode-network-proxy = { workspace = true }
akode-otel = { workspace = true }
akode-protocol = { workspace = true }
akode-rmcp-client = { workspace = true }
akode-utils-absolute-path = { workspace = true }
akode-utils-path-uri = { workspace = true }
akode-utils-plugins = { workspace = true }
akode-utils-process = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
lru = { workspace = true }
regex-lite = { workspace = true }
rmcp = { workspace = true, default-features = false, features = ["base64", "macros", "schemars", "server"] }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sha1 = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["io-util", "macros", "rt-multi-thread"] }
tokio-util = { workspace = true, features = ["rt"] }
tracing = { workspace = true }
url = { workspace = true }
uuid = { workspace = true, features = ["v4"] }
[dev-dependencies]
assert_matches = { workspace = true }
akode-exec-server-test-support = { workspace = true }
akode-plugin = { workspace = true }
akode-utils-cargo-bin = { workspace = true }
insta = { workspace = true }
pretty_assertions = { workspace = true }
rmcp = { workspace = true, default-features = false, features = ["base64", "macros", "schemars", "server"] }
tempfile = { workspace = true }
uuid = { workspace = true }

View File

@@ -0,0 +1,37 @@
# Codex MCP runtime
This crate manages Codex's MCP connections, tool calls, and their captured authority.
## Sandbox request metadata
An MCP server advertises the experimental `codex/sandbox-state` capability to
receive sandbox metadata on tool calls. The deprecated capability name
`codex/sandbox-state-meta` opts into the same contract during migration.
Codex supplies these entries in the request's `_meta` object:
| Key | Value |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `codex/sandbox-state` | Opaque policy to pass to `akode sandbox --sandbox-state-json`. |
| `codex/sandbox-state-meta` | An identical copy of that policy under the deprecated name. |
| `codex/sandbox-launcher` | When available, an object with an absolute `codexExecutable` path to a verified full Codex CLI on the MCP server's host. |
Use the launcher path to invoke `sandbox --sandbox-state-json` with the entire
state value serialized as one argument, followed by `--` and the command to run.
The state contains neither launcher discovery data nor deprecation messages.
Preserve unknown policy fields by forwarding the original value rather than
deserializing and reconstructing it. The two state names are aliases, not separate
policies; new consumers should prefer `codex/sandbox-state`.
Launcher metadata is currently available only for local stdio servers. An HTTP
endpoint, including loopback, or a remote executor does not establish a shared
filesystem with the harness. Codex omits the launcher when its path is unknown,
not representable as UTF-8, or fails the cached capability probe. Absence does not
authorize a PATH search or unsandboxed fallback. Servers that require a launcher
must fail closed or require an explicit operator opt-out.
The state and launcher describe the issuing call. Retain both when starting a
long-lived subprocess or caching policy-bound results; reject changed authority
before reusing them. Tool arguments supplied by the model are not authority.
See [`sandbox_metadata.rs`](src/sandbox_metadata.rs) for the wire types and
[`binding.rs`](src/binding.rs) for execution-environment selection.

View File

@@ -0,0 +1,532 @@
use super::PluginMcpConfigParseOutcome;
use super::PluginMcpServerParseError;
use akode_config::McpServerConfig;
use serde::Deserialize;
use serde_json::Map as JsonMap;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::Path;
use std::path::PathBuf;
use url::Host;
// Published Agent Plugins v1 MCP schema:
// https://github.com/agentplugins/agent-plugins-spec/blob/main/schemas/1.0.0/mcp.schema.json
const AGENT_PLUGIN_MCP_SCHEMA_URI: &str = "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json";
const SUPPORTED_AGENT_PLUGIN_MCP_SCHEMA_URIS: &[&str] = &[AGENT_PLUGIN_MCP_SCHEMA_URI];
const PLUGIN_ROOT_VARIABLE: &str = "PLUGIN_ROOT";
const PLUGIN_DATA_VARIABLE: &str = "PLUGIN_DATA";
const CLIENT_OWNED_HTTP_HEADERS: &[&str] = &[
"accept",
"authorization",
"connection",
"content-encoding",
"content-length",
"content-type",
"host",
"last-event-id",
"mcp-protocol-version",
"mcp-session-id",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"user-agent",
];
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct AgentPluginMcpFile {
#[serde(rename = "$schema")]
schema: String,
mcp_servers: BTreeMap<String, JsonValue>,
}
#[derive(Debug, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
enum AgentPluginMcpServer {
#[serde(rename = "stdio")]
Stdio {
command: String,
#[serde(default)]
args: Vec<String>,
#[serde(default)]
env: BTreeMap<String, String>,
cwd: Option<String>,
},
#[serde(rename = "streamable-http")]
StreamableHttp {
url: String,
headers: Option<BTreeMap<String, String>>,
},
#[serde(rename = "sse")]
Sse {
#[serde(rename = "url")]
_url: String,
#[serde(rename = "headers")]
_headers: Option<BTreeMap<String, String>>,
},
}
/// Translates an Agent Plugins `mcp.json` into Codex MCP configuration.
pub fn parse_agent_plugin_mcp_config(
plugin_root: &Path,
plugin_data_root: &Path,
contents: &str,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
parse_agent_plugin_mcp_config_from(contents, plugin_root, plugin_data_root)
}
fn parse_agent_plugin_mcp_config_from(
contents: &str,
plugin_root: &Path,
plugin_data_root: &Path,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
let AgentPluginMcpFile {
schema,
mcp_servers,
} = serde_json::from_str(contents)?;
if !SUPPORTED_AGENT_PLUGIN_MCP_SCHEMA_URIS.contains(&schema.as_str()) {
return Err(plugin_mcp_json_error(format!(
"unsupported Agent Plugins MCP schema `{schema}`; supported schemas: {}",
SUPPORTED_AGENT_PLUGIN_MCP_SCHEMA_URIS.join(", ")
)));
}
let mut outcome = PluginMcpConfigParseOutcome::default();
for (name, value) in mcp_servers {
match normalize_agent_plugin_mcp_server(value, plugin_root, plugin_data_root) {
Ok(config) => {
outcome.servers.insert(name, config);
}
Err(message) => outcome
.errors
.push(PluginMcpServerParseError { name, message }),
}
}
Ok(outcome)
}
fn normalize_agent_plugin_mcp_server(
value: JsonValue,
plugin_root: &Path,
plugin_data_root: &Path,
) -> Result<McpServerConfig, String> {
let object = value
.as_object()
.ok_or_else(|| "Agent Plugins MCP server must be an object".to_string())?;
match object.get("type").and_then(JsonValue::as_str) {
Some("stdio") => reject_explicit_null(object, "cwd")?,
Some("streamable-http" | "sse") => reject_explicit_null(object, "headers")?,
_ => {}
}
let server =
serde_json::from_value::<AgentPluginMcpServer>(value).map_err(|err| err.to_string())?;
let object = match server {
AgentPluginMcpServer::Stdio {
command,
args,
env,
cwd,
} => normalize_agent_plugin_stdio_server(
command,
args,
env,
cwd,
plugin_root,
plugin_data_root,
)?,
AgentPluginMcpServer::StreamableHttp { url, headers } => {
normalize_agent_plugin_http_server(url, headers)?
}
AgentPluginMcpServer::Sse { .. } => {
return Err("Agent Plugins legacy SSE transport is not supported by Codex".to_string());
}
};
serde_json::from_value(JsonValue::Object(object)).map_err(|err| err.to_string())
}
fn normalize_agent_plugin_stdio_server(
mut command: String,
mut args: Vec<String>,
mut env: BTreeMap<String, String>,
cwd: Option<String>,
plugin_root: &Path,
plugin_data_root: &Path,
) -> Result<JsonMap<String, JsonValue>, String> {
#[cfg(windows)]
let has_windows_path_prefix = matches!(
Path::new(&command).components().next(),
Some(std::path::Component::Prefix(_))
);
#[cfg(not(windows))]
let has_windows_path_prefix = false;
let is_bare_command = !command.is_empty()
&& !command.contains('/')
&& !command.contains('\\')
&& !has_windows_path_prefix;
let is_plugin_relative_command =
command.starts_with("./") && is_portable_relative_path(&command);
if !is_bare_command && !is_plugin_relative_command {
return Err(
"Agent Plugins stdio command must be a bare executable name or a contained `./` path"
.to_string(),
);
}
for reserved in [PLUGIN_ROOT_VARIABLE, PLUGIN_DATA_VARIABLE] {
if env
.keys()
.any(|name| environment_variable_names_match(name, reserved))
{
return Err(format!(
"Agent Plugins stdio `env` cannot override reserved variable `{reserved}`"
));
}
}
#[cfg(windows)]
{
let mut normalized_env = BTreeMap::new();
for (name, value) in env {
let normalized_name = name.to_ascii_uppercase();
if normalized_env.insert(normalized_name, value).is_some() {
return Err(format!(
"duplicate case-insensitive Agent Plugins environment variable `{name}`"
));
}
}
env = normalized_env;
}
let root_path = absolute_plugin_path(plugin_root)?;
let data_root_path = absolute_plugin_path(plugin_data_root)?;
let root = host_path_string(&root_path);
let data_root = host_path_string(&data_root_path);
if command.starts_with("./") {
command = host_path_string(&resolve_contained_host_path(
&command, &root_path, &root_path,
)?);
}
for arg in &mut args {
*arg = expand_agent_plugin_placeholders(arg, &root, &data_root);
}
for value in env.values_mut() {
*value = expand_agent_plugin_placeholders(value, &root, &data_root);
}
let cwd = cwd.as_deref().unwrap_or("${PLUGIN_ROOT}");
let Some(cwd_root) = parse_agent_plugin_cwd(cwd) else {
return Err(
"Agent Plugins stdio `cwd` must be a contained `./`, `${PLUGIN_ROOT}`, or `${PLUGIN_DATA}` path"
.to_string(),
);
};
let cwd = expand_agent_plugin_placeholders(cwd, &root, &data_root);
let cwd_root = match cwd_root {
AgentPluginCwdRoot::Package => &root_path,
AgentPluginCwdRoot::Data => &data_root_path,
};
env.insert(PLUGIN_ROOT_VARIABLE.to_string(), root);
env.insert(PLUGIN_DATA_VARIABLE.to_string(), data_root);
Ok(JsonMap::from_iter([
("command".to_string(), JsonValue::String(command)),
(
"args".to_string(),
JsonValue::Array(args.into_iter().map(JsonValue::String).collect()),
),
("env".to_string(), string_map_value(env)),
(
"cwd".to_string(),
JsonValue::String(host_path_string(&resolve_contained_host_path(
&cwd, cwd_root, cwd_root,
)?)),
),
]))
}
fn reject_explicit_null(object: &JsonMap<String, JsonValue>, field: &str) -> Result<(), String> {
if object.get(field).is_some_and(JsonValue::is_null) {
return Err(format!(
"Agent Plugins MCP `{field}` must use its declared type when present"
));
}
Ok(())
}
fn environment_variable_names_match(left: &str, right: &str) -> bool {
if cfg!(windows) {
left.eq_ignore_ascii_case(right)
} else {
left == right
}
}
fn normalize_agent_plugin_http_server(
url: String,
mut headers: Option<BTreeMap<String, String>>,
) -> Result<JsonMap<String, JsonValue>, String> {
validate_agent_plugin_url(&url)?;
if let Some(configured_headers) = headers.as_mut() {
validate_agent_plugin_headers(configured_headers)?;
configured_headers.retain(|name, _| {
!CLIENT_OWNED_HTTP_HEADERS
.iter()
.any(|owned| name.eq_ignore_ascii_case(owned))
});
}
let mut object = JsonMap::from_iter([("url".to_string(), JsonValue::String(url))]);
if let Some(headers) = headers.filter(|headers| !headers.is_empty()) {
object.insert("http_headers".to_string(), string_map_value(headers));
}
Ok(object)
}
fn validate_agent_plugin_url(raw_url: &str) -> Result<(), String> {
if raw_url.is_empty() {
return Err("Agent Plugins HTTP server requires a non-empty `url`".to_string());
}
let parsed = url::Url::parse(raw_url)
.map_err(|err| format!("invalid Agent Plugins MCP URL `{raw_url}`: {err}"))?;
if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
return Err("Agent Plugins MCP URL must be absolute HTTP or HTTPS".to_string());
}
if !parsed.username().is_empty() || parsed.password().is_some() || parsed.fragment().is_some() {
return Err(
"Agent Plugins MCP URL must not contain user information or a fragment".to_string(),
);
}
let is_loopback = match parsed.host() {
Some(Host::Domain(host)) => host == "localhost",
Some(Host::Ipv4(address)) => address.is_loopback(),
Some(Host::Ipv6(address)) => address.is_loopback(),
None => false,
};
if parsed.scheme() == "http" && !is_loopback {
return Err("non-loopback Agent Plugins MCP endpoints must use HTTPS".to_string());
}
Ok(())
}
fn validate_agent_plugin_headers(headers: &BTreeMap<String, String>) -> Result<(), String> {
let mut seen = std::collections::HashSet::new();
for (name, value) in headers {
if !seen.insert(name.to_ascii_lowercase()) {
return Err(format!(
"duplicate case-insensitive Agent Plugins HTTP header `{name}`"
));
}
if !is_valid_http_header_name(name) {
return Err(format!("invalid Agent Plugins HTTP header name `{name}`"));
}
if value
.bytes()
.any(|byte| (byte < 32 && byte != b'\t') || byte == 127)
{
return Err(format!(
"invalid Agent Plugins HTTP header value for `{name}`"
));
}
}
Ok(())
}
fn string_map_value(values: BTreeMap<String, String>) -> JsonValue {
JsonValue::Object(
values
.into_iter()
.map(|(name, value)| (name, JsonValue::String(value)))
.collect(),
)
}
#[derive(Clone, Copy, Debug)]
enum AgentPluginCwdRoot {
Package,
Data,
}
fn parse_agent_plugin_cwd(value: &str) -> Option<AgentPluginCwdRoot> {
if value == "./" {
return Some(AgentPluginCwdRoot::Package);
}
if let Some(relative) = value.strip_prefix("./")
&& is_portable_path_suffix(relative)
{
return Some(AgentPluginCwdRoot::Package);
}
for (placeholder, root) in [
("${PLUGIN_ROOT}", AgentPluginCwdRoot::Package),
("${PLUGIN_DATA}", AgentPluginCwdRoot::Data),
] {
if value == placeholder {
return Some(root);
}
if let Some(relative) = value.strip_prefix(&format!("{placeholder}/"))
&& (relative.is_empty() || is_portable_path_suffix(relative))
{
return Some(root);
}
}
None
}
fn expand_agent_plugin_placeholders(value: &str, plugin_root: &str, plugin_data: &str) -> String {
const ROOT: &str = "${PLUGIN_ROOT}";
const DATA: &str = "${PLUGIN_DATA}";
let mut output = String::with_capacity(value.len());
let mut remaining = value;
loop {
let next = match (remaining.find(ROOT), remaining.find(DATA)) {
(Some(root), Some(data)) if root <= data => Some((root, ROOT, plugin_root)),
(Some(_), Some(data)) => Some((data, DATA, plugin_data)),
(Some(root), None) => Some((root, ROOT, plugin_root)),
(None, Some(data)) => Some((data, DATA, plugin_data)),
(None, None) => None,
};
let Some((index, placeholder, replacement)) = next else {
output.push_str(remaining);
break;
};
output.push_str(&remaining[..index]);
output.push_str(replacement);
remaining = &remaining[index + placeholder.len()..];
}
output
}
fn absolute_plugin_path(path: &Path) -> Result<PathBuf, String> {
let absolute = if path.is_absolute() {
Ok(path.to_path_buf())
} else {
std::env::current_dir()
.map(|cwd| cwd.join(path))
.map_err(|err| format!("failed to resolve plugin path: {err}"))
}?;
resolve_existing_path_prefix(&absolute)
}
fn resolve_contained_host_path(
value: &str,
root: &Path,
allowed_root: &Path,
) -> Result<PathBuf, String> {
let value = Path::new(value);
let path = if value.is_absolute() {
value.to_path_buf()
} else {
root.join(value)
};
let path = resolve_existing_path_prefix(&path)?;
if !path.starts_with(allowed_root) {
return Err(format!(
"expanded path `{}` must remain within `{}`",
value.display(),
allowed_root.display()
));
}
Ok(path)
}
fn resolve_existing_path_prefix(path: &Path) -> Result<PathBuf, String> {
let mut existing = path.to_path_buf();
let mut missing_components = Vec::<OsString>::new();
loop {
match std::fs::canonicalize(&existing) {
Ok(mut resolved) => {
for component in missing_components.iter().rev() {
resolved.push(component);
}
return Ok(lexical_normalize(&resolved));
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
if std::fs::symlink_metadata(&existing)
.is_ok_and(|metadata| metadata.file_type().is_symlink())
{
return Err(format!(
"failed to resolve symlinked path `{}`",
path.display()
));
}
let Some(component) = existing.components().next_back() else {
return Err(format!(
"failed to resolve path `{}`: {err}",
path.display()
));
};
if matches!(
component,
std::path::Component::Prefix(_) | std::path::Component::RootDir
) {
return Err(format!(
"failed to resolve path `{}`: {err}",
path.display()
));
}
missing_components.push(component.as_os_str().to_os_string());
if !existing.pop() {
return Err(format!(
"failed to resolve path `{}`: {err}",
path.display()
));
}
}
Err(err) => {
return Err(format!(
"failed to resolve path `{}`: {err}",
path.display()
));
}
}
}
}
fn host_path_string(path: &Path) -> String {
let rendered = path.to_string_lossy();
#[cfg(windows)]
if let Some(path) = rendered.strip_prefix(r"\\?\") {
return path
.strip_prefix(r"UNC\")
.map(|path| format!(r"\\{path}"))
.unwrap_or_else(|| path.to_string());
}
rendered.into_owned()
}
fn is_portable_relative_path(value: &str) -> bool {
value
.strip_prefix("./")
.is_some_and(is_portable_path_suffix)
}
fn is_portable_path_suffix(value: &str) -> bool {
!value.is_empty() && !value.contains('\\')
}
fn is_valid_http_header_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
}
fn lexical_normalize(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
normalized.pop();
}
component => normalized.push(component.as_os_str()),
}
}
normalized
}
fn plugin_mcp_json_error(message: impl Into<String>) -> serde_json::Error {
serde_json::Error::io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
message.into(),
))
}

View File

@@ -0,0 +1,62 @@
//! Forwards auth invalidations without credentials. The managed client owns the watcher.
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use akode_login::AuthChangeState;
use akode_rmcp_client::RmcpClient;
use rmcp::model::ServerCapabilities;
use serde_json::json;
use tokio::sync::watch;
use tokio_util::task::AbortOnDropHandle;
pub(crate) const CAPABILITY: &str = "codex/auth-change";
const NOTIFICATION: &str = "notifications/codex/authChanged";
const SEND_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) async fn start(
client: Arc<RmcpClient>,
capabilities: &ServerCapabilities,
changes: Option<watch::Receiver<AuthChangeState>>,
) -> Result<Option<Arc<AbortOnDropHandle<()>>>> {
let Some(mut changes) = changes.filter(|_| {
capabilities
.experimental
.as_ref()
.is_some_and(|capabilities| capabilities.contains_key(CAPABILITY))
}) else {
return Ok(None);
};
notify(&client, &mut changes).await?;
let task = tokio::spawn(async move {
while changes.changed().await.is_ok() {
if notify(&client, &mut changes).await.is_err() {
tracing::warn!("MCP auth invalidation delivery failed; closing connection");
client.shutdown().await;
break;
}
}
});
Ok(Some(Arc::new(AbortOnDropHandle::new(task))))
}
async fn notify(client: &RmcpClient, changes: &mut watch::Receiver<AuthChangeState>) -> Result<()> {
let state = *changes.borrow_and_update();
tokio::time::timeout(
SEND_TIMEOUT,
client.send_custom_notification(
NOTIFICATION,
Some(json!({
"generation": state.generation,
"ownerGeneration": state.owner_generation,
})),
),
)
.await?
}
#[cfg(test)]
#[path = "auth_changes_tests.rs"]
mod tests;

View File

@@ -0,0 +1,104 @@
use super::*;
use akode_rmcp_client::InProcessTransportFactory;
use futures::FutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use rmcp::ServiceExt;
use rmcp::model::ClientCapabilities;
use rmcp::model::CustomNotification;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use tokio::sync::mpsc;
use tokio::time::timeout;
#[derive(Clone)]
struct NotificationServer(mpsc::Sender<serde_json::Value>);
impl rmcp::ServerHandler for NotificationServer {
async fn on_custom_notification(
&self,
notification: CustomNotification,
_context: rmcp::service::NotificationContext<rmcp::RoleServer>,
) {
self.0.send(json!(notification)).await.unwrap();
}
}
impl InProcessTransportFactory for NotificationServer {
fn open(&self) -> BoxFuture<'static, std::io::Result<tokio::io::DuplexStream>> {
let server = self.clone();
async move {
let (client, transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
tokio::spawn(async move {
let service = server.serve(transport).await.unwrap();
service.waiting().await.unwrap();
});
Ok(client)
}
.boxed()
}
}
#[tokio::test]
async fn auth_notifications_require_opt_in_and_follow_client_lifetime() -> Result<()> {
let (notifications, mut received) = mpsc::channel(/*buffer*/ 8);
let client = Arc::new(
RmcpClient::new_in_process_client(Arc::new(NotificationServer(notifications))).await?,
);
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("test", "1"),
),
Some(SEND_TIMEOUT),
Box::new(|_, _| async { anyhow::bail!("unexpected elicitation") }.boxed()),
)
.await?;
let (changes, receiver) = watch::channel(AuthChangeState::default());
let mut capabilities = ServerCapabilities::default();
assert!(
start(Arc::clone(&client), &capabilities, Some(receiver.clone()))
.await?
.is_none()
);
capabilities.experimental = Some([(CAPABILITY.to_string(), Default::default())].into());
assert!(
start(Arc::clone(&client), &capabilities, /*changes*/ None)
.await?
.is_none()
);
assert_eq!(received.try_recv(), Err(mpsc::error::TryRecvError::Empty));
let watcher = start(Arc::clone(&client), &capabilities, Some(receiver))
.await?
.unwrap();
assert_eq!(
timeout(SEND_TIMEOUT, received.recv()).await?,
Some(
json!({"method": NOTIFICATION, "params": {"_meta": {}, "generation": 0, "ownerGeneration": 0}})
),
);
changes.send_modify(|state| state.generation += 1);
assert_eq!(
timeout(SEND_TIMEOUT, received.recv()).await?,
Some(
json!({"method": NOTIFICATION, "params": {"_meta": {}, "generation": 1, "ownerGeneration": 0}})
),
);
for _ in 0..2 {
changes.send_modify(|state| {
state.generation += 1;
state.owner_generation += 1;
});
}
assert_eq!(
timeout(SEND_TIMEOUT, received.recv()).await?,
Some(
json!({"method": NOTIFICATION, "params": {"_meta": {}, "generation": 3, "ownerGeneration": 2}})
),
);
drop(watcher);
timeout(SEND_TIMEOUT, changes.closed()).await?;
client.shutdown().await;
Ok(())
}

View File

@@ -0,0 +1,497 @@
//! Immutable MCP catalog and execution handles.
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use akode_config::AppToolApproval;
use akode_exec_server::FileSystemSandboxContext;
use akode_protocol::mcp::CallToolResult;
use akode_protocol::models::PermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use rmcp::model::Resource;
use rmcp::model::ResourceTemplate;
use serde_json::Value as JsonValue;
use crate::McpConfig;
use crate::McpServerPermissions;
use crate::binding_clients::McpBindingClients;
use crate::client_tool_catalog::ToolCatalogSnapshot;
use crate::connection_manager::McpConnectionSet;
use crate::rmcp_client::ManagedClient;
use crate::server::McpServerMetadata;
use crate::tools::ToolInfo;
/// The exact tool catalog and execution handles shared by compatible sampling steps.
pub struct McpBinding {
connections: Arc<McpConnectionSet>,
clients: Arc<McpBindingClients>,
config: Arc<McpConfig>,
plugins_available: bool,
tools: Arc<[ToolInfo]>,
calls: HashMap<(String, String), PreparedMcpCall>,
}
impl McpBinding {
/// Creates an empty binding for tests and callers without a materialized runtime.
pub fn empty(config: Arc<McpConfig>) -> Self {
Self::new(
Arc::new(McpConnectionSet::empty(config.prefix_mcp_tool_names)),
Arc::new(McpBindingClients::new(HashMap::new())),
config,
/*plugins_available*/ false,
Vec::new(),
HashMap::new(),
)
}
pub(crate) fn new(
connections: Arc<McpConnectionSet>,
clients: Arc<McpBindingClients>,
config: Arc<McpConfig>,
plugins_available: bool,
tools: impl Into<Arc<[ToolInfo]>>,
calls: HashMap<(String, String), PreparedMcpCall>,
) -> Self {
Self {
connections,
clients,
config,
plugins_available,
tools: tools.into(),
calls,
}
}
pub fn config(&self) -> &Arc<McpConfig> {
&self.config
}
pub fn plugins_available(&self) -> bool {
self.plugins_available
}
/// Returns the frozen model-visible catalog captured for this binding.
pub fn tools(&self) -> &[ToolInfo] {
&self.tools
}
/// Returns permitted tool metadata, including app-only tools.
pub fn tool_info(&self, server: &str, tool: &str) -> Option<&ToolInfo> {
self.calls
.get(&(server.to_string(), tool.to_string()))
.map(PreparedMcpCall::tool_info)
}
/// Binds a model-visible call to the exact client and metadata in this binding.
pub fn prepare_call(&self, server: &str, tool: &str) -> Option<PreparedMcpCall> {
self.calls
.get(&(server.to_string(), tool.to_string()))
.filter(|call| crate::tool_is_model_visible(call.tool_info()))
.cloned()
}
pub fn has_servers(&self) -> bool {
self.connections.has_servers()
}
/// The environment owning this server in the step's connection set, even if it exposes no tools.
pub fn server_environment_id(&self, server: &str) -> Option<&str> {
self.connections.server_environment_id(server)
}
pub async fn list_resources(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourcesResult> {
if self.clients.client(server).is_some() {
self.clients.list_resources(server, params).await
} else {
self.connections.list_resources(server, params).await
}
}
pub async fn list_all_resources(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<Resource>> {
self.clients.list_all_resources(include_server).await
}
pub async fn list_resource_templates(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourceTemplatesResult> {
if self.clients.client(server).is_some() {
self.clients.list_resource_templates(server, params).await
} else {
self.connections
.list_resource_templates(server, params)
.await
}
}
pub async fn list_all_resource_templates(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<ResourceTemplate>> {
self.clients
.list_all_resource_templates(include_server)
.await
}
pub async fn read_resource(
&self,
server: &str,
params: ReadResourceRequestParams,
) -> Result<ReadResourceResult> {
if self.clients.client(server).is_some() {
self.clients.read_resource(server, params).await
} else {
self.connections.read_resource(server, params).await
}
}
}
impl fmt::Debug for McpBinding {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("McpBinding")
.field("tools", &self.tools)
.field("prepared_call_count", &self.calls.len())
.finish_non_exhaustive()
}
}
/// A call bound to an exact client, catalog revision, timeout, and permission authority.
#[derive(Clone)]
pub struct PreparedMcpCall {
connections: Arc<McpConnectionSet>,
client: Arc<ManagedClient>,
config: Arc<McpConfig>,
catalog_snapshot: Arc<ToolCatalogSnapshot>,
tool_info: PreparedToolInfo,
server_name: String,
server_metadata: McpServerMetadata,
plugin_id: Option<String>,
selected_plugin_server: bool,
}
/// The rules for a prepared call and the folders used to interpret them.
pub enum McpPermissionSource<'a> {
Environment {
environment_id: &'a str,
sandbox: &'a Arc<FileSystemSandboxContext>,
},
Thread {
profile: &'a PermissionProfile,
host_cwd: &'a AbsolutePathBuf,
},
}
impl<'a> McpPermissionSource<'a> {
pub fn profile(&self) -> &'a PermissionProfile {
match self {
Self::Environment { sandbox, .. } => &sandbox.permissions,
Self::Thread { profile, .. } => profile,
}
}
}
#[derive(Clone)]
pub(crate) struct PreparedToolInfo {
catalog: Arc<[ToolInfo]>,
index: usize,
}
impl PreparedToolInfo {
pub(crate) fn from_binding_catalog(catalog: Arc<[ToolInfo]>, index: usize) -> Self {
assert!(
index < catalog.len(),
"prepared tool index must refer to its binding catalog"
);
Self { catalog, index }
}
pub(crate) fn get(&self) -> &ToolInfo {
&self.catalog[self.index]
}
}
impl From<ToolInfo> for PreparedToolInfo {
fn from(tool_info: ToolInfo) -> Self {
Self {
catalog: Arc::new([tool_info]),
index: 0,
}
}
}
impl PreparedMcpCall {
#[expect(
clippy::too_many_arguments,
reason = "the exact call authority stays together"
)]
pub(crate) fn new(
connections: Arc<McpConnectionSet>,
client: Arc<ManagedClient>,
config: Arc<McpConfig>,
catalog_snapshot: Arc<ToolCatalogSnapshot>,
tool_info: impl Into<PreparedToolInfo>,
server_metadata: McpServerMetadata,
plugin_id: Option<String>,
selected_plugin_server: bool,
) -> Option<Self> {
let tool_info = tool_info.into();
let server_name = tool_info.get().server_name.clone();
config.permission_profile_for_server(&server_name)?;
Some(Self {
connections,
client,
config,
catalog_snapshot,
tool_info,
server_name,
server_metadata,
plugin_id,
selected_plugin_server,
})
}
pub fn tool_info(&self) -> &ToolInfo {
self.tool_info.get()
}
/// Whether the server connection that issued the step's tools still owns this call.
pub fn uses_connection_from(&self, binding: &McpBinding) -> bool {
self.connections
.shares_server_connection(&binding.connections, &self.server_name)
}
/// Returns the configuration and approval authority captured with this client.
pub fn config(&self) -> &McpConfig {
&self.config
}
/// A hosted app can run through the local server but use thread rules, not local environment rules.
pub fn permission_source(&self) -> McpPermissionSource<'_> {
// The constructor only prepares calls with an entry in this immutable config.
match &self.config.server_permissions[&self.server_name] {
McpServerPermissions::Environment(sandbox) => McpPermissionSource::Environment {
environment_id: self.server_environment_id(),
sandbox,
},
McpServerPermissions::Thread => McpPermissionSource::Thread {
profile: &self.config.permission_profile,
host_cwd: &self.config.host_cwd,
},
}
}
/// Returns the owner permissions validated when this immutable call was prepared.
pub fn permission_profile(&self) -> &PermissionProfile {
self.permission_source().profile()
}
/// Attach policy aliases and the server-host launcher, replacing stale authority.
/// Callers negotiate the state capability before requesting this metadata.
pub async fn augment_sandbox_metadata(
&self,
meta: &mut Option<JsonValue>,
state: crate::SandboxState,
) -> Result<()> {
crate::sandbox_metadata::augment_metadata(
meta,
state,
self.sandbox_codex_executable().await,
)
}
/// Full CLI path usable by a local stdio server. An HTTP endpoint (even on
/// loopback) or remote executor does not establish a shared filesystem.
/// Capability probes are cached process-wide by absolute executable path.
pub async fn sandbox_codex_executable(&self) -> Option<AbsolutePathBuf> {
let server = self
.config
.mcp_server_catalog
.server(&self.server_name)?
.config();
if self.server_environment_id() != akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID
|| !server.is_local_environment()
|| !matches!(
server.transport,
akode_config::McpServerTransportConfig::Stdio { .. }
)
{
return None;
}
// Require a literal absolute path before the constructor can expand `~`.
let executable = self
.config
.codex_self_exe
.as_deref()
.filter(|path| path.is_absolute() && path.to_str().is_some())?;
let executable = AbsolutePathBuf::from_absolute_path_checked(executable).ok()?;
crate::sandbox_executable::supports_sandbox_state(&executable)
.await
.then_some(executable)
}
pub fn server_name(&self) -> &str {
&self.server_name
}
pub fn server_origin(&self) -> Option<&str> {
self.server_metadata
.origin
.as_ref()
.map(super::server::McpServerOrigin::as_str)
}
pub fn server_environment_id(&self) -> &str {
&self.server_metadata.environment_id
}
pub fn server_pollutes_memory(&self) -> bool {
self.server_metadata.pollutes_memory
}
pub fn tool_approval_mode(&self) -> AppToolApproval {
self.server_metadata
.tool_approval_mode(&self.tool_info().tool.name)
}
/// Returns the explicit output budget captured with this call's effective server config.
pub fn output_token_limit(&self) -> Option<usize> {
self.config
.mcp_server_catalog
.server(&self.server_name)?
.config()
.tools
.get(self.tool_info().tool.name.as_ref())?
.output_token_limit
.map(std::num::NonZeroUsize::get)
}
pub fn plugin_id(&self) -> Option<&str> {
self.plugin_id.as_deref()
}
pub fn is_selected_plugin_server(&self) -> bool {
self.selected_plugin_server
}
pub async fn server_supports_sandbox_state_meta_capability(&self) -> Result<bool> {
Ok(self.client.server_supports_sandbox_state_meta_capability)
}
pub async fn call(
&self,
arguments: Option<JsonValue>,
meta: Option<JsonValue>,
timeout: Option<Duration>,
) -> Result<CallToolResult> {
self.call_with_preparation(timeout, || async move { Ok((arguments, meta)) })
.await
}
/// Runs irreversible call preparation and execution under the authority of
/// this call's captured catalog and the extensions owned by the Codex session.
/// A caller-supplied timeout can further restrict the server's configured timeout.
pub async fn call_with_preparation<F, Fut>(
&self,
requested_timeout: Option<Duration>,
prepare: F,
) -> Result<CallToolResult>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<(Option<JsonValue>, Option<JsonValue>)>>,
{
let effective_timeout = match (self.client.tool_timeout, requested_timeout) {
(Some(server_timeout), Some(requested_timeout)) => {
Some(server_timeout.min(requested_timeout))
}
(server_timeout, requested_timeout) => server_timeout.or(requested_timeout),
};
let tool_name = self.tool_info().tool.name.to_string();
let operation =
self.client
.tool_catalog
.run_with_snapshot(&self.catalog_snapshot, || async {
let (arguments, meta) = prepare().await?;
let timeout_deadline =
effective_timeout.map(|timeout| tokio::time::Instant::now() + timeout);
let remaining_timeout = match effective_timeout.zip(timeout_deadline) {
Some((timeout, deadline)) => {
let remaining =
deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
return Err(akode_rmcp_client::request_timeout_error(
"tools/call",
timeout,
));
}
Some(remaining)
}
None => None,
};
self.client
.call_tool(
tool_name.clone(),
arguments,
self.connections.network_policy_meta_for_call(
&self.client,
Some(self.permission_profile()),
self.server_environment_id(),
meta,
),
remaining_timeout,
)
.await
.with_context(|| {
format!("tool call failed for `{}/{tool_name}`", self.server_name)
})
});
self.client
.with_active_shared_lease(operation)
.await?
.ok_or_else(|| anyhow::anyhow!(
"tool call rejected because the catalog changed after `{}/{tool_name}` was prepared",
self.server_name
))?
.map(call_tool_result_from_rmcp)
}
}
pub(crate) fn call_tool_result_from_rmcp(result: rmcp::model::CallToolResult) -> CallToolResult {
let content = result
.content
.into_iter()
.map(|content| {
serde_json::to_value(content)
.unwrap_or_else(|_| JsonValue::String("<content>".to_string()))
})
.collect();
CallToolResult {
content,
structured_content: result.structured_content,
is_error: result.is_error,
meta: result.meta.and_then(|meta| serde_json::to_value(meta).ok()),
}
}
#[cfg(test)]
#[path = "binding_tests.rs"]
mod tests;

View File

@@ -0,0 +1,153 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use rmcp::model::Resource;
use rmcp::model::ResourceTemplate;
use tokio::task::JoinSet;
use tracing::warn;
use crate::pagination::collect_paginated;
use crate::rmcp_client::ManagedClient;
/// The ready clients captured for one model step.
pub(crate) struct McpBindingClients {
clients: HashMap<String, Arc<ManagedClient>>,
}
impl McpBindingClients {
pub(crate) fn new(clients: HashMap<String, Arc<ManagedClient>>) -> Self {
Self { clients }
}
pub(crate) fn client(&self, server: &str) -> Option<Arc<ManagedClient>> {
self.clients.get(server).cloned()
}
pub(crate) async fn list_resources(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourcesResult> {
let managed = self
.client(server)
.ok_or_else(|| anyhow!("MCP server '{server}' was not ready for this step"))?;
managed
.list_resources(params, managed.tool_timeout)
.await
.with_context(|| format!("resources/list failed for `{server}`"))
}
pub(crate) async fn list_resource_templates(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourceTemplatesResult> {
let managed = self
.client(server)
.ok_or_else(|| anyhow!("MCP server '{server}' was not ready for this step"))?;
managed
.list_resource_templates(params, managed.tool_timeout)
.await
.with_context(|| format!("resources/templates/list failed for `{server}`"))
}
pub(crate) async fn read_resource(
&self,
server: &str,
params: ReadResourceRequestParams,
) -> Result<ReadResourceResult> {
let managed = self
.client(server)
.ok_or_else(|| anyhow!("MCP server '{server}' was not ready for this step"))?;
let uri = params.uri.clone();
managed
.read_resource(params, managed.tool_timeout)
.await
.with_context(|| format!("resources/read failed for `{server}` ({uri})"))
}
pub(crate) async fn list_all_resources(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<Resource>> {
let mut join_set = JoinSet::new();
for (server_name, managed) in self
.clients
.iter()
.filter(|(server_name, _)| include_server(server_name))
{
let server_name = server_name.clone();
let client = Arc::clone(managed);
let timeout = managed.tool_timeout;
join_set.spawn(async move {
let resources = collect_paginated("resources/list", timeout, |params| {
let client = Arc::clone(&client);
async move {
let response = client.list_resources(params, timeout).await?;
Ok((response.resources, response.next_cursor))
}
})
.await;
(server_name, resources)
});
}
collect_resource_results(&mut join_set, "resources").await
}
pub(crate) async fn list_all_resource_templates(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<ResourceTemplate>> {
let mut join_set = JoinSet::new();
for (server_name, managed) in self
.clients
.iter()
.filter(|(server_name, _)| include_server(server_name))
{
let server_name = server_name.clone();
let client = Arc::clone(managed);
let timeout = managed.tool_timeout;
join_set.spawn(async move {
let templates = collect_paginated("resources/templates/list", timeout, |params| {
let client = Arc::clone(&client);
async move {
let response = client.list_resource_templates(params, timeout).await?;
Ok((response.resource_templates, response.next_cursor))
}
})
.await;
(server_name, templates)
});
}
collect_resource_results(&mut join_set, "resource templates").await
}
}
async fn collect_resource_results<T: Send + 'static>(
join_set: &mut JoinSet<(String, Result<Vec<T>>)>,
kind: &str,
) -> HashMap<String, Vec<T>> {
let mut resources = HashMap::new();
while let Some(result) = join_set.join_next().await {
match result {
Ok((server, Ok(server_resources))) => {
resources.insert(server, server_resources);
}
Ok((server, Err(error))) => {
warn!("Failed to list {kind} for MCP server '{server}': {error:#}");
}
Err(error) => {
warn!("Task panic when listing {kind} for MCP server: {error:#}");
}
}
}
resources
}

View File

@@ -0,0 +1,503 @@
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use akode_config::AppToolApproval;
use akode_config::Constrained;
use akode_config::types::ApprovalsReviewer;
use akode_exec_server::FileSystemSandboxContext;
use akode_protocol::mcp::McpServerInfo;
use akode_protocol::models::PermissionProfile;
use akode_protocol::protocol::AskForApproval;
use akode_rmcp_client::InProcessTransportFactory;
use akode_rmcp_client::RmcpClient;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use rmcp::model::JsonObject;
use rmcp::model::Tool;
use tokio::io::DuplexStream;
use super::McpBinding;
use super::McpPermissionSource;
use super::PreparedMcpCall;
use crate::McpServerPermissions;
use crate::binding_clients::McpBindingClients;
use crate::client_tool_catalog::ClientToolCatalog;
use crate::connection_manager::McpConnectionSet;
use crate::rmcp_client::ManagedClient;
use crate::server::McpServerMetadata;
use crate::server::McpServerOrigin;
use crate::tools::ToolInfo;
const SERVER_NAME: &str = "docs";
const TOOL_NAME: &str = "search";
struct TestInProcessTransportFactory;
impl InProcessTransportFactory for TestInProcessTransportFactory {
fn open(&self) -> futures::future::BoxFuture<'static, io::Result<DuplexStream>> {
async {
let (client_stream, _server_stream) = tokio::io::duplex(1);
Ok(client_stream)
}
.boxed()
}
}
struct TestStep {
step: Arc<McpBinding>,
client: Arc<RmcpClient>,
tool_catalog: Arc<ClientToolCatalog>,
}
async fn test_step(
label: &str,
approval_mode: AppToolApproval,
supports_sandbox_state_meta: bool,
) -> TestStep {
let tool = ToolInfo {
server_name: SERVER_NAME.to_string(),
supports_parallel_tool_calls: false,
server_origin: None,
callable_name: TOOL_NAME.to_string(),
callable_namespace: SERVER_NAME.to_string(),
namespace_description: None,
tool: Tool::new(
TOOL_NAME.to_string(),
format!("{label} catalog"),
Arc::new(JsonObject::default()),
),
plugin_display_names: Vec::new(),
};
let client = Arc::new(
RmcpClient::new_in_process_client(Arc::new(TestInProcessTransportFactory))
.await
.expect("create in-process MCP client"),
);
let tool_catalog = Arc::new(ClientToolCatalog::new(
vec![tool.clone()],
/*meta*/ None));
let managed_client = Arc::new(ManagedClient {
connection_sharing: Default::default(),
shared_elicitation: None,
_auth_change_notifications: None,
client: Arc::clone(&client),
server_info: McpServerInfo {
name: label.to_string(),
title: Some(format!("{label} server")),
version: "1.0.0".to_string(),
description: None,
icons: None,
website_url: None,
},
tool_catalog: Arc::clone(&tool_catalog),
tool_timeout: None,
server_instructions: None,
server_supports_sandbox_state_meta_capability: supports_sandbox_state_meta,
client_supports_network_policy_meta_capability: false,
});
let clients = Arc::new(McpBindingClients::new(HashMap::from([(
SERVER_NAME.to_string(),
Arc::clone(&managed_client),
)])));
let connections = Arc::new(McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true));
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
config.host_cwd = config.host_cwd.join(label);
config.environment_cwds.insert(
akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
akode_utils_path_uri::PathUri::from_abs_path(&config.host_cwd.join("executor")),
);
let server_permissions = if label == "old" {
config.approval_policy = Constrained::allow_any(AskForApproval::Never);
config.permission_profile = PermissionProfile::Disabled;
let mut sandbox = FileSystemSandboxContext::from_permission_profile(
PermissionProfile::read_only(),
PathUri::from_abs_path(&config.host_cwd.join("executor")),
);
sandbox.user_home_dir = Some(PathUri::from_abs_path(&config.host_cwd.join("home")));
sandbox.temporary_directories =
Some(vec![PathUri::from_abs_path(&config.host_cwd.join("tmp"))]);
McpServerPermissions::Environment(Arc::new(sandbox))
} else {
config.approvals_reviewer = ApprovalsReviewer::AutoReview;
McpServerPermissions::Thread
};
config
.server_permissions
.insert(SERVER_NAME.to_string(), server_permissions);
config
.environment_use_mxc
.insert(format!("{label}-environment"), label == "new");
let config = Arc::new(config);
let prepared = PreparedMcpCall::new(
Arc::clone(&connections),
managed_client,
Arc::clone(&config),
tool_catalog.read(Arc::new).await,
tool.clone(),
McpServerMetadata {
environment_id: format!("{label}-environment"),
pollutes_memory: label == "old",
origin: Some(McpServerOrigin::StreamableHttp(format!(
"https://{label}.example"
))),
supports_parallel_tool_calls: false,
default_tools_approval_mode: Some(approval_mode),
tool_approval_modes: HashMap::new(),
},
Some(format!("{label}-plugin")),
label == "old",
)
.expect("test call should have a permission source");
let calls = HashMap::from([((SERVER_NAME.to_string(), TOOL_NAME.to_string()), prepared)]);
TestStep {
step: Arc::new(McpBinding::new(
connections,
clients,
config,
/*plugins_available*/ false,
vec![tool],
calls,
)),
client,
tool_catalog,
}
}
#[tokio::test]
async fn prepared_call_keeps_captured_connection_and_authority_after_refresh() -> anyhow::Result<()>
{
let old = test_step(
"old",
AppToolApproval::Prompt,
/*supports_sandbox_state_meta*/ true,
)
.await;
let old_call = old
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("old step should prepare the advertised tool");
let old_connections = Arc::downgrade(&old.step.connections);
let new = test_step(
"new",
AppToolApproval::Approve,
/*supports_sandbox_state_meta*/ false,
)
.await;
let new_call = new
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("new step should prepare the advertised tool");
assert_eq!(
(
old.step.tools()[0].tool.description.as_deref(),
old_call.tool_info().tool.description.as_deref(),
old_call.server_origin(),
old_call.server_environment_id(),
old_call.server_pollutes_memory(),
old_call.tool_approval_mode(),
old_call.plugin_id(),
old_call.is_selected_plugin_server(),
old_call
.server_supports_sandbox_state_meta_capability()
.await?,
),
(
Some("old catalog"),
Some("old catalog"),
Some("https://old.example"),
"old-environment",
true,
AppToolApproval::Prompt,
Some("old-plugin"),
true,
true,
)
);
assert_eq!(
(
new.step.tools()[0].tool.description.as_deref(),
new_call.tool_info().tool.description.as_deref(),
new_call.server_environment_id(),
new_call.tool_approval_mode(),
),
(
Some("new catalog"),
Some("new catalog"),
"new-environment",
AppToolApproval::Approve,
)
);
assert!(Arc::ptr_eq(&old_call.client.client, &old.client));
assert!(!Arc::ptr_eq(&old.client, &new.client));
let McpPermissionSource::Environment { sandbox, .. } = old_call.permission_source() else {
anyhow::bail!("expected the old call to keep its environment permissions");
};
let old_root = AbsolutePathBuf::current_dir()?.join("old");
assert_eq!(
(
&sandbox.cwd,
&sandbox.user_home_dir,
&sandbox.temporary_directories
),
(
&PathUri::from_abs_path(&old_root.join("executor")),
&Some(PathUri::from_abs_path(&old_root.join("home"))),
&Some(vec![PathUri::from_abs_path(&old_root.join("tmp"))]),
),
);
let McpPermissionSource::Thread { host_cwd, .. } = new_call.permission_source() else {
anyhow::bail!("expected thread permissions");
};
assert_eq!(host_cwd, &AbsolutePathBuf::current_dir()?.join("new"));
assert_eq!(
(
old_call.config().approval_policy.value(),
old_call.permission_profile(),
old_call.config().approvals_reviewer,
old_call.config().environment_use_mxc.get("old-environment"),
),
(
AskForApproval::Never,
&PermissionProfile::read_only(),
ApprovalsReviewer::User,
Some(&false),
)
);
assert_eq!(
(
new_call.config().approval_policy.value(),
new_call.config().approvals_reviewer,
new_call.config().environment_use_mxc.get("new-environment"),
),
(
AskForApproval::OnRequest,
ApprovalsReviewer::AutoReview,
Some(&true)
)
);
drop(old.step);
assert!(
old_connections.upgrade().is_some(),
"the prepared call should keep its captured connection set alive"
);
drop(old_call);
assert!(
old_connections.upgrade().is_none(),
"the captured connection set should be released with the prepared call"
);
Ok(())
}
#[tokio::test]
async fn prepared_call_does_not_reroute_after_captured_connection_closes() {
let old = test_step(
"old",
AppToolApproval::Prompt,
/*supports_sandbox_state_meta*/ true,
)
.await;
let old_call = old
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("old step should prepare the advertised tool");
let new = test_step(
"new",
AppToolApproval::Approve,
/*supports_sandbox_state_meta*/ false,
)
.await;
assert!(!Arc::ptr_eq(&old.client, &new.client));
old.client.shutdown().await;
let error = old_call
.call(
Some(serde_json::json!({"query": "codex"})),
/*meta*/ None,
/*timeout*/ None,
)
.await
.expect_err("a call bound to a closed connection must fail");
assert!(
format!("{error:#}").contains("MCP client is shut down"),
"the prepared call should fail on its captured client: {error:#}"
);
}
#[tokio::test]
async fn prepared_call_is_rejected_after_catalog_refresh() {
let step = test_step(
"old",
AppToolApproval::Prompt,
/*supports_sandbox_state_meta*/ true,
)
.await;
let prepared = step
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("step should prepare the advertised tool");
let mut changed_tools = step.step.tools().to_vec();
changed_tools[0].tool.description = Some("changed".into());
step.tool_catalog.replace_for_test(changed_tools).await;
let error = prepared
.call(
Some(serde_json::json!({"query": "codex"})),
/*meta*/ None,
/*timeout*/ None,
)
.await
.expect_err("a call from an older catalog must be rejected");
assert!(
format!("{error:#}").contains("catalog changed"),
"unexpected error: {error:#}"
);
}
#[tokio::test]
async fn stale_prepared_call_does_not_run_preparation() {
let step = test_step(
"old",
AppToolApproval::Prompt,
/*supports_sandbox_state_meta*/ true,
)
.await;
let prepared = step
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("step should prepare the advertised tool");
let mut changed_tools = step.step.tools().to_vec();
changed_tools[0].tool.description = Some("changed".into());
step.tool_catalog.replace_for_test(changed_tools).await;
let prepared_side_effect_ran = Arc::new(AtomicBool::new(false));
let marker = Arc::clone(&prepared_side_effect_ran);
prepared
.call_with_preparation(/*requested_timeout*/ None, || async move {
marker.store(true, Ordering::SeqCst);
Ok((None, None))
})
.await
.expect_err("a call from an older catalog must be rejected");
assert!(!prepared_side_effect_ran.load(Ordering::SeqCst));
}
#[tokio::test]
async fn sandbox_executable_requires_local_stdio_and_a_full_cli() -> anyhow::Result<()> {
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
let step = test_step(
"old",
AppToolApproval::Approve,
/*supports_sandbox_state_meta*/ true,
)
.await;
let call = step
.step
.prepare_call(SERVER_NAME, TOOL_NAME)
.expect("prepared call");
// Use a probe-capable CLI so remote/HTTP exclusions cannot pass merely
// because the supplied executable lacks the sandbox capability.
let executable = akode_utils_cargo_bin::cargo_bin("akode")?;
for (server, runtime_environment, path, expected) in [
(
serde_json::json!({"command": "mcp"}),
"local",
Some(executable.clone()),
Some(AbsolutePathBuf::from_absolute_path_checked(&executable)?),
),
// The Rust test harness accepts `sandbox --help`, but must not be
// advertised as a sandbox launcher: it lacks `--sandbox-state-json`.
(
serde_json::json!({"command": "mcp"}),
"local",
Some(std::env::current_exe()?),
None,
),
(serde_json::json!({"command": "mcp"}), "local", None, None),
#[cfg(unix)]
(
serde_json::json!({"command": "mcp"}),
"local",
Some(std::ffi::OsStr::from_bytes(b"/non-utf8-\xff/codex").into()),
None,
),
(
serde_json::json!({"command": "mcp"}),
"local",
Some("codex".into()),
None,
),
(
serde_json::json!({"command": "mcp", "environment_id": "remote"}),
"remote",
Some(executable.clone()),
None,
),
(
serde_json::json!({"command": "mcp"}),
"remote",
Some(executable.clone()),
None,
),
(
serde_json::json!({"url": "http://127.0.0.1:8080/mcp"}),
"local",
Some(executable),
None,
),
] {
let mut call = call.clone();
let config = Arc::make_mut(&mut call.config);
config.codex_self_exe = path;
let mut catalog = crate::ResolvedMcpCatalog::builder();
catalog.register(crate::McpServerRegistration::from_config(
SERVER_NAME.to_owned(),
serde_json::from_value(server)?,
));
config.mcp_server_catalog = catalog.build();
call.server_metadata.environment_id = runtime_environment.to_owned();
assert_eq!(call.sandbox_codex_executable().await, expected);
let state = crate::SandboxState {
permission_profile: PermissionProfile::default(),
codex_linux_sandbox_exe: None,
sandbox_cwd: akode_utils_path_uri::PathUri::from_host_native_path(
std::env::current_dir()?,
)?,
use_legacy_landlock: false,
use_mxc: false,
};
let expected_state = serde_json::to_value(&state)?;
let mut metadata = Some(serde_json::json!({
"unrelated": "retained",
"codex/sandbox-state": {"stale": true},
"codex/sandbox-state-meta": {"different": true},
"codex/sandbox-launcher": {"codexExecutable": "must-not-survive"},
}));
call.augment_sandbox_metadata(&mut metadata, state).await?;
let mut expected_metadata = serde_json::json!({
"unrelated": "retained",
"codex/sandbox-state": expected_state,
"codex/sandbox-state-meta": expected_state,
});
if let Some(executable) = expected {
expected_metadata["codex/sandbox-launcher"] =
serde_json::json!({"codexExecutable": executable});
}
assert_eq!(metadata, Some(expected_metadata));
}
Ok(())
}

View File

@@ -0,0 +1,668 @@
use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use akode_config::McpServerConfig;
use akode_config::McpServerDisabledReason;
use akode_config::McpServerTransportConfig;
use akode_config::RequirementSource;
use akode_protocol::mcp_policy::EnvironmentMcpPolicy;
use akode_utils_path_uri::PathUri;
use crate::McpProtocolMode;
use crate::server::McpCredentialPolicy;
/// Plugin identity retained with an MCP registration for tool attribution.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct McpPluginAttribution {
plugin_id: String,
display_name: String,
agent_plugin: bool,
host_root: Option<PathUri>,
}
impl McpPluginAttribution {
pub fn new(plugin_id: String, display_name: String) -> Self {
Self {
plugin_id,
display_name,
agent_plugin: false,
host_root: None,
}
}
pub fn agent_plugin(plugin_id: String, display_name: String) -> Self {
Self {
plugin_id,
display_name,
agent_plugin: true,
host_root: None,
}
}
/// Records the exact host-discovered plugin root.
pub fn with_host_root(mut self, host_root: PathUri) -> Self {
self.host_root = Some(host_root);
self
}
pub fn plugin_id(&self) -> &str {
&self.plugin_id
}
pub fn display_name(&self) -> &str {
&self.display_name
}
pub fn is_agent_plugin(&self) -> bool {
self.agent_plugin
}
/// Returns the host-discovered root captured with this server registration.
pub fn host_root(&self) -> Option<&PathUri> {
self.host_root.as_ref()
}
}
/// The component that declared an MCP server registration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum McpServerSource {
/// A plugin discovered through the process-wide legacy plugin manager.
Plugin(McpPluginAttribution),
/// A plugin explicitly selected for this thread through a capability root.
SelectedPlugin(McpPluginAttribution),
Config,
Compatibility {
id: String,
},
Extension {
id: String,
},
}
impl McpServerSource {
pub fn is_agent_plugin(&self) -> bool {
match self {
Self::Plugin(attribution) | Self::SelectedPlugin(attribution) => {
attribution.is_agent_plugin()
}
Self::Config | Self::Compatibility { .. } | Self::Extension { .. } => false,
}
}
fn disabled_registration_is_name_veto(&self) -> bool {
// A selected package's policy applies to its registration, not to a higher runtime source
// that happens to use the same logical server name.
!matches!(self, Self::SelectedPlugin(_))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum RegistrationPrecedence {
Plugin(Reverse<usize>),
SelectedPlugin(Reverse<usize>),
Config,
Compatibility,
Extension(usize),
}
impl RegistrationPrecedence {
fn tier(self) -> u8 {
match self {
Self::Plugin(_) => 0,
Self::SelectedPlugin(_) => 1,
Self::Config => 2,
Self::Compatibility => 3,
Self::Extension(_) => 4,
}
}
}
/// One named MCP server declaration before source resolution.
#[derive(Clone, Debug, PartialEq)]
pub struct McpServerRegistration {
name: String,
source: McpServerSource,
config: McpServerConfig,
credential_policy: McpCredentialPolicy,
protocol_mode: Option<McpProtocolMode>,
precedence: RegistrationPrecedence,
}
impl McpServerRegistration {
/// Registers host-owned configuration, which may resolve credentials on the host.
pub fn from_config(name: String, config: McpServerConfig) -> Self {
Self::new(
name,
McpServerSource::Config,
config,
RegistrationPrecedence::Config,
McpCredentialPolicy::HostFallbackAllowed,
)
}
/// Registers executor-discovered configuration without authority to read
/// host environment credentials.
pub fn from_executor_config(name: String, config: McpServerConfig) -> Self {
Self::new(
name,
McpServerSource::Config,
config,
RegistrationPrecedence::Config,
McpCredentialPolicy::ExecutorOnly,
)
}
/// Registers a plugin discovered by the host's process-wide plugin manager.
pub fn from_plugin(
name: String,
attribution: McpPluginAttribution,
plugin_order: usize,
config: McpServerConfig,
) -> Self {
Self::new(
name,
McpServerSource::Plugin(attribution),
config,
RegistrationPrecedence::Plugin(Reverse(plugin_order)),
McpCredentialPolicy::HostFallbackAllowed,
)
}
/// Registers a thread-selected plugin above discovered plugins and below config.
/// HTTP credential authority comes from the selected root, not the server's execution environment.
pub fn from_selected_plugin(
name: String,
attribution: McpPluginAttribution,
selection_order: usize,
source_environment_id: &str,
config: McpServerConfig,
) -> Self {
let credential_policy = if source_environment_id != DEFAULT_MCP_SERVER_ENVIRONMENT_ID
&& matches!(
&config.transport,
McpServerTransportConfig::StreamableHttp { .. }
) {
McpCredentialPolicy::ExecutorOnly
} else {
McpCredentialPolicy::HostFallbackAllowed
};
Self::new(
name,
McpServerSource::SelectedPlugin(attribution),
config,
RegistrationPrecedence::SelectedPlugin(Reverse(selection_order)),
credential_policy,
)
}
pub fn from_compatibility(
name: String,
id: impl Into<String>,
config: McpServerConfig,
) -> Self {
Self::new(
name,
McpServerSource::Compatibility { id: id.into() },
config,
RegistrationPrecedence::Compatibility,
McpCredentialPolicy::HostFallbackAllowed,
)
}
pub fn from_extension(
name: String,
id: impl Into<String>,
contribution_order: usize,
config: McpServerConfig,
) -> Self {
Self::new(
name,
McpServerSource::Extension { id: id.into() },
config,
RegistrationPrecedence::Extension(contribution_order),
McpCredentialPolicy::HostFallbackAllowed,
)
}
/// Overrides the protocol for this registration if it wins HTTP server resolution.
pub fn with_protocol_mode(mut self, protocol_mode: McpProtocolMode) -> Self {
self.protocol_mode = Some(protocol_mode);
self
}
fn new(
name: String,
source: McpServerSource,
config: McpServerConfig,
precedence: RegistrationPrecedence,
credential_policy: McpCredentialPolicy,
) -> Self {
Self {
name,
source,
config,
credential_policy,
protocol_mode: None,
precedence,
}
}
}
/// The authority available for MCP servers running in one environment.
#[derive(Clone, Copy, Debug)]
pub enum McpEnvironmentAuthority<'a> {
/// The selected environment adds no restrictions to the controller policy.
Unrestricted,
/// The owner supplied the final restrictions for this environment.
Restricted(&'a EnvironmentMcpPolicy),
/// An explicitly selected plugin can use its executor without attaching that executor.
SelectedPluginsOnly,
/// The attachment is pending or failed, so its owner policy is not available.
Unavailable,
}
/// One side of an MCP server conflict, including whether it registers or
/// removes the server.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum McpServerConflictAction {
Register(McpServerSource),
Remove(McpServerSource),
}
/// A same-tier name collision and the final outcome after all precedence is applied.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct McpServerConflict {
pub name: String,
pub outcome: McpServerConflictAction,
pub contenders: Vec<McpServerConflictAction>,
}
#[derive(Clone, Debug)]
enum CatalogAction {
Register(Box<McpServerRegistration>),
Remove {
name: String,
source: McpServerSource,
precedence: RegistrationPrecedence,
},
}
impl CatalogAction {
fn name(&self) -> &str {
match self {
Self::Register(registration) => &registration.name,
Self::Remove { name, .. } => name,
}
}
fn precedence(&self) -> RegistrationPrecedence {
match self {
Self::Register(registration) => registration.precedence,
Self::Remove { precedence, .. } => *precedence,
}
}
fn conflict_action(&self) -> McpServerConflictAction {
match self {
Self::Register(registration) => {
McpServerConflictAction::Register(registration.source.clone())
}
Self::Remove { source, .. } => McpServerConflictAction::Remove(source.clone()),
}
}
}
/// Mutable inputs used to produce an immutable resolved catalog.
#[derive(Clone, Debug, Default)]
pub struct McpCatalogBuilder {
actions: Vec<CatalogAction>,
disabled_server_names: BTreeSet<String>,
requirements_disabled_server_names: BTreeMap<String, RequirementSource>,
}
impl McpCatalogBuilder {
pub fn register(&mut self, registration: McpServerRegistration) {
self.actions
.push(CatalogAction::Register(Box::new(registration)));
}
/// Applies the legacy name-scoped disabled veto after source resolution.
pub fn disable(&mut self, name: String) {
self.disabled_server_names.insert(name);
}
pub fn remove_compatibility(&mut self, name: String, id: impl Into<String>) {
self.actions.push(CatalogAction::Remove {
name,
source: McpServerSource::Compatibility { id: id.into() },
precedence: RegistrationPrecedence::Compatibility,
});
}
pub fn remove_extension(
&mut self,
name: String,
id: impl Into<String>,
contribution_order: usize,
) {
self.actions.push(CatalogAction::Remove {
name,
source: McpServerSource::Extension { id: id.into() },
precedence: RegistrationPrecedence::Extension(contribution_order),
});
}
/// Applies environment authority before resolving immutable server registrations.
pub fn build_with_environment_authority<'a>(
mut self,
mut authority_for_environment: impl FnMut(&str) -> McpEnvironmentAuthority<'a>,
) -> ResolvedMcpCatalog {
for action in &mut self.actions {
let CatalogAction::Register(registration) = action else {
continue;
};
// Existing managed denials are not attachment-owned.
if !registration.config.enabled {
continue;
}
let allowed = match authority_for_environment(&registration.config.environment_id) {
McpEnvironmentAuthority::Unrestricted => true,
McpEnvironmentAuthority::SelectedPluginsOnly => {
matches!(&registration.source, McpServerSource::SelectedPlugin(_))
}
McpEnvironmentAuthority::Unavailable => false,
McpEnvironmentAuthority::Restricted(policy) => match &registration.source {
McpServerSource::Config
| McpServerSource::Compatibility { .. }
| McpServerSource::Extension { .. } => {
policy.servers.as_ref().is_none_or(|requirements| {
requirements
.get(&registration.name)
.is_some_and(|requirement| {
registration.config.matches_requirement(requirement)
})
})
}
McpServerSource::Plugin(attribution)
| McpServerSource::SelectedPlugin(attribution) => {
// Empty server policy denies every plugin; otherwise use package policy.
!policy.servers.as_ref().is_some_and(BTreeMap::is_empty)
&& policy
.plugins
.as_ref()
.filter(|plugins| {
plugins.values().any(|plugin| plugin.mcp_servers.is_some())
})
.is_none_or(|plugins| {
plugins
.get(attribution.plugin_id())
.and_then(|plugin| plugin.mcp_servers.as_ref())
.and_then(|requirements| {
requirements.get(&registration.name)
})
.is_some_and(|requirement| {
registration.config.matches_requirement(requirement)
})
})
}
},
};
if !allowed {
registration.config.enabled = false;
registration.config.disabled_reason = Some(McpServerDisabledReason::Requirements {
source: RequirementSource::Unknown,
});
}
}
self.build()
}
pub fn build(mut self) -> ResolvedMcpCatalog {
// Stable sorting makes action order the tie-breaker when precedence is equal.
self.actions.sort_by_key(CatalogAction::precedence);
let mut winners = BTreeMap::<String, CatalogAction>::new();
let mut actions_by_name_and_tier = BTreeMap::<(String, u8), Vec<&CatalogAction>>::new();
for action in &self.actions {
winners.insert(action.name().to_string(), action.clone());
actions_by_name_and_tier
.entry((action.name().to_string(), action.precedence().tier()))
.or_default()
.push(action);
}
let mut conflicts = Vec::new();
for ((name, _), actions) in actions_by_name_and_tier {
if actions.len() < 2 {
continue;
}
let Some(outcome) = winners.get(&name).map(CatalogAction::conflict_action) else {
continue;
};
conflicts.push(McpServerConflict {
name,
outcome,
contenders: actions
.into_iter()
.map(CatalogAction::conflict_action)
.collect(),
});
}
let mut disabled_server_names = self.disabled_server_names;
let mut requirements_disabled_server_names = self.requirements_disabled_server_names;
let servers = winners
.into_iter()
.filter_map(|(name, action)| match action {
CatalogAction::Register(registration) => {
let mut registration = *registration;
let persist_disabled_name =
registration.source.disabled_registration_is_name_veto()
&& !(matches!(
registration.source,
McpServerSource::Plugin(_) | McpServerSource::SelectedPlugin(_)
) && matches!(
registration.config.auth,
akode_config::McpServerAuth::EmaAuth
));
if !registration.config.enabled && persist_disabled_name {
match &registration.config.disabled_reason {
Some(
McpServerDisabledReason::Requirements { source }
| McpServerDisabledReason::ExplicitAndRequirements { source },
) => {
requirements_disabled_server_names
.insert(name.clone(), source.clone());
if matches!(
registration.config.disabled_reason,
Some(McpServerDisabledReason::ExplicitAndRequirements { .. })
) {
disabled_server_names.insert(name.clone());
}
}
Some(McpServerDisabledReason::Unknown) | None => {
disabled_server_names.insert(name.clone());
}
}
}
if disabled_server_names.contains(&name) {
registration.config.enabled = false;
}
// Retain a previous registration's requirements denial so a later
// replacement is still blocked.
if let Some(source) = requirements_disabled_server_names.get(&name) {
registration.config.disable_by_requirements(source.clone());
}
if matches!(
registration.config.auth,
akode_config::McpServerAuth::EmaAuth
) {
// Enterprise-managed authorization was removed. Never start these
// servers, but do not turn the denial into a persistent name veto.
registration.config.enabled = false;
}
Some((
name,
ResolvedMcpServer {
source: registration.source,
config: registration.config,
credential_policy: registration.credential_policy,
protocol_mode: registration.protocol_mode,
},
))
}
CatalogAction::Remove { .. } => None,
})
.collect();
ResolvedMcpCatalog {
actions: self.actions,
disabled_server_names,
requirements_disabled_server_names,
servers,
conflicts,
}
}
}
/// A single winning MCP registration.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedMcpServer {
source: McpServerSource,
config: McpServerConfig,
credential_policy: McpCredentialPolicy,
protocol_mode: Option<McpProtocolMode>,
}
impl ResolvedMcpServer {
pub fn source(&self) -> &McpServerSource {
&self.source
}
pub fn config(&self) -> &McpServerConfig {
&self.config
}
pub(crate) fn credential_policy(&self) -> McpCredentialPolicy {
self.credential_policy
}
pub fn protocol_mode(&self) -> Option<McpProtocolMode> {
self.protocol_mode
}
}
/// Immutable result of MCP registration resolution.
#[derive(Clone, Debug, Default)]
pub struct ResolvedMcpCatalog {
actions: Vec<CatalogAction>,
disabled_server_names: BTreeSet<String>,
requirements_disabled_server_names: BTreeMap<String, RequirementSource>,
servers: BTreeMap<String, ResolvedMcpServer>,
conflicts: Vec<McpServerConflict>,
}
impl ResolvedMcpCatalog {
pub fn builder() -> McpCatalogBuilder {
McpCatalogBuilder::default()
}
pub fn to_builder(&self) -> McpCatalogBuilder {
McpCatalogBuilder {
actions: self.actions.clone(),
disabled_server_names: self.disabled_server_names.clone(),
requirements_disabled_server_names: self.requirements_disabled_server_names.clone(),
}
}
pub fn server(&self, name: &str) -> Option<&ResolvedMcpServer> {
self.servers.get(name)
}
pub fn configured_servers(&self) -> HashMap<String, McpServerConfig> {
self.servers
.iter()
.map(|(name, server)| (name.clone(), server.config.clone()))
.collect()
}
/// Returns whether both catalogs have the same winning servers and sources.
pub fn has_same_servers(&self, other: &Self) -> bool {
self.servers == other.servers
}
/// Replaces the resolved server set while preserving known sources.
///
/// # Panics
///
/// Panics if a materialized server is missing from the catalog.
pub fn with_materialized_servers(&self, servers: HashMap<String, McpServerConfig>) -> Self {
let mut builder = McpCatalogBuilder {
disabled_server_names: self.disabled_server_names.clone(),
requirements_disabled_server_names: self.requirements_disabled_server_names.clone(),
..Default::default()
};
for (name, config) in servers {
#[expect(
clippy::expect_used,
reason = "materialized servers must have catalog registrations"
)]
let previous = self
.server(&name)
.expect("materialized MCP server must have a catalog registration");
let source = previous.source.clone();
let precedence = match &source {
McpServerSource::Plugin(_) => RegistrationPrecedence::Plugin(Reverse(0)),
McpServerSource::SelectedPlugin(_) => {
RegistrationPrecedence::SelectedPlugin(Reverse(0))
}
McpServerSource::Config => RegistrationPrecedence::Config,
McpServerSource::Compatibility { .. } => RegistrationPrecedence::Compatibility,
McpServerSource::Extension { .. } => RegistrationPrecedence::Extension(0),
};
let credential_policy = previous.credential_policy();
let mut registration =
McpServerRegistration::new(name, source, config, precedence, credential_policy);
registration.protocol_mode = previous.protocol_mode();
builder.register(registration);
}
builder.build()
}
/// Returns package attribution for each winning plugin-owned server.
pub fn plugin_attributions_by_server_name(&self) -> HashMap<String, McpPluginAttribution> {
self.servers
.iter()
.filter_map(|(name, server)| match server.source() {
McpServerSource::Plugin(attribution)
| McpServerSource::SelectedPlugin(attribution) => {
Some((name.clone(), attribution.clone()))
}
McpServerSource::Config
| McpServerSource::Compatibility { .. }
| McpServerSource::Extension { .. } => None,
})
.collect()
}
/// Returns the names of winning servers supplied by thread-selected plugins.
pub(crate) fn selected_plugin_server_names(&self) -> impl Iterator<Item = &str> {
self.servers.iter().filter_map(|(name, server)| {
matches!(server.source(), McpServerSource::SelectedPlugin(_)).then_some(name.as_str())
})
}
pub fn conflicts(&self) -> &[McpServerConflict] {
&self.conflicts
}
}
#[cfg(test)]
#[path = "catalog_tests.rs"]
mod tests;

View File

@@ -0,0 +1,744 @@
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::time::Duration;
use akode_config::AppToolApproval;
use akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use akode_config::McpServerAuth;
use akode_config::McpServerConfig;
use akode_config::McpServerToolConfig;
use akode_config::McpServerTransportConfig;
use akode_protocol::mcp_policy::EnvironmentMcpPolicy;
use akode_protocol::mcp_policy::PluginMcpRequirements;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use crate::McpProtocolMode;
use crate::server::McpCredentialPolicy;
use super::McpEnvironmentAuthority;
use super::McpPluginAttribution;
use super::McpServerConflict;
use super::McpServerConflictAction;
use super::McpServerRegistration;
use super::McpServerSource;
use super::ResolvedMcpCatalog;
use super::ResolvedMcpServer;
fn server(url: &str) -> McpServerConfig {
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: url.to_string(),
bearer_token_env_var: None,
http_headers: None,
env_http_headers: None,
http_headers_helper: None,
},
environment_id: DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: true,
startup_readiness: Default::default(),
supports_parallel_tool_calls: true,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: Some(Duration::from_secs(7)),
tool_timeout_sec: Some(Duration::from_secs(11)),
default_tools_approval_mode: Some(AppToolApproval::Prompt),
enabled_tools: Some(vec!["read".to_string()]),
disabled_tools: Some(vec!["write".to_string()]),
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::from([(
"read".to_string(),
McpServerToolConfig {
approval_mode: Some(AppToolApproval::Approve),
..Default::default()
},
)]),
}
}
fn plugin(plugin_id: &str) -> McpPluginAttribution {
McpPluginAttribution::new(plugin_id.to_string(), plugin_id.to_string())
}
fn plugin_source(plugin_id: &str) -> McpServerSource {
McpServerSource::Plugin(plugin(plugin_id))
}
fn selected_plugin_source(plugin_id: &str) -> McpServerSource {
McpServerSource::SelectedPlugin(plugin(plugin_id))
}
fn compatibility_source(id: &str) -> McpServerSource {
McpServerSource::Compatibility { id: id.to_string() }
}
fn extension_source(id: &str) -> McpServerSource {
McpServerSource::Extension { id: id.to_string() }
}
fn register(source: McpServerSource) -> McpServerConflictAction {
McpServerConflictAction::Register(source)
}
fn remove(source: McpServerSource) -> McpServerConflictAction {
McpServerConflictAction::Remove(source)
}
#[test]
fn executor_credential_policy_survives_catalog_rebuilds_and_materialization() {
let mut config = server("https://executor.example/mcp");
config.environment_id = "remote".to_string();
let mut executor = ResolvedMcpCatalog::builder();
executor.register(McpServerRegistration::from_executor_config(
"docs".to_string(),
config.clone(),
));
let executor = executor.build();
let mut host = ResolvedMcpCatalog::builder();
host.register(McpServerRegistration::from_config(
"docs".to_string(),
config,
));
let host = host.build();
for catalog in [
executor.to_builder().build(),
executor.with_materialized_servers(executor.configured_servers()),
] {
assert_eq!(
catalog.server("docs").unwrap(),
executor.server("docs").unwrap(),
);
assert_eq!(
catalog.server("docs").unwrap().credential_policy(),
McpCredentialPolicy::ExecutorOnly,
);
assert!(!catalog.has_same_servers(&host));
}
assert_eq!(
host.server("docs").unwrap().credential_policy(),
McpCredentialPolicy::HostFallbackAllowed,
);
}
#[test]
#[should_panic(expected = "materialized MCP server must have a catalog registration")]
fn materialized_server_requires_catalog_registration() {
let catalog = ResolvedMcpCatalog::default();
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://executor.example/mcp",
"environment_id": "remote",
"bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
}))
.expect("valid MCP server config");
catalog.with_materialized_servers(HashMap::from([("unregistered".to_string(), server)]));
}
#[test]
fn selected_plugin_credential_policy_follows_origin_and_survives_catalog_rebuild() {
let mut remote_stdio: McpServerConfig =
serde_json::from_value(serde_json::json!({ "command": "remote-server" }))
.expect("valid stdio server");
remote_stdio.environment_id = "executor-1".to_string();
let mut remote_destination = server("https://executor.example/mcp");
remote_destination.environment_id = "executor-1".to_string();
for (source_environment_id, config, expected_policy) in [
(
"executor-1",
server("https://executor.example/mcp"),
McpCredentialPolicy::ExecutorOnly,
),
(
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
remote_destination,
McpCredentialPolicy::HostFallbackAllowed,
),
(
"executor-1",
remote_stdio,
McpCredentialPolicy::HostFallbackAllowed,
),
] {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_selected_plugin(
"docs".to_string(),
plugin("selected-root"),
/*selection_order*/ 0,
source_environment_id,
config,
));
let catalog = builder.build();
for rebuilt in [
catalog.to_builder().build(),
catalog.with_materialized_servers(catalog.configured_servers()),
] {
let registration = rebuilt.server("docs").unwrap();
assert_eq!(
registration.source(),
&selected_plugin_source("selected-root")
);
assert_eq!(registration.credential_policy(), expected_policy);
assert_eq!(registration, catalog.server("docs").unwrap());
}
}
}
#[test]
fn plugin_host_root_is_retained_in_catalog_identity() {
let original_root = PathUri::parse("file:///plugins/original").expect("valid plugin root URI");
let replacement_root =
PathUri::parse("file:///plugins/replacement").expect("valid plugin root URI");
let catalog_for_root = |root| {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("plugin@test").with_host_root(root),
/*plugin_order*/ 0,
server("https://plugin.example/mcp"),
));
builder.build()
};
let original = catalog_for_root(original_root.clone());
let replacement = catalog_for_root(replacement_root);
let Some(McpServerSource::Plugin(attribution)) =
original.server("docs").map(ResolvedMcpServer::source)
else {
panic!("expected host-discovered plugin registration");
};
assert_eq!(attribution.host_root(), Some(&original_root));
assert!(!original.has_same_servers(&replacement));
}
#[test]
fn removed_ema_auth_servers_are_never_enabled() {
let mut config = server("https://resource.example/mcp");
config.auth = McpServerAuth::EmaAuth;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_config(
"enterprise".to_string(),
config,
));
let original = builder.build();
assert!(!original.server("enterprise").unwrap().config().enabled);
let materialized = original.with_materialized_servers(original.configured_servers());
assert!(!materialized.server("enterprise").unwrap().config().enabled);
}
#[test]
fn source_precedence_preserves_the_winning_registration() {
let extension = server("https://extension.example/mcp");
let mut plugin_server = server("https://plugin.example/mcp");
plugin_server.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
extension.clone(),
));
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("plugin@test"),
/*plugin_order*/ 0,
plugin_server,
));
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("other-plugin@test"),
/*plugin_order*/ 1,
server("https://other-plugin.example/mcp"),
));
builder.register(McpServerRegistration::from_compatibility(
"docs".to_string(),
"legacy",
server("https://compatibility.example/mcp"),
));
builder.register(McpServerRegistration::from_config(
"docs".to_string(),
server("https://config.example/mcp"),
));
let catalog = builder.build();
let resolved = catalog.server("docs").expect("resolved server");
assert_eq!(
resolved.source(),
&McpServerSource::Extension {
id: "hosted".to_string(),
}
);
assert_eq!(resolved.config(), &extension);
assert!(catalog.plugin_attributions_by_server_name().is_empty());
assert_eq!(
catalog.conflicts(),
&[McpServerConflict {
name: "docs".to_string(),
outcome: register(extension_source("hosted")),
contenders: vec![
register(plugin_source("other-plugin@test")),
register(plugin_source("plugin@test")),
],
}]
);
}
#[test]
fn disabled_veto_only_disables_the_winning_registration() {
let extension = server("https://extension.example/mcp");
let mut expected = extension.clone();
expected.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
extension,
));
builder.disable("docs".to_string());
let actual = builder
.build()
.server("docs")
.expect("resolved server")
.config()
.clone();
assert_eq!(actual, expected);
}
#[test]
fn disabled_winner_remains_a_veto_when_the_catalog_is_extended() {
let mut disabled = server("https://config.example/mcp");
disabled.enabled = false;
let mut expected = server("https://extension.example/mcp");
expected.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_config(
"docs".to_string(),
disabled,
));
let mut builder = builder.build().to_builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
server("https://extension.example/mcp"),
));
let resolved = builder.build();
assert_eq!(
resolved.server("docs"),
Some(&super::ResolvedMcpServer {
source: extension_source("hosted"),
config: expected,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
}
#[test]
fn disabled_discovered_plugin_remains_a_veto_for_runtime_overlays() {
let mut disabled = server("https://plugin.example/mcp");
disabled.enabled = false;
let mut expected = server("https://extension.example/mcp");
expected.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("plugin@test"),
/*plugin_order*/ 0,
disabled,
));
let mut builder = builder.build().to_builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
server("https://extension.example/mcp"),
));
let resolved = builder.build();
assert_eq!(
resolved.server("docs"),
Some(&super::ResolvedMcpServer {
source: extension_source("hosted"),
config: expected,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
}
#[test]
fn earlier_plugin_wins_with_an_explicit_conflict() {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("alpha@test"),
/*plugin_order*/ 0,
server("https://alpha.example/mcp"),
));
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("beta@test"),
/*plugin_order*/ 1,
server("https://beta.example/mcp"),
));
let catalog = builder.build();
assert_eq!(
catalog.plugin_attributions_by_server_name(),
HashMap::from([("docs".to_string(), plugin("alpha@test"))])
);
assert_eq!(
catalog.conflicts(),
&[McpServerConflict {
name: "docs".to_string(),
outcome: register(plugin_source("alpha@test")),
contenders: vec![
register(plugin_source("beta@test")),
register(plugin_source("alpha@test")),
],
}]
);
}
#[test]
fn selected_plugins_override_discovered_plugins_but_not_config() {
let selected = server("https://selected-alpha.example/mcp");
let mut discovered = server("https://local.example/mcp");
discovered.enabled = false;
discovered.default_tools_approval_mode = Some(AppToolApproval::Auto);
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("local@test"),
/*plugin_order*/ 0,
discovered,
));
builder.register(McpServerRegistration::from_selected_plugin(
"docs".to_string(),
plugin("selected-beta"),
/*selection_order*/ 1,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
server("https://selected-beta.example/mcp"),
));
builder.register(McpServerRegistration::from_selected_plugin(
"docs".to_string(),
plugin("selected-alpha"),
/*selection_order*/ 0,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
selected.clone(),
));
let catalog = builder.build();
assert_eq!(
catalog.server("docs"),
Some(&super::ResolvedMcpServer {
source: selected_plugin_source("selected-alpha"),
config: selected,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
assert_eq!(
catalog.plugin_attributions_by_server_name(),
HashMap::from([("docs".to_string(), plugin("selected-alpha"))])
);
assert_eq!(
catalog.conflicts(),
&[McpServerConflict {
name: "docs".to_string(),
outcome: register(selected_plugin_source("selected-alpha")),
contenders: vec![
register(selected_plugin_source("selected-beta")),
register(selected_plugin_source("selected-alpha")),
],
}]
);
let refreshed = server("https://refreshed.example/mcp");
let catalog =
catalog.with_materialized_servers(HashMap::from([("docs".to_string(), refreshed.clone())]));
assert_eq!(
catalog.server("docs"),
Some(&super::ResolvedMcpServer {
source: selected_plugin_source("selected-alpha"),
config: refreshed,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
let mut builder = catalog.to_builder();
let configured = server("https://config.example/mcp");
builder.register(McpServerRegistration::from_config(
"docs".to_string(),
configured.clone(),
));
let catalog = builder.build();
assert_eq!(
catalog.server("docs"),
Some(&super::ResolvedMcpServer {
source: McpServerSource::Config,
config: configured,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
}
#[test]
fn disabled_selected_plugin_does_not_veto_runtime_overlays() {
let mut disabled = server("https://selected.example/mcp");
disabled.enabled = false;
let extension = server("https://extension.example/mcp");
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_selected_plugin(
"docs".to_string(),
plugin("selected"),
/*selection_order*/ 0,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
disabled,
));
let mut builder = builder.build().to_builder();
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
extension.clone(),
));
let resolved = builder.build();
assert_eq!(
resolved.server("docs"),
Some(&super::ResolvedMcpServer {
source: extension_source("hosted"),
config: extension,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
}
#[test]
fn equal_precedence_uses_insertion_order_not_source_identity() {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_compatibility(
"docs".to_string(),
"z-first",
server("https://first.example/mcp"),
));
builder.register(McpServerRegistration::from_compatibility(
"docs".to_string(),
"a-second",
server("https://second.example/mcp"),
));
let catalog = builder.build();
assert_eq!(
catalog.server("docs"),
Some(&super::ResolvedMcpServer {
source: compatibility_source("a-second"),
config: server("https://second.example/mcp"),
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
let mut builder = catalog.to_builder();
builder.remove_compatibility("docs".to_string(), "remove-last");
let catalog = builder.build();
assert_eq!(catalog.server("docs"), None);
assert_eq!(
catalog.conflicts(),
&[McpServerConflict {
name: "docs".to_string(),
outcome: remove(compatibility_source("remove-last")),
contenders: vec![
register(compatibility_source("z-first")),
register(compatibility_source("a-second")),
remove(compatibility_source("remove-last")),
],
}]
);
}
#[test]
fn extension_protocol_mode_follows_the_winner_through_materialization() {
let config = server("https://apps.example/mcp");
let mut builder = ResolvedMcpCatalog::builder();
builder.register(
McpServerRegistration::from_extension(
"apps".to_string(),
"loser",
/*contribution_order*/ 0,
config.clone(),
)
.with_protocol_mode(McpProtocolMode::V20260728),
);
builder.register(McpServerRegistration::from_extension(
"apps".to_string(),
"winner",
/*contribution_order*/ 1,
config.clone(),
));
let without_override = builder.build();
assert_eq!(
without_override
.server("apps")
.and_then(ResolvedMcpServer::protocol_mode),
None
);
let mut builder = ResolvedMcpCatalog::builder();
builder.register(
McpServerRegistration::from_extension(
"apps".to_string(),
"winner",
/*contribution_order*/ 1,
config,
)
.with_protocol_mode(McpProtocolMode::Legacy),
);
let with_override = builder.build();
assert!(!without_override.has_same_servers(&with_override));
let refreshed = server("https://refreshed.example/mcp");
let materialized = with_override
.with_materialized_servers(HashMap::from([("apps".to_string(), refreshed.clone())]));
assert_eq!(
materialized.server("apps"),
Some(&ResolvedMcpServer {
source: extension_source("winner"),
config: refreshed,
credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: Some(McpProtocolMode::Legacy),
})
);
}
#[test]
fn environment_policy_denies_extension_registrations_named_like_hosted_apps() {
let policy = EnvironmentMcpPolicy {
servers: Some(BTreeMap::new()),
plugins: None,
};
let custom = server("https://custom.example/mcp");
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_config(
"codex_apps".to_string(),
custom.clone(),
));
let denied =
builder.build_with_environment_authority(|_| McpEnvironmentAuthority::Restricted(&policy));
let mut builder = denied.to_builder();
builder.register(McpServerRegistration::from_extension(
"codex_apps".to_string(),
"apps",
/*contribution_order*/ 0,
server("https://apps.example/mcp"),
));
let catalog =
builder.build_with_environment_authority(|_| McpEnvironmentAuthority::Restricted(&policy));
assert!(
!catalog
.server("codex_apps")
.expect("extension registration")
.config()
.enabled
);
let mut builder = catalog
.with_materialized_servers(catalog.configured_servers())
.to_builder();
builder.register(McpServerRegistration::from_extension(
"codex_apps".to_string(),
"custom",
/*contribution_order*/ 1,
custom,
));
assert_eq!(
builder.build().configured_servers(),
denied.configured_servers()
);
}
#[test]
fn environment_policy_preserves_selected_plugin_and_empty_server_allowlist_semantics() {
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_selected_plugin(
"selected".to_string(),
plugin("selected-plugin"),
/*selection_order*/ 0,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
server("https://plugin.example/mcp"),
));
let metadata_only_policy = EnvironmentMcpPolicy {
servers: None,
plugins: Some(BTreeMap::from([(
"metadata-only-plugin".to_string(),
PluginMcpRequirements { mcp_servers: None },
)])),
};
let deny_all_policy = EnvironmentMcpPolicy {
servers: Some(BTreeMap::new()),
plugins: None,
};
for (policy, expected) in [(&metadata_only_policy, true), (&deny_all_policy, false)] {
let resolved = builder
.clone()
.build_with_environment_authority(|_| McpEnvironmentAuthority::Restricted(policy));
assert_eq!(
resolved
.server("selected")
.expect("selected plugin")
.config()
.enabled,
expected
);
}
}
#[test]
fn retired_plugin_ema_does_not_veto_a_later_runtime_registration() {
let mut retired = server("https://plugin.example/mcp");
retired.auth = McpServerAuth::EmaAuth;
retired.enabled = false;
let mut builder = ResolvedMcpCatalog::builder();
builder.register(McpServerRegistration::from_plugin(
"docs".to_string(),
plugin("plugin@test"),
/*plugin_order*/ 0,
retired,
));
let catalog = builder.build();
assert!(!catalog.server("docs").unwrap().config().enabled);
let mut builder = catalog.to_builder();
let expected = server("https://extension.example/mcp");
builder.register(McpServerRegistration::from_extension(
"docs".to_string(),
"hosted",
/*contribution_order*/ 0,
expected.clone(),
));
assert_eq!(builder.build().server("docs").unwrap().config(), &expected);
}

View File

@@ -0,0 +1,71 @@
use std::collections::HashMap;
use akode_protocol::mcp::ClientMcpExtensions;
use akode_protocol::mcp::MCP_APP_UI_EXTENSION_ID;
use akode_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID;
use akode_protocol::mcp::OPENAI_FORM_EXTENSION_ID;
use akode_protocol::mcp::OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID;
use serde_json::Map;
use serde_json::Value;
/// Projects privileged capabilities only to their intended recipients.
/// User verification required the hosted plugin service and network policy metadata was only
/// offered to trusted hosted origins; aKode never connects to either, so both are stripped for
/// every server. Server names and caller-supplied capabilities grant neither.
pub(crate) fn server_mcp_extensions(extensions: &ClientMcpExtensions) -> ClientMcpExtensions {
ClientMcpExtensions::new(
extensions
.iter()
.filter(|(id, _)| *id != crate::MCP_NETWORK_POLICY_META_CAPABILITY)
.map(|(id, settings)| {
let mut settings = settings.clone();
if id == OPENAI_ELICITATION_EXTENSION_ID
&& let Some(settings) = settings.as_object_mut()
{
settings.remove("userVerification");
}
(id.to_string(), settings)
}),
)
}
/// Selects the MCP extensions Codex supports from those declared by the app-server host.
///
/// App-server clients may declare unrelated extensions. Codex retains only the
/// trusted extension namespaces it knows how to project downstream. The
/// legacy form capability is normalized into the same extension map.
pub fn client_mcp_extensions(
extensions: Option<&HashMap<String, Value>>,
legacy_openai_form_elicitation: bool,
) -> ClientMcpExtensions {
let mut selected = extensions
.into_iter()
.flat_map(HashMap::iter)
.filter(|(id, _)| {
matches!(
id.as_str(),
OPENAI_FORM_EXTENSION_ID
| OPENAI_ELICITATION_EXTENSION_ID
| OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID
| MCP_APP_UI_EXTENSION_ID
)
})
.map(|(id, value)| (id.clone(), value.clone()))
.collect::<HashMap<_, _>>();
if let Some(settings) = selected
.get_mut(OPENAI_ELICITATION_EXTENSION_ID)
.and_then(Value::as_object_mut)
{
settings.retain(|key, _| key == "form");
}
if legacy_openai_form_elicitation {
selected
.entry(OPENAI_FORM_EXTENSION_ID.to_string())
.or_insert_with(|| Value::Object(Map::new()));
}
ClientMcpExtensions::new(selected)
}
#[cfg(test)]
#[path = "client_capabilities_tests.rs"]
mod tests;

View File

@@ -0,0 +1,86 @@
use std::collections::HashMap;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::*;
#[test]
fn selects_only_supported_mcp_extensions() {
let app_ui = json!({
"mimeTypes": [
"text/html;profile=mcp-app",
"text/x-dil;profile=mcp-app",
],
"futureField": {"preserved": true},
});
let form = json!({"futureField": {"preserved": true}});
let extensions = HashMap::from([
(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"form": form, "userVerification": {}, "unsupported": {}}),
),
(MCP_APP_UI_EXTENSION_ID.to_string(), app_ui.clone()),
(OPENAI_FORM_EXTENSION_ID.to_string(), json!({})),
(
OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(),
json!({}),
),
("example/other".to_string(), json!({"enabled": true})),
]);
assert_eq!(
client_mcp_extensions(
Some(&extensions),
/*legacy_openai_form_elicitation*/ false,
),
ClientMcpExtensions::new(HashMap::from([
(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"form": form}),
),
(MCP_APP_UI_EXTENSION_ID.to_string(), app_ui),
(OPENAI_FORM_EXTENSION_ID.to_string(), json!({})),
(
OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(),
json!({}),
),
]))
);
}
#[test]
fn normalizes_legacy_form_capability_into_extensions() {
assert_eq!(
client_mcp_extensions(
/*extensions*/ None, /*legacy_openai_form_elicitation*/ true,
),
ClientMcpExtensions::new(HashMap::from([(
OPENAI_FORM_EXTENSION_ID.to_string(),
json!({}),
)]))
);
}
#[test]
fn user_verification_and_network_policy_are_never_projected_to_servers() {
let extensions = ClientMcpExtensions::new([
(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"form": {}, "userVerification": {}}),
),
(
crate::MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
json!({}),
),
]);
// Server names and registrations, including the formerly reserved `codex_apps` name, never
// grant user verification or network policy metadata.
assert_eq!(
server_mcp_extensions(&extensions),
ClientMcpExtensions::new([(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
json!({"form": {}}),
)]),
);
}

View File

@@ -0,0 +1,203 @@
//! Client-local catalog revisions and synchronization for MCP calls.
//!
//! Only active readers, calls, and frozen model bindings pin earlier snapshots.
//! Servers coalesce list-change notifications and publish only a stable listing.
//! Notifications update discovery without waiting for admitted calls to finish.
//! Failed refreshes retain the last catalog and share a short retry cooldown.
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use akode_rmcp_client::ToolListRevision;
use tokio::sync::Mutex;
use tokio::sync::RwLock;
use tokio::time::Instant;
use crate::tools::ToolInfo;
const NOTIFICATION_REFRESH_COOLDOWN: Duration = Duration::from_secs(5);
pub(crate) struct ClientToolCatalog {
current: RwLock<CatalogState>,
/// Serialize fetches and retain the next retry time after failure or cancellation.
refresh_lock: Mutex<Option<Instant>>,
/// Starts at zero so notifications during the initial listing stay pending.
listed_notification_revision: AtomicU64,
}
struct CatalogState {
revision: u64,
tools: Arc<[ToolInfo]>,
meta: Option<Arc<serde_json::Value>>,
}
#[derive(Clone)]
pub(crate) struct ToolCatalogSnapshot {
pub(crate) revision: u64,
pub(crate) tools: Arc<[ToolInfo]>,
pub(crate) meta: Option<Arc<serde_json::Value>>,
}
impl ClientToolCatalog {
pub(crate) fn new(
tools: impl Into<Arc<[ToolInfo]>>,
meta: Option<Arc<serde_json::Value>>,
) -> Self {
Self {
current: RwLock::new(CatalogState {
revision: 0,
tools: tools.into(),
meta,
}),
refresh_lock: Mutex::new(None),
listed_notification_revision: AtomicU64::new(0),
}
}
pub(crate) async fn read<R>(&self, read: impl FnOnce(ToolCatalogSnapshot) -> R) -> R {
let current = self.current.read().await;
let snapshot = ToolCatalogSnapshot {
revision: current.revision,
tools: Arc::clone(&current.tools),
meta: current.meta.clone(),
};
drop(current);
read(snapshot)
}
pub(crate) fn notifications_current(&self, notifications: &ToolListRevision) -> bool {
self.listed_notification_revision.load(Ordering::Acquire) == notifications.current()
}
/// Refresh ordinary server catalogs, coalescing concurrent readers. Never mark a
/// listing current if another notification arrived while fetching its pages.
/// Retry once; persistent churn stays pending until the retry cooldown expires.
#[expect(
clippy::await_holding_invalid_type,
reason = "refreshes must remain serialized through fetching and catalog publication"
)]
pub(crate) async fn refresh_after_notifications<F, Fut>(
&self,
notifications: &ToolListRevision,
timeout: Duration,
mut fetch: F,
) -> Result<()>
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<(Vec<ToolInfo>, Option<Arc<serde_json::Value>>)>>,
{
if self.notifications_current(notifications) {
return Ok(());
}
let deadline = Instant::now() + timeout;
let mut retry_after = tokio::time::timeout_at(deadline, self.refresh_lock.lock())
.await
.context("MCP tool catalog refresh timed out")?;
if self.notifications_current(notifications)
|| retry_after.is_some_and(|deadline| Instant::now() < deadline)
{
return Ok(());
}
// Also bound retries if the caller cancels this future during the fetch.
*retry_after = Some(deadline + NOTIFICATION_REFRESH_COOLDOWN);
let result = tokio::time::timeout_at(deadline, async {
for _ in 0..2 {
let revision = notifications.current();
let tools = fetch().await;
let mut current = self.current.write().await;
if notifications.current() != revision {
continue;
}
let (tools, meta) = tools?;
current.tools = tools.into();
current.meta = meta;
current.revision += 1;
self.listed_notification_revision
.store(revision, Ordering::Release);
return Ok(());
}
bail!("MCP tool list changed during catalog refresh")
})
.await
.context("MCP tool catalog refresh timed out")
.and_then(std::convert::identity);
*retry_after = result
.is_err()
.then(|| Instant::now() + NOTIFICATION_REFRESH_COOLDOWN);
result
}
/// Installs a new catalog as a list-change refresh would.
#[cfg(test)]
pub(crate) async fn replace_for_test(&self, tools: Vec<ToolInfo>) {
let mut current = self.current.write().await;
current.tools = tools.into();
current.revision += 1;
}
/// Reject stale calls before preparation. List-change notifications may publish while an
/// admitted call runs.
pub(crate) async fn run_with_snapshot<R, F, Fut>(
&self,
expected: &ToolCatalogSnapshot,
run: F,
) -> Option<R>
where
F: FnOnce() -> Fut,
Fut: Future<Output = R>,
{
let current = self.read(|snapshot| snapshot).await;
if current.revision != expected.revision
&& !catalogs_match(&current.tools, &expected.tools)
{
return None;
}
Some(run().await)
}
}
/// Compares complete definitions independently of tool-list order. Stable sorting keeps
/// conflicting duplicate identities in their original order, since deduplication can pick the
/// first definition. This slow path runs only after the client's revision has changed.
fn catalogs_match(left: &[ToolInfo], right: &[ToolInfo]) -> bool {
if left == right {
return true;
}
if left.len() != right.len() {
return false;
}
let mut left = left.iter().collect::<Vec<_>>();
let mut right = right.iter().collect::<Vec<_>>();
for tools in [&mut left, &mut right] {
tools.sort_by_key(|tool| {
(
tool.server_name.as_str(),
tool.tool.name.as_ref(),
tool.callable_namespace.as_str(),
tool.callable_name.as_str(),
)
});
}
left == right
}
/// A binding cache key includes client identity, since new clients start at zero.
#[derive(Clone)]
pub(crate) struct ClientToolCatalogRevision {
pub(crate) catalog: Arc<ClientToolCatalog>,
pub(crate) revision: u64,
}
impl PartialEq for ClientToolCatalogRevision {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.catalog, &other.catalog) && self.revision == other.revision
}
}
impl Eq for ClientToolCatalogRevision {}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,98 @@
//! Privacy-safe size telemetry for raw MCP tool catalogs.
use rmcp::model::Tool;
use serde::Serialize;
use std::io::Write;
const RAW_DEFINITION_JSON_BYTES_METRIC: &str =
"codex.mcp.binding_catalog.raw_definition_json_bytes";
const KIB: f64 = 1024.0;
const MIB: f64 = 1024.0 * KIB;
const RAW_DEFINITION_JSON_BYTES_BUCKETS: &[f64] = &[
64.0 * KIB,
128.0 * KIB,
256.0 * KIB,
512.0 * KIB,
768.0 * KIB,
MIB,
1.5 * MIB,
2.0 * MIB,
3.0 * MIB,
4.0 * MIB,
6.0 * MIB,
8.0 * MIB,
12.0 * MIB,
16.0 * MIB,
24.0 * MIB,
32.0 * MIB,
48.0 * MIB,
64.0 * MIB,
96.0 * MIB,
128.0 * MIB,
192.0 * MIB,
256.0 * MIB,
384.0 * MIB,
512.0 * MIB,
];
pub(super) fn tool_definition_json_bytes<'a>(tools: impl Iterator<Item = &'a Tool>) -> usize {
tools.map(serialized_json_bytes).sum()
}
pub(super) fn record_binding_catalog_size(
metrics: &akode_otel::MetricsClient,
product_sku: &'static str,
raw_definition_json_bytes: usize,
) {
let _ = metrics.histogram_with_boundaries(
RAW_DEFINITION_JSON_BYTES_METRIC,
i64::try_from(raw_definition_json_bytes).unwrap_or(i64::MAX),
RAW_DEFINITION_JSON_BYTES_BUCKETS,
&[("product_sku", product_sku)],
);
}
pub(super) fn emit_binding_catalog(
product_sku: &'static str,
server_kind: &'static str,
plugin_id: Option<&str>,
catalog_source: &'static str,
tool_count: usize,
tool_definition_json_bytes: usize,
) {
tracing::event!(
target: "akode_otel.trace_safe",
tracing::Level::INFO,
event.name = "mcp.binding_catalog",
product_sku,
server_kind,
plugin_id = plugin_id.unwrap_or(""),
catalog_source,
tool_count,
tool_definition_json_bytes,
"MCP binding catalog materialized"
);
}
#[derive(Default)]
struct CountingWriter(usize);
impl Write for CountingWriter {
fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
self.0 += buffer.len();
Ok(buffer.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn serialized_json_bytes<T: Serialize + ?Sized>(value: &T) -> usize {
let mut writer = CountingWriter::default();
if serde_json::to_writer(&mut writer, value).is_ok() {
writer.0
} else {
0
}
}

View File

@@ -0,0 +1,85 @@
//! Adds negotiated policy metadata using the same publication as the MCP call.
use super::McpConnectionSet;
use crate::MCP_NETWORK_POLICY_META_CAPABILITY;
use crate::rmcp_client::ManagedClient;
use anyhow::Context;
use akode_network_proxy::NetworkMode;
use akode_protocol::models::PermissionProfile;
use rmcp::model::ServerCapabilities;
use serde::Serialize;
use serde_json::Value;
use std::sync::OnceLock;
/// Effective network restrictions delivered with an MCP call, without proxy endpoints or credentials.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkPolicyMetadata {
pub enabled: bool,
pub mode: NetworkMode,
pub allowed_domains: Vec<String>,
pub denied_domains: Vec<String>,
pub hard_deny_allowlist_misses: bool,
}
/// Produces trusted network policy metadata from an MCP publication's frozen policy sources.
/// Implementations must use the supplied call authority and capture mutable grants once per call.
pub trait NetworkPolicyMetadataProvider: Send + Sync {
fn metadata_for_call(
&self,
permission_profile: &PermissionProfile,
environment_id: &str,
) -> anyhow::Result<NetworkPolicyMetadata>;
}
impl McpConnectionSet {
pub(crate) fn network_policy_meta_for_call(
&self,
client: &ManagedClient,
permission_profile: Option<&PermissionProfile>,
environment_id: &str,
mut meta: Option<Value>,
) -> impl Fn(&ServerCapabilities) -> anyhow::Result<Option<Value>> + Send + Sync {
if let Some(Value::Object(meta)) = meta.as_mut() {
meta.remove(MCP_NETWORK_POLICY_META_CAPABILITY);
}
// A retry can negotiate policy support for the first time. Capture mutable grants
// only once, when an attempt needs them, and keep that snapshot through recovery.
let policy = OnceLock::new();
move |capabilities| {
let mut meta = meta.clone();
if client.client_supports_network_policy_meta_capability
&& capabilities
.experimental
.as_ref()
.is_some_and(|experimental| {
experimental.contains_key(MCP_NETWORK_POLICY_META_CAPABILITY)
})
{
let policy = policy.get_or_init(|| -> anyhow::Result<Value> {
let provider = self
.network_policy_metadata
.as_ref()
.context("MCP network policy metadata source is unavailable")?;
let permission_profile = permission_profile
.context("MCP server has no captured permission authority")?;
serde_json::to_value(
provider.metadata_for_call(permission_profile, environment_id)?,
)
.map_err(Into::into)
});
let policy = policy
.as_ref()
.map_err(|error| anyhow::anyhow!("{error:#}"))?;
meta.get_or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.context("MCP request metadata must be an object")?
.insert(
MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
policy.clone(),
);
}
Ok(meta)
}
}
}

View File

@@ -0,0 +1,289 @@
//! Exercises policy metadata through real in-process MCP requests on both dispatch paths.
use super::*;
use crate::MCP_NETWORK_POLICY_META_CAPABILITY;
use crate::McpServerPermissions;
use crate::NetworkPolicyMetadata;
use crate::NetworkPolicyMetadataProvider;
use crate::catalog::McpServerRegistration;
use crate::catalog::ResolvedMcpCatalog;
use akode_exec_server::FileSystemSandboxContext;
use akode_network_proxy::NetworkMode;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use rmcp::model::CallToolRequestParams;
use rmcp::model::CallToolResponse;
use serde_json::Value;
use serde_json::json;
#[derive(Clone)]
struct MetadataEchoServer {
supports_policy: bool,
}
impl ServerHandler for MetadataEchoServer {
fn get_info(&self) -> ServerConfig {
let mut capabilities = ServerCapabilities::builder().enable_tools().build();
if self.supports_policy {
capabilities.experimental = Some(std::collections::BTreeMap::from([(
MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
JsonObject::new(),
)]));
}
ServerConfig::new(capabilities)
}
async fn call_tool(
&self,
_request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, McpError> {
let mut result = rmcp::model::CallToolResult::success(Vec::new());
result.structured_content = Some(Value::Object(context.meta.0.0));
Ok(CallToolResponse::Complete(result))
}
}
impl InProcessTransportFactory for MetadataEchoServer {
fn open(&self) -> BoxFuture<'static, io::Result<DuplexStream>> {
let server = self.clone();
async move {
let (client_stream, server_stream) = tokio::io::duplex(4096);
tokio::spawn(async move {
let server = server
.serve(server_stream)
.await
.expect("serve metadata echo");
server.waiting().await
});
Ok(client_stream)
}
.boxed()
}
}
#[derive(Default)]
struct CapturedPolicy(AtomicUsize);
impl NetworkPolicyMetadataProvider for CapturedPolicy {
fn metadata_for_call(
&self,
profile: &PermissionProfile,
environment: &str,
) -> anyhow::Result<NetworkPolicyMetadata> {
assert_eq!(
(profile, environment),
(&PermissionProfile::read_only(), "owner-environment")
);
self.0.fetch_add(1, Ordering::SeqCst);
Ok(NetworkPolicyMetadata {
enabled: false,
mode: NetworkMode::Limited,
allowed_domains: vec!["allowed.example.com".to_string()],
denied_domains: vec!["blocked.example.com".to_string()],
hard_deny_allowlist_misses: true,
})
}
}
#[tokio::test]
async fn tool_calls_never_deliver_network_policy_and_strip_forged_metadata() -> anyhow::Result<()> {
// Network policy metadata was only offered to trusted ChatGPT origins, which aKode never
// connects to, so no server receives it and forged caller metadata is always stripped.
for (url, provider_available, supports_policy, delivers_policy) in [
(Some("https://chatgpt.com/mcp"), true, true, false),
(Some("https://chatgpt.com/mcp"), true, false, false),
(Some("https://chatgpt.com/mcp"), false, true, false),
(Some("https://gov.chatgpt.com/mcp"), true, true, false),
(
Some("https://chatgpt.com.attacker.example/mcp"),
true,
true,
false,
),
(Some("http://chatgpt.com/mcp"), true, true, false),
(Some("https://third-party.example/mcp"), true, true, false),
(None, true, true, false),
] {
let mut server_config = reusable_server_config(url.unwrap_or("https://chatgpt.com/mcp"));
if url.is_none() {
server_config.transport = McpServerTransportConfig::Stdio {
command: "metadata-echo".to_string(),
args: Vec::new(),
env: None,
env_vars: Vec::new(),
cwd: None,
};
}
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"docs".into(),
server_config,
));
let catalog = catalog.build();
assert!(catalog.server("docs").is_some());
let extensions = crate::client_capabilities::server_mcp_extensions(
&ClientMcpExtensions::new([(
MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
json!({"forged": true}),
)]),
);
let client_supports_policy = extensions
.iter()
.any(|(id, _)| id == MCP_NETWORK_POLICY_META_CAPABILITY);
let client = Arc::new(
RmcpClient::new_in_process_client(Arc::new(MetadataEchoServer { supports_policy }))
.await?,
);
client
.initialize(
crate::rmcp_client::mcp_initialize_request_params(
ElicitationCapability::default(),
extensions,
),
Some(Duration::from_secs(5)),
Box::new(|_, _| async { Err(anyhow!("unexpected elicitation")) }.boxed()),
)
.await?;
let mut managed = create_test_managed_client(vec![create_test_tool("docs", "echo")]).await;
managed.client = Arc::clone(&client);
managed.client_supports_network_policy_meta_capability = client_supports_policy;
let (managed, _started, release) = create_gated_async_managed_client(managed);
release.send(()).expect("release initialized client");
let policy = Arc::new(CapturedPolicy::default());
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
config.permission_profile = PermissionProfile::Disabled;
let sandbox = FileSystemSandboxContext::from_permission_profile(
PermissionProfile::read_only(),
PathUri::from_host_native_path(std::env::temp_dir())?,
);
config.server_permissions.insert(
"docs".to_string(),
McpServerPermissions::Environment(Arc::new(sandbox)),
);
let config = Arc::new(config);
let mut manager = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
manager.config = Some(Arc::clone(&config));
manager.network_policy_metadata =
provider_available.then(|| policy.clone() as Arc<dyn NetworkPolicyMetadataProvider>);
manager.insert_test_client("docs", managed);
let view = manager.servers.get_mut("docs").expect("docs server");
view.metadata.environment_id = "owner-environment".to_string();
let manager = Arc::new(manager);
let binding = manager
.capture_binding_with_metadata(
config,
/*plugins_available*/ false,
/*required_servers*/ &[],
/*required_plugins*/ &HashSet::new(),
)
.await;
let prepared = binding
.prepare_call("docs", "echo")
.expect("prepare advertised tool");
let forged_meta = || {
Some(json!({
"codex/network-policy-meta": {"enabled": true, "forged": true},
"keep": "caller metadata",
}))
};
let mut expected = json!({"keep": "caller metadata"});
if delivers_policy {
expected[MCP_NETWORK_POLICY_META_CAPABILITY] = json!({
"enabled": false,
"mode": "limited",
"allowedDomains": ["allowed.example.com"],
"deniedDomains": ["blocked.example.com"],
"hardDenyAllowlistMisses": true,
});
}
for result in [
prepared
.call(
/*arguments*/ None,
forged_meta(),
/*timeout*/ None,
)
.await?,
manager
.call_tool(
"docs",
"echo",
/*environment_id*/ None,
/*arguments*/ None,
forged_meta(),
/*requested_timeout*/ None,
/*wait_for_server*/ true,
)
.await?,
] {
let mut received = result.structured_content.expect("echoed wire metadata");
received
.as_object_mut()
.expect("metadata object")
.remove("progressToken");
assert_eq!(received, expected);
}
assert_eq!(
policy.0.load(Ordering::SeqCst),
if delivers_policy { 2 } else { 0 }
);
client.shutdown().await;
}
Ok(())
}
#[tokio::test]
async fn recovered_session_policy_keeps_one_captured_call_authority() -> anyhow::Result<()> {
let mut client = create_test_managed_client(Vec::new()).await;
client.client_supports_network_policy_meta_capability = true;
let policy = Arc::new(CapturedPolicy::default());
let mut manager = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
manager.network_policy_metadata = Some(policy.clone());
let profile = PermissionProfile::read_only();
let metadata = manager.network_policy_meta_for_call(
&client,
Some(&profile),
"owner-environment",
Some(json!({"codex/network-policy-meta": {"forged": true}, "keep": "caller"})),
);
let legacy = ServerCapabilities::default();
let mut negotiated = legacy.clone();
negotiated.experimental = Some(std::collections::BTreeMap::from([(
MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
JsonObject::new(),
)]));
assert_eq!(metadata(&legacy)?, Some(json!({"keep": "caller"})));
assert_eq!(policy.0.load(Ordering::SeqCst), 0);
let expected = Some(json!({
"keep": "caller",
"codex/network-policy-meta": {
"enabled": false,
"mode": "limited",
"allowedDomains": ["allowed.example.com"],
"deniedDomains": ["blocked.example.com"],
"hardDenyAllowlistMisses": true,
},
}));
assert_eq!(metadata(&negotiated)?, expected);
assert_eq!(metadata(&legacy)?, Some(json!({"keep": "caller"})));
assert_eq!(metadata(&negotiated)?, expected);
assert_eq!(policy.0.load(Ordering::SeqCst), 1);
let missing_provider = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
let metadata = missing_provider.network_policy_meta_for_call(
&client,
Some(&profile),
"owner-environment",
/*meta*/ None,
);
assert_eq!(metadata(&legacy)?, None);
assert!(
metadata(&negotiated)
.unwrap_err()
.to_string()
.contains("source is unavailable")
);
Ok(())
}

View File

@@ -0,0 +1,71 @@
use std::collections::HashSet;
use anyhow::Result;
use anyhow::anyhow;
use akode_protocol::protocol::McpStartupFailure;
use tracing::Instrument;
use tracing::info_span;
use super::McpConnectionSet;
use crate::rmcp_client::StartupOutcomeError;
impl McpConnectionSet {
/// Waits for required servers unless their readiness policy accepts a cached catalog.
///
/// The manager must already be reachable through [`crate::McpRuntime`] so
/// startup-time elicitation can resolve while validation waits.
pub(crate) async fn validate_required_servers(&self) -> Result<()> {
let failures = async {
self.record_startup_readiness("required_startup", &[], &HashSet::new());
let mut failures = Vec::new();
for server_name in &self.required_servers {
let Some(view) = self.servers.get(server_name) else {
failures.push(McpStartupFailure {
server: server_name.clone(),
error: format!("required MCP server `{server_name}` was not initialized"),
});
continue;
};
if view.allows_cached_startup()
&& view.cached_startup_tools(/*fallback*/ None).is_some()
{
continue;
}
match view.connection.client().await {
Ok(_) => {}
Err(error) => failures.push(McpStartupFailure {
server: server_name.clone(),
error: startup_outcome_error_message(error),
}),
}
}
failures
}
.instrument(info_span!(
"session_init.required_mcp_wait",
otel.name = "session_init.required_mcp_wait",
session_init.required_mcp_server_count = self.required_servers.len(),
))
.await;
if failures.is_empty() {
return Ok(());
}
let details = failures
.iter()
.map(|failure| format!("{}: {}", failure.server, failure.error))
.collect::<Vec<_>>()
.join("; ");
Err(anyhow!(
"required MCP servers failed to initialize: {details}"
))
}
}
fn startup_outcome_error_message(error: StartupOutcomeError) -> String {
match error {
StartupOutcomeError::Cancelled => "MCP startup cancelled".to_string(),
StartupOutcomeError::Failed { error, .. } => error,
}
}

View File

@@ -0,0 +1,189 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use rmcp::model::Resource;
use rmcp::model::ResourceTemplate;
use tokio::task::JoinSet;
use tracing::warn;
use super::McpConnectionSet;
use crate::pagination::collect_paginated;
use crate::resource_client::McpResourceServerCacheKey;
use crate::rmcp_client::ManagedClient;
impl McpConnectionSet {
pub(crate) fn resource_cache_key(
&self,
server: &str,
generation: u64,
) -> Option<McpResourceServerCacheKey> {
self.servers
.get(server)
.map(|view| McpResourceServerCacheKey {
connection: Arc::downgrade(&view.connection),
generation,
})
}
/// Returns resources from servers selected by `include_server`.
pub async fn list_all_resources(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<Resource>> {
let mut join_set = JoinSet::new();
for (server_name, view) in self
.servers
.iter()
.filter(|(server_name, _)| include_server(server_name))
{
let server_name = server_name.clone();
let Ok(client) = view.connection.client().await else {
continue;
};
let timeout = view.tool_timeout;
join_set.spawn(async move {
let resources = collect_paginated("resources/list", timeout, |params| {
let client = client.clone();
async move {
let response = client.list_resources(params, timeout).await?;
Ok((response.resources, response.next_cursor))
}
})
.await;
(server_name, resources)
});
}
let mut resources = HashMap::new();
while let Some(result) = join_set.join_next().await {
match result {
Ok((server_name, Ok(server_resources))) => {
resources.insert(server_name, server_resources);
}
Ok((server_name, Err(error))) => {
warn!("Failed to list resources for MCP server '{server_name}': {error:#}");
}
Err(error) => {
warn!("Task panic when listing resources for MCP server: {error:#}");
}
}
}
resources
}
/// Returns resource templates from servers selected by `include_server`.
pub async fn list_all_resource_templates(
&self,
include_server: impl Fn(&str) -> bool,
) -> HashMap<String, Vec<ResourceTemplate>> {
let mut join_set = JoinSet::new();
for (server_name, view) in self
.servers
.iter()
.filter(|(server_name, _)| include_server(server_name))
{
let server_name = server_name.clone();
let Ok(client) = view.connection.client().await else {
continue;
};
let timeout = view.tool_timeout;
join_set.spawn(async move {
let templates = collect_paginated("resources/templates/list", timeout, |params| {
let client = client.clone();
async move {
let response = client.list_resource_templates(params, timeout).await?;
Ok((response.resource_templates, response.next_cursor))
}
})
.await;
(server_name, templates)
});
}
let mut templates = HashMap::new();
while let Some(result) = join_set.join_next().await {
match result {
Ok((server_name, Ok(server_templates))) => {
templates.insert(server_name, server_templates);
}
Ok((server_name, Err(error))) => {
warn!(
"Failed to list resource templates for MCP server '{server_name}': {error:#}"
);
}
Err(error) => {
warn!("Task panic when listing resource templates for MCP server: {error:#}");
}
}
}
templates
}
pub async fn list_resources(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourcesResult> {
let (managed, timeout) = self.client_by_name(server).await?;
managed
.list_resources(params, timeout)
.await
.with_context(|| format!("resources/list failed for `{server}`"))
}
pub async fn list_resource_templates(
&self,
server: &str,
params: Option<PaginatedRequestParams>,
) -> Result<ListResourceTemplatesResult> {
let (managed, timeout) = self.client_by_name(server).await?;
managed
.list_resource_templates(params, timeout)
.await
.with_context(|| format!("resources/templates/list failed for `{server}`"))
}
pub async fn read_resource(
&self,
server: &str,
params: ReadResourceRequestParams,
) -> Result<ReadResourceResult> {
let (managed, timeout) = self.client_by_name(server).await?;
let uri = params.uri.clone();
managed
.read_resource(params, timeout)
.await
.with_context(|| format!("resources/read failed for `{server}` ({uri})"))
}
pub(crate) fn server_environment_id(&self, server: &str) -> Option<&str> {
self.servers
.get(server)
.map(|view| view.metadata.environment_id.as_str())
}
pub(crate) async fn client_by_name(
&self,
name: &str,
) -> Result<(ManagedClient, Option<Duration>)> {
let view = self
.servers
.get(name)
.ok_or_else(|| anyhow!("unknown MCP server '{name}'"))?;
let client = view
.connection
.client()
.await
.context("failed to get client")?;
Ok((client, view.tool_timeout))
}
}

View File

@@ -0,0 +1,109 @@
use std::collections::HashMap;
use anyhow::Result;
use async_channel::Sender;
use akode_config::McpServerConfig;
use akode_config::McpServerTransportConfig;
use akode_protocol::protocol::Event;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::McpStartupFailureReason;
use akode_protocol::protocol::McpStartupUpdateEvent;
use akode_rmcp_client::McpAuthState;
use akode_rmcp_client::McpLoginRequirement;
use crate::rmcp_client::DEFAULT_STARTUP_TIMEOUT;
use crate::rmcp_client::StartupOutcomeError;
pub(super) async fn emit_update(
submit_id: &str,
tx_event: &Sender<Event>,
update: McpStartupUpdateEvent,
) -> Result<(), async_channel::SendError<Event>> {
tx_event
.send(Event {
id: submit_id.to_string(),
msg: EventMsg::McpStartupUpdate(update),
})
.await
}
pub(super) fn mcp_startup_failure_reason(
auth_state: Option<McpAuthState>,
error: &StartupOutcomeError,
) -> Option<McpStartupFailureReason> {
if !error.is_authentication_required() {
return None;
}
match auth_state {
Some(
McpAuthState::LoggedOut(McpLoginRequirement::Reauthentication) | McpAuthState::OAuth,
) => Some(McpStartupFailureReason::ReauthenticationRequired),
Some(
McpAuthState::Unsupported
| McpAuthState::Unknown
| McpAuthState::LoggedOut(McpLoginRequirement::Login)
| McpAuthState::BearerToken,
)
| None => None,
}
}
pub(super) fn mcp_init_error_display(
server_name: &str,
config: Option<&McpServerConfig>,
error: &StartupOutcomeError,
reason: Option<McpStartupFailureReason>,
) -> String {
let server_key = if !server_name.is_empty()
&& server_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
server_name.to_string()
} else {
serde_json::Value::String(server_name.to_string()).to_string()
};
if let Some(McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
..
}) = config.map(|config| &config.transport)
&& url == "https://api.githubcopilot.com/mcp/"
&& bearer_token_env_var.is_none()
&& http_headers.as_ref().map(HashMap::is_empty).unwrap_or(true)
{
format!(
"GitHub MCP does not support OAuth. Log in by adding a personal access token (https://github.com/settings/personal-access-tokens) to your environment and config.toml:\n[mcp_servers.{server_key}]\nbearer_token_env_var = AKODE_GITHUB_PERSONAL_ACCESS_TOKEN"
)
} else if error.is_authentication_required() {
let recovery_hint = if config.is_some_and(|config| !config.is_local_environment()) {
"Use your client's MCP OAuth sign-in flow.".to_string()
} else {
format!("Run `akode mcp login {server_name}`.")
};
let auth_status = match reason {
Some(McpStartupFailureReason::ReauthenticationRequired) => {
"requires OAuth reauthentication"
}
None => "is not logged in",
};
format!("The {server_name} MCP server {auth_status}. {recovery_hint}")
} else if matches!(
error,
StartupOutcomeError::Failed { error, .. }
if error.contains("request timed out")
|| error.contains("timed out handshaking with MCP server")
|| error.contains("MCP client startup timed out")
) {
let startup_timeout_secs = config
.and_then(|config| config.startup_timeout_sec)
.unwrap_or(DEFAULT_STARTUP_TIMEOUT)
.as_secs();
format!(
"MCP client for `{server_name}` timed out after {startup_timeout_secs} seconds. Add or adjust `startup_timeout_sec` in your config.toml:\n[mcp_servers.{server_key}]\nstartup_timeout_sec = XX"
)
} else {
format!("MCP client for `{server_name}` failed to start: {error:#}")
}
}

View File

@@ -0,0 +1,30 @@
//! Read-only connection state; observing a server must not start it.
use std::collections::HashMap;
use akode_protocol::mcp::McpServerConnectionStatus;
use super::McpConnectionSet;
impl McpConnectionSet {
pub(crate) async fn connection_statuses(&self) -> HashMap<String, McpServerConnectionStatus> {
use McpServerConnectionStatus as Status;
let mut statuses = self
.disabled_servers
.iter()
.map(|name| (name.clone(), Status::Disabled))
.collect::<HashMap<_, _>>();
for (name, view) in &self.servers {
let connection = &view.connection;
let client = &connection.client;
let status = if connection.startup_is_dormant() && !client.cancel_token.is_cancelled() {
Status::NotStarted
} else {
client.connection_status().await
};
statuses.insert(name.clone(), status);
}
statuses
}
}

View File

@@ -0,0 +1,622 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use anyhow::Context;
use anyhow::Result;
use akode_config::McpStartupReadiness;
use futures::future::join_all;
use tracing::Instrument;
use tracing::instrument;
use tracing::trace;
use tracing::trace_span;
use super::McpConnectionSet;
use super::McpServerMetadata;
use super::catalog_telemetry::emit_binding_catalog;
use super::catalog_telemetry::record_binding_catalog_size;
use super::catalog_telemetry::tool_definition_json_bytes;
use crate::binding::McpBinding;
use crate::binding::PreparedMcpCall;
use crate::binding::PreparedToolInfo;
use crate::binding_clients::McpBindingClients;
use crate::client_tool_catalog::ClientToolCatalogRevision;
use crate::client_tool_catalog::ToolCatalogSnapshot;
use crate::rmcp_client::ManagedClient;
use crate::tools::ToolInfo;
use crate::tools::filter_tools;
use crate::tools::normalize_tools_for_model_with_prefix;
const MCP_UI_META_KEY: &str = "ui";
const MCP_UI_VISIBILITY_META_KEY: &str = "visibility";
const MCP_UI_MODEL_VISIBILITY: &str = "model";
/// Returns whether a tool may be included in model-facing tool declarations.
///
/// Tools without visibility metadata remain visible. Tools with visibility
/// metadata are hidden unless they explicitly include `model`.
///
/// <https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#resource-discovery>
pub fn tool_is_model_visible(tool: &ToolInfo) -> bool {
let Some(visibility) = tool
.tool
.meta
.as_deref()
.and_then(|meta| meta.get(MCP_UI_META_KEY))
.and_then(serde_json::Value::as_object)
.and_then(|ui| ui.get(MCP_UI_VISIBILITY_META_KEY))
.and_then(serde_json::Value::as_array)
else {
return true;
};
visibility
.iter()
.any(|target| target.as_str() == Some(MCP_UI_MODEL_VISIBILITY))
}
/// Catalog identity within one published connection set, including cached declarations.
#[derive(Clone, PartialEq, Eq)]
pub(crate) enum BindingCatalogRevision {
Ready(ClientToolCatalogRevision),
Cached(u64),
}
enum PendingCallToolInfo {
BindingCatalog(usize),
Owned(PreparedToolInfo),
}
impl McpConnectionSet {
/// Observes opted-in servers at startup gates without waiting or cloning catalogs.
pub(crate) fn record_startup_readiness(
&self,
phase: &'static str,
required_servers: &[String],
required_plugins: &HashSet<String>,
) {
if !tracing::enabled!(tracing::Level::INFO) {
return;
}
for (server_name, view) in &self.servers {
if view.startup_readiness != McpStartupReadiness::Catalog {
continue;
}
let client = &view.connection.client;
let startup_pending = !client.startup_complete.load(Ordering::Acquire);
let cache_eligible = startup_pending
&& client
.tool_catalog_cache_context
.as_ref()
.is_some_and(|cache| {
cache
.current_revision_if(|tools| view.accepts_cached_tools(tools))
.is_some()
});
let explicitly_required = required_servers.contains(server_name)
|| (self.is_selected_plugin_mcp_server(server_name)
&& self
.plugin_id_for_mcp_server_name(server_name)
.is_some_and(|plugin_id| required_plugins.contains(plugin_id)));
tracing::info!(
event.name = "mcp.startup_readiness",
server_name = %server_name,
phase,
startup_pending,
startup_readiness = "catalog",
cache_eligible,
required = self.required_servers.binary_search(server_name).is_ok(),
explicitly_required,
"MCP startup readiness observed"
);
}
}
pub(crate) async fn stable_catalog_revisions(
&self,
required_servers: &[String],
required_plugins: &HashSet<String>,
) -> Option<HashMap<String, BindingCatalogRevision>> {
let mut revisions = HashMap::new();
for (server_name, view) in &self.servers {
let startup_complete = view
.connection
.client
.startup_complete
.load(Ordering::Acquire);
if !startup_complete
|| (view.startup_readiness == McpStartupReadiness::Catalog
&& view.connection.client.ready_client().is_none())
{
// Explicit requirements still wait for a live connection during capture.
if !view.allows_cached_startup()
|| view.connection.client.cancel_token.is_cancelled()
|| required_servers
.iter()
.any(|required| required == server_name)
|| (self.is_selected_plugin_mcp_server(server_name)
&& self
.plugin_id_for_mcp_server_name(server_name)
.is_some_and(|plugin_id| required_plugins.contains(plugin_id)))
{
return None;
}
let revision = view
.connection
.client
.tool_catalog_cache_context
.as_ref()?
.current_revision_if(|tools| view.accepts_cached_tools(tools))?;
revisions.insert(
server_name.clone(),
BindingCatalogRevision::Cached(revision),
);
continue;
}
let Some(client) = view.connection.client.ready_client() else {
if self.required_servers.binary_search(server_name).is_err()
&& matches!(view.connection.client.client.peek(), Some(Err(_)))
{
continue;
}
return None;
};
if client.client.is_closed().await
|| (view.refresh_tool_list
&& !client
.tool_catalog
.notifications_current(&client.client.tool_list_revision()))
{
return None;
}
let revision = client.tool_catalog.read(|catalog| catalog.revision).await;
revisions.insert(
server_name.clone(),
BindingCatalogRevision::Ready(ClientToolCatalogRevision {
catalog: Arc::clone(&client.tool_catalog),
revision,
}),
);
}
Some(revisions)
}
/// Returns all tools with model-visible names normalized.
pub async fn list_all_tools(&self) -> Vec<ToolInfo> {
Box::pin(self.list_tools_with_errors(|_| true)).await.0
}
#[instrument(level = "trace", skip_all, fields(mcp_server_count = self.servers.len()))]
pub(crate) async fn list_tools_with_errors(
&self,
include_server: impl Fn(&str) -> bool,
) -> (Vec<ToolInfo>, HashMap<String, String>) {
let (tools, errors, _) = self.list_catalogs_with_errors(include_server).await;
(tools, errors)
}
pub(crate) async fn list_catalogs_with_errors(
&self,
include_server: impl Fn(&str) -> bool,
) -> (
Vec<ToolInfo>,
HashMap<String, String>,
HashMap<String, Arc<serde_json::Value>>,
) {
let mut metadata = HashMap::new();
let mut tools = Vec::new();
let mut errors = HashMap::new();
let mut available_server_count = 0;
let mut unavailable_server_count = 0;
let server_results = join_all(
self.servers
.iter()
.filter(|(name, _)| include_server(name))
.map(|(server_name, view)| async move {
let has_cached_tools = view.connection.client.has_cached_tools();
let startup_complete = view
.connection
.client
.startup_complete
.load(Ordering::Acquire);
let server_tools = view
.listed_catalog(server_name, &self.tool_plugin_context)
.instrument(trace_span!(
"list_tools_for_server",
server_name = %server_name,
has_cached_tools,
startup_complete
))
.await;
let result = match server_tools {
Ok((server_tools, meta)) => Ok((
server_tools
.into_iter()
.map(|tool| Self::with_server_metadata(tool, &view.metadata))
.collect::<Vec<_>>(),
meta,
)),
Err(error) => {
trace!(
server_name = %server_name,
has_cached_tools,
startup_complete,
"MCP server tools unavailable while building tool list"
);
Err(error)
}
};
(server_name, result)
}),
)
.await;
for (server_name, server_tools) in server_results {
match server_tools {
Ok((server_tools, meta)) => {
if let Some(meta) = meta {
metadata.insert(server_name.clone(), meta);
}
available_server_count += 1;
tools.extend(server_tools);
}
Err(error) => {
unavailable_server_count += 1;
errors.insert(server_name.clone(), error.to_string());
}
}
}
let tools = normalize_tools_for_model_with_prefix(
tools,
self.prefix_mcp_tool_names,
&self.non_prefixed_mcp_tool_servers,
);
trace!(
available_server_count,
unavailable_server_count,
tool_count = tools.len(),
"built MCP tool list"
);
(tools, errors, metadata)
}
#[instrument(level = "trace", skip_all)]
pub(crate) async fn capture_binding_with_metadata(
self: &Arc<Self>,
config: Arc<crate::McpConfig>,
plugins_available: bool,
required_servers: &[String],
required_plugins: &HashSet<String>,
) -> McpBinding {
let mut listed_tools = Vec::new();
let mut clients = HashMap::new();
let catalog_log_enabled = tracing::enabled!(
target: "akode_otel.trace_safe",
tracing::Level::INFO
);
let catalog_metrics = akode_otel::global();
let catalog_measurement_enabled = catalog_log_enabled || catalog_metrics.is_some();
let product_sku = akode_otel::bounded_product_sku(Some(crate::mcp::MCP_CATALOG_PRODUCT_SKU))
.unwrap_or("unknown");
let optional_mcp_startup_grace = config.optional_mcp_startup_grace;
let server_snapshots = join_all(self.servers.iter().map(|(server_name, view)| async move {
if !view
.connection
.client
.startup_complete
.load(Ordering::Acquire)
{
let required = self.required_servers.binary_search(server_name).is_ok();
// Keep the catalog that lets us skip startup even if it expires during the wait.
let cached_tools = view.cached_startup_tools(/*fallback*/ None);
let has_cached_tools = cached_tools.is_some();
let must_wait_for_startup = (required
&& (!view.allows_cached_startup() || !has_cached_tools))
|| required_servers
.iter()
.any(|required| required == server_name)
|| (self.is_selected_plugin_mcp_server(server_name)
&& self
.plugin_id_for_mcp_server_name(server_name)
.is_some_and(|plugin_id| required_plugins.contains(plugin_id)));
if !must_wait_for_startup && has_cached_tools {
trace!(server_name = %server_name, "using cached MCP catalog without waiting for startup");
return (server_name, view, cached_tools);
}
if !must_wait_for_startup && optional_mcp_startup_grace.is_zero() {
if let Some(cache) = view.connection.client.tool_catalog_cache_context.as_ref()
{
cache.optional_startup_deadline(
tokio::time::Instant::now(),
optional_mcp_startup_grace,
);
}
let _ = view.connection.client().await;
} else if !must_wait_for_startup {
let optional_startup_deadline = if view.connection.startup_is_dormant() {
tokio::time::Instant::now() + optional_mcp_startup_grace
} else {
*self.optional_startup_deadline.get_or_init(|| {
tokio::time::Instant::now() + optional_mcp_startup_grace
})
};
let startup_deadline = view
.connection
.client
.tool_catalog_cache_context
.as_ref()
.map(|cache| {
cache.optional_startup_deadline(
optional_startup_deadline,
optional_mcp_startup_grace,
)
})
.unwrap_or(optional_startup_deadline);
if tokio::time::timeout_at(startup_deadline, view.connection.client())
.await
.is_err()
{
trace!(server_name = %server_name, "omitting pending optional MCP server");
}
return (server_name, view, cached_tools);
}
let _ = view.connection.client().await;
return (server_name, view, cached_tools);
}
(server_name, view, None)
}))
.await;
let server_results = join_all(server_snapshots.into_iter().map(|(server_name, view, cached_tools)| async move {
let startup_pending = !view
.connection
.client
.startup_complete
.load(Ordering::Acquire);
let accepts_cached_catalog = view.startup_readiness == McpStartupReadiness::Catalog;
let cached_tools = if startup_pending
|| (accepts_cached_catalog && view.connection.client.ready_client().is_none())
{
view.cached_startup_tools(cached_tools)
} else {
None
};
let (client, server_tools, catalog_source) = if let Some(cached_tools) = cached_tools {
(None, cached_tools, "cached")
} else {
// A server may opt out of caching after the first pass. Required catalog
// readiness must then wait for discovery rather than silently omit its tools.
if startup_pending
&& !(accepts_cached_catalog
&& self.required_servers.binary_search(server_name).is_ok())
{
return None;
}
let Ok(mut client) = view.connection.client().await else {
trace!(server_name = %server_name, "omitting MCP server without an exact ready client");
return None;
};
view.refresh_notified_catalog(server_name, &client).await;
client.tool_timeout = view.tool_timeout;
let snapshot = client.tool_catalog.read(Arc::new).await;
let server_tools = snapshot.tools.to_vec();
(
Some((Arc::new(client), snapshot)),
server_tools,
"live",
)
};
let raw_definition_json_bytes = if catalog_measurement_enabled {
tool_definition_json_bytes(server_tools.iter().map(|tool| &tool.tool))
} else {
0
};
if catalog_log_enabled {
let plugin_id = self.plugin_id_for_mcp_server_name(server_name);
emit_binding_catalog(
product_sku,
if plugin_id.is_some() {
"plugin"
} else {
"configured"
},
plugin_id,
catalog_source,
server_tools.len(),
raw_definition_json_bytes,
);
}
let server_tools = filter_tools(server_tools, &view.tool_filter);
let server_tools = crate::rmcp_client::prepare_regular_mcp_tools_for_model(
server_tools,
&self.tool_plugin_context,
);
let server_tools = server_tools
.into_iter()
.map(|mut tool| {
if client.is_none()
&& let Some(annotations) = tool.tool.annotations.as_mut()
{
annotations.read_only_hint = None;
}
Self::with_server_metadata(tool, &view.metadata)
})
.collect::<Vec<_>>();
Some((
server_name.clone(),
client,
server_tools,
raw_definition_json_bytes,
))
}))
.await;
let mut raw_definition_json_bytes = 0usize;
for (server_name, client, server_tools, server_definition_json_bytes) in
server_results.into_iter().flatten()
{
raw_definition_json_bytes =
raw_definition_json_bytes.saturating_add(server_definition_json_bytes);
if let Some((client, snapshot)) = client {
clients.insert(server_name, (client, snapshot));
}
listed_tools.extend(server_tools);
}
if let Some(metrics) = catalog_metrics.as_ref() {
record_binding_catalog_size(metrics, product_sku, raw_definition_json_bytes);
}
let listed_tools = normalize_tools_for_model_with_prefix(
listed_tools,
self.prefix_mcp_tool_names,
&self.non_prefixed_mcp_tool_servers,
);
let mut tools = Vec::with_capacity(listed_tools.len());
let mut pending_calls = Vec::with_capacity(listed_tools.len());
for tool_info in listed_tools {
let model_visible = crate::tool_is_model_visible(&tool_info);
let Some((client, snapshot)) = clients.get(&tool_info.server_name) else {
if model_visible {
tools.push(tool_info);
}
continue;
};
if config
.permission_profile_for_server(&tool_info.server_name)
.is_none()
{
trace!(
server_name = %tool_info.server_name,
tool_name = %tool_info.tool.name,
"omitting MCP tool without an exact ready client"
);
continue;
}
let pending_tool_info = if model_visible {
let tool_index = tools.len();
tools.push(tool_info);
PendingCallToolInfo::BindingCatalog(tool_index)
} else {
PendingCallToolInfo::Owned(tool_info.into())
};
pending_calls.push((pending_tool_info, Arc::clone(client), Arc::clone(snapshot)));
}
let tools: Arc<[ToolInfo]> = tools.into();
let mut calls = std::collections::HashMap::with_capacity(pending_calls.len());
for (pending_tool_info, client, snapshot) in pending_calls {
let tool_info = match pending_tool_info {
PendingCallToolInfo::BindingCatalog(tool_index) => {
PreparedToolInfo::from_binding_catalog(Arc::clone(&tools), tool_index)
}
PendingCallToolInfo::Owned(tool_info) => tool_info,
};
let Some(call) = self.prepare_call(tool_info, client, Arc::clone(&config), snapshot)
else {
continue;
};
calls.insert(
(
call.server_name().to_string(),
call.tool_info().tool.name.to_string(),
),
call,
);
}
let clients = Arc::new(McpBindingClients::new(
clients
.into_iter()
.map(|(server_name, (client, _))| (server_name, client))
.collect(),
));
McpBinding::new(
Arc::clone(self),
clients,
config,
plugins_available,
tools,
calls,
)
}
#[instrument(level = "trace", skip_all)]
pub(crate) async fn prepare_call_for_tool(
self: &Arc<Self>,
config: Arc<crate::McpConfig>,
advertised_tool: &ToolInfo,
) -> Result<PreparedMcpCall> {
let server_name = &advertised_tool.server_name;
let unavailable = || advertised_tool.unavailable_to_model_error();
let view = self.servers.get(server_name).ok_or_else(unavailable)?;
if !view.tool_filter.allows(&advertised_tool.tool.name) {
return Err(unavailable());
}
// Recovery belongs to readiness, before the caller acquires the tool execution lock.
let mut client = view
.connection
.client()
.await
.with_context(|| format!("Could not start MCP server `{server_name}`"))?;
client.tool_timeout = view.tool_timeout;
let snapshot = client.tool_catalog.read(Arc::new).await;
let current_tool = snapshot
.tools
.iter()
.find(|tool| {
tool.server_name == *server_name
&& tool.tool.name == advertised_tool.tool.name
})
.ok_or_else(unavailable)?;
let mut tool_info = crate::rmcp_client::prepare_regular_mcp_tools_for_model(
vec![current_tool.clone()],
&self.tool_plugin_context,
)
.pop()
.filter(tool_is_model_visible)
.ok_or_else(unavailable)?;
tool_info = Self::with_server_metadata(tool_info, &view.metadata);
// Preserve the globally normalized identity advertised to the model, while
// taking schema, annotations, and approval metadata from the current catalog.
tool_info
.callable_namespace
.clone_from(&advertised_tool.callable_namespace);
tool_info
.callable_name
.clone_from(&advertised_tool.callable_name);
self.prepare_call(tool_info, Arc::new(client), config, snapshot)
.ok_or_else(unavailable)
}
fn prepare_call(
self: &Arc<Self>,
tool_info: impl Into<PreparedToolInfo>,
client: Arc<ManagedClient>,
config: Arc<crate::McpConfig>,
tool_catalog_snapshot: Arc<ToolCatalogSnapshot>,
) -> Option<PreparedMcpCall> {
let tool_info = tool_info.into();
let (server_metadata, plugin_id, selected_plugin_server) = {
let server_name = &tool_info.get().server_name;
let view = self.servers.get(server_name)?;
(
view.metadata.clone(),
self.plugin_id_for_mcp_server_name(server_name)
.map(str::to_string),
self.is_selected_plugin_mcp_server(server_name),
)
};
PreparedMcpCall::new(
Arc::clone(self),
client,
config,
tool_catalog_snapshot,
tool_info,
server_metadata,
plugin_id,
selected_plugin_server,
)
}
fn with_server_metadata(mut tool: ToolInfo, metadata: &McpServerMetadata) -> ToolInfo {
tool.supports_parallel_tool_calls = metadata.supports_parallel_tool_calls;
tool.server_origin = metadata
.origin
.as_ref()
.map(|origin| origin.as_str().to_string());
tool
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,568 @@
//! Shares MCP 2026-07-28 connections while keeping each chat's ownership separate.
//!
//! The protocol requires request-scoped context and explicit handles for application state.
//! Request continuations use the calling chat's elicitation authority. Legacy connections and
//! servers that request input during startup remain private.
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::Weak;
use std::time::Duration;
use akode_async_utils::OrCancelExt;
use akode_login::AuthChangeState;
use akode_login::AuthManager;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::RequestScope;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::SendElicitation;
use futures::FutureExt;
use futures::future::BoxFuture;
use futures::future::Shared;
use rmcp::model::ElicitationAction;
use rmcp::model::ProtocolVersion;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use uuid::Uuid;
use crate::client_tool_catalog::ClientToolCatalog;
use crate::client_tool_catalog::ToolCatalogSnapshot;
use crate::rmcp_client::ManagedClient;
use crate::rmcp_client::ManagedClientFuture;
use crate::rmcp_client::StartupOutcomeError;
use crate::rmcp_client::list_tools_for_client_uncached;
use crate::server::McpServerConnectionIdentity;
use crate::tool_catalog_cache::McpToolCatalogCacheContext;
/// Opt-in resource lifecycle for negotiated stdio connections. Tool calls and resource reads
/// carry a host-owned lease ID. Catalog requests remain independent of a particular lease.
pub(crate) const LEASE_CAPABILITY: &str = "codex/connection-lease";
/// Request metadata set by the host when a connection lease is negotiated.
pub const LEASE_META_KEY: &str = "codex/connectionLease";
const LEASE_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone)]
pub(crate) struct ServerLease {
pub(crate) id: Uuid,
pub(crate) requests: RequestScope,
opened: Shared<BoxFuture<'static, Result<(), StartupOutcomeError>>>,
}
impl ServerLease {
async fn release(self, client: &RmcpClient, entry: &Arc<Entry>) {
if self.opened.await.is_err() {
return;
}
// MCP cancellation has no acknowledgement. The server owns any handler still
// winding down after it receives these cancellation writes and then release.
self.requests.cancel_and_wait().await;
if let Err(error) = client
.send_custom_request(
"codex/connection/release",
Some(serde_json::json!({"leaseId": self.id})),
)
.await
{
entry.remove_from_pool();
tracing::warn!(%error, "failed to release a server-side MCP lease");
}
}
}
/// Process-owned registry for compatible local stdio servers using MCP 2026-07-28.
#[derive(Clone, Default)]
pub struct McpConnectionPool {
entries: Arc<Mutex<Vec<Weak<Entry>>>>,
}
#[derive(Clone)]
pub(crate) struct ConnectionKey {
pub(crate) server_name: String,
pub(crate) identity: McpServerConnectionIdentity,
pub(crate) auth_state: Option<(Arc<AuthManager>, AuthChangeState)>,
pub(crate) startup_timeout: Duration,
pub(crate) catalog_item_limit: usize,
}
impl PartialEq for ConnectionKey {
fn eq(&self, other: &Self) -> bool {
self.server_name == other.server_name
&& self.identity == other.identity
&& self.startup_timeout == other.startup_timeout
&& self.catalog_item_limit == other.catalog_item_limit
&& match (&self.auth_state, &other.auth_state) {
(Some((left, left_state)), Some((right, right_state))) => {
Arc::ptr_eq(left, right)
&& left_state.owner_generation == right_state.owner_generation
&& left_state.source_generation == right_state.source_generation
&& left_state.login_generation == right_state.login_generation
}
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
}
}
}
struct Entry {
runtime: tokio::runtime::Handle,
key: ConnectionKey,
client: ManagedClientFuture,
capabilities: Arc<Mutex<Option<serde_json::Value>>>,
// Share immutable definitions; every chat owns its catalog revisions and refresh locks.
catalog: Mutex<Option<ToolCatalogSnapshot>>,
cancellation: CancellationToken,
/// Wakes joiners without cancelling the creator's startup.
sharing_declined: CancellationToken,
owners: Weak<LeaseOwners>,
pool: Weak<Mutex<Vec<Weak<Entry>>>>,
}
/// One strong reference per active chat lease, independent of retained client bindings.
/// Every strong reference must be consumed by `ConnectionLease::release`.
struct LeaseOwners;
#[derive(Clone, Copy, PartialEq, Eq)]
enum AcquisitionRole {
Creator,
Joiner,
}
impl Entry {
fn remove_from_pool(self: &Arc<Self>) {
if let Some(pool) = self.pool.upgrade() {
pool.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.retain(|entry| !entry.ptr_eq(&Arc::downgrade(self)));
}
}
async fn tool_catalog_for_chat(
&self,
client: &ManagedClient,
role: AcquisitionRole,
cache_context: Option<&McpToolCatalogCacheContext>,
) -> Result<Arc<ClientToolCatalog>, StartupOutcomeError> {
// Listing must not update another chat's catalog or wait for its calls.
let listed = if role == AcquisitionRole::Creator {
client.tool_catalog.read(|snapshot| snapshot).await
} else {
let fetch_ticket = cache_context.map(|context| (context, context.begin_fetch()));
let (tools, meta) = list_tools_for_client_uncached(
&self.key.server_name,
&client.client,
Some(self.key.startup_timeout),
self.key.catalog_item_limit,
client.server_instructions.as_deref(),
)
.await?;
if let Some((context, mut ticket)) = fetch_ticket {
if context.track_tool_list_changes {
ticket.tool_list_revision = Some(client.client.tool_list_revision());
}
context.publish_if_newest(ticket, &tools, meta.clone());
}
ToolCatalogSnapshot {
revision: 0,
tools: tools.into(),
meta,
}
};
let mut catalog = self
.catalog
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let catalog = catalog.get_or_insert_with(|| listed.clone());
if catalog.tools != listed.tools || catalog.meta != listed.meta {
*catalog = listed;
}
Ok(Arc::new(ClientToolCatalog::new(
Arc::clone(&catalog.tools),
catalog.meta.clone(),
)))
}
}
/// A chat releases its lease explicitly on shutdown, even while bindings retain its client.
pub(crate) struct ConnectionLease {
entry: Arc<Entry>,
owner: Mutex<Option<Arc<LeaseOwners>>>,
cancellation: CancellationToken,
slot: Arc<ConnectionSlot>,
server_lease: OnceLock<ServerLease>,
}
/// Tracks an acquisition without retaining its lease, including before startup completes.
#[derive(Default)]
pub(crate) struct ConnectionSlot {
state: Mutex<SlotState>,
shutdown_tasks: OnceLock<TaskTracker>,
}
#[derive(Default)]
enum SlotState {
#[default]
Available,
Acquired(Weak<Entry>),
Retired,
}
impl ConnectionSlot {
pub(crate) fn retire(&self) {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let SlotState::Acquired(entry) = std::mem::replace(&mut *state, SlotState::Retired)
&& let Some(entry) = entry.upgrade()
{
entry.remove_from_pool();
}
}
pub(crate) async fn wait_for_shutdown(&self) {
if let Some(tasks) = self.shutdown_tasks.get() {
tasks.close();
tasks.wait().await;
}
}
}
#[derive(Clone, Default)]
pub(crate) enum ConnectionSharing {
#[default]
Private,
Negotiated,
/// The server declined sharing, but its creator still owns the startup entry.
Owned(Arc<ConnectionLease>),
Shared(Arc<ConnectionLease>),
}
impl ConnectionSharing {
/// Identifies this chat to servers that negotiated per-chat leases.
pub(crate) fn server_lease(&self) -> Option<&ServerLease> {
match self {
Self::Shared(lease) => lease.server_lease.get(),
_ => None,
}
}
}
impl McpConnectionPool {
pub(crate) async fn connect(
&self,
slot: Arc<ConnectionSlot>,
key: ConnectionKey,
capabilities: Arc<Mutex<Option<serde_json::Value>>>,
tool_catalog_cache_context: Option<McpToolCatalogCacheContext>,
cancellation: CancellationToken,
start: impl Fn(CancellationToken, Option<CancellationToken>) -> ManagedClientFuture + Sync,
) -> Result<ManagedClient, StartupOutcomeError> {
let (lease, role) = self
.acquire(key, &slot, Arc::clone(&capabilities), &cancellation, &start)
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
let outcome = tokio::select! {
outcome = lease.entry.client.clone() => Some(outcome),
() = lease.entry.sharing_declined.cancelled(), if role == AcquisitionRole::Joiner => None,
() = cancellation.cancelled() => return Err(StartupOutcomeError::Cancelled),
};
match outcome {
Some(Ok(mut client))
if role == AcquisitionRole::Creator
|| matches!(client.connection_sharing, ConnectionSharing::Negotiated) =>
{
let shared_capabilities = lease
.entry
.capabilities
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let server_tracks_leases = shared_capabilities
.as_ref()
.and_then(|caps| caps.get("extensions"))
.and_then(|caps| caps.get(LEASE_CAPABILITY))
.is_some();
*capabilities
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = shared_capabilities;
client.connection_sharing =
if matches!(client.connection_sharing, ConnectionSharing::Negotiated) {
client.client.enable_request_cancellation();
client.tool_catalog = lease
.entry
.tool_catalog_for_chat(
&client,
role,
tool_catalog_cache_context.as_ref(),
)
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
if server_tracks_leases {
lease
.open_on_server(Arc::clone(&client.client))
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
}
ConnectionSharing::Shared(lease)
} else {
lease.entry.remove_from_pool();
ConnectionSharing::Owned(lease)
};
Ok(client)
}
Some(Err(error)) if role == AcquisitionRole::Creator => Err(error),
_ => {
// Older or failed servers leave other chats to initialize privately
// with their own elicitation authority.
drop(lease);
start(cancellation, /*sharing_declined*/ None).await
}
}
}
async fn acquire(
&self,
key: ConnectionKey,
slot: &Arc<ConnectionSlot>,
capabilities: Arc<Mutex<Option<serde_json::Value>>>,
cancellation: &CancellationToken,
start: impl Fn(CancellationToken, Option<CancellationToken>) -> ManagedClientFuture,
) -> Result<(Arc<ConnectionLease>, AcquisitionRole), StartupOutcomeError> {
loop {
let (lease, role) = {
let mut state = slot
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if matches!(&*state, SlotState::Retired) {
return Err(StartupOutcomeError::Cancelled);
}
let mut entries = self
.entries
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
entries.retain(|entry| entry.strong_count() > 0);
let lease_cancellation = cancellation.child_token();
let existing = entries
.iter()
.filter_map(Weak::upgrade)
.filter(|entry| {
entry.key == key
&& !entry.sharing_declined.is_cancelled()
&& entry.client.peek().is_none_or(|result| {
result.as_ref().is_ok_and(|client| {
matches!(
client.connection_sharing,
ConnectionSharing::Negotiated
)
})
})
})
.find_map(|entry| entry.owners.upgrade().map(|owner| (entry, owner)));
let (entry, owner, role) = if let Some((entry, owner)) = existing {
(entry, owner, AcquisitionRole::Joiner)
} else {
let startup_cancellation = CancellationToken::new();
let sharing_declined = CancellationToken::new();
let client =
start(startup_cancellation.clone(), Some(sharing_declined.clone()));
// Startup belongs to the connection, including if its first chat is cancelled.
tokio::spawn(client.clone());
let owner = Arc::new(LeaseOwners);
let entry = Arc::new(Entry {
runtime: tokio::runtime::Handle::current(),
key: key.clone(),
client,
capabilities: Arc::clone(&capabilities),
catalog: Mutex::new(None),
cancellation: startup_cancellation,
sharing_declined,
owners: Arc::downgrade(&owner),
pool: Arc::downgrade(&self.entries),
});
entries.push(Arc::downgrade(&entry));
(entry, owner, AcquisitionRole::Creator)
};
let lease = Arc::new(ConnectionLease {
entry,
owner: Mutex::new(Some(owner)),
cancellation: lease_cancellation,
slot: Arc::clone(slot),
server_lease: OnceLock::new(),
});
*state = SlotState::Acquired(Arc::downgrade(&lease.entry));
(lease, role)
};
if let Some(Ok(client)) = lease.entry.client.peek()
&& client.client.is_closed().await
{
lease.entry.remove_from_pool();
lease.release();
continue;
}
return Ok((lease, role));
}
}
}
impl ConnectionLease {
pub(crate) fn cancellation(&self) -> &CancellationToken {
&self.cancellation
}
/// Register a unique logical owner before publishing the chat's client. Release retains
/// the same future so cancellation during open cannot reorder the two lifecycle requests.
async fn open_on_server(&self, client: Arc<RmcpClient>) -> Result<(), StartupOutcomeError> {
let id = Uuid::new_v4();
let opened = async move {
client
.send_custom_request(
"codex/connection/open",
Some(serde_json::json!({"leaseId": id})),
)
.await
.map(|_| ())
.map_err(StartupOutcomeError::from)
}
.boxed()
.shared();
let opened = {
// Publish while we still own the lease so a racing unload will wait for this open.
let owner = self
.owner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if owner.is_none() {
return Err(StartupOutcomeError::Cancelled);
}
self.server_lease
.get_or_init(|| ServerLease {
id,
opened,
requests: RequestScope::new(
self.entry.runtime.clone(),
self.cancellation.clone(),
),
})
.opened
.clone()
};
// Bound chat startup while preserving the actual reply for a racing release.
tokio::time::timeout(LEASE_REQUEST_TIMEOUT, opened)
.await
.map_err(|_| {
self.entry.remove_from_pool();
anyhow::anyhow!("timed out waiting for the MCP server to open a connection lease")
})?
}
/// Track this chat's server-side release or the final shutdown of the physical connection.
pub(crate) fn release(&self) -> Option<&ConnectionSlot> {
self.cancellation.cancel();
let mut owner = self
.owner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let server_lease = if Arc::into_inner(owner.take()?).is_some() {
self.entry.cancellation.cancel();
self.entry.remove_from_pool();
None
} else {
Some(self.server_lease.get()?.clone())
};
let entry = Arc::clone(&self.entry);
// The chat must be able to await its final release even when cancellation drops the lease.
let tasks = self.slot.shutdown_tasks.get_or_init(TaskTracker::new);
let completion = tasks.token();
self.entry.runtime.spawn(async move {
match (entry.client.clone().await, server_lease) {
(Ok(client), None) => client.client.shutdown().await,
(Ok(client), Some(lease)) => {
let release = lease
.release(&client.client, &entry)
.or_cancel(&entry.cancellation);
tokio::pin!(release);
if tokio::time::timeout(LEASE_REQUEST_TIMEOUT, &mut release)
.await
.is_err()
{
// Let the chat unload. A late open reply or cancellation write
// must still precede release while other chats own the connection.
entry.remove_from_pool();
drop(completion);
let _ = release.await;
}
}
(Err(error), _) => error.wait_for_shutdown().await,
}
});
Some(&self.slot)
}
}
impl Drop for ConnectionLease {
fn drop(&mut self) {
let _ = self.release();
}
}
/// Releases waiting chats when startup becomes private and detaches callbacks after sharing.
pub(crate) struct SharingNegotiation {
callback: Arc<Mutex<Option<SendElicitation>>>,
sharing_declined: CancellationToken,
}
impl SharingNegotiation {
pub(crate) fn new(
sender: SendElicitation,
sharing_declined: CancellationToken,
) -> (Self, SendElicitation) {
let callback = Arc::new(Mutex::new(Some(sender)));
let negotiation = Self {
callback: Arc::clone(&callback),
sharing_declined: sharing_declined.clone(),
};
let sender: SendElicitation = Box::new(move |id, request| {
let callback = callback
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(callback) = callback.as_ref() {
// Client input binds this startup to its original chat.
sharing_declined.cancel();
callback(id, request)
} else {
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: None,
}))
.boxed()
}
});
(negotiation, sender)
}
pub(crate) fn finish(self, protocol_version: &ProtocolVersion) -> ConnectionSharing {
let mut callback = self
.callback
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if *protocol_version == ProtocolVersion::V_2026_07_28
&& !self.sharing_declined.is_cancelled()
{
callback.take();
ConnectionSharing::Negotiated
} else {
self.sharing_declined.cancel();
ConnectionSharing::Private
}
}
}
#[cfg(test)]
#[path = "connection_pool_tests.rs"]
pub(crate) mod tests;

View File

@@ -0,0 +1,849 @@
//! Tests for shared MCP connection ownership and protocol negotiation.
use super::*;
use crate::McpServerPermissions;
use crate::binding_clients::McpBindingClients;
use crate::connection_manager::tests::create_ready_async_managed_client;
use crate::connection_manager::tests::create_test_tool;
use crate::connection_manager::tests::reusable_server_identity;
use crate::runtime::McpRuntimeContext;
use akode_config::McpServerConfig;
use akode_exec_server::EnvironmentManager;
use akode_login::CodexAuth;
use akode_rmcp_client::Elicitation;
use akode_rmcp_client::InProcessTransportFactory;
use akode_rmcp_client::RmcpClient;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use rmcp::ServerHandler;
use rmcp::ServiceExt;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::ListToolsResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ProtocolVersion;
use rmcp::model::ServerCapabilities;
use rmcp::model::ServerConfig;
use rmcp::model::Tool;
use rmcp::service::RequestContext;
use rmcp::service::RoleServer;
use serde_json::json;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::sync::Notify;
use tokio::sync::Semaphore;
use tokio::sync::mpsc;
#[derive(Clone)]
pub(crate) struct TestServer {
tools: Arc<Mutex<Vec<Tool>>>,
block_listing: Arc<AtomicBool>,
started_listings: Arc<Semaphore>,
cancelled_listings: Arc<Semaphore>,
}
impl Default for TestServer {
fn default() -> Self {
Self {
tools: Arc::new(Mutex::new(vec![
create_test_tool("test_server", "test").tool,
])),
block_listing: Arc::default(),
started_listings: Arc::new(Semaphore::new(/*permits*/ 0)),
cancelled_listings: Arc::new(Semaphore::new(/*permits*/ 0)),
}
}
}
impl ServerHandler for TestServer {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_tools()
.enable_resources()
.build(),
)
}
async fn call_tool(
&self,
_request: rmcp::model::CallToolRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
Ok(rmcp::model::CallToolResult::success(Vec::new()).into())
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, rmcp::ErrorData> {
if self.block_listing.load(Ordering::Acquire) {
context.ct.cancelled().await;
self.cancelled_listings.add_permits(1);
return Err(rmcp::ErrorData::internal_error(
"listing cancelled",
/*data*/ None,
));
}
Ok(ListToolsResult::with_all_items(
self.tools.lock().unwrap().clone(),
))
}
async fn list_resources(
&self,
_request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> Result<ListResourcesResult, rmcp::ErrorData> {
if self.block_listing.load(Ordering::Acquire) {
self.started_listings.add_permits(1);
context.ct.cancelled().await;
self.cancelled_listings.add_permits(1);
}
Ok(ListResourcesResult::with_all_items(Vec::new()))
}
async fn list_resource_templates(
&self,
_request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> Result<ListResourceTemplatesResult, rmcp::ErrorData> {
if self.block_listing.load(Ordering::Acquire) {
self.started_listings.add_permits(1);
context.ct.cancelled().await;
self.cancelled_listings.add_permits(1);
}
Ok(ListResourceTemplatesResult::with_all_items(Vec::new()))
}
}
impl InProcessTransportFactory for TestServer {
fn open(&self) -> BoxFuture<'static, std::io::Result<tokio::io::DuplexStream>> {
let server = self.clone();
async move {
let (client, transport) = tokio::io::duplex(4096);
tokio::spawn(async move {
server
.serve(transport)
.await
.unwrap()
.waiting()
.await
.unwrap();
});
Ok(client)
}
.boxed()
}
}
pub(crate) fn key(context: &McpRuntimeContext, config: &McpServerConfig) -> ConnectionKey {
ConnectionKey {
server_name: "test_server".to_string(),
identity: reusable_server_identity("test_server", config, context),
auth_state: None,
startup_timeout: Duration::from_secs(30),
catalog_item_limit: 100,
}
}
pub(crate) fn context() -> McpRuntimeContext {
McpRuntimeContext::new(
Arc::new(EnvironmentManager::default_for_tests()),
std::env::temp_dir(),
)
}
pub(crate) fn config() -> McpServerConfig {
serde_json::from_value(json!({"command": "test-server", "args": ["server.mjs"]})).unwrap()
}
pub(crate) fn startup(
sharing: ConnectionSharing,
starts: Arc<AtomicUsize>,
first_started: Arc<Notify>,
release_first: Arc<Notify>,
server: impl InProcessTransportFactory + Clone + 'static,
) -> impl Fn(CancellationToken, Option<CancellationToken>) -> ManagedClientFuture {
move |cancellation, _sharing_declined| {
let sharing = sharing.clone();
let starts = Arc::clone(&starts);
let first_started = Arc::clone(&first_started);
let release_first = Arc::clone(&release_first);
let server = server.clone();
async move {
async {
if starts.fetch_add(1, Ordering::SeqCst) == 0 {
first_started.notify_one();
release_first.notified().await;
}
let mut client = create_ready_async_managed_client(Vec::new())
.await
.client()
.await?;
client.client = Arc::new(
RmcpClient::new_in_process_client(Arc::new(server))
.await
.expect("create test MCP client"),
);
client
.client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("test", "1"),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(30)),
Box::new(|_, _| {
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
}))
.boxed()
}),
)
.await?;
let (tools, meta) = list_tools_for_client_uncached(
"test_server",
&client.client,
/*timeout*/ None,
/*catalog_item_limit*/ 100,
/*server_instructions*/ None,
)
.await?;
client.tool_catalog =
Arc::new(ClientToolCatalog::new(tools, meta));
client.connection_sharing = sharing;
Ok(client)
}
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))
}
.boxed()
.shared()
}
}
struct LeaseFrame {
message: serde_json::Value,
replies: mpsc::UnboundedSender<serde_json::Value>,
}
impl LeaseFrame {
fn reply(&self, result: serde_json::Value) {
self.replies
.send(json!({"jsonrpc": "2.0", "id": self.message["id"], "result": result}))
.unwrap();
}
}
#[derive(Clone)]
struct LeaseTransport(mpsc::UnboundedSender<LeaseFrame>);
impl InProcessTransportFactory for LeaseTransport {
fn open(&self) -> BoxFuture<'static, std::io::Result<tokio::io::DuplexStream>> {
let (client, server) = tokio::io::duplex(4096);
let (reader, mut writer) = tokio::io::split(server);
let mut lines = BufReader::new(reader).lines();
let frames = self.0.clone();
let (replies, mut responses) = mpsc::unbounded_channel();
tokio::spawn(async move {
loop {
tokio::select! {
Some(response) = responses.recv() => {
writer.write_all(format!("{response}\n").as_bytes()).await.unwrap();
}
line = lines.next_line() => {
let Some(line) = line.unwrap() else { break };
let frame = LeaseFrame {
message: serde_json::from_str(&line).unwrap(),
replies: replies.clone(),
};
match frame.message["method"].as_str().unwrap() {
"initialize" => frame.reply(json!({
"protocolVersion": "2025-06-18", "capabilities": {"tools": {}},
"serverInfo": {"name": "test", "version": "1"}
})),
"notifications/initialized" => {}
"tools/list" => frame.reply(json!({"tools": []})),
_ => frames.send(frame).unwrap(),
}
}
}
}
});
futures::future::ready(Ok(client)).boxed()
}
}
struct LeasePeer {
pool: McpConnectionPool,
key: ConnectionKey,
transport: LeaseTransport,
frames: mpsc::UnboundedReceiver<LeaseFrame>,
}
impl LeasePeer {
fn new() -> Self {
let (tx, frames) = mpsc::unbounded_channel();
Self {
pool: McpConnectionPool::default(),
key: key(&context(), &config()),
transport: LeaseTransport(tx),
frames,
}
}
fn attach(&self) -> tokio::task::JoinHandle<Result<ManagedClient, StartupOutcomeError>> {
let pool = self.pool.clone();
let key = self.key.clone();
let transport = self.transport.clone();
tokio::spawn(async move {
let ready = Arc::<Notify>::default();
ready.notify_one();
let launch = startup(
ConnectionSharing::Negotiated,
Arc::default(),
Arc::default(),
ready,
transport,
);
pool.connect(
Arc::default(),
key,
Arc::new(Mutex::new(Some(
json!({"extensions": {LEASE_CAPABILITY: {}}}),
))),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
launch,
)
.await
})
}
async fn next(&mut self, method: &str) -> LeaseFrame {
let frame = tokio::time::timeout(Duration::from_secs(2), self.frames.recv())
.await
.expect("expected a frame from the client")
.unwrap();
assert_eq!(frame.message["method"], method);
frame
}
async fn chat(&mut self) -> (ManagedClient, serde_json::Value) {
let attach = self.attach();
let open = self.next("codex/connection/open").await;
open.reply(json!({}));
(
attach.await.unwrap().unwrap(),
open.message["params"]["leaseId"].clone(),
)
}
}
#[tokio::test(start_paused = true)]
async fn releasing_lease_cancels_pending_call_before_release() {
let mut peer = LeasePeer::new();
let (first, first_id) = peer.chat().await;
let (other, other_id) = peer.chat().await;
let call = first.call_tool(
"wait".into(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
);
tokio::pin!(call);
let request = tokio::select! {
result = &mut call => panic!("call completed without a reply: {result:?}"),
frame = peer.next("tools/call") => frame,
};
let ConnectionSharing::Shared(lease) = &first.connection_sharing else {
panic!("expected shared lease")
};
lease.release();
// Leave the caller unpolled: the release must drive the cancellation write itself.
let cancel = peer.next("notifications/cancelled").await;
assert_eq!(cancel.message["params"]["requestId"], request.message["id"]);
let release = peer.next("codex/connection/release").await;
assert_eq!(release.message["params"]["leaseId"], first_id);
release.reply(json!({}));
assert!(call.await.is_err());
let (result, ()) = tokio::join!(
other.call_tool(
"test".into(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
),
async {
let request = peer.next("tools/call").await;
assert_eq!(request.message["params"]["_meta"][LEASE_META_KEY], other_id);
request.reply(json!({"content": []}));
}
);
result.unwrap();
}
#[tokio::test(start_paused = true)]
async fn dropping_lease_outside_runtime_releases_it() {
let mut peer = LeasePeer::new();
let (_other, _) = peer.chat().await;
let (chat, id) = peer.chat().await;
std::thread::spawn(move || drop(chat)).join().unwrap();
let release = peer.next("codex/connection/release").await;
assert_eq!(release.message["params"]["leaseId"], id);
release.reply(json!({}));
}
#[tokio::test(start_paused = true)]
async fn timed_out_open_is_released_after_the_server_acknowledges_it() {
let mut peer = LeasePeer::new();
let (_other, _) = peer.chat().await;
let attach = peer.attach();
let open = peer.next("codex/connection/open").await;
tokio::time::advance(LEASE_REQUEST_TIMEOUT).await;
assert!(attach.await.unwrap().is_err());
assert!(
tokio::time::timeout(Duration::from_secs(1), peer.frames.recv())
.await
.is_err()
);
open.reply(json!({}));
let release = peer.next("codex/connection/release").await;
assert_eq!(
release.message["params"]["leaseId"],
open.message["params"]["leaseId"]
);
release.reply(json!({}));
}
#[tokio::test]
async fn shared_startup_survives_first_chat_cancellation_and_rejects_released_bindings() {
let pool = McpConnectionPool::default();
let key = key(&context(), &config());
let server = TestServer::default();
let starts = Arc::new(AtomicUsize::new(0));
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let launch = startup(
ConnectionSharing::Negotiated,
Arc::clone(&starts),
Arc::clone(&started),
Arc::clone(&release),
server.clone(),
);
let first_cancel = CancellationToken::new();
let first = pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
first_cancel.clone(),
&launch,
);
let second = pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
);
tokio::pin!(first, second);
assert!(futures::poll!(&mut first).is_pending());
assert!(futures::poll!(&mut second).is_pending());
started.notified().await;
first_cancel.cancel();
assert!(matches!(first.await, Err(StartupOutcomeError::Cancelled)));
release.notify_one();
let client = second.await.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 1);
assert!(!client.client.is_closed().await);
let other = pool
.connect(
Arc::default(),
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
)
.await
.unwrap();
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
config
.server_permissions
.insert("test_server".to_string(), McpServerPermissions::Thread);
let prepared = crate::binding::PreparedMcpCall::new(
Arc::new(crate::connection_manager::McpConnectionSet::empty(
/*prefix_mcp_tool_names*/ true,
)),
Arc::new(client.clone()),
Arc::new(config),
client.tool_catalog.read(Arc::new).await,
create_test_tool("test_server", "test"),
crate::server::McpServerMetadata {
environment_id: "local".to_string(),
pollutes_memory: false,
origin: None,
supports_parallel_tool_calls: true,
default_tools_approval_mode: None,
tool_approval_modes: Default::default(),
},
/*plugin_id*/ None,
/*selected_plugin_server*/ false,
)
.unwrap();
let bindings = McpBindingClients::new(HashMap::from([(
"test_server".to_string(),
Arc::new(client.clone()),
)]));
server.block_listing.store(true, Ordering::Release);
let waiting = async {
tokio::join!(
bindings.list_resources("test_server", /*params*/ None),
bindings.list_resource_templates("test_server", /*params*/ None),
)
};
tokio::pin!(waiting);
tokio::select! {
_ = &mut waiting => panic!("resource listings must wait for cancellation"),
permits = server.started_listings.acquire_many(2) => permits.unwrap().forget(),
}
let mut owned = create_ready_async_managed_client(Vec::new()).await;
owned.client = futures::future::ready(Ok(client.clone())).boxed().shared();
owned.shutdown().await;
let (resources, templates) = waiting.await;
assert!(resources.is_err());
assert!(templates.is_err());
tokio::time::timeout(
Duration::from_secs(1),
server.cancelled_listings.acquire_many(2),
)
.await
.expect("released resource listings must be cancelled")
.unwrap()
.forget();
let prepared_error = prepared
.call_with_preparation(/*requested_timeout*/ None, || async {
panic!("released bindings must not perform irreversible preparation")
})
.await
.unwrap_err();
assert!(
prepared_error
.to_string()
.contains("lease has been released")
);
other
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
owned.client = futures::future::ready(Ok(other)).boxed().shared();
owned.shutdown().await;
}
#[tokio::test]
async fn callback_during_startup_releases_waiting_chats_without_sharing_authority() {
let pool = McpConnectionPool::default();
let key = key(&context(), &config());
let starts = Arc::new(AtomicUsize::new(0));
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let second_callback = Arc::new(Notify::new());
let release_second = Arc::new(Notify::new());
let callbacks = Arc::new(Mutex::new(Vec::new()));
let launch = |name| {
let launch = startup(
ConnectionSharing::Private,
Arc::clone(&starts),
Arc::clone(&started),
Arc::clone(&release),
TestServer::default(),
);
let callbacks = Arc::clone(&callbacks);
let second_callback = Arc::clone(&second_callback);
let release_second = Arc::clone(&release_second);
move |cancellation, sharing_declined: Option<CancellationToken>| {
let startup = launch(cancellation, sharing_declined.clone());
let callbacks = Arc::clone(&callbacks);
let second_callback = Arc::clone(&second_callback);
let release_second = Arc::clone(&release_second);
async move {
let mut client = startup.await?;
let (negotiation, callback) = SharingNegotiation::new(
Box::new(move |_, _| {
callbacks.lock().unwrap().push(name);
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
}))
.boxed()
}),
sharing_declined.unwrap_or_default(),
);
callback(
rmcp::model::RequestId::Number(0),
Elicitation::OpenAiForm {
meta: None,
message: "startup prompt".to_string(),
requested_schema: json!({}),
},
)
.await
.unwrap();
if name == "first" {
second_callback.notified().await;
} else {
second_callback.notify_one();
release_second.notified().await;
}
client.connection_sharing = negotiation.finish(&ProtocolVersion::V_2026_07_28);
Ok(client)
}
.boxed()
.shared()
}
};
let first = pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
launch("first"),
);
let second = pool.connect(
Arc::default(),
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
launch("second"),
);
tokio::pin!(first, second);
assert!(futures::poll!(&mut first).is_pending());
assert!(futures::poll!(&mut second).is_pending());
started.notified().await;
release.notify_one();
let first = tokio::time::timeout(Duration::from_secs(10), async {
tokio::select! {
first = &mut first => first,
_ = &mut second => panic!("the joining chat should still be starting"),
}
})
.await
.expect("the joining chat must start before the first finishes")
.unwrap();
first
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
let mut owner = create_ready_async_managed_client(Vec::new()).await;
owner.client = futures::future::ready(Ok(first.clone())).boxed().shared();
tokio::time::timeout(Duration::from_secs(10), owner.shutdown())
.await
.expect("private owner shutdown must not wait for the joining chat");
assert!(first.client.is_closed().await);
release_second.notify_one();
let second = second.await.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 2);
assert_eq!(*callbacks.lock().unwrap(), ["first", "second"]);
second
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
}
#[tokio::test]
async fn connection_key_changes_with_the_owner_but_survives_credential_refresh() {
let manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
let mut original = key(&context(), &config());
original.auth_state = Some((manager, AuthChangeState::default()));
let mut refreshed = original.clone();
refreshed.auth_state.as_mut().unwrap().1.generation += 1;
assert!(original == refreshed);
refreshed.auth_state.as_mut().unwrap().1.owner_generation += 1;
assert!(original != refreshed);
}
#[tokio::test(start_paused = true)]
async fn new_chat_relists_tools_without_invalidating_or_waiting_for_existing_calls() {
let pool = McpConnectionPool::default();
let key = key(&context(), &config());
let server = TestServer::default();
let starts = Arc::new(AtomicUsize::new(0));
let release = Arc::new(Notify::new());
release.notify_one();
let launch = startup(
ConnectionSharing::Negotiated,
Arc::clone(&starts),
Arc::default(),
release,
server.clone(),
);
let first = pool
.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
)
.await
.unwrap();
let before = first.tool_catalog.read(|snapshot| snapshot).await;
let release_call = Notify::new();
let call = first
.tool_catalog
.run_with_snapshot(&before, || release_call.notified());
tokio::pin!(call);
assert!(futures::poll!(&mut call).is_pending());
for tool_name in ["test", "new"] {
*server.tools.lock().unwrap() = vec![create_test_tool("test_server", tool_name).tool];
let second = tokio::time::timeout(
Duration::from_secs(1),
pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
),
)
.await
.expect("new chats must not wait for existing calls")
.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 1);
assert_eq!(
second
.tool_catalog
.read(|snapshot| snapshot.tools[0].tool.name.to_string())
.await,
tool_name
);
tokio::time::timeout(
Duration::from_secs(1),
second
.tool_catalog
.replace_for_test(vec![create_test_tool("test_server", "refreshed")]),
)
.await
.expect("one chat's refresh must not wait for another chat's calls");
assert_eq!(
first
.tool_catalog
.read(|snapshot| snapshot.tools[0].tool.name.to_string())
.await,
"test"
);
}
release_call.notify_one();
assert_eq!(call.await, Some(()));
server.block_listing.store(true, Ordering::Release);
let failed = pool
.connect(
Arc::default(),
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&launch,
)
.await;
assert!(failed.is_err());
let _cancelled =
tokio::time::timeout(Duration::from_secs(1), server.cancelled_listings.acquire())
.await
.expect("timed-out listings must be cancelled")
.unwrap();
first
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
}
#[tokio::test]
async fn negotiation_requires_the_stateless_protocol_and_detaches_startup_callbacks() {
for (protocol_version, expected_sharing, expected_action) in [
(
ProtocolVersion::V_2025_06_18,
false,
ElicitationAction::Decline,
),
(
ProtocolVersion::V_2026_07_28,
true,
ElicitationAction::Cancel,
),
] {
let (negotiation, callback) = SharingNegotiation::new(
Box::new(|_, _| {
futures::future::ready(Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
}))
.boxed()
}),
CancellationToken::new(),
);
let sharing = negotiation.finish(&protocol_version);
assert_eq!(
matches!(sharing, ConnectionSharing::Negotiated),
expected_sharing
);
let response = callback(
rmcp::model::RequestId::Number(0),
Elicitation::OpenAiForm {
meta: None,
message: "unexpected".to_string(),
requested_schema: json!({}),
},
)
.await
.unwrap();
assert_eq!(response.action, expected_action);
}
}

View File

@@ -0,0 +1,713 @@
//! MCP elicitation request tracking and policy handling.
//!
//! RMCP clients call into this module when a server asks Codex to elicit data
//! from the user. It decides whether the request can be automatically accepted,
//! must be declined by policy, or should be surfaced as a Codex protocol event
//! and later resolved through the stored responder.
//! Explicit MCP elicitation requests can be surfaced by root and non-root agents.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use crate::McpConfig;
use crate::mcp::McpPermissionPromptAutoApproveContext;
use crate::mcp::mcp_permission_prompt_is_auto_approved;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use async_channel::Sender;
use akode_protocol::approvals::ElicitationAbandonedEvent;
use akode_protocol::approvals::ElicitationRequest;
use akode_protocol::approvals::ElicitationRequestEvent;
use akode_protocol::mcp::RequestId as ProtocolRequestId;
use akode_protocol::mcp_approval_meta::APPROVAL_KIND_KEY;
use akode_protocol::mcp_approval_meta::APPROVAL_KIND_TOOL_SUGGESTION;
use akode_protocol::mcp_approval_meta::APPROVALS_REVIEWER_KEY;
use akode_protocol::mcp_approval_meta::STRICT_AUTO_REVIEW_KEY;
use akode_protocol::protocol::AskForApproval;
use akode_protocol::protocol::Event;
use akode_protocol::protocol::EventMsg;
use akode_rmcp_client::Elicitation;
use akode_rmcp_client::ElicitationResponse;
use akode_rmcp_client::SendElicitation;
use futures::future::BoxFuture;
use futures::future::FutureExt;
use rmcp::model::ElicitationAction;
use rmcp::model::RequestId;
use serde_json::Value;
use tokio::sync::oneshot;
static NEXT_ELICITATION_REQUEST_ID: AtomicU64 = AtomicU64::new(0);
const STRICT_AUTO_REVIEW_DECLINE_MESSAGE: &str = "Automated review of this operation failed. Do not proceed without asking the user for explicit approval.";
#[derive(Debug, Clone)]
pub struct ElicitationReviewRequest {
pub server_name: String,
pub request_id: RequestId,
pub elicitation: Elicitation,
}
pub trait ElicitationReviewer: Send + Sync {
fn review(
&self,
request: ElicitationReviewRequest,
) -> BoxFuture<'static, Result<Option<ElicitationResponse>>>;
}
pub type ElicitationReviewerHandle = Arc<dyn ElicitationReviewer>;
/// Holds an owner-provided registration while an MCP elicitation is waiting for a response.
#[derive(Clone)]
pub struct ElicitationLifecycle {
register: Arc<dyn Fn() -> Box<dyn Send + Sync> + Send + Sync>,
}
impl ElicitationLifecycle {
pub fn new<T>(register: impl Fn() -> T + Send + Sync + 'static) -> Self
where
T: Send + Sync + 'static,
{
Self {
register: Arc::new(move || Box::new(register())),
}
}
fn start(&self) -> ActiveElicitation {
ActiveElicitation {
_registration: (self.register)(),
}
}
}
struct ActiveElicitation {
_registration: Box<dyn Send + Sync>,
}
/// Routes model-visible elicitation response tokens to their exact pending responders.
///
/// One router is shared by every MCP runtime created for a thread. The public response token is
/// generated by Codex rather than copied from the MCP connection, so separate runtimes may reuse
/// the same server request ID without colliding.
#[derive(Clone, Default)]
pub(crate) struct ElicitationRequestRouter {
requests: Arc<StdMutex<PendingResponders>>,
terminal_actions_finished: Arc<tokio::sync::Notify>,
auto_deny: Arc<AtomicBool>,
full_access_form_input_enabled: Arc<AtomicBool>,
}
// Removes and abandons a published request when its native waiter is dropped.
struct ElicitationRequestGuard {
router: ElicitationRequestRouter,
key: (String, RequestId),
}
#[derive(Default, PartialEq)]
enum RouterPhase {
#[default]
Open,
Closing,
Closed,
}
#[derive(Default)]
struct PendingResponders {
pending: ResponderMap,
phase: RouterPhase,
terminal_actions: usize,
}
// Owns response delivery and the original source for abandonment notifications.
struct ElicitationResponder {
response: oneshot::Sender<ElicitationResponse>,
abandonment_events: Option<Sender<Event>>,
}
// Removal elects a winner, but shutdown must also wait for its outside-lock delivery.
struct ElicitationDeliveryGuard(ElicitationRequestRouter);
impl Drop for ElicitationDeliveryGuard {
fn drop(&mut self) {
let mut state = self
.0
.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.terminal_actions -= 1;
if state.phase == RouterPhase::Closing && state.terminal_actions == 0 {
state.phase = RouterPhase::Closed;
}
drop(state);
self.0.terminal_actions_finished.notify_waiters();
}
}
impl Drop for ElicitationRequestGuard {
fn drop(&mut self) {
if let Ok(Some((responder, _terminal_action))) = self.router.take_responder(&self.key) {
emit_abandonment(&self.key, responder.abandonment_events.as_ref());
drop(responder);
}
}
}
fn emit_abandonment(key: &(String, RequestId), events: Option<&Sender<Event>>) {
if let Some(events) = events {
let event = Event {
id: "mcp_elicitation_abandoned".to_string(),
msg: EventMsg::ElicitationAbandoned(ElicitationAbandonedEvent {
server_name: key.0.clone(),
id: match &key.1 {
RequestId::String(id) => ProtocolRequestId::String(id.to_string()),
RequestId::Number(id) => ProtocolRequestId::Integer(*id),
},
}),
};
match events.try_send(event) {
Ok(()) | Err(async_channel::TrySendError::Closed(_)) => {}
Err(async_channel::TrySendError::Full(_)) => {
unreachable!("validated unbounded elicitation event channel became full")
}
}
}
}
impl ElicitationRequestRouter {
fn take_responder(
&self,
key: &(String, RequestId),
) -> Result<Option<(ElicitationResponder, ElicitationDeliveryGuard)>> {
let mut state = self
.requests
.lock()
.map_err(|_| anyhow!("elicitation request router unavailable"))?;
Ok(state.pending.remove(key).map(|responder| {
state.terminal_actions += 1;
(responder, ElicitationDeliveryGuard(self.clone()))
}))
}
/// Fence unbounded source publication and terminal deliveries before reporting shutdown.
/// Bounded sources retain their existing request-only behavior and backpressure.
pub(crate) async fn close(&self) {
{
let (pending, _terminal_action) = {
let mut state = self
.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state.phase == RouterPhase::Closed {
return;
}
if state.phase == RouterPhase::Open {
state.phase = RouterPhase::Closing;
}
let pending = state
.pending
.extract_if(|_, responder| responder.abandonment_events.is_some())
.collect::<ResponderMap>();
state.terminal_actions += 1;
(pending, ElicitationDeliveryGuard(self.clone()))
};
// This synchronous batch completes before the first cancellation point.
for (key, responder) in pending {
emit_abandonment(&key, responder.abandonment_events.as_ref());
drop(responder);
}
}
loop {
let notified = self.terminal_actions_finished.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self
.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.phase
== RouterPhase::Closed
{
return;
}
notified.await;
}
}
pub(crate) fn auto_deny(&self) -> bool {
self.auto_deny.load(Ordering::Relaxed)
}
pub(crate) fn set_auto_deny(&self, auto_deny: bool) {
self.auto_deny.store(auto_deny, Ordering::Relaxed);
}
pub(crate) fn full_access_form_input_enabled(&self) -> bool {
self.full_access_form_input_enabled.load(Ordering::Acquire)
}
pub(crate) fn enable_full_access_form_input(&self) {
self.full_access_form_input_enabled
.store(true, Ordering::Release);
}
pub(crate) async fn resolve(
&self,
server_name: String,
id: RequestId,
response: ElicitationResponse,
) -> Result<()> {
let key = (server_name, id);
let (responder, _terminal_action) = self
.take_responder(&key)?
.ok_or_else(|| anyhow!("elicitation request not found"))?;
if responder.response.send(response).is_err() {
emit_abandonment(&key, responder.abandonment_events.as_ref());
return Err(anyhow!("elicitation response receiver closed"));
}
Ok(())
}
async fn request_user_interaction(
&self,
events: Option<Sender<Event>>,
authority: &ElicitationAuthority,
server_name: String,
request: ElicitationRequest,
) -> Result<ElicitationResponse> {
let Some(events) = events else {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
};
// Core uses an unbounded source channel, which can atomically publish a request
// and synchronously enqueue abandonment from Drop. Preserve bounded callers'
// existing request-only behavior because they require asynchronous backpressure.
let abandonment_events = events.capacity().is_none().then(|| events.clone());
let (delivery_context, response_context) =
if matches!(&request, ElicitationRequest::UserVerification { .. }) {
(
"failed to deliver user-verification request",
"user-verification response channel closed",
)
} else {
(
"failed to deliver MCP elicitation request",
"elicitation request channel closed unexpectedly",
)
};
let public_request_id = format!(
"codex-mcp-elicitation-{}",
NEXT_ELICITATION_REQUEST_ID.fetch_add(1, Ordering::Relaxed)
);
let request_key = (
server_name.clone(),
RequestId::String(public_request_id.clone().into()),
);
let (tx, rx) = oneshot::channel();
let _active_elicitation = authority
.lifecycle
.as_ref()
.map(ElicitationLifecycle::start);
let event = Event {
id: "mcp_elicitation_request".to_string(),
msg: EventMsg::ElicitationRequest(ElicitationRequestEvent {
turn_id: None,
server_name,
id: ProtocolRequestId::String(public_request_id),
request,
}),
};
let legacy_event = if abandonment_events.is_some() {
let mut state = self
.requests
.lock()
.map_err(|_| anyhow!("elicitation request router unavailable"))?;
anyhow::ensure!(
state.phase == RouterPhase::Open,
"elicitation request router closed"
);
let mut responder =
state
.pending
.entry(request_key.clone())
.insert_entry(ElicitationResponder {
response: tx,
abandonment_events: None,
});
// Resolve and close cannot observe a published request without its responder.
// The validated unbounded send cannot wait or yield while admission is locked.
if let Err(error) = events.try_send(event) {
responder.remove();
return Err(error).context(delivery_context);
}
responder.get_mut().abandonment_events = abandonment_events;
None
} else {
self.requests
.lock()
.map_err(|_| anyhow!("elicitation request router unavailable"))?
.pending
.insert(
request_key.clone(),
ElicitationResponder {
response: tx,
abandonment_events: None,
},
);
Some(event)
};
let _pending_request = ElicitationRequestGuard {
router: self.clone(),
key: request_key,
};
if let Some(event) = legacy_event {
events.send(event).await.context(delivery_context)?;
}
rx.await.context(response_context)
}
}
#[derive(Clone)]
pub(crate) struct ElicitationAuthority {
pub(crate) config: Arc<McpConfig>,
reviewer: Option<ElicitationReviewerHandle>,
lifecycle: Option<ElicitationLifecycle>,
}
#[derive(Clone, Default)]
pub(crate) struct ElicitationRequestManager {
router: ElicitationRequestRouter,
pub(crate) authority: Arc<StdMutex<Option<ElicitationAuthority>>>,
}
impl ElicitationRequestManager {
pub(crate) fn new(
config: Arc<McpConfig>,
reviewer: Option<ElicitationReviewerHandle>,
lifecycle: Option<ElicitationLifecycle>,
router: ElicitationRequestRouter,
) -> Self {
Self {
router,
authority: Arc::new(StdMutex::new(Some(ElicitationAuthority {
config,
reviewer,
lifecycle,
}))),
}
}
pub(crate) fn update(
&self,
config: Arc<McpConfig>,
reviewer: Option<ElicitationReviewerHandle>,
lifecycle: Option<ElicitationLifecycle>,
) -> bool {
let Ok(mut authority) = self.authority.lock() else {
return false;
};
*authority = Some(ElicitationAuthority {
config,
reviewer,
lifecycle,
});
true
}
pub(crate) fn make_sender(
&self,
server_name: String,
tx_event: Option<Sender<Event>>,
) -> SendElicitation {
let router = self.router.clone();
let authority = self.authority.clone();
Box::new(move |id, elicitation| {
let router = router.clone();
let tx_event = tx_event.clone();
let server_name = server_name.clone();
let authority = authority.clone();
async move {
let authority = authority
.lock()
.ok()
.and_then(|authority| authority.clone());
// User verification was only honored for the hosted plugin service, which aKode
// never connects to. Cancel it for every server, outside approval policy.
if matches!(elicitation, Elicitation::UserVerification { .. }) {
return Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: Some(
akode_rmcp_client::UserVerificationReason::ApprovalUnavailable
.into_meta(),
),
});
}
if router.auto_deny() {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
}
if elicitation
.meta()
.and_then(|meta| meta.get(APPROVAL_KIND_KEY))
.and_then(serde_json::Value::as_str)
== Some(APPROVAL_KIND_TOOL_SUGGESTION)
{
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
}
let Some(authority) = authority else {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
};
let ElicitationAuthority {
config,
reviewer,
lifecycle,
..
} = &authority;
let approval_policy = config.approval_policy.value();
let Some(permission_profile) = config.permission_profile_for_server(&server_name)
else {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
};
match elicitation
.meta()
.and_then(|meta| meta.get(STRICT_AUTO_REVIEW_KEY))
{
Some(Value::Bool(true)) => {
if matches!(
approval_policy,
AskForApproval::Granular(config) if !config.allows_mcp_elicitations()
) {
return Ok(strict_auto_review_decline());
}
let Some(reviewer) = reviewer.as_ref() else {
return Ok(strict_auto_review_decline());
};
let _active_elicitation =
lifecycle.as_ref().map(ElicitationLifecycle::start);
return Ok(
match reviewer
.review(ElicitationReviewRequest {
server_name,
request_id: id,
elicitation,
})
.await
{
Ok(Some(response))
if (response.action == ElicitationAction::Accept
&& response.content == Some(serde_json::json!({}))
|| matches!(
response.action,
ElicitationAction::Decline | ElicitationAction::Cancel
) && response.content.is_none())
&& response
.meta
.as_ref()
.and_then(Value::as_object)
.and_then(|meta| meta.get(APPROVALS_REVIEWER_KEY))
.and_then(Value::as_str)
== Some("auto_review") =>
{
response
}
Ok(Some(_)) | Ok(None) | Err(_) => strict_auto_review_decline(),
},
);
}
None | Some(Value::Bool(false)) => {}
Some(_) => return Ok(strict_auto_review_decline()),
}
let permission_prompt_is_auto_approved = mcp_permission_prompt_is_auto_approved(
approval_policy,
permission_profile,
McpPermissionPromptAutoApproveContext::default(),
);
if permission_prompt_is_auto_approved && can_auto_accept_elicitation(&elicitation) {
return Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(serde_json::json!({})),
meta: None,
});
}
let should_surface_form_in_full_access = router.full_access_form_input_enabled()
&& permission_prompt_is_auto_approved
&& !elicitation
.meta()
.is_some_and(|meta| meta.contains_key(APPROVAL_KIND_KEY))
&& match &elicitation {
Elicitation::Mcp(
rmcp::model::ElicitRequestParams::FormElicitationParams {
requested_schema,
..
},
) => !requested_schema.properties.is_empty(),
Elicitation::OpenAiElicitationForm {
requested_schema, ..
} => requested_schema
.get("properties")
.and_then(Value::as_object)
.is_some_and(|properties| !properties.is_empty()),
Elicitation::Mcp(_)
| Elicitation::OpenAiForm { .. }
| Elicitation::UserVerification { .. } => false,
};
if !should_surface_form_in_full_access {
if elicitation_is_rejected_by_policy(approval_policy) {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
}
if let Some(reviewer) = reviewer {
let request = ElicitationReviewRequest {
server_name: server_name.clone(),
request_id: id.clone(),
elicitation: elicitation.clone(),
};
if let Some(response) = reviewer.review(request).await? {
return Ok(response);
}
}
}
let request = match elicitation {
Elicitation::UserVerification { .. } => {
return Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: None,
});
}
Elicitation::Mcp(rmcp::model::ElicitRequestParams::FormElicitationParams {
meta,
message,
requested_schema,
}) => ElicitationRequest::Form {
meta: meta
.map(serde_json::to_value)
.transpose()
.context("failed to serialize MCP elicitation metadata")?,
message,
requested_schema: serde_json::to_value(requested_schema)
.context("failed to serialize MCP elicitation schema")?,
},
Elicitation::Mcp(rmcp::model::ElicitRequestParams::UrlElicitationParams {
meta,
message,
url,
elicitation_id,
}) => ElicitationRequest::Url {
meta: meta
.map(serde_json::to_value)
.transpose()
.context("failed to serialize MCP elicitation metadata")?,
message,
url,
elicitation_id,
},
Elicitation::Mcp(_) => {
return Ok(ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
});
}
Elicitation::OpenAiForm {
meta,
message,
requested_schema,
} => ElicitationRequest::OpenAiForm {
meta,
message,
requested_schema,
},
Elicitation::OpenAiElicitationForm {
meta,
message,
requested_schema,
} => ElicitationRequest::OpenAiElicitationForm {
meta,
message,
requested_schema,
},
};
router
.request_user_interaction(tx_event, &authority, server_name, request)
.await
}
.boxed()
})
}
}
fn strict_auto_review_decline() -> ElicitationResponse {
ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: Some(serde_json::json!({
"message": STRICT_AUTO_REVIEW_DECLINE_MESSAGE,
})),
}
}
pub(crate) fn elicitation_is_rejected_by_policy(approval_policy: AskForApproval) -> bool {
match approval_policy {
AskForApproval::Never => true,
AskForApproval::OnRequest => false,
AskForApproval::UnlessTrusted => false,
AskForApproval::Granular(granular_config) => !granular_config.allows_mcp_elicitations(),
}
}
type ResponderMap = HashMap<(String, RequestId), ElicitationResponder>;
fn can_auto_accept_elicitation(elicitation: &Elicitation) -> bool {
match elicitation {
Elicitation::Mcp(rmcp::model::ElicitRequestParams::FormElicitationParams {
requested_schema,
..
}) => {
// Auto-accept confirm/approval elicitations without schema requirements.
requested_schema.properties.is_empty()
}
Elicitation::Mcp(_)
| Elicitation::OpenAiForm { .. }
| Elicitation::OpenAiElicitationForm { .. }
| Elicitation::UserVerification { .. } => false,
}
}
#[cfg(test)]
#[path = "elicitation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,995 @@
use super::*;
use crate::McpServerPermissions;
use crate::mcp::tests::test_elicitation_config;
use async_channel::Receiver;
use akode_protocol::models::PermissionProfile;
use akode_protocol::protocol::GranularApprovalConfig;
use pretty_assertions::assert_eq;
use rmcp::model::ElicitRequestParams;
use rmcp::model::ElicitationSchema;
use rmcp::model::RequestMetaObject;
use serde_json::Map;
use serde_json::json;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::Relaxed;
type ReviewerResponse = std::result::Result<Option<ElicitationResponse>, &'static str>;
#[tokio::test]
async fn abandonment_is_ordered_and_exactly_once_when_the_native_waiter_is_dropped() {
let (manager, _, _) = verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let router = manager.router.clone();
let authority = manager.authority.lock().unwrap().clone().unwrap();
let (tx, events) = async_channel::unbounded();
let (replacement_tx, replacement_events) = async_channel::unbounded();
let request = ElicitationRequest::Form {
meta: None,
message: "Continue".into(),
requested_schema: json!({"type": "object"}),
};
let mut first = Box::pin(router.request_user_interaction(
Some(tx),
&authority,
"server".into(),
request.clone(),
));
let mut sibling = Box::pin(router.request_user_interaction(
Some(replacement_tx),
&authority,
"server".into(),
request,
));
assert!(futures::poll!(&mut first).is_pending());
let EventMsg::ElicitationRequest(first_request) = events.recv().await.unwrap().msg else {
panic!("request must precede abandonment");
};
assert!(futures::poll!(&mut sibling).is_pending());
let EventMsg::ElicitationRequest(sibling_request) =
replacement_events.recv().await.unwrap().msg
else {
panic!("expected sibling request");
};
drop(first);
let EventMsg::ElicitationAbandoned(abandoned) = events.recv().await.unwrap().msg else {
panic!("expected abandonment");
};
assert_eq!(
abandoned,
ElicitationAbandonedEvent {
server_name: first_request.server_name,
id: first_request.id.clone()
}
);
assert_eq!(router.requests.lock().unwrap().pending.len(), 1);
let ProtocolRequestId::String(id) = first_request.id else {
panic!("generated token")
};
assert!(
router
.resolve(
"server".into(),
RequestId::String(id.into()),
approved_response()
)
.await
.is_err()
);
let ProtocolRequestId::String(id) = sibling_request.id else {
panic!("generated token")
};
router
.resolve(
"server".into(),
RequestId::String(id.into()),
approved_response(),
)
.await
.unwrap();
assert_eq!(sibling.await.unwrap(), approved_response());
assert!(events.try_recv().is_err());
assert!(replacement_events.try_recv().is_err());
assert!(router.requests.lock().unwrap().pending.is_empty());
}
#[tokio::test]
async fn bounded_sources_preserve_backpressure_across_close() {
let (manager, _, _) = verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let authority = manager.authority.lock().unwrap().clone().unwrap();
let router = manager.router.clone();
let (tx, events) = async_channel::bounded(1);
tx.send(Event {
id: "queued".into(),
msg: EventMsg::ShutdownComplete,
})
.await
.unwrap();
let mut pending = Box::pin(router.request_user_interaction(
Some(tx),
&authority,
"server".into(),
ElicitationRequest::Form {
meta: None,
message: "Continue".into(),
requested_schema: json!({"type": "object"}),
},
));
assert!(futures::poll!(&mut pending).is_pending());
router.close().await;
assert_eq!(router.requests.lock().unwrap().pending.len(), 1);
assert_eq!(events.recv().await.unwrap().id, "queued");
assert!(futures::poll!(&mut pending).is_pending());
let EventMsg::ElicitationRequest(request) = events.recv().await.unwrap().msg else {
panic!("bounded request must publish after capacity becomes available");
};
let ProtocolRequestId::String(id) = request.id else {
panic!("expected generated token");
};
router
.resolve(
"server".into(),
RequestId::String(id.into()),
approved_response(),
)
.await
.unwrap();
assert_eq!(pending.await.unwrap(), approved_response());
assert!(events.try_recv().is_err());
}
#[tokio::test]
async fn abandonment_closed_receiver_cleans_up_without_delivery_or_replay() {
let (manager, _, _) = verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let authority = manager.authority.lock().unwrap().clone().unwrap();
let router = manager.router.clone();
for close_before_publication in [true, false] {
let (tx, events) = async_channel::unbounded();
if close_before_publication {
events.close();
}
let mut pending = Box::pin(router.request_user_interaction(
Some(tx),
&authority,
"server".into(),
ElicitationRequest::Form {
meta: None,
message: "Continue".into(),
requested_schema: json!({"type": "object"}),
},
));
if close_before_publication {
assert!(pending.await.is_err());
} else {
assert!(futures::poll!(&mut pending).is_pending());
assert!(matches!(
events.recv().await.unwrap().msg,
EventMsg::ElicitationRequest(_)
));
events.close();
drop(pending);
}
assert!(router.requests.lock().unwrap().pending.is_empty());
assert!(events.try_recv().is_err());
}
}
#[tokio::test]
async fn abandonment_close_joins_elected_actions_and_rejects_retained_router_admission() {
let (manager, _, _) = verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let authority = manager.authority.lock().unwrap().clone().unwrap();
let router = manager.router.clone();
let retained_router = router.clone();
let (tx, events) = async_channel::unbounded();
let request = ElicitationRequest::Form {
meta: None,
message: "Continue".into(),
requested_schema: json!({"type": "object"}),
};
let mut pending = Box::pin(router.request_user_interaction(
Some(tx.clone()),
&authority,
"server".into(),
request.clone(),
));
assert!(futures::poll!(&mut pending).is_pending());
let EventMsg::ElicitationRequest(published) = events.recv().await.unwrap().msg else {
panic!("expected published request");
};
let ProtocolRequestId::String(id) = &published.id else {
panic!("expected generated token");
};
let key = (
published.server_name.clone(),
RequestId::String(id.clone().into()),
);
let (responder, terminal_action) = router.take_responder(&key).unwrap().unwrap();
let mut close = Box::pin(router.close());
assert!(futures::poll!(&mut close).is_pending());
drop(close);
let mut repeated_close = Box::pin(retained_router.close());
assert!(futures::poll!(&mut repeated_close).is_pending());
assert!(
retained_router
.request_user_interaction(
Some(tx.clone()),
&authority,
"server".into(),
request.clone(),
)
.await
.unwrap_err()
.to_string()
.contains("router closed")
);
assert!(events.try_recv().is_err());
emit_abandonment(&key, responder.abandonment_events.as_ref());
drop(responder);
drop(terminal_action);
repeated_close.await;
assert!(pending.await.is_err());
let EventMsg::ElicitationAbandoned(abandoned) = events.recv().await.unwrap().msg else {
panic!("close must wait for the winning remover to enqueue abandonment");
};
assert_eq!(
abandoned,
ElicitationAbandonedEvent {
server_name: published.server_name,
id: published.id,
}
);
router.close().await;
assert!(
retained_router
.request_user_interaction(Some(tx), &authority, "server".into(), request,)
.await
.is_err()
);
assert!(events.try_recv().is_err());
}
#[tokio::test]
async fn abandonment_close_invalidates_a_published_responder_before_returning() {
let (manager, _, _) = verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let authority = manager.authority.lock().unwrap().clone().unwrap();
let router = manager.router.clone();
let (tx, events) = async_channel::unbounded();
let mut pending = Box::pin(router.request_user_interaction(
Some(tx),
&authority,
"server".into(),
ElicitationRequest::Form {
meta: None,
message: "Continue".into(),
requested_schema: json!({"type": "object"}),
},
));
assert!(futures::poll!(&mut pending).is_pending());
let EventMsg::ElicitationRequest(published) = events.recv().await.unwrap().msg else {
panic!("expected request");
};
router.close().await;
assert!(pending.await.is_err());
let EventMsg::ElicitationAbandoned(abandoned) = events.try_recv().unwrap().msg else {
panic!("close must enqueue abandonment before returning");
};
assert_eq!(
abandoned,
ElicitationAbandonedEvent {
server_name: published.server_name,
id: published.id,
}
);
assert!(events.try_recv().is_err());
}
#[tokio::test]
async fn abandonment_resolve_reports_failed_response_delivery_once() {
let router = ElicitationRequestRouter::default();
let (tx, events) = async_channel::unbounded();
let (response, receiver) = tokio::sync::oneshot::channel();
let key = (
"server".to_string(),
RequestId::String("published-token".into()),
);
router.requests.lock().unwrap().pending.insert(
key.clone(),
ElicitationResponder {
response,
abandonment_events: Some(tx),
},
);
drop(receiver);
assert!(
router
.resolve(key.0, key.1, approved_response())
.await
.is_err()
);
router.close().await;
let EventMsg::ElicitationAbandoned(abandoned) = events.try_recv().unwrap().msg else {
panic!("failed oneshot delivery must abandon the published request");
};
assert_eq!(
abandoned,
ElicitationAbandonedEvent {
server_name: "server".into(),
id: ProtocolRequestId::String("published-token".into()),
}
);
assert!(events.try_recv().is_err());
}
struct RecordingReviewer {
calls: AtomicUsize,
active_elicitations: Arc<AtomicUsize>,
response: ReviewerResponse,
}
impl RecordingReviewer {
fn new(response: ReviewerResponse) -> Arc<Self> {
Arc::new(Self {
calls: AtomicUsize::default(),
active_elicitations: Arc::default(),
response,
})
}
}
impl ElicitationReviewer for RecordingReviewer {
fn review(
&self,
request: ElicitationReviewRequest,
) -> BoxFuture<'static, Result<Option<ElicitationResponse>>> {
assert_eq!(request.server_name, "independent-mcp");
self.calls.fetch_add(/*val*/ 1, Relaxed);
let active_elicitations = self.active_elicitations.clone();
let active_during_review = usize::from(
request
.elicitation
.meta()
.is_some_and(|meta| meta.get(STRICT_AUTO_REVIEW_KEY) == Some(&Value::Bool(true))),
);
let response = self.response.clone();
async move {
assert_eq!(active_elicitations.load(Relaxed), active_during_review);
tokio::task::yield_now().await;
assert_eq!(active_elicitations.load(Relaxed), active_during_review);
response.map_err(anyhow::Error::msg)
}
.boxed()
}
}
struct LifecycleRegistration(Arc<AtomicUsize>);
impl Drop for LifecycleRegistration {
fn drop(&mut self) {
self.0.fetch_sub(/*val*/ 1, Relaxed);
}
}
fn approved_response() -> ElicitationResponse {
ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({})),
meta: Some(json!({ "approvals_reviewer": "auto_review" })),
}
}
fn elicitation_fixture(
approval_policy: AskForApproval,
permission_profile: PermissionProfile,
reviewer: Option<Arc<RecordingReviewer>>,
) -> (ElicitationRequestManager, Receiver<Event>, SendElicitation) {
let lifecycle = reviewer.as_ref().map(|reviewer| {
let active_elicitations = reviewer.active_elicitations.clone();
ElicitationLifecycle::new(move || {
active_elicitations.fetch_add(/*val*/ 1, Relaxed);
LifecycleRegistration(active_elicitations.clone())
})
});
let mut config =
test_elicitation_config("independent-mcp", approval_policy, permission_profile);
Arc::make_mut(&mut config).server_permissions.insert(
"another-independent-mcp".to_string(),
McpServerPermissions::Thread,
);
let manager = ElicitationRequestManager::new(
config,
reviewer.map(|reviewer| reviewer as Arc<dyn ElicitationReviewer>),
lifecycle,
ElicitationRequestRouter::default(),
);
let (tx_event, events) = async_channel::bounded(1);
let sender = manager.make_sender(
"independent-mcp".to_string(),
Some(tx_event),
);
(manager, events, sender)
}
async fn send_elicitation(sender: &SendElicitation, marker: Option<Value>) -> ElicitationResponse {
let elicitation = Elicitation::Mcp(ElicitRequestParams::FormElicitationParams {
meta: marker.map(|value| {
RequestMetaObject::from(Map::from_iter([(STRICT_AUTO_REVIEW_KEY.into(), value)]))
}),
message: "Review this request".to_string(),
requested_schema: ElicitationSchema::builder().build().unwrap(),
});
sender(RequestId::Number(7), elicitation)
.await
.expect("elicitation must receive a terminal response")
}
fn form_elicitations(meta: Option<Value>, properties: Value) -> [Elicitation; 3] {
let schema = json!({"type": "object", "properties": properties});
[
Elicitation::Mcp(ElicitRequestParams::FormElicitationParams {
meta: meta
.as_ref()
.map(|meta| RequestMetaObject::from(meta.as_object().unwrap().clone())),
message: "Review this request".into(),
requested_schema: serde_json::from_value(schema.clone()).unwrap(),
}),
Elicitation::OpenAiForm {
meta: meta.clone(),
message: "Review this request".into(),
requested_schema: schema.clone(),
},
Elicitation::OpenAiElicitationForm {
meta,
message: "Review this request".into(),
requested_schema: schema,
},
]
}
#[tokio::test]
async fn permission_elicitation_preserves_automatic_review_decisions() {
for (strict_auto_review, approval_policy, expected_reviews) in [
(false, AskForApproval::OnRequest, 1),
(true, AskForApproval::OnRequest, 1),
(true, AskForApproval::Never, 1),
(false, AskForApproval::Never, 0),
] {
for response in [
approved_response(),
ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: Some(json!({"approvals_reviewer": "auto_review", "message": "Denied"})),
},
] {
let reviewer = RecordingReviewer::new(Ok(Some(response.clone())));
let (manager, events, sender) = elicitation_fixture(
approval_policy,
PermissionProfile::Disabled,
Some(reviewer.clone()),
);
let [request, _, _] = form_elicitations(
Some(json!({
"codex_request_type": "approval_request",
"codex_approval_kind": "mcp_tool_call",
"codex_strict_auto_review": strict_auto_review,
"tool_name": "access_browser_origin",
"tool_params": {"origin": "https://example.com"},
})),
json!({}),
);
let expected = if expected_reviews == 0 {
ElicitationResponse {
meta: None,
..approved_response()
}
} else {
response
};
assert_eq!(
sender(RequestId::Number(7), request).await.unwrap(),
expected
);
assert_eq!(reviewer.calls.load(Relaxed), expected_reviews);
assert_eq!(reviewer.active_elicitations.load(Relaxed), 0);
assert!(events.is_empty());
assert!(manager.router.requests.lock().unwrap().pending.is_empty());
}
}
}
#[tokio::test]
async fn elicitation_without_an_automatic_decision_prompts() {
for reviewer in [None, Some(RecordingReviewer::new(Ok(None)))] {
let (manager, events, sender) = elicitation_fixture(
AskForApproval::OnRequest,
PermissionProfile::read_only(),
reviewer.clone(),
);
let mut requests = Vec::from(form_elicitations(/*meta*/ None, json!({})));
requests.extend(form_elicitations(
Some(json!({"codex_requires_user_input": true})),
json!({"answer": {"type": "string"}}),
));
requests.push(Elicitation::Mcp(
ElicitRequestParams::UrlElicitationParams {
meta: None,
message: "Sign in to continue".into(),
url: "https://example.com/auth".into(),
elicitation_id: "test-auth".into(),
},
));
let expected_reviews = requests.len() + 1;
for elicitation in requests {
let pending = tokio::spawn(sender(RequestId::Number(7), elicitation));
let event = tokio::time::timeout(std::time::Duration::from_secs(1), events.recv())
.await
.expect("elicitation should prompt")
.expect("event channel should remain open");
let EventMsg::ElicitationRequest(request) = event.msg else {
panic!("expected MCP elicitation");
};
assert!(!pending.is_finished());
let ProtocolRequestId::String(request_id) = request.id else {
panic!("expected Codex-owned string request ID");
};
let response = ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({"answer": "continue"})),
meta: None,
};
manager
.router
.resolve(
request.server_name,
RequestId::String(request_id.into()),
response.clone(),
)
.await
.unwrap();
assert_eq!(pending.await.unwrap().unwrap(), response);
}
assert_eq!(
send_elicitation(&sender, Some(json!(true))).await,
strict_auto_review_decline()
);
if let Some(reviewer) = reviewer {
assert_eq!(reviewer.calls.load(Relaxed), expected_reviews);
assert_eq!(reviewer.active_elicitations.load(Relaxed), 0);
}
assert!(events.is_empty());
assert!(manager.router.requests.lock().unwrap().pending.is_empty());
}
}
async fn assert_declined(marker: Value, response: Option<ReviewerResponse>) {
let expected_calls = usize::from(marker == Value::Bool(true));
let reviewer = response.map(RecordingReviewer::new);
let (_, events, sender) = elicitation_fixture(
AskForApproval::Never,
PermissionProfile::Disabled,
reviewer.clone(),
);
assert_eq!(
send_elicitation(&sender, Some(marker)).await,
strict_auto_review_decline()
);
if let Some(reviewer) = reviewer {
assert_eq!(reviewer.calls.load(Relaxed), expected_calls);
}
assert!(events.is_empty());
}
#[test]
fn closed_event_channel_immediately_cleans_up_pending_elicitation() {
let active_elicitations = Arc::new(AtomicUsize::new(0));
let registrations = active_elicitations.clone();
let lifecycle = ElicitationLifecycle::new(move || {
registrations.fetch_add(/*val*/ 1, Relaxed);
LifecycleRegistration(registrations.clone())
});
let (manager, events, sender) = elicitation_fixture(
AskForApproval::OnRequest,
PermissionProfile::Disabled,
/*reviewer*/ None,
);
assert!(manager.update(
test_elicitation_config(
"independent-mcp",
AskForApproval::OnRequest,
PermissionProfile::Disabled
),
/*reviewer*/ None,
Some(lifecycle),
));
drop(events);
let elicitation = Elicitation::Mcp(ElicitRequestParams::FormElicitationParams {
meta: None,
message: "Review this request".to_string(),
requested_schema: ElicitationSchema::builder().build().unwrap(),
});
let error = sender(RequestId::Number(7), elicitation)
.now_or_never()
.expect("closed event channel must not leave an elicitation pending")
.expect_err("closed event channel must fail the elicitation");
assert_eq!(
error.to_string(),
"failed to deliver MCP elicitation request"
);
assert!(
manager
.router
.requests
.lock()
.expect("pending request router should be available")
.pending
.is_empty()
);
assert_eq!(active_elicitations.load(Relaxed), 0);
}
#[tokio::test]
async fn strict_auto_review_respects_explicit_elicitation_denials() {
for policy in [
AskForApproval::OnRequest,
AskForApproval::UnlessTrusted,
AskForApproval::Never,
AskForApproval::Granular(GranularApprovalConfig {
sandbox_approval: true,
rules: true,
skill_approval: true,
request_permissions: true,
mcp_elicitations: false,
}),
] {
let explicitly_denied = matches!(
policy,
AskForApproval::Granular(config) if !config.allows_mcp_elicitations()
);
let reviewer = RecordingReviewer::new(Ok(Some(approved_response())));
let (manager, events, sender) =
elicitation_fixture(policy, PermissionProfile::Disabled, Some(reviewer.clone()));
assert_eq!(
send_elicitation(&sender, Some(json!(true))).await,
if explicitly_denied {
strict_auto_review_decline()
} else {
approved_response()
}
);
if policy == AskForApproval::Never {
for (server_name, marker) in [
("independent-mcp", Some(json!(false))),
("another-independent-mcp", None),
] {
let sender = manager.make_sender(
server_name.into(),
/*tx_event*/ None,
);
assert_eq!(
send_elicitation(&sender, marker).await,
ElicitationResponse {
meta: None,
..approved_response()
},
);
}
}
manager.router.set_auto_deny(/*auto_deny*/ true);
assert_eq!(
send_elicitation(&sender, Some(json!(true))).await,
ElicitationResponse {
meta: None,
..strict_auto_review_decline()
},
);
assert_eq!(
(
reviewer.calls.load(Relaxed),
reviewer.active_elicitations.load(Relaxed)
),
(usize::from(!explicitly_denied), 0),
);
assert!(events.is_empty(), "strict review must not emit an event");
}
}
#[tokio::test]
async fn strict_auto_review_preserves_guardian_denials_and_cancellations() {
for response in [
ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: Some(json!({
"approvals_reviewer": "auto_review",
"message": "The user has not authorized sending this data. Ask the user for approval.",
})),
},
ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: Some(json!({ "approvals_reviewer": "auto_review" })),
},
] {
let reviewer = RecordingReviewer::new(Ok(Some(response.clone())));
let (_, events, sender) = elicitation_fixture(
AskForApproval::Never,
PermissionProfile::Disabled,
Some(reviewer.clone()),
);
assert_eq!(send_elicitation(&sender, Some(json!(true))).await, response);
assert_eq!(reviewer.calls.load(Relaxed), 1);
assert!(events.is_empty(), "strict review must not emit an event");
}
}
#[tokio::test]
async fn strict_auto_review_fails_closed_without_a_canonical_decision() {
for marker in ["null", "\"true\"", "1", "{}", "[true]"] {
let marker = serde_json::from_str(marker).expect("valid malformed marker");
assert_declined(marker, Some(Ok(Some(approved_response())))).await;
}
for response in [Ok(None), Err("reviewer failed")] {
assert_declined(json!(true), Some(response)).await;
}
let invalid_decisions: [fn(&mut ElicitationResponse); 6] = [
|response| {
response.action = ElicitationAction::Decline;
response.meta = Some(json!({ "message": "Ask the user to approve this request." }));
},
|response| response.action = ElicitationAction::Cancel,
|response| response.meta = None,
|response| response.meta = Some(json!({ "approvals_reviewer": "user" })),
|response| response.meta = Some(json!({ "approvals_reviewer": "guardian_subagent" })),
|response| response.content = Some(json!({ "approved_for_session": true })),
];
for make_invalid in invalid_decisions {
let mut response = approved_response();
make_invalid(&mut response);
assert_declined(json!(true), Some(Ok(Some(response)))).await;
}
assert_declined(json!(true), /*response*/ None).await;
}
#[tokio::test]
async fn reused_elicitation_senders_follow_each_servers_latest_permission_authority() {
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
config.approval_policy = akode_config::Constrained::allow_any(AskForApproval::Never);
config.permission_profile = PermissionProfile::Disabled;
let auth = akode_login::CodexAuth::from_api_key("test-api-key");
let hosted_server = crate::mcp::test_http_mcp_server_config("https://example.com");
let mut attached_server = hosted_server.clone();
attached_server.environment_id = "attached".to_string();
let mut catalog = crate::ResolvedMcpCatalog::builder();
catalog.register(crate::McpServerRegistration::from_config(
"attached".to_string(),
attached_server,
));
// A user-configured server on the local environment, which is not attached below.
catalog.register(crate::McpServerRegistration::from_config(
"local".to_string(),
hosted_server,
));
config.mcp_server_catalog = catalog.build();
let servers = crate::effective_mcp_servers(&config, Some(&auth));
let attachment = |permissions| {
let sandbox = akode_exec_server::FileSystemSandboxContext::from_permission_profile(
permissions,
akode_utils_path_uri::PathUri::from_host_native_path(std::env::temp_dir()).unwrap(),
);
let sandbox = Arc::new(sandbox);
// Unattached local servers keep using thread permissions.
[("attached".to_string(), sandbox)]
};
config.set_server_permissions(&servers, attachment(PermissionProfile::read_only()));
let manager = ElicitationRequestManager::new(
Arc::new(config.clone()),
/*reviewer*/ None,
/*lifecycle*/ None,
ElicitationRequestRouter::default(),
);
let attached = manager.make_sender(
"attached".to_string(),
/*tx_event*/ None,
);
let hosted = manager.make_sender(
"local".to_string(),
/*tx_event*/ None,
);
assert_eq!(
send_elicitation(&attached, /*marker*/ None).await.action,
ElicitationAction::Decline
);
assert_eq!(
send_elicitation(&hosted, /*marker*/ None).await.action,
ElicitationAction::Accept
);
config.set_server_permissions(&servers, attachment(PermissionProfile::Disabled));
assert!(manager.update(
Arc::new(config.clone()),
/*reviewer*/ None,
/*lifecycle*/ None,
));
assert_eq!(
send_elicitation(&attached, /*marker*/ None).await.action,
ElicitationAction::Accept
);
let mut configured_servers = config.mcp_server_catalog.configured_servers();
configured_servers
.get_mut("attached")
.expect("attached server should be registered")
.enabled = false;
config.mcp_server_catalog = config
.mcp_server_catalog
.with_materialized_servers(configured_servers);
let servers = crate::effective_mcp_servers(&config, Some(&auth));
config.set_server_permissions(&servers, attachment(PermissionProfile::Disabled));
assert!(manager.update(
Arc::new(config.clone()),
/*reviewer*/ None,
/*lifecycle*/ None,
));
assert_eq!(
send_elicitation(&attached, /*marker*/ None).await.action,
ElicitationAction::Decline
);
let mut configured_servers = config.mcp_server_catalog.configured_servers();
configured_servers
.get_mut("local")
.expect("local server should be registered")
.enabled = false;
config.mcp_server_catalog = config
.mcp_server_catalog
.with_materialized_servers(configured_servers);
let servers = crate::effective_mcp_servers(&config, /*auth*/ None);
config.set_server_permissions(&servers, std::iter::empty());
assert!(manager.update(
Arc::new(config.clone()),
/*reviewer*/ None,
/*lifecycle*/ None,
));
assert_eq!(
send_elicitation(&hosted, /*marker*/ None).await.action,
ElicitationAction::Decline
);
}
fn verification_fixture(
approval_policy: AskForApproval,
reviewer: Option<Arc<RecordingReviewer>>,
) -> (ElicitationRequestManager, Receiver<Event>, SendElicitation) {
let mut config = test_elicitation_config(
"codex_apps",
approval_policy,
PermissionProfile::Disabled,
);
let mut catalog = crate::catalog::ResolvedMcpCatalog::builder();
catalog.register(crate::catalog::McpServerRegistration::from_extension(
"codex_apps".to_string(),
"verification-test",
/*contribution_order*/ 0,
crate::mcp::test_http_mcp_server_config("https://example.com"),
));
Arc::make_mut(&mut config).mcp_server_catalog = catalog.build();
let manager = ElicitationRequestManager::new(
config,
reviewer.map(|reviewer| reviewer as Arc<dyn ElicitationReviewer>),
/*lifecycle*/ None,
ElicitationRequestRouter::default(),
);
let (tx, events) = async_channel::bounded(1);
let sender = manager.make_sender(
"codex_apps".into(),
Some(tx),
);
(manager, events, sender)
}
#[tokio::test]
async fn user_verification_cancels_when_no_app_can_receive_the_request() {
let (manager, _, _) = verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let sender = manager.make_sender(
"codex_apps".into(),
/*tx_event*/ None,
);
assert_eq!(
sender(
RequestId::Number(7),
Elicitation::UserVerification {
meta: None,
title: "Approve".into(),
description: String::new(),
challenge: "AQID".into(),
}
)
.await
.unwrap(),
ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: Some(json!({"openai/userVerificationReason": "approvalUnavailable"}))
},
);
}
#[tokio::test]
async fn user_verification_cancels_for_an_event_receiver_without_host_activation() {
let (manager, _, _) = verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
let (tx, events) = async_channel::bounded(1);
let sender = manager.make_sender(
"codex_apps".into(),
Some(tx),
);
let response = tokio::time::timeout(
std::time::Duration::from_secs(1),
sender(
RequestId::Number(7),
Elicitation::UserVerification {
meta: None,
title: "Approve".into(),
description: String::new(),
challenge: "AQID".into(),
},
),
)
.await
.expect("an inactive host must not wait for a response")
.unwrap();
assert_eq!(
response,
ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: Some(json!({"openai/userVerificationReason": "approvalUnavailable"})),
},
);
assert!(events.try_recv().is_err());
assert!(manager.router.requests.lock().unwrap().pending.is_empty());
}
#[tokio::test]
async fn user_verification_rejects_attached_servers_even_if_they_use_the_plugin_service_name() {
for name in ["attached", "codex_apps"] {
let (manager, _, _) =
verification_fixture(AskForApproval::OnRequest, /*reviewer*/ None);
{
let mut authority = manager.authority.lock().unwrap();
let config = Arc::make_mut(&mut authority.as_mut().unwrap().config);
let mut catalog = crate::catalog::ResolvedMcpCatalog::builder();
catalog.register(crate::catalog::McpServerRegistration::from_config(
name.into(),
crate::mcp::test_http_mcp_server_config("https://example.com"),
));
config.mcp_server_catalog = catalog.build();
}
let (tx, events) = async_channel::bounded(1);
let sender = manager.make_sender(
name.into(),
Some(tx),
);
assert_eq!(
sender(
RequestId::Number(7),
Elicitation::UserVerification {
meta: None,
title: "Approve".into(),
description: String::new(),
challenge: "AQID".into()
}
)
.await
.unwrap(),
ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: Some(json!({"openai/userVerificationReason": "approvalUnavailable"}))
},
);
assert!(events.try_recv().is_err());
}
}

View File

@@ -0,0 +1,45 @@
use std::sync::Arc;
use akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpHeader;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
use futures::future::BoxFuture;
pub(crate) struct ExecutorEnvironmentHttpClient {
pub(crate) bearer_token_env_var: String,
pub(crate) http_client: Arc<dyn HttpClient>,
}
impl ExecutorEnvironmentHttpClient {
fn attach_authorization(&self, params: &mut HttpRequestParams) {
params
.headers
.retain(|header| !header.name.eq_ignore_ascii_case("authorization"));
params.headers.push(HttpHeader {
name: "authorization".to_string(),
value: "Bearer ".to_string(),
value_env_var: Some(self.bearer_token_env_var.clone()),
});
}
}
impl HttpClient for ExecutorEnvironmentHttpClient {
fn http_request(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.attach_authorization(&mut params);
self.http_client.http_request(params)
}
fn http_request_stream(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.attach_authorization(&mut params);
self.http_client.http_request_stream(params)
}
}

View File

@@ -0,0 +1,109 @@
pub use binding::McpBinding;
pub use binding::McpPermissionSource;
pub use binding::PreparedMcpCall;
pub use client_capabilities::client_mcp_extensions;
pub use akode_rmcp_client::McpProtocolMode;
pub use connection_manager::NetworkPolicyMetadata;
pub use connection_manager::NetworkPolicyMetadataProvider;
pub use connection_manager::tool_is_model_visible;
pub use connection_pool::LEASE_META_KEY as MCP_CONNECTION_LEASE_META_KEY;
pub use connection_pool::McpConnectionPool;
pub use elicitation::ElicitationLifecycle;
pub use elicitation::ElicitationReviewRequest;
pub use elicitation::ElicitationReviewer;
pub use elicitation::ElicitationReviewerHandle;
pub use resource_client::McpResourceClient;
pub use resource_client::McpResourceClientAuthKey;
pub use resource_client::McpResourceClientCacheKey;
pub use resource_client::McpResourcePage;
pub use resource_client::McpResourceReadResult;
pub use resource_client::McpResourceServerCacheKey;
pub use rmcp::model::ReadResourceRequestParams;
pub use rmcp_client::MCP_NETWORK_POLICY_META_CAPABILITY;
pub use runtime::McpRuntime;
pub use runtime::McpRuntimeContext;
pub use runtime::McpRuntimeInput;
pub use runtime::McpStartupPolicy;
pub use runtime::McpToolCallResult;
pub use runtime::apply_http_headers_helper;
pub use sandbox_metadata::MCP_SANDBOX_LAUNCHER_META_KEY;
pub use sandbox_metadata::MCP_SANDBOX_STATE_CAPABILITY;
pub use sandbox_metadata::MCP_SANDBOX_STATE_META_CAPABILITY;
pub use sandbox_metadata::SandboxState;
pub use tool_catalog_cache::McpToolCatalogCache;
pub use tool_request_meta::McpToolRequestMetaHook;
pub use tool_request_meta::McpToolRequestMetaProvider;
pub use tools::ToolInfo;
pub use catalog::McpCatalogBuilder;
pub use catalog::McpEnvironmentAuthority;
pub use catalog::McpPluginAttribution;
pub use catalog::McpServerConflict;
pub use catalog::McpServerConflictAction;
pub use catalog::McpServerRegistration;
pub use catalog::McpServerSource;
pub use catalog::ResolvedMcpCatalog;
pub use catalog::ResolvedMcpServer;
pub use mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE;
pub use mcp::McpConfig;
pub use mcp::McpServerPermissions;
pub use mcp::ToolPluginContext;
pub use server::EffectiveMcpServer;
pub use mcp::configured_mcp_servers;
pub use mcp::effective_mcp_servers;
pub use mcp::effective_mcp_servers_from_configured;
pub use mcp::tool_plugin_context;
pub use plugin_config::PluginMcpConfigParseOutcome;
pub use plugin_config::PluginMcpServerParseError;
pub use plugin_config::normalize_executor_plugin_mcp_declarations;
pub use plugin_config::parse_agent_plugin_mcp_config;
pub use plugin_config::parse_executor_plugin_mcp_config;
pub use plugin_config::parse_plugin_mcp_config;
pub use plugin_config::parse_plugin_mcp_declarations;
pub use mcp::McpServerStatusSnapshot;
pub use mcp::McpSnapshotDetail;
pub use mcp::collect_mcp_server_status_snapshot_with_detail;
pub use mcp::read_mcp_resource;
pub use mcp::McpAuthStatusEntry;
pub use mcp::McpOAuthLoginConfig;
pub use mcp::McpOAuthLoginSupport;
pub use mcp::McpOAuthScopesSource;
pub use mcp::ResolvedMcpOAuthScopes;
pub use mcp::compute_auth_statuses;
pub use mcp::discover_supported_scopes;
pub use mcp::oauth_login_support;
pub use mcp::resolve_oauth_callback;
pub use mcp::resolve_oauth_scopes;
pub use mcp::should_retry_without_scopes;
pub use mcp::McpPermissionPromptAutoApproveContext;
pub use mcp::mcp_permission_prompt_is_auto_approved;
pub use mcp::qualified_mcp_tool_name_prefix;
mod auth_changes;
mod binding;
pub(crate) mod binding_clients;
mod catalog;
mod client_capabilities;
mod client_tool_catalog;
pub(crate) mod connection_manager;
mod connection_pool;
pub(crate) mod elicitation;
mod executor_environment_http_client;
pub(crate) mod mcp;
mod openai_docs_source_attribution;
mod pagination;
mod plugin_config;
mod resource_client;
pub(crate) mod rmcp_client;
pub(crate) mod runtime;
mod sandbox_executable;
mod sandbox_metadata;
pub(crate) mod server;
mod tool_catalog_cache;
mod tool_request_meta;
pub(crate) mod tools;

View File

@@ -0,0 +1,485 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Result;
use akode_config::McpServerAuth;
use akode_config::McpServerConfig;
use akode_config::McpServerTransportConfig;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::HttpClient;
use akode_login::CodexAuth;
use akode_rmcp_client::McpAuthState;
use akode_rmcp_client::McpOAuthCallbackMode;
use akode_rmcp_client::OAuthDiscoveryTimeout;
use akode_rmcp_client::OAuthProviderError;
use akode_rmcp_client::StreamableHttpRedirectMode;
use akode_rmcp_client::determine_streamable_http_auth_status;
use akode_rmcp_client::determine_streamable_http_auth_status_from_credentials;
use akode_rmcp_client::discover_streamable_http_oauth;
use akode_rmcp_client::resolve_mcp_oauth_callback_url;
use futures::FutureExt;
use futures::future::join_all;
use tracing::warn;
use crate::runtime::McpRuntimeContext;
use crate::server::EffectiveMcpServer;
use crate::server::has_explicit_http_authorization;
#[derive(Debug, Clone)]
pub struct McpOAuthLoginConfig {
pub url: String,
pub http_headers: Option<HashMap<String, String>>,
pub env_http_headers: Option<HashMap<String, String>>,
pub discovered_scopes: Option<Vec<String>>,
pub callback_mode: McpOAuthCallbackMode,
}
#[derive(Debug)]
pub enum McpOAuthLoginSupport {
Supported(McpOAuthLoginConfig),
Unsupported,
Unknown(anyhow::Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpOAuthScopesSource {
Explicit,
Configured,
Discovered,
Empty,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedMcpOAuthScopes {
pub scopes: Vec<String>,
pub source: McpOAuthScopesSource,
}
/// Keeps registered callbacks tied to their client while preserving legacy redirects.
pub fn resolve_oauth_callback(
server: &McpServerConfig,
server_url: &str,
global_callback_url: Option<&str>,
) -> Result<Option<String>> {
if let Some(callback_url) = server
.oauth
.as_ref()
.and_then(|oauth| oauth.callback_url.as_deref())
{
return Ok(Some(callback_url.to_string()));
}
if server
.oauth_client_id()
.is_none_or(|client_id| client_id.trim().is_empty())
{
return Ok(global_callback_url.map(ToOwned::to_owned));
}
resolve_mcp_oauth_callback_url(
server_url,
global_callback_url,
McpOAuthCallbackMode::CallbackSpecific,
)
.map(Some)
}
#[derive(Debug, Clone)]
pub struct McpAuthStatusEntry {
pub config: Option<McpServerConfig>,
pub auth_state: McpAuthState,
}
pub async fn oauth_login_support(
transport: &McpServerTransportConfig,
http_client: Arc<dyn HttpClient>,
discovery_timeout: OAuthDiscoveryTimeout,
redirect_mode: StreamableHttpRedirectMode,
) -> McpOAuthLoginSupport {
let Some(mut config) = oauth_login_candidate(transport) else {
return McpOAuthLoginSupport::Unsupported;
};
match discover_streamable_http_oauth(
&config.url,
config.http_headers.clone(),
config.env_http_headers.clone(),
http_client,
discovery_timeout,
redirect_mode,
)
.await
{
Ok(Some(discovery)) => {
config.discovered_scopes = discovery.scopes_supported;
config.callback_mode = discovery.callback_mode;
McpOAuthLoginSupport::Supported(config)
}
Ok(None) => McpOAuthLoginSupport::Unsupported,
Err(err) => McpOAuthLoginSupport::Unknown(err),
}
}
fn oauth_login_candidate(transport: &McpServerTransportConfig) -> Option<McpOAuthLoginConfig> {
let McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
..
} = transport
else {
return None;
};
if bearer_token_env_var.is_some() {
return None;
}
Some(McpOAuthLoginConfig {
url: url.clone(),
http_headers: http_headers.clone(),
env_http_headers: env_http_headers.clone(),
discovered_scopes: None,
callback_mode: McpOAuthCallbackMode::CallbackSpecific,
})
}
pub async fn discover_supported_scopes(
transport: &McpServerTransportConfig,
http_client: Arc<dyn HttpClient>,
discovery_timeout: OAuthDiscoveryTimeout,
redirect_mode: StreamableHttpRedirectMode,
) -> Option<Vec<String>> {
match oauth_login_support(transport, http_client, discovery_timeout, redirect_mode).await {
McpOAuthLoginSupport::Supported(config) => config.discovered_scopes,
McpOAuthLoginSupport::Unsupported | McpOAuthLoginSupport::Unknown(_) => None,
}
}
pub fn resolve_oauth_scopes(
explicit_scopes: Option<Vec<String>>,
configured_scopes: Option<Vec<String>>,
discovered_scopes: Option<Vec<String>>,
) -> ResolvedMcpOAuthScopes {
if let Some(scopes) = explicit_scopes {
return ResolvedMcpOAuthScopes {
scopes,
source: McpOAuthScopesSource::Explicit,
};
}
if let Some(scopes) = configured_scopes {
return ResolvedMcpOAuthScopes {
scopes,
source: McpOAuthScopesSource::Configured,
};
}
if let Some(scopes) = discovered_scopes
&& !scopes.is_empty()
{
return ResolvedMcpOAuthScopes {
scopes,
source: McpOAuthScopesSource::Discovered,
};
}
ResolvedMcpOAuthScopes {
scopes: Vec::new(),
source: McpOAuthScopesSource::Empty,
}
}
pub fn should_retry_without_scopes(scopes: &ResolvedMcpOAuthScopes, error: &anyhow::Error) -> bool {
scopes.source == McpOAuthScopesSource::Discovered
&& error.downcast_ref::<OAuthProviderError>().is_some()
}
pub async fn compute_auth_statuses<'a, I>(
servers: I,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
auth: Option<&CodexAuth>,
runtime_context: &McpRuntimeContext,
) -> HashMap<String, McpAuthStatusEntry>
where
I: IntoIterator<Item = (&'a String, &'a EffectiveMcpServer)>,
{
let futures = servers.into_iter().map(|(name, server)| {
let name = name.clone();
let redirect_mode = if server.is_agent_plugin() {
StreamableHttpRedirectMode::AgentPluginV1
} else {
StreamableHttpRedirectMode::Legacy
};
let config = server.config().clone();
let runtime_context = runtime_context.clone();
async move {
let auth_state = match compute_auth_status(
&name,
&config,
store_mode,
keyring_backend_kind,
auth,
&runtime_context,
redirect_mode,
)
.await
{
Ok(status) => status,
Err(error) => {
warn!("failed to determine auth status for MCP server `{name}`: {error:?}");
McpAuthState::Unknown
}
};
let entry = McpAuthStatusEntry {
config: Some(config),
auth_state,
};
(name, entry)
}
});
join_all(futures).await.into_iter().collect()
}
#[allow(clippy::too_many_arguments)]
async fn compute_auth_status(
server_name: &str,
config: &McpServerConfig,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
_auth: Option<&CodexAuth>,
runtime_context: &McpRuntimeContext,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<McpAuthState> {
if !config.enabled {
return Ok(McpAuthState::Unsupported);
}
if matches!(config.auth, McpServerAuth::EmaAuth) {
// Enterprise-managed authorization was removed; these servers never start.
return Ok(McpAuthState::Unsupported);
}
if matches!(config.auth, McpServerAuth::ChatGpt) && !config.is_local_environment() {
return Ok(if has_explicit_http_authorization(config) {
McpAuthState::BearerToken
} else {
McpAuthState::Unsupported
});
}
match &config.transport {
McpServerTransportConfig::Stdio { .. } => Ok(McpAuthState::Unsupported),
McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
http_headers_helper,
} => {
if http_headers_helper.is_some() {
// Status inspection must not execute an arbitrary local helper. Existing
// credentials remain reportable; otherwise discovery waits for startup/login.
return Ok(determine_streamable_http_auth_status_from_credentials(
config.oauth_credential_name(server_name).as_ref(),
url,
bearer_token_env_var.as_deref(),
http_headers.clone(),
env_http_headers.clone(),
store_mode,
keyring_backend_kind,
)?
.unwrap_or(McpAuthState::Unknown));
}
let http_client = runtime_context
.resolve_http_client(server_name, config)
.map_err(anyhow::Error::msg)?;
let discovery_timeout = if config.is_local_environment() {
OAuthDiscoveryTimeout::LOCAL
} else {
OAuthDiscoveryTimeout::Requested
};
let oauth_credential_name = config.oauth_credential_name(server_name);
determine_streamable_http_auth_status(
oauth_credential_name.as_ref(),
url,
bearer_token_env_var.as_deref(),
http_headers.clone(),
env_http_headers.clone(),
store_mode,
keyring_backend_kind,
http_client,
discovery_timeout,
redirect_mode,
)
.boxed()
.await
}
}
}
#[cfg(test)]
mod tests {
use anyhow::anyhow;
use pretty_assertions::assert_eq;
use super::McpOAuthScopesSource;
use super::OAuthProviderError;
use super::ResolvedMcpOAuthScopes;
use super::resolve_oauth_callback;
use super::resolve_oauth_scopes;
use super::should_retry_without_scopes;
#[test]
fn callback_resolution_preserves_registered_and_legacy_clients() -> anyhow::Result<()> {
for (client_id, saved_callback, global_callback, expected_callback) in [
(
Some("registered-client"),
Some("http://127.0.0.1/callback"),
Some("https://override.example/callback"),
Some("http://127.0.0.1/callback"),
),
(
Some("legacy-client"),
None,
None,
Some("http://127.0.0.1/callback/epMNJ6P1xGQ9"),
),
(
None,
Some("https://plugin.example/callback"),
Some("https://override.example/callback"),
Some("https://plugin.example/callback"),
),
(
None,
None,
Some("https://override.example/callback"),
Some("https://override.example/callback"),
),
] {
let server = serde_json::from_value(serde_json::json!({
"url": "https://mcp.example.com/mcp",
"oauth": {
"client_id": client_id,
"callback_url": saved_callback,
},
}))?;
assert_eq!(
resolve_oauth_callback(&server, "https://mcp.example.com/mcp", global_callback)?
.as_deref(),
expected_callback
);
}
Ok(())
}
#[test]
fn resolve_oauth_scopes_prefers_explicit() {
let resolved = resolve_oauth_scopes(
Some(vec!["explicit".to_string()]),
Some(vec!["configured".to_string()]),
Some(vec!["discovered".to_string()]),
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: vec!["explicit".to_string()],
source: McpOAuthScopesSource::Explicit,
}
);
}
#[test]
fn resolve_oauth_scopes_prefers_configured_over_discovered() {
let resolved = resolve_oauth_scopes(
/*explicit_scopes*/ None,
Some(vec!["configured".to_string()]),
Some(vec!["discovered".to_string()]),
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: vec!["configured".to_string()],
source: McpOAuthScopesSource::Configured,
}
);
}
#[test]
fn resolve_oauth_scopes_uses_discovered_when_needed() {
let resolved = resolve_oauth_scopes(
/*explicit_scopes*/ None,
/*configured_scopes*/ None,
Some(vec!["discovered".to_string()]),
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: vec!["discovered".to_string()],
source: McpOAuthScopesSource::Discovered,
}
);
}
#[test]
fn resolve_oauth_scopes_preserves_explicitly_empty_configured_scopes() {
let resolved = resolve_oauth_scopes(
/*explicit_scopes*/ None,
Some(Vec::new()),
Some(vec!["ignored".into()]),
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: Vec::new(),
source: McpOAuthScopesSource::Configured,
}
);
}
#[test]
fn resolve_oauth_scopes_falls_back_to_empty() {
let resolved = resolve_oauth_scopes(
/*explicit_scopes*/ None, /*configured_scopes*/ None,
/*discovered_scopes*/ None,
);
assert_eq!(
resolved,
ResolvedMcpOAuthScopes {
scopes: Vec::new(),
source: McpOAuthScopesSource::Empty,
}
);
}
#[test]
fn should_retry_without_scopes_only_for_discovered_provider_errors() {
let discovered = ResolvedMcpOAuthScopes {
scopes: vec!["scope".to_string()],
source: McpOAuthScopesSource::Discovered,
};
let provider_error = anyhow!(OAuthProviderError::new(
Some("invalid_scope".to_string()),
Some("scope rejected".to_string()),
));
assert!(should_retry_without_scopes(&discovered, &provider_error));
let configured = ResolvedMcpOAuthScopes {
scopes: vec!["scope".to_string()],
source: McpOAuthScopesSource::Configured,
};
assert!(!should_retry_without_scopes(&configured, &provider_error));
assert!(!should_retry_without_scopes(
&discovered,
&anyhow!("timed out waiting for OAuth callback"),
));
}
}

View File

@@ -0,0 +1,727 @@
pub use auth::McpAuthStatusEntry;
pub use auth::McpOAuthLoginConfig;
pub use auth::McpOAuthLoginSupport;
pub use auth::McpOAuthScopesSource;
pub use auth::ResolvedMcpOAuthScopes;
pub use auth::compute_auth_statuses;
pub use auth::discover_supported_scopes;
pub use auth::oauth_login_support;
pub use auth::resolve_oauth_callback;
pub use auth::resolve_oauth_scopes;
pub use auth::should_retry_without_scopes;
pub(crate) mod auth;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use akode_config::ConfigLayerStack;
use akode_config::Constrained;
use akode_config::McpServerAuth;
use akode_config::McpServerConfig;
use akode_config::types::AppToolApproval;
use akode_config::types::ApprovalsReviewer;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::FileSystemSandboxContext;
use akode_login::CodexAuth;
use akode_protocol::mcp::ClientMcpExtensions;
use akode_protocol::mcp::McpServerInfo;
use akode_protocol::mcp::Resource;
use akode_protocol::mcp::ResourceTemplate;
use akode_protocol::mcp::Tool;
use akode_protocol::models::PermissionProfile;
use akode_protocol::protocol::AskForApproval;
use akode_protocol::protocol::McpAuthStatus;
use akode_rmcp_client::McpOAuthRefreshMode;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use rmcp::model::ElicitationCapability;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use crate::McpProtocolMode;
use crate::McpServerSource;
use crate::ResolvedMcpCatalog;
use crate::connection_manager::McpConnectionSet;
use crate::runtime::McpPublicationGate;
use crate::runtime::McpRuntimeContext;
use crate::runtime::McpRuntimeInput;
use crate::runtime::McpStartupPolicy;
use crate::server::EffectiveMcpServer;
/// Product SKU reported in MCP catalog telemetry.
pub(crate) const MCP_CATALOG_PRODUCT_SKU: &str = "codex";
const MCP_TOOL_NAME_PREFIX: &str = "mcp";
const MCP_TOOL_NAME_DELIMITER: &str = "__";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum McpSnapshotDetail {
#[default]
Full,
ToolsAndAuthOnly,
}
impl McpSnapshotDetail {
fn include_resources(self) -> bool {
matches!(self, Self::Full)
}
}
pub fn qualified_mcp_tool_name_prefix(server_name: &str) -> String {
sanitize_responses_api_tool_name(&format!(
"{MCP_TOOL_NAME_PREFIX}{MCP_TOOL_NAME_DELIMITER}{server_name}{MCP_TOOL_NAME_DELIMITER}"
))
}
/// Returns true when MCP permission prompts should resolve as approved instead
/// of being shown to the user.
pub fn mcp_permission_prompt_is_auto_approved(
approval_policy: AskForApproval,
permission_profile: &PermissionProfile,
context: McpPermissionPromptAutoApproveContext,
) -> bool {
if context.tool_approval_mode == Some(AppToolApproval::Approve) {
return true;
}
if approval_policy != AskForApproval::Never {
return false;
}
match permission_profile {
PermissionProfile::Disabled | PermissionProfile::External { .. } => true,
PermissionProfile::Managed { file_system, .. } => {
file_system.to_sandbox_policy().has_full_disk_write_access()
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct McpPermissionPromptAutoApproveContext {
pub tool_approval_mode: Option<AppToolApproval>,
}
/// Which rules a registered MCP server uses.
#[derive(Debug, Clone)]
pub enum McpServerPermissions {
Thread,
Environment(Arc<FileSystemSandboxContext>),
}
/// MCP runtime settings derived from `akode_core::config::Config`.
///
/// Each published runtime and prepared call owns one immutable copy of these
/// settings, so its connection, approval policy, and sandbox authority cannot
/// change independently. Auth remains separate and is supplied explicitly to
/// runtime entry points such as [`effective_mcp_servers`].
#[derive(Debug, Clone)]
pub struct McpConfig {
/// Requests server-side read-only filtering and invocation checks for MCP tools.
pub requires_read_only_mcp_tools: bool,
/// Codex home directory used for MCP OAuth state and app-tool cache files.
pub codex_home: PathBuf,
/// Preferred credential store for MCP OAuth tokens.
pub mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode,
/// OAuth refresh ownership selected for new MCP connections.
pub oauth_refresh_mode: McpOAuthRefreshMode,
/// Backend used when MCP OAuth storage is configured for keyring-backed persistence.
pub auth_keyring_backend_kind: AuthKeyringBackendKind,
/// Optional fixed localhost callback port for MCP OAuth login.
pub mcp_oauth_callback_port: Option<u16>,
/// Optional OAuth redirect URI override for MCP login.
pub mcp_oauth_callback_url: Option<String>,
/// How long a tool catalog capture waits for optional MCP servers to initialize.
///
/// A zero duration disables the shared grace and waits for each server's
/// configured startup timeout instead.
pub optional_mcp_startup_grace: Duration,
/// Whether skill MCP dependency installation prompts are enabled.
pub skill_mcp_dependency_install_enabled: bool,
/// Approval policy used for MCP tool calls and MCP elicitation requests.
pub approval_policy: Constrained<AskForApproval>,
/// Permission profile captured with the connections and approval policy.
pub permission_profile: PermissionProfile,
/// Host working directory used to interpret thread permissions.
pub host_cwd: AbsolutePathBuf,
/// Configuration layers used to evaluate Apps tool policy and reviewer selection.
pub config_layer_stack: ConfigLayerStack,
pub plugins: akode_config::types::PluginsConfigToml,
/// Default reviewer used when an Apps tool has no reviewer override.
pub approvals_reviewer: ApprovalsReviewer,
/// Working directories for the exact environment handles used by this runtime.
pub environment_cwds: HashMap<String, PathUri>,
/// Effective backends captured with the environment handles, including local fallback.
pub environment_use_mxc: HashMap<String, bool>,
/// Permissions for registered servers. Unavailable servers have no entry.
pub server_permissions: HashMap<String, McpServerPermissions>,
/// Host-supplied re-exec binary. Probe its sandbox capability before advertising it.
/// Never infer this from PATH or an MCP server's configuration.
pub codex_self_exe: Option<PathBuf>,
/// Optional path to `akode-linux-sandbox` for sandboxed MCP tool execution.
pub codex_linux_sandbox_exe: Option<PathBuf>,
/// Whether to use legacy Landlock behavior in the MCP sandbox state.
// TODO(anp): Reconcile this runtime-wide copy with TurnEnvironment::sandbox_context
// for the environment that owns each MCP server.
pub use_legacy_landlock: bool,
/// Whether model-visible MCP tool namespaces should keep the legacy
/// `mcp__` prefix.
pub prefix_mcp_tool_names: bool,
/// MCP servers whose model-visible tool namespaces omit the `mcp__` prefix.
pub non_prefixed_mcp_tool_servers: Vec<String>,
/// Protocol mode for MCP servers.
pub protocol_mode: McpProtocolMode,
/// Try protocol discovery before initializing eligible local stdio servers.
pub discover_local_stdio: bool,
/// Refresh ordinary server catalogs after tools/list_changed notifications.
pub mcp_tool_list_changed: bool,
/// Client-side elicitation capabilities advertised during MCP initialization.
pub client_elicitation_capability: ElicitationCapability,
/// Resolved MCP registrations keyed by logical server name.
pub mcp_server_catalog: ResolvedMcpCatalog,
}
/// Default amount of time a tool catalog capture waits for optional MCP servers.
pub const DEFAULT_OPTIONAL_MCP_STARTUP_GRACE: Duration = Duration::from_secs(1);
impl McpConfig {
/// Resolves enabled runtime servers against the exact attachment permissions being published.
pub fn set_server_permissions(
&mut self,
servers: &HashMap<String, EffectiveMcpServer>,
environment_sandboxes: impl IntoIterator<Item = (String, Arc<FileSystemSandboxContext>)>,
) {
let environment_sandboxes = environment_sandboxes.into_iter().collect::<HashMap<_, _>>();
self.server_permissions = servers
.iter()
.filter(|(_, server)| server.enabled())
.filter_map(|(server_name, _)| {
let server = self.mcp_server_catalog.server(server_name)?;
let permissions = if let Some(sandbox) =
environment_sandboxes.get(&server.config().environment_id)
{
McpServerPermissions::Environment(Arc::clone(sandbox))
} else if server.config().is_local_environment()
|| matches!(server.source(), McpServerSource::SelectedPlugin(_))
{
McpServerPermissions::Thread
} else {
return None;
};
Some((server_name.clone(), permissions))
})
.collect();
}
/// Returns this server's published permission authority.
pub fn permission_profile_for_server(&self, server_name: &str) -> Option<&PermissionProfile> {
Some(match self.server_permissions.get(server_name)? {
McpServerPermissions::Thread => &self.permission_profile,
McpServerPermissions::Environment(sandbox) => &sandbox.permissions,
})
}
/// Standalone discovery and resource reads must not inherit thread execution authority.
pub fn for_threadless_operations(&self, servers: &HashMap<String, EffectiveMcpServer>) -> Self {
let mut config = self.clone();
config.permission_profile = PermissionProfile::default();
config.server_permissions = servers
.iter()
.filter(|(_, server)| server.enabled())
.map(|(name, _)| (name.clone(), McpServerPermissions::Thread))
.collect();
config
}
}
/// Plugin attribution and selection data derived from the current MCP configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolPluginContext {
plugin_display_names_by_mcp_server_name: HashMap<String, Vec<String>>,
plugin_ids_by_mcp_server_name: HashMap<String, String>,
selected_plugin_mcp_server_names: HashSet<String>,
}
impl ToolPluginContext {
pub fn plugin_display_names_for_mcp_server_name(&self, server_name: &str) -> &[String] {
self.plugin_display_names_by_mcp_server_name
.get(server_name)
.map(Vec::as_slice)
.unwrap_or(&[])
}
pub fn plugin_id_for_mcp_server_name(&self, server_name: &str) -> Option<&str> {
self.plugin_ids_by_mcp_server_name
.get(server_name)
.map(String::as_str)
}
pub(crate) fn is_selected_plugin_mcp_server(&self, server_name: &str) -> bool {
self.selected_plugin_mcp_server_names.contains(server_name)
}
fn from_config(config: &McpConfig) -> Self {
let mut tool_plugin_context = Self::default();
for (server_name, attribution) in config
.mcp_server_catalog
.plugin_attributions_by_server_name()
{
tool_plugin_context
.plugin_display_names_by_mcp_server_name
.insert(
server_name.clone(),
vec![attribution.display_name().to_string()],
);
tool_plugin_context
.plugin_ids_by_mcp_server_name
.insert(server_name, attribution.plugin_id().to_string());
}
tool_plugin_context.selected_plugin_mcp_server_names.extend(
config
.mcp_server_catalog
.selected_plugin_server_names()
.map(str::to_string),
);
for plugin_names in tool_plugin_context
.plugin_display_names_by_mcp_server_name
.values_mut()
{
plugin_names.sort_unstable();
plugin_names.dedup();
}
tool_plugin_context
}
}
pub fn configured_mcp_servers(config: &McpConfig) -> HashMap<String, McpServerConfig> {
config.mcp_server_catalog.configured_servers()
}
pub fn effective_mcp_servers(
config: &McpConfig,
auth: Option<&CodexAuth>,
) -> HashMap<String, EffectiveMcpServer> {
effective_mcp_servers_from_configured(configured_mcp_servers(config), config, auth)
}
/// Converts a materialized server map to its auth-gated runtime view.
///
/// Compatibility built-ins and extension overlays must already be reflected in
/// `configured_servers`; this function does not synthesize missing servers.
///
/// # Panics
///
/// Panics if a materialized server is missing from the catalog.
pub fn effective_mcp_servers_from_configured(
configured_servers: HashMap<String, McpServerConfig>,
config: &McpConfig,
_auth: Option<&CodexAuth>,
) -> HashMap<String, EffectiveMcpServer> {
configured_servers
.into_iter()
.map(|(name, mut server)| {
#[expect(
clippy::expect_used,
reason = "materialized servers must have catalog registrations"
)]
let registration = config
.mcp_server_catalog
.server(&name)
.expect("materialized MCP server must have a catalog registration");
// ChatGPT credentials are never available, so local servers that ask for them use
// their own OAuth flow. Executor-owned servers keep `ChatGpt` so they never consult
// orchestrator OAuth stores and are rejected unless they carry explicit authorization.
if matches!(server.auth, McpServerAuth::ChatGpt) && server.is_local_environment() {
server.auth = McpServerAuth::OAuth;
}
(
name,
EffectiveMcpServer::from_config_with_policy(
server,
registration.credential_policy(),
)
.with_agent_plugin(registration.source().is_agent_plugin()),
)
})
.collect::<HashMap<_, _>>()
}
pub fn tool_plugin_context(config: &McpConfig) -> ToolPluginContext {
ToolPluginContext::from_config(config)
}
#[allow(clippy::too_many_arguments)]
pub async fn read_mcp_resource(
config: &McpConfig,
auth: Option<&CodexAuth>,
runtime_context: McpRuntimeContext,
tool_catalog_cache: crate::McpToolCatalogCache,
server: &str,
params: ReadResourceRequestParams,
) -> anyhow::Result<ReadResourceResult> {
let mut mcp_servers = effective_mcp_servers(config, auth);
mcp_servers.retain(|name, _| name == server);
let cancel_token = CancellationToken::new();
let runtime_config = config.for_threadless_operations(&mcp_servers);
let manager = McpConnectionSet::new(
/*predecessor*/ None,
/*previous*/ None,
McpPublicationGate::already_published(),
McpRuntimeInput {
network_policy_metadata: None,
startup_policy: McpStartupPolicy::Eager,
config: Arc::new(runtime_config),
plugins_available: false,
ready_selected_capability_roots: Vec::new(),
mcp_servers,
submit_id: String::new(),
tx_event: None,
startup_cancellation_token: cancel_token.clone(),
runtime_context,
tool_catalog_cache,
client_mcp_extensions: ClientMcpExtensions::default(),
auth: auth.cloned(),
auth_manager: None,
elicitation_reviewer: None,
elicitation_lifecycle: None,
},
crate::elicitation::ElicitationRequestRouter::default(),
)
.await;
let result = manager.read_resource(server, params).await;
cancel_token.cancel();
result
}
#[derive(Debug, Clone)]
pub struct McpServerStatusSnapshot {
pub server_infos: HashMap<String, McpServerInfo>,
pub server_capabilities: HashMap<String, serde_json::Value>,
pub tool_list_meta: HashMap<String, Arc<serde_json::Value>>,
pub tools_by_server: HashMap<String, HashMap<String, Tool>>,
pub tools_errors: HashMap<String, String>,
pub resources: HashMap<String, Vec<Resource>>,
pub resource_templates: HashMap<String, Vec<ResourceTemplate>>,
pub auth_statuses: HashMap<String, McpAuthStatus>,
pub server_names: Vec<String>,
}
#[allow(clippy::too_many_arguments)]
pub async fn collect_mcp_server_status_snapshot_with_detail(
config: &McpConfig,
auth: Option<&CodexAuth>,
runtime_context: McpRuntimeContext,
tool_catalog_cache: crate::McpToolCatalogCache,
detail: McpSnapshotDetail,
server_name: Option<&str>,
) -> McpServerStatusSnapshot {
let mut mcp_servers = effective_mcp_servers(config, auth);
mcp_servers.retain(|name, _| server_name.is_none_or(|selected| name == selected));
if mcp_servers.is_empty() {
return McpServerStatusSnapshot {
server_infos: HashMap::new(),
server_capabilities: HashMap::new(),
tool_list_meta: HashMap::new(),
tools_by_server: HashMap::new(),
tools_errors: HashMap::new(),
resources: HashMap::new(),
resource_templates: HashMap::new(),
auth_statuses: HashMap::new(),
server_names: Vec::new(),
};
}
let auth_status_entries = compute_auth_statuses(
mcp_servers.iter(),
config.mcp_oauth_credentials_store_mode,
config.auth_keyring_backend_kind,
auth,
&runtime_context,
)
.await;
let server_names = mcp_servers.keys().cloned().collect();
let cancel_token = CancellationToken::new();
let runtime_config = config.for_threadless_operations(&mcp_servers);
let mcp_connection_manager = McpConnectionSet::new(
/*predecessor*/ None,
/*previous*/ None,
McpPublicationGate::already_published(),
McpRuntimeInput {
network_policy_metadata: None,
startup_policy: McpStartupPolicy::Eager,
config: Arc::new(runtime_config),
plugins_available: false,
ready_selected_capability_roots: Vec::new(),
mcp_servers,
submit_id: String::new(),
tx_event: None,
startup_cancellation_token: cancel_token.clone(),
runtime_context,
tool_catalog_cache,
client_mcp_extensions: ClientMcpExtensions::default(),
auth: auth.cloned(),
auth_manager: None,
elicitation_reviewer: None,
elicitation_lifecycle: None,
},
crate::elicitation::ElicitationRequestRouter::default(),
)
.await;
let snapshot = collect_mcp_server_status_snapshot_from_manager(
&mcp_connection_manager,
auth_status_entries,
server_names,
detail,
)
.await;
cancel_token.cancel();
snapshot
}
/// The Responses API requires tool names to match `^[a-zA-Z0-9_-]+$`.
/// MCP server/tool names are user-controlled, so sanitize the fully-qualified
/// name we expose to the model by replacing any disallowed character with `_`.
pub(crate) fn sanitize_responses_api_tool_name(name: &str) -> String {
let mut sanitized = String::with_capacity(name.len());
for c in name.chars() {
if c.is_ascii_alphanumeric() || c == '_' {
sanitized.push(c);
} else {
sanitized.push('_');
}
}
if sanitized.is_empty() {
"_".to_string()
} else {
sanitized
}
}
fn protocol_tool_from_rmcp_tool(name: &str, tool: &rmcp::model::Tool) -> Option<Tool> {
match serde_json::to_value(tool) {
Ok(value) => match Tool::from_mcp_value(value) {
Ok(tool) => Some(tool),
Err(err) => {
tracing::warn!("Failed to convert MCP tool '{name}': {err}");
None
}
},
Err(err) => {
tracing::warn!("Failed to serialize MCP tool '{name}': {err}");
None
}
}
}
fn auth_statuses_from_entries(
auth_status_entries: &HashMap<String, crate::mcp::auth::McpAuthStatusEntry>,
) -> HashMap<String, McpAuthStatus> {
auth_status_entries
.iter()
.map(|(name, entry)| (name.clone(), McpAuthStatus::from(entry.auth_state)))
.collect::<HashMap<_, _>>()
}
fn convert_mcp_resources(
resources: HashMap<String, Vec<rmcp::model::Resource>>,
) -> HashMap<String, Vec<Resource>> {
resources
.into_iter()
.map(|(name, resources)| {
let resources = resources
.into_iter()
.filter_map(|resource| match serde_json::to_value(resource) {
Ok(value) => match Resource::from_mcp_value(value.clone()) {
Ok(resource) => Some(resource),
Err(err) => {
let (uri, resource_name) = match value {
Value::Object(obj) => (
obj.get("uri")
.and_then(|v| v.as_str().map(ToString::to_string)),
obj.get("name")
.and_then(|v| v.as_str().map(ToString::to_string)),
),
_ => (None, None),
};
tracing::warn!(
"Failed to convert MCP resource (uri={uri:?}, name={resource_name:?}): {err}"
);
None
}
},
Err(err) => {
tracing::warn!("Failed to serialize MCP resource: {err}");
None
}
})
.collect::<Vec<_>>();
(name, resources)
})
.collect::<HashMap<_, _>>()
}
fn convert_mcp_resource_templates(
resource_templates: HashMap<String, Vec<rmcp::model::ResourceTemplate>>,
) -> HashMap<String, Vec<ResourceTemplate>> {
resource_templates
.into_iter()
.map(|(name, templates)| {
let templates = templates
.into_iter()
.filter_map(|template| match serde_json::to_value(template) {
Ok(value) => match ResourceTemplate::from_mcp_value(value.clone()) {
Ok(template) => Some(template),
Err(err) => {
let (uri_template, template_name) = match value {
Value::Object(obj) => (
obj.get("uriTemplate")
.or_else(|| obj.get("uri_template"))
.and_then(|v| v.as_str().map(ToString::to_string)),
obj.get("name")
.and_then(|v| v.as_str().map(ToString::to_string)),
),
_ => (None, None),
};
tracing::warn!(
"Failed to convert MCP resource template (uri_template={uri_template:?}, name={template_name:?}): {err}"
);
None
}
},
Err(err) => {
tracing::warn!("Failed to serialize MCP resource template: {err}");
None
}
})
.collect::<Vec<_>>();
(name, templates)
})
.collect::<HashMap<_, _>>()
}
pub(crate) async fn collect_mcp_server_status_snapshot_from_manager(
mcp_connection_manager: &McpConnectionSet,
auth_status_entries: HashMap<String, crate::mcp::auth::McpAuthStatusEntry>,
server_names: Vec<String>,
detail: McpSnapshotDetail,
) -> McpServerStatusSnapshot {
let selected_servers: HashSet<&str> = server_names.iter().map(String::as_str).collect();
let include_server = |name: &str| selected_servers.contains(name);
let ((server_infos, (tools, tools_errors, tool_list_meta)), resources, resource_templates) = tokio::join!(
async {
let server_infos = mcp_connection_manager
.list_available_server_infos(include_server)
.await;
let tools = mcp_connection_manager
.list_catalogs_with_errors(include_server)
.await;
(server_infos, tools)
},
async {
if detail.include_resources() {
mcp_connection_manager
.list_all_resources(include_server)
.await
} else {
HashMap::new()
}
},
async {
if detail.include_resources() {
mcp_connection_manager
.list_all_resource_templates(include_server)
.await
} else {
HashMap::new()
}
},
);
let server_capabilities =
mcp_connection_manager.list_available_server_capabilities(include_server);
let mut tools_by_server = HashMap::<String, HashMap<String, Tool>>::new();
for tool_info in tools {
let raw_tool_name = tool_info.tool.name.to_string();
let Some(tool) = protocol_tool_from_rmcp_tool(&raw_tool_name, &tool_info.tool) else {
continue;
};
let tool_name = tool.name.clone();
tools_by_server
.entry(tool_info.server_name)
.or_default()
.insert(tool_name, tool);
}
// Status-only discovery has no event channel. Report OAuth failures from the completed
// connection attempt instead of retaining the credential-presence status read beforehand.
let mut auth_statuses = auth_statuses_from_entries(&auth_status_entries);
for server_name in mcp_connection_manager.authentication_failed_servers().await {
if auth_statuses.get(&server_name) == Some(&McpAuthStatus::OAuth) {
auth_statuses.insert(server_name, McpAuthStatus::NotLoggedIn);
}
}
McpServerStatusSnapshot {
server_capabilities,
tool_list_meta,
server_infos,
tools_by_server,
tools_errors,
resources: convert_mcp_resources(resources),
resource_templates: convert_mcp_resource_templates(resource_templates),
auth_statuses,
server_names,
}
}
#[cfg(test)]
#[path = "mod_tests.rs"]
pub(crate) mod tests;
/// Test fixture: a generic user-configured streamable HTTP MCP server at `url`.
#[cfg(test)]
pub(crate) fn test_http_mcp_server_config(url: &str) -> McpServerConfig {
McpServerConfig {
transport: akode_config::McpServerTransportConfig::StreamableHttp {
url: url.to_string(),
bearer_token_env_var: None,
http_headers: None,
env_http_headers: None,
http_headers_helper: None,
},
auth: McpServerAuth::default(),
environment_id: akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: Some(Duration::from_secs(30)),
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
}
}

View File

@@ -0,0 +1,622 @@
use super::*;
use crate::McpPluginAttribution;
use crate::McpServerPermissions;
use crate::McpServerRegistration;
use crate::connection_manager::tests::create_ready_async_managed_client;
use crate::mcp::auth::McpAuthStatusEntry;
use crate::rmcp_client::StartupOutcomeError;
use crate::server::McpCredentialPolicy;
use anyhow::Context;
use akode_config::Constrained;
use akode_config::types::AppToolApproval;
use akode_config::types::AuthKeyringBackendKind;
use akode_exec_server_test_support::environment_manager_without_environments;
use akode_login::CodexAuth;
use akode_protocol::models::ManagedFileSystemPermissions;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_protocol::protocol::AskForApproval;
use akode_protocol::protocol::GranularApprovalConfig;
use akode_config::McpServerTransportConfig;
use akode_rmcp_client::McpAuthState;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
#[tokio::test]
async fn removed_ema_auth_servers_report_unsupported_auth() -> anyhow::Result<()> {
let home = tempfile::tempdir()?;
let auth = CodexAuth::from_api_key("test-api-key");
let mut servers = HashMap::new();
for name in ["first", "second"] {
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": format!("https://resource.example/{name}"),
"auth": "ema_auth"
}))?;
servers.insert(
name.to_string(),
EffectiveMcpServer::from_host_config(server),
);
}
let runtime_context = McpRuntimeContext::new(
Arc::new(environment_manager_without_environments()),
home.path().to_path_buf(),
);
let statuses = tokio::time::timeout(
Duration::from_secs(5),
compute_auth_statuses(
servers.iter(),
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Some(&auth),
&runtime_context,
),
)
.await
.context("MCP auth status should not block")?;
// Enterprise-managed authorization was removed; never borrow another credential.
assert_eq!(
statuses
.into_iter()
.map(|(name, entry)| (name, entry.auth_state))
.collect::<HashMap<_, _>>(),
HashMap::from([
("first".to_string(), McpAuthState::Unsupported),
("second".to_string(), McpAuthState::Unsupported),
]),
);
Ok(())
}
#[tokio::test]
async fn status_snapshot_only_downgrades_oauth_authentication_failures() {
let auth_failure = StartupOutcomeError::Failed {
error: "OAuth refresh token was rejected".to_string(),
is_authentication_required: true,
shutdown: None,
};
let mut manager = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
let mut auth_status_entries = HashMap::new();
for (name, auth_state, startup_error) in [
(
"oauth-failed",
McpAuthState::OAuth,
Some(auth_failure.clone()),
),
("oauth-ready", McpAuthState::OAuth, None),
(
"oauth-provider-error",
McpAuthState::OAuth,
Some(StartupOutcomeError::Failed {
error: "provider temporarily unavailable".to_string(),
is_authentication_required: false,
shutdown: None,
}),
),
("bearer", McpAuthState::BearerToken, Some(auth_failure)),
] {
let mut client = create_ready_async_managed_client(Vec::new()).await;
if let Some(error) = startup_error {
client.client = futures::future::ready(Err(error)).boxed().shared();
}
manager.insert_test_client(name, client);
auth_status_entries.insert(
name.to_string(),
McpAuthStatusEntry {
config: None,
auth_state,
},
);
}
let server_names = auth_status_entries.keys().cloned().collect();
let snapshot = collect_mcp_server_status_snapshot_from_manager(
&manager,
auth_status_entries,
server_names,
McpSnapshotDetail::ToolsAndAuthOnly,
)
.await;
assert_eq!(
snapshot.auth_statuses,
HashMap::from([
("oauth-failed".to_string(), McpAuthStatus::NotLoggedIn),
("oauth-ready".to_string(), McpAuthStatus::OAuth),
("oauth-provider-error".to_string(), McpAuthStatus::OAuth),
("bearer".to_string(), McpAuthStatus::BearerToken),
]),
);
}
pub(crate) fn test_mcp_config(codex_home: PathBuf) -> McpConfig {
McpConfig {
requires_read_only_mcp_tools: false,
codex_home,
mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode::default(),
oauth_refresh_mode: McpOAuthRefreshMode::Legacy,
auth_keyring_backend_kind: AuthKeyringBackendKind::default(),
mcp_oauth_callback_port: None,
mcp_oauth_callback_url: None,
optional_mcp_startup_grace: DEFAULT_OPTIONAL_MCP_STARTUP_GRACE,
skill_mcp_dependency_install_enabled: true,
approval_policy: Constrained::allow_any(AskForApproval::OnRequest),
permission_profile: PermissionProfile::default(),
host_cwd: AbsolutePathBuf::current_dir().expect("test working directory"),
config_layer_stack: akode_config::ConfigLayerStack::default(),
plugins: Default::default(),
approvals_reviewer: akode_config::types::ApprovalsReviewer::default(),
environment_cwds: HashMap::new(),
environment_use_mxc: HashMap::new(),
server_permissions: HashMap::new(),
codex_self_exe: None,
codex_linux_sandbox_exe: None,
use_legacy_landlock: false,
prefix_mcp_tool_names: true,
non_prefixed_mcp_tool_servers: Vec::new(),
protocol_mode: McpProtocolMode::Legacy,
discover_local_stdio: false,
mcp_tool_list_changed: true,
client_elicitation_capability: ElicitationCapability::default(),
mcp_server_catalog: ResolvedMcpCatalog::default(),
}
}
pub(crate) fn test_elicitation_config(
server_name: &str,
approval_policy: AskForApproval,
permission_profile: PermissionProfile,
) -> Arc<McpConfig> {
let mut config = test_mcp_config(PathBuf::new());
config.approval_policy = Constrained::allow_any(approval_policy);
config.permission_profile = permission_profile;
config
.server_permissions
.insert(server_name.to_string(), McpServerPermissions::Thread);
Arc::new(config)
}
#[test]
fn removed_ema_auth_servers_stay_disabled_for_every_source_and_policy() {
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://resource.example/mcp", "auth": "ema_auth",
"oauth": { "client_id": "resource-client", "authorization_server_issuer": "https://as.example" }
})).unwrap();
let plugin = McpPluginAttribution::agent_plugin("plugin@test".into(), "Plugin".into());
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"configured".into(),
server.clone(),
));
catalog.register(McpServerRegistration::from_plugin(
"installed".into(),
plugin.clone(),
/*plugin_order*/ 0,
server.clone(),
));
catalog.register(McpServerRegistration::from_selected_plugin(
"selected".into(),
plugin,
/*selection_order*/ 0,
akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
server,
));
let mut config = test_mcp_config(PathBuf::new());
let deny_all = akode_protocol::mcp_policy::EnvironmentMcpPolicy {
servers: Some(Default::default()),
plugins: None,
};
for denied in [false, true] {
let catalog = catalog.clone();
config.mcp_server_catalog = catalog.build_with_environment_authority(|_| {
if denied {
crate::McpEnvironmentAuthority::Restricted(&deny_all)
} else {
crate::McpEnvironmentAuthority::Unrestricted
}
});
let servers = effective_mcp_servers(&config, /*auth*/ None);
for name in ["configured", "installed", "selected"] {
assert!(!servers[name].enabled(), "{name}");
assert_eq!(servers[name].config().auth, McpServerAuth::EmaAuth);
}
}
}
#[test]
fn qualified_mcp_tool_name_prefix_sanitizes_server_names_without_lowercasing() {
assert_eq!(
qualified_mcp_tool_name_prefix("Some-Server"),
"mcp__Some_Server__".to_string()
);
}
#[test]
fn mcp_server_permissions_handle_unattached_and_threadless_servers() {
let mut config = test_mcp_config(PathBuf::new());
config.permission_profile = PermissionProfile::Disabled;
let mut missing_server = test_http_mcp_server_config("https://example.com");
missing_server.environment_id = "missing".to_string();
let mut selected_server = missing_server.clone();
selected_server.environment_id = "unattached".to_string();
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"missing".to_string(),
missing_server,
));
catalog.register(McpServerRegistration::from_selected_plugin(
"selected".to_string(),
McpPluginAttribution::new("selected@test".to_string(), "Selected".to_string()),
/*selection_order*/ 0,
akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
selected_server,
));
config.mcp_server_catalog = catalog.build();
let servers = effective_mcp_servers(&config, /*auth*/ None);
assert_eq!(config.permission_profile_for_server("selected"), None);
config.set_server_permissions(&servers, std::iter::empty());
assert_eq!(
config.permission_profile_for_server("selected"),
Some(&PermissionProfile::Disabled)
);
assert_eq!(config.permission_profile_for_server("missing"), None);
let config = config.for_threadless_operations(&servers);
assert_eq!(
config.permission_profile_for_server("selected"),
Some(&PermissionProfile::default())
);
}
#[test]
fn mcp_prompt_auto_approval_honors_unrestricted_managed_profiles() {
assert!(mcp_permission_prompt_is_auto_approved(
AskForApproval::Never,
&PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Unrestricted,
network: NetworkSandboxPolicy::Enabled,
},
McpPermissionPromptAutoApproveContext::default(),
));
assert!(mcp_permission_prompt_is_auto_approved(
AskForApproval::Never,
&PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Unrestricted,
network: NetworkSandboxPolicy::Restricted,
},
McpPermissionPromptAutoApproveContext::default(),
));
assert!(!mcp_permission_prompt_is_auto_approved(
AskForApproval::Never,
&PermissionProfile::read_only(),
McpPermissionPromptAutoApproveContext::default(),
));
assert!(!mcp_permission_prompt_is_auto_approved(
AskForApproval::OnRequest,
&PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Unrestricted,
network: NetworkSandboxPolicy::Enabled,
},
McpPermissionPromptAutoApproveContext::default(),
));
}
#[test]
fn mcp_prompt_auto_approval_honors_approved_tools_in_all_permission_modes() {
for approval_policy in [
AskForApproval::UnlessTrusted,
AskForApproval::OnRequest,
AskForApproval::Granular(GranularApprovalConfig {
sandbox_approval: true,
rules: true,
skill_approval: true,
request_permissions: true,
mcp_elicitations: true,
}),
AskForApproval::Never,
] {
assert!(mcp_permission_prompt_is_auto_approved(
approval_policy,
&PermissionProfile::read_only(),
McpPermissionPromptAutoApproveContext {
tool_approval_mode: Some(AppToolApproval::Approve),
},
));
}
assert!(!mcp_permission_prompt_is_auto_approved(
AskForApproval::OnRequest,
&PermissionProfile::read_only(),
McpPermissionPromptAutoApproveContext {
tool_approval_mode: Some(AppToolApproval::Auto),
},
));
}
#[test]
fn tool_plugin_context_collects_mcp_sources() {
let mut config = test_mcp_config(PathBuf::new());
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_plugin(
"alpha".to_string(),
McpPluginAttribution::new("alpha@test".to_string(), "alpha-plugin".to_string()),
/*plugin_order*/ 0,
test_http_mcp_server_config("https://alpha.example"),
));
config.mcp_server_catalog = catalog.build();
let provenance = tool_plugin_context(&config);
assert_eq!(
provenance,
ToolPluginContext {
plugin_display_names_by_mcp_server_name: HashMap::from([(
"alpha".to_string(),
vec!["alpha-plugin".to_string()],
)]),
plugin_ids_by_mcp_server_name: HashMap::from([(
"alpha".to_string(),
"alpha@test".to_string(),
)]),
selected_plugin_mcp_server_names: HashSet::new(),
}
);
assert_eq!(
provenance.plugin_id_for_mcp_server_name("alpha"),
Some("alpha@test")
);
assert_eq!(provenance.plugin_id_for_mcp_server_name("beta"), None);
}
#[test]
fn selected_mcp_attribution_does_not_join_an_unrelated_local_summary() {
let mut config = test_mcp_config(PathBuf::new());
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_selected_plugin(
"github".to_string(),
McpPluginAttribution::new(
"shared-plugin-id".to_string(),
"Executor GitHub".to_string(),
),
/*selection_order*/ 0,
"executor-1",
test_http_mcp_server_config("https://github.example"),
));
config.mcp_server_catalog = catalog.build();
let provenance = tool_plugin_context(&config);
assert_eq!(
provenance,
ToolPluginContext {
plugin_display_names_by_mcp_server_name: HashMap::from([(
"github".to_string(),
vec!["Executor GitHub".to_string()],
)]),
plugin_ids_by_mcp_server_name: HashMap::from([(
"github".to_string(),
"shared-plugin-id".to_string(),
)]),
selected_plugin_mcp_server_names: HashSet::from(["github".to_string()]),
}
);
assert!(provenance.is_selected_plugin_mcp_server("github"));
}
#[test]
fn effective_mcp_servers_preserve_executor_credential_policy() {
let mut config = test_mcp_config(PathBuf::new());
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://executor.example/mcp",
"environment_id": "remote",
"bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
}))
.expect("valid MCP server config");
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_executor_config(
"executor".to_string(),
server.clone(),
));
catalog.register(McpServerRegistration::from_config(
"host".to_string(),
server,
));
config.mcp_server_catalog = catalog.build();
let effective = effective_mcp_servers(&config, /*auth*/ None);
assert_eq!(
effective["executor"].credential_policy(),
McpCredentialPolicy::ExecutorOnly,
);
assert_eq!(
effective["host"].credential_policy(),
McpCredentialPolicy::HostFallbackAllowed,
);
}
#[test]
#[should_panic(expected = "materialized MCP server must have a catalog registration")]
fn effective_mcp_servers_require_catalog_registration() {
let config = test_mcp_config(PathBuf::new());
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://executor.example/mcp",
"environment_id": "remote",
"bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
}))
.expect("valid MCP server config");
effective_mcp_servers_from_configured(
HashMap::from([("unregistered".to_string(), server)]),
&config,
/*auth*/ None,
);
}
#[test]
fn effective_mcp_servers_never_grant_chatgpt_auth_even_for_chatgpt_origins() {
for (base_url, server_url) in [
("https://chatgpt-staging.com", "https://chatgpt-staging.com"),
(
"https://preview.chatgpt-staging.com",
"https://preview.chatgpt-staging.com",
),
("https://gov.chatgpt.com", "https://chatgpt.com"),
(
"https://chatgpt.com",
"https://gov.chatgpt.com/backend-api/",
),
("https://chatgpt.com", "https://GOV.CHATGPT.COM:443"),
] {
let mut config = test_mcp_config(PathBuf::new());
let mut server = test_http_mcp_server_config(server_url);
server.auth = McpServerAuth::ChatGpt;
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"trusted".to_string(),
server,
));
config.mcp_server_catalog = catalog.build();
let effective = effective_mcp_servers(&config, /*auth*/ None);
assert_eq!(
effective["trusted"].config().auth,
McpServerAuth::OAuth,
"backend {base_url}, server {server_url}",
);
}
}
#[test]
fn effective_mcp_servers_reject_untrusted_origins_for_chatgpt_auth() {
for url in [
"http://gov.chatgpt.com",
"https://gov.chatgpt.com:8443",
"https://gov.chatgpt.com.evil.example",
"https://sub.gov.chatgpt.com",
"https://gov.chatgpt.com.",
"https://gov.chatgpt.com@evil.example",
"https://example.com",
] {
let mut config = test_mcp_config(PathBuf::new());
let mut server = test_http_mcp_server_config(url);
server.auth = McpServerAuth::ChatGpt;
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"untrusted".to_string(),
server,
));
config.mcp_server_catalog = catalog.build();
let effective = effective_mcp_servers(&config, /*auth*/ None);
assert_eq!(
effective["untrusted"].config().auth,
McpServerAuth::OAuth,
"server {url}",
);
}
}
#[tokio::test]
async fn effective_mcp_servers_preserve_runtime_servers() {
let codex_home = tempfile::tempdir().expect("tempdir");
let mut config = test_mcp_config(codex_home.path().to_path_buf());
let auth = CodexAuth::from_api_key("test-api-key");
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
"sample".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://user.example/mcp".to_string(),
bearer_token_env_var: None,
http_headers: None,
env_http_headers: None,
http_headers_helper: None,
},
environment_id: akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
},
));
catalog.register(McpServerRegistration::from_config(
"docs".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://docs.example/mcp".to_string(),
bearer_token_env_var: None,
http_headers: None,
env_http_headers: None,
http_headers_helper: None,
},
environment_id: akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
},
));
catalog.register(McpServerRegistration::from_config(
"codex_apps".to_string(),
test_http_mcp_server_config("https://apps.example/mcp"),
));
config.mcp_server_catalog = catalog.build();
let effective = effective_mcp_servers(&config, Some(&auth));
let sample = effective.get("sample").expect("user server should exist");
let docs = effective
.get("docs")
.expect("configured server should exist");
// The formerly reserved hosted Apps name is now an ordinary configured server.
assert!(effective.contains_key("codex_apps"));
let sample = sample.config();
let docs = docs.config();
match &sample.transport {
McpServerTransportConfig::StreamableHttp { url, .. } => {
assert_eq!(url, "https://user.example/mcp");
}
other => panic!("expected streamable http transport, got {other:?}"),
}
match &docs.transport {
McpServerTransportConfig::StreamableHttp { url, .. } => {
assert_eq!(url, "https://docs.example/mcp");
}
other => panic!("expected streamable http transport, got {other:?}"),
}
}

View File

@@ -0,0 +1,56 @@
use std::sync::Arc;
use akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
use futures::future::BoxFuture;
const OPENAI_DEVELOPER_DOCS_MCP_URL: &str = "https://developers.openai.com/mcp";
const OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL: &str = "https://developers.openai.com/mcp?source=codex";
pub(crate) fn maybe_with_openai_docs_source_attribution(
mcp_server_url: &str,
http_client: Arc<dyn HttpClient>,
) -> Arc<dyn HttpClient> {
if mcp_server_url == OPENAI_DEVELOPER_DOCS_MCP_URL {
Arc::new(OpenAiDocsHttpClient { http_client })
} else {
http_client
}
}
struct OpenAiDocsHttpClient {
http_client: Arc<dyn HttpClient>,
}
impl OpenAiDocsHttpClient {
fn attribute_mcp_request(&self, params: &mut HttpRequestParams) {
if params.url == OPENAI_DEVELOPER_DOCS_MCP_URL {
params.url = OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL.to_string();
}
}
}
impl HttpClient for OpenAiDocsHttpClient {
fn http_request(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.attribute_mcp_request(&mut params);
self.http_client.http_request(params)
}
fn http_request_stream(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.attribute_mcp_request(&mut params);
self.http_client.http_request_stream(params)
}
}
#[cfg(test)]
#[path = "openai_docs_source_attribution_tests.rs"]
mod tests;

View File

@@ -0,0 +1,92 @@
use std::sync::Arc;
use std::sync::Mutex;
use akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpRedirectPolicy;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
use futures::FutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use super::OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL;
use super::OPENAI_DEVELOPER_DOCS_MCP_URL;
use super::maybe_with_openai_docs_source_attribution;
#[derive(Default)]
struct RecordingHttpClient {
urls: Mutex<Vec<String>>,
}
impl HttpClient for RecordingHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.urls.lock().unwrap().push(params.url);
async { Err(ExecServerError::HttpRequest("test response".to_string())) }.boxed()
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.urls.lock().unwrap().push(params.url);
async { Err(ExecServerError::HttpRequest("test response".to_string())) }.boxed()
}
}
fn request(url: &str) -> HttpRequestParams {
HttpRequestParams {
method: "POST".to_string(),
url: url.to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "test-request".to_string(),
stream_response: true,
}
}
#[tokio::test]
async fn attributes_only_docs_mcp_requests() {
let recording_client = Arc::new(RecordingHttpClient::default());
let http_client = maybe_with_openai_docs_source_attribution(
OPENAI_DEVELOPER_DOCS_MCP_URL,
recording_client.clone(),
);
let _ = http_client
.http_request_stream(request(OPENAI_DEVELOPER_DOCS_MCP_URL))
.await;
let _ = http_client
.http_request(request(
"https://developers.openai.com/.well-known/oauth-protected-resource/mcp",
))
.await;
assert_eq!(
recording_client.urls.lock().unwrap().as_slice(),
[
OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL,
"https://developers.openai.com/.well-known/oauth-protected-resource/mcp",
]
);
}
#[test]
fn leaves_other_mcp_clients_unwrapped() {
let recording_client = Arc::new(RecordingHttpClient::default());
let http_client = maybe_with_openai_docs_source_attribution(
"https://example.com/mcp",
recording_client.clone(),
);
assert!(Arc::ptr_eq(
&http_client,
&(recording_client as Arc<dyn HttpClient>)
));
}

View File

@@ -0,0 +1,83 @@
use std::collections::HashSet;
use std::future::Future;
use std::time::Duration;
use anyhow::Result;
use anyhow::anyhow;
use rmcp::model::PaginatedRequestParams;
const MAX_MCP_CATALOG_PAGES: usize = 100;
pub(crate) const MAX_MCP_CATALOG_ITEMS: usize = 2_048;
const MAX_MCP_PAGINATION_CURSOR_BYTES: usize = 64 * 1024;
const DEFAULT_MCP_PAGINATION_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) async fn collect_paginated<T, F, Fut>(
method: &str,
overall_timeout: Option<Duration>,
fetch: F,
) -> Result<Vec<T>>
where
F: FnMut(Option<PaginatedRequestParams>) -> Fut,
Fut: Future<Output = Result<(Vec<T>, Option<String>)>>,
{
collect_paginated_with_limit(method, overall_timeout, MAX_MCP_CATALOG_ITEMS, fetch).await
}
pub(crate) async fn collect_paginated_with_limit<T, F, Fut>(
method: &str,
overall_timeout: Option<Duration>,
max_items: usize,
mut fetch: F,
) -> Result<Vec<T>>
where
F: FnMut(Option<PaginatedRequestParams>) -> Fut,
Fut: Future<Output = Result<(Vec<T>, Option<String>)>>,
{
let collect = async {
let mut collected = Vec::new();
let mut cursor = None;
let mut seen_cursors = HashSet::new();
let mut page_count = 0;
loop {
if page_count == MAX_MCP_CATALOG_PAGES {
return Err(anyhow!(
"{method} exceeded the pagination limit of {MAX_MCP_CATALOG_PAGES} pages"
));
}
page_count += 1;
let params = cursor.as_ref().map(|next: &String| {
PaginatedRequestParams::default().with_cursor(Some(next.clone()))
});
let (items, next_cursor) = fetch(params).await?;
if items.len() > max_items.saturating_sub(collected.len()) {
return Err(anyhow!(
"{method} exceeded the catalog limit of {max_items} items"
));
}
collected.extend(items);
let Some(next_cursor) = next_cursor else {
return Ok(collected);
};
if next_cursor.len() > MAX_MCP_PAGINATION_CURSOR_BYTES {
return Err(anyhow!(
"{method} returned a pagination cursor exceeding {MAX_MCP_PAGINATION_CURSOR_BYTES} bytes"
));
}
if !seen_cursors.insert(next_cursor.clone()) {
return Err(anyhow!("{method} returned a repeated pagination cursor"));
}
cursor = Some(next_cursor);
}
};
let timeout = overall_timeout.unwrap_or(DEFAULT_MCP_PAGINATION_TIMEOUT);
tokio::time::timeout(timeout, collect)
.await
.map_err(|_| anyhow!("{method} pagination timed out after {timeout:?}"))?
}
#[cfg(test)]
#[path = "pagination_tests.rs"]
mod tests;

View File

@@ -0,0 +1,226 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use anyhow::anyhow;
use pretty_assertions::assert_eq;
use super::MAX_MCP_CATALOG_ITEMS;
use super::MAX_MCP_CATALOG_PAGES;
use super::MAX_MCP_PAGINATION_CURSOR_BYTES;
use super::collect_paginated;
#[tokio::test]
async fn collects_all_pages_including_an_empty_cursor() {
let requests = Arc::new(Mutex::new(Vec::new()));
let observed = Arc::clone(&requests);
let pages = collect_paginated("tools/list", /*overall_timeout*/ None, move |params| {
let observed = Arc::clone(&observed);
async move {
let cursor = params.and_then(|params| params.cursor);
observed.lock().expect("request lock").push(cursor.clone());
match cursor.as_deref() {
None => Ok((vec!["first"], Some(String::new()))),
Some("") => Ok((vec!["second"], Some("last".to_string()))),
Some("last") => Ok((vec!["third"], None)),
Some(cursor) => Err(anyhow!("unexpected cursor: {cursor}")),
}
}
})
.await
.expect("paginated request succeeds");
assert_eq!(pages, vec!["first", "second", "third"]);
assert_eq!(
*requests.lock().expect("request lock"),
vec![None, Some(String::new()), Some("last".to_string())]
);
}
#[tokio::test]
async fn rejects_nonconsecutive_repeated_cursors() {
let error = collect_paginated(
"resources/list",
/*overall_timeout*/ None,
|params| async move {
let cursor = params.and_then(|params| params.cursor);
let next = match cursor.as_deref() {
None => "first",
Some("first") => "second",
Some("second") => "first",
Some(cursor) => return Err(anyhow!("unexpected cursor: {cursor}")),
};
Ok((Vec::<()>::new(), Some(next.to_string())))
},
)
.await
.expect_err("a repeated cursor must fail");
assert_eq!(
error.to_string(),
"resources/list returned a repeated pagination cursor"
);
}
#[tokio::test]
async fn rejects_excessive_pagination_before_fetching_another_page() {
let requests = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&requests);
let error = collect_paginated(
"tools/list",
/*overall_timeout*/ None,
move |_params| {
let observed = Arc::clone(&observed);
async move {
let page = observed.fetch_add(1, Ordering::Relaxed);
Ok((Vec::<()>::new(), Some(page.to_string())))
}
},
)
.await
.expect_err("unbounded pagination must fail");
assert_eq!(
error.to_string(),
format!("tools/list exceeded the pagination limit of {MAX_MCP_CATALOG_PAGES} pages")
);
assert_eq!(requests.load(Ordering::Relaxed), MAX_MCP_CATALOG_PAGES);
}
#[tokio::test]
async fn rejects_a_page_exceeding_the_catalog_item_limit() {
let error = collect_paginated(
"tools/list",
/*overall_timeout*/ None,
|_params| async { Ok((vec![(); MAX_MCP_CATALOG_ITEMS + 1], None)) },
)
.await
.expect_err("an oversized catalog page must fail");
assert_eq!(
error.to_string(),
format!("tools/list exceeded the catalog limit of {MAX_MCP_CATALOG_ITEMS} items")
);
}
#[tokio::test]
async fn rejects_a_catalog_exceeding_the_item_limit_across_pages() {
let error = collect_paginated(
"tools/list",
/*overall_timeout*/ None,
|params| async move {
match params.and_then(|params| params.cursor) {
None => Ok((vec![(); MAX_MCP_CATALOG_ITEMS], Some("last".to_string()))),
Some(cursor) if cursor == "last" => Ok((vec![()], None)),
Some(cursor) => Err(anyhow!("unexpected cursor: {cursor}")),
}
},
)
.await
.expect_err("catalog items must be bounded across pages");
assert_eq!(
error.to_string(),
format!("tools/list exceeded the catalog limit of {MAX_MCP_CATALOG_ITEMS} items")
);
}
#[tokio::test]
async fn rejects_oversized_pagination_cursors_before_following_them() {
let requests = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&requests);
let error = collect_paginated(
"resources/list",
/*overall_timeout*/ None,
move |_params| {
let observed = Arc::clone(&observed);
async move {
observed.fetch_add(1, Ordering::Relaxed);
Ok((
Vec::<()>::new(),
Some("x".repeat(MAX_MCP_PAGINATION_CURSOR_BYTES + 1)),
))
}
},
)
.await
.expect_err("an oversized pagination cursor must fail");
assert_eq!(
error.to_string(),
format!(
"resources/list returned a pagination cursor exceeding {MAX_MCP_PAGINATION_CURSOR_BYTES} bytes"
)
);
assert_eq!(requests.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn forwards_page_failures() {
let error = collect_paginated(
"resources/templates/list",
/*overall_timeout*/ None,
|_params| async { Err::<(Vec<()>, Option<String>), _>(anyhow!("page failed")) },
)
.await
.expect_err("a page error must fail");
assert_eq!(error.to_string(), "page failed");
}
#[tokio::test(start_paused = true)]
async fn applies_a_default_timeout_when_no_timeout_is_configured() {
let error = collect_paginated(
"resources/list",
/*overall_timeout*/ None,
|_params| async {
tokio::time::sleep(Duration::from_secs(31)).await;
Ok((Vec::<()>::new(), None))
},
)
.await
.expect_err("pagination without a configured timeout must still be bounded");
assert_eq!(
error.to_string(),
"resources/list pagination timed out after 30s"
);
}
#[tokio::test(start_paused = true)]
async fn applies_one_timeout_across_individually_timely_pages() {
let requests = Arc::new(Mutex::new(Vec::new()));
let observed = Arc::clone(&requests);
let error = collect_paginated("tools/list", Some(Duration::from_secs(5)), move |params| {
let observed = Arc::clone(&observed);
async move {
let cursor = params.and_then(|params| params.cursor);
observed.lock().expect("request lock").push(cursor.clone());
tokio::time::sleep(Duration::from_secs(2)).await;
match cursor.as_deref() {
None => Ok((vec!["first"], Some("second".to_string()))),
Some("second") => Ok((vec!["second"], Some("third".to_string()))),
Some("third") => Ok((vec!["third"], None)),
Some(cursor) => Err(anyhow!("unexpected cursor: {cursor}")),
}
}
})
.await
.expect_err("the combined page duration must exceed the shared timeout");
assert_eq!(
error.to_string(),
"tools/list pagination timed out after 5s"
);
assert_eq!(
*requests.lock().expect("request lock"),
vec![None, Some("second".to_string()), Some("third".to_string())]
);
}

View File

@@ -0,0 +1,338 @@
use akode_config::McpServerAuth;
use akode_config::McpServerConfig;
use akode_config::McpServerEnvVar;
use akode_config::McpServerTransportConfig;
use akode_utils_path_uri::LegacyAppPathString;
use akode_utils_path_uri::PathUri;
use serde::Deserialize;
use serde_json::Map as JsonMap;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
use std::path::Path;
use tracing::warn;
#[path = "agent_plugin_config.rs"]
mod agent_plugin_config;
pub use agent_plugin_config::parse_agent_plugin_mcp_config;
#[derive(Clone, Copy, Debug)]
enum PluginMcpSource<'a> {
Host {
root: &'a Path,
},
Environment {
root: &'a PathUri,
environment_id: &'a str,
},
}
/// One plugin MCP server that could not be normalized into runtime configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginMcpServerParseError {
pub name: String,
pub message: String,
}
/// Valid servers and per-server errors parsed from one plugin MCP file.
#[derive(Debug, Default, PartialEq)]
pub struct PluginMcpConfigParseOutcome {
pub servers: BTreeMap<String, McpServerConfig>,
pub errors: Vec<PluginMcpServerParseError>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PluginMcpServersFile {
mcp_servers: BTreeMap<String, JsonValue>,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum PluginMcpFile {
McpServersObject(PluginMcpServersFile),
ServerMap(BTreeMap<String, JsonValue>),
}
impl PluginMcpFile {
fn into_mcp_servers(self) -> BTreeMap<String, JsonValue> {
match self {
Self::McpServersObject(file) => file.mcp_servers,
Self::ServerMap(mcp_servers) => mcp_servers,
}
}
}
/// Parses wrapped or plain plugin MCP declarations without runtime normalization.
pub fn parse_plugin_mcp_declarations(
contents: &str,
) -> Result<BTreeMap<String, JsonValue>, serde_json::Error> {
serde_json::from_str::<PluginMcpFile>(contents).map(PluginMcpFile::into_mcp_servers)
}
/// Parses the two supported plugin MCP file shapes and normalizes each server.
///
/// Native plugin HTTP servers share the regular MCP transport configuration;
/// relative helper commands therefore use the session's local process cwd.
///
/// Invalid individual servers are returned as errors without discarding valid
/// siblings. A malformed top-level document fails the whole parse.
pub fn parse_plugin_mcp_config(
plugin_root: &Path,
contents: &str,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
parse_plugin_mcp_config_from(contents, PluginMcpSource::Host { root: plugin_root })
}
/// Parses executor-owned plugin MCP config without interpreting the plugin root
/// as a path on the orchestrator host.
pub fn parse_executor_plugin_mcp_config(
plugin_root: &PathUri,
contents: &str,
environment_id: &str,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
parse_plugin_mcp_config_from(
contents,
PluginMcpSource::Environment {
root: plugin_root,
environment_id,
},
)
}
/// Normalizes already-parsed declarations for one executor installation.
pub fn normalize_executor_plugin_mcp_declarations(
plugin_root: &PathUri,
declarations: BTreeMap<String, JsonValue>,
environment_id: &str,
) -> PluginMcpConfigParseOutcome {
normalize_plugin_mcp_declarations(
declarations,
PluginMcpSource::Environment {
root: plugin_root,
environment_id,
},
)
}
impl PluginMcpSource<'_> {
fn display(self) -> String {
match self {
Self::Host { root } => root.display().to_string(),
Self::Environment { root, .. } => root.to_string(),
}
}
}
fn parse_plugin_mcp_config_from(
contents: &str,
source: PluginMcpSource<'_>,
) -> Result<PluginMcpConfigParseOutcome, serde_json::Error> {
let declarations = parse_plugin_mcp_declarations(contents)?;
Ok(normalize_plugin_mcp_declarations(declarations, source))
}
fn normalize_plugin_mcp_declarations(
declarations: BTreeMap<String, JsonValue>,
source: PluginMcpSource<'_>,
) -> PluginMcpConfigParseOutcome {
let mut outcome = PluginMcpConfigParseOutcome::default();
for (name, config_value) in declarations {
match normalize_plugin_mcp_server(config_value, source) {
Ok(config) => {
outcome.servers.insert(name, config);
}
Err(message) => outcome
.errors
.push(PluginMcpServerParseError { name, message }),
}
}
outcome
}
fn normalize_plugin_mcp_server(
value: JsonValue,
source: PluginMcpSource<'_>,
) -> Result<McpServerConfig, String> {
let mut object = normalize_plugin_mcp_server_value(value, source);
if let PluginMcpSource::Environment {
root,
environment_id,
} = source
{
object.insert(
"environment_id".to_string(),
JsonValue::String(environment_id.to_string()),
);
if object.contains_key("command") {
match object.remove("cwd") {
Some(JsonValue::String(cwd)) => object.insert(
"cwd".to_string(),
JsonValue::String(environment_cwd(root, Some(&cwd))?.into_string()),
),
Some(JsonValue::Null) | None => object.insert(
"cwd".to_string(),
JsonValue::String(
environment_cwd(root, /*configured_cwd*/ None)?.into_string(),
),
),
Some(value) => object.insert("cwd".to_string(), value),
};
}
}
let mut config = serde_json::from_value::<McpServerConfig>(JsonValue::Object(object))
.map_err(|err| err.to_string())?;
if matches!(config.auth, McpServerAuth::EmaAuth) {
return Err(
"plugin MCP declarations cannot select ema_auth; enterprise-managed authorization is not supported"
.to_string(),
);
}
if matches!(source, PluginMcpSource::Environment { .. }) {
bind_environment_env_vars(&mut config)?;
}
Ok(config)
}
fn environment_cwd(
root: &PathUri,
configured_cwd: Option<&str>,
) -> Result<LegacyAppPathString, String> {
let Some(configured_cwd) = configured_cwd else {
return Ok(root.clone().into());
};
let cwd = PathUri::parse(configured_cwd)
.or_else(|_| root.join(configured_cwd))
.map_err(|err| format!("invalid cwd `{configured_cwd}`: {err}"))?;
if !cwd.starts_with(root) {
return Err(format!(
"cwd `{configured_cwd}` must remain within plugin root `{root}`"
));
}
Ok(cwd.into())
}
fn bind_environment_env_vars(config: &mut McpServerConfig) -> Result<(), String> {
let is_local_environment = config.is_local_environment();
let env_vars = match &mut config.transport {
McpServerTransportConfig::Stdio { env_vars, .. } => env_vars,
// Bearer credentials resolve on the executor; other header variables do not yet.
McpServerTransportConfig::StreamableHttp {
env_http_headers, ..
} => {
if is_local_environment {
return Ok(());
}
if env_http_headers
.as_ref()
.is_some_and(|headers| !headers.is_empty())
{
return Err(
"`env_http_headers` requires executor-side environment resolution for an executor-owned HTTP MCP"
.to_string(),
);
}
return Ok(());
}
};
for env_var in env_vars {
match env_var {
McpServerEnvVar::Name(name) if !is_local_environment => {
*env_var = McpServerEnvVar::Config {
name: std::mem::take(name),
source: Some("remote".to_string()),
};
}
McpServerEnvVar::Name(_) => {}
McpServerEnvVar::Config { name, source } => {
match (is_local_environment, source.as_deref()) {
(true, None | Some("local")) | (false, Some("remote")) => {}
(true, Some("remote")) => {
return Err(format!(
"env_vars entry `{name}` cannot use source `remote` in a local environment"
));
}
(false, None) => *source = Some("remote".to_string()),
(false, Some("local")) => {
return Err(format!(
"env_vars entry `{name}` cannot use source `local` in an executor-owned plugin"
));
}
(_, Some(source)) => unreachable!("validated env_vars source `{source}`"),
}
}
}
}
Ok(())
}
fn normalize_plugin_mcp_server_value(
value: JsonValue,
source: PluginMcpSource<'_>,
) -> JsonMap<String, JsonValue> {
let mut object = match value {
JsonValue::Object(object) => object,
_ => return JsonMap::new(),
};
if let Some(JsonValue::String(transport_type)) = object.remove("type") {
match transport_type.as_str() {
"http" | "streamable_http" | "streamable-http" | "stdio" => {}
other => {
let plugin_display = source.display();
warn!(
plugin = %plugin_display,
transport = other,
"plugin MCP server uses an unknown transport type"
);
}
}
}
if let Some(JsonValue::Object(mut oauth)) = object.remove("oauth") {
if let Some(callback_url) = oauth.remove("callbackUrl") {
oauth
.entry("callback_url".to_string())
.or_insert(callback_url);
}
if let Some(callback_port) = oauth.remove("callbackPort") {
oauth
.entry("callback_port".to_string())
.or_insert(callback_port);
}
if let Some(client_id) = oauth.remove("clientId") {
oauth.entry("client_id".to_string()).or_insert(client_id);
}
if let Some(client_secret) = oauth.remove("clientSecret") {
oauth
.entry("client_secret".to_string())
.or_insert(client_secret);
}
if !oauth.is_empty() {
object.insert("oauth".to_string(), JsonValue::Object(oauth));
}
}
if let PluginMcpSource::Host { root } = source
&& let Some(JsonValue::String(cwd)) = object.get("cwd")
&& !Path::new(cwd).is_absolute()
{
object.insert(
"cwd".to_string(),
JsonValue::String(root.join(cwd).display().to_string()),
);
}
object
}
#[cfg(test)]
#[path = "plugin_config_tests.rs"]
mod tests;

View File

@@ -0,0 +1,987 @@
use super::PluginMcpConfigParseOutcome;
use super::PluginMcpServerParseError;
use super::normalize_executor_plugin_mcp_declarations;
use super::parse_agent_plugin_mcp_config;
use super::parse_executor_plugin_mcp_config;
use super::parse_plugin_mcp_config;
use akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use akode_config::McpServerConfig;
use akode_config::McpServerEnvVar;
use akode_config::McpServerOAuthConfig;
use akode_config::McpServerTransportConfig;
use akode_utils_path_uri::LegacyAppPathString;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
fn plugin_root() -> PathBuf {
std::env::current_dir()
.expect("current directory")
.join("plugin-root")
}
fn plugin_root_uri(plugin_root: &Path) -> PathUri {
PathUri::from_host_native_path(plugin_root).expect("plugin root URI")
}
#[test]
fn agent_plugin_placeholder_expansion_is_single_pass() {
let plugin_root = plugin_root().join("${PLUGIN_DATA}");
let plugin_data_root = plugin_root
.parent()
.expect("plugin root parent")
.join("plugin-data");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"demo":{
"type":"stdio",
"command":"python",
"args":["${PLUGIN_ROOT}:${PLUGIN_DATA}"]
}}
}"#,
)
.expect("parse Agent Plugins MCP config");
let McpServerTransportConfig::Stdio { args, .. } = &outcome.servers["demo"].transport else {
panic!("expected stdio transport");
};
assert_eq!(
args,
&vec![format!(
"{}:{}",
plugin_root.display(),
plugin_data_root.display()
)]
);
}
#[test]
fn agent_plugin_mcp_expands_reserved_paths_and_maps_transports() {
let plugin_root = plugin_root();
let plugin_data_root = plugin_root.parent().expect("parent").join("plugin-data");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"local": {
"type":"stdio",
"command":"python",
"args":["${PLUGIN_ROOT}/server.py", "${PLUGIN_DATA}/state.json"],
"env":{"CACHE":"${PLUGIN_DATA}/cache"},
"cwd":"${PLUGIN_ROOT}/scripts"
},
"remote": {
"type":"streamable-http",
"url":"https://example.com/mcp",
"headers":{"X-Plugin":"demo"}
}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
let local = outcome.servers.get("local").expect("local server");
let McpServerTransportConfig::Stdio { args, env, cwd, .. } = &local.transport else {
panic!("expected stdio transport");
};
assert_eq!(
args,
&vec![
format!("{}/server.py", plugin_root.display()),
format!("{}/state.json", plugin_data_root.display()),
]
);
assert_eq!(
env.as_ref().expect("environment").get("PLUGIN_ROOT"),
Some(&plugin_root.display().to_string())
);
assert_eq!(
env.as_ref().expect("environment").get("PLUGIN_DATA"),
Some(&plugin_data_root.display().to_string())
);
assert_eq!(
cwd.as_ref(),
Some(&LegacyAppPathString::from_path(
&plugin_root.join("scripts")
))
);
let remote = outcome.servers.get("remote").expect("remote server");
let McpServerTransportConfig::StreamableHttp { http_headers, .. } = &remote.transport else {
panic!("expected HTTP transport");
};
assert_eq!(
http_headers
.as_ref()
.and_then(|headers| headers.get("X-Plugin")),
Some(&"demo".to_string())
);
}
#[test]
fn agent_plugin_mcp_handles_portable_path_and_http_edge_cases() {
let plugin_root = plugin_root();
let plugin_data_root = plugin_root.parent().expect("parent").join("plugin-data");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"contained":{"type":"stdio","command":"./bin/../server","cwd":"${PLUGIN_ROOT}/work/../data"},
"redundant-separator":{"type":"stdio","command":".//bin/server"},
"root-slash":{"type":"stdio","command":"python","cwd":"${PLUGIN_ROOT}/"},
"data-slash":{"type":"stdio","command":"python","cwd":"${PLUGIN_DATA}/"},
"headers":{"type":"streamable-http","url":"https://example.com/mcp","headers":{"aUtHoRiZaTiOn":"public-package-value","Content-Length":"0","HOST":"other.example.com","Proxy-Authorization":"public-package-value","Transfer-Encoding":"chunked","uSeR-aGeNt":"plugin-agent/1.0","X-Plugin":"demo","X-Plugin-Name":"café"}},
"loopback":{"type":"streamable-http","url":"http://[::1]/mcp"}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
assert_eq!(
outcome.servers.keys().collect::<Vec<_>>(),
vec![
"contained",
"data-slash",
"headers",
"loopback",
"redundant-separator",
"root-slash"
]
);
let McpServerTransportConfig::Stdio { command, cwd, .. } =
&outcome.servers["contained"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(command, &plugin_root.join("server").display().to_string());
assert_eq!(
cwd.as_ref(),
Some(&LegacyAppPathString::from_path(&plugin_root.join("data")))
);
let McpServerTransportConfig::Stdio { command, .. } =
&outcome.servers["redundant-separator"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(
command,
&plugin_root.join("bin").join("server").display().to_string()
);
for (server_name, expected_cwd) in [
("root-slash", plugin_root.as_path()),
("data-slash", plugin_data_root.as_path()),
] {
let McpServerTransportConfig::Stdio { cwd, .. } = &outcome.servers[server_name].transport
else {
panic!("expected stdio transport");
};
assert_eq!(
cwd.as_ref(),
Some(&LegacyAppPathString::from_path(expected_cwd))
);
}
let McpServerTransportConfig::StreamableHttp { http_headers, .. } =
&outcome.servers["headers"].transport
else {
panic!("expected HTTP transport");
};
assert_eq!(
http_headers,
&Some(HashMap::from([
("X-Plugin".to_string(), "demo".to_string()),
("X-Plugin-Name".to_string(), "café".to_string()),
]))
);
}
#[test]
fn agent_plugin_mcp_skips_invalid_server_without_disabling_siblings() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"valid":{"type":"stdio","command":"python"},
"reserved":{"type":"stdio","command":"python","env":{"PLUGIN_ROOT":"bad"}}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert_eq!(outcome.servers.keys().collect::<Vec<_>>(), vec!["valid"]);
assert_eq!(outcome.errors.len(), 1);
assert_eq!(outcome.errors[0].name, "reserved");
assert!(
outcome.errors[0]
.message
.contains("reserved variable `PLUGIN_ROOT`")
);
}
#[test]
fn agent_plugin_mcp_preserves_server_named_mcp_servers() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"mcpServers":{"type":"stdio","command":"first"},
"sibling":{"type":"stdio","command":"second"}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
assert_eq!(
outcome.servers.keys().collect::<Vec<_>>(),
vec!["mcpServers", "sibling"]
);
}
#[test]
fn agent_plugin_mcp_preserves_arbitrary_server_names() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"agent.smoke / local":{"type":"stdio","command":"python"}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
assert!(outcome.servers.contains_key("agent.smoke / local"));
}
#[test]
fn agent_plugin_mcp_rejects_explicit_null_optional_fields() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{
"cwd":{"type":"stdio","command":"python","cwd":null},
"headers":{"type":"streamable-http","url":"https://example.com/mcp","headers":null}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.servers.is_empty());
assert_eq!(outcome.errors.len(), 2);
assert!(
outcome
.errors
.iter()
.any(|error| error.message.contains("`cwd`"))
);
assert!(
outcome
.errors
.iter()
.any(|error| error.message.contains("`headers`"))
);
}
#[cfg(windows)]
#[test]
fn agent_plugin_mcp_rejects_reserved_environment_aliases_case_insensitively() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"reserved":{"type":"stdio","command":"python","env":{"plugin_root":"bad"}}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.servers.is_empty());
assert_eq!(outcome.errors.len(), 1);
}
#[cfg(windows)]
#[test]
fn agent_plugin_mcp_overlays_windows_environment_case_insensitively() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{
"configured":{"type":"stdio","command":"python","env":{"Path":"configured"}},
"duplicate":{"type":"stdio","command":"python","env":{"PATH":"one","Path":"two"}}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert_eq!(
outcome.servers.keys().collect::<Vec<_>>(),
vec!["configured"]
);
assert_eq!(outcome.errors.len(), 1);
let McpServerTransportConfig::Stdio { env, .. } = &outcome.servers["configured"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(
env.as_ref().and_then(|env| env.get("PATH")),
Some(&"configured".to_string())
);
}
#[cfg(unix)]
#[test]
fn agent_plugin_mcp_resolves_root_before_collapsing_parent_components() {
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir().expect("temporary directory");
let base = temp.path().join("base");
let outside = temp.path().join("outside");
let outside_directory = outside.join("directory");
let resolved_plugin_root = outside.join("plugin");
let plugin_data_root = temp.path().join("plugin-data");
std::fs::create_dir_all(&base).expect("create base directory");
std::fs::create_dir_all(&outside_directory).expect("create symlink target");
std::fs::create_dir_all(&resolved_plugin_root).expect("create resolved plugin root");
std::fs::create_dir_all(&plugin_data_root).expect("create plugin data root");
let canonical_plugin_root = resolved_plugin_root
.canonicalize()
.expect("canonical plugin root");
symlink(&outside_directory, base.join("link")).expect("create root symlink");
let plugin_root = base.join("link/../plugin");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"demo":{"type":"stdio","command":"python"}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
let McpServerTransportConfig::Stdio { env, cwd, .. } = &outcome.servers["demo"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(
env.as_ref().and_then(|env| env.get("PLUGIN_ROOT")),
Some(&canonical_plugin_root.display().to_string())
);
assert_eq!(
cwd.as_ref(),
Some(&LegacyAppPathString::from_path(&canonical_plugin_root))
);
}
#[cfg(unix)]
#[test]
fn agent_plugin_mcp_rejects_missing_descendant_below_escaping_symlink() {
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir().expect("temporary directory");
let plugin_root = temp.path().join("plugin");
let plugin_data_root = temp.path().join("plugin-data");
let outside = temp.path().join("outside");
std::fs::create_dir_all(&plugin_root).expect("create plugin root");
std::fs::create_dir_all(&plugin_data_root).expect("create plugin data root");
std::fs::create_dir_all(&outside).expect("create outside directory");
symlink(&outside, plugin_root.join("link")).expect("create escaping symlink");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"escape":{"type":"stdio","command":"./link/missing"}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.servers.is_empty());
assert_eq!(outcome.errors.len(), 1);
assert!(outcome.errors[0].message.contains("must remain within"));
}
#[test]
fn agent_plugin_mcp_enforces_closed_transport_and_path_semantics() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"valid":{"type":"stdio","command":"python"},
"command":{"type":"stdio","command":"../server"},
"escape":{"type":"stdio","command":"./../server"},
"cwd":{"type":"stdio","command":"python","cwd":"${PLUGIN_ROOT}/../outside"},
"backslash":{"type":"stdio","command":"./scripts\\..\\outside"},
"remote":{"type":"streamable-http","url":"http://example.com/mcp"},
"header":{"type":"streamable-http","url":"https://example.com/mcp","headers":{"X-Demo":"one","x-demo":"two"}},
"sse":{"type":"sse","url":"https://example.com/sse"},
"unknown":{"type":"stdio","command":"python","future":true}
}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert_eq!(outcome.servers.keys().collect::<Vec<_>>(), vec!["valid"]);
assert_eq!(outcome.errors.len(), 8);
}
#[cfg(windows)]
#[test]
fn agent_plugin_mcp_rejects_drive_relative_windows_command() {
let plugin_root = plugin_root();
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json","mcpServers":{"drive-relative":{"type":"stdio","command":"C:server.exe"}}}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.servers.is_empty());
assert_eq!(outcome.errors.len(), 1);
}
#[test]
fn agent_plugin_mcp_treats_args_and_env_as_opaque_after_expansion() {
let plugin_root = plugin_root();
let data_root = plugin_root.join("data");
let outcome = parse_agent_plugin_mcp_config(
&plugin_root,
&data_root,
r#"{
"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers":{"demo":{
"type":"stdio",
"command":"python",
"args":["${PLUGIN_ROOT}/../opaque"],
"env":{"OPAQUE":"${PLUGIN_DATA}/../opaque"}
}}
}"#,
)
.expect("parse Agent Plugins MCP config");
assert!(outcome.errors.is_empty());
let McpServerTransportConfig::Stdio { args, env, .. } = &outcome.servers["demo"].transport
else {
panic!("expected stdio transport");
};
assert_eq!(args, &vec![format!("{}/../opaque", plugin_root.display())]);
assert_eq!(
env.as_ref().and_then(|env| env.get("OPAQUE")),
Some(&format!("{}/../opaque", data_root.display()))
);
}
#[test]
fn agent_plugin_mcp_rejects_unsupported_schema() {
let plugin_root = plugin_root();
let error = parse_agent_plugin_mcp_config(
&plugin_root,
&plugin_root.join("data"),
r#"{"$schema":"https://agent-plugins.org/schemas/2.0.0/mcp.schema.json","mcpServers":{}}"#,
)
.expect_err("unsupported schema");
assert!(
error
.to_string()
.contains("unsupported Agent Plugins MCP schema")
);
}
fn stdio_server(
command: &str,
environment_id: &str,
cwd: LegacyAppPathString,
env_vars: Vec<McpServerEnvVar>,
) -> McpServerConfig {
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::Stdio {
command: command.to_string(),
args: Vec::new(),
env: None,
env_vars,
cwd: Some(cwd),
},
environment_id: environment_id.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
}
}
#[test]
fn declared_placement_preserves_local_plugin_normalization() {
let plugin_root = plugin_root();
let expected_stdio = stdio_server(
"demo-mcp",
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
LegacyAppPathString::from_path(&plugin_root.join("scripts")),
Vec::new(),
);
let expected_http = 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: DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: Some(McpServerOAuthConfig {
client_id: Some("client-id".to_string()),
client_secret: Some("plugin-client-secret".into()),
callback_url: Some("http://127.0.0.1/callback/registered".to_string()),
callback_port: Some(9876),
..Default::default()
}),
oauth_resource: None,
tools: HashMap::new(),
};
let mut expected_helper = McpServerConfig {
oauth: None,
..expected_http.clone()
};
let McpServerTransportConfig::StreamableHttp {
http_headers_helper,
..
} = &mut expected_helper.transport
else {
unreachable!("expected HTTP transport");
};
*http_headers_helper = Some("./auth.sh".to_string());
let outcome = parse_plugin_mcp_config(
&plugin_root,
r#"{
"demo": {
"type": "stdio",
"command": "demo-mcp",
"cwd": "scripts"
},
"hosted": {
"type": "http",
"url": "https://example.com/mcp",
"oauth": {"clientId": "client-id", "clientSecret": "plugin-client-secret", "callbackUrl": "http://127.0.0.1/callback/registered", "callbackPort": 9876}
},
"helper": {"type":"http","url":"https://example.com/mcp","http_headers_helper":"./auth.sh"}
}"#,
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([
("demo".to_string(), expected_stdio),
("helper".to_string(), expected_helper),
("hosted".to_string(), expected_http),
]),
errors: Vec::new(),
}
);
}
#[test]
fn native_plugin_mcp_cannot_self_declare_ema_auth() {
let server = serde_json::json!({
"type": "http",
"url": "https://resource.example/mcp",
"auth": "ema_auth"
});
for contents in [
serde_json::json!({"enterprise": server}),
serde_json::json!({"mcpServers": {"enterprise": server}}),
] {
let outcome = parse_plugin_mcp_config(&plugin_root(), &contents.to_string())
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::new(),
errors: vec![PluginMcpServerParseError {
name: "enterprise".to_string(),
message: "plugin MCP declarations cannot select ema_auth; enterprise-managed authorization is not supported".to_string(),
}],
}
);
}
}
#[test]
fn environment_placement_forces_authority_and_defaults_null_cwd() {
let plugin_root = plugin_root();
let plugin_root_uri = plugin_root_uri(&plugin_root);
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri,
r#"{
"$schema":"https://example.com/plugin-mcp.schema.json",
"mcpServers":{"demo":{
"command":"demo-mcp",
"environment_id":"local",
"cwd":null,
"env_vars":["EXECUTOR_TOKEN", {"name":"OTHER_TOKEN"}]
}}
}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
stdio_server(
"demo-mcp",
"executor-1",
plugin_root_uri.into(),
vec![
McpServerEnvVar::Config {
name: "EXECUTOR_TOKEN".to_string(),
source: Some("remote".to_string()),
},
McpServerEnvVar::Config {
name: "OTHER_TOKEN".to_string(),
source: Some("remote".to_string()),
},
],
),
)]),
errors: Vec::new(),
}
);
}
#[test]
fn environment_placement_resolves_relative_cwd_beneath_plugin_root() {
let plugin_root = plugin_root();
let plugin_root_uri = plugin_root_uri(&plugin_root);
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri,
r#"{"demo":{"command":"demo-mcp","cwd":"scripts"}}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
stdio_server(
"demo-mcp",
"executor-1",
plugin_root_uri
.join("scripts")
.expect("plugin cwd URI")
.into(),
Vec::new(),
),
)]),
errors: Vec::new(),
}
);
}
#[test]
fn executor_environment_placement_resolves_foreign_uri_cwd() {
let plugin_root = PathUri::parse("file:///C:/plugins/demo").expect("plugin root URI");
let outcome = parse_executor_plugin_mcp_config(
&plugin_root,
r#"{"demo":{"command":"demo-mcp","cwd":"scripts"}}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
normalize_executor_plugin_mcp_declarations(
&plugin_root,
BTreeMap::from([(
"demo".to_string(),
serde_json::json!({"command": "demo-mcp", "cwd": "scripts"}),
)]),
"executor-1",
),
outcome
);
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
stdio_server(
"demo-mcp",
"executor-1",
LegacyAppPathString::from(
plugin_root.join("scripts").expect("executor cwd URI"),
),
Vec::new(),
),
)]),
errors: Vec::new(),
}
);
}
#[test]
fn environment_placement_rejects_relative_cwd_that_escapes_package() {
let plugin_root = plugin_root();
let plugin_root_uri = plugin_root_uri(&plugin_root);
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri,
r#"{"demo":{"command":"demo-mcp","cwd":"../outside"}}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::new(),
errors: vec![PluginMcpServerParseError {
name: "demo".to_string(),
message: format!(
"cwd `../outside` must remain within plugin root `{plugin_root_uri}`"
),
}],
}
);
}
#[test]
fn environment_placement_rejects_orchestrator_env_vars() {
let plugin_root = plugin_root();
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri(&plugin_root),
r#"{"demo":{"command":"demo-mcp","env_vars":[{"name":"TOKEN","source":"local"}]}}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::new(),
errors: vec![PluginMcpServerParseError {
name: "demo".to_string(),
message:
"env_vars entry `TOKEN` cannot use source `local` in an executor-owned plugin"
.to_string(),
}],
}
);
}
#[test]
fn remote_environment_placement_preserves_bearer_and_rejects_header_env_references() {
let plugin_root = plugin_root();
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri(&plugin_root),
r#"{
"bearer": {
"url": "https://example.com/bearer",
"bearer_token_env_var": "TOKEN"
},
"headers": {
"url": "https://example.com/headers",
"env_http_headers": {"Authorization": "TOKEN"}
}
}"#,
"executor-1",
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"bearer".to_string(),
serde_json::from_value(serde_json::json!({
"url": "https://example.com/bearer",
"bearer_token_env_var": "TOKEN",
"environment_id": "executor-1",
}))
.expect("executor-owned bearer configuration"),
)]),
errors: vec![PluginMcpServerParseError {
name: "headers".to_string(),
message: "`env_http_headers` requires executor-side environment resolution for an executor-owned HTTP MCP"
.to_string(),
}],
}
);
}
#[test]
fn local_environment_placement_preserves_http_env_references() {
let plugin_root = plugin_root();
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri(&plugin_root),
r#"{
"demo": {
"url": "https://example.com/mcp",
"bearer_token_env_var": "TOKEN",
"env_http_headers": {"X-Account": "ACCOUNT_ID"}
}
}"#,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://example.com/mcp".to_string(),
bearer_token_env_var: Some("TOKEN".to_string()),
http_headers: None,
env_http_headers: Some(HashMap::from([(
"X-Account".to_string(),
"ACCOUNT_ID".to_string(),
)])),
http_headers_helper: None,
},
environment_id: DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
enabled: true,
required: false,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
},
)]),
errors: Vec::new(),
}
);
}
#[test]
fn local_environment_placement_preserves_local_env_vars() {
let plugin_root = plugin_root();
let plugin_root_uri = plugin_root_uri(&plugin_root);
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri,
r#"{"demo":{"command":"demo-mcp","env_vars":["TOKEN",{"name":"OTHER","source":"local"}]}}"#,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::from([(
"demo".to_string(),
stdio_server(
"demo-mcp",
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
plugin_root_uri.into(),
vec![
McpServerEnvVar::Name("TOKEN".to_string()),
McpServerEnvVar::Config {
name: "OTHER".to_string(),
source: Some("local".to_string()),
},
],
),
)]),
errors: Vec::new(),
}
);
}
#[test]
fn local_environment_placement_rejects_remote_env_vars() {
let plugin_root = plugin_root();
let outcome = parse_executor_plugin_mcp_config(
&plugin_root_uri(&plugin_root),
r#"{"demo":{"command":"demo-mcp","env_vars":[{"name":"TOKEN","source":"remote"}]}}"#,
DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
)
.expect("parse plugin MCP config");
assert_eq!(
outcome,
PluginMcpConfigParseOutcome {
servers: BTreeMap::new(),
errors: vec![PluginMcpServerParseError {
name: "demo".to_string(),
message: "env_vars entry `TOKEN` cannot use source `remote` in a local environment"
.to_string(),
}],
}
);
}

View File

@@ -0,0 +1,173 @@
use std::sync::Arc;
use std::sync::Weak;
use anyhow::Context;
use anyhow::Result;
use akode_protocol::mcp::Resource;
use akode_protocol::mcp::ResourceContent;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use crate::McpRuntime;
use crate::connection_manager::McpConnectionSet;
use crate::connection_manager::McpServerConnection;
/// One page of resources returned by an MCP server.
#[derive(Clone, Debug, PartialEq)]
pub struct McpResourcePage {
/// Resources advertised on this page.
pub resources: Vec<Resource>,
/// Opaque cursor to supply when requesting the next page.
pub next_cursor: Option<String>,
}
/// Contents returned after reading one MCP resource.
#[derive(Clone, Debug, PartialEq)]
pub struct McpResourceReadResult {
/// Text or blob content returned for the requested resource.
pub contents: Vec<ResourceContent>,
}
/// Access to MCP resources through the latest runtime.
#[derive(Clone)]
pub struct McpResourceClient {
runtime: Arc<McpRuntime>,
}
/// Opaque identity for the connection set currently used by an MCP resource client.
#[derive(Clone)]
pub struct McpResourceClientCacheKey(Weak<McpConnectionSet>);
impl PartialEq for McpResourceClientCacheKey {
fn eq(&self, other: &Self) -> bool {
self.0.ptr_eq(&other.0)
}
}
impl Eq for McpResourceClientCacheKey {}
/// Identity of one server's resource cache across MCP runtime publications.
///
/// Survives publications that reuse the same connection until resource caches are explicitly
/// invalidated. The key does not keep superseded connections alive.
#[derive(Clone)]
pub struct McpResourceServerCacheKey {
pub(crate) connection: Weak<McpServerConnection>,
pub(crate) generation: u64,
}
impl PartialEq for McpResourceServerCacheKey {
fn eq(&self, other: &Self) -> bool {
self.connection.ptr_eq(&other.connection) && self.generation == other.generation
}
}
impl Eq for McpResourceServerCacheKey {}
/// Opaque auth scope and server availability, independent of connection-set rebuilds.
/// This is for fixed, host-owned sources; it does not fingerprint arbitrary server config.
#[derive(Clone)]
pub struct McpResourceClientAuthKey {
pub(crate) generation: Arc<()>,
pub(crate) server: String,
pub(crate) available: bool,
}
impl PartialEq for McpResourceClientAuthKey {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.generation, &other.generation)
&& self.server == other.server
&& self.available == other.available
}
}
impl Eq for McpResourceClientAuthKey {}
impl std::fmt::Debug for McpResourceClient {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("McpResourceClient")
.finish_non_exhaustive()
}
}
impl McpResourceClient {
/// Creates a resource client that follows the thread's latest published runtime.
pub fn new(runtime: Arc<McpRuntime>) -> Self {
Self { runtime }
}
/// Returns the identity of the connection set used by this client.
pub fn cache_key(&self) -> McpResourceClientCacheKey {
McpResourceClientCacheKey(Arc::downgrade(&self.runtime.latest_connections()))
}
/// Returns a server's resource cache identity without starting its connection.
pub fn server_cache_key(&self, server: &str) -> Option<McpResourceServerCacheKey> {
self.runtime.resource_cache_key(server)
}
/// Tracks published auth and source availability without invalidating on unrelated
/// environment changes. This key contains no credentials.
pub fn auth_cache_key_for_server(&self, server: &str) -> McpResourceClientAuthKey {
self.runtime.auth_cache_key_for_server(server)
}
/// Returns whether this client can address the named server.
///
/// This does not wait for server startup.
pub async fn has_server(&self, server: &str) -> bool {
self.runtime.latest_connections().contains_server(server)
}
/// Lists one resource page from the named server.
pub async fn list_resources(
&self,
server: &str,
cursor: Option<String>,
) -> Result<McpResourcePage> {
let params =
cursor.map(|cursor| PaginatedRequestParams::default().with_cursor(Some(cursor)));
let result = self
.runtime
.latest_connections()
.list_resources(server, params)
.await?;
let resources = result
.resources
.into_iter()
.map(resource_from_rmcp)
.collect::<Result<Vec<_>>>()?;
Ok(McpResourcePage {
resources,
next_cursor: result.next_cursor,
})
}
/// Reads one resource from the named server.
pub async fn read_resource(&self, server: &str, uri: &str) -> Result<McpResourceReadResult> {
let params = ReadResourceRequestParams::new(uri.to_string());
let result = self
.runtime
.latest_connections()
.read_resource(server, params)
.await?;
let contents = result
.contents
.into_iter()
.map(resource_content_from_rmcp)
.collect::<Result<Vec<_>>>()?;
Ok(McpResourceReadResult { contents })
}
}
fn resource_from_rmcp(resource: rmcp::model::Resource) -> Result<Resource> {
let value = serde_json::to_value(resource).context("failed to serialize MCP resource")?;
Resource::from_mcp_value(value).context("failed to convert MCP resource")
}
fn resource_content_from_rmcp(content: rmcp::model::ResourceContents) -> Result<ResourceContent> {
let value =
serde_json::to_value(content).context("failed to serialize MCP resource content")?;
serde_json::from_value(value).context("failed to convert MCP resource content")
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,161 @@
//! A chat's access to an initialized MCP client and its tool catalog.
//! A pooled connection honors this chat's lease and routes input requests back to it.
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use crate::client_tool_catalog::ClientToolCatalog;
use crate::connection_pool::ConnectionSharing;
use crate::tools::ToolInfo;
use anyhow::Result;
use anyhow::anyhow;
use akode_protocol::mcp::McpServerInfo;
use akode_rmcp_client::RmcpClient;
use akode_rmcp_client::SendElicitation;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ServerCapabilities;
use serde_json::Value;
use tokio_util::task::AbortOnDropHandle;
#[derive(Clone)]
pub(crate) struct ManagedClient {
pub(crate) connection_sharing: ConnectionSharing,
/// The calling chat's input handler, separate from the shared transport's startup handler.
pub(crate) shared_elicitation: Option<Arc<SendElicitation>>,
pub(crate) _auth_change_notifications: Option<Arc<AbortOnDropHandle<()>>>,
pub(crate) client: Arc<RmcpClient>,
pub(crate) server_info: McpServerInfo,
pub(crate) tool_catalog: Arc<ClientToolCatalog>,
pub(crate) tool_timeout: Option<Duration>,
pub(crate) server_instructions: Option<String>,
pub(crate) server_supports_sandbox_state_meta_capability: bool,
pub(crate) client_supports_network_policy_meta_capability: bool,
}
impl ManagedClient {
pub(crate) async fn with_active_shared_lease<T>(
&self,
operation: impl Future<Output = T>,
) -> Result<T> {
match &self.connection_sharing {
ConnectionSharing::Shared(lease) => tokio::select! {
biased;
() = lease.cancellation().cancelled() => {
Err(anyhow!("MCP connection lease has been released"))
}
result = operation => Ok(result),
},
ConnectionSharing::Private
| ConnectionSharing::Negotiated
| ConnectionSharing::Owned(_) => Ok(operation.await),
}
}
pub(crate) async fn with_lease_request<T>(
&self,
operation: impl Future<Output = Result<T>>,
) -> Result<T> {
// Keep one copy of the request future as it passes through both lease scopes.
let operation = std::pin::pin!(operation);
self.with_active_shared_lease(async {
match self.connection_sharing.server_lease() {
Some(lease) => lease.requests.scope(operation).await,
None => operation.await,
}
})
.await?
}
pub(crate) async fn call_tool(
&self,
name: String,
arguments: Option<Value>,
meta_for_session: impl Fn(&ServerCapabilities) -> Result<Option<Value>> + Send + Sync,
timeout: Option<Duration>,
) -> Result<rmcp::model::CallToolResult> {
let meta_for_session = |caps: &ServerCapabilities| {
let mut meta = meta_for_session(caps)?;
if let Some(lease) = self.connection_sharing.server_lease() {
meta.get_or_insert_with(|| serde_json::json!({}))
.as_object_mut()
.ok_or_else(|| anyhow!("MCP tool metadata must be an object"))?
.insert(
crate::connection_pool::LEASE_META_KEY.to_owned(),
serde_json::json!(lease.id),
);
}
Ok(meta)
};
self.with_lease_request(async {
if let Some(send_elicitation) = &self.shared_elicitation {
self.client
.call_tool_with_elicitation(
name,
arguments,
meta_for_session,
timeout,
Arc::clone(send_elicitation),
)
.await
} else {
self.client
.call_tool(name, arguments, meta_for_session, timeout)
.await
}
})
.await
}
/// Lists resources within this chat's lease lifetime.
pub(crate) async fn list_resources(
&self,
params: Option<PaginatedRequestParams>,
timeout: Option<Duration>,
) -> Result<ListResourcesResult> {
self.with_active_shared_lease(self.client.list_resources(params, timeout))
.await?
}
/// Lists resource templates within this chat's lease lifetime.
pub(crate) async fn list_resource_templates(
&self,
params: Option<PaginatedRequestParams>,
timeout: Option<Duration>,
) -> Result<ListResourceTemplatesResult> {
self.with_active_shared_lease(self.client.list_resource_templates(params, timeout))
.await?
}
/// Reads a resource using this chat's input authority and lease lifetime.
pub(crate) async fn read_resource(
&self,
mut params: rmcp::model::ReadResourceRequestParams,
timeout: Option<Duration>,
) -> Result<rmcp::model::ReadResourceResult> {
if let Some(lease) = self.connection_sharing.server_lease() {
params.meta.get_or_insert_default().insert(
crate::connection_pool::LEASE_META_KEY.to_owned(),
serde_json::json!(lease.id),
);
}
self.with_lease_request(async {
if let Some(send_elicitation) = &self.shared_elicitation {
self.client
.read_resource_with_elicitation(params, timeout, Arc::clone(send_elicitation))
.await
} else {
self.client.read_resource(params, timeout).await
}
})
.await
}
pub(crate) async fn listed_catalog(&self) -> (Vec<ToolInfo>, Option<Arc<serde_json::Value>>) {
self.tool_catalog
.read(|catalog| (catalog.tools.to_vec(), catalog.meta))
.await
}
}

View File

@@ -0,0 +1,83 @@
//! Plugin attribution stays bounded without changing tool definitions or membership.
use super::*;
use pretty_assertions::assert_eq;
fn app_tool(description: &str) -> ToolInfo {
regular_mcp_tool_info_from_listed_tool(
"docs",
/*server_instructions*/ None,
ToolWithConnectorId {
tool: RmcpTool::new("search", description.to_string(), Arc::default()),
connector_id: None,
connector_name: None,
connector_description: None,
},
)
}
#[test]
fn provenance_preserves_short_descriptions_and_membership() {
for (description, names, expected_description) in [
("Search", vec![], "Search"),
("", vec!["Alpha"], "This tool is part of plugin `Alpha`."),
(
"Search",
vec!["Alpha"],
"Search. This tool is part of plugin `Alpha`.",
),
(
"Search!",
vec!["Alpha", "Beta"],
"Search! This tool is part of plugins `Alpha`, `Beta`.",
),
] {
let names = names.into_iter().map(str::to_string).collect::<Vec<_>>();
let mut tool = app_tool(description);
let mut expected = tool.clone();
expected.tool.description = Some(expected_description.to_string().into());
expected.plugin_display_names = names.clone();
add_plugin_provenance_to_tool(&mut tool, &names);
assert_eq!(tool, expected);
}
}
#[test]
fn provenance_bounds_aggregate_names_and_retains_all_associations() {
let exact_name =
"a".repeat(MAX_PLUGIN_PROVENANCE_BYTES - "This tool is part of plugin ``.".len());
for names in [
vec![exact_name.clone()],
vec![format!("{exact_name}a")],
vec!["界".repeat(MAX_PLUGIN_PROVENANCE_BYTES)],
(0..512)
.map(|index| format!("{index:03}{}", "界".repeat(61)))
.collect(),
] {
let mut tool = app_tool("Search.");
let original = tool.clone();
add_plugin_provenance_to_tool(&mut tool, &names);
let note = tool
.tool
.description
.as_deref()
.unwrap()
.strip_prefix("Search. ")
.unwrap();
assert!(note.len() <= MAX_PLUGIN_PROVENANCE_BYTES);
if names[0] == exact_name {
assert_eq!(note.len(), MAX_PLUGIN_PROVENANCE_BYTES);
} else if names.len() == 1 {
assert_eq!(note, "This tool is part of 1 plugin.");
} else {
let shown = note.matches('`').count() / 2;
assert!(shown > 0 && shown < names.len());
assert!(note.starts_with(&format!("This tool is part of plugins `{}`", names[0])));
assert!(note.ends_with(&format!(", and {} more.", names.len() - shown)));
}
let mut expected = original;
expected.tool.description = tool.tool.description.clone();
expected.plugin_display_names = names;
assert_eq!(tool, expected);
}
}

View File

@@ -0,0 +1,30 @@
//! Observe the latest startup attempt without polling it or initiating a retry.
use akode_protocol::mcp::McpServerConnectionStatus as Status;
use super::AsyncManagedClient;
use super::StartupOutcomeError;
impl AsyncManagedClient {
pub(crate) async fn connection_status(&self) -> Status {
if self.cancel_token.is_cancelled() {
return Status::Cancelled;
}
let outcome = self.client.peek().cloned();
match outcome {
Some(Ok(client)) => {
if client.client.is_closed().await {
Status::Failed
} else {
Status::Connected
}
}
Some(Err(error)) if error.is_authentication_required() => {
Status::AuthenticationRequired
}
Some(Err(StartupOutcomeError::Failed { .. })) => Status::Failed,
Some(Err(StartupOutcomeError::Cancelled)) => Status::Cancelled,
None => Status::Starting,
}
}
}

View File

@@ -0,0 +1,59 @@
//! Credential resolution must retain executor provenance when host fallback is considered.
use super::resolve_bearer_token;
use crate::server::McpCredentialPolicy;
use pretty_assertions::assert_eq;
#[test]
fn executor_credentials_reject_host_fallback_for_arbitrary_environment_names() {
for env_var in ["PATH", "MCP_UNPROTECTED_TEST_TOKEN"] {
let error = resolve_bearer_token("docs", Some(env_var), McpCredentialPolicy::ExecutorOnly)
.expect_err("executor credential names must never resolve on the host");
assert_eq!(
error.to_string(),
"MCP server 'docs' requires executor-side environment credential resolution; update the executor to a version that supports it (host fallback is disabled)",
);
}
}
#[test]
fn servers_without_environment_credentials_do_not_require_host_fallback() {
for policy in [
McpCredentialPolicy::ExecutorOnly,
McpCredentialPolicy::HostFallbackAllowed,
] {
assert_eq!(
resolve_bearer_token("docs", /*bearer_token_env_var*/ None, policy)
.expect("a server without an environment credential needs no resolution"),
None,
);
}
}
#[test]
fn configured_credentials_retain_host_environment_resolution() {
// PATH is nonsecret and read without changing the process environment.
let expected = match std::env::var("PATH") {
Ok(value) if value.is_empty() => {
Err("Environment variable PATH for MCP server 'docs' is empty".to_string())
}
Ok(value) => Ok(Some(value)),
Err(std::env::VarError::NotPresent) => {
Err("Environment variable PATH for MCP server 'docs' is not set".to_string())
}
Err(std::env::VarError::NotUnicode(_)) => Err(
"Environment variable PATH for MCP server 'docs' contains invalid Unicode".to_string(),
),
};
assert_eq!(
resolve_bearer_token(
"docs",
Some("PATH"),
McpCredentialPolicy::HostFallbackAllowed
)
.map_err(|error| error.to_string()),
expected,
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,60 @@
//! Read selected-server metadata from one published thread runtime.
use std::sync::Arc;
use super::McpRuntime;
use super::McpRuntimeContext;
use crate::McpConfig;
use crate::McpServerStatusSnapshot;
use crate::McpSnapshotDetail;
use crate::ResolvedMcpServer;
use crate::mcp::collect_mcp_server_status_snapshot_from_manager;
use crate::mcp::compute_auth_statuses;
use crate::mcp::effective_mcp_servers;
impl McpRuntime {
/// Reuses the selected connection and catalog without starting unrelated servers.
/// Configuration and metadata belong to the same captured runtime publication.
/// An expected registration excludes mismatched connections before discovery.
pub async fn server_status_snapshot(
&self,
server: &str,
detail: McpSnapshotDetail,
expected_registration: Option<&ResolvedMcpServer>,
runtime_context: &McpRuntimeContext,
) -> anyhow::Result<(Arc<McpConfig>, McpServerStatusSnapshot)> {
let current = self.current.load_full();
let runtime_context = runtime_context.clone().with_selected_environments(
Arc::clone(&current.environment_selections),
current.ready_environments.clone(),
);
let config = Arc::clone(
current
.config
.as_ref()
.ok_or_else(|| anyhow::anyhow!("MCP runtime is not configured"))?,
);
let mut servers = effective_mcp_servers(&config, current.auth.as_ref());
servers.retain(|name, _| {
name == server
&& expected_registration
.is_none_or(|expected| config.mcp_server_catalog.server(name) == Some(expected))
});
let auth_statuses = compute_auth_statuses(
servers.iter(),
config.mcp_oauth_credentials_store_mode,
config.auth_keyring_backend_kind,
current.auth.as_ref(),
&runtime_context,
)
.await;
let snapshot = collect_mcp_server_status_snapshot_from_manager(
&current.connections,
auth_statuses,
servers.into_keys().collect(),
detail,
)
.await;
Ok((config, snapshot))
}
}

View File

@@ -0,0 +1,168 @@
use super::*;
use crate::connection_manager::tests::create_ready_async_managed_client;
use crate::connection_pool::ConnectionSharing;
use crate::connection_pool::ConnectionSlot;
use crate::connection_pool::McpConnectionPool;
use crate::connection_pool::tests as fixture;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use std::sync::atomic::AtomicUsize;
use tokio::sync::Notify;
#[tokio::test]
async fn forced_refresh_replaces_pending_connection_without_interrupting_other_chats() {
let pool = McpConnectionPool::default();
let key = fixture::key(&fixture::context(), &fixture::config());
let starts = Arc::new(AtomicUsize::new(0));
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let launch = Arc::new(fixture::startup(
ConnectionSharing::Negotiated,
Arc::clone(&starts),
Arc::clone(&started),
Arc::clone(&release),
fixture::TestServer::default(),
));
let slot = Arc::new(ConnectionSlot::default());
let first = {
let pool = pool.clone();
let key = key.clone();
let slot = Arc::clone(&slot);
let launch = Arc::clone(&launch);
async move {
pool.connect(
slot,
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&*launch,
)
.await
}
.boxed()
.shared()
};
let mut poll_first = first.clone();
assert!(futures::poll!(&mut poll_first).is_pending());
let other = pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&*launch,
);
tokio::pin!(other);
assert!(futures::poll!(&mut other).is_pending());
started.notified().await;
let mut owner = create_ready_async_managed_client(Vec::new()).await;
owner.client = first;
owner.connection_slot = Some(slot);
let mut connections = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
connections.insert_test_client("test_server", owner);
let connections = Arc::new(connections);
let config = Arc::new(crate::mcp::tests::test_mcp_config(std::env::temp_dir()));
let runtime = McpRuntime::empty(/*prefix_mcp_tool_names*/ true);
runtime.current.store(Arc::new(PublishedMcpRuntime {
connections: Arc::clone(&connections),
config: Some(Arc::clone(&config)),
auth: None,
auth_manager: None,
auth_token: None,
auth_owner: None,
auth_generation: Arc::new(()),
plugins_available: false,
ready_selected_capability_roots: Vec::new(),
environment_selections: Arc::default(),
ready_environments: HashMap::new(),
cached_binding: Mutex::new(None),
}));
let input = McpRuntimeInput {
network_policy_metadata: None,
startup_policy: McpStartupPolicy::Eager,
config,
plugins_available: false,
ready_selected_capability_roots: Vec::new(),
mcp_servers: HashMap::new(),
submit_id: "refresh".to_string(),
tx_event: None,
startup_cancellation_token: CancellationToken::new(),
runtime_context: fixture::context(),
tool_catalog_cache: McpToolCatalogCache::default(),
client_mcp_extensions: ClientMcpExtensions::default(),
auth: None,
auth_manager: None,
elicitation_reviewer: None,
elicitation_lifecycle: None,
};
let binding = runtime.current_binding_for_call("test_server");
tokio::pin!(binding);
assert!(futures::poll!(&mut binding).is_pending());
runtime.reconnect_on_next_refresh();
runtime.replace(input).await;
let _replacement = tokio::time::timeout(
Duration::from_secs(1),
pool.connect(
Arc::default(),
key.clone(),
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&*launch,
),
)
.await
.expect("forced refresh must not wait for the old startup")
.unwrap();
release.notify_one();
let other = other.await.unwrap();
other
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
// A second refresh of the old owner must not evict the newer replacement.
connections.retire_shared_connections();
let _joined = pool
.connect(
Arc::default(),
key,
Arc::default(),
/*tool_catalog_cache_context*/ None,
CancellationToken::new(),
&*launch,
)
.await
.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 2);
let binding = binding.await.expect("binding from the old publication");
runtime.shutdown().await;
assert!(
binding
.list_resources("test_server", /*params*/ None)
.await
.is_err()
);
other
.call_tool(
"test".to_string(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
)
.await
.unwrap();
let transport = Arc::clone(&other.client);
let mut other_owner = create_ready_async_managed_client(Vec::new()).await;
other_owner.client = futures::future::ready(Ok(other)).boxed().shared();
other_owner.shutdown().await;
assert!(transport.is_closed().await);
drop(binding);
}

View File

@@ -0,0 +1,50 @@
//! Verify that the host's re-exec binary supports the sandbox metadata contract.
//! Cache completed probes per absolute executable path; never infer capability from its name or PATH.
use std::collections::HashMap;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::Duration;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_process::background_command;
use tokio::sync::Mutex;
use tokio::sync::OnceCell;
const PROBE_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
static PROBES: LazyLock<Mutex<HashMap<AbsolutePathBuf, Arc<OnceCell<bool>>>>> =
LazyLock::new(Mutex::default);
pub(crate) async fn supports_sandbox_state(executable: &AbsolutePathBuf) -> bool {
let probe = {
let mut probes = PROBES.lock().await;
Arc::clone(probes.entry(executable.clone()).or_default())
};
*probe
.get_or_init(|| async {
matches!(
tokio::time::timeout(PROBE_TIMEOUT, probe_sandbox_state(executable)).await,
Ok(Ok(true))
)
})
.await
}
/// Check that the binary accepts the sandbox-state option without launching a sandbox.
///
/// Plain `sandbox --help` can also succeed for unrelated binaries, including Rust test
/// harnesses. Put `--sandbox-state-json` before `--help` so those parsers reject the
/// unknown option. Codex handles help before interpreting the placeholder `{}` policy
/// or loading configuration; only its exit status matters, not the help text.
async fn probe_sandbox_state(executable: &AbsolutePathBuf) -> std::io::Result<bool> {
let status = tokio::process::Command::from(background_command(executable.as_os_str()))
.args(["sandbox", "--sandbox-state-json", "{}", "--help"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.status()
.await?;
Ok(status.success())
}

View File

@@ -0,0 +1,82 @@
//! Keep opaque sandbox policy separate from the launcher used to apply it.
//! Both state names carry identical values during migration; neither contains
//! executable discovery data or deprecation messages.
use akode_protocol::models::PermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Map;
use serde_json::Value;
use std::path::PathBuf;
/// Servers advertise this experimental capability to receive opaque sandbox state
/// in tool-call `_meta`, along with a local launcher when one is available.
pub const MCP_SANDBOX_STATE_CAPABILITY: &str = "codex/sandbox-state";
/// Deprecated capability and metadata spelling, retained as an identical alias.
/// Deprecation guidance is outside the opaque policy object.
pub const MCP_SANDBOX_STATE_META_CAPABILITY: &str = "codex/sandbox-state-meta";
/// Tool-call metadata describing a sandbox launcher on the MCP server's host.
pub const MCP_SANDBOX_LAUNCHER_META_KEY: &str = "codex/sandbox-launcher";
/// Opaque policy forwarded unchanged to `akode sandbox --sandbox-state-json`.
///
/// Servers advertise `codex/sandbox-state` (or its deprecated `-meta` alias) to
/// receive the same object under both state keys. Consumers must preserve unknown
/// fields, not deserialize and reconstruct the policy. Launcher information lives
/// separately under `codex/sandbox-launcher`; only its documented fields may be
/// interpreted. Long-lived subprocesses retain both their state and launcher and
/// must not be reused under different authority without a lifecycle decision.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SandboxState {
pub permission_profile: PermissionProfile,
pub codex_linux_sandbox_exe: Option<PathBuf>,
pub sandbox_cwd: PathUri,
#[serde(default)]
pub use_legacy_landlock: bool,
#[serde(default)]
pub use_mxc: bool,
}
/// The known launcher envelope is distinct from the opaque policy. Absence never
/// authorizes searching PATH or falling back to an unsandboxed process.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct SandboxLauncher {
/// A full CLI on the MCP server's host, supporting `sandbox --sandbox-state-json`.
/// Remote/HTTP servers and hosts without a verified, UTF-8 CLI path omit the envelope.
codex_executable: AbsolutePathBuf,
}
pub(crate) fn augment_metadata(
meta: &mut Option<Value>,
state: SandboxState,
executable: Option<AbsolutePathBuf>,
) -> anyhow::Result<()> {
let state = serde_json::to_value(state)?;
let launcher = executable
.map(|codex_executable| serde_json::to_value(SandboxLauncher { codex_executable }))
.transpose()?;
let Some(metadata) = meta
.get_or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()
else {
return Ok(());
};
metadata.insert(MCP_SANDBOX_STATE_CAPABILITY.to_owned(), state.clone());
metadata.insert(MCP_SANDBOX_STATE_META_CAPABILITY.to_owned(), state);
// Reserved launcher metadata must not survive from a previous/local call
// when this server's execution environment has no verified executable.
metadata.remove(MCP_SANDBOX_LAUNCHER_META_KEY);
if let Some(launcher) = launcher {
metadata.insert(MCP_SANDBOX_LAUNCHER_META_KEY.to_owned(), launcher);
}
Ok(())
}
#[cfg(test)]
#[path = "sandbox_metadata_tests.rs"]
mod tests;

View File

@@ -0,0 +1,62 @@
//! Preserve sandbox policy wire semantics while launcher metadata evolves separately.
use super::*;
use pretty_assertions::assert_eq;
use serde_json::Value;
#[test]
fn sandbox_state_serializes_skip_missing_entries_as_missing_path_behavior() {
let sandbox_cwd = PathUri::from_host_native_path(
std::env::current_dir().expect("current directory should be available"),
)
.expect("current directory should convert to a URI");
let sandbox_state = SandboxState {
permission_profile: PermissionProfile::workspace_write(),
codex_linux_sandbox_exe: None,
sandbox_cwd,
use_legacy_landlock: false,
use_mxc: false,
};
let serialized = serde_json::to_value(&sandbox_state).expect("serialize sandbox state");
let serialized_text = serde_json::to_string(&serialized).expect("serialize JSON text");
assert!(
!serialized_text.contains("generated_default_path"),
"MCP sandbox metadata must preserve FileSystemPath's stable wire variants"
);
assert!(
!serialized_text.contains("generated_default_special"),
"MCP sandbox metadata must preserve FileSystemPath's stable wire variants"
);
let entries = serialized
.pointer("/permissionProfile/file_system/entries")
.and_then(Value::as_array)
.expect("workspace-write profile should contain filesystem entries");
let skip_missing_entries = entries
.iter()
.filter(|entry| entry.get("missing_path_behavior").and_then(Value::as_str) == Some("skip"))
.collect::<Vec<_>>();
assert!(
!skip_missing_entries.is_empty(),
"skip-missing entries should be represented as optional missing_path_behavior"
);
assert!(
skip_missing_entries.iter().all(|entry| {
matches!(
entry.pointer("/path/type").and_then(Value::as_str),
Some("path" | "special")
)
}),
"skip-missing entries should use the stable path/special variants"
);
let deserialized: SandboxState =
serde_json::from_value(serialized.clone()).expect("deserialize legacy sandbox state");
assert_eq!(deserialized, sandbox_state);
let mut extended = serialized;
extended["futureField"] = serde_json::json!({"preservedByOpaqueConsumers": true});
let deserialized: SandboxState = serde_json::from_value(extended).expect("extended state");
assert_eq!(deserialized, sandbox_state);
}

View File

@@ -0,0 +1,485 @@
use std::collections::HashMap;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::Arc;
use crate::runtime::McpRuntimeContext;
use akode_config::AppToolApproval;
use akode_config::McpServerAuth;
use akode_config::McpServerConfig;
use akode_config::McpServerOAuthConfig;
use akode_config::McpServerTransportConfig;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::Environment;
use akode_protocol::mcp::ClientMcpExtensions;
use akode_rmcp_client::McpOAuthRefreshMode;
use akode_rmcp_client::McpProtocolMode;
use akode_rmcp_client::StoredOAuthCredentialSnapshot;
use akode_rmcp_client::StoredOAuthTokens;
use akode_utils_path_uri::PathUri;
use rmcp::model::ElicitationCapability;
use tracing::warn;
/// Authority to resolve environment-variable credentials, retained independently of
/// executor capabilities so a reconnect cannot promote guest configuration to host access.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum McpCredentialPolicy {
/// Host-configured servers retain local and legacy remote credential resolution.
HostFallbackAllowed,
/// Executor-discovered names must never be looked up in the host environment.
ExecutorOnly,
}
/// MCP server after runtime additions have been applied.
#[derive(Debug, Clone)]
pub struct EffectiveMcpServer {
config: McpServerConfig,
credential_policy: McpCredentialPolicy,
agent_plugin: bool,
requires_read_only_mcp_tools: bool,
}
impl EffectiveMcpServer {
/// Constructs an effective server from host-owned configuration.
pub fn from_host_config(config: McpServerConfig) -> Self {
Self::from_config_with_policy(config, McpCredentialPolicy::HostFallbackAllowed)
}
pub(crate) fn from_config_with_policy(
config: McpServerConfig,
credential_policy: McpCredentialPolicy,
) -> Self {
Self {
config,
credential_policy,
agent_plugin: false,
requires_read_only_mcp_tools: false,
}
}
pub(crate) fn credential_policy(&self) -> McpCredentialPolicy {
self.credential_policy
}
pub fn with_agent_plugin(mut self, agent_plugin: bool) -> Self {
self.agent_plugin = agent_plugin;
self
}
pub(crate) fn with_read_only_mcp_tools(mut self, requires_read_only_mcp_tools: bool) -> Self {
self.requires_read_only_mcp_tools = requires_read_only_mcp_tools;
self
}
pub(crate) fn requires_read_only_mcp_tools(&self) -> bool {
self.requires_read_only_mcp_tools
}
pub fn config(&self) -> &McpServerConfig {
&self.config
}
/// Checks whether Core can discover the protocol of a local stdio server.
///
/// Servers that selected the removed enterprise-managed authorization never start.
pub(crate) fn can_discover_local_stdio(&self) -> bool {
self.config.is_local_environment()
&& !matches!(self.config.auth, McpServerAuth::EmaAuth)
&& self
.stdio_protocol_mode(McpProtocolMode::DiscoverLocalStdio)
.is_some()
}
/// Returns the handshake a stdio launch would use, or `None` for HTTP or an invalid version.
pub(crate) fn stdio_protocol_mode(&self, mode: McpProtocolMode) -> Option<McpProtocolMode> {
let McpServerTransportConfig::Stdio { env, .. } = &self.config.transport else {
return None;
};
let version = env
.as_ref()
.and_then(|env| env.get("AKODE_MCP_PROTOCOL_VERSION"));
mode.stdio_mode(version.map(OsStr::new)).ok()
}
pub fn enabled(&self) -> bool {
self.config.enabled
}
pub fn required(&self) -> bool {
self.config.required
}
pub fn is_agent_plugin(&self) -> bool {
self.agent_plugin
}
}
pub(crate) fn has_explicit_http_authorization(config: &McpServerConfig) -> bool {
let McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
http_headers,
env_http_headers,
..
} = &config.transport
else {
return false;
};
if bearer_token_env_var.is_some()
|| env_http_headers
.as_ref()
.is_some_and(|headers| !headers.is_empty())
{
return false;
}
http_headers.as_ref().is_some_and(|headers| {
headers.iter().any(|(name, value)| {
name.eq_ignore_ascii_case("authorization")
&& !value.trim().is_empty()
&& value
.bytes()
.all(|byte| byte == b'\t' || (byte >= b' ' && byte != 0x7f))
})
})
}
/// Inputs that determine the identity of a live MCP connection.
///
/// Tool policy and presentation metadata intentionally do not appear here:
/// those belong to a publication and can change without reconnecting.
#[derive(Clone)]
pub(crate) struct McpServerConnectionIdentity {
auth: McpServerAuth,
pub(crate) credential_policy: McpCredentialPolicy,
transport: McpServerTransportConfig,
environment_id: String,
host_plugin_root: Option<PathUri>,
oauth_store: Option<(OAuthCredentialsStoreMode, AuthKeyringBackendKind)>,
oauth_refresh_mode: Option<McpOAuthRefreshMode>,
oauth_config: Option<McpServerOAuthConfig>,
oauth_credentials: Result<Option<StoredOAuthCredentialSnapshot>, String>,
pub(crate) oauth_store_was_contended: bool,
resolved_environment: Result<Option<Arc<Environment>>, String>,
local_stdio_fallback_cwd: Option<PathBuf>,
referenced_environment_variables: Vec<(String, Option<OsString>)>,
client_elicitation_capability: ElicitationCapability,
client_mcp_extensions: ClientMcpExtensions,
agent_plugin: bool,
requires_read_only_mcp_tools: bool,
}
impl McpServerConnectionIdentity {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
server_name: &str,
server: &EffectiveMcpServer,
host_plugin_root: Option<&PathUri>,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
oauth_refresh_mode: McpOAuthRefreshMode,
resolved_environment: &Result<Option<Arc<Environment>>, String>,
runtime_context: &McpRuntimeContext,
client_elicitation_capability: ElicitationCapability,
client_mcp_extensions: ClientMcpExtensions,
previous_identity: Option<&Self>,
) -> Self {
let config = server.config();
let valid_http_header_value = |value: &str| {
value
.bytes()
.all(|byte| byte == b'\t' || (byte >= b' ' && byte != 0x7f))
};
let stored_oauth_url = if !matches!(config.auth, McpServerAuth::EmaAuth)
&& (!matches!(config.auth, McpServerAuth::ChatGpt) || config.is_local_environment())
{
match &config.transport {
McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var: None,
http_headers,
env_http_headers,
http_headers_helper: _,
} if !http_headers.as_ref().is_some_and(|headers| {
headers.iter().any(|(name, value)| {
name.eq_ignore_ascii_case("authorization") && valid_http_header_value(value)
})
}) && !env_http_headers.as_ref().is_some_and(|headers| {
server.credential_policy() == McpCredentialPolicy::HostFallbackAllowed
&& headers.iter().any(|(name, env_var)| {
name.eq_ignore_ascii_case("authorization")
&& std::env::var(env_var).is_ok_and(|value| {
!value.trim().is_empty() && valid_http_header_value(&value)
})
})
}) =>
{
Some(url)
}
McpServerTransportConfig::StreamableHttp { .. }
| McpServerTransportConfig::Stdio { .. } => None,
}
} else {
None
};
let oauth_credentials = stored_oauth_url.map_or(Ok(None), |url| {
let credential_name = config.oauth_credential_name(server_name);
StoredOAuthCredentialSnapshot::for_runtime_refresh(
previous_identity.and_then(|previous_identity| {
previous_identity
.oauth_credentials
.as_ref()
.ok()
.and_then(Option::as_ref)
.filter(|_| {
previous_identity.oauth_store
== Some((store_mode, keyring_backend_kind))
})
}),
credential_name.as_ref(),
url,
store_mode,
keyring_backend_kind,
)
.map_err(|error| {
warn!(server_name, %error, "failed to read stored MCP OAuth credentials");
error.to_string()
})
});
let local_stdio_fallback_cwd = (config.is_local_environment()
&& matches!(
config.transport,
McpServerTransportConfig::Stdio { cwd: None, .. }
| McpServerTransportConfig::StreamableHttp {
http_headers_helper: Some(_),
..
}
))
.then(|| runtime_context.local_process_cwd());
let referenced_environment_variables = match server.credential_policy() {
McpCredentialPolicy::HostFallbackAllowed => referenced_environment_variables(config),
McpCredentialPolicy::ExecutorOnly => Vec::new(),
};
let oauth_store_was_contended = oauth_credentials
.as_ref()
.ok()
.and_then(Option::as_ref)
.is_some_and(StoredOAuthCredentialSnapshot::store_was_contended);
Self {
auth: config.auth.clone(),
credential_policy: server.credential_policy(),
transport: config.transport.clone(),
environment_id: config.environment_id.clone(),
host_plugin_root: host_plugin_root.cloned(),
oauth_store: stored_oauth_url
.is_some()
.then_some((store_mode, keyring_backend_kind)),
oauth_refresh_mode: stored_oauth_url.is_some().then_some(oauth_refresh_mode),
oauth_config: stored_oauth_url.and(config.oauth.clone()),
oauth_credentials,
oauth_store_was_contended,
resolved_environment: resolved_environment.clone(),
local_stdio_fallback_cwd,
referenced_environment_variables,
client_elicitation_capability,
client_mcp_extensions,
agent_plugin: server.is_agent_plugin(),
requires_read_only_mcp_tools: server.requires_read_only_mcp_tools(),
}
}
pub(crate) fn has_same_connection_config(&self, other: &Self) -> bool {
self.auth == other.auth
&& self.credential_policy == other.credential_policy
&& self.transport == other.transport
&& self.environment_id == other.environment_id
&& self.host_plugin_root == other.host_plugin_root
&& self.oauth_store == other.oauth_store
&& self.oauth_refresh_mode == other.oauth_refresh_mode
// Callback settings only affect a future login, not the live connection.
&& self.oauth_config.as_ref().and_then(|oauth| oauth.client_id.as_ref())
== other.oauth_config.as_ref().and_then(|oauth| oauth.client_id.as_ref())
&& self.oauth_config.as_ref().and_then(|oauth| oauth.client_secret.as_ref())
== other.oauth_config.as_ref().and_then(|oauth| oauth.client_secret.as_ref())
&& same_resolved_environment(&self.resolved_environment, &other.resolved_environment)
&& self.local_stdio_fallback_cwd == other.local_stdio_fallback_cwd
&& self.referenced_environment_variables == other.referenced_environment_variables
&& self.client_elicitation_capability == other.client_elicitation_capability
&& self.client_mcp_extensions == other.client_mcp_extensions
&& self.agent_plugin == other.agent_plugin
&& self.requires_read_only_mcp_tools == other.requires_read_only_mcp_tools
}
pub(crate) fn oauth_credentials(&self) -> Result<Option<&StoredOAuthTokens>, &String> {
self.oauth_credentials.as_ref().map(|credentials| {
credentials
.as_ref()
.map(StoredOAuthCredentialSnapshot::credentials)
})
}
pub(crate) fn oauth_credentials_changed(
&self,
server_name: &str,
config: &McpServerConfig,
) -> bool {
let Some((store_mode, keyring_backend_kind)) = self.oauth_store else {
return false;
};
let McpServerTransportConfig::StreamableHttp { url, .. } = &self.transport else {
return false;
};
let credential_name = config.oauth_credential_name(server_name);
let current_credentials = match self.oauth_credentials.as_ref() {
Ok(Some(credentials)) => credentials.reload(
credential_name.as_ref(),
url,
store_mode,
keyring_backend_kind,
),
Ok(None) | Err(_) => StoredOAuthCredentialSnapshot::for_runtime_refresh(
/*previous*/ None,
credential_name.as_ref(),
url,
store_mode,
keyring_backend_kind,
)
.map(|snapshot| snapshot.map(|snapshot| snapshot.credentials().clone())),
};
match current_credentials {
Ok(Some(current_credentials)) => {
self.oauth_credentials() != Ok(Some(&current_credentials))
}
Ok(None) => false,
Err(error) => {
warn!(server_name, %error, "failed to read stored MCP OAuth credentials");
false
}
}
}
}
impl PartialEq for McpServerConnectionIdentity {
fn eq(&self, other: &Self) -> bool {
self.has_same_connection_config(other) && self.oauth_credentials == other.oauth_credentials
}
}
fn same_resolved_environment(
left: &Result<Option<Arc<Environment>>, String>,
right: &Result<Option<Arc<Environment>>, String>,
) -> bool {
match (left, right) {
(Ok(Some(left)), Ok(Some(right))) => Arc::ptr_eq(left, right),
(Ok(None), Ok(None)) => true,
(Err(left), Err(right)) => left == right,
(Ok(_), Ok(_)) | (Ok(_), Err(_)) | (Err(_), Ok(_)) => false,
}
}
fn referenced_environment_variables(config: &McpServerConfig) -> Vec<(String, Option<OsString>)> {
let mut names = match &config.transport {
McpServerTransportConfig::Stdio { env_vars, .. } => env_vars
.iter()
.filter(|env_var| !env_var.is_remote_source())
.map(|env_var| env_var.name().to_string())
.collect::<Vec<_>>(),
McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
env_http_headers,
..
} => bearer_token_env_var
.iter()
.filter(|name| config.is_local_environment() || std::env::var_os(name).is_some())
.chain(env_http_headers.iter().flat_map(|headers| headers.values()))
.cloned()
.collect(),
};
names.sort();
names.dedup();
names
.into_iter()
.map(|name| {
let value = std::env::var_os(&name);
(name, value)
})
.collect()
}
/// Transport origin retained for metrics and diagnostics after server launch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum McpServerOrigin {
Stdio,
StreamableHttp(String),
}
impl McpServerOrigin {
pub fn as_str(&self) -> &str {
match self {
Self::Stdio => "stdio",
Self::StreamableHttp(origin) => origin,
}
}
fn from_transport(transport: &McpServerTransportConfig) -> Option<Self> {
match transport {
McpServerTransportConfig::StreamableHttp { url, .. } => {
let parsed = url::Url::parse(url).ok()?;
Some(Self::StreamableHttp(parsed.origin().ascii_serialization()))
}
McpServerTransportConfig::Stdio { .. } => Some(Self::Stdio),
}
}
}
/// Semantic metadata that must survive after the server is launched.
#[derive(Debug, Clone)]
pub(crate) struct McpServerMetadata {
pub environment_id: String,
pub pollutes_memory: bool,
pub origin: Option<McpServerOrigin>,
pub supports_parallel_tool_calls: bool,
pub default_tools_approval_mode: Option<AppToolApproval>,
pub tool_approval_modes: HashMap<String, AppToolApproval>,
}
impl McpServerMetadata {
pub fn tool_approval_mode(&self, tool_name: &str) -> AppToolApproval {
self.tool_approval_modes
.get(tool_name)
.copied()
.or(self.default_tools_approval_mode)
.unwrap_or_default()
}
}
impl From<&EffectiveMcpServer> for McpServerMetadata {
fn from(server: &EffectiveMcpServer) -> Self {
let config = server.config();
Self {
environment_id: config.environment_id.clone(),
pollutes_memory: true,
origin: McpServerOrigin::from_transport(&config.transport),
supports_parallel_tool_calls: config.supports_parallel_tool_calls,
default_tools_approval_mode: config.default_tools_approval_mode,
tool_approval_modes: config
.tools
.iter()
.filter_map(|(name, config)| {
config
.approval_mode
.map(|approval_mode| (name.clone(), approval_mode))
})
.collect(),
}
}
}
#[cfg(test)]
#[path = "server_tests.rs"]
mod tests;

View File

@@ -0,0 +1,175 @@
use super::EffectiveMcpServer;
use super::McpCredentialPolicy;
use super::McpServerConnectionIdentity;
use super::referenced_environment_variables;
use crate::McpProtocolMode;
use crate::runtime::McpRuntimeContext;
use crate::tool_catalog_cache::McpToolCatalogCache;
use akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use akode_config::McpServerConfig;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server_test_support::environment_manager_without_environments;
use akode_protocol::mcp::ClientMcpExtensions;
use akode_rmcp_client::McpOAuthRefreshMode;
use pretty_assertions::assert_eq;
use rmcp::model::ElicitationCapability;
use std::sync::Arc;
#[test]
fn remote_http_connections_track_host_headers_but_not_executor_bearer_tokens() {
let mut config: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp",
"environment_id": "executor-1",
"bearer_token_env_var": "NODE_REPL_AUTH_TOKEN",
"env_http_headers": {"X-Api-Key": "PATH"},
}))
.expect("remote MCP configuration should deserialize");
assert_eq!(
referenced_environment_variables(&config),
vec![("PATH".to_string(), std::env::var_os("PATH"))],
);
let remote_host_bearer: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp",
"environment_id": "executor-1",
"bearer_token_env_var": "PATH",
}))
.expect("host-resolved remote MCP configuration should deserialize");
assert_eq!(
referenced_environment_variables(&remote_host_bearer),
vec![("PATH".to_string(), std::env::var_os("PATH"))],
);
config.environment_id = DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string();
assert_eq!(
referenced_environment_variables(&config),
vec![
(
"NODE_REPL_AUTH_TOKEN".to_string(),
std::env::var_os("NODE_REPL_AUTH_TOKEN"),
),
("PATH".to_string(), std::env::var_os("PATH")),
],
);
}
fn runtime_context() -> McpRuntimeContext {
McpRuntimeContext::new(
Arc::new(environment_manager_without_environments()),
std::env::temp_dir(),
)
}
fn connection_identity(
server: &EffectiveMcpServer,
runtime_context: &McpRuntimeContext,
) -> McpServerConnectionIdentity {
McpServerConnectionIdentity::new(
"docs",
server,
/*host_plugin_root*/ None,
OAuthCredentialsStoreMode::default(),
AuthKeyringBackendKind::default(),
McpOAuthRefreshMode::Legacy,
&Ok(None),
runtime_context,
ElicitationCapability::default(),
ClientMcpExtensions::default(),
/*previous_identity*/ None,
)
}
fn explicit_authorization_server() -> EffectiveMcpServer {
EffectiveMcpServer::from_host_config(
serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp",
"environment_id": "executor-1",
"http_headers": {"Authorization": "Bearer test-canary"},
}))
.expect("remote MCP configuration should deserialize"),
)
}
#[test]
fn connection_identity_does_not_reuse_connections_across_credential_policies() {
let runtime_context = runtime_context();
let host_server = explicit_authorization_server();
let executor_server = EffectiveMcpServer::from_config_with_policy(
host_server.config().clone(),
McpCredentialPolicy::ExecutorOnly,
);
let host_identity = connection_identity(&host_server, &runtime_context);
let executor_identity = connection_identity(&executor_server, &runtime_context);
assert!(
host_identity
.has_same_connection_config(&connection_identity(&host_server, &runtime_context,))
);
assert!(
executor_identity
.has_same_connection_config(&connection_identity(&executor_server, &runtime_context,))
);
assert!(!host_identity.has_same_connection_config(&executor_identity));
assert!(!executor_identity.has_same_connection_config(&host_identity));
}
#[test]
fn executor_connection_identity_does_not_capture_host_environment_values() {
let runtime_context = runtime_context();
let host_server = EffectiveMcpServer::from_host_config(
serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp",
"environment_id": "executor-1",
"bearer_token_env_var": "PATH",
}))
.expect("remote MCP configuration should deserialize"),
);
let executor_server = EffectiveMcpServer::from_config_with_policy(
host_server.config().clone(),
McpCredentialPolicy::ExecutorOnly,
);
assert_eq!(
connection_identity(&host_server, &runtime_context).referenced_environment_variables,
vec![("PATH".to_string(), std::env::var_os("PATH"))],
);
assert_eq!(
connection_identity(&executor_server, &runtime_context).referenced_environment_variables,
Vec::new(),
);
}
#[test]
fn tool_catalog_cache_does_not_reuse_catalogs_across_credential_policies() {
let runtime_context = runtime_context();
let host_server = explicit_authorization_server();
let executor_server = EffectiveMcpServer::from_config_with_policy(
host_server.config().clone(),
McpCredentialPolicy::ExecutorOnly,
);
let host_identity = connection_identity(&host_server, &runtime_context);
let executor_identity = connection_identity(&executor_server, &runtime_context);
let cache = McpToolCatalogCache::default();
let context = |identity| {
cache
.context(
"docs",
host_server.config(),
&runtime_context,
/*resolved_environment*/ None,
(
&ElicitationCapability::default(),
&ClientMcpExtensions::default(),
),
Some((identity, McpProtocolMode::Legacy, false)),
)
.expect("explicit authorization permits catalog caching")
};
let host_context = context(&host_identity);
host_context.publish_if_newest(host_context.begin_fetch(), &[], /*meta*/ None);
assert_eq!(context(&host_identity).current_tools(), Some(Vec::new()));
assert_eq!(context(&executor_identity).current_tools(), None);
}

View File

@@ -0,0 +1,19 @@
---
source: akode-mcp/src/connection_manager_tests.rs
expression: "displays.join(\"\\n\\n\")"
---
MCP client for `npm:@scope/package.name` timed out after 30 seconds. Add or adjust `startup_timeout_sec` in your config.toml:
[mcp_servers."npm:@scope/package.name"]
startup_timeout_sec = XX
GitHub MCP does not support OAuth. Log in by adding a personal access token (https://github.com/settings/personal-access-tokens) to your environment and config.toml:
[mcp_servers."npm:@scope/package.name"]
bearer_token_env_var = AKODE_GITHUB_PERSONAL_ACCESS_TOKEN
MCP client for `server.name` timed out after 30 seconds. Add or adjust `startup_timeout_sec` in your config.toml:
[mcp_servers."server.name"]
startup_timeout_sec = XX
GitHub MCP does not support OAuth. Log in by adding a personal access token (https://github.com/settings/personal-access-tokens) to your environment and config.toml:
[mcp_servers."server.name"]
bearer_token_env_var = AKODE_GITHUB_PERSONAL_ACCESS_TOKEN

View File

@@ -0,0 +1,491 @@
use std::collections::BTreeMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::Weak;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use akode_config::McpServerAuth;
use akode_config::McpServerConfig;
use akode_config::McpServerTransportConfig;
use akode_exec_server::Environment;
use akode_protocol::mcp::ClientMcpExtensions;
use akode_rmcp_client::ToolListRevision;
use lru::LruCache;
use rmcp::model::ElicitationCapability;
use sha1::Digest;
use sha1::Sha1;
use tokio::time::Instant;
use crate::McpProtocolMode;
use crate::McpRuntimeContext;
use crate::ToolInfo;
use crate::server::McpCredentialPolicy;
use crate::server::McpServerConnectionIdentity;
use crate::server::has_explicit_http_authorization;
const TOOL_CATALOG_CACHE_CAPACITY: usize = 32;
const TOOL_CATALOG_CACHE_TTL: Duration = Duration::from_secs(30 * 60);
/// Process-scoped cache of recent reusable tool definitions for MCP servers.
#[derive(Clone)]
pub struct McpToolCatalogCache {
entries: Arc<Mutex<LruCache<ToolCatalogIdentity, Arc<ToolCatalogCacheEntry>>>>,
}
impl Default for McpToolCatalogCache {
fn default() -> Self {
Self {
entries: Arc::new(Mutex::new(LruCache::new(
NonZeroUsize::new(TOOL_CATALOG_CACHE_CAPACITY).unwrap_or(NonZeroUsize::MIN),
))),
}
}
}
struct ToolCatalogCacheEntry {
state: Mutex<ToolCatalogCacheState>,
next_fetch_generation: AtomicU64,
}
#[derive(Default)]
struct ToolCatalogCacheState {
snapshot: Option<ToolCatalogSnapshot>,
optional_startup_deadline: Option<OptionalStartupDeadline>,
last_catalog_generation: u64,
last_modern_discovery_generation: u64,
disabled_by_server: bool,
}
struct OptionalStartupDeadline {
grace: Duration,
deadline: Instant,
}
struct ToolCatalogSnapshot {
tools: Vec<ToolInfo>,
meta: Option<Arc<serde_json::Value>>,
published_at: Instant,
tool_list_revision: Option<ToolListRevision>,
}
#[derive(Clone)]
pub(crate) struct McpToolCatalogCacheContext {
pub(crate) track_tool_list_changes: bool,
pub(crate) before_stdio_discovery: bool,
entry: Arc<ToolCatalogCacheEntry>,
}
pub(crate) struct McpToolCatalogFetchTicket {
pub(crate) tool_list_revision: Option<ToolListRevision>,
generation: u64,
}
impl McpToolCatalogCache {
pub(crate) fn context(
&self,
server_name: &str,
config: &McpServerConfig,
runtime_context: &McpRuntimeContext,
resolved_environment: Option<&Arc<Environment>>,
client_context: (&ElicitationCapability, &ClientMcpExtensions),
connection_identity: Option<(&McpServerConnectionIdentity, McpProtocolMode, bool)>,
) -> Option<McpToolCatalogCacheContext> {
let identity = ToolCatalogIdentity::new(
server_name,
config,
runtime_context,
resolved_environment,
client_context,
connection_identity,
)?;
let entry = lock_unpoisoned(&self.entries)
.get_or_insert(identity, || Arc::new(ToolCatalogCacheEntry::default()))
.clone();
Some(McpToolCatalogCacheContext {
entry,
track_tool_list_changes: false,
before_stdio_discovery: false,
})
}
}
impl Default for ToolCatalogCacheEntry {
fn default() -> Self {
Self {
state: Mutex::new(ToolCatalogCacheState::default()),
next_fetch_generation: AtomicU64::new(0),
}
}
}
impl McpToolCatalogCacheContext {
fn accepts_snapshot(
&self,
state: &ToolCatalogCacheState,
snapshot: &ToolCatalogSnapshot,
) -> bool {
if self.before_stdio_discovery
&& state.last_modern_discovery_generation > state.last_catalog_generation
{
return false;
}
// Enabling refresh must not reuse a catalog published without notification tracking.
snapshot
.tool_list_revision
.as_ref()
.map_or(!self.track_tool_list_changes, |revision| {
revision.current() == 0
})
}
pub(crate) fn has_tools(&self) -> bool {
self.current_revision_if(|_| true).is_some()
}
/// Checks eligibility and reads the revision under one lock without cloning tools.
/// The predicate borrows the current catalog while the cache entry is locked.
pub(crate) fn current_revision_if(
&self,
accepts_tools: impl FnOnce(&[ToolInfo]) -> bool,
) -> Option<u64> {
let state = lock_unpoisoned(&self.entry.state);
let snapshot = state.snapshot.as_ref()?;
(!state.disabled_by_server
&& self.accepts_snapshot(&state, snapshot)
&& !snapshot.tools.is_empty()
&& snapshot.published_at.elapsed() <= TOOL_CATALOG_CACHE_TTL
&& accepts_tools(&snapshot.tools))
.then_some(state.last_catalog_generation)
}
pub(crate) fn optional_startup_deadline(
&self,
default_deadline: Instant,
startup_grace: Duration,
) -> Instant {
let mut state = lock_unpoisoned(&self.entry.state);
if state.disabled_by_server
|| state.snapshot.as_ref().is_some_and(|snapshot| {
self.accepts_snapshot(&state, snapshot)
&& snapshot.published_at.elapsed() <= TOOL_CATALOG_CACHE_TTL
})
{
return default_deadline;
}
let cached_deadline =
state
.optional_startup_deadline
.get_or_insert(OptionalStartupDeadline {
grace: startup_grace,
deadline: default_deadline,
});
if cached_deadline.grace != startup_grace {
*cached_deadline = OptionalStartupDeadline {
grace: startup_grace,
deadline: default_deadline,
};
}
cached_deadline.deadline
}
#[cfg(test)]
pub(crate) fn current_tools(&self) -> Option<Vec<ToolInfo>> {
self.current_tools_or(/*fallback*/ None)
}
/// Prefers the current catalog, retaining a capture's fallback across expiry but not opt-out.
pub(crate) fn current_tools_or(
&self,
fallback: Option<Vec<ToolInfo>>,
) -> Option<Vec<ToolInfo>> {
self.current_catalog_or(fallback.map(|tools| (tools, None)))
.map(|(tools, _)| tools)
}
pub(crate) fn current_catalog_or(
&self,
fallback: Option<(Vec<ToolInfo>, Option<Arc<serde_json::Value>>)>,
) -> Option<(Vec<ToolInfo>, Option<Arc<serde_json::Value>>)> {
let state = lock_unpoisoned(&self.entry.state);
if state.disabled_by_server
|| state
.snapshot
.as_ref()
.is_some_and(|snapshot| !self.accepts_snapshot(&state, snapshot))
{
return None;
}
state
.snapshot
.as_ref()
.filter(|snapshot| snapshot.published_at.elapsed() <= TOOL_CATALOG_CACHE_TTL)
.map(|snapshot| (snapshot.tools.clone(), snapshot.meta.clone()))
.or(fallback)
}
pub(crate) fn begin_fetch(&self) -> McpToolCatalogFetchTicket {
McpToolCatalogFetchTicket {
tool_list_revision: None,
generation: self
.entry
.next_fetch_generation
.fetch_add(1, Ordering::Relaxed)
+ 1,
}
}
pub(crate) fn disable(&self) {
let mut state = lock_unpoisoned(&self.entry.state);
state.disabled_by_server = true;
state.snapshot = None;
}
/// A modern handshake rules out older legacy catalogs for discovery. Clients forced to use
/// the legacy protocol can still use those catalogs, including legacy fetches in flight.
pub(crate) fn record_modern_stdio_discovery(&self, ticket: &McpToolCatalogFetchTicket) {
let mut state = lock_unpoisoned(&self.entry.state);
if ticket.generation
> state
.last_catalog_generation
.max(state.last_modern_discovery_generation)
{
state.last_modern_discovery_generation = ticket.generation;
state.optional_startup_deadline = None;
}
}
pub(crate) fn publish_if_newest(
&self,
ticket: McpToolCatalogFetchTicket,
tools: &[ToolInfo],
meta: Option<Arc<serde_json::Value>>,
) {
let mut state = lock_unpoisoned(&self.entry.state);
if state.disabled_by_server || ticket.generation <= state.last_catalog_generation {
return;
}
state.last_catalog_generation = ticket.generation;
state.optional_startup_deadline = None;
let mut tools = tools.to_vec();
for tool in &mut tools {
// Tool annotations affect approval and parallelism decisions, so only the live
// connection may supply them.
tool.tool.annotations = None;
}
state.snapshot = Some(ToolCatalogSnapshot {
tools,
meta,
published_at: Instant::now(),
tool_list_revision: ticket.tool_list_revision,
});
}
}
fn lock_unpoisoned<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
struct ToolCatalogIdentity {
server_name: String,
transport: ToolCatalogTransportIdentity,
environment: Option<Weak<Environment>>,
local_stdio_fallback_cwd: Option<PathBuf>,
}
impl PartialEq for ToolCatalogIdentity {
fn eq(&self, other: &Self) -> bool {
self.server_name == other.server_name
&& self.transport == other.transport
&& self.local_stdio_fallback_cwd == other.local_stdio_fallback_cwd
&& match (&self.environment, &other.environment) {
(Some(environment), Some(other)) => Weak::ptr_eq(environment, other),
(None, None) => true,
_ => false,
}
}
}
impl Eq for ToolCatalogIdentity {}
impl Hash for ToolCatalogIdentity {
fn hash<H: Hasher>(&self, state: &mut H) {
self.server_name.hash(state);
self.transport.hash(state);
self.local_stdio_fallback_cwd.hash(state);
self.environment
.as_ref()
.map(|environment| Weak::as_ptr(environment) as usize)
.hash(state);
}
}
impl ToolCatalogIdentity {
fn new(
server_name: &str,
config: &McpServerConfig,
runtime_context: &McpRuntimeContext,
environment: Option<&Arc<Environment>>,
client_context: (&ElicitationCapability, &ClientMcpExtensions),
connection_identity: Option<(&McpServerConnectionIdentity, McpProtocolMode, bool)>,
) -> Option<Self> {
let transport =
ToolCatalogTransportIdentity::new(config, client_context, connection_identity)?;
Some(Self {
server_name: server_name.to_string(),
transport,
environment: environment.map(Arc::downgrade),
local_stdio_fallback_cwd: matches!(
&config.transport,
McpServerTransportConfig::Stdio { cwd: None, .. }
)
.then(|| runtime_context.local_process_cwd()),
})
}
}
#[derive(PartialEq, Eq, Hash)]
enum ToolCatalogTransportIdentity {
Stdio { fingerprint: [u8; 20] },
StreamableHttp { fingerprint: [u8; 20] },
}
impl ToolCatalogTransportIdentity {
fn new(
config: &McpServerConfig,
client_context: (&ElicitationCapability, &ClientMcpExtensions),
connection_identity: Option<(&McpServerConnectionIdentity, McpProtocolMode, bool)>,
) -> Option<Self> {
let (client_elicitation_capability, client_mcp_extensions) = client_context;
if let McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
http_headers_helper,
} = &config.transport
{
// Helper output is a dynamic credential identity that cannot be represented by config.
if http_headers_helper.is_some() {
return None;
}
let (connection_identity, protocol_mode, agent_plugin) = connection_identity?;
if config.oauth.is_some()
|| config.scopes.is_some()
|| config.oauth_resource.is_some()
|| (matches!(config.auth, McpServerAuth::ChatGpt)
&& !has_explicit_http_authorization(config))
|| (!has_explicit_http_authorization(config)
&& connection_identity.oauth_credentials().ok()?.is_some())
{
return None;
}
let mut hasher = Sha1::new();
hasher.update(match connection_identity.credential_policy {
McpCredentialPolicy::HostFallbackAllowed => b"host-fallback".as_slice(),
McpCredentialPolicy::ExecutorOnly => b"executor-only".as_slice(),
});
hasher.update(
serde_json::to_vec(&(
url,
bearer_token_env_var,
http_headers
.as_ref()
.map(|headers| headers.iter().collect::<BTreeMap<_, _>>()),
env_http_headers
.as_ref()
.map(|headers| headers.iter().collect::<BTreeMap<_, _>>()),
&config.auth,
&config.environment_id,
agent_plugin,
protocol_mode.preferred_protocol_version().as_str(),
client_elicitation_capability,
client_mcp_extensions.iter().collect::<BTreeMap<_, _>>(),
))
.ok()?,
);
let mut env_vars = bearer_token_env_var
.iter()
.chain(env_http_headers.iter().flat_map(|headers| headers.values()))
.collect::<Vec<_>>();
env_vars.sort_unstable();
env_vars.dedup();
for name in env_vars {
hasher.update(name.as_bytes());
if connection_identity.credential_policy == McpCredentialPolicy::HostFallbackAllowed
{
let mut value_hasher = DefaultHasher::new();
std::env::var_os(name).hash(&mut value_hasher);
hasher.update(value_hasher.finish().to_le_bytes());
}
}
return Some(Self::StreamableHttp {
fingerprint: hasher.finalize().into(),
});
}
let McpServerTransportConfig::Stdio {
command,
args,
env,
env_vars,
cwd,
} = &config.transport
else {
return None;
};
// An unmarked helper can expose different tools after a legacy fallback.
if matches!(
connection_identity,
Some((_, McpProtocolMode::DiscoverLocalStdio, _))
) {
return None;
}
if env_vars
.iter()
.any(akode_config::McpServerEnvVar::is_remote_source)
{
return None;
}
let mut hasher = Sha1::new();
let env = env.as_ref().map(|env| {
env.iter()
.map(|(key, value)| (key.as_str(), value.as_str()))
.collect::<BTreeMap<_, _>>()
});
hasher.update(
serde_json::to_vec(&(
command,
args,
env,
env_vars,
cwd,
&config.environment_id,
connection_identity.map(|(_, mode, _)| mode.preferred_protocol_version()),
client_elicitation_capability,
client_mcp_extensions.iter().collect::<BTreeMap<_, _>>(),
))
.ok()?,
);
for env_var in env_vars {
hasher.update(env_var.name().as_bytes());
let mut value_hasher = DefaultHasher::new();
std::env::var_os(env_var.name()).hash(&mut value_hasher);
hasher.update(value_hasher.finish().to_le_bytes());
}
Some(Self::Stdio {
fingerprint: hasher.finalize().into(),
})
}
}

View File

@@ -0,0 +1,70 @@
//! Host-provided metadata for a specific tool on a specific MCP registration.
use std::sync::Arc;
use crate::McpServerSource;
use crate::PreparedMcpCall;
use anyhow::Context;
use akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use akode_config::McpServerTransportConfig;
use akode_protocol::ThreadId;
use futures::future::BoxFuture;
use serde_json::Value;
/// Supplies one MCP request metadata value for a live tool invocation. An error
/// fails the tool call before dispatch and is reported to the tool caller.
pub trait McpToolRequestMetaProvider: Send + Sync {
fn value<'a>(
&'a self,
thread_id: ThreadId,
turn_id: &'a str,
call_id: &'a str,
) -> BoxFuture<'a, anyhow::Result<Value>>;
}
/// Install in thread extension data to add a private `_meta` field to one remote
/// tool on the selected local MCP registration. Bind the source and full transport
/// supplied by the trusted host, including routing headers for a proxied endpoint.
pub struct McpToolRequestMetaHook {
pub server_name: String,
pub source: McpServerSource,
pub transport: McpServerTransportConfig,
pub tool_name: String,
/// A metadata key owned by the provider. Existing metadata cannot be overwritten.
pub key: String,
pub provider: Arc<dyn McpToolRequestMetaProvider>,
}
impl McpToolRequestMetaHook {
/// Adds the provider’s value only when the immutable call matches the selected registration.
pub async fn apply(
&self,
call: &PreparedMcpCall,
thread_id: ThreadId,
turn_id: &str,
call_id: &str,
meta: &mut Option<Value>,
) -> anyhow::Result<()> {
if call.server_name() == self.server_name
&& call.tool_info().tool.name.as_ref() == self.tool_name
&& call.server_environment_id() == DEFAULT_MCP_SERVER_ENVIRONMENT_ID
&& let Some(server) = call.config().mcp_server_catalog.server(call.server_name())
&& server.config().is_local_environment()
&& server.source() == &self.source
&& server.config().transport == self.transport
{
let meta = meta
.as_mut()
.and_then(Value::as_object_mut)
.context("missing MCP request metadata object")?;
anyhow::ensure!(
!meta.contains_key(&self.key),
"MCP request metadata already contains {}",
self.key
);
let value = self.provider.value(thread_id, turn_id, call_id).await?;
meta.insert(self.key.clone(), value);
}
Ok(())
}
}

View File

@@ -0,0 +1,315 @@
//! MCP tool metadata, filtering, and name normalization.
//!
//! Raw MCP tool identities must be preserved for protocol calls, while
//! model-visible tool names must be sanitized, deduplicated, and kept within API
//! limits. This module owns that translation as well as the shared [`ToolInfo`]
//! type.
use std::collections::HashMap;
use std::collections::HashSet;
use akode_config::McpServerConfig;
use akode_protocol::ToolName;
use rmcp::model::Tool;
use serde::Deserialize;
use serde::Serialize;
use sha1::Digest;
use sha1::Sha1;
use tracing::warn;
use crate::mcp::sanitize_responses_api_tool_name;
const LEGACY_MCP_TOOL_NAME_PREFIX: &str = "mcp__";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolInfo {
/// Raw MCP server name used for routing the tool call.
pub server_name: String,
/// Whether calls routed to this server may run in parallel.
#[serde(default)]
pub supports_parallel_tool_calls: bool,
/// MCP server origin used for telemetry and diagnostics, when known.
#[serde(default)]
pub server_origin: Option<String>,
/// Model-visible tool name used in Responses API tool declarations.
#[serde(rename = "tool_name", alias = "callable_name")]
pub callable_name: String,
/// Model-visible namespace used for deferred tool loading.
#[serde(rename = "tool_namespace", alias = "callable_namespace")]
pub callable_namespace: String,
/// Model-visible namespace description.
// Keep the old serialized field name readable for cached ToolInfo values.
#[serde(default, alias = "connector_description")]
pub namespace_description: Option<String>,
/// Raw MCP tool definition; `tool.name` is sent back to the MCP server.
pub tool: Tool,
#[serde(default)]
pub plugin_display_names: Vec<String>,
}
impl ToolInfo {
/// The model-facing error when this advertised tool cannot be called.
pub fn unavailable_to_model_error(&self) -> anyhow::Error {
anyhow::anyhow!(
"MCP tool `{}/{}` is not available to the model",
self.server_name,
self.tool.name
)
}
pub fn canonical_tool_name(&self) -> ToolName {
ToolName::namespaced(self.callable_namespace.clone(), self.callable_name.clone())
}
}
/// A tool is allowed to be used if both are true:
/// 1. enabled is None (no allowlist is set) or the tool is explicitly enabled.
/// 2. The tool is not explicitly disabled.
#[derive(Default, Clone)]
pub(crate) struct ToolFilter {
pub(crate) enabled: Option<HashSet<String>>,
pub(crate) disabled: HashSet<String>,
}
impl ToolFilter {
pub(crate) fn from_config(cfg: &McpServerConfig) -> Self {
let enabled = cfg
.enabled_tools
.as_ref()
.map(|tools| tools.iter().cloned().collect::<HashSet<_>>());
let disabled = cfg
.disabled_tools
.as_ref()
.map(|tools| tools.iter().cloned().collect::<HashSet<_>>())
.unwrap_or_default();
Self { enabled, disabled }
}
pub(crate) fn allows(&self, tool_name: &str) -> bool {
if let Some(enabled) = &self.enabled
&& !enabled.contains(tool_name)
{
return false;
}
!self.disabled.contains(tool_name)
}
}
pub(crate) fn filter_tools(tools: Vec<ToolInfo>, filter: &ToolFilter) -> Vec<ToolInfo> {
tools
.into_iter()
.filter(|tool| filter.allows(&tool.tool.name))
.collect()
}
/// Returns MCP tools with model-visible names normalized.
///
/// Raw MCP server/tool names are kept on each [`ToolInfo`] for protocol calls, while
/// `callable_namespace` / `callable_name` are sanitized and, when necessary, hashed so
/// every model-visible name is unique and <= 128 bytes.
///
/// When `prefix_mcp_tool_names` is true, the historical `mcp__` namespace
/// prefix is added except for tools from `non_prefixed_mcp_tool_servers`.
pub(crate) fn normalize_tools_for_model_with_prefix<I>(
tools: I,
prefix_mcp_tool_names: bool,
non_prefixed_mcp_tool_servers: &[String],
) -> Vec<ToolInfo>
where
I: IntoIterator<Item = ToolInfo>,
{
let mut seen_raw_names = HashSet::new();
let mut candidates = Vec::new();
for tool in tools {
// The trailing separator keeps hashed names stable across catalog versions.
let raw_namespace_identity =
format!("{}\0{}\0", tool.server_name, tool.callable_namespace);
let raw_tool_identity = format!(
"{}\0{}\0{}",
raw_namespace_identity, tool.callable_name, tool.tool.name
);
if !seen_raw_names.insert(raw_tool_identity.clone()) {
warn!("skipping duplicated tool {}", tool.tool.name);
continue;
}
let callable_namespace = callable_namespace_with_prefix(
&sanitize_responses_api_tool_name(&tool.callable_namespace),
prefix_mcp_tool_names && !non_prefixed_mcp_tool_servers.contains(&tool.server_name),
);
candidates.push(CallableToolCandidate {
callable_namespace,
callable_name: sanitize_responses_api_tool_name(&tool.callable_name),
raw_namespace_identity,
raw_tool_identity,
tool,
});
}
let mut namespace_identities_by_base = HashMap::<String, HashSet<String>>::new();
for candidate in &candidates {
namespace_identities_by_base
.entry(candidate.callable_namespace.clone())
.or_default()
.insert(candidate.raw_namespace_identity.clone());
}
let colliding_namespaces = namespace_identities_by_base
.into_iter()
.filter_map(|(namespace, identities)| (identities.len() > 1).then_some(namespace))
.collect::<HashSet<_>>();
for candidate in &mut candidates {
if colliding_namespaces.contains(&candidate.callable_namespace) {
candidate.callable_namespace = append_namespace_hash_suffix(
&candidate.callable_namespace,
&candidate.raw_namespace_identity,
);
}
}
let mut tool_identities_by_base = HashMap::<(String, String), HashSet<String>>::new();
for candidate in &candidates {
tool_identities_by_base
.entry((
candidate.callable_namespace.clone(),
candidate.callable_name.clone(),
))
.or_default()
.insert(candidate.raw_tool_identity.clone());
}
let colliding_tools = tool_identities_by_base
.into_iter()
.filter_map(|(key, identities)| (identities.len() > 1).then_some(key))
.collect::<HashSet<_>>();
for candidate in &mut candidates {
if colliding_tools.contains(&(
candidate.callable_namespace.clone(),
candidate.callable_name.clone(),
)) {
candidate.callable_name =
append_hash_suffix(&candidate.callable_name, &candidate.raw_tool_identity);
}
}
candidates.sort_by(|left, right| left.raw_tool_identity.cmp(&right.raw_tool_identity));
let mut used_names = HashSet::new();
let mut model_tools = Vec::new();
for mut candidate in candidates {
let (callable_namespace, callable_name) = unique_callable_parts(
&candidate.callable_namespace,
&candidate.callable_name,
&candidate.raw_tool_identity,
&mut used_names,
MCP_TOOL_NAME_DELIMITER.len(),
);
candidate.tool.callable_namespace = callable_namespace;
candidate.tool.callable_name = callable_name;
model_tools.push(candidate.tool);
}
model_tools
}
#[derive(Debug)]
struct CallableToolCandidate {
tool: ToolInfo,
raw_namespace_identity: String,
raw_tool_identity: String,
callable_namespace: String,
callable_name: String,
}
const MCP_TOOL_NAME_DELIMITER: &str = "__";
const MAX_TOOL_NAME_LENGTH: usize = 128;
const CALLABLE_NAME_HASH_LEN: usize = 12;
fn callable_namespace_with_prefix(namespace: &str, prefix_mcp_tool_names: bool) -> String {
if !prefix_mcp_tool_names || namespace.starts_with(LEGACY_MCP_TOOL_NAME_PREFIX) {
namespace.to_string()
} else {
format!("{LEGACY_MCP_TOOL_NAME_PREFIX}{namespace}")
}
}
fn sha1_hex(s: &str) -> String {
let mut hasher = Sha1::new();
hasher.update(s.as_bytes());
let sha1 = hasher.finalize();
format!("{sha1:x}")
}
fn callable_name_hash_suffix(raw_identity: &str) -> String {
let hash = sha1_hex(raw_identity);
format!("_{}", &hash[..CALLABLE_NAME_HASH_LEN])
}
fn append_hash_suffix(value: &str, raw_identity: &str) -> String {
format!("{value}{}", callable_name_hash_suffix(raw_identity))
}
fn append_namespace_hash_suffix(namespace: &str, raw_identity: &str) -> String {
if let Some(namespace) = namespace.strip_suffix(MCP_TOOL_NAME_DELIMITER) {
format!(
"{}{}{}",
namespace,
callable_name_hash_suffix(raw_identity),
MCP_TOOL_NAME_DELIMITER
)
} else {
append_hash_suffix(namespace, raw_identity)
}
}
fn truncate_name(value: &str, max_len: usize) -> String {
value.chars().take(max_len).collect()
}
fn fit_callable_parts_with_hash(
namespace: &str,
tool_name: &str,
raw_identity: &str,
reserved_len: usize,
) -> (String, String) {
let suffix = callable_name_hash_suffix(raw_identity);
let max_tool_len = MAX_TOOL_NAME_LENGTH.saturating_sub(namespace.len() + reserved_len);
if max_tool_len >= suffix.len() {
let prefix_len = max_tool_len - suffix.len();
return (
namespace.to_string(),
format!("{}{}", truncate_name(tool_name, prefix_len), suffix),
);
}
let max_namespace_len = MAX_TOOL_NAME_LENGTH.saturating_sub(suffix.len() + reserved_len);
(truncate_name(namespace, max_namespace_len), suffix)
}
fn unique_callable_parts(
namespace: &str,
tool_name: &str,
raw_identity: &str,
used_names: &mut HashSet<String>,
reserved_len: usize,
) -> (String, String) {
let model_name = format!("{namespace}{tool_name}");
if model_name.len() + reserved_len <= MAX_TOOL_NAME_LENGTH && used_names.insert(model_name) {
return (namespace.to_string(), tool_name.to_string());
}
let mut attempt = 0_u32;
loop {
let hash_input = if attempt == 0 {
raw_identity.to_string()
} else {
format!("{raw_identity}\0{attempt}")
};
let (namespace, tool_name) =
fit_callable_parts_with_hash(namespace, tool_name, &hash_input, reserved_len);
let model_name = format!("{namespace}{tool_name}");
if used_names.insert(model_name) {
return (namespace, tool_name);
}
attempt = attempt.saturating_add(1);
}
}