Skip to main content

lean_ctx_server/server/
progress.rs

1// SPDX-License-Identifier: Apache-2.0
2use rmcp::RoleServer;
3use rmcp::model::{ProgressNotificationParam, ProgressToken};
4use rmcp::service::Peer;
5
6/// Sends MCP progress notifications to the client during long-running tool operations.
7#[derive(Clone)]
8pub struct ProgressSender {
9    peer: Peer<RoleServer>,
10    token: ProgressToken,
11}
12
13impl ProgressSender {
14    pub fn new(peer: Peer<RoleServer>, token: ProgressToken) -> Self {
15        Self { peer, token }
16    }
17
18    pub fn send(&self, progress: f64, total: Option<f64>, message: Option<String>) {
19        // ProgressNotificationParam is #[non_exhaustive] since rmcp 2.0 — build via ctor.
20        let mut params = ProgressNotificationParam::new(self.token.clone(), progress);
21        if let Some(total) = total {
22            params = params.with_total(total);
23        }
24        if let Some(message) = message {
25            params = params.with_message(message);
26        }
27        let peer = self.peer.clone();
28        tokio::spawn(async move {
29            if let Err(e) = peer.notify_progress(params).await {
30                tracing::debug!("[progress] notify failed: {e}");
31            }
32        });
33    }
34}
35
36pub type SharedProgressSender = std::sync::Arc<std::sync::Mutex<Option<ProgressSender>>>;
37
38/// Over a real MCP connection: progress belongs to the call that asked for it.
39///
40/// A `ctx_shell` call that waits on a long command reports progress every 5 s.
41/// The sender used to sit in one server-wide slot that was set by any call
42/// with a `progressToken` and never cleared, so a later call without a token
43/// sent its progress under the token of a call that had already returned.
44/// The MCP spec forbids that, and a strict host answers it by closing the
45/// connection.
46///
47/// The host here speaks raw JSON-RPC: the rmcp client puts a token on every
48/// request it sends, but real hosts send calls without one.
49#[cfg(all(test, unix))]
50mod over_mcp {
51    use rmcp::ServiceExt;
52    use serde_json::{Value, json};
53    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
54
55    use crate::tools::LeanCtxServer;
56
57    struct Host {
58        lines: tokio::io::Lines<BufReader<tokio::io::ReadHalf<tokio::io::DuplexStream>>>,
59        writer: tokio::io::WriteHalf<tokio::io::DuplexStream>,
60    }
61
62    impl Host {
63        async fn send(&mut self, message: Value) {
64            let mut line = message.to_string();
65            line.push('\n');
66            self.writer.write_all(line.as_bytes()).await.unwrap();
67        }
68
69        /// Reads until the response to `id`; returns it with the tokens of
70        /// every progress notification that came before it.
71        async fn answer(&mut self, id: u64) -> (Value, Vec<Value>) {
72            let mut tokens = Vec::new();
73            loop {
74                let line = tokio::time::timeout(
75                    std::time::Duration::from_secs(60),
76                    self.lines.next_line(),
77                )
78                .await
79                .expect("the server answers within a minute")
80                .expect("readable")
81                .expect("the connection stays open");
82                let message: Value = serde_json::from_str(&line).expect("JSON-RPC");
83                if message["method"] == "notifications/progress" {
84                    tokens.push(message["params"]["progressToken"].clone());
85                } else if message["id"] == id {
86                    return (message, tokens);
87                }
88            }
89        }
90
91        async fn shell(
92            &mut self,
93            id: u64,
94            command: &str,
95            token: Option<u64>,
96        ) -> (String, Vec<Value>) {
97            let mut params = json!({ "name": "ctx_shell", "arguments": { "command": command } });
98            if let Some(token) = token {
99                params["_meta"] = json!({ "progressToken": token });
100            }
101            self.send(
102                json!({ "jsonrpc": "2.0", "id": id, "method": "tools/call", "params": params }),
103            )
104            .await;
105            let (response, tokens) = self.answer(id).await;
106            assert!(
107                response.get("error").is_none(),
108                "a JSON-RPC answer, no error: {response}"
109            );
110            assert_ne!(
111                response["result"]["isError"],
112                json!(true),
113                "no tool error: {response}"
114            );
115            let text = response["result"]["content"]
116                .as_array()
117                .into_iter()
118                .flatten()
119                .filter_map(|block| block["text"].as_str())
120                .collect::<String>();
121            (text, tokens)
122        }
123    }
124
125    async fn connect(root: &str) -> Host {
126        let server = LeanCtxServer::new_with_project_root(Some(root));
127        let (server_io, client_io) = tokio::io::duplex(1 << 16);
128        tokio::spawn(async move {
129            if let Ok(running) = server.serve(server_io).await {
130                let _ = running.waiting().await;
131            }
132        });
133        let (reader, writer) = tokio::io::split(client_io);
134        let mut host = Host {
135            lines: BufReader::new(reader).lines(),
136            writer,
137        };
138        host.send(json!({
139            "jsonrpc": "2.0", "id": 1, "method": "initialize",
140            "params": {
141                "protocolVersion": "2025-06-18",
142                "capabilities": {},
143                "clientInfo": { "name": "test-host", "version": "1.0.0" }
144            }
145        }))
146        .await;
147        host.answer(1).await;
148        host.send(json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }))
149            .await;
150        host
151    }
152
153    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
154    async fn progress_goes_only_to_the_call_that_asked_for_it() {
155        let _data = lean_ctx::core::data_dir::isolated_data_dir();
156        // Past one 5 s progress tick, short of the 6 s commands below: each
157        // command reports once and then detaches at the cap.
158        let _cap = lean_ctx::test_env::VarGuard::set("LEAN_CTX_SHELL_FG_CAP_MS", "5600");
159        let _security = lean_ctx::test_env::VarGuard::set("LEAN_CTX_SHELL_SECURITY", "off");
160        let project = tempfile::tempdir().unwrap();
161        std::fs::create_dir(project.path().join(".git")).unwrap();
162        let mut host = connect(&project.path().to_string_lossy()).await;
163
164        let (text, tokens) = host.shell(2, "sleep 6; echo with_token", Some(9)).await;
165        assert!(
166            text.contains("auto-background"),
167            "detached at the cap, cleanly: {text}"
168        );
169        assert!(
170            !tokens.is_empty(),
171            "the call with a token hears its progress"
172        );
173        assert!(
174            tokens.iter().all(|t| *t == json!(9)),
175            "only under its own token: {tokens:?}"
176        );
177
178        let (text, tokens) = host.shell(3, "sleep 6; echo without_token", None).await;
179        assert!(
180            text.contains("auto-background"),
181            "detached at the cap, cleanly: {text}"
182        );
183        assert!(
184            tokens.is_empty(),
185            "a call without a token sends no progress, least of all under the \
186             finished call's token: {tokens:?}"
187        );
188
189        let (text, _) = host.shell(4, "echo still_connected", None).await;
190        assert!(text.contains("still_connected"), "{text}");
191    }
192
193    #[test]
194    fn the_default_foreground_cap_returns_before_hosts_abort_a_call() {
195        // Hosts closed the connection at 105–108 s on `sleep 110`; the detach
196        // result has to be on its way well before that.
197        const { assert!(crate::tools::registered::ctx_shell::DEFAULT_FOREGROUND_SOFT_CAP_MS <= 90_000) };
198    }
199}