Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/tests/mcp.rs

20.2 KiB, 1 run

created by r1870400018:79731, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1#![cfg(feature = "async")]
2//! The MCP client against a fixture server: this test's own binary, run again as the child with
3//! `MCP_FIXTURE` set (stdio), or served here over HTTP on loopback and on a Unix socket. No
4//! harness, so the child's stdout carries only the protocol.
5
6use oxedyne_fe2o3_core::prelude::*;
7use oxedyne_fe2o3_jdat::{
8 prelude::*,
9 bdat::limits::DecodeLimits,
10};
11use oxedyne_fe2o3_net::{
12 http::loc::Url,
13 mcp::{
14 Client,
15 Content,
16 Limits,
17 Transport,
18 },
19};
20
21use std::{
22 io::{
23 BufRead,
24 Write,
25 },
26 path::PathBuf,
27 sync::{
28 Arc,
29 atomic::{
30 AtomicU64,
31 Ordering,
32 },
33 },
34 time::{
35 Duration,
36 Instant,
37 },
38};
39
40use tokio::{
41 io::{
42 AsyncRead,
43 AsyncReadExt,
44 AsyncWrite,
45 AsyncWriteExt,
46 },
47 net::{
48 TcpListener,
49 UnixListener,
50 },
51 process::Command,
52};
53
54
55const MODE: &str = "MCP_FIXTURE";
56const WAIT: Duration = Duration::from_secs(10);
57
58fn main() {
59 if let Ok(mode) = std::env::var(MODE) {
60 return fixture(&mode);
61 }
62 let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
63 Ok(rt) => rt,
64 Err(e) => { eprintln!("no runtime: {}", e); std::process::exit(1) },
65 };
66 let mut failed = 0;
67 let mut check = |name: &str, r: Outcome<()>| match r {
68 Ok(()) => println!("test {} ... ok", name),
69 Err(e) => { println!("test {} ... FAILED\n{}", name, e); failed += 1; },
70 };
71 check("stdio_tools_resources_prompts", rt.block_on(stdio_whole()));
72 check("stdio_hung_call_times_out_in_words", rt.block_on(stdio_hung()));
73 check("stdio_list_changed_is_noted", rt.block_on(stdio_changed()));
74 check("stdio_server_that_ends_fails_its_calls", rt.block_on(stdio_dies()));
75 check("stdio_line_over_max_is_dropped", rt.block_on(stdio_long()));
76 check("stdio_stderr_is_capped", rt.block_on(stdio_stderr()));
77 check("stdio_stderr_is_written_while_the_server_runs", rt.block_on(stdio_stderr_live()));
78 check("stdio_mute_server_times_out_at_start", rt.block_on(stdio_mute()));
79 check("stdio_missing_program_refused", rt.block_on(stdio_missing()));
80 check("http_session_and_event_stream", rt.block_on(http_whole(false)));
81 check("http_through_a_unix_socket", rt.block_on(http_whole(true)));
82 println!("\ntest result: {}. {} failed", if failed == 0 { "ok" } else { "FAILED" }, failed);
83 std::process::exit(if failed == 0 { 0 } else { 1 });
84}
85
86fn limits() -> Limits {
87 Limits { line_max: 65536, stderr_max: 4096, wait: WAIT }
88}
89
90fn scratch(name: &str) -> PathBuf {
91 let d = std::env::temp_dir().join(fmt!("fe2o3_mcp_{}_{}", std::process::id(), name));
92 let _ = std::fs::create_dir_all(&d);
93 d
94}
95
96async fn stdio(mode: &str, lim: &Limits, stderr: Option<PathBuf>) -> Outcome<Client> {
97 let mut cmd = Command::new(res!(std::env::current_exe()));
98 cmd.env_clear().env(MODE, mode);
99 Client::connect(Transport::Stdio { cmd, stderr }, lim, "fe2o3-test", "1").await
100}
101
102fn want(ok: bool, what: &str) -> Outcome<()> {
103 match ok {
104 true => Ok(()),
105 false => Err(err!("{}", what; Test)),
106 }
107}
108
109fn first_text(c: &[Content]) -> String {
110 match c.first() {
111 Some(Content::Text(t)) => t.clone(),
112 _ => String::new(),
113 }
114}
115
116// ┌───────────────────────────────────────────────────────────────────────────┐
117// │ STDIO │
118// └───────────────────────────────────────────────────────────────────────────┘
119
120async fn stdio_whole() -> Outcome<()> {
121 let err = scratch("whole").join("stderr");
122 let c = res!(stdio("serve", &limits(), Some(err.clone())).await);
123 res!(want(c.server.name == "fixture" && c.server.tools && c.server.resources && c.server.prompts,
124 &fmt!("server {:?}", c.server)));
125 res!(want(c.server.instructions == "Use the echo tool.", "instructions"));
126 // Two pages, and the server's ping answered before the second.
127 let tools = res!(c.tools(10, WAIT).await);
128 let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
129 res!(want(names == ["echo", "fail", "hang", "change", "die", "long"], &fmt!("tools {:?}", names)));
130 res!(want(tools[0].read_only && !tools[1].read_only, "readOnlyHint"));
131 res!(want(res!(c.tools(2, WAIT).await).len() == 2, "tools capped at max"));
132 let r = res!(c.call("echo", "{\"text\":\"cobalt\"}", WAIT).await);
133 res!(want(!r.error && first_text(&r.content) == "echo: cobalt", &fmt!("echo {:?}", r)));
134 let r = res!(c.call("fail", "{}", WAIT).await);
135 res!(want(r.error && first_text(&r.content) == "it failed", &fmt!("fail {:?}", r)));
136 let e = c.call("nosuch", "{}", WAIT).await;
137 res!(want(matches!(&e, Err(e) if e.to_string().contains("refused tools/call (-32602)")), &fmt!("unknown tool {:?}", e)));
138 let rs = res!(c.resources(10, WAIT).await);
139 res!(want(rs.len() == 1 && rs[0].uri == "fixture://a" && rs[0].mime == "text/plain", &fmt!("resources {:?}", rs)));
140 let got = res!(c.read("fixture://a", WAIT).await);
141 res!(want(matches!(got.first(), Some(Content::Resource { text: Some(t), .. }) if t == "alpha"), &fmt!("read {:?}", got)));
142 let ps = res!(c.prompts(10, WAIT).await);
143 res!(want(ps.len() == 1 && ps[0].name == "greet" && ps[0].arguments == [("who".to_string(), "Whom".to_string(), true)],
144 &fmt!("prompts {:?}", ps)));
145 let m = res!(c.prompt("greet", "{\"who\":\"Ada\"}", WAIT).await);
146 res!(want(m == [("user".to_string(), Content::Text("Hello, Ada.".to_string()))], &fmt!("prompt {:?}", m)));
147 c.close(Duration::from_secs(2)).await;
148 let kept = std::fs::read_to_string(&err).unwrap_or_default();
149 want(kept.starts_with("fixture starting"), &fmt!("stderr kept {:?}", kept))
150}
151
152async fn stdio_hung() -> Outcome<()> {
153 let c = res!(stdio("serve", &limits(), None).await);
154 let t = Instant::now();
155 let e = c.call("hang", "{}", Duration::from_millis(300)).await;
156 res!(want(t.elapsed() < Duration::from_secs(3), "the wait was bounded"));
157 res!(want(matches!(&e, Err(e) if e.to_string().contains("did not answer tools/call within 300 ms")), &fmt!("hang {:?}", e)));
158 // The server lives on and answers the next call; it heard the cancellation.
159 let r = res!(c.call("echo", "{\"text\":\"after\"}", WAIT).await);
160 want(first_text(&r.content) == "echo: after (cancelled 1)", &fmt!("after {:?}", r))
161}
162
163async fn stdio_changed() -> Outcome<()> {
164 let c = res!(stdio("serve", &limits(), None).await);
165 res!(want(!c.changed(), "unchanged at start"));
166 res!(c.call("change", "{}", WAIT).await);
167 res!(want(c.changed(), "list_changed noted"));
168 res!(c.tools(10, WAIT).await);
169 want(!c.changed(), "cleared by listing")
170}
171
172async fn stdio_dies() -> Outcome<()> {
173 let err = scratch("dies").join("stderr");
174 let c = res!(stdio("serve", &limits(), Some(err.clone())).await);
175 let e = c.call("die", "{}", WAIT).await;
176 res!(want(matches!(&e, Err(e) if e.to_string().contains("ended its output")), &fmt!("die {:?}", e)));
177 res!(want(c.ended().is_some_and(|w| w.contains(&err.display().to_string())), &fmt!("ended {:?}", c.ended())));
178 let t = Instant::now();
179 let e = c.call("echo", "{\"text\":\"x\"}", WAIT).await;
180 want(e.is_err() && t.elapsed() < Duration::from_secs(1), &fmt!("after death {:?}", e))
181}
182
183async fn stdio_long() -> Outcome<()> {
184 let lim = Limits { line_max: 4096, ..limits() };
185 let c = res!(stdio("serve", &lim, None).await);
186 let r = res!(c.call("long", "{}", WAIT).await);
187 want(first_text(&r.content) == "after the long line", &fmt!("long {:?}", r))
188}
189
190async fn stdio_stderr() -> Outcome<()> {
191 let err = scratch("loud").join("stderr");
192 let lim = Limits { stderr_max: 100, ..limits() };
193 let c = res!(stdio("loud", &lim, Some(err.clone())).await);
194 res!(c.call("echo", "{\"text\":\"x\"}", WAIT).await);
195 c.close(Duration::from_secs(2)).await;
196 let kept = std::fs::read_to_string(&err).unwrap_or_default();
197 want(kept.len() < 160 && kept.contains("[stderr cut at 100 bytes]"), &fmt!("kept {} bytes: {:?}", kept.len(), kept))
198}
199
200async fn stdio_stderr_live() -> Outcome<()> {
201 let err = scratch("serve").join("stderr");
202 let c = res!(stdio("serve", &limits(), Some(err.clone())).await);
203 res!(c.call("echo", "{\"text\":\"x\"}", WAIT).await);
204 let kept = std::fs::read_to_string(&err).unwrap_or_default();
205 c.close(Duration::from_secs(2)).await;
206 want(kept.starts_with("fixture starting"), &fmt!("kept while running: {:?}", kept))
207}
208
209async fn stdio_mute() -> Outcome<()> {
210 let lim = Limits { wait: Duration::from_millis(400), ..limits() };
211 let t = Instant::now();
212 let e = stdio("mute", &lim, None).await;
213 res!(want(t.elapsed() < Duration::from_secs(3), "bounded"));
214 want(matches!(&e, Err(e) if e.to_string().contains("did not answer initialize within 400 ms")),
215 &fmt!("mute {:?}", e.err()))
216}
217
218async fn stdio_missing() -> Outcome<()> {
219 let cmd = Command::new("/nonexistent/mcp-server");
220 let e = Client::connect(Transport::Stdio { cmd, stderr: None }, &limits(), "t", "1").await;
221 want(matches!(&e, Err(e) if e.to_string().contains("did not start")), &fmt!("missing {:?}", e.err()))
222}
223
224// ┌───────────────────────────────────────────────────────────────────────────┐
225// │ HTTP │
226// └───────────────────────────────────────────────────────────────────────────┘
227
228async fn http_whole(unix: bool) -> Outcome<()> {
229 let state = Arc::new(AtomicU64::new(0));
230 let (url, via) = match unix {
231 false => {
232 let l = res!(TcpListener::bind("127.0.0.1:0").await);
233 let port = res!(l.local_addr()).port();
234 let s = state.clone();
235 tokio::spawn(async move { while let Ok((c, _)) = l.accept().await { tokio::spawn(http_one(c, s.clone())); } });
236 (res!(Url::parse(&fmt!("http://127.0.0.1:{}/mcp", port))), None)
237 },
238 true => {
239 let sock = scratch("unix").join("proxy.sock");
240 let _ = std::fs::remove_file(&sock);
241 let l = res!(UnixListener::bind(&sock));
242 let s = state.clone();
243 tokio::spawn(async move { while let Ok((c, _)) = l.accept().await { tokio::spawn(http_one(c, s.clone())); } });
244 (res!(Url::parse("https://mcp.example.com/mcp")), Some(sock))
245 },
246 };
247 let headers = vec![("X-Fixture".to_string(), "yes".to_string())];
248 let c = res!(Client::connect(Transport::Http { url, headers, via, tls: None }, &limits(), "t", "1").await);
249 res!(want(c.server.name == "fixture", "http server"));
250 let tools = res!(c.tools(10, WAIT).await);
251 res!(want(tools.len() == 6, &fmt!("http tools {}", tools.len())));
252 let r = res!(c.call("echo", "{\"text\":\"over http\"}", WAIT).await);
253 res!(want(first_text(&r.content) == "echo: over http", &fmt!("http echo {:?}", r)));
254 res!(want(c.changed(), "a notification in the event stream is heard"));
255 let got = res!(c.read("fixture://a", WAIT).await);
256 res!(want(matches!(got.first(), Some(Content::Resource { text: Some(t), .. }) if t == "alpha"), "http read"));
257 c.close(Duration::from_secs(2)).await;
258 want(state.load(Ordering::Relaxed) == 1, "the session was deleted")
259}
260
261// One HTTP request: every request after `initialize` must carry the session and the revision.
262async fn http_one<S: AsyncRead + AsyncWrite + Unpin>(mut c: S, deleted: Arc<AtomicU64>) {
263 let mut buf = Vec::new();
264 let mut b = [0u8; 4096];
265 let (head, body) = loop {
266 match c.read(&mut b).await {
267 Ok(0) | Err(_) => return,
268 Ok(n) => buf.extend_from_slice(&b[..n]),
269 }
270 let text = String::from_utf8_lossy(&buf).to_string();
271 if let Some(i) = text.find("\r\n\r\n") {
272 let head = text[..i].to_ascii_lowercase();
273 let len = head.lines().find_map(|l| l.strip_prefix("content-length: ")).and_then(|v| v.trim().parse().ok()).unwrap_or(0);
274 if buf.len() >= i + 4 + len {
275 break (head, String::from_utf8_lossy(&buf[i + 4..i + 4 + len]).to_string());
276 }
277 }
278 };
279 let field = |n: &str| head.lines().find_map(|l| l.strip_prefix(n)).map(|v| v.trim().to_string()).unwrap_or_default();
280 let reply = |status: &str, kind: &str, extra: &str, body: &str| fmt!("HTTP/1.1 {}\r\nContent-Type: {}\r\n{}Content-Length: {}\r\n\
281 Connection: close\r\n\r\n{}", status, kind, extra, body.len(), body);
282 if head.starts_with("delete ") {
283 if field("mcp-session-id:") == "s-1" { deleted.fetch_add(1, Ordering::Relaxed); }
284 let _ = c.write_all(reply("200 OK", "text/plain", "", "").as_bytes()).await;
285 return;
286 }
287 let msg = match Dat::decode_json_strict(&body, &DecodeLimits::default()) {
288 Ok(m) => m,
289 Err(_) => return,
290 };
291 let method = msg.map_get_string(&dat!("method")).unwrap_or_default();
292 let ok = field("x-fixture:") == "yes" && field("accept:").contains("text/event-stream")
293 && (method == "initialize" || (field("mcp-session-id:") == "s-1" && field("mcp-protocol-version:") == "2025-06-18"));
294 let out = match (ok, answer(&msg, &mut Fixture::default())) {
295 (false, _) => reply("400 Bad Request", "text/plain", "", "no session"),
296 (true, v) if v.is_empty() => reply("202 Accepted", "text/plain", "", ""),
297 (true, v) if method == "tools/call" => {
298 let mut ev = String::from("data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}\n\n");
299 for m in v { ev.push_str(&fmt!("event: message\ndata: {}\n\n", m)); }
300 reply("200 OK", "text/event-stream", "", &ev)
301 },
302 (true, v) => reply("200 OK", "application/json", if method == "initialize" { "Mcp-Session-Id: s-1\r\n" } else { "" },
303 &v.join("")),
304 };
305 let _ = c.write_all(out.as_bytes()).await;
306}
307
308// ┌───────────────────────────────────────────────────────────────────────────┐
309// │ THE FIXTURE SERVER │
310// └───────────────────────────────────────────────────────────────────────────┘
311
312#[derive(Default)]
313struct Fixture {
314 cancelled: u64,
315}
316
317fn fixture(mode: &str) {
318 eprintln!("fixture starting");
319 if mode == "loud" {
320 eprintln!("{}", "x".repeat(10_000));
321 }
322 let stdin = std::io::stdin();
323 let mut out = std::io::stdout();
324 let mut f = Fixture::default();
325 let mut lines = stdin.lock().lines();
326 while let Some(Ok(l)) = lines.next() {
327 if mode == "mute" {
328 continue;
329 }
330 let msg = match Dat::decode_json_strict(&l, &DecodeLimits::default()) {
331 Ok(m) => m,
332 Err(_) => continue,
333 };
334 let method = msg.map_get_string(&dat!("method")).unwrap_or_default();
335 let call = tool_of(&msg);
336 // The server's own request of the client, answered before the second page.
337 if method == "tools/list" && msg.map_get(&dat!("params")).ok().flatten().and_then(|p| p.map_get(&dat!("cursor")).ok().flatten()).is_some() {
338 let _ = writeln!(out, "{{\"jsonrpc\":\"2.0\",\"id\":\"s-ping\",\"method\":\"ping\"}}");
339 let _ = out.flush();
340 match lines.next() {
341 Some(Ok(r)) if r.contains("\"s-ping\"") && r.contains("\"result\":{}") => (),
342 _ => return,
343 }
344 }
345 match call.as_str() {
346 "hang" => continue,
347 "die" => std::process::exit(3),
348 "change" => { let _ = writeln!(out, "{{\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}}"); },
349 "long" => { let _ = writeln!(out, "{}", "y".repeat(10_000)); },
350 _ => (),
351 }
352 for r in answer(&msg, &mut f) {
353 let _ = writeln!(out, "{}", r);
354 }
355 let _ = out.flush();
356 }
357}
358
359fn tool_of(msg: &Dat) -> String {
360 msg.map_get(&dat!("params")).ok().flatten().and_then(|p| p.map_get_string(&dat!("name")).ok()).unwrap_or_default()
361}
362
363// The fixture's answers to one message, none for a notification.
364fn answer(msg: &Dat, f: &mut Fixture) -> Vec<String> {
365 let method = msg.map_get_string(&dat!("method")).unwrap_or_default();
366 let id = match msg.map_get(&dat!("id")) {
367 Ok(Some(id)) => id.json_canonical().unwrap_or_default(),
368 _ => {
369 if method == "notifications/cancelled" { f.cancelled += 1; }
370 return Vec::new();
371 },
372 };
373 let params = msg.map_get(&dat!("params")).ok().flatten().cloned().unwrap_or_else(|| mapdat!{});
374 let tool = |n: &str, ro: bool| fmt!("{{\"name\":\"{}\",\"description\":\"The {} tool.\",\"inputSchema\":{{\"type\":\"object\"}},\
375 \"annotations\":{{\"readOnlyHint\":{}}}}}", n, n, ro);
376 let result = match method.as_str() {
377 "initialize" => "{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{\"tools\":{\"listChanged\":true},\"resources\":{},\
378 \"prompts\":{}},\"serverInfo\":{\"name\":\"fixture\",\"version\":\"1\"},\"instructions\":\"Use the echo tool.\"}".to_string(),
379 "tools/list" => match params.map_get(&dat!("cursor")).ok().flatten() {
380 None => fmt!("{{\"tools\":[{},{}],\"nextCursor\":\"p2\"}}", tool("echo", true), tool("fail", false)),
381 Some(_) => fmt!("{{\"tools\":[{},{},{},{}]}}", tool("hang", false), tool("change", false), tool("die", false), tool("long", true)),
382 },
383 "tools/call" => {
384 let args = params.map_get(&dat!("arguments")).ok().flatten().cloned().unwrap_or_else(|| mapdat!{});
385 let said = |t: &str, e: bool| fmt!("{{\"content\":[{{\"type\":\"text\",\"text\":{}}}],\"isError\":{}}}",
386 Dat::Str(t.to_string()).json_canonical().unwrap_or_default(), e);
387 match tool_of(msg).as_str() {
388 "echo" => {
389 let t = args.map_get_string(&dat!("text")).unwrap_or_default();
390 match f.cancelled {
391 0 => said(&fmt!("echo: {}", t), false),
392 n => said(&fmt!("echo: {} (cancelled {})", t, n), false),
393 }
394 },
395 "fail" => said("it failed", true),
396 "change" => said("changed", false),
397 "long" => said("after the long line", false),
398 n => return vec![fmt!("{{\"jsonrpc\":\"2.0\",\"id\":{},\"error\":{{\"code\":-32602,\"message\":\"Unknown tool: {}\"}}}}", id, n)],
399 }
400 },
401 "resources/list" => "{\"resources\":[{\"uri\":\"fixture://a\",\"name\":\"a\",\"mimeType\":\"text/plain\"}]}".to_string(),
402 "resources/read" => "{\"contents\":[{\"uri\":\"fixture://a\",\"mimeType\":\"text/plain\",\"text\":\"alpha\"}]}".to_string(),
403 "prompts/list" => "{\"prompts\":[{\"name\":\"greet\",\"arguments\":[{\"name\":\"who\",\"description\":\"Whom\",\"required\":true}]}]}".to_string(),
404 "prompts/get" => {
405 let who = params.map_get(&dat!("arguments")).ok().flatten().and_then(|a| a.map_get_string(&dat!("who")).ok()).unwrap_or_default();
406 fmt!("{{\"messages\":[{{\"role\":\"user\",\"content\":{{\"type\":\"text\",\"text\":\"Hello, {}.\"}}}}]}}", who)
407 },
408 m => return vec![fmt!("{{\"jsonrpc\":\"2.0\",\"id\":{},\"error\":{{\"code\":-32601,\"message\":\"No {}\"}}}}", id, m)],
409 };
410 vec![fmt!("{{\"jsonrpc\":\"2.0\",\"id\":{},\"result\":{}}}", id, result)]
411}