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
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
//! MCP tool parameter definitions.

use std::path::PathBuf;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::bridge::{
    CodeActionKindFilter, CompletionTrigger, FoldingKindFilter, HierarchyItem, InvalidTextField,
    KindFilterField, KindFilterInput, LogLevel, MAX_RESTART_SERVER_IDS, MAX_SERVER_ID_BYTES,
    NewName, Position, Position2D, Range, RestartTarget, ResultContext, ServerIds, ServerIdsError,
    SymbolKindFilter, SymbolName, SymbolQuery, SymbolTarget, TabSize, TextField,
};
use crate::error::Error;

/// Schema description of the opt-in `context` input shared by every tool that
/// can attach enclosing symbols.
const CONTEXT_DESCRIPTION: &str = "Extra context: `none` (default) or `enclosing_symbol` (innermost symbol, one request per file).\n\nAttaches the name path, kind and range of the innermost containing symbol. Costs one documentSymbol request per distinct file, capped per call.";

/// Declares a wire struct whose first fields are a file path and a 1-based
/// position, followed by the tool's own fields.
///
/// Wire structs deny unknown fields, which rules out `#[serde(flatten)]`, so
/// each tool spells out the shared fields through these macros instead.
macro_rules! position_wire {
    ($(#[$meta:meta])* $name:ident { $($extra:tt)* }) => {
        #[derive(Debug, Clone, Deserialize, JsonSchema)]
        #[serde(deny_unknown_fields)]
        $(#[$meta])*
        struct $name {
            #[schemars(description = "Absolute path to the file.")]
            file_path: PathBuf,
            #[schemars(description = "Line number (1-based).")]
            line: u32,
            #[schemars(description = "Character/column number (1-based).")]
            character: u32,
            $($extra)*
        }
    };
}

/// Declares a wire struct whose first fields are a file path and a 1-based
/// range, followed by the tool's own fields.
macro_rules! range_wire {
    ($(#[$meta:meta])* $name:ident { $($extra:tt)* }) => {
        #[derive(Debug, Clone, Deserialize, JsonSchema)]
        #[serde(deny_unknown_fields)]
        $(#[$meta])*
        struct $name {
            #[schemars(description = "Absolute path to the file.")]
            file_path: PathBuf,
            #[schemars(description = "Start line (1-based).")]
            start_line: u32,
            #[schemars(description = "Start character (1-based).")]
            start_character: u32,
            #[schemars(description = "End line (1-based).")]
            end_line: u32,
            #[schemars(description = "End character (1-based).")]
            end_character: u32,
            $($extra)*
        }

        impl $name {
            const fn range(&self) -> RangeParams {
                RangeParams {
                    start_line: self.start_line,
                    start_character: self.start_character,
                    end_line: self.end_line,
                    end_character: self.end_character,
                }
            }
        }
    };
}

/// Declares a wire struct whose first fields address a symbol in a file, by
/// position or by name, followed by the tool's own fields.
macro_rules! target_wire {
    ($(#[$meta:meta])* $name:ident { $($extra:tt)* }) => {
        #[derive(Debug, Clone, Deserialize, JsonSchema)]
        #[serde(deny_unknown_fields)]
        $(#[$meta])*
        struct $name {
            #[schemars(description = "Absolute path to the file.")]
            file_path: PathBuf,
            #[schemars(
                description = "Line number (1-based). Give with `character`, instead of `symbol_name`."
            )]
            #[serde(default)]
            line: Option<u32>,
            #[schemars(
                description = "Character/column number (1-based). Give with `line`, instead of `symbol_name`."
            )]
            #[serde(default)]
            character: Option<u32>,
            #[schemars(
                description = "Name of a symbol defined in this file, instead of `line`/`character`. May be qualified (`Type::method`, `Type.method`). If it matches several symbols the call fails and lists them."
            )]
            #[serde(default)]
            symbol_name: Option<String>,
            #[schemars(
                description = "With `symbol_name`: keep only symbols of this kind, by name (function, method, class, struct, ...) or numeric LSP SymbolKind value."
            )]
            #[serde(default)]
            symbol_kind: Option<KindFilterInput<SymbolKindFilter>>,
            #[schemars(
                description = "With `symbol_name`: keep only symbols inside a container (type, impl, class, module) of this name.\n\nOnly symbols directly inside the container match."
            )]
            #[serde(default)]
            container: Option<String>,
            $($extra)*
        }

        impl $name {
            /// Moves the addressing fields out into the target, leaving them
            /// empty; the tool's own fields stay in place.
            fn take_target(&mut self) -> Result<SymbolTargetParams, TargetAddressError> {
                SymbolTargetParams::from_parts(
                    std::mem::take(&mut self.file_path),
                    PositionFields {
                        line: self.line,
                        character: self.character,
                    },
                    self.symbol_name.take(),
                    self.symbol_kind.take(),
                    self.container.take(),
                )
            }
        }
    };
}

/// Why the addressing fields of a tool call do not name exactly one symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum TargetAddressError {
    /// `symbol_kind` or `container` was given without `symbol_name`.
    #[error("`symbol_kind` and `container` apply only with `symbol_name`")]
    QualifierWithoutName,
    /// Both a position and a `symbol_name` were given.
    #[error("give either `line` and `character`, or `symbol_name`, not both")]
    BothForms,
    /// Neither a position nor a `symbol_name` was given.
    #[error("give `line` and `character`, or `symbol_name`")]
    NoForm,
    /// Only one of `line` and `character` was given.
    #[error("`line` and `character` must be given together and not with `symbol_name`")]
    HalfPosition,
    /// The symbol name or container is blank or too long.
    #[error(transparent)]
    Name(#[from] InvalidTextField),
}

/// The `line` and `character` fields of a call as the client wrote them,
/// either of which may be absent.
#[derive(Debug, Clone, Copy)]
struct PositionFields {
    line: Option<u32>,
    character: Option<u32>,
}

/// A complete, still unchecked 1-based position.
#[derive(Debug, Clone, Copy)]
struct WirePosition {
    line: u32,
    character: u32,
}

