trusty-code 0.8.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! The MCP loader against a REAL stdio MCP server (#5428).
//!
//! Why: the loader's whole contract is transport — spawn a subprocess, run the
//! JSON-RPC handshake, register what it advertises, dispatch a call back to
//! it. A mocked client would prove none of that. `examples/mcp_fixture_server.rs`
//! is the counterpart server; `fixture_binary` builds it, `cargo install` does
//! not ship it.
//! What: config written into a tempdir, never the developer's real
//! `~/.trusty-tools/mcp/servers.toml`.
//! Test: this file.

use std::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};

/// The fixture server's freshly-built path.
///
/// Why (#7951): `CARGO_BIN_EXE_*` covers `[[bin]]` targets only, and this
/// fixture is deliberately an example so it never ships — so nothing kept it
/// current. `cargo test --test mcp_loader_e2e` builds this target alone and
/// NOT the crate's examples, so the suite ran against whatever copy of
/// `examples/mcp_fixture_server.rs` was compiled last. The crate's other
/// fixtures use `env!("CARGO_BIN_EXE_tcode")`, which cargo rebuilds for every
/// test run; an example has no such variable, so this builds it instead.
/// What: runs `cargo build --example mcp_fixture_server` once per test
/// process, into the same target directory and profile the running test binary
/// came from — so it follows a custom `CARGO_TARGET_DIR` and a `--release` run
/// alike. An absent or unbuildable binary FAILS rather than skipping: a gate
/// that silently does not run is not a gate.
/// Test: `the_fixture_binary_is_never_stale_relative_to_its_source_7951`.
fn fixture_binary() -> String {
    static BUILT: OnceLock<String> = OnceLock::new();
    BUILT.get_or_init(build_fixture_binary).clone()
}

/// Build the fixture example into this run's own target dir, once.
///
/// Why: the one-time half of [`fixture_binary`], kept separate so the
/// `OnceLock` body stays a single call.
/// What: `target/debug` is the `dev` profile's directory and every other
/// profile directory is named after the profile itself, so the directory the
/// test binary lives in names both the target dir and the profile to rebuild
/// under. Cargo's own build lock serialises this against a concurrent build.
/// Test: `the_fixture_binary_is_never_stale_relative_to_its_source_7951`.
fn build_fixture_binary() -> String {
    let mut profile_dir: PathBuf = std::env::current_exe().expect("the test binary has a path");
    profile_dir.pop();
    if profile_dir.ends_with("deps") {
        profile_dir.pop();
    }
    let target_dir = profile_dir
        .parent()
        .expect("a profile directory has a parent");
    let profile = match profile_dir.file_name().and_then(|n| n.to_str()) {
        Some("debug") | None => "dev",
        Some(other) => other,
    };

    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()
}

/// A global `servers.toml` declaring one stdio server per `(name, command)`.
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
}

/// A global `servers.toml` of `wedged` servers, then one healthy `fixture`.
///
/// Why TWO wedged servers by default: with only one, a sequential loader costs
/// one budget plus the healthy server's few milliseconds — indistinguishable
/// from a concurrent one, so the test would pass against the very defect it
/// exists to catch. N wedged servers make the sequential cost N budgets and
/// the concurrent cost one.
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
}

/// A tool that only has to occupy a name.
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")
    }
}

/// Why: the whole slice, end to end — a configured server is spawned, its
/// tools are discovered and registered under `mcp__<server>__<tool>`, and a
/// dispatch through the registry reaches the real subprocess and comes back.
#[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");

    // The advertised schema reaches the model unmodified.
    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"])
    );
}

/// Why: a configured `env` carries the credential an MCP server needs, and it
/// has to actually reach the child — an overlay that silently did not apply
/// would look exactly like a server misbehaving.
#[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");
}

/// Why: the isolation ruling. One unstartable server must cost exactly itself
/// — the healthy sibling's tools still register and still dispatch.
#[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");
}

/// Why: the per-server startup bound is only worth having if the servers are
/// attempted CONCURRENTLY. Connected in sequence, N wedged connectors cost
/// N × the bound before the agent loop starts, so the worst case grew with the
/// operator's config. THREE wedged servers plus a healthy one: concurrently
/// the load costs about one budget, sequentially at least three, so the
/// margin below tells the two apart. The healthy sibling — last in config
/// order — must still register and dispatch.
#[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,
    );

    // Config order survives the concurrency.
    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",
    );
}

/// Why: `ToolRegistry::register` overwrites a duplicate outside a debug build,
/// so a colliding MCP tool could silently replace a tool the run depends on.
/// It must be skipped, the incumbent left intact, and the caller told.
#[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,
    );
    // The server's other tool still registered.
    assert_eq!(
        registry
            .dispatch("mcp__fixture__echo_env", json!({}))
            .await
            .content(),
        "fixture-token-5428",
    );
}

/// Why: the trust gate, over a real spawn. A project entry that keeps a
/// trusted NAME but changes the command must not be what runs — and the
/// refusal must be visible.
#[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,
    );
}

/// Why (#7951): every other assertion in this file reads the fixture's
/// behaviour — its tool list, its schema, its env echo — so all of them are
/// only as true as the binary is current. `cargo test --test mcp_loader_e2e`
/// builds this target and NOT the crate's examples, so the suite ran against
/// whatever copy of `examples/mcp_fixture_server.rs` happened to be compiled
/// last: a source change was invisible, which is a wrong-reason failure or a
/// silent false green. This is the freshness check the rest of the file rests
/// on, and it fails if [`fixture_binary`] ever stops rebuilding.
#[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(),
    );
}