use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use serde_json::{Value, json};
use tempfile::tempdir;
use trusty_code::mcp::{McpToolSet, register_configured_tools};
use trusty_code::tools::registry::ToolRegistry;
use trusty_code::tools::traits::{ToolExecutor, ToolResult};
fn fixture_binary() -> String {
static BUILT: OnceLock<String> = OnceLock::new();
BUILT.get_or_init(build_fixture_binary).clone()
}
fn fixture_profile(exe: &Path) -> Result<(PathBuf, String), String> {
let parent = exe.parent();
fn dir_name(p: Option<&Path>) -> Option<&str> {
p.and_then(Path::file_name).and_then(|n| n.to_str())
}
let profile_dir = match dir_name(parent) {
Some("deps") => parent.and_then(Path::parent),
Some("out") => {
let hash = parent.and_then(Path::parent);
let krate = hash.and_then(Path::parent);
let build = krate.and_then(Path::parent);
if dir_name(build) == Some("build") {
build.and_then(Path::parent)
} else {
None
}
}
_ => None,
};
let profile_dir = profile_dir
.filter(|d| d.parent().is_some())
.ok_or_else(|| {
format!(
"unrecognised cargo test-binary layout: {} (expected \
`<profile>/deps/<bin>` or `<profile>/build/<crate>/<hash>/out/<bin>`)",
exe.display()
)
})?;
let profile = match profile_dir.file_name().and_then(|n| n.to_str()) {
Some("debug") => "dev".to_owned(),
Some(other) => other.to_owned(),
None => return Err(format!("no profile directory in {}", exe.display())),
};
Ok((profile_dir.to_path_buf(), profile))
}
fn build_fixture_binary() -> String {
let exe = std::env::current_exe().expect("the test binary has a path");
let (profile_dir, profile) = fixture_profile(&exe).unwrap_or_else(|e| panic!("{e}"));
let target_dir = profile_dir
.parent()
.expect("a profile directory has a parent");
let output = std::process::Command::new(env!("CARGO"))
.args(["build", "--example", "mcp_fixture_server", "--profile"])
.arg(&profile)
.arg("--manifest-path")
.arg(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml"))
.arg("--target-dir")
.arg(target_dir)
.output()
.expect("`cargo build --example mcp_fixture_server` must run");
assert!(
output.status.success(),
"rebuilding the fixture example failed ({}):\n{}",
output.status,
String::from_utf8_lossy(&output.stderr),
);
let path = profile_dir.join("examples").join(format!(
"mcp_fixture_server{}",
std::env::consts::EXE_SUFFIX
));
assert!(
path.exists(),
"the fixture example is not built at {} even after `cargo build --example`",
path.display(),
);
path.display().to_string()
}
fn global_config(dir: &std::path::Path, servers: &[(&str, &str)]) -> PathBuf {
let mut text = String::new();
for (name, command) in servers {
text.push_str(&format!(
"[[servers]]\nname = {name:?}\n[servers.transport]\ntype = \"stdio\"\ncommand = {command:?}\n[servers.transport.env]\nTCODE_FIXTURE_TOKEN = \"fixture-token-5428\"\n\n"
));
}
let path = dir.join("servers.toml");
std::fs::write(&path, text).expect("writing the global fixture");
path
}
fn wedged_then_healthy(dir: &std::path::Path, wedged: usize) -> PathBuf {
let binary = fixture_binary();
let mut text = String::new();
for i in 0..wedged {
text.push_str(&format!(
"[[servers]]\nname = \"wedged-{i}\"\n[servers.transport]\ntype = \"stdio\"\ncommand = {binary:?}\n\
[servers.transport.env]\nTCODE_FIXTURE_HANG = \"1\"\n\n"
));
}
text.push_str(&format!(
"[[servers]]\nname = \"fixture\"\n[servers.transport]\ntype = \"stdio\"\ncommand = {binary:?}\n\
[servers.transport.env]\nTCODE_FIXTURE_TOKEN = \"fixture-token-5428\"\n"
));
let path = dir.join("servers.toml");
std::fs::write(&path, text).expect("writing the global fixture");
path
}
struct Squatter(String);
#[async_trait]
impl ToolExecutor for Squatter {
fn name(&self) -> &str {
&self.0
}
fn schema(&self) -> Value {
json!({"type": "function", "function": {"name": self.0}})
}
async fn execute(&self, _args: Value) -> ToolResult {
ToolResult::ok("squatted")
}
}
#[tokio::test]
async fn end_to_end_dispatch_echoes_through_the_registry() {
let home = tempdir().expect("tempdir");
let project = tempdir().expect("tempdir");
let global = global_config(home.path(), &[("fixture", &fixture_binary())]);
let set = McpToolSet::load_at(&global, project.path()).await;
let mut registry = ToolRegistry::new();
let diagnostics = register_configured_tools(&mut registry, &set);
assert!(diagnostics.issues.is_empty(), "{:?}", diagnostics.issues);
assert_eq!(diagnostics.usable_count(), 1);
assert_eq!(
diagnostics.tools,
vec!["mcp__fixture__echo", "mcp__fixture__echo_env"],
);
let result = registry
.dispatch("mcp__fixture__echo", json!({"message": "hello 5428"}))
.await;
assert!(!result.is_error(), "{}", result.content());
assert_eq!(result.content(), "hello 5428");
let schemas = registry.schemas();
let echo = schemas
.iter()
.find(|s| s["function"]["name"] == "mcp__fixture__echo")
.expect("the echo schema is advertised");
assert_eq!(
echo["function"]["parameters"]["required"],
json!(["message"])
);
}
#[tokio::test]
async fn a_configured_env_reaches_the_child_process() {
let home = tempdir().expect("tempdir");
let project = tempdir().expect("tempdir");
let global = global_config(home.path(), &[("fixture", &fixture_binary())]);
let set = McpToolSet::load_at(&global, project.path()).await;
let mut registry = ToolRegistry::new();
register_configured_tools(&mut registry, &set);
let result = registry.dispatch("mcp__fixture__echo_env", json!({})).await;
assert_eq!(result.content(), "fixture-token-5428");
}
#[tokio::test]
async fn spawn_failure_isolates_the_healthy_server() {
let home = tempdir().expect("tempdir");
let project = tempdir().expect("tempdir");
let global = global_config(
home.path(),
&[
("ghost", "/nonexistent/mcp/binary/xyzzy-5428"),
("fixture", &fixture_binary()),
],
);
let set = McpToolSet::load_at(&global, project.path()).await;
let mut registry = ToolRegistry::new();
let diagnostics = register_configured_tools(&mut registry, &set);
assert_eq!(diagnostics.statuses.len(), 2, "both are reported");
let ghost = &diagnostics.statuses[0];
assert_eq!(ghost.name, "ghost");
assert!(!ghost.usable);
assert!(ghost.detail.as_deref().is_some_and(|d| d.contains("xyzzy")));
assert!(diagnostics.statuses[1].usable, "the sibling is unaffected");
let result = registry
.dispatch("mcp__fixture__echo", json!({"message": "still here"}))
.await;
assert_eq!(result.content(), "still here");
}
#[tokio::test]
async fn a_hung_server_does_not_serialise_its_siblings() {
let home = tempdir().expect("tempdir");
let project = tempdir().expect("tempdir");
const WEDGED: usize = 3;
let global = wedged_then_healthy(home.path(), WEDGED);
let budget = Duration::from_millis(1_000);
let started = Instant::now();
let set = McpToolSet::load_within(&global, project.path(), budget).await;
let elapsed = started.elapsed();
let mut registry = ToolRegistry::new();
let diagnostics = register_configured_tools(&mut registry, &set);
assert!(
elapsed >= budget,
"the wedged servers must actually have been waited out: {elapsed:?}",
);
assert!(
elapsed < budget * 2,
"{WEDGED} wedged servers plus one healthy: the load took {elapsed:?}. \
Concurrently that is about one budget of {budget:?}; sequentially it \
would be at least {:?}. The connections are running in sequence.",
budget * WEDGED as u32,
);
let names: Vec<&str> = diagnostics
.statuses
.iter()
.map(|s| s.name.as_str())
.collect();
assert_eq!(names, vec!["wedged-0", "wedged-1", "wedged-2", "fixture"]);
for status in &diagnostics.statuses[..WEDGED] {
assert!(!status.usable);
assert!(
status
.detail
.as_deref()
.is_some_and(|d| d.contains("handshake")),
"a wedged server reports the timeout: {status:?}",
);
}
assert!(diagnostics.statuses[WEDGED].usable);
assert_eq!(
registry
.dispatch("mcp__fixture__echo", json!({"message": "unblocked"}))
.await
.content(),
"unblocked",
);
}
#[tokio::test]
async fn a_name_already_in_the_registry_is_skipped() {
let home = tempdir().expect("tempdir");
let project = tempdir().expect("tempdir");
let global = global_config(home.path(), &[("fixture", &fixture_binary())]);
let set = McpToolSet::load_at(&global, project.path()).await;
let mut registry = ToolRegistry::new();
registry.register(Arc::new(Squatter("mcp__fixture__echo".to_string())));
let diagnostics = register_configured_tools(&mut registry, &set);
assert_eq!(
registry
.dispatch("mcp__fixture__echo", json!({"message": "hi"}))
.await
.content(),
"squatted",
"registration must never overwrite an existing tool",
);
assert!(
!diagnostics
.tools
.contains(&"mcp__fixture__echo".to_string()),
"a skipped tool is not reported as registered: {:?}",
diagnostics.tools,
);
assert!(
diagnostics
.issues
.iter()
.any(|i| i.detail.contains("mcp__fixture__echo")),
"the collision is reported: {:?}",
diagnostics.issues,
);
assert_eq!(
registry
.dispatch("mcp__fixture__echo_env", json!({}))
.await
.content(),
"fixture-token-5428",
);
}
#[tokio::test]
async fn a_project_set_with_a_new_command_never_spawns() {
let home = tempdir().expect("tempdir");
let project = tempdir().expect("tempdir");
let global = global_config(home.path(), &[("fixture", &fixture_binary())]);
let project_dir = project.path().join(".trusty-code");
std::fs::create_dir_all(&project_dir).expect("project config dir");
std::fs::write(
project_dir.join("mcp.toml"),
"[[servers]]\nname = \"fixture\"\n[servers.transport]\ntype = \"stdio\"\ncommand = \"/nonexistent/mcp/attacker-5428\"\n",
)
.expect("project fixture");
let set = McpToolSet::load_at(&global, project.path()).await;
let mut registry = ToolRegistry::new();
let diagnostics = register_configured_tools(&mut registry, &set);
assert_eq!(diagnostics.usable_count(), 1, "the GLOBAL entry ran");
assert_eq!(
registry
.dispatch("mcp__fixture__echo", json!({"message": "global wins"}))
.await
.content(),
"global wins",
);
assert!(
diagnostics
.issues
.iter()
.any(|i| i.detail.contains("fixture")),
"the refusal is reported: {:?}",
diagnostics.issues,
);
}
#[test]
fn the_fixture_binary_is_never_stale_relative_to_its_source_7951() {
let binary = PathBuf::from(fixture_binary());
let source = PathBuf::from(concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/mcp_fixture_server.rs"
));
let built = std::fs::metadata(&binary)
.and_then(|m| m.modified())
.expect("the built fixture has an mtime");
let edited = std::fs::metadata(&source)
.and_then(|m| m.modified())
.expect("the fixture source has an mtime");
assert!(
built >= edited,
"the fixture binary at {} is older than {} — this suite is running \
against a stale fixture (#7951)",
binary.display(),
source.display(),
);
}
#[test]
fn profile_is_derived_from_both_cargo_layouts_and_rejects_others_11138() {
let cases = [
(
"/t/debug/deps/mcp_loader_e2e-0123456789abcdef",
"/t/debug",
"dev",
),
(
"/t/release/deps/mcp_loader_e2e-0123456789abcdef",
"/t/release",
"release",
),
(
"/t/debug/build/trusty-code/0123456789abcdef/out/mcp_loader_e2e-0123456789abcdef",
"/t/debug",
"dev",
),
(
"/t/release/build/trusty-code/0123456789abcdef/out/mcp_loader_e2e-0123456789abcdef",
"/t/release",
"release",
),
];
for (exe, dir, profile) in cases {
let (got_dir, got_profile) =
fixture_profile(Path::new(exe)).unwrap_or_else(|e| panic!("{exe} must parse: {e}"));
assert_eq!(got_dir, PathBuf::from(dir), "profile dir of {exe}");
assert_eq!(got_profile, profile, "profile of {exe}");
}
for bad in [
"/t/debug/mcp_loader_e2e-0123456789abcdef",
"/t/debug/odd/mcp_loader_e2e-0123456789abcdef",
"/t/debug/notbuild/trusty-code/0123456789abcdef/out/mcp_loader_e2e-0123456789abcdef",
"/out/mcp_loader_e2e-0123456789abcdef",
] {
assert!(
fixture_profile(Path::new(bad)).is_err(),
"{bad} must be rejected"
);
}
}