croft-software 0.2.82

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! MCP client: JSON-RPC 2.0 envelope + the MCP lifecycle over a [`McpTransport`].
//!
//! The handshake is `initialize` (request) -> server result ->
//! `notifications/initialized` (notification), after which `tools/list` and
//! `tools/call` are available. Requests carry a monotonic integer `id`; the
//! client matches a response to its request by that id, discarding interleaved
//! server-initiated notifications (e.g. `notifications/message` logging).
//!
//! The client is synchronous: one outstanding request at a time, which is all a
//! deterministic palette-invoked host needs (a human triggers one tool call and
//! croft renders the result). That keeps response correlation a simple
//! recv-until-matching-id loop instead of a pending-request map.

use std::collections::BTreeMap;
use std::path::Path;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::mpsc::RecvTimeoutError;
use std::time::Duration;

use anyhow::{Context, Result, bail};
use serde_json::{Value, json};

use crate::mcp::transport::McpTransport;

/// The MCP protocol revision croft speaks. The server echoes a (possibly older)
/// `protocolVersion` in its `initialize` result; croft accepts whatever the
/// server negotiates rather than hard-failing on an exact match.
pub const PROTOCOL_VERSION: &str = "2025-11-25";

/// How long a single request waits for its matching response before erroring,
/// so a wedged server can't hang croft's invocation forever.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// How long a request whose server died waits for the rest of its stderr.
const EXIT_REASON_WAIT: Duration = Duration::from_millis(500);

/// Build a JSON-RPC 2.0 request envelope (the transport does not add `id`).
pub fn request(id: i64, method: &str, params: Value) -> Value {
    json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })
}

/// Build a JSON-RPC 2.0 notification envelope (no `id`, no response expected).
pub fn notification(method: &str, params: Value) -> Value {
    json!({ "jsonrpc": "2.0", "method": method, "params": params })
}

/// The `initialize` params: the protocol revision, croft's (empty) client
/// capabilities, and its identity.
pub fn initialize_params(client_name: &str, client_version: &str) -> Value {
    json!({
        "protocolVersion": PROTOCOL_VERSION,
        "capabilities": {},
        "clientInfo": { "name": client_name, "version": client_version },
    })
}

/// The `tools/call` params: the tool name and its arguments object.
pub fn tools_call_params(name: &str, arguments: Value) -> Value {
    json!({ "name": name, "arguments": arguments })
}

/// Extract the `result` from a JSON-RPC response, turning a JSON-RPC `error`
/// object into an `Err` carrying its message. A response missing both is
/// malformed.
pub fn response_result(message: &Value) -> Result<Value> {
    if let Some(err) = message.get("error") {
        let msg = err
            .get("message")
            .and_then(Value::as_str)
            .unwrap_or("unknown error");
        let code = err.get("code").and_then(Value::as_i64).unwrap_or(0);
        bail!("MCP error {code}: {msg}");
    }
    message
        .get("result")
        .cloned()
        .context("JSON-RPC response has neither result nor error")
}

/// Whether `message` is the response to request `id` (a JSON-RPC response echoes
/// the request's integer `id`). Server notifications carry no `id` and are thus
/// never matched.
fn is_response_to(message: &Value, id: i64) -> bool {
    message.get("id").and_then(Value::as_i64) == Some(id)
}

/// One tool a server advertises, projected from a `tools/list` entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tool {
    pub name: String,
    pub description: String,
}

/// Parse the `tools` array out of a `tools/list` result.
pub fn parse_tools(result: &Value) -> Vec<Tool> {
    result
        .get("tools")
        .and_then(Value::as_array)
        .map(|tools| {
            tools
                .iter()
                .filter_map(|t| {
                    let name = t.get("name")?.as_str()?.to_string();
                    let description = t
                        .get("description")
                        .and_then(Value::as_str)
                        .unwrap_or_default()
                        .to_string();
                    Some(Tool { name, description })
                })
                .collect()
        })
        .unwrap_or_default()
}

/// Flatten a `tools/call` result's `content` array into plain text. MCP tool
/// content is a list of typed blocks; croft renders the `text` blocks joined by
/// blank lines (the markdown scratch buffer the pilot writes). Non-text blocks
/// (images, resources) are skipped in this first cut.
pub fn tool_result_text(result: &Value) -> String {
    result
        .get("content")
        .and_then(Value::as_array)
        .map(|blocks| {
            blocks
                .iter()
                .filter_map(|b| b.get("text").and_then(Value::as_str))
                .collect::<Vec<_>>()
                .join("\n\n")
        })
        .unwrap_or_default()
}

