mcpls-core 0.8.0

Core library for MCP to LSP protocol translation
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
//! Typed catalogue of the MCP tool surface and the `get_tool_support` report.
//!
//! [`McpTool`] names every tool exactly once and declares, via
//! [`McpTool::spec`], its name and which LSP route (if any) serves it, so the
//! report is derived from the same routing vocabulary the bridge enforces with.

use std::borrow::Cow;

use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::{Serialize, Serializer};

use crate::bridge::{Capability, RouteSupport, ToolSupportSnapshot};
use crate::config::{LanguageId, ToolKind, ToolPrefix};
use crate::redaction::{Redactions, ServerText};

/// Where a tool's request is served.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ToolBackend {
    /// Routed per file, by the language of the file argument.
    Document(ToolKind),
    /// Routed workspace-wide, without a language.
    Workspace(ToolKind),
    /// Answered by mcpls itself; needs no language server.
    Local,
}

/// The static description of one [`McpTool`]: the single record from which
/// [`McpTool::name`] and [`McpTool::spec`] are derived.
#[derive(Debug, Clone, Copy)]
pub(super) struct ToolSpec {
    /// The unprefixed MCP tool name.
    pub(super) name: &'static str,
    /// The route serving the tool.
    pub(super) backend: ToolBackend,
}

/// Every MCP tool mcpls exposes, one variant per `#[tool]` handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum McpTool {
    GetHover,
    GetDefinition,
    GetReferences,
    GetDiagnostics,
    RenameSymbol,
    GetCompletions,
    GetDocumentSymbols,
    FormatDocument,
    WorkspaceSymbolSearch,
    GetCodeActions,
    PrepareCallHierarchy,
    GetIncomingCalls,
    GetOutgoingCalls,
    PrepareTypeHierarchy,
    GetSupertypes,
    GetSubtypes,
    PrepareRename,
    GetDocumentHighlights,
    FormatRange,
    GetSelectionRanges,
    GetFoldingRanges,
    GetCachedDiagnostics,
    GetServerLogs,
    GetServerMessages,
    GetSignatureHelp,
    GoToImplementation,
    GoToTypeDefinition,
    GetInlayHints,
    GetToolSupport,
    GoToDeclaration,
    RestartServer,
}

impl McpTool {
    /// Every tool, in registration order.
    pub(super) const ALL: [Self; 31] = [
        Self::GetHover,
        Self::GetDefinition,
        Self::GetReferences,
        Self::GetDiagnostics,
        Self::RenameSymbol,
        Self::GetCompletions,
        Self::GetDocumentSymbols,
        Self::FormatDocument,
        Self::WorkspaceSymbolSearch,
        Self::GetCodeActions,
        Self::PrepareCallHierarchy,
        Self::GetIncomingCalls,
        Self::GetOutgoingCalls,
        Self::PrepareTypeHierarchy,
        Self::GetSupertypes,
        Self::GetSubtypes,
        Self::PrepareRename,
        Self::GetDocumentHighlights,
        Self::FormatRange,
        Self::GetSelectionRanges,
        Self::GetFoldingRanges,
        Self::GetCachedDiagnostics,
        Self::GetServerLogs,
        Self::GetServerMessages,
        Self::GetSignatureHelp,
        Self::GoToImplementation,
        Self::GoToTypeDefinition,
        Self::GetInlayHints,
        Self::GetToolSupport,
        Self::GoToDeclaration,
        Self::RestartServer,
    ];