impl PositionFields {
    /// The position when both fields are given, `None` when neither is.
    const fn complete(self) -> Result<Option<WirePosition>, TargetAddressError> {
        match (self.line, self.character) {
            (Some(line), Some(character)) => Ok(Some(WirePosition { line, character })),
            (None, None) => Ok(None),
            _ => Err(TargetAddressError::HalfPosition),
        }
    }
}

/// Shared position parameters (file path plus 1-based line/character) used by
/// every tool that operates at a single point in a file.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PositionParams {
    /// Absolute path to the file.
    #[schemars(description = "Absolute path to the file.")]
    pub file_path: PathBuf,
    /// Line number (1-based).
    #[schemars(description = "Line number (1-based).")]
    pub line: u32,
    /// Character/column number (1-based).
    #[schemars(description = "Character/column number (1-based).")]
    pub character: u32,
}

/// Shared range parameters (1-based start/end line and character) used by
/// every tool that operates over a range in a file.
#[derive(Debug, Clone)]
pub struct RangeParams {
    /// Start line (1-based).
    pub start_line: u32,
    /// Start character (1-based).
    pub start_character: u32,
    /// End line (1-based).
    pub end_line: u32,
    /// End character (1-based).
    pub end_character: u32,
}

target_wire! {
    /// Wire form of [`SymbolTargetParams`]: a file plus either a position or a
    /// symbol name.
    #[schemars(
        description = "A file plus the symbol to act on: give either `line` and `character`, or `symbol_name`."
    )]
    SymbolTargetWire {}
}

/// A file and the symbol in it a tool acts on, addressed by position or by
/// name. Exactly one addressing form is representable: a request with both,
/// neither, half a position, or qualifiers without a name fails to
/// deserialize and is reported as invalid parameters.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(try_from = "SymbolTargetWire")]
#[schemars(with = "SymbolTargetWire")]
pub struct SymbolTargetParams {
    /// Absolute path to the file.
    pub file_path: PathBuf,
    /// The symbol to act on, as the client wrote it.
    pub target: SymbolTargetInput,
}

/// A symbol addressed by position or by name, before the position is checked.
///
/// The position and the kind filter stay raw so a bad value is rejected as
/// invalid parameters (JSON-RPC `-32602`) by [`Self::into_target`] in the tool
/// method, not as a deserialization failure, which MCP reports as a
/// tool-result error.
#[derive(Debug, Clone)]
pub enum SymbolTargetInput {
    /// A 1-based position, unchecked.
    Position {
        /// Line number (1-based).
        line: u32,
        /// Character offset (1-based).
        character: u32,
    },
    /// A symbol name with optional qualifiers.
    Name {
        /// The symbol's name, optionally qualified.
        name: SymbolName,
        /// Keep only symbols of this kind, unchecked.
        kind: Option<KindFilterInput<SymbolKindFilter>>,
        /// Keep only symbols directly inside a container of this name.
        container: Option<SymbolName>,
    },
}

impl SymbolTargetInput {
    /// Checks the position or the kind filter and yields the typed target.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidPositionInput`] for a position below 1 or above
    /// [`MAX_POSITION_VALUE`](crate::bridge::MAX_POSITION_VALUE), and
    /// [`Error::InvalidToolParams`] for a `symbol_kind` that names no kind.
    pub fn into_target(self) -> Result<SymbolTarget, Error> {
        match self {
            Self::Position { line, character } => Ok(SymbolTarget::Position(
                Position::from_client(line, character)?,
            )),
            Self::Name {
                name,
                kind,
                container,
            } => Ok(SymbolTarget::Name(SymbolQuery {
                name,
                kind: kind
                    .map(|kind| kind.into_known(KindFilterField::SymbolKind))
                    .transpose()?
                    .map(SymbolKindFilter::kind),
                container,
            })),
        }
    }
}

impl SymbolTargetParams {
    /// Builds the target from the addressing fields of a tool call.
    ///
    /// # Errors
    ///
    /// A [`TargetAddressError`] when the fields do not address exactly one
    /// symbol, or when a symbol name or container is blank or too long.
    fn from_parts(
        file_path: PathBuf,
        position: PositionFields,
        symbol_name: Option<String>,
        symbol_kind: Option<KindFilterInput<SymbolKindFilter>>,
        container: Option<String>,
    ) -> Result<Self, TargetAddressError> {
        let target = match (position.complete()?, symbol_name) {
            (Some(WirePosition { line, character }), None) => {
                if symbol_kind.is_some() || container.is_some() {
                    return Err(TargetAddressError::QualifierWithoutName);
                }
                SymbolTargetInput::Position { line, character }
            }
            (None, Some(name)) => SymbolTargetInput::Name {
                name: SymbolName::new(name).map_err(InvalidTextField::of(TextField::SymbolName))?,
                kind: symbol_kind,
                container: container
                    .map(|container| {
                        SymbolName::new(container)
                            .map_err(InvalidTextField::of(TextField::Container))
                    })
                    .transpose()?,
            },
            (Some(_), Some(_)) => return Err(TargetAddressError::BothForms),
            (None, None) => return Err(TargetAddressError::NoForm),
        };
        Ok(Self { file_path, target })
    }
}

impl TryFrom<SymbolTargetWire> for SymbolTargetParams {
    type Error = TargetAddressError;

    fn try_from(mut wire: SymbolTargetWire) -> Result<Self, Self::Error> {
        wire.take_target()
    }
}

#[cfg(test)]
impl From<PositionParams> for SymbolTargetParams {
    fn from(position: PositionParams) -> Self {
        Self {
            file_path: position.file_path,
            target: SymbolTargetInput::Position {
                line: position.line,
                character: position.character,
            },
        }
    }
}

target_wire! {
    /// Wire form of [`ReferencesParams`].
    #[schemars(description = "Parameters for finding all references to a symbol.")]
    ReferencesWire {
        #[schemars(description = "Whether to include the declaration in the results.")]
        #[serde(default)]
        include_declaration: bool,
        #[schemars(description = CONTEXT_DESCRIPTION)]
        #[serde(default)]
        context: ResultContext,
    }
}