/// A stable fingerprint of a named tool's definition (name + description + input
/// schema) taken from a raw `tools/list` result, for trust-on-first-use rug-pull
/// detection: croft records the fingerprint the first time it calls a tool and
/// refuses to call again if the definition silently changed (the MCPoison /
/// tool-mutation class). The compact JSON of the canonical fields is the
/// fingerprint — serde_json orders object keys deterministically, so it is
/// stable across runs without a crypto dependency. Empty string if not found.
pub fn tool_fingerprint(tools_list_result: &Value, name: &str) -> String {
    let Some(entry) = tools_list_result
        .get("tools")
        .and_then(Value::as_array)
        .and_then(|a| {
            a.iter()
                .find(|t| t.get("name").and_then(Value::as_str) == Some(name))
        })
    else {
        return String::new();
    };
    json!({
        "name": entry.get("name").cloned().unwrap_or(Value::Null),
        "description": entry.get("description").cloned().unwrap_or(Value::Null),
        "inputSchema": entry.get("inputSchema").cloned().unwrap_or(Value::Null),
    })
    .to_string()
}

/// A live MCP session: an initialized server plus the id counter for requests.
pub struct McpClient {
    transport: McpTransport,
    next_id: AtomicI64,
}

impl McpClient {
    /// Spawn and initialize an MCP server: handshake then return the ready
    /// client. `env` is the least-privilege environment for the server.
    pub fn connect(
        program: &str,
        args: &[String],
        cwd: &Path,
        env: &BTreeMap<String, String>,
        client_name: &str,
        client_version: &str,
    ) -> Result<McpClient> {
        let transport = McpTransport::spawn(program, args, cwd, env)?;
        let client = McpClient {
            transport,
            next_id: AtomicI64::new(0),
        };
        client.initialize(client_name, client_version)?;
        Ok(client)
    }

    fn next_id(&self) -> i64 {
        self.next_id.fetch_add(1, Ordering::SeqCst) + 1
    }

    /// Send a request and block until its matching response arrives (discarding
    /// interleaved server notifications), returning the `result` or an error.
    pub fn call(&self, method: &str, params: Value) -> Result<Value> {
        let id = self.next_id();
        if let Err(e) = self.transport.send(&request(id, method, params)) {
            // A server that already died closed its stdin: say why it died.
            let broken_pipe = e
                .root_cause()
                .downcast_ref::<std::io::Error>()
                .is_some_and(|io| io.kind() == std::io::ErrorKind::BrokenPipe);
            if broken_pipe {
                bail!("{}", self.transport.exit_reason(EXIT_REASON_WAIT));
            }
            return Err(e);
        }
        let deadline = std::time::Instant::now() + REQUEST_TIMEOUT;
        loop {
            let remaining = deadline
                .checked_duration_since(std::time::Instant::now())
                .context("MCP request timed out")?;
            let msg = match self.transport.incoming.recv_timeout(remaining) {
                Ok(msg) => msg,
                Err(RecvTimeoutError::Timeout) => bail!("MCP server timed out before responding"),
                // stdout closed: the server died, and its stderr says why.
                Err(RecvTimeoutError::Disconnected) => {
                    bail!("{}", self.transport.exit_reason(EXIT_REASON_WAIT))
                }
            };
            if is_response_to(&msg, id) {
                return response_result(&msg);
            }
            // Otherwise a server notification/request: ignore and keep waiting.
        }
    }

    /// Send a fire-and-forget notification.
    pub fn notify(&self, method: &str, params: Value) -> Result<()> {
        self.transport.send(&notification(method, params))
    }

    /// Run the MCP handshake: `initialize`, then the `notifications/initialized`
    /// acknowledgement the spec requires before normal operation.
    fn initialize(&self, client_name: &str, client_version: &str) -> Result<Value> {
        let result = self.call("initialize", initialize_params(client_name, client_version))?;
        self.notify("notifications/initialized", json!({}))?;
        Ok(result)
    }

