catenary-mcp 1.6.1

A high-performance multiplexing bridge between MCP (Model Context Protocol) and LSP (Language Server Protocol). Enables LLMs to access IDE-grade code intelligence across multiple languages simultaneously with smart routing and UTF-8 accuracy.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Mark Wells <contact@markwells.dev>

//! Protocol categorization and collapse key computation for the display pipeline.
//!
//! Pure functions that map protocol messages to grouping labels and collapse
//! keys. Categories follow the LSP and MCP specs' own method groupings —
//! explicit `match` on method strings, no regex or prefix matching.

use crate::session::SessionMessage;

// ── Category functions ───────────────────────────────────────────────────

/// Categorize an LSP method.
#[must_use]
pub fn lsp_category(method: &str) -> &'static str {
    match method {
        // lifecycle
        "initialize"
        | "initialized"
        | "shutdown"
        | "exit"
        | "client/registerCapability"
        | "client/unregisterCapability"
        | "$/setTrace"
        | "$/logTrace" => "lifecycle",

        // sync
        "textDocument/didOpen"
        | "textDocument/didChange"
        | "textDocument/didSave"
        | "textDocument/didClose"
        | "textDocument/willSave"
        | "textDocument/willSaveWaitUntil" => "sync",

        // language
        "textDocument/hover"
        | "textDocument/definition"
        | "textDocument/references"
        | "textDocument/rename"
        | "textDocument/prepareRename"
        | "textDocument/implementation"
        | "textDocument/typeDefinition"
        | "textDocument/declaration"
        | "textDocument/codeAction"
        | "textDocument/documentSymbol"
        | "textDocument/completion"
        | "textDocument/signatureHelp"
        | "textDocument/formatting"
        | "textDocument/rangeFormatting"
        | "textDocument/diagnostic"
        | "textDocument/codeLens"
        | "textDocument/documentHighlight"
        | "textDocument/foldingRange"
        | "textDocument/selectionRange"
        | "textDocument/linkedEditingRange"
        | "textDocument/semanticTokens/full"
        | "textDocument/semanticTokens/range"
        | "callHierarchy/incomingCalls"
        | "callHierarchy/outgoingCalls"
        | "textDocument/prepareCallHierarchy"
        | "typeHierarchy/subtypes"
        | "typeHierarchy/supertypes"
        | "textDocument/prepareTypeHierarchy"
        | "workspaceSymbol/resolve" => "language",

        // window
        "window/logMessage" | "window/showMessage" | "window/workDoneProgress/create" => "window",

        // workspace
        "workspace/symbol"
        | "workspace/configuration"
        | "workspace/didChangeConfiguration"
        | "workspace/didChangeWatchedFiles"
        | "workspace/didChangeWorkspaceFolders" => "workspace",

        // progress
        "$/progress" => "progress",

        _ => "unknown",
    }
}

/// Categorize an MCP method.
#[must_use]
pub fn mcp_category(method: &str) -> &'static str {
    match method {
        "initialize" | "notifications/initialized" => "init",
        "tools/list" | "tools/call" => "tools",
        "roots/list" | "notifications/roots/list_changed" => "roots",
        "notifications/cancelled" => "cancelled",
        _ => "unknown",
    }
}

/// Categorize a hook method.
///
/// Matches on the action suffix (after the last `/`) so categories
/// work with the full `namespace/action` method strings.
#[must_use]
pub fn hook_category(method: &str) -> &'static str {
    match method.rsplit('/').next().unwrap_or(method) {
        "diagnostics" => "diagnostics",
        "roots-sync" => "sync",
        "enforce-editing" | "require-release" | "clear-editing" => "lifecycle",
        _ => "unknown",
    }
}

// ── Collapse key ─────────────────────────────────────────────────────────

/// Returns a collapse key for run grouping, or `None` if the message
/// should never collapse.
#[must_use]
pub fn collapse_key(msg: &SessionMessage) -> Option<String> {
    match msg.r#type.as_str() {
        "lsp" => {
            let cat = lsp_category(&msg.method);
            match cat {
                "progress" => {
                    let token = extract_progress_token(&msg.payload).unwrap_or_default();
                    Some(format!("progress:{}:{token}", msg.server))
                }
                "window" => {
                    let level = extract_log_level(&msg.payload)?;
                    if level >= 3 {
                        Some(format!("log:{}:{level}", msg.server))
                    } else {
                        // Errors and warnings never collapse.
                        None
                    }
                }
                "sync" => {
                    let uri = extract_sync_uri(&msg.payload).unwrap_or_default();
                    Some(format!("sync:{}:{uri}", msg.server))
                }
                "lifecycle" => Some(format!("lifecycle:{}", msg.server)),
                _ => Some(format!(
                    "proto:{}:{}:{}:{}",
                    msg.r#type, msg.server, msg.client, msg.method
                )),
            }
        }
        "mcp" => {
            let cat = mcp_category(&msg.method);
            match cat {
                "init" => Some("init:mcp".to_string()),
                _ => Some(format!(
                    "proto:{}:{}:{}:{}",
                    msg.r#type, msg.server, msg.client, msg.method
                )),
            }
        }
        // All hook messages and anything else → never collapse.
        _ => None,
    }
}