/// Parameters for the `get_references` tool.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(try_from = "ReferencesWire")]
#[schemars(with = "ReferencesWire")]
pub struct ReferencesParams {
    /// The symbol to find references to.
    pub target: SymbolTargetParams,
    /// Whether to include the declaration in the results.
    pub include_declaration: bool,
    /// Optional extra context for each returned item.
    pub context: ResultContext,
}

impl TryFrom<ReferencesWire> for ReferencesParams {
    type Error = TargetAddressError;

    fn try_from(mut wire: ReferencesWire) -> Result<Self, Self::Error> {
        Ok(Self {
            target: wire.take_target()?,
            include_declaration: wire.include_declaration,
            context: wire.context,
        })
    }
}

target_wire! {
    /// Wire form of [`NavigationParams`].
    #[schemars(description = "Parameters for navigating from a symbol to related locations.")]
    NavigationWire {
        #[schemars(description = CONTEXT_DESCRIPTION)]
        #[serde(default)]
        context: ResultContext,
    }
}

/// Parameters for the `get_definition`, `go_to_implementation` and
/// `go_to_type_definition` tools.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(try_from = "NavigationWire")]
#[schemars(with = "NavigationWire")]
pub struct NavigationParams {
    /// The symbol to navigate from.
    pub target: SymbolTargetParams,
    /// Optional extra context for each returned item.
    pub context: ResultContext,
}

impl TryFrom<NavigationWire> for NavigationParams {
    type Error = TargetAddressError;

    fn try_from(mut wire: NavigationWire) -> Result<Self, Self::Error> {
        Ok(Self {
            target: wire.take_target()?,
            context: wire.context,
        })
    }
}

#[cfg(test)]
impl From<PositionParams> for NavigationParams {
    fn from(position: PositionParams) -> Self {
        Self {
            target: position.into(),
            context: ResultContext::None,
        }
    }
}

position_wire! {
    /// Wire form of [`DeclarationParams`].
    #[schemars(description = "Parameters for navigating from a position to its declaration.")]
    DeclarationWire {
        #[schemars(description = CONTEXT_DESCRIPTION)]
        #[serde(default)]
        context: ResultContext,
    }
}

/// Parameters for the `go_to_declaration` tool.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(from = "DeclarationWire")]
#[schemars(with = "DeclarationWire")]
pub struct DeclarationParams {
    /// The position to navigate from.
    pub position: PositionParams,
    /// Optional extra context for each returned item.
    pub context: ResultContext,
}

impl From<DeclarationWire> for DeclarationParams {
    fn from(wire: DeclarationWire) -> Self {
        Self {
            position: PositionParams {
                file_path: wire.file_path,
                line: wire.line,
                character: wire.character,
            },
            context: wire.context,
        }
    }
}

#[cfg(test)]
impl From<PositionParams> for DeclarationParams {
    fn from(position: PositionParams) -> Self {
        Self {
            position,
            context: ResultContext::None,
        }
    }
}

/// Parameters for the `get_diagnostics` tool.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(description = "Parameters for getting diagnostics (errors, warnings) for a file.")]
pub struct DiagnosticsParams {
    /// Absolute path to the file.
    #[schemars(description = "Absolute path to the file.")]
    pub file_path: PathBuf,
    /// Optional extra context for each returned item.
    #[schemars(description = CONTEXT_DESCRIPTION)]
    #[serde(default)]
    pub context: ResultContext,
}

target_wire! {
    /// Wire form of [`RenameParams`].
    #[schemars(description = "Parameters for renaming a symbol across the workspace.")]
    RenameWire {
        #[schemars(description = "New name for the symbol (non-blank, at most 1000 bytes).")]
        #[schemars(with = "String")]
        new_name: NewName,
    }
}

/// Parameters for the `rename_symbol` tool.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(try_from = "RenameWire")]
#[schemars(with = "RenameWire")]
pub struct RenameParams {
    /// The symbol to rename.
    pub target: SymbolTargetParams,
    /// New name for the symbol.
    pub new_name: NewName,
}

impl TryFrom<RenameWire> for RenameParams {
    type Error = TargetAddressError;

    fn try_from(mut wire: RenameWire) -> Result<Self, Self::Error> {
        Ok(Self {
            target: wire.take_target()?,
            new_name: wire.new_name,
        })
    }
}

position_wire! {
    /// Wire form of [`CompletionsParams`].
    #[schemars(description = "Parameters for getting code completion suggestions.")]
    CompletionsWire {
        #[schemars(
            description = "Optional trigger character (e.g., '.', ':', '->'), 1 to 8 bytes."
        )]
        #[schemars(with = "Option<String>")]
        trigger: Option<CompletionTrigger>,
    }
}

/// Parameters for the `get_completions` tool.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(from = "CompletionsWire")]
#[schemars(with = "CompletionsWire")]
pub struct CompletionsParams {
    /// Position in the file to operate on.
    pub position: PositionParams,
    /// Optional trigger character (e.g., '.', ':', '->').
    pub trigger: Option<CompletionTrigger>,
}

impl From<CompletionsWire> for CompletionsParams {
    fn from(wire: CompletionsWire) -> Self {
        Self {
            position: PositionParams {
                file_path: wire.file_path,
                line: wire.line,
                character: wire.character,
            },
            trigger: wire.trigger,
        }
    }
}

/// Parameters for the `get_folding_ranges` tool.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(description = "Parameters for getting the foldable regions of a file.")]
pub struct FoldingRangesParams {
    /// Absolute path to the file.
    #[schemars(description = "Absolute path to the file.")]
    pub file_path: PathBuf,
    /// Which regions to return.
    #[schemars(
        description = "`all` (default), `comment`, `imports` or `region`; regions without a kind match only `all`."
    )]
    #[schemars(with = "FoldingKindFilter", transform = without_default)]
    #[serde(default)]
    pub kind: KindFilterInput<FoldingKindFilter>,
}