    /// Call a tool by name with an arguments object; returns the raw result.
    pub fn call_tool(&self, name: &str, arguments: Value) -> Result<Value> {
        self.call("tools/call", tools_call_params(name, arguments))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn request_and_notification_envelopes_are_jsonrpc_2_0() {
        let r = request(1, "tools/list", json!({}));
        assert_eq!(r["jsonrpc"], "2.0");
        assert_eq!(r["id"], 1);
        assert_eq!(r["method"], "tools/list");
        let n = notification("notifications/initialized", json!({}));
        assert_eq!(n["jsonrpc"], "2.0");
        assert_eq!(n["method"], "notifications/initialized");
        assert!(n.get("id").is_none(), "a notification carries no id");
    }

    #[test]
    fn initialize_params_advertise_the_protocol_version_and_client() {
        let p = initialize_params("croft", "0.1.0");
        assert_eq!(p["protocolVersion"], PROTOCOL_VERSION);
        assert_eq!(p["clientInfo"]["name"], "croft");
        assert_eq!(p["clientInfo"]["version"], "0.1.0");
    }

    #[test]
    fn response_result_extracts_result_and_maps_error_to_err() {
        let ok = json!({"jsonrpc": "2.0", "id": 1, "result": {"tools": []}});
        assert_eq!(response_result(&ok).unwrap(), json!({"tools": []}));

        let err = json!({"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "Method not found"}});
        let e = response_result(&err).unwrap_err().to_string();
        assert!(e.contains("-32601"), "{e}");
        assert!(e.contains("Method not found"), "{e}");

        let malformed = json!({"jsonrpc": "2.0", "id": 1});
        assert!(response_result(&malformed).is_err());
    }

    #[test]
    fn is_response_to_matches_only_the_request_id() {
        assert!(is_response_to(&json!({"id": 5, "result": {}}), 5));
        assert!(!is_response_to(&json!({"id": 6, "result": {}}), 5));
        // A server notification has no id and never matches.
        assert!(!is_response_to(
            &json!({"method": "notifications/message"}),
            5
        ));
    }

    #[test]
    fn parse_tools_projects_name_and_description() {
        let result = json!({
            "tools": [
                {"name": "fetch", "description": "Fetch a URL", "inputSchema": {}},
                {"name": "echo"},
            ]
        });
        let tools = parse_tools(&result);
        assert_eq!(tools.len(), 2);
        assert_eq!(
            tools[0],
            Tool {
                name: "fetch".into(),
                description: "Fetch a URL".into()
            }
        );
        assert_eq!(tools[1].name, "echo");
        assert_eq!(
            tools[1].description, "",
            "missing description defaults empty"
        );
    }

    #[test]
    fn tool_fingerprint_is_stable_and_changes_with_the_definition() {
        let list = json!({"tools": [
            {"name": "fetch", "description": "Fetch a URL", "inputSchema": {"type": "object"}},
            {"name": "other"},
        ]});
        let fp = tool_fingerprint(&list, "fetch");
        assert!(!fp.is_empty());
        // Stable across calls on the same definition.
        assert_eq!(fp, tool_fingerprint(&list, "fetch"));
        // A mutated description (a rug-pull) changes the fingerprint.
        let mutated = json!({"tools": [
            {"name": "fetch", "description": "Fetch a URL and exfiltrate it", "inputSchema": {"type": "object"}},
        ]});
        assert_ne!(fp, tool_fingerprint(&mutated, "fetch"));
        // Unknown tool fingerprints empty.
        assert_eq!(tool_fingerprint(&list, "nope"), "");
    }

    #[test]
    fn tool_result_text_joins_text_content_blocks() {
        let result = json!({
            "content": [
                {"type": "text", "text": "# Heading"},
                {"type": "image", "data": "..."},
                {"type": "text", "text": "body"},
            ]
        });
        assert_eq!(tool_result_text(&result), "# Heading\n\nbody");
    }

    /// The env a test sidecar runs with: just PATH, so `/bin/sh` finds
    /// `head` and `tr`.
    fn path_env() -> BTreeMap<String, String> {
        std::env::var("PATH")
            .map(|p| BTreeMap::from([(String::from("PATH"), p)]))
            .unwrap_or_default()
    }

    /// A sidecar that crashes on import (the pinned mcp-server-time under
    /// mcp 2.x) must say why, not report a generic timeout (#1297).
    #[test]
    fn a_server_that_dies_before_answering_names_its_error() {
        let script = "echo 'Traceback (most recent call last):' >&2; \
             echo \"ImportError: cannot import name 'McpError' from 'mcp.shared.exceptions'\" >&2; \
             echo >&2; exit 1";
        let err = McpClient::connect(
            "/bin/sh",
            &[String::from("-c"), script.to_string()],
            &std::env::temp_dir(),
            &path_env(),
            "croft",
            "test",
        )
        .err()
        .expect("a server that exits never connects")
        .to_string();
        assert_eq!(
            err,
            "the server exited: ImportError: cannot import name 'McpError' from 'mcp.shared.exceptions'"
        );
    }

    /// A server that dies without a word still says it exited, rather than
    /// that it timed out.
    #[test]
    fn a_silent_server_exit_is_reported_as_an_exit() {
        let err = McpClient::connect(
            "/bin/sh",
            &[String::from("-c"), String::from("exit 3")],
            &std::env::temp_dir(),
            &path_env(),
            "croft",
            "test",
        )
        .err()
        .expect("a server that exits never connects")
        .to_string();
        assert_eq!(err, "the server exited before responding");
    }

    /// Negative: a server that logs far past the 64 KiB pipe buffer before
    /// answering still answers, since stderr is drained, not left to fill.
    #[test]
    fn a_server_logging_past_the_pipe_buffer_still_answers() {
        let script = "head -c 300000 /dev/zero | tr '\\000' x >&2; read l; \
             printf '%s\\n' '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}'; cat >/dev/null";
        McpClient::connect(
            "/bin/sh",
            &[String::from("-c"), script.to_string()],
            &std::env::temp_dir(),
            &path_env(),
            "croft",
            "test",
        )
        .expect("a chatty server still completes the handshake");
    }

    /// End-to-end against a real MCP server process: a tiny hermetic Python
    /// server (stdlib only) that implements `initialize`, `tools/list`, and an
    /// `echo` tool over NDJSON stdio. Proves the full spawn -> handshake ->
    /// tools/list -> tools/call loop on the real wire, no network or npm.
    ///
    /// Ignored by default (needs `python3` on PATH); run with
    /// `cargo test --bin croft -- --ignored mcp_handshake`.
    #[test]
    #[ignore = "requires python3 on PATH"]
    fn mcp_handshake_lists_and_calls_a_tool_against_a_real_server() {
        use std::io::Write;
        const SERVER: &str = r#"
import sys, json
def reply(i, result):
    sys.stdout.write(json.dumps({"jsonrpc":"2.0","id":i,"result":result}) + "\n")
    sys.stdout.flush()
for line in sys.stdin:
    line = line.strip()
    if not line:
        continue
    msg = json.loads(line)
    m = msg.get("method")
    if m == "initialize":
        reply(msg["id"], {"protocolVersion":"2025-11-25","capabilities":{},"serverInfo":{"name":"mock","version":"0"}})
    elif m == "notifications/initialized":
        pass
    elif m == "tools/list":
        reply(msg["id"], {"tools":[{"name":"echo","description":"Echo text"}]})
    elif m == "tools/call":
        text = msg["params"]["arguments"].get("text","")
        reply(msg["id"], {"content":[{"type":"text","text":text}]})
    elif "id" in msg:
        reply(msg["id"], {})
"#;
        let dir = std::env::temp_dir().join(format!("croft-mcp-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let script = dir.join("server.py");
        let mut f = std::fs::File::create(&script).unwrap();
        f.write_all(SERVER.as_bytes()).unwrap();
        drop(f);

        let env = BTreeMap::new();
        let client = McpClient::connect(
            "python3",
            &[script.to_string_lossy().into_owned()],
            &dir,
            &env,
            "croft",
            "test",
        )
        .expect("connect + initialize against the mock MCP server");

        let list = client.call("tools/list", json!({})).expect("tools/list");
        let tools = parse_tools(&list);
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].name, "echo");

        let result = client
            .call_tool("echo", json!({"text": "hello mcp"}))
            .expect("tools/call echo");
        assert_eq!(tool_result_text(&result), "hello mcp");

        let _ = std::fs::remove_dir_all(&dir);
    }
}