|
| 1 | +//! Wire-level acceptance for per-request log gating (2026-07-28). |
| 2 | +//! |
| 3 | +//! `RequestMetaObject.logLevel`: "If absent, the server MUST NOT send any |
| 4 | +//! `notifications/message` notifications for this request. The client opts in |
| 5 | +//! to log messages by explicitly setting a level. Replaces the former |
| 6 | +//! `logging/setLevel` RPC." |
| 7 | +//! |
| 8 | +//! Built only under the 2026 feature; compiles to nothing under 2025-11-25. |
| 9 | +#![cfg(feature = "protocol-2026-07-28")] |
| 10 | + |
| 11 | +use std::time::Duration; |
| 12 | + |
| 13 | +use futures::StreamExt; |
| 14 | +use turul_mcp_derive::McpTool; |
| 15 | +use turul_mcp_server::prelude::*; |
| 16 | + |
| 17 | +/// Emits one info-level `notifications/message` mid-execution, then returns. |
| 18 | +#[derive(McpTool, Clone, Default)] |
| 19 | +#[tool(name = "chatty", description = "Logs while working", output = String)] |
| 20 | +struct ChattyTool {} |
| 21 | + |
| 22 | +impl ChattyTool { |
| 23 | + async fn execute(&self, session: Option<SessionContext>) -> McpResult<String> { |
| 24 | + if let Some(session) = session { |
| 25 | + session |
| 26 | + .notify_log( |
| 27 | + turul_mcp_protocol::logging::LoggingLevel::Info, |
| 28 | + serde_json::json!("working..."), |
| 29 | + Some("chatty".to_string()), |
| 30 | + None, |
| 31 | + ) |
| 32 | + .await; |
| 33 | + } |
| 34 | + Ok("done".to_string()) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +async fn start_server() -> String { |
| 39 | + let port = std::net::TcpListener::bind("127.0.0.1:0") |
| 40 | + .unwrap() |
| 41 | + .local_addr() |
| 42 | + .unwrap() |
| 43 | + .port(); |
| 44 | + |
| 45 | + let server = McpServer::builder() |
| 46 | + .name("loggate-2026-test") |
| 47 | + .version("0.4.0") |
| 48 | + .tool(ChattyTool::default()) |
| 49 | + .bind_address(format!("127.0.0.1:{port}").parse().unwrap()) |
| 50 | + .build() |
| 51 | + .expect("build 2026 server"); |
| 52 | + |
| 53 | + tokio::spawn(async move { |
| 54 | + server.run().await.ok(); |
| 55 | + }); |
| 56 | + |
| 57 | + let url = format!("http://127.0.0.1:{port}/mcp"); |
| 58 | + let client = reqwest::Client::new(); |
| 59 | + for _ in 0..50 { |
| 60 | + if client.get(&url).send().await.is_ok() { |
| 61 | + break; |
| 62 | + } |
| 63 | + tokio::time::sleep(Duration::from_millis(20)).await; |
| 64 | + } |
| 65 | + url |
| 66 | +} |
| 67 | + |
| 68 | +/// POST a `chatty` tools/call with SSE framing; return every `data:` JSON |
| 69 | +/// payload observed on the response stream. |
| 70 | +async fn call_chatty(url: &str, log_level: Option<&str>) -> Vec<serde_json::Value> { |
| 71 | + let mut meta = serde_json::json!({ |
| 72 | + "io.modelcontextprotocol/protocolVersion": "2026-07-28", |
| 73 | + "io.modelcontextprotocol/clientInfo": { "name": "test-client", "version": "1.0.0" }, |
| 74 | + "io.modelcontextprotocol/clientCapabilities": {} |
| 75 | + }); |
| 76 | + if let (Some(m), Some(level)) = (meta.as_object_mut(), log_level) { |
| 77 | + m.insert( |
| 78 | + "io.modelcontextprotocol/logLevel".to_string(), |
| 79 | + serde_json::json!(level), |
| 80 | + ); |
| 81 | + } |
| 82 | + |
| 83 | + let client = reqwest::Client::new(); |
| 84 | + let resp = client |
| 85 | + .post(url) |
| 86 | + // Both media types accepted → tools/call gets the SSE framing, which |
| 87 | + // is where request-scoped notifications ride. |
| 88 | + .header("Accept", "application/json, text/event-stream") |
| 89 | + .header("MCP-Protocol-Version", "2026-07-28") |
| 90 | + .header("Mcp-Method", "tools/call") |
| 91 | + .header("Mcp-Name", "chatty") |
| 92 | + .json(&serde_json::json!({ |
| 93 | + "jsonrpc": "2.0", "id": 1, "method": "tools/call", |
| 94 | + "params": { "name": "chatty", "arguments": {}, "_meta": meta } |
| 95 | + })) |
| 96 | + .send() |
| 97 | + .await |
| 98 | + .expect("chatty POST"); |
| 99 | + assert_eq!(resp.status(), 200); |
| 100 | + |
| 101 | + let mut events = Vec::new(); |
| 102 | + let mut buffer = String::new(); |
| 103 | + let mut stream = resp.bytes_stream(); |
| 104 | + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); |
| 105 | + loop { |
| 106 | + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); |
| 107 | + if remaining.is_zero() { |
| 108 | + break; |
| 109 | + } |
| 110 | + match tokio::time::timeout(remaining, stream.next()).await { |
| 111 | + Ok(Some(Ok(chunk))) => buffer.push_str(&String::from_utf8_lossy(&chunk)), |
| 112 | + _ => break, |
| 113 | + } |
| 114 | + let mut done = false; |
| 115 | + while let Some(pos) = buffer.find("\n\n") { |
| 116 | + let event: String = buffer.drain(..pos + 2).collect(); |
| 117 | + for line in event.lines() { |
| 118 | + if let Some(data) = line.strip_prefix("data: ") |
| 119 | + && let Ok(json) = serde_json::from_str::<serde_json::Value>(data) |
| 120 | + { |
| 121 | + // The final JSON-RPC response ends the request stream. |
| 122 | + if json.get("result").is_some() || json.get("error").is_some() { |
| 123 | + done = true; |
| 124 | + } |
| 125 | + events.push(json); |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + if done { |
| 130 | + break; |
| 131 | + } |
| 132 | + } |
| 133 | + events |
| 134 | +} |
| 135 | + |
| 136 | +#[tokio::test] |
| 137 | +async fn message_notifications_require_a_declared_log_level() { |
| 138 | + let url = start_server().await; |
| 139 | + |
| 140 | + // Without logLevel in _meta: the server MUST NOT emit notifications/message. |
| 141 | + let events = call_chatty(&url, None).await; |
| 142 | + assert!( |
| 143 | + !events.is_empty(), |
| 144 | + "the final response must arrive on the stream" |
| 145 | + ); |
| 146 | + assert!( |
| 147 | + !events |
| 148 | + .iter() |
| 149 | + .any(|e| e["method"] == "notifications/message"), |
| 150 | + "no logLevel declared → no notifications/message, got: {events:?}" |
| 151 | + ); |
| 152 | + |
| 153 | + // With logLevel "info": the info-level message must be delivered. |
| 154 | + let events = call_chatty(&url, Some("info")).await; |
| 155 | + assert!( |
| 156 | + events |
| 157 | + .iter() |
| 158 | + .any(|e| e["method"] == "notifications/message"), |
| 159 | + "declared logLevel must opt in to notifications/message, got: {events:?}" |
| 160 | + ); |
| 161 | +} |
| 162 | + |
| 163 | +#[tokio::test] |
| 164 | +async fn declared_level_is_the_severity_threshold() { |
| 165 | + let url = start_server().await; |
| 166 | + |
| 167 | + // The tool logs at info; a request declaring only "error" must not get it. |
| 168 | + let events = call_chatty(&url, Some("error")).await; |
| 169 | + assert!( |
| 170 | + !events |
| 171 | + .iter() |
| 172 | + .any(|e| e["method"] == "notifications/message"), |
| 173 | + "info-level message must be filtered below an 'error' threshold: {events:?}" |
| 174 | + ); |
| 175 | +} |
0 commit comments