/// Parameters for the `get_document_symbols` tool.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(description = "Parameters for getting all symbols in a document.")]
pub struct DocumentSymbolsParams {
    /// Absolute path to the file.
    #[schemars(description = "Absolute path to the file.")]
    pub file_path: PathBuf,
}

/// Parameters for the `format_document` tool.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(description = "Parameters for formatting a document.")]
pub struct FormatDocumentParams {
    /// Absolute path to the file.
    #[schemars(description = "Absolute path to the file.")]
    pub file_path: PathBuf,
    /// Tab size for formatting (1 to 32, default: 4).
    #[schemars(description = "Tab size for formatting (1 to 32, default: 4).")]
    #[serde(default)]
    pub tab_size: TabSize,
    /// Whether to use spaces instead of tabs (default: true).
    #[schemars(description = "Whether to use spaces instead of tabs (default: true).")]
    #[serde(default = "default_insert_spaces")]
    pub insert_spaces: bool,
}

const fn default_insert_spaces() -> bool {
    true
}

/// Parameters for the `workspace_symbol_search` tool.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(description = "Parameters for searching symbols across the workspace.")]
pub struct WorkspaceSymbolParams {
    /// Search query for symbol names (supports partial matching).
    #[schemars(description = "Search query for symbol names (supports partial matching).")]
    pub query: String,
    /// Optional filter by symbol kind: a name (function, class, variable,
    /// etc.) or the numeric LSP `SymbolKind` value from a result's `kind`
    /// field. A name is validated against the known kinds; a numeric value
    /// is accepted as-is with no validation (it may name a server-specific
    /// custom kind), so a value that matches no symbol returns an empty
    /// result rather than an error.
    #[schemars(
        description = "Optional symbol kind filter: a name (function, class) or the numeric LSP `SymbolKind`.\n\nThe number is the `kind` of a result's symbol. \
                        A name is validated against the known kinds; a numeric value is accepted \
                        as-is with no validation, so one that matches no symbol returns an empty \
                        result rather than an error."
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind_filter: Option<KindFilterInput<SymbolKindFilter>>,
    /// Maximum results to return (default: 100).
    #[schemars(description = "Maximum results to return (default: 100).")]
    #[serde(default = "default_max_results")]
    pub limit: u32,
}

const fn default_max_results() -> u32 {
    100
}

range_wire! {
    /// Wire form of [`CodeActionsParams`].
    #[schemars(
        description = "Parameters for getting available code actions (quick fixes, refactorings) for a range."
    )]
    CodeActionsWire {
        #[schemars(
            description = "Optional filter by action kind, in any case; sent to the server in its canonical spelling."
        )]
        kind_filter: Option<KindFilterInput<CodeActionKindFilter>>,
    }
}

/// Parameters for the `get_code_actions` tool.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(from = "CodeActionsWire")]
#[schemars(with = "CodeActionsWire")]
pub struct CodeActionsParams {
    /// Absolute path to the file.
    pub file_path: PathBuf,
    /// Range in the file to operate on.
    pub range: RangeParams,
    /// Optional filter by action kind (quickfix, refactor, source, etc.).
    pub kind_filter: Option<KindFilterInput<CodeActionKindFilter>>,
}

impl From<CodeActionsWire> for CodeActionsParams {
    fn from(wire: CodeActionsWire) -> Self {
        let range = wire.range();
        Self {
            file_path: wire.file_path,
            range,
            kind_filter: wire.kind_filter,
        }
    }
}

/// Drops the `default` annotation, which the advertised schema of an input
/// that echoes a result field does not carry.
fn without_default(schema: &mut schemars::Schema) {
    schema.remove("default");
}

/// Input form of [`Position2D`]: the same schema under the same name, closed
/// to unknown fields. The output type stays open for compatible additions.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
    rename = "Position2D",
    description = "Position in a document (1-based for MCP)."
)]
struct Position2DInput {
    /// Line number (1-based).
    line: u32,
    /// Character offset (1-based).
    character: u32,
}

/// Input form of [`Range`]: the same schema under the same name, closed to
/// unknown fields.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
    rename = "Range",
    description = "Range in a document (1-based for MCP)."
)]
struct RangeInput {
    /// Start position.
    start: Position2DInput,
    /// End position.
    end: Position2DInput,
}

/// Input form of [`HierarchyItem`]: the same schema under the same name,
/// closed to unknown fields except `data`, which is opaque by contract.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
    rename = "HierarchyItem",
    description = "A call or type hierarchy item."
)]
struct HierarchyItemInput {
    /// Name of the symbol.
    name: String,
    /// LSP numeric symbol kind (e.g. 12 for Function, 5 for Class).
    kind: u32,
    /// More detail for this item.
    detail: Option<String>,
    /// URI of the document.
    uri: String,
    /// Range of the symbol.
    range: RangeInput,
    /// Selection range (identifier location).
    #[serde(rename = "selectionRange")]
    selection_range: RangeInput,
    /// Opaque data to pass back unchanged.
    data: Option<serde_json::Value>,
    /// Whether this item is not provably inside any configured workspace
    /// root. Ignored on input.
    #[serde(default)]
    #[schemars(transform = without_default)]
    out_of_workspace: bool,
}

impl From<Position2DInput> for Position2D {
    fn from(position: Position2DInput) -> Self {
        Self {
            line: position.line,
            character: position.character,
        }
    }
}

impl From<RangeInput> for Range {
    fn from(range: RangeInput) -> Self {
        Self {
            start: range.start.into(),
            end: range.end.into(),
        }
    }
}

impl From<HierarchyItemInput> for HierarchyItem {
    fn from(item: HierarchyItemInput) -> Self {
        Self {
            name: item.name,
            kind: item.kind,
            detail: item.detail,
            uri: item.uri,
            range: item.range.into(),
            selection_range: item.selection_range.into(),
            data: item.data,
            out_of_workspace: item.out_of_workspace,
        }
    }
}

/// Wire form of [`CallHierarchyCallsParams`].
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
    description = "Parameters for getting incoming or outgoing calls for a call hierarchy item."
)]
struct CallHierarchyCallsWire {
    #[schemars(
        description = "The call hierarchy item, exactly as a prepare, incoming or outgoing call result gave it."
    )]
    item: HierarchyItemInput,
}