// ── Payload extraction helpers ───────────────────────────────────────────

/// Extract progress token from a `$/progress` payload.
///
/// The token can be a string or a number (per LSP spec).
fn extract_progress_token(payload: &serde_json::Value) -> Option<String> {
    let token = payload.get("token")?;
    token
        .as_str()
        .map(String::from)
        .or_else(|| token.as_u64().map(|n| n.to_string()))
        .or_else(|| token.as_i64().map(|n| n.to_string()))
}

/// Extract log level (`MessageType`) from a `window/logMessage` payload.
///
/// `MessageType` enum: 1=error, 2=warning, 3=info, 4=log.
fn extract_log_level(payload: &serde_json::Value) -> Option<u32> {
    #[allow(
        clippy::cast_possible_truncation,
        reason = "MessageType values are 1-4"
    )]
    payload.get("type")?.as_u64().map(|n| n as u32)
}

/// Extract the document URI from a sync notification payload.
fn extract_sync_uri(payload: &serde_json::Value) -> Option<String> {
    payload
        .get("textDocument")?
        .get("uri")?
        .as_str()
        .map(String::from)
}

// ── Collapsed run payload extractors ────────────────────────────────

/// Extract the progress title from a run of `$/progress` messages.
///
/// Looks for the first message with `value.kind == "begin"` and a `title`
/// field. Falls back to the progress token from the first message.
pub(crate) fn extract_progress_title(
    messages: &[SessionMessage],
    start: usize,
    end: usize,
) -> String {
    for msg in &messages[start..=end] {
        if let Some(value) = msg.payload.get("value")
            && value.get("kind").and_then(|k| k.as_str()) == Some("begin")
            && let Some(title) = value.get("title").and_then(|t| t.as_str())
        {
            return title.to_string();
        }
    }
    // Fall back to progress token from the first message.
    extract_progress_token(&messages[start].payload).unwrap_or_default()
}

/// Extract the percentage range from a run of `$/progress` messages.
///
/// Returns the first and last `value.percentage` values found in the run.
pub(crate) fn extract_progress_pct_range(
    messages: &[SessionMessage],
    start: usize,
    end: usize,
) -> (Option<u64>, Option<u64>) {
    let mut first = None;
    let mut last = None;
    for msg in &messages[start..=end] {
        if let Some(value) = msg.payload.get("value")
            && let Some(pct) = value.get("percentage").and_then(serde_json::Value::as_u64)
        {
            if first.is_none() {
                first = Some(pct);
            }
            last = Some(pct);
        }
    }
    (first, last)
}

/// Extract the file basename from a sync run's `textDocument.uri`.
pub(crate) fn extract_sync_basename(
    messages: &[SessionMessage],
    start: usize,
    end: usize,
) -> Option<String> {
    for msg in &messages[start..=end] {
        if let Some(uri) = extract_sync_uri(&msg.payload) {
            let name = std::path::Path::new(uri.as_str())
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(&uri);
            return Some(name.to_string());
        }
    }
    None
}

/// Extract deduplicated operation labels from a sync run, preserving order.
///
/// Maps `didOpen` → `open`, `didChange` → `change`, etc.
pub(crate) fn extract_sync_operations(
    messages: &[SessionMessage],
    start: usize,
    end: usize,
) -> Vec<&'static str> {
    let mut ops: Vec<&'static str> = Vec::new();
    for msg in &messages[start..=end] {
        let label = match msg.method.as_str() {
            "textDocument/didOpen" => "open",
            "textDocument/didChange" => "change",
            "textDocument/didSave" => "save",
            "textDocument/didClose" => "close",
            _ => continue,
        };
        if !ops.contains(&label) {
            ops.push(label);
        }
    }
    ops
}

