|
| 1 | +//! Wire-level acceptance for request-scoped progress on the 2026 path. |
| 2 | +//! |
| 3 | +//! Progress §Behavior: "Progress notifications MUST only reference tokens |
| 4 | +//! that: Were provided in an active request; Are associated with an |
| 5 | +//! in-progress operation." The caller opts in via `_meta.progressToken`; |
| 6 | +//! a request without one gets no `notifications/progress`, and the echoed |
| 7 | +//! token preserves the caller's JSON type (string or number). |
| 8 | +//! |
| 9 | +//! Built only under the 2026 feature; compiles to nothing under 2025-11-25. |
| 10 | +#![cfg(feature = "protocol-2026-07-28")] |
| 11 | + |
| 12 | +use std::time::Duration; |
| 13 | + |
| 14 | +use futures::StreamExt; |
| 15 | +use turul_mcp_derive::McpTool; |
| 16 | +use turul_mcp_server::prelude::*; |
| 17 | + |
| 18 | +/// Emits one request-scoped progress notification mid-execution. |
| 19 | +#[derive(McpTool, Clone, Default)] |
| 20 | +#[tool(name = "worker", description = "Works with progress", output = String)] |
| 21 | +struct WorkerTool {} |
| 22 | + |
| 23 | +impl WorkerTool { |
| 24 | + async fn execute(&self, session: Option<SessionContext>) -> McpResult<String> { |
| 25 | + if let Some(session) = session { |
| 26 | + session.notify_request_progress(0.5, Some(1.0)).await; |
| 27 | + } |
| 28 | + Ok("done".to_string()) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +async fn start_server() -> String { |
| 33 | + let port = std::net::TcpListener::bind("127.0.0.1:0") |
| 34 | + .unwrap() |
| 35 | + .local_addr() |
| 36 | + .unwrap() |
| 37 | + .port(); |
| 38 | + |
| 39 | + let server = McpServer::builder() |
| 40 | + .name("progress-2026-test") |
| 41 | + .version("0.4.0") |
| 42 | + .tool(WorkerTool::default()) |
| 43 | + .bind_address(format!("127.0.0.1:{port}").parse().unwrap()) |
| 44 | + .build() |
| 45 | + .expect("build 2026 server"); |
| 46 | + |
| 47 | + tokio::spawn(async move { |
| 48 | + server.run().await.ok(); |
| 49 | + }); |
| 50 | + |
| 51 | + let url = format!("http://127.0.0.1:{port}/mcp"); |
| 52 | + let client = reqwest::Client::new(); |
| 53 | + for _ in 0..50 { |
| 54 | + if client.get(&url).send().await.is_ok() { |
| 55 | + break; |
| 56 | + } |
| 57 | + tokio::time::sleep(Duration::from_millis(20)).await; |
| 58 | + } |
| 59 | + url |
| 60 | +} |
| 61 | + |
| 62 | +/// POST a `worker` tools/call with SSE framing; return every `data:` JSON |
| 63 | +/// payload observed on the response stream. |
| 64 | +async fn call_worker( |
| 65 | + url: &str, |
| 66 | + progress_token: Option<serde_json::Value>, |
| 67 | +) -> Vec<serde_json::Value> { |
| 68 | + let mut meta = serde_json::json!({ |
| 69 | + "io.modelcontextprotocol/protocolVersion": "2026-07-28", |
| 70 | + "io.modelcontextprotocol/clientInfo": { "name": "test-client", "version": "1.0.0" }, |
| 71 | + "io.modelcontextprotocol/clientCapabilities": {} |
| 72 | + }); |
| 73 | + if let (Some(m), Some(token)) = (meta.as_object_mut(), progress_token) { |
| 74 | + m.insert("progressToken".to_string(), token); |
| 75 | + } |
| 76 | + |
| 77 | + let client = reqwest::Client::new(); |
| 78 | + let resp = client |
| 79 | + .post(url) |
| 80 | + .header("Accept", "application/json, text/event-stream") |
| 81 | + .header("MCP-Protocol-Version", "2026-07-28") |
| 82 | + .header("Mcp-Method", "tools/call") |
| 83 | + .header("Mcp-Name", "worker") |
| 84 | + .json(&serde_json::json!({ |
| 85 | + "jsonrpc": "2.0", "id": 1, "method": "tools/call", |
| 86 | + "params": { "name": "worker", "arguments": {}, "_meta": meta } |
| 87 | + })) |
| 88 | + .send() |
| 89 | + .await |
| 90 | + .expect("worker POST"); |
| 91 | + assert_eq!(resp.status(), 200); |
| 92 | + |
| 93 | + let mut events = Vec::new(); |
| 94 | + let mut buffer = String::new(); |
| 95 | + let mut stream = resp.bytes_stream(); |
| 96 | + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); |
| 97 | + loop { |
| 98 | + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); |
| 99 | + if remaining.is_zero() { |
| 100 | + break; |
| 101 | + } |
| 102 | + match tokio::time::timeout(remaining, stream.next()).await { |
| 103 | + Ok(Some(Ok(chunk))) => buffer.push_str(&String::from_utf8_lossy(&chunk)), |
| 104 | + _ => break, |
| 105 | + } |
| 106 | + let mut done = false; |
| 107 | + while let Some(pos) = buffer.find("\n\n") { |
| 108 | + let event: String = buffer.drain(..pos + 2).collect(); |
| 109 | + for line in event.lines() { |
| 110 | + if let Some(data) = line.strip_prefix("data: ") |
| 111 | + && let Ok(json) = serde_json::from_str::<serde_json::Value>(data) |
| 112 | + { |
| 113 | + if json.get("result").is_some() || json.get("error").is_some() { |
| 114 | + done = true; |
| 115 | + } |
| 116 | + events.push(json); |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + if done { |
| 121 | + break; |
| 122 | + } |
| 123 | + } |
| 124 | + events |
| 125 | +} |
| 126 | + |
| 127 | +fn progress_notifications(events: &[serde_json::Value]) -> Vec<&serde_json::Value> { |
| 128 | + events |
| 129 | + .iter() |
| 130 | + .filter(|e| e["method"] == "notifications/progress") |
| 131 | + .collect() |
| 132 | +} |
| 133 | + |
| 134 | +#[tokio::test] |
| 135 | +async fn progress_echoes_the_request_string_token() { |
| 136 | + let url = start_server().await; |
| 137 | + let events = call_worker(&url, Some(serde_json::json!("tok-1"))).await; |
| 138 | + let progress = progress_notifications(&events); |
| 139 | + assert!( |
| 140 | + !progress.is_empty(), |
| 141 | + "a declared progressToken must opt in to notifications/progress: {events:?}" |
| 142 | + ); |
| 143 | + assert_eq!( |
| 144 | + progress[0]["params"]["progressToken"], |
| 145 | + serde_json::json!("tok-1"), |
| 146 | + "the notification must reference the REQUEST's token: {progress:?}" |
| 147 | + ); |
| 148 | + assert_eq!(progress[0]["params"]["progress"], serde_json::json!(0.5)); |
| 149 | + assert_eq!(progress[0]["params"]["total"], serde_json::json!(1.0)); |
| 150 | +} |
| 151 | + |
| 152 | +#[tokio::test] |
| 153 | +async fn progress_preserves_a_numeric_token() { |
| 154 | + let url = start_server().await; |
| 155 | + let events = call_worker(&url, Some(serde_json::json!(7))).await; |
| 156 | + let progress = progress_notifications(&events); |
| 157 | + assert!(!progress.is_empty(), "{events:?}"); |
| 158 | + assert_eq!( |
| 159 | + progress[0]["params"]["progressToken"], |
| 160 | + serde_json::json!(7), |
| 161 | + "a numeric token must round-trip as a JSON number: {progress:?}" |
| 162 | + ); |
| 163 | +} |
| 164 | + |
| 165 | +#[tokio::test] |
| 166 | +async fn no_token_means_no_progress_notifications() { |
| 167 | + let url = start_server().await; |
| 168 | + let events = call_worker(&url, None).await; |
| 169 | + assert!( |
| 170 | + !events.is_empty(), |
| 171 | + "the final response must arrive on the stream" |
| 172 | + ); |
| 173 | + assert!( |
| 174 | + progress_notifications(&events).is_empty(), |
| 175 | + "MUST only reference tokens provided in an active request — no token, \ |
| 176 | + no notifications/progress: {events:?}" |
| 177 | + ); |
| 178 | +} |
| 179 | + |
| 180 | +/// A numeric progressToken must survive the typed params parse. |
| 181 | +#[test] |
| 182 | +fn numeric_token_parses_into_call_params() { |
| 183 | + let params = serde_json::json!({ |
| 184 | + "name": "worker", "arguments": {}, |
| 185 | + "_meta": { |
| 186 | + "io.modelcontextprotocol/protocolVersion": "2026-07-28", |
| 187 | + "io.modelcontextprotocol/clientInfo": { "name": "t", "version": "1" }, |
| 188 | + "io.modelcontextprotocol/clientCapabilities": {}, |
| 189 | + "progressToken": 7 |
| 190 | + } |
| 191 | + }); |
| 192 | + let typed: turul_mcp_protocol::tools::CallToolRequestParams = |
| 193 | + serde_json::from_value(params).expect("parse"); |
| 194 | + assert!( |
| 195 | + typed.meta.progress_token.is_some(), |
| 196 | + "numeric progressToken must survive the typed parse: {:?}", |
| 197 | + typed.meta |
| 198 | + ); |
| 199 | +} |
0 commit comments