/// Wire form of [`TypeHierarchyWalkParams`].
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
    description = "Parameters for getting the supertypes or subtypes of a type hierarchy item."
)]
struct TypeHierarchyWalkWire {
    #[schemars(
        description = "The type hierarchy item, exactly as a prepare, supertypes or subtypes result gave it."
    )]
    item: HierarchyItemInput,
}

/// Parameters for the `get_incoming_calls` and `get_outgoing_calls` tools.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(from = "CallHierarchyCallsWire")]
#[schemars(with = "CallHierarchyCallsWire")]
pub struct CallHierarchyCallsParams {
    /// The call hierarchy item to get calls for (from prepare response).
    pub item: HierarchyItem,
}

impl From<CallHierarchyCallsWire> for CallHierarchyCallsParams {
    fn from(wire: CallHierarchyCallsWire) -> Self {
        Self {
            item: wire.item.into(),
        }
    }
}

/// Parameters for the `get_supertypes` and `get_subtypes` tools.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(from = "TypeHierarchyWalkWire")]
#[schemars(with = "TypeHierarchyWalkWire")]
pub struct TypeHierarchyWalkParams {
    /// The type hierarchy item to walk from (from a prepare, supertypes or subtypes response).
    pub item: HierarchyItem,
}

impl From<TypeHierarchyWalkWire> for TypeHierarchyWalkParams {
    fn from(wire: TypeHierarchyWalkWire) -> Self {
        Self {
            item: wire.item.into(),
        }
    }
}

range_wire! {
    /// Wire form of [`FormatRangeParams`].
    #[schemars(description = "Parameters for formatting a range of a document.")]
    FormatRangeWire {
        #[schemars(description = "Tab size for formatting (1 to 32, default: 4).")]
        #[serde(default)]
        tab_size: TabSize,
        #[schemars(description = "Whether to use spaces instead of tabs (default: true).")]
        #[serde(default = "default_insert_spaces")]
        insert_spaces: bool,
    }
}

/// Parameters for the `format_range` tool.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(from = "FormatRangeWire")]
#[schemars(with = "FormatRangeWire")]
pub struct FormatRangeParams {
    /// Absolute path to the file.
    pub file_path: PathBuf,
    /// Range in the file to format.
    pub range: RangeParams,
    /// Tab size for formatting (1 to 32, default: 4).
    pub tab_size: TabSize,
    /// Whether to use spaces instead of tabs (default: true).
    pub insert_spaces: bool,
}

impl From<FormatRangeWire> for FormatRangeParams {
    fn from(wire: FormatRangeWire) -> Self {
        let range = wire.range();
        Self {
            file_path: wire.file_path,
            range,
            tab_size: wire.tab_size,
            insert_spaces: wire.insert_spaces,
        }
    }
}

/// Parameters for the `get_cached_diagnostics` tool.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
    description = "Parameters for getting cached diagnostics from LSP server notifications."
)]
pub struct CachedDiagnosticsParams {
    /// Absolute path to the file.
    #[schemars(description = "Absolute path to the file.")]
    pub file_path: PathBuf,
}

/// Parameters for the `get_server_logs` tool.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(description = "Parameters for getting recent LSP server log messages.")]
pub struct ServerLogsParams {
    /// Maximum number of log entries to return (default: 50).
    #[schemars(description = "Maximum number of log entries to return (default: 50).")]
    #[serde(default = "default_log_limit")]
    pub limit: usize,
    /// Minimum log level to include: error, warning, info, debug.
    #[schemars(description = "Minimum log level to include: error, warning, info, debug.")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_level: Option<LogLevel>,
}

const fn default_log_limit() -> usize {
    50
}

/// Parameters for the `get_server_messages` tool.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
    description = "Parameters for getting recent LSP server messages (showMessage notifications)."
)]
pub struct ServerMessagesParams {
    /// Maximum number of messages to return (default: 20).
    #[schemars(description = "Maximum number of messages to return (default: 20).")]
    #[serde(default = "default_message_limit")]
    pub limit: usize,
}

const fn default_message_limit() -> usize {
    20
}

/// Parameters for the `get_tool_support` tool.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(description = "Parameters for reporting which tools are usable for which languages.")]
pub struct ToolSupportParams {
    /// Restrict the report to the language of this file.
    #[schemars(description = "Absolute path to a file; restricts the report to its language.")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_path: Option<PathBuf>,
}

/// Wire form of [`RestartServerParams`]: exactly one of the two fields selects
/// the servers.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
    description = "Parameters for restarting LSP servers. Give exactly one of `servers` or `all`."
)]
struct RestartServerWire {
    /// Ids of the servers to restart.
    #[schemars(
        description = "Ids of the servers to restart; an unknown id is rejected with the list of configured ids. Non-empty."
    )]
    #[schemars(length(max = MAX_RESTART_SERVER_IDS), inner(length(max = MAX_SERVER_ID_BYTES)))]
    #[serde(default)]
    servers: Option<Vec<String>>,
    /// Restart every configured server.
    #[schemars(description = "Set to true to restart every configured server.")]
    #[serde(default)]
    all: bool,
}

/// Parameters for the `restart_server` tool, parsed into a [`RestartTarget`]
/// at deserialization so a bare call, an empty list, or both selectors are
/// rejected as invalid parameters.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(try_from = "RestartServerWire")]
#[schemars(with = "RestartServerWire")]
pub struct RestartServerParams {
    /// Which servers to restart.
    pub target: RestartTarget,
}

/// Why the selectors of a `restart_server` call do not name a set of servers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum RestartTargetError {
    /// Both `servers` and `all` were given.
    #[error("give either `servers` or `all`, not both")]
    BothSelectors,
    /// Neither `servers` nor `all: true` was given.
    #[error("give `servers` (a non-empty list of server ids) or `all: true`")]
    NoSelector,
    /// The `servers` list is empty, too long or holds a bad id.
    #[error(transparent)]
    Servers(#[from] ServerIdsError),
}

