返回 CodeWhale
mcp_server_proxy.rs
根目录 / crates / cli / tests / mcp_server_proxy.rs
1 //! The retired aggregation proxy's CLI spelling delegates to the native server.
2 //! Exercise both real binary entrypoints with isolated config; never launch or
3 //! rewrite legacy child-server definitions. The active MCP client is separate.
4
5 use std::fs;
6 use std::io::{BufRead, BufReader, Read, Write};
7 use std::path::PathBuf;
8 use std::process::{Command, Stdio};
9
10 use serde_json::{Value, json};
11 use tempfile::TempDir;
12
13 struct Fixture {
14 _root: TempDir,
15 home: PathBuf,
16 }
17
18 impl Fixture {
19 /// Seal HOME before anything writes config. The suite has written to the
20 /// real `~/.codewhale/config.toml` before (#4831); this test must never be
21 /// the one that does it again.
22 fn new() -> Self {
23 let root = TempDir::new().expect("fixture root");
24 let home = root.path().join("sealed-home");
25 fs::create_dir_all(home.join(".codewhale")).expect("sealed config dir");
26 fs::write(home.join(".codewhale").join("config.toml"), "").expect("seed config");
27 Self { _root: root, home }
28 }
29
30 fn command(&self) -> Command {
31 let mut command = Command::new(codewhale_binary());
32 command
33 .current_dir(&self.home)
34 .env_clear()
35 .env("PATH", std::env::var("PATH").unwrap_or_default())
36 .env("HOME", &self.home)
37 .env("USERPROFILE", &self.home)
38 .env("CODEWHALE_HOME", self.home.join(".codewhale"))
39 .env("CODEWHALE_SECRET_BACKEND", "file");
40 command
41 }
42
43 fn configure_servers(&self, definitions: Value) {
44 let output = self
45 .command()
46 .args(["config", "set", "mcp.server_definitions"])
47 .arg(definitions.to_string())
48 .output()
49 .expect("run config set");
50 assert!(
51 output.status.success(),
52 "config set failed\nstdout:\n{}\nstderr:\n{}",
53 String::from_utf8_lossy(&output.stdout),
54 String::from_utf8_lossy(&output.stderr)
55 );
56 }
57
58 /// Drive `codewhale mcp-server` over stdio with `requests`, returning the
59 /// parsed JSON-RPC responses plus stderr.
60 fn run_mcp_server(&self, args: &[&str], requests: &[Value]) -> (Vec<Value>, String) {
61 let mut child = self
62 .command()
63 .args(args)
64 .stdin(Stdio::piped())
65 .stdout(Stdio::piped())
66 .stderr(Stdio::piped())
67 .spawn()
68 .expect("spawn codewhale mcp-server");
69
70 let mut stdin = child.stdin.take().expect("mcp-server stdin");
71 let mut stdout = BufReader::new(child.stdout.take().expect("mcp-server stdout"));
72 let mut responses = Vec::new();
73 for request in requests {
74 writeln!(stdin, "{request}").expect("write request");
75 stdin.flush().expect("flush request");
76 if let Some(id) = request.get("id") {
77 let mut line = String::new();
78 assert!(stdout.read_line(&mut line).expect("read response") > 0);
79 let response: Value = serde_json::from_str(&line).expect("stdout is only JSON-RPC");
80 assert_eq!(response.get("id"), Some(id));
81 responses.push(response);
82 }
83 }
84 drop(stdin);
85 let mut remainder = String::new();
86 stdout
87 .read_to_string(&mut remainder)
88 .expect("read remaining output");
89 assert!(
90 remainder.trim().is_empty(),
91 "unexpected response: {remainder}"
92 );
93 let output = child.wait_with_output().expect("mcp-server output");
94 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
95 assert!(
96 output.status.success(),
97 "native MCP server failed: {stderr}"
98 );
99 (responses, stderr)
100 }
101 }
102
103 fn codewhale_binary() -> PathBuf {
104 if let Some(path) = std::env::var_os("CARGO_BIN_EXE_codewhale").filter(|v| !v.is_empty()) {
105 return PathBuf::from(path);
106 }
107 if let Some(path) = option_env!("CARGO_BIN_EXE_codewhale") {
108 return PathBuf::from(path);
109 }
110 let mut path = std::env::current_exe().expect("current test executable path");
111 path.pop();
112 if path.ends_with("deps") {
113 path.pop();
114 }
115 path.join("codewhale")
116 }
117
118 fn initialize() -> Value {
119 json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {
120 "protocolVersion": "2024-11-05",
121 "clientInfo": {"name": "native-alias-test", "version": "1"},
122 "capabilities": {}
123 }})
124 }
125
126 #[test]
127 fn both_cli_spellings_expose_the_same_native_read_only_tools() {
128 let fixture = Fixture::new();
129 let requests = [
130 initialize(),
131 json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
132 json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}),
133 json!({"jsonrpc": "2.0", "id": 2, "method": "ping"}),
134 json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {
135 "name": "file_write", "approved": true,
136 "arguments": {"path": "forbidden.txt", "content": "must not be written"}
137 }}),
138 ];
139 let (alias, _) = fixture.run_mcp_server(&["mcp-server"], &requests);
140 let (native, _) = fixture.run_mcp_server(&["serve", "--mcp"], &requests);
141 assert_eq!(alias, native);
142 assert_eq!(alias.len(), 4);
143 assert_eq!(
144 alias[0]["result"]["serverInfo"]["name"],
145 "codewhale-mcp-server"
146 );
147 assert_eq!(alias[0]["result"]["protocolVersion"], "2024-11-05");
148 let names: Vec<&str> = alias[1]["result"]["tools"]
149 .as_array()
150 .unwrap()
151 .iter()
152 .map(|tool| tool["name"].as_str().unwrap())
153 .collect();
154 assert_eq!(names, ["file_read", "search"]);
155 assert_eq!(alias[2]["result"], json!({}));
156 assert_eq!(alias[3]["error"]["code"], -32602);
157 assert!(!fixture.home.join("forbidden.txt").exists());
158 }
159
160 #[test]
161 fn alias_neither_launches_nor_rewrites_legacy_child_server_definitions() {
162 let fixture = Fixture::new();
163 let marker = fixture.home.join("legacy-child-was-launched");
164 // Even an invalid executable would produce a visible startup failure in
165 // the old proxy. The native server must never attempt this launch.
166 fixture.configure_servers(json!([{"config": {
167 "name": "retired-proxy", "command": marker,
168 "env": {"PRIVATE_TOKEN": "test-only-sentinel"}
169 }}]));
170 let config = fixture.home.join(".codewhale/config.toml");
171 let before = fs::read(&config).unwrap();
172 let (responses, stderr) = fixture.run_mcp_server(
173 &["mcp-server"],
174 &[
175 initialize(),
176 json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
177 json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}),
178 ],
179 );
180 assert_eq!(responses.len(), 2);
181 assert_eq!(responses[1]["result"]["tools"].as_array().unwrap().len(), 2);
182 assert_eq!(
183 fs::read(config).unwrap(),
184 before,
185 "saved legacy data is untouched"
186 );
187 assert!(!stderr.contains("retired-proxy"), "{stderr}");
188 assert!(!stderr.contains("PRIVATE_TOKEN"), "{stderr}");
189 assert!(!stderr.contains("test-only-sentinel"), "{stderr}");
190 assert!(!marker.exists());
191 }
192
192 lines RUST