/// Map a log collapse key's level to a human-readable label.
///
/// Collapse key format: `log:{server}:{level}`.
/// Level 3 = info, level 4 = log.
pub(crate) fn log_level_label(collapse_key: &str) -> &'static str {
    match collapse_key.rsplit(':').next() {
        Some("3") => "info",
        _ => "log",
    }
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    reason = "tests use expect for readable assertions"
)]
mod tests {
    use super::*;
    use crate::session::SessionMessage;

    fn make_message(r#type: &str, method: &str, server: &str) -> SessionMessage {
        SessionMessage {
            id: 0,
            r#type: r#type.to_string(),
            method: method.to_string(),
            server: server.to_string(),
            client: "catenary".to_string(),
            request_id: None,
            parent_id: None,
            timestamp: chrono::Utc::now(),
            payload: serde_json::json!({}),
        }
    }

    fn make_message_with_payload(
        r#type: &str,
        method: &str,
        server: &str,
        payload: serde_json::Value,
    ) -> SessionMessage {
        SessionMessage {
            id: 0,
            r#type: r#type.to_string(),
            method: method.to_string(),
            server: server.to_string(),
            client: "catenary".to_string(),
            request_id: None,
            parent_id: None,
            timestamp: chrono::Utc::now(),
            payload,
        }
    }

    // ── Category tests ───────────────────────────────────────────────────

    #[test]
    fn test_lsp_category_hover() {
        assert_eq!(lsp_category("textDocument/hover"), "language");
    }

    #[test]
    fn test_lsp_category_progress() {
        assert_eq!(lsp_category("$/progress"), "progress");
    }

    #[test]
    fn test_lsp_category_did_open() {
        assert_eq!(lsp_category("textDocument/didOpen"), "sync");
    }

    #[test]
    fn test_lsp_category_unknown() {
        assert_eq!(lsp_category("custom/unknownMethod"), "unknown");
    }

    #[test]
    fn test_mcp_category_tools_call() {
        assert_eq!(mcp_category("tools/call"), "tools");
    }

    #[test]
    fn test_mcp_category_initialize() {
        assert_eq!(mcp_category("initialize"), "init");
    }

    #[test]
    fn test_hook_category_methods() {
        assert_eq!(hook_category("post-tool/diagnostics"), "diagnostics");
        assert_eq!(hook_category("pre-agent/roots-sync"), "sync");
        assert_eq!(hook_category("pre-tool/enforce-editing"), "lifecycle");
        assert_eq!(hook_category("post-agent/require-release"), "lifecycle");
        assert_eq!(hook_category("session-start/clear-editing"), "lifecycle");
        assert_eq!(hook_category("unknown/method"), "unknown");
    }

    // ── Collapse key tests ───────────────────────────────────────────────

    #[test]
    fn test_collapse_key_progress() {
        let msg = make_message_with_payload(
            "lsp",
            "$/progress",
            "rust-analyzer",
            serde_json::json!({"token": "rust-analyzer/indexing"}),
        );
        let key = collapse_key(&msg);
        assert_eq!(
            key.as_deref(),
            Some("progress:rust-analyzer:rust-analyzer/indexing")
        );
    }

    #[test]
    fn test_collapse_key_sync() {
        let msg = make_message_with_payload(
            "lsp",
            "textDocument/didOpen",
            "rust-analyzer",
            serde_json::json!({"textDocument": {"uri": "file:///src/main.rs"}}),
        );
        let key = collapse_key(&msg);
        assert!(key.is_some());
        let key = key.expect("should have collapse key");
        assert!(
            key.starts_with("sync:"),
            "key should start with sync: got {key}"
        );
        assert!(
            key.contains("rust-analyzer"),
            "key should contain server: got {key}"
        );
    }

    #[test]
    fn test_collapse_key_hook_none() {
        let msg = make_message("hook", "PostToolUse", "catenary");
        assert!(collapse_key(&msg).is_none());
    }

    #[test]
    fn test_collapse_key_error_log_none() {
        let msg = make_message_with_payload(
            "lsp",
            "window/logMessage",
            "rust-analyzer",
            serde_json::json!({"type": 1}), // error
        );
        assert!(
            collapse_key(&msg).is_none(),
            "error-level log messages should not collapse"
        );
    }

    #[test]
    fn test_collapse_key_info_log() {
        let msg = make_message_with_payload(
            "lsp",
            "window/logMessage",
            "rust-analyzer",
            serde_json::json!({"type": 3}), // info
        );
        let key = collapse_key(&msg);
        assert!(key.is_some());
        let key = key.expect("should have collapse key");
        assert!(
            key.starts_with("log:"),
            "key should start with log: got {key}"
        );
    }
}