返回 CodeWhale
mcp.rs
根目录 / crates / tui / src / conformance / mcp.rs
1 //! Recorded-MCP family: one transcript, every dispatch implementation.
2 //!
3 //! A transcript (`<case>.case.json`) scripts an MCP server — what it answers
4 //! to `initialize`, `tools/list`, `resources/*`, `prompts/*`, and to each
5 //! `tools/call` (a result, an `isError` result, a JSON-RPC error, progress
6 //! notifications before the result, or no answer at all until the caller
7 //! cancels) — plus the steps a host takes against it. The harness serves the
8 //! transcript as a real Streamable HTTP MCP server on loopback
9 //! ([`server`]), so any client that can open a URL can be pointed at it,
10 //! including a child Node process; or, for `"transport": "stdio"`, as a
11 //! POSIX-shell child (`stdio_server.sh.fixture`, named so the repo's `*.sh`
12 //! ignore rule does not swallow it) the dispatch spawns itself.
13 //!
14 //! [`DISPATCHES`] is the seam for the TypeScript migration
15 //! (TS-EXTENSION-HOST-DESIGN §5.2, §9.3): native Rust and the default Host
16 //! SDK dispatch must produce the same semantic golden. Transport goldens
17 //! name each dispatch so discovery, authentication and session behavior stay
18 //! explicit. Host uses the real pinned SDK and Rust broker.
19 //!
20 //! Normalization: the server URL/port is masked; results are
21 //! `{"ok": {success, content, metadata, content_blocks}}` with JSON content
22 //! parsed, or `{"err": {kind, detail}}` with exact detail bytes.
23 //! `server_received` lists the side-effecting requests the server saw
24 //! (`tools/call`, `resources/read`, `prompts/get`) — a call that must not be
25 //! sent, or must not be replayed, shows up there.
26 //!
27 //! # Case fields beyond the original two cases
28 //!
29 //! All optional; an absent field is the original behaviour, so the original
30 //! goldens did not move.
31 //!
32 //! - `transport`: `"http"` (default) or `"stdio"`. A stdio case's `server`
33 //! object is written to files for `stdio_server.sh.fixture`; only `initialize`,
34 //! `tools/list` and `tools/call` (by `match.name`, with `"exit": true` for
35 //! a server that dies after reading the call) are supported. Unix only.
36 //! - `config`: extra `McpServerConfig` fields merged over the harness's own.
37 //! - `disallowed_tools`: deny rules handed to the dispatch (pool-level and
38 //! per-call, as the engine does).
39 //! - `expect_boot`: `"error"` records a failed boot as
40 //! `{"op":"boot","outcome":{"err":detail}}` instead of failing the harness;
41 //! steps still run, so the catalog after a failed boot is pinned too. A
42 //! case that expects an error and boots cleanly fails the harness.
43 //! - `server_options`: `numbered_sessions`, `require_bearer` (see [`server`]).
44 //! - `bearer_secret`: a fake token the harness exports as the server's
45 //! `bearer_token_env_var`. It must appear in no recorded byte: the outcome
46 //! is scanned for it before a golden is compared or written, in update mode
47 //! too.
48 //! - `sink`: start a second server and put its URL where the spec says
49 //! `{{sink_url}}`; the outcome records how many requests reached it.
50 //! - `record_requests`: `"full"` adds every POST the server saw (session,
51 //! protocol version, authorization shape, status) to the outcome as
52 //! `requests`; `"summary"` adds only the distinct methods, authorization
53 //! shapes and statuses (`requests_summary`), for cases that must not pin how
54 //! often a client retries a connect.
55 //!
56 //! Steps: `catalog`, `call`, and `approval_hints` (`{"op":"approval_hints",
57 //! "tools":[model names]}`, read after a `catalog` step).
58 //!
59 //! What a host-backed dispatch is *not* tested on by this family is listed in
60 //! the fixture README's coverage boundaries: reviewed-plugin launches (hash
61 //! refusal, trusted-read-only approval hints), real OAuth login, the SSE
62 //! legacy transport, the 32 MiB aggregate catalog byte cap, concurrent
63 //! calls, and a held stdio call.
64
65 mod controls;
66 mod server;
67
68 use std::path::{Path, PathBuf};
69 use std::sync::{Arc, Mutex};
70 use std::time::Duration;
71
72 use serde_json::{Value, json};
73 use tokio::sync::{Mutex as AsyncMutex, mpsc};
74 use tokio_util::sync::CancellationToken;
75
76 use self::server::{ServerOptions, TranscriptServer};
77 use super::golden::{self, Failures, Sandbox};
78 use crate::test_support::EnvVarGuard;
79 use codewhale_engine::core::engine::Engine;
80 use codewhale_engine::core::events::Event;
81 use codewhale_engine::mcp::{McpPool, McpToolApprovalHint};
82 use codewhale_engine::tools::spec::{RichToolResult, ToolError};
83 use codewhale_mcp::config::McpConfig;
84
85 const FAMILY: &str = "mcp";
86 const CALL_DEADLINE: Duration = Duration::from_secs(30);
87 /// The environment variable a case's `bearer_secret` is exported through.
88 const BEARER_ENV: &str = "CODEWHALE_CONFORMANCE_MCP_TOKEN";
89
90 // === The dispatch seam ===
91
92 /// Everything a dispatch is built from: the connection config, and the deny
93 /// rules the engine would also hand to the pool (`--disallowed-tools`).
94 struct DispatchSetup {
95 config: McpConfig,
96 disallowed_tools: Vec<String>,
97 }
98
99 /// One implementation of "call a tool on an external MCP server", as the
100 /// engine sees it. Planning, hooks and approval happen before `call`;
101 /// implementors never gate (design §5.2) — except that deny rules are part of
102 /// the dispatch's setup and refuse a call before anything reaches a server.
103 #[async_trait::async_trait]
104 trait McpDispatchUnderTest: Send + Sync {
105 /// Connect to every configured server. An `Err` is a connect failure
106 /// (including needs-auth); the dispatch must still answer `catalog` and
107 /// `call` afterwards, with whatever it can still advertise.
108 async fn boot(&self) -> Result<(), String>;
109 /// The model-visible tool catalog this dispatch advertises.
110 async fn catalog(&self) -> Vec<codewhale_models::Tool>;
111 /// Call one model-facing tool; `cancel` is the turn interrupt.
112 async fn call(
113 &self,
114 model_name: &str,
115 input: Value,
116 cancel: CancellationToken,
117 ) -> Result<RichToolResult, ToolError>;
118 /// Addition for the approval-hint case: how the approval path may treat
119 /// `model_name` given what the server's catalog declared, read after
120 /// `catalog()`. `"destructive"` (each call keeps its prompt),
121 /// `"trusted_read_only"` (a reviewed plugin's read-only tool runs
122 /// unprompted), or `None`. Implementation-neutral: any dispatch that
123 /// consumes MCP tool annotations has this answer.
124 async fn approval_hint(&self, model_name: &str) -> Option<&'static str>;
125 async fn shutdown(&self);
126 }
127
128 type DispatchFactory = fn(setup: DispatchSetup) -> Box<dyn McpDispatchUnderTest>;
129
130 /// Every dispatch shares semantic goldens and retains its transport goldens.
131 const DISPATCHES: &[(&str, DispatchFactory)] = &[
132 ("mcp_pool", McpPoolDispatch::boxed),
133 ("host_sdk", HostMcpDispatch::boxed),
134 ];
135
136 /// The explicitly selected native Rust path through the shared engine pool.
137 struct McpPoolDispatch {
138 pool: Arc<AsyncMutex<McpPool>>,
139 tx_event: mpsc::Sender<Event>,
140 disallowed_tools: Vec<String>,
141 // Kept open so status events the dispatch emits never hit a closed channel.
142 _rx_event: Mutex<mpsc::Receiver<Event>>,
143 }
144
145 impl McpPoolDispatch {
146 fn boxed(setup: DispatchSetup) -> Box<dyn McpDispatchUnderTest> {
147 let (tx_event, rx_event) = mpsc::channel(64);
148 let pool = McpPool::new(setup.config)
149 .with_backend(codewhale_config::McpBackend::Rust)
150 .with_disallowed_tools(setup.disallowed_tools.clone());
151 Box::new(Self {
152 pool: Arc::new(AsyncMutex::new(pool)),
153 tx_event,
154 disallowed_tools: setup.disallowed_tools,
155 _rx_event: Mutex::new(rx_event),
156 })
157 }
158 }
159
160 #[async_trait::async_trait]
161 impl McpDispatchUnderTest for McpPoolDispatch {
162 async fn boot(&self) -> Result<(), String> {
163 let errors = self.pool.lock().await.connect_all().await;
164 if errors.is_empty() {
165 Ok(())
166 } else {
167 Err(errors
168 .iter()
169 .map(|(name, error)| format!("{name}: {error:#}"))
170 .collect::<Vec<_>>()
171 .join("; "))
172 }
173 }
174
175 async fn catalog(&self) -> Vec<codewhale_models::Tool> {
176 self.pool.lock().await.to_api_tools()
177 }
178
179 async fn call(
180 &self,
181 model_name: &str,
182 input: Value,
183 cancel: CancellationToken,
184 ) -> Result<RichToolResult, ToolError> {
185 // The engine interrupts a tool by dropping its future; do the same.
186 tokio::select! {
187 biased;
188 () = cancel.cancelled() => Err(ToolError::cancelled("tool call interrupted by the host")),
189 result = Engine::execute_mcp_tool_with_pool(
190 Arc::clone(&self.pool),
191 &self.tx_event,
192 model_name,
193 input,
194 // The engine hands the registry context's rules to every call
195 // as well as to the pool; do both.
196 &self.disallowed_tools,
197 // Conformance probes cannot supply a person's card decision.
198 None,
199 None,
200 None,
201 None,
202 ) => result,
203 }
204 }
205
206 async fn approval_hint(&self, model_name: &str) -> Option<&'static str> {
207 codewhale_engine::mcp::mcp_tool_approval_hint(model_name).map(|hint| match hint {
208 McpToolApprovalHint::TrustedReadOnly => "trusted_read_only",
209 McpToolApprovalHint::Destructive => "destructive",
210 })
211 }
212
213 async fn shutdown(&self) {
214 self.pool.lock().await.shutdown_all().await;
215 }
216 }
217
218 /// The selected production Host pool, not a semantic fake. The sandbox
219 /// already seals CODEWHALE_HOME; manager materialization and native child
220 /// launch use that same root. Guards live through shutdown on this runner's
221 /// current-thread runtime, so host workers never inherit another case's policy.
222 struct HostMcpDispatch {
223 inner: McpPoolDispatch,
224 manager: Arc<codewhale_engine::extension_host::ExtensionHostManager>,
225 _manager: codewhale_engine::extension_host::TestManagerGuard,
226 _policy: codewhale_plugins::activation::TestPolicyGuard,
227 }
228 impl HostMcpDispatch {
229 fn boxed(setup: DispatchSetup) -> Box<dyn McpDispatchUnderTest> {
230 let node = codewhale_engine::extension_host::test_support::node_for_tests(
231 "recorded MCP Host SDK parity",
232 )
233 .expect("recorded Host SDK parity requires a supported local Node runtime");
234 let root =
235 PathBuf::from(std::env::var_os("CODEWHALE_HOME").expect("sealed conformance home"));
236 let manager = Arc::new(codewhale_engine::extension_host::ExtensionHostManager::new(
237 codewhale_engine::extension_host::ExtensionHostOptions {
238 node_override: Some(node),
239 root: Some(root),
240 ..Default::default()
241 },
242 ));
243 let policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(true);
244 let manager_guard =
245 codewhale_engine::extension_host::TestManagerGuard::install(Arc::clone(&manager));
246 let (tx_event, rx_event) = mpsc::channel(64);
247 let pool = McpPool::new(setup.config)
248 .with_disallowed_tools(setup.disallowed_tools.clone())
249 .with_backend(codewhale_config::McpBackend::Host);
250 Box::new(Self {
251 inner: McpPoolDispatch {
252 pool: Arc::new(AsyncMutex::new(pool)),
253 tx_event,
254 disallowed_tools: setup.disallowed_tools,
255 _rx_event: Mutex::new(rx_event),
256 },
257 manager,
258 _manager: manager_guard,
259 _policy: policy,
260 })
261 }
262 }
263 #[async_trait::async_trait]
264 impl McpDispatchUnderTest for HostMcpDispatch {
265 async fn boot(&self) -> Result<(), String> {
266 self.inner.boot().await
267 }
268 async fn catalog(&self) -> Vec<codewhale_models::Tool> {
269 self.inner.catalog().await
270 }
271 async fn call(
272 &self,
273 name: &str,
274 input: Value,
275 cancel: CancellationToken,
276 ) -> Result<RichToolResult, ToolError> {
277 self.inner.call(name, input, cancel).await
278 }
279 async fn approval_hint(&self, name: &str) -> Option<&'static str> {
280 self.inner.approval_hint(name).await
281 }
282 async fn shutdown(&self) {
283 self.inner.shutdown().await;
284 self.manager.shutdown().await;
285 }
286 }
287
288 // === The server a case runs against ===
289
290 struct Backend {
291 server: Option<TranscriptServer>,
292 sink: Option<TranscriptServer>,
293 stdio_dir: Option<PathBuf>,
294 }
295
296 impl Backend {
297 /// Start what the case scripts and return it with the `McpServerConfig`
298 /// the dispatch connects with.
299 async fn start(case: &Value, workspace: &Path) -> (Self, Value) {
300 let mut config = if case["transport"].as_str() == Some("stdio") {
301 let dir = workspace.join("stdio_server");
302 write_stdio_server(&dir, &case["server"]);
303 let script = dir.join("stdio_server.sh");
304 let config = json!({
305 "command": "sh",
306 "args": [script, dir],
307 "connect_timeout": 10,
308 "execute_timeout": 10,
309 });
310 return (
311 Self {
312 server: None,
313 sink: None,
314 stdio_dir: Some(dir),
315 },
316 merged(config, &case["config"]),
317 );
318 } else {
319 json!({ "connect_timeout": 10, "execute_timeout": 10 })
320 };
321 let sink = if case["sink"].as_bool() == Some(true) {
322 Some(TranscriptServer::start(json!({}), ServerOptions::default()).await)
323 } else {
324 None
325 };
326 // The sink's URL is not known until it is listening; the spec names
327 // it as `{{sink_url}}`.
328 let spec = match &sink {
329 Some(sink) => serde_json::from_str(
330 &case["server"]
331 .to_string()
332 .replace("{{sink_url}}", &sink.url),
333 )
334 .expect("spec with sink url"),
335 None => case["server"].clone(),
336 };
337 let secret = case["bearer_secret"].as_str();
338 let options = ServerOptions {
339 numbered_sessions: case["server_options"]["numbered_sessions"].as_bool() == Some(true),
340 require_bearer: case["server_options"]["require_bearer"]
341 .as_bool()
342 .filter(|required| *required)
343 .and_then(|_| secret.map(str::to_string)),
344 };
345 let server = TranscriptServer::start(spec, options).await;
346 config["url"] = json!(server.url);
347 if secret.is_some() {
348 config["bearer_token_env_var"] = json!(BEARER_ENV);
349 }
350 (
351 Self {
352 server: Some(server),
353 sink,
354 stdio_dir: None,
355 },
356 merged(config, &case["config"]),
357 )
358 }
359
360 /// Server URL/port literals the golden masks.
361 fn literals(&self) -> Vec<(String, String)> {
362 let mut literals = Vec::new();
363 for (server, url_label, addr_label) in [
364 (&self.server, "<SERVER_URL>", "<SERVER_ADDR>"),
365 (&self.sink, "<SINK_URL>", "<SINK_ADDR>"),
366 ] {
367 if let Some(server) = server {
368 literals.push((server.url.clone(), url_label.to_string()));
369 literals.push((server.addr.clone(), addr_label.to_string()));
370 }
371 }
372 literals
373 }
374
375 /// Side-effecting requests the server was asked to run.
376 fn received(&self) -> Vec<Value> {
377 if let Some(server) = &self.server {
378 return server.received();
379 }
380 let dir = self.stdio_dir.as_ref().expect("a backend has a server");
381 std::fs::read_to_string(dir.join("calls.log"))
382 .unwrap_or_default()
383 .lines()
384 .map(|line| {
385 let request: Value = serde_json::from_str(line).expect("logged request");
386 json!({
387 "method": "tools/call",
388 "name": request["params"]["name"],
389 "arguments": request["params"].get("arguments").cloned().unwrap_or(Value::Null),
390 })
391 })
392 .collect()
393 }
394 }
395
396 fn merged(mut base: Value, extra: &Value) -> Value {
397 if let Some(extra) = extra.as_object() {
398 for (key, value) in extra {
399 base[key] = value.clone();
400 }
401 }
402 base
403 }
404
405 /// Materialize a transcript for `stdio_server.sh.fixture`: the script itself plus one
406 /// reply file per scripted answer (see the script's header).
407 fn write_stdio_server(dir: &Path, spec: &Value) {
408 std::fs::create_dir_all(dir).expect("stdio server dir");
409 std::fs::copy(
410 golden::family_dir(FAMILY).join("stdio_server.sh.fixture"),
411 dir.join("stdio_server.sh"),
412 )
413 .expect("copy stdio_server.sh.fixture");
414 // `"result":{…}` / `"error":{…}`: a JSON-RPC reply minus its id.
415 let fragment = |entry: &Value| match entry.get("error") {
416 Some(error) => format!("\"error\":{error}"),
417 None => format!("\"result\":{}", entry["result"]),
418 };
419 for (method, file) in [
420 ("initialize", "initialize.reply"),
421 ("tools/list", "tools_list.reply"),
422 ] {
423 let entry = spec
424 .get(method)
425 .unwrap_or_else(|| panic!("a stdio case scripts `{method}`"));
426 std::fs::write(dir.join(file), fragment(entry)).expect("write reply");
427 }
428 for call in spec["tools/call"].as_array().into_iter().flatten() {
429 let tool = call["match"]["name"]
430 .as_str()
431 .expect("tools/call match.name");
432 if call["exit"].as_bool() == Some(true) {
433 std::fs::write(dir.join(format!("call.{tool}.exit")), "").expect("write exit");
434 } else {
435 std::fs::write(dir.join(format!("call.{tool}.reply")), fragment(call))
436 .expect("write reply");
437 }
438 }
439 }
440
441 // === Running a transcript ===
442
443 #[test]
444 fn harness_timeout_rejects_a_real_unanswered_mcp_call() {
445 let mut case = golden::read_case(FAMILY, "tools_resources_prompts");
446 let held = case["steps"]
447 .as_array()
448 .expect("steps")
449 .iter()
450 .find(|step| step["cancel"] == "after_server_holds")
451 .expect("held-call fixture")
452 .clone();
453 let mut held = held;
454 held.as_object_mut().expect("step").remove("cancel");
455 case["steps"] = json!([held]);
456 let outcome = run_case(
457 "unanswered_call",
458 &case,
459 "mcp_pool",
460 McpPoolDispatch::boxed,
461 Duration::from_secs(1),
462 true,
463 );
464 let mut failures = Failures::default();
465 match outcome {
466 Err(error) => failures.push("unanswered_call", error),
467 Ok(()) => panic!("an unanswered MCP call became recordable output"),
468 }
469 assert!(failures.contains("harness timeout: MCP call"));
470 }
471
472 fn normalize_call(result: &Result<RichToolResult, ToolError>) -> Value {
473 match result {
474 Ok(rich) => json!({ "ok": {
475 "success": rich.result.success,
476 "content": serde_json::from_str::<Value>(&rich.result.content)
477 .unwrap_or_else(|_| Value::String(rich.result.content.clone())),
478 "metadata": rich.result.metadata,
479 "content_blocks": rich.content_blocks,
480 } }),
481 Err(error) => {
482 json!({ "err": { "kind": golden::tool_error_kind(error), "detail": error.to_string() } })
483 }
484 }
485 }
486
487 async fn run_transcript(
488 case: &Value,
489 factory: DispatchFactory,
490 workspace: &Path,
491 deadline: Duration,
492 ) -> Result<(Value, Vec<(String, String)>), String> {
493 let scripted_steps = case["steps"].as_array().expect("case.steps");
494 if scripted_steps.is_empty() {
495 return Err("MCP transcript has no host steps".to_string());
496 }
497 let (backend, server_config) = Backend::start(case, workspace).await;
498 let server_name = case["server_name"].as_str().unwrap_or("conformance");
499 let config: McpConfig =
500 serde_json::from_value(json!({ "servers": { server_name: server_config } }))
501 .expect("transcript MCP config");
502 let dispatch = factory(DispatchSetup {
503 config,
504 disallowed_tools: case["disallowed_tools"]
505 .as_array()
506 .into_iter()
507 .flatten()
508 .map(|rule| rule.as_str().expect("deny rule").to_string())
509 .collect(),
510 });
511 let mut steps = Vec::new();
512 let expect_boot_error = case["expect_boot"].as_str() == Some("error");
513 let boot = match golden::complete_within("MCP boot", deadline, dispatch.boot()).await? {
514 Ok(()) if expect_boot_error => {
515 return Err("MCP transcript expected boot to fail but it connected".to_string());
516 }
517 Ok(()) => json!("ok"),
518 Err(detail) if expect_boot_error => json!({ "err": detail }),
519 Err(detail) => return Err(format!("MCP transcript could not boot: {detail}")),
520 };
521 steps.push(json!({ "op": "boot", "outcome": boot }));
522 for step in scripted_steps {
523 match step["op"].as_str().expect("step.op") {
524 "catalog" => {
525 let catalog = serde_json::to_value(
526 golden::complete_within("MCP catalog", deadline, dispatch.catalog()).await?,
527 )
528 .expect("catalog");
529 steps.push(json!({ "op": "catalog", "tools": catalog }));
530 }
531 "approval_hints" => {
532 let mut hints = serde_json::Map::new();
533 for tool in step["tools"].as_array().expect("step.tools") {
534 let tool = tool.as_str().expect("tool name");
535 let hint = golden::complete_within(
536 "MCP approval hint",
537 deadline,
538 dispatch.approval_hint(tool),
539 )
540 .await?;
541 hints.insert(tool.to_string(), json!(hint));
542 }
543 steps.push(json!({ "op": "approval_hints", "hints": hints }));
544 }
545 "call" => {
546 let tool = step["tool"].as_str().expect("step.tool");
547 let cancel = CancellationToken::new();
548 let canceller =
549 (step["cancel"].as_str() == Some("after_server_holds")).then(|| {
550 let state = Arc::clone(
551 &backend
552 .server
553 .as_ref()
554 .expect("only an HTTP case can hold a call")
555 .state,
556 );
557 let cancel = cancel.clone();
558 tokio::spawn(async move {
559 state.held.notified().await;
560 cancel.cancel();
561 })
562 });
563 let outcome = golden::complete_within(
564 "MCP call",
565 deadline,
566 dispatch.call(tool, step["input"].clone(), cancel),
567 )
568 .await;
569 if let Some(canceller) = canceller {
570 canceller.abort();
571 }
572 let outcome = normalize_call(&outcome?);
573 steps.push(json!({ "op": "call", "tool": tool, "outcome": outcome }));
574 }
575 other => panic!("unknown transcript op `{other}`"),
576 }
577 }
578 golden::complete_within("MCP shutdown", deadline, dispatch.shutdown()).await?;
579 let mut outcome = json!({ "steps": steps, "server_received": backend.received() });
580 let requests = backend
581 .server
582 .as_ref()
583 .map(TranscriptServer::requests)
584 .unwrap_or_default();
585 match case["record_requests"].as_str() {
586 Some("full") => outcome["requests"] = Value::Array(requests),
587 Some("summary") => outcome["requests_summary"] = summarize_requests(&requests),
588 Some(other) => panic!("unknown record_requests `{other}`"),
589 None => {}
590 }
591 if let Some(sink) = &backend.sink {
592 outcome["sink_requests"] = json!(sink.requests().len());
593 }
594 Ok((outcome, backend.literals()))
595 }
596
597 /// The distinct RPC methods, `Authorization` shapes and HTTP statuses the
598 /// server saw, without their order or count. For cases where *that* a request
599 /// carried a credential (or never got past `initialize`) is the contract, but
600 /// how often a client retries a connect is its own business.
601 fn summarize_requests(requests: &[Value]) -> Value {
602 let distinct = |field: &str| {
603 let mut values: Vec<Value> = Vec::new();
604 for request in requests {
605 if !values.contains(&request[field]) {
606 values.push(request[field].clone());
607 }
608 }
609 values.sort_by_key(Value::to_string);
610 Value::Array(values)
611 };
612 json!({
613 "rpcs": distinct("rpc"),
614 "authorization_shapes": distinct("authorization"),
615 "statuses": distinct("status"),
616 })
617 }
618
619 /// No recorded byte may carry a credential. The needle is the secret itself,
620 /// so a bearer header, a URL, a JSON string or an error detail all trip it.
621 fn assert_no_secret(secret: &str, recorded: &str) -> Result<(), String> {
622 if recorded.contains(secret) {
623 return Err(format!(
624 "secret leak: the case's bearer secret appears in the recorded output:\n{}",
625 recorded
626 .lines()
627 .filter(|line| line.contains(secret))
628 .collect::<Vec<_>>()
629 .join("\n")
630 ));
631 }
632 Ok(())
633 }
634
635 /// Run one case through one dispatch and compare with its golden.
636 ///
637 /// `compare_only` forces compare mode even under `CODEWHALE_CONFORMANCE_UPDATE`:
638 /// the negative controls feed deliberately changed cases through here and must
639 /// never rewrite a golden.
640 fn run_case(
641 name: &str,
642 case: &Value,
643 dispatch: &str,
644 factory: DispatchFactory,
645 deadline: Duration,
646 compare_only: bool,
647 ) -> Result<(), String> {
648 if case["transport"].as_str() == Some("stdio") && !cfg!(unix) {
649 eprintln!("conformance: `{name}` needs a POSIX shell; skipped on this platform");
650 return Ok(());
651 }
652 // The pool may touch its state directory; keep that hermetic. Guards are
653 // declared after the sandbox so they restore the environment before the
654 // sandbox releases the lock.
655 let sandbox = Sandbox::new(&Value::Null);
656 let _compare_only = compare_only.then(|| EnvVarGuard::set(golden::UPDATE_ENV, "0"));
657 let secret = case["bearer_secret"].as_str();
658 let _bearer = secret.map(|secret| EnvVarGuard::set(BEARER_ENV, secret));
659 let runtime = tokio::runtime::Builder::new_current_thread()
660 .enable_all()
661 .build()
662 .expect("runtime");
663 let (mut outcome, literals) =
664 runtime.block_on(run_transcript(case, factory, &sandbox.workspace, deadline))?;
665 drop(runtime);
666 let mut masker = sandbox.masker(&[]);
667 for (literal, label) in literals {
668 masker = masker.literal(&literal, &label);
669 }
670 masker.value(&mut outcome);
671 let recorded = golden::pretty(&golden::canonical(&outcome));
672 if let Some(secret) = secret {
673 assert_no_secret(secret, &recorded)?;
674 }
675 let transport = if let Some(kind) = case["record_requests"].as_str() {
676 let field = match kind {
677 "full" => "requests",
678 "summary" => "requests_summary",
679 other => panic!("unknown record_requests `{other}`"),
680 };
681 Some(
682 json!({field: outcome.as_object_mut().expect("outcome").remove(field).expect("recorded transport")}),
683 )
684 } else {
685 None
686 };
687 golden::check_golden(
688 &golden::family_dir(FAMILY).join(format!("{name}.golden.json")),
689 &golden::pretty(&golden::canonical(&outcome)),
690 )?;
691 if let Some(transport) = transport {
692 golden::check_golden(
693 &golden::family_dir(FAMILY).join(format!("{name}.{dispatch}.transport.golden.json")),
694 &golden::pretty(&golden::canonical(&transport)),
695 )?;
696 }
697 Ok(())
698 }
699
700 #[test]
701 fn mcp_transcripts_match_goldens_for_every_dispatch() {
702 let names = golden::case_names(FAMILY);
703 let mut failures = Failures::default();
704 for name in &names {
705 let case = golden::read_case(FAMILY, name);
706 for (dispatch, factory) in DISPATCHES {
707 failures.record(
708 &format!("{name} via {dispatch}"),
709 run_case(name, &case, dispatch, *factory, CALL_DEADLINE, false),
710 );
711 }
712 }
713 failures.finish(FAMILY, names.len() * DISPATCHES.len());
714 }
715
715 lines RUST