    /// Byte length of the longest unprefixed tool name.
    #[expect(
        clippy::indexing_slicing,
        reason = "the loop condition keeps `i` below `ALL.len()`"
    )]
    pub(super) const MAX_NAME_BYTES: usize = {
        let mut max = 0;
        let mut i = 0;
        while i < Self::ALL.len() {
            let len = Self::ALL[i].name().len();
            if len > max {
                max = len;
            }
            i += 1;
        }
        max
    };

    /// The name and route of this tool.
    pub(super) const fn spec(self) -> ToolSpec {
        use ToolBackend::{Document, Local, Workspace};
        let (name, backend) = match self {
            Self::GetHover => ("get_hover", Document(ToolKind::Hover)),
            Self::GetDefinition => ("get_definition", Document(ToolKind::Definition)),
            Self::GetReferences => ("get_references", Document(ToolKind::References)),
            Self::GetDiagnostics => ("get_diagnostics", Document(ToolKind::Diagnostics)),
            Self::RenameSymbol => ("rename_symbol", Document(ToolKind::Rename)),
            Self::GetCompletions => ("get_completions", Document(ToolKind::Completions)),
            Self::GetDocumentSymbols => {
                ("get_document_symbols", Document(ToolKind::DocumentSymbols))
            }
            Self::FormatDocument => ("format_document", Document(ToolKind::FormatDocument)),
            Self::WorkspaceSymbolSearch => (
                "workspace_symbol_search",
                Workspace(ToolKind::WorkspaceSymbols),
            ),
            Self::GetCodeActions => ("get_code_actions", Document(ToolKind::CodeActions)),
            Self::PrepareCallHierarchy => {
                ("prepare_call_hierarchy", Document(ToolKind::CallHierarchy))
            }
            Self::GetIncomingCalls => ("get_incoming_calls", Document(ToolKind::CallHierarchy)),
            Self::GetOutgoingCalls => ("get_outgoing_calls", Document(ToolKind::CallHierarchy)),
            Self::PrepareTypeHierarchy => {
                ("prepare_type_hierarchy", Document(ToolKind::TypeHierarchy))
            }
            Self::GetSupertypes => ("get_supertypes", Document(ToolKind::TypeHierarchy)),
            Self::GetSubtypes => ("get_subtypes", Document(ToolKind::TypeHierarchy)),
            Self::PrepareRename => ("prepare_rename", Document(ToolKind::Rename)),
            Self::GetDocumentHighlights => (
                "get_document_highlights",
                Document(ToolKind::DocumentHighlights),
            ),
            Self::FormatRange => ("format_range", Document(ToolKind::FormatRange)),
            Self::GetSelectionRanges => {
                ("get_selection_ranges", Document(ToolKind::SelectionRange))
            }
            Self::GetFoldingRanges => ("get_folding_ranges", Document(ToolKind::FoldingRange)),
            Self::GetCachedDiagnostics => ("get_cached_diagnostics", Local),
            Self::GetServerLogs => ("get_server_logs", Local),
            Self::GetServerMessages => ("get_server_messages", Local),
            Self::GetSignatureHelp => ("get_signature_help", Document(ToolKind::SignatureHelp)),
            Self::GoToImplementation => {
                ("go_to_implementation", Document(ToolKind::Implementation))
            }
            Self::GoToTypeDefinition => {
                ("go_to_type_definition", Document(ToolKind::TypeDefinition))
            }
            Self::GetInlayHints => ("get_inlay_hints", Document(ToolKind::InlayHints)),
            Self::GetToolSupport => ("get_tool_support", Local),
            Self::GoToDeclaration => ("go_to_declaration", Document(ToolKind::Declaration)),
            Self::RestartServer => ("restart_server", Local),
        };
        ToolSpec { name, backend }
    }

    /// The unprefixed MCP tool name.
    pub(super) const fn name(self) -> &'static str {
        self.spec().name
    }

    /// The capability this tool's call is gated on, or `None` when it is
    /// ungated or answered locally. A tool sharing another tool's route can
    /// need a different capability (`prepare_rename` on the `Rename` route),
    /// so this is per tool, not per [`ToolKind`].
    pub(super) const fn capability(self) -> Option<Capability> {
        match self {
            Self::PrepareRename => Some(Capability::PrepareRename),
            _ => match self.spec().backend {
                ToolBackend::Document(kind) | ToolBackend::Workspace(kind) => {
                    Capability::for_tool(kind)
                }
                ToolBackend::Local => None,
            },
        }
    }
}

/// The client-visible name of `name` under an optional configured prefix.
pub(super) fn prefixed_tool_name(prefix: Option<&ToolPrefix>, name: &str) -> String {
    prefix.map_or_else(|| name.to_string(), |prefix| format!("{prefix}_{name}"))
}

/// How widely a tool is usable across the languages in the report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub(super) enum ToolCoverage {
    /// Supported for every listed language.
    All,
    /// Supported for some listed languages but not all.
    #[serde(rename = "some")]
    Partial,
    /// Supported for no listed language (or nothing is configured).
    #[serde(rename = "none")]
    Unsupported,
    /// Not supported anywhere yet, but at least one server is still initializing.
    Unknown,
    /// Answered by mcpls itself; independent of language servers.
    Always,
}