impl TryFrom<RestartServerWire> for RestartServerParams {
    type Error = RestartTargetError;

    fn try_from(wire: RestartServerWire) -> Result<Self, Self::Error> {
        let target = match (wire.servers, wire.all) {
            (Some(_), true) => return Err(RestartTargetError::BothSelectors),
            (None, false) => return Err(RestartTargetError::NoSelector),
            (None, true) => RestartTarget::All,
            (Some(ids), false) => RestartTarget::Servers(ServerIds::parse(ids)?),
        };
        Ok(Self { target })
    }
}

range_wire! {
    /// Wire form of [`InlayHintsParams`].
    #[schemars(description = "Parameters for getting inlay hints in a range.")]
    InlayHintsWire {}
}

/// Parameters for the `get_inlay_hints` tool.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(from = "InlayHintsWire")]
#[schemars(with = "InlayHintsWire")]
pub struct InlayHintsParams {
    /// Absolute path to the file.
    pub file_path: PathBuf,
    /// Range in the file to operate on.
    pub range: RangeParams,
}

impl From<InlayHintsWire> for InlayHintsParams {
    fn from(wire: InlayHintsWire) -> Self {
        let range = wire.range();
        Self {
            file_path: wire.file_path,
            range,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;
    use std::path::Path;

    use super::*;
    use crate::bridge::{MAX_NEW_NAME_LENGTH, MAX_TRIGGER_CHARACTER_BYTES};

    #[test]
    fn restart_params_accept_servers_or_all() {
        let one: RestartServerParams =
            serde_json::from_value(serde_json::json!({"servers": ["rust", "rust", "py"]})).unwrap();
        let RestartTarget::Servers(ids) = one.target else {
            panic!("expected a server list");
        };
        assert_eq!(ids.as_slice().len(), 2);

        let all: RestartServerParams =
            serde_json::from_value(serde_json::json!({"all": true})).unwrap();
        assert_eq!(all.target, RestartTarget::All);
    }

    #[test]
    fn restart_params_reject_ambiguous_or_empty_selectors() {
        for bad in [
            serde_json::json!({}),
            serde_json::json!({"all": false}),
            serde_json::json!({"servers": []}),
            serde_json::json!({"servers": [" "]}),
            serde_json::json!({"servers": ["rust"], "all": true}),
            serde_json::json!({"servers": (0..=MAX_RESTART_SERVER_IDS).map(|i| format!("s{i}")).collect::<Vec<_>>()}),
            serde_json::json!({"servers": ["x".repeat(MAX_SERVER_ID_BYTES + 1)]}),
        ] {
            assert!(
                serde_json::from_value::<RestartServerParams>(bad.clone()).is_err(),
                "{bad}"
            );
        }
    }

    #[test]
    fn restart_params_schema_exposes_wire_fields() {
        let schema = schemars::schema_for!(RestartServerParams);
        let properties = schema
            .as_object()
            .unwrap()
            .get("properties")
            .unwrap()
            .as_object()
            .unwrap();
        assert!(properties.contains_key("servers"));
        assert!(properties.contains_key("all"));
        assert!(!properties.contains_key("target"));
        let servers = &properties["servers"];
        assert_eq!(servers["maxItems"], MAX_RESTART_SERVER_IDS);
        assert_eq!(servers["items"]["maxLength"], MAX_SERVER_ID_BYTES);
    }

    /// A flat JSON object (what an MCP client actually sends) must deserialize
    /// into the nested Rust shape.
    #[test]
    fn flat_json_deserializes_into_flattened_params() {
        let json = serde_json::json!({"file_path": "/a.rs", "line": 1, "character": 2});
        let references: ReferencesParams = serde_json::from_value(json).unwrap();
        assert_eq!(references.target.file_path.as_path(), Path::new("/a.rs"));
        assert_matches!(
            references.target.target,
            SymbolTargetInput::Position {
                line: 1,
                character: 2
            }
        );
        assert!(!references.include_declaration);

        let json = serde_json::json!({
            "file_path": "/a.rs",
            "symbol_name": "parse",
            "symbol_kind": "function",
            "container": "Config",
            "include_declaration": true,
        });
        let references: ReferencesParams = serde_json::from_value(json).unwrap();
        assert!(references.include_declaration);
        let SymbolTarget::Name(query) = references.target.target.into_target().unwrap() else {
            panic!("expected a name target");
        };
        assert_eq!(query.name.as_str(), "parse");
        assert_eq!(query.kind, Some(lsp_types::SymbolKind::Function));
        assert_eq!(query.container.unwrap().as_str(), "Config");
    }

    #[test]
    fn symbol_target_accepts_exactly_one_addressing_form() {
        let parse = |json: serde_json::Value| serde_json::from_value::<SymbolTargetParams>(json);
        assert!(
            parse(serde_json::json!({"file_path": "/a.rs", "line": 1, "character": 1})).is_ok()
        );
        assert!(parse(serde_json::json!({"file_path": "/a.rs", "symbol_name": "f"})).is_ok());
        for bad in [
            serde_json::json!({"file_path": "/a.rs"}),
            serde_json::json!({"file_path": "/a.rs", "line": 1}),
            serde_json::json!({"file_path": "/a.rs", "character": 1}),
            serde_json::json!({"file_path": "/a.rs", "line": 1, "character": 1, "symbol_name": "f"}),
            serde_json::json!({"file_path": "/a.rs", "line": 1, "symbol_name": "f"}),
            serde_json::json!({"file_path": "/a.rs", "line": 1, "character": 1, "container": "T"}),
            serde_json::json!({"file_path": "/a.rs", "symbol_name": " "}),
            serde_json::json!({"file_path": "/a.rs", "symbol_name": "f", "container": ""}),
        ] {
            assert!(parse(bad.clone()).is_err(), "{bad}");
        }
    }

    #[test]
    fn restart_selector_errors_are_typed() {
        let parse = |json: serde_json::Value| {
            serde_json::from_value::<RestartServerParams>(json)
                .unwrap_err()
                .to_string()
        };
        assert!(parse(serde_json::json!({"servers": ["a"], "all": true})).contains("not both"));
        assert!(parse(serde_json::json!({})).contains("or `all: true`"));
        assert!(parse(serde_json::json!({"servers": []})).contains("must not be empty"));
    }

    #[test]
    fn symbol_target_errors_name_the_violated_rule() {
        let error = |json: serde_json::Value| {
            serde_json::from_value::<SymbolTargetParams>(json)
                .unwrap_err()
                .to_string()
        };
        assert!(error(serde_json::json!({"file_path": "/a.rs"})).contains("give `line`"));
        assert!(
            error(serde_json::json!({"file_path": "/a.rs", "line": 1}))
                .contains("must be given together")
        );
        assert!(
            error(serde_json::json!({"file_path": "/a.rs", "symbol_name": " "}))
                .contains("`symbol_name` cannot be empty")
        );
    }

    #[test]
    fn rename_rejects_a_blank_or_oversized_new_name_while_parsing() {
        let parse = |new_name: &str| {
            serde_json::from_value::<RenameParams>(serde_json::json!({
                "file_path": "/a.rs", "line": 1, "character": 1, "new_name": new_name,
            }))
        };
        assert!(parse("renamed").is_ok());
        assert!(parse(&"a".repeat(MAX_NEW_NAME_LENGTH)).is_ok());
        assert!(parse("").is_err());
        assert!(parse("  ").is_err());
        assert!(parse(&"a".repeat(MAX_NEW_NAME_LENGTH + 1)).is_err());
    }

    #[test]
    fn completions_reject_an_empty_or_oversized_trigger_while_parsing() {
        let parse = |trigger: &str| {
            serde_json::from_value::<CompletionsParams>(serde_json::json!({
                "file_path": "/a.rs", "line": 1, "character": 1, "trigger": trigger,
            }))
        };
        assert!(parse(".").is_ok());
        assert!(parse("->").is_ok());
        assert!(parse(&"a".repeat(MAX_TRIGGER_CHARACTER_BYTES)).is_ok());
        assert!(parse(&"a".repeat(MAX_TRIGGER_CHARACTER_BYTES + 1)).is_err());
        assert!(parse(" ").is_ok());
        let empty = parse("").unwrap_err().to_string();
        assert!(empty.contains("`trigger` cannot be empty"), "{empty}");
    }

    #[test]
    fn symbol_kind_accepts_names_and_numeric_values() {
        let kind = |value: &str| {
            let json =
                serde_json::json!({"file_path": "/a.rs", "symbol_name": "f", "symbol_kind": value});
            let params: SymbolTargetParams = serde_json::from_value(json).unwrap();
            let SymbolTarget::Name(query) = params.target.into_target().unwrap() else {
                panic!("expected a name target");
            };
            query.kind
        };
        assert_eq!(kind("Method"), Some(lsp_types::SymbolKind::Method));
        assert_eq!(kind("6"), Some(lsp_types::SymbolKind::Method));
        assert_eq!(kind("METHOD"), Some(lsp_types::SymbolKind::Method));
    }

    #[test]
    fn format_range_params_are_flat_and_default_options() {
        let json = serde_json::json!({
            "file_path": "/a.rs",
            "start_line": 1,
            "start_character": 1,
            "end_line": 2,
            "end_character": 3,
        });
        let params: FormatRangeParams = serde_json::from_value(json).unwrap();
        assert_eq!(params.range.end_line, 2);
        assert_eq!(params.tab_size, TabSize::default());
        assert!(params.insert_spaces);
    }

    #[test]
    fn format_params_reject_tab_sizes_outside_the_bounds() {
        let params = |tab_size: u32| {
            serde_json::from_value::<FormatDocumentParams>(
                serde_json::json!({ "file_path": "/a.rs", "tab_size": tab_size }),
            )
        };
        assert_eq!(
            params(crate::bridge::MAX_TAB_SIZE).unwrap().tab_size.get(),
            crate::bridge::MAX_TAB_SIZE
        );
        assert_eq!(params(1).unwrap().tab_size.get(), 1);
        for rejected in [0, crate::bridge::MAX_TAB_SIZE + 1, u32::MAX] {
            let error = params(rejected).unwrap_err().to_string();
            assert!(
                error.contains("tab_size must be between 1 and 32"),
                "{error}"
            );
        }
    }

    #[test]
    fn format_range_params_reject_tab_sizes_outside_the_bounds() {
        let params = |tab_size: u32| {
            serde_json::from_value::<FormatRangeParams>(serde_json::json!({
                "file_path": "/a.rs",
                "start_line": 1,
                "start_character": 1,
                "end_line": 2,
                "end_character": 3,
                "tab_size": tab_size,
            }))
        };
        assert_eq!(params(32).unwrap().tab_size.get(), 32);
        for rejected in [0, 33] {
            let error = params(rejected).unwrap_err().to_string();
            assert!(
                error.contains("tab_size must be between 1 and 32"),
                "{error}"
            );
        }
    }

    #[test]
    fn folding_range_params_default_to_all_kinds_and_reject_unknown_ones() {
        let params = |kind: Option<&str>| {
            let mut json = serde_json::json!({ "file_path": "/a.rs" });
            if let Some(kind) = kind {
                json["kind"] = kind.into();
            }
            serde_json::from_value::<FoldingRangesParams>(json)
        };
        let known = |kind: Option<&str>| {
            params(kind)
                .unwrap()
                .kind
                .into_known(KindFilterField::Kind)
                .unwrap()
        };
        assert_eq!(known(None), FoldingKindFilter::All);
        assert_eq!(known(Some("imports")), FoldingKindFilter::Imports);
        assert_eq!(known(Some("Imports")), FoldingKindFilter::Imports);
        let rejected = params(Some("unspecified"))
            .unwrap()
            .kind
            .into_known(KindFilterField::Kind)
            .unwrap_err();
        assert!(
            rejected.to_string().contains("Invalid kind: 'unspecified'"),
            "{rejected}"
        );
    }

    #[test]
    fn a_rejected_symbol_kind_is_invalid_params_not_a_deserialization_error() {
        let json = serde_json::json!({
            "file_path": "/a.rs",
            "symbol_name": "f",
            "symbol_kind": "nope",
        });
        let params: SymbolTargetParams = serde_json::from_value(json).unwrap();
        let error = params.target.into_target().unwrap_err();
        assert_matches!(&error, Error::InvalidToolParams(message) if message.contains("Invalid symbol_kind: 'nope'"));
    }

    #[test]
    fn type_hierarchy_walk_params_require_a_typed_item() {
        let untyped = serde_json::json!({"item": {"invalid": "structure"}});
        assert!(serde_json::from_value::<TypeHierarchyWalkParams>(untyped).is_err());

        let schema = schemars::schema_for!(TypeHierarchyWalkParams);
        let item = &schema.as_object().unwrap()["properties"]["item"];
        assert!(item.get("$ref").is_some());
    }

    /// The generated JSON schema must expose `PositionParams`/`RangeParams`
    /// fields as top-level properties, not nested under `position`/`range` --
    /// otherwise MCP clients would see a schema that no longer matches the
    /// flat wire format.
    #[test]
    fn generated_schema_exposes_flattened_fields_at_top_level() {
        let schema = schemars::schema_for!(ReferencesParams);
        let properties = schema
            .as_object()
            .unwrap()
            .get("properties")
            .unwrap()
            .as_object()
            .unwrap();
        assert!(properties.contains_key("file_path"));
        assert!(properties.contains_key("line"));
        assert!(properties.contains_key("character"));
        assert!(properties.contains_key("symbol_name"));
        assert!(properties.contains_key("symbol_kind"));
        assert!(properties.contains_key("container"));
        assert!(properties.contains_key("include_declaration"));
        assert!(!properties.contains_key("target"));

        let schema = schemars::schema_for!(InlayHintsParams);
        let properties = schema
            .as_object()
            .unwrap()
            .get("properties")
            .unwrap()
            .as_object()
            .unwrap();
        assert!(properties.contains_key("file_path"));
        assert!(properties.contains_key("start_line"));
        assert!(properties.contains_key("start_character"));
        assert!(properties.contains_key("end_line"));
        assert!(properties.contains_key("end_character"));
        assert!(!properties.contains_key("range"));
    }

    /// mcp/016 FR-010: `null` is absent for an `Option` parameter and a type
    /// error for a defaulted non-`Option` one, whose schema is non-nullable.
    #[test]
    fn null_is_absent_for_option_fields_and_rejected_for_defaulted_ones() {
        use serde::de::DeserializeOwned;
        use serde_json::{Value, json};

        fn accepts<P: DeserializeOwned>(base: &Value, field: &str) -> bool {
            let mut args = base.clone();
            args[field] = Value::Null;
            serde_json::from_value::<P>(args).is_ok()
        }

        let range = json!({
            "file_path": "/a.rs", "start_line": 1, "start_character": 1,
            "end_line": 2, "end_character": 3,
        });
        let named = json!({"file_path": "/a.rs", "symbol_name": "f"});
        let file = json!({"file_path": "/a.rs"});
        let position = json!({"file_path": "/a.rs", "line": 1, "character": 1});

        for field in ["line", "character", "symbol_kind", "container"] {
            assert!(accepts::<ReferencesParams>(&named, field), "{field}");
        }
        assert!(accepts::<ReferencesParams>(&position, "symbol_name"));
        assert!(accepts::<CompletionsParams>(&position, "trigger"));
        assert!(accepts::<CodeActionsParams>(&range, "kind_filter"));
        assert!(accepts::<WorkspaceSymbolParams>(
            &json!({"query": "q"}),
            "kind_filter"
        ));
        assert!(accepts::<ServerLogsParams>(&json!({}), "min_level"));
        assert!(accepts::<ToolSupportParams>(&json!({}), "file_path"));
        assert!(accepts::<RestartServerParams>(
            &json!({"all": true}),
            "servers"
        ));

        assert!(!accepts::<ReferencesParams>(&named, "include_declaration"));
        assert!(!accepts::<ReferencesParams>(&named, "context"));
        assert!(!accepts::<NavigationParams>(&named, "context"));
        assert!(!accepts::<DeclarationParams>(&position, "context"));
        assert!(!accepts::<DiagnosticsParams>(&file, "context"));
        assert!(!accepts::<FormatDocumentParams>(&file, "tab_size"));
        assert!(!accepts::<FormatDocumentParams>(&file, "insert_spaces"));
        assert!(!accepts::<FormatRangeParams>(&range, "tab_size"));
        assert!(!accepts::<FormatRangeParams>(&range, "insert_spaces"));
        assert!(!accepts::<FoldingRangesParams>(&file, "kind"));
        assert!(!accepts::<WorkspaceSymbolParams>(
            &json!({"query": "q"}),
            "limit"
        ));
        assert!(!accepts::<ServerLogsParams>(&json!({}), "limit"));
        assert!(!accepts::<ServerMessagesParams>(&json!({}), "limit"));
        assert!(!accepts::<RestartServerParams>(
            &json!({"servers": ["a"]}),
            "all"
        ));
    }

    /// `HierarchyItemInput` mirrors `HierarchyItem` by hand: a full output
    /// item must come back unchanged when a client passes it to a walking tool.
    #[test]
    fn hierarchy_item_input_round_trips_a_full_output_item() {
        let at = |line, character| Position2D { line, character };
        let item = HierarchyItem {
            name: "Base".into(),
            kind: 5,
            detail: Some("trait".into()),
            uri: "file:///a.rs".into(),
            range: Range {
                start: at(1, 2),
                end: at(3, 4),
            },
            selection_range: Range {
                start: at(1, 6),
                end: at(1, 10),
            },
            data: Some(serde_json::json!({"opaque": [1, "x"]})),
            out_of_workspace: true,
        };
        let wire = serde_json::to_value(&item).unwrap();
        let input: HierarchyItemInput = serde_json::from_value(wire.clone()).unwrap();
        let back = serde_json::to_value(HierarchyItem::from(input)).unwrap();
        assert_eq!(back, wire);
    }
}