impl ToolCoverage {
    fn from_routes<'a>(routes: impl Iterator<Item = &'a RouteSupport>) -> Self {
        let (mut total, mut supported, mut initializing) = (0_usize, 0_usize, false);
        for route in routes {
            total = total.saturating_add(1);
            match route {
                RouteSupport::Supported { .. } | RouteSupport::PushOnly { .. } => {
                    supported = supported.saturating_add(1);
                }
                RouteSupport::Initializing => initializing = true,
                RouteSupport::CapabilityNotAdvertised { .. } | RouteSupport::NoServer => {}
            }
        }
        if total == 0 {
            Self::Unsupported
        } else if supported == total {
            Self::All
        } else if supported > 0 {
            Self::Partial
        } else if initializing {
            Self::Unknown
        } else {
            Self::Unsupported
        }
    }
}

/// The languages of one tool that share an identical [`RouteSupport`].
#[derive(Debug, PartialEq, Eq, Serialize)]
pub(super) struct LanguageGroup {
    languages: Vec<LanguageId>,
    #[serde(flatten)]
    support: RouteSupport,
}

/// The routes of one tool in the report.
///
/// Serializes as a flat array in both variants: document routes are grouped
/// by identical support (`languages` lists the members), a workspace route has
/// no language and is a single element without `languages`.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum ToolRoutes {
    /// Per-document tool: languages grouped by identical support, in
    /// first-seen order over the sorted languages.
    Document(Vec<LanguageGroup>),
    /// Workspace-wide tool: its one route.
    Workspace(RouteSupport),
}

impl ToolRoutes {
    /// Group `routes` (one per language) by identical support, keeping the
    /// order in which each distinct support is first seen.
    fn grouped(routes: Vec<(LanguageId, RouteSupport)>) -> Self {
        let mut groups: Vec<LanguageGroup> = Vec::new();
        for (language, support) in routes {
            match groups.iter_mut().find(|group| group.support == support) {
                Some(group) => group.languages.push(language),
                None => groups.push(LanguageGroup {
                    languages: vec![language],
                    support,
                }),
            }
        }
        Self::Document(groups)
    }
}

/// One route of a tool: the languages that share this support status.
///
/// The languages are absent for workspace-wide tools.
#[derive(JsonSchema)]
#[expect(
    dead_code,
    reason = "describes the wire shape for schema generation only"
)]
struct RouteShape {
    languages: Option<Vec<LanguageId>>,
    #[serde(flatten)]
    support: RouteSupport,
}

impl JsonSchema for ToolRoutes {
    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("ToolRoutes")
    }

    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
        <Vec<RouteShape>>::json_schema(generator)
    }
}

impl Serialize for ToolRoutes {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Document(groups) => serializer.collect_seq(groups),
            Self::Workspace(support) => serializer.collect_seq(std::iter::once(support)),
        }
    }
}

/// One tool in the report.
#[derive(Debug, Serialize, JsonSchema)]
pub(super) struct ToolEntry {
    name: String,
    coverage: ToolCoverage,
    #[serde(skip_serializing_if = "Option::is_none")]
    routes: Option<ToolRoutes>,
}

/// The `get_tool_support` response.
#[derive(Debug, Serialize, JsonSchema)]
pub(super) struct ToolSupportReport {
    languages: Vec<LanguageId>,
    tools: Vec<ToolEntry>,
}

impl ToolSupportReport {
    /// Build the report over `languages` (the domain of every per-document
    /// tool) from `snapshot`, naming tools as clients see them under `prefix`.
    pub(super) fn build(
        snapshot: &ToolSupportSnapshot,
        languages: &[LanguageId],
        prefix: Option<&ToolPrefix>,
    ) -> Self {
        let tools = McpTool::ALL
            .iter()
            .map(|tool| {
                let spec = tool.spec();
                let (coverage, routes) = match spec.backend {
                    ToolBackend::Local => (ToolCoverage::Always, None),
                    ToolBackend::Document(kind) => {
                        let routes: Vec<_> = languages
                            .iter()
                            .map(|language| {
                                (
                                    language.clone(),
                                    snapshot.document_support_gated(
                                        language,
                                        kind,
                                        tool.capability(),
                                    ),
                                )
                            })
                            .collect();
                        let coverage = ToolCoverage::from_routes(routes.iter().map(|(_, s)| s));
                        let push_only = routes
                            .iter()
                            .any(|(_, s)| matches!(s, RouteSupport::PushOnly { .. }));
                        (
                            coverage,
                            (coverage != ToolCoverage::All || push_only)
                                .then(|| ToolRoutes::grouped(routes)),
                        )
                    }
                    ToolBackend::Workspace(kind) => {
                        let support = snapshot.workspace_support(kind);
                        let coverage = ToolCoverage::from_routes(std::iter::once(&support));
                        (
                            coverage,
                            (coverage != ToolCoverage::All)
                                .then_some(ToolRoutes::Workspace(support)),
                        )
                    }
                };
                ToolEntry {
                    name: prefixed_tool_name(prefix, spec.name),
                    coverage,
                    routes,
                }
            })
            .collect();
        Self {
            languages: languages.to_vec(),
            tools,
        }
    }
}

// Languages and tool names come from configuration, not from a server.
impl ServerText for ToolSupportReport {
    fn redact_server_text(&mut self, _redactions: &Redactions) {
        let Self {
            languages: _,
            tools: _,
        } = self;
    }
}

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

    fn supported() -> RouteSupport {
        RouteSupport::Supported {
            server: ServerId::from_static("s"),
        }
    }

    #[test]
    fn coverage_distinguishes_all_some_none_unknown() {
        let missing = RouteSupport::NoServer;
        assert_eq!(
            ToolCoverage::from_routes([].iter()),
            ToolCoverage::Unsupported
        );
        assert_eq!(
            ToolCoverage::from_routes([supported(), supported()].iter()),
            ToolCoverage::All
        );
        assert_eq!(
            ToolCoverage::from_routes([supported(), missing.clone()].iter()),
            ToolCoverage::Partial
        );
        assert_eq!(
            ToolCoverage::from_routes([supported(), RouteSupport::Initializing].iter()),
            ToolCoverage::Partial
        );
        assert_eq!(
            ToolCoverage::from_routes([missing.clone(), RouteSupport::Initializing].iter()),
            ToolCoverage::Unknown
        );
        assert_eq!(
            ToolCoverage::from_routes([missing, RouteSupport::NoServer].iter()),
            ToolCoverage::Unsupported
        );
    }

    #[test]
    fn coverage_serializes_to_spec_names() {
        let names: Vec<String> = [
            ToolCoverage::All,
            ToolCoverage::Partial,
            ToolCoverage::Unsupported,
            ToolCoverage::Unknown,
            ToolCoverage::Always,
        ]
        .iter()
        .map(|c| {
            serde_json::to_value(c)
                .unwrap()
                .as_str()
                .unwrap()
                .to_string()
        })
        .collect();
        assert_eq!(names, ["all", "some", "none", "unknown", "always"]);
    }

    #[test]
    fn tool_names_are_unique() {
        let mut names: Vec<&str> = McpTool::ALL.iter().map(|t| t.name()).collect();
        names.sort_unstable();
        names.dedup();
        assert_eq!(names.len(), McpTool::ALL.len());
    }

    #[test]
    fn prefixed_tool_name_joins_with_underscore() {
        let prefix: ToolPrefix = "optics".parse().unwrap();
        assert_eq!(
            prefixed_tool_name(Some(&prefix), "get_hover"),
            "optics_get_hover"
        );
        assert_eq!(prefixed_tool_name(None, "get_hover"), "get_hover");
    }

    #[test]
    fn document_routes_group_identical_support_in_first_seen_order() {
        let none = RouteSupport::NoServer;
        let routes = ToolRoutes::grouped(vec![
            (LanguageId::from_static("c"), none.clone()),
            (LanguageId::from_static("go"), supported()),
            (LanguageId::from_static("java"), none),
            (LanguageId::from_static("rust"), supported()),
        ]);
        assert_eq!(
            serde_json::to_value(&routes).unwrap(),
            serde_json::json!([
                {"languages": ["c", "java"], "status": "no_server"},
                {"languages": ["go", "rust"], "status": "supported", "server": "s"},
            ])
        );
    }

    #[test]
    fn push_only_route_serializes_as_push_only_with_its_server() {
        let push_only = RouteSupport::PushOnly {
            server: ServerId::from_static("ts"),
        };
        assert_eq!(
            serde_json::to_value(&push_only).unwrap(),
            serde_json::json!({"status": "push_only", "server": "ts"})
        );
        assert_eq!(
            ToolCoverage::from_routes([&push_only].into_iter()),
            ToolCoverage::All
        );
    }

    #[test]
    fn workspace_route_serializes_without_languages() {
        assert_eq!(
            serde_json::to_value(ToolRoutes::Workspace(RouteSupport::NoServer)).unwrap(),
            serde_json::json!([{"status": "no_server"}])
        );
    }
}