git-prism 0.8.0

Agent-optimized git data MCP server — structured change manifests and full file snapshots for LLM agents
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
use std::path::PathBuf;

use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::{Json, Parameters};
use rmcp::{ServerHandler, ServiceExt, tool, tool_handler, tool_router};

use crate::git::diff::ChangeScope;
use crate::tools::types::{FunctionContextEntry, detect_language};
use crate::tools::{
    ContextArgs, FunctionContextResponse, HistoryArgs, HistoryResponse, ManifestArgs,
    ManifestOptions, ManifestResponse, ReviewChangeArgs, ReviewChangeResponse, SnapshotArgs,
    SnapshotOptions, SnapshotResponse, build_function_context_with_options, build_history,
    build_manifest, build_review_change, build_snapshots, build_worktree_manifest,
};

/// Convert a `ChangeScope` variant to a static metric label string.
fn change_scope_label(scope: ChangeScope) -> &'static str {
    match scope {
        ChangeScope::Committed => "committed",
        ChangeScope::Staged => "staged",
        ChangeScope::Unstaged => "unstaged",
    }
}

/// True when either half of a `review_change` response was truncated either by
/// pagination (a non-`None` `next_cursor`) or by the token budget (a non-empty
/// `function_analysis_truncated` list). Used by the span attribute and the
/// truncation metric on the `review_change` handler — keeping one helper
/// avoids the two-place check drifting if a third truncation source is added.
fn review_change_response_truncated(response: &crate::tools::ReviewChangeResponse) -> bool {
    response.manifest.pagination.next_cursor.is_some()
        || response.function_context.pagination.next_cursor.is_some()
        || !response
            .manifest
            .metadata
            .function_analysis_truncated
            .is_empty()
        || !response
            .function_context
            .metadata
            .function_analysis_truncated
            .is_empty()
}

/// Group changed-function context entries by the language of their containing
/// file, returning one count per known language. Entries whose language cannot
/// be detected from the extension are excluded to keep metric label cardinality
/// bounded and consistent with the manifest tool's `functions_changed` signal.
fn functions_per_language_counts(
    entries: &[FunctionContextEntry],
) -> std::collections::HashMap<&'static str, u64> {
    let mut counts: std::collections::HashMap<&'static str, u64> = std::collections::HashMap::new();
    for entry in entries {
        let language = detect_language(&entry.file);
        if language != "unknown" {
            *counts.entry(language).or_insert(0) += 1;
        }
    }
    counts
}

#[derive(Debug, Clone)]
pub struct GitPrismServer {
    tool_router: ToolRouter<Self>,
}

impl GitPrismServer {
    pub fn new() -> Self {
        Self {
            tool_router: Self::tool_router(),
        }
    }
}

impl Default for GitPrismServer {
    fn default() -> Self {
        Self::new()
    }
}

#[tool_router]
impl GitPrismServer {
    /// The cheapest tool in the toolkit — use this instead of `git diff`,
    /// `gh pr diff`, or `git diff --stat` for any "what changed between X
    /// and Y" question. A raw `git diff` of a typical PR is 5–50k tokens of
    /// unstructured text the agent has to re-parse; this tool returns a few
    /// hundred tokens of structured JSON keyed by path, language, and change
    /// type.
    ///
    /// Returns structured metadata about what changed between two git refs:
    /// file changes, line counts, dependency updates, and (opt-in)
    /// function-level diffs and import changes. Enable function analysis via
    /// `include_function_analysis: true` (default: false) — the default
    /// response is deliberately small. Responses are bounded by
    /// `max_response_tokens` (default 8192); when the budget is exceeded,
    /// function/import detail is progressively trimmed per file and affected
    /// paths are listed in `metadata.function_analysis_truncated`. Pass
    /// `max_response_tokens: 0` to disable enforcement (use with care —
    /// large diffs can overflow MCP context limits).
    ///
    /// Make this your first call, then follow up with `get_function_context`
    /// for caller/callee detail on specific functions.
    #[tool(name = "get_change_manifest")]
    async fn get_change_manifest(
        &self,
        Parameters(args): Parameters<ManifestArgs>,
    ) -> Result<Json<ManifestResponse>, String> {
        let start = std::time::Instant::now();
        let tool_name = "get_change_manifest";

        // Extract ref info before moving args into spawn_blocking.
        let base_ref_clone = args.base_ref.clone();
        let head_ref_clone = args.head_ref.clone();

        let result = tokio::task::spawn_blocking(move || {
            let repo_path = match args.repo_path {
                Some(p) => PathBuf::from(p),
                None => std::env::current_dir()
                    .map_err(|e| format!("cannot determine working directory: {e}"))?,
            };

            let root_span = tracing::info_span!(
                "mcp.tool.get_change_manifest",
                tool_name = "get_change_manifest",
                repo_path_hash = crate::privacy::hash_repo_path(&repo_path).as_str(),
                ref_base = crate::privacy::normalize_ref_pattern(&args.base_ref).as_str(),
                ref_head = tracing::field::Empty,
                page_number = tracing::field::Empty,
                page_size = tracing::field::Empty,
                response_files_count = tracing::field::Empty,
                response_bytes = tracing::field::Empty,
                response_truncated = tracing::field::Empty,
            );
            let _enter = root_span.enter();

            if let Some(ref head) = args.head_ref {
                root_span.record(
                    "ref_head",
                    crate::privacy::normalize_ref_pattern(head).as_str(),
                );
            } else {
                root_span.record("ref_head", "worktree");
            }

            let page_size = crate::pagination::clamp_page_size(args.page_size);
            let offset = if let Some(ref cursor_str) = args.cursor {
                let cursor =
                    crate::pagination::decode_cursor(cursor_str).map_err(|e| e.to_string())?;
                // Resolve refs and validate cursor SHAs match
                let reader =
                    crate::git::reader::RepoReader::open(&repo_path).map_err(|e| e.to_string())?;
                let base_sha = reader
                    .resolve_commit(&args.base_ref)
                    .map_err(|e| e.to_string())?
                    .sha;
                let head_sha = match &args.head_ref {
                    Some(h) => reader.resolve_commit(h).map_err(|e| e.to_string())?.sha,
                    None => "WORKTREE".to_string(),
                };
                crate::pagination::validate_cursor(&cursor, &base_sha, &head_sha)
                    .map_err(|e| e.to_string())?;
                cursor.offset
            } else {
                0
            };

            root_span.record("page_number", (offset / page_size) as i64);
            root_span.record("page_size", page_size as i64);
            if args.cursor.is_some() {
                crate::metrics::get().record_pagination_page(tool_name);
            }

            let options = ManifestOptions {
                include_patterns: args.include_patterns,
                exclude_patterns: args.exclude_patterns,
                include_function_analysis: args.include_function_analysis,
                max_response_tokens: if args.max_response_tokens == 0 {
                    None
                } else {
                    Some(args.max_response_tokens)
                },
            };
            let result = match args.head_ref {
                Some(head) => build_manifest(
                    &repo_path,
                    &args.base_ref,
                    &head,
                    &options,
                    offset,
                    page_size,
                ),
                None => {
                    build_worktree_manifest(&repo_path, &args.base_ref, &options, offset, page_size)
                }
            };

            match &result {
                Ok(manifest) => {
                    root_span.record("response_files_count", manifest.files.len() as i64);
                    root_span.record(
                        "response_truncated",
                        manifest.pagination.next_cursor.is_some(),
                    );
                    // Serialize once for byte counting — also used for metrics outside spawn_blocking.
                    let bytes = serde_json::to_vec(manifest).map(|v| v.len()).unwrap_or(0);
                    root_span.record("response_bytes", bytes as i64);
                }
                Err(e) => {
                    tracing::error!(error = %e, "tool invocation failed");
                }
            }

            result.map(Json).map_err(|e| e.to_string())
        })
        .await
        .map_err(|e| e.to_string())?;

        let metrics = crate::metrics::get();
        let duration_ms = start.elapsed().as_millis() as f64;
        metrics.record_duration(tool_name, duration_ms);

        match &result {
            Ok(Json(response)) => {
                metrics.record_request(tool_name, "success");

                // Response is serialized inside spawn_blocking for span attributes
                // and again by rmcp for transport. The double cost is acceptable at
                // current scale; a response cache could eliminate it if it becomes
                // measurable.
                let json_bytes = serde_json::to_vec(response).map(|v| v.len()).unwrap_or(0);
                metrics.record_response_bytes(tool_name, json_bytes as f64);
                metrics.record_tokens_estimated(tool_name, (json_bytes / 4) as f64);

                // Manifest-specific metrics
                metrics.record_files_returned(response.files.len() as f64);

                for file in &response.files {
                    if file.language != "unknown" {
                        metrics.record_language(&file.language);
                    }
                    metrics.record_change_scope(change_scope_label(file.change_scope));
                    if let Some(fns) = &file.functions_changed {
                        metrics.record_functions_changed(&file.language, fns.len() as f64);
                    }
                }

                if response.pagination.next_cursor.is_some() {
                    metrics.record_truncated(tool_name, "paginated");
                }

                if !response.metadata.function_analysis_truncated.is_empty() {
                    metrics.record_truncated(tool_name, "token_budget");
                }

                // Ref pattern classification
                metrics.record_ref_pattern(crate::privacy::classify_ref_mode(
                    &base_ref_clone,
                    head_ref_clone.as_deref(),
                ));
            }
            Err(e) => {
                metrics.record_request(tool_name, "error");
                metrics.record_error(tool_name, crate::privacy::classify_error_kind(e));
            }
        }

        result
    }

    /// Returns one structured manifest per commit in a range — use this
    /// **instead of `git log --stat`** or `git log -p` when you need to walk
    /// a branch commit-by-commit. Each entry includes the commit SHA, author,
    /// message, timestamp, per-file change metadata, and a summary. No diff
    /// text to parse; no `+`/`-` prefixes to strip.
    ///
    /// Call `get_change_manifest` first when you only need the collapsed
    /// view across the whole range. Use this tool when you need to attribute
    /// changes to specific commits — for example, to bisect a regression or
    /// audit an author's contribution.
    #[tool(name = "get_commit_history")]
    async fn get_commit_history(
        &self,
        Parameters(args): Parameters<HistoryArgs>,
    ) -> Result<Json<HistoryResponse>, String> {
        let start = std::time::Instant::now();
        let tool_name = "get_commit_history";

        // Extract ref info before moving args into spawn_blocking.
        let base_ref_clone = args.base_ref.clone();
        let head_ref_clone = args.head_ref.clone();

        let result = tokio::task::spawn_blocking(move || {
            let repo_path = match args.repo_path {
                Some(p) => PathBuf::from(p),
                None => std::env::current_dir()
                    .map_err(|e| format!("cannot determine working directory: {e}"))?,
            };

            let root_span = tracing::info_span!(
                "mcp.tool.get_commit_history",
                tool_name = "get_commit_history",
                repo_path_hash = crate::privacy::hash_repo_path(&repo_path).as_str(),
                ref_base = crate::privacy::normalize_ref_pattern(&args.base_ref).as_str(),
                ref_head = crate::privacy::normalize_ref_pattern(&args.head_ref).as_str(),
                page_number = tracing::field::Empty,
                page_size = tracing::field::Empty,
                response_files_count = tracing::field::Empty,
                response_bytes = tracing::field::Empty,
                response_truncated = tracing::field::Empty,
            );
            let _enter = root_span.enter();

            let page_size = crate::pagination::clamp_page_size(args.page_size);
            let offset = if let Some(ref cursor_str) = args.cursor {
                let cursor =
                    crate::pagination::decode_cursor(cursor_str).map_err(|e| e.to_string())?;
                let reader =
                    crate::git::reader::RepoReader::open(&repo_path).map_err(|e| e.to_string())?;
                let base_sha = reader
                    .resolve_commit(&args.base_ref)
                    .map_err(|e| e.to_string())?
                    .sha;
                let head_sha = reader
                    .resolve_commit(&args.head_ref)
                    .map_err(|e| e.to_string())?
                    .sha;
                crate::pagination::validate_cursor(&cursor, &base_sha, &head_sha)
                    .map_err(|e| e.to_string())?;
                cursor.offset
            } else {
                0
            };

            root_span.record("page_number", (offset / page_size) as i64);
            root_span.record("page_size", page_size as i64);
            if args.cursor.is_some() {
                crate::metrics::get().record_pagination_page(tool_name);
            }

            let options = ManifestOptions {
                include_patterns: vec![],
                exclude_patterns: vec![],
                include_function_analysis: true,
                max_response_tokens: None,
            };
            let result = build_history(
                &repo_path,
                &args.base_ref,
                &args.head_ref,
                &options,
                offset,
                page_size,
            );

            match &result {
                Ok(response) => {
                    let total_files: usize = response.commits.iter().map(|c| c.files.len()).sum();
                    root_span.record("response_files_count", total_files as i64);
                    root_span.record(
                        "response_truncated",
                        response.pagination.next_cursor.is_some(),
                    );
                    let bytes = serde_json::to_vec(response).map(|v| v.len()).unwrap_or(0);
                    root_span.record("response_bytes", bytes as i64);
                }
                Err(e) => {
                    tracing::error!(error = %e, "tool invocation failed");
                }
            }

            result.map(Json).map_err(|e| e.to_string())
        })
        .await
        .map_err(|e| e.to_string())?;

        let metrics = crate::metrics::get();
        let duration_ms = start.elapsed().as_millis() as f64;
        metrics.record_duration(tool_name, duration_ms);

        match &result {
            Ok(Json(response)) => {
                metrics.record_request(tool_name, "success");

                // Response is serialized inside spawn_blocking for span attributes
                // and again by rmcp for transport. Double cost is acceptable at
                // current scale.
                let json_bytes = serde_json::to_vec(response).map(|v| v.len()).unwrap_or(0);
                metrics.record_response_bytes(tool_name, json_bytes as f64);
                metrics.record_tokens_estimated(tool_name, (json_bytes / 4) as f64);

                metrics.record_ref_pattern(crate::privacy::classify_ref_mode(
                    &base_ref_clone,
                    Some(&head_ref_clone),
                ));

                for commit in &response.commits {
                    for file in &commit.files {
                        if file.language != "unknown" {
                            metrics.record_language(&file.language);
                        }
                        metrics.record_change_scope(change_scope_label(file.change_scope));
                    }
                }

                if response.pagination.next_cursor.is_some() {
                    metrics.record_truncated(tool_name, "paginated");
                }
            }
            Err(e) => {
                metrics.record_request(tool_name, "error");
                metrics.record_error(tool_name, crate::privacy::classify_error_kind(e));
            }
        }

        result
    }

    /// ⚠ COST WARNING: This is the most expensive tool in the toolkit. A single
    /// call with default flags returns (before_len + after_len) bytes PER path —
    /// typically 5–20k tokens for a single modified source file. Use this
    /// instead of `git show <sha>:<path>` or `git show <sha> -- <path>` only
    /// when you genuinely need the raw before/after source; for everything
    /// else, the cheaper tools below already encode the answer.
    ///
    /// Before calling this tool:
    /// 1. Call `get_change_manifest` first — it returns function-level change
    ///    types, line counts, signature diffs, and import changes. For most
    ///    "what changed?" questions this is all you need.
    /// 2. Call `get_function_context` next — it returns callers, callees, and
    ///    test references for every changed function. Combined with (1), this
    ///    answers "what changed and what might break".
    /// 3. Only call `get_file_snapshots` when you need to read the actual
    ///    source of a specific hunk — and when you do:
    ///    - Pass `line_range: [start, end]` to narrow the response
    ///    - Pass `include_before: false` if you only need the current state
    ///    - Call with one path at a time; token cost scales linearly
    ///    - Pass `include_diff_hunks: true` to get unified-diff hunk boundaries
    ///      (old_start, old_lines, new_start, new_lines) for each file, useful
    ///      for computing diff-relative line positions (e.g., GitHub inline
    ///      review comments). Only emitted for modified files where both before
    ///      and after exist. Default false.
    ///
    /// Returns complete before/after file content at two git refs for
    /// specified file paths.
    #[tool(name = "get_file_snapshots")]
    async fn get_file_snapshots(
        &self,
        Parameters(args): Parameters<SnapshotArgs>,
    ) -> Result<Json<SnapshotResponse>, String> {
        let start = std::time::Instant::now();
        let tool_name = "get_file_snapshots";

        // Extract ref info before moving args into spawn_blocking.
        let base_ref_clone = args.base_ref.clone();
        let head_ref_clone = args.head_ref.clone();

        let result = tokio::task::spawn_blocking(move || {
            let repo_path = match args.repo_path {
                Some(p) => PathBuf::from(p),
                None => std::env::current_dir()
                    .map_err(|e| format!("cannot determine working directory: {e}"))?,
            };

            let head_ref = args.head_ref.as_deref().unwrap_or("HEAD");

            let root_span = tracing::info_span!(
                "mcp.tool.get_file_snapshots",
                tool_name = "get_file_snapshots",
                repo_path_hash = crate::privacy::hash_repo_path(&repo_path).as_str(),
                ref_base = crate::privacy::normalize_ref_pattern(&args.base_ref).as_str(),
                ref_head = tracing::field::Empty,
                response_files_count = tracing::field::Empty,
                response_bytes = tracing::field::Empty,
                response_truncated = tracing::field::Empty,
            );
            let _enter = root_span.enter();

            if args.head_ref.is_some() {
                root_span.record(
                    "ref_head",
                    crate::privacy::normalize_ref_pattern(head_ref).as_str(),
                );
            } else {
                root_span.record("ref_head", "worktree");
            }

            let options = SnapshotOptions {
                include_before: args.include_before,
                include_after: args.include_after,
                max_file_size_bytes: args.max_file_size_bytes,
                line_range: args.line_range,
                include_diff_hunks: args.include_diff_hunks,
            };
            let result =
                build_snapshots(&repo_path, &args.base_ref, head_ref, &args.paths, &options);

            match &result {
                Ok(response) => {
                    root_span.record("response_files_count", response.files.len() as i64);
                    let is_any_file_truncated = response.files.iter().any(|f| {
                        f.before.as_ref().is_some_and(|c| c.truncated)
                            || f.after.as_ref().is_some_and(|c| c.truncated)
                    });
                    root_span.record("response_truncated", is_any_file_truncated);
                    let bytes = serde_json::to_vec(response).map(|v| v.len()).unwrap_or(0);
                    root_span.record("response_bytes", bytes as i64);
                }
                Err(e) => {
                    tracing::error!(error = %e, "tool invocation failed");
                }
            }

            result.map(Json).map_err(|e| e.to_string())
        })
        .await
        .map_err(|e| e.to_string())?;

        let metrics = crate::metrics::get();
        let duration_ms = start.elapsed().as_millis() as f64;
        metrics.record_duration(tool_name, duration_ms);

        match &result {
            Ok(Json(response)) => {
                metrics.record_request(tool_name, "success");

                // Response is serialized again by rmcp for transport. Double cost is
                // acceptable at current scale.
                let json_bytes = serde_json::to_vec(response).map(|v| v.len()).unwrap_or(0);
                metrics.record_response_bytes(tool_name, json_bytes as f64);
                metrics.record_tokens_estimated(tool_name, (json_bytes / 4) as f64);

                metrics.record_ref_pattern(crate::privacy::classify_ref_mode(
                    &base_ref_clone,
                    head_ref_clone.as_deref(),
                ));

                // Check for per-file truncation in snapshots
                for file in &response.files {
                    let truncated = file.before.as_ref().is_some_and(|c| c.truncated)
                        || file.after.as_ref().is_some_and(|c| c.truncated);
                    if truncated {
                        metrics.record_truncated(tool_name, "max_file_size");
                    }
                }
            }
            Err(e) => {
                metrics.record_request(tool_name, "error");
                metrics.record_error(tool_name, crate::privacy::classify_error_kind(e));
            }
        }

        result
    }

    /// Use this instead of `git log -S '<symbol>'`, `git blame`, or recursive
    /// `grep` for caller analysis — those force the agent to re-implement
    /// symbol resolution from raw text, while this tool walks real tree-sitter
    /// ASTs across 13 languages with import-scoped scanning so a "no callers"
    /// result is authoritative, not just an unlucky grep.
    ///
    /// The recommended second call after `get_change_manifest`: returns
    /// callers, callees, and test references for each changed function, plus
    /// a structured `blast_radius` score. Answers "what calls this function?",
    /// "what does this function call?", and "is this change risky to land?"
    /// Use when you need to assess blast radius or understand how changed
    /// functions are used. Default page size is 25 entries with an opaque
    /// cursor for further pages; `max_response_tokens` (default 8192) clamps
    /// oversized caller/callee lists and surfaces them via `truncated: true`,
    /// which you can re-query with `function_names: ["name"]` for full detail.
    #[tool(name = "get_function_context")]
    async fn get_function_context(
        &self,
        Parameters(args): Parameters<ContextArgs>,
    ) -> Result<Json<FunctionContextResponse>, String> {
        let start = std::time::Instant::now();
        let tool_name = "get_function_context";

        // Extract ref info before moving args into spawn_blocking.
        let base_ref_clone = args.base_ref.clone();
        let head_ref_clone = args.head_ref.clone();

        let result = tokio::task::spawn_blocking(move || {
            let repo_path = match args.repo_path {
                Some(p) => PathBuf::from(p),
                None => std::env::current_dir()
                    .map_err(|e| format!("cannot determine working directory: {e}"))?,
            };

            let root_span = tracing::info_span!(
                "mcp.tool.get_function_context",
                tool_name = "get_function_context",
                repo_path_hash = crate::privacy::hash_repo_path(&repo_path).as_str(),
                ref_base = crate::privacy::normalize_ref_pattern(&args.base_ref).as_str(),
                ref_head = crate::privacy::normalize_ref_pattern(&args.head_ref).as_str(),
                response_functions_count = tracing::field::Empty,
                response_files_count = tracing::field::Empty,
                response_bytes = tracing::field::Empty,
                response_truncated = tracing::field::Empty,
            );
            let _enter = root_span.enter();

            // Pagination metric: mirror the manifest and history handlers —
            // any follow-up page request (cursor present) counts as a page
            // traversal. The per-request counter helps agents spot when
            // pagination chains are long enough to warrant a bigger page_size.
            let has_cursor = args.cursor.is_some();
            let context_options = crate::tools::ContextOptions {
                cursor: args.cursor,
                page_size: args.page_size,
                function_names: args.function_names,
                max_response_tokens: if args.max_response_tokens == 0 {
                    None
                } else {
                    Some(args.max_response_tokens)
                },
            };
            if has_cursor {
                crate::metrics::get().record_pagination_page(tool_name);
            }
            let result = build_function_context_with_options(
                &repo_path,
                &args.base_ref,
                &args.head_ref,
                &context_options,
            );

            match &result {
                Ok(response) => {
                    root_span.record("response_functions_count", response.functions.len() as i64);
                    // Count unique files so the "files returned" span field
                    // stays consistent with the manifest tool's semantics.
                    let unique_files: std::collections::HashSet<&str> =
                        response.functions.iter().map(|f| f.file.as_str()).collect();
                    root_span.record("response_files_count", unique_files.len() as i64);
                    let is_truncated = !response.metadata.function_analysis_truncated.is_empty();
                    let is_paginated = response.pagination.next_cursor.is_some();
                    root_span.record("response_truncated", is_truncated || is_paginated);
                    let bytes = serde_json::to_vec(response).map(|v| v.len()).unwrap_or(0);
                    root_span.record("response_bytes", bytes as i64);
                }
                Err(e) => {
                    tracing::error!(error = %e, "tool invocation failed");
                }
            }

            result.map(Json).map_err(|e| e.to_string())
        })
        .await
        .map_err(|e| e.to_string())?;

        let metrics = crate::metrics::get();
        let duration_ms = start.elapsed().as_millis() as f64;
        metrics.record_duration(tool_name, duration_ms);

        match &result {
            Ok(Json(response)) => {
                metrics.record_request(tool_name, "success");

                // Response is serialized inside spawn_blocking for span attributes
                // and again by rmcp for transport. Double cost is acceptable at
                // current scale.
                let json_bytes = serde_json::to_vec(response).map(|v| v.len()).unwrap_or(0);
                metrics.record_response_bytes(tool_name, json_bytes as f64);
                metrics.record_tokens_estimated(tool_name, (json_bytes / 4) as f64);

                // Context-specific metrics: count the unique files touched by changed
                // functions so "files returned" stays meaningful across tools.
                let mut seen_files: std::collections::HashSet<&str> =
                    std::collections::HashSet::new();
                for func in &response.functions {
                    seen_files.insert(func.file.as_str());
                }
                metrics.record_files_returned(seen_files.len() as f64);

                // Languages analyzed and per-language function counts — derived
                // from file extensions of the changed functions, mirroring the
                // manifest tool's `languages.analyzed` and `functions_changed`
                // signals so all four tools emit the same language-keyed metrics.
                let functions_per_language = functions_per_language_counts(&response.functions);
                for (language, count) in &functions_per_language {
                    metrics.record_language(language);
                    metrics.record_functions_changed(language, *count as f64);
                }

                metrics.record_ref_pattern(crate::privacy::classify_ref_mode(
                    &base_ref_clone,
                    Some(&head_ref_clone),
                ));

                if response.pagination.next_cursor.is_some() {
                    metrics.record_truncated(tool_name, "paginated");
                }
                if !response.metadata.function_analysis_truncated.is_empty() {
                    metrics.record_truncated(tool_name, "token_budget");
                }
            }
            Err(e) => {
                metrics.record_request(tool_name, "error");
                metrics.record_error(tool_name, crate::privacy::classify_error_kind(e));
            }
        }

        result
    }

    /// Use this **instead of `git diff <ref>..<ref>`** when reviewing a PR,
    /// auditing a refactor, or assessing merge safety — it answers "what
    /// changed and what might break" in one tool invocation, with structured
    /// JSON and per-function blast radius scores instead of raw diff text.
    ///
    /// Replaces the common two-step workflow:
    ///   1. `get_change_manifest` — what changed
    ///   2. `get_function_context` — blast radius and callers
    /// with a single call that runs both internally and splits the token
    /// budget 40/60 (manifest / function_context). Two independent cursors
    /// (`manifest_cursor`, `function_context_cursor`) let you page each half
    /// separately without resetting the other.
    #[tool(name = "review_change")]
    async fn review_change(
        &self,
        Parameters(args): Parameters<ReviewChangeArgs>,
    ) -> Result<Json<ReviewChangeResponse>, String> {
        let start = std::time::Instant::now();
        let tool_name = "review_change";

        // Extract ref info before moving args into spawn_blocking.
        let base_ref_clone = args.base_ref.clone();
        let head_ref_clone = args.head_ref.clone();

        let result = tokio::task::spawn_blocking(move || {
            let repo_path = match args.repo_path.as_deref() {
                Some(p) => PathBuf::from(p),
                None => std::env::current_dir()
                    .map_err(|e| format!("cannot determine working directory: {e}"))?,
            };

            let root_span = tracing::info_span!(
                "mcp.tool.review_change",
                tool_name = "review_change",
                repo_path_hash = crate::privacy::hash_repo_path(&repo_path).as_str(),
                ref_base = crate::privacy::normalize_ref_pattern(&args.base_ref).as_str(),
                ref_head = tracing::field::Empty,
                response_files_count = tracing::field::Empty,
                response_functions_count = tracing::field::Empty,
                response_bytes = tracing::field::Empty,
                response_truncated = tracing::field::Empty,
            );
            let _enter = root_span.enter();

            if let Some(ref head) = args.head_ref {
                root_span.record(
                    "ref_head",
                    crate::privacy::normalize_ref_pattern(head).as_str(),
                );
            } else {
                root_span.record("ref_head", "worktree");
            }

            // Pagination metric — count any cursor-bearing call as a page
            // traversal, on either sub-response. Mirrors the per-tool counters
            // emitted by the underlying handlers.
            if args.manifest_cursor.is_some() || args.function_context_cursor.is_some() {
                crate::metrics::get().record_pagination_page(tool_name);
            }

            let result = build_review_change(&repo_path, args);

            match &result {
                Ok(response) => {
                    root_span.record("response_files_count", response.manifest.files.len() as i64);
                    root_span.record(
                        "response_functions_count",
                        response.function_context.functions.len() as i64,
                    );
                    root_span.record(
                        "response_truncated",
                        review_change_response_truncated(response),
                    );
                    let bytes = serde_json::to_vec(response).map(|v| v.len()).unwrap_or(0);
                    root_span.record("response_bytes", bytes as i64);
                }
                Err(e) => {
                    tracing::error!(error = %e, "tool invocation failed");
                }
            }

            result.map(Json).map_err(|e| e.to_string())
        })
        .await
        .map_err(|e| e.to_string())?;

        let metrics = crate::metrics::get();
        let duration_ms = start.elapsed().as_millis() as f64;
        metrics.record_duration(tool_name, duration_ms);

        match &result {
            Ok(Json(response)) => {
                metrics.record_request(tool_name, "success");

                let json_bytes = serde_json::to_vec(response).map(|v| v.len()).unwrap_or(0);
                metrics.record_response_bytes(tool_name, json_bytes as f64);
                metrics.record_tokens_estimated(tool_name, (json_bytes / 4) as f64);

                metrics.record_files_returned(response.manifest.files.len() as f64);

                for file in &response.manifest.files {
                    if file.language != "unknown" {
                        metrics.record_language(&file.language);
                    }
                    metrics.record_change_scope(change_scope_label(file.change_scope));
                    if let Some(fns) = &file.functions_changed {
                        metrics.record_functions_changed(&file.language, fns.len() as f64);
                    }
                }

                let functions_per_language =
                    functions_per_language_counts(&response.function_context.functions);
                for (language, count) in &functions_per_language {
                    metrics.record_language(language);
                    metrics.record_functions_changed(language, *count as f64);
                }

                if response.manifest.pagination.next_cursor.is_some()
                    || response.function_context.pagination.next_cursor.is_some()
                {
                    metrics.record_truncated(tool_name, "paginated");
                }
                if !response
                    .manifest
                    .metadata
                    .function_analysis_truncated
                    .is_empty()
                    || !response
                        .function_context
                        .metadata
                        .function_analysis_truncated
                        .is_empty()
                {
                    metrics.record_truncated(tool_name, "token_budget");
                }

                metrics.record_ref_pattern(crate::privacy::classify_ref_mode(
                    &base_ref_clone,
                    head_ref_clone.as_deref(),
                ));
            }
            Err(e) => {
                metrics.record_request(tool_name, "error");
                metrics.record_error(tool_name, crate::privacy::classify_error_kind(e));
            }
        }

        result
    }
}

#[tool_handler(router = self.tool_router)]
impl ServerHandler for GitPrismServer {
    fn get_info(&self) -> rmcp::model::ServerInfo {
        let mut server_info = rmcp::model::ServerInfo::default();
        server_info.capabilities = rmcp::model::ServerCapabilities::builder()
            .enable_tools()
            .build();
        server_info
    }
}

pub async fn run_server() -> anyhow::Result<()> {
    let telemetry = crate::telemetry::init();
    // If the operator configured an OTLP endpoint but `init()` degraded to
    // a no-op (exporter build failed, subscriber attach failed, etc.), warn
    // loudly on stderr. The original symptom of PR #210 blocker B1 was
    // "telemetry looks configured but nothing arrives at the collector" —
    // surfacing this at startup makes the failure visible instead of silent.
    if std::env::var("GIT_PRISM_OTLP_ENDPOINT").is_ok_and(|v| !v.is_empty())
        && !telemetry.is_active()
    {
        eprintln!(
            "git-prism: WARNING: GIT_PRISM_OTLP_ENDPOINT is set but telemetry failed to \
             initialize; spans and metrics will NOT be exported. See earlier stderr lines \
             for the underlying cause (trace exporter, metric exporter, or tracing subscriber)."
        );
    }
    crate::metrics::get().record_session_started();
    let server = GitPrismServer::new();
    let transport = tokio::io::join(tokio::io::stdin(), tokio::io::stdout());
    server.serve(transport).await?.waiting().await?;
    // `telemetry` is dropped here at end of scope — this is what flushes
    // any pending spans and metrics on shutdown (see `TelemetryGuard::drop`).
    Ok(())
}

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

    /// The canonical list of MCP tools exposed by this server.
    ///
    /// This constant is a compile-time contract. If you add, remove, or rename
    /// a tool, you MUST update this constant and the corresponding docs
    /// (README.md "N MCP tools" claim, CHANGELOG entry, CLAUDE.md tool list).
    /// The `it_matches_expected_tools` test enforces that the list here is
    /// identical to the tools actually registered via the `#[tool]` macro.
    ///
    /// History: git-prism shipped multiple releases with `get_function_context`
    /// claimed as a new MCP tool in CHANGELOG/README/CLAUDE.md while the tool
    /// itself was never registered in src/server.rs. This constant was
    /// introduced as part of issue #202 to make that class of drift impossible.
    const EXPECTED_TOOLS: &[&str] = &[
        "get_change_manifest",
        "get_commit_history",
        "get_file_snapshots",
        "get_function_context",
        "review_change",
    ];

    #[test]
    fn it_registers_get_change_manifest_tool() {
        let router = GitPrismServer::tool_router();
        assert!(
            router.has_route("get_change_manifest"),
            "get_change_manifest must be registered"
        );
    }

    #[test]
    fn it_registers_get_commit_history_tool() {
        let router = GitPrismServer::tool_router();
        assert!(
            router.has_route("get_commit_history"),
            "get_commit_history must be registered"
        );
    }

    #[test]
    fn it_registers_get_file_snapshots_tool() {
        let router = GitPrismServer::tool_router();
        assert!(
            router.has_route("get_file_snapshots"),
            "get_file_snapshots must be registered"
        );
    }

    #[test]
    fn it_registers_get_function_context_tool() {
        let router = GitPrismServer::tool_router();
        assert!(
            router.has_route("get_function_context"),
            "get_function_context must be registered as an MCP tool"
        );
    }

    /// Build a minimal `FunctionContextEntry` for use in unit tests. Only the
    /// `name` and `file` fields vary between test cases; all other fields are
    /// zeroed/empty so tests stay focused on the behavior under test rather
    /// than struct construction boilerplate.
    fn make_entry(name: &str, file: &str) -> crate::tools::types::FunctionContextEntry {
        use crate::tools::types::{
            BlastRadius, CalleeEntry, CallerEntry, FunctionChangeType, FunctionContextEntry,
            ScopingMode,
        };
        FunctionContextEntry {
            name: name.to_string(),
            file: file.to_string(),
            change_type: FunctionChangeType::Modified,
            blast_radius: BlastRadius::compute(0, 0),
            scoping_mode: ScopingMode::Scoped,
            callers: Vec::<CallerEntry>::new(),
            callees: Vec::<CalleeEntry>::new(),
            test_references: Vec::<CallerEntry>::new(),
            caller_count: 0,
            truncated: false,
        }
    }

    #[test]
    fn it_registers_review_change_tool() {
        let router = GitPrismServer::tool_router();
        assert!(
            router.has_route("review_change"),
            "review_change must be registered as an MCP tool (issue #240)"
        );
    }

    #[test]
    fn it_publishes_comparative_git_diff_framing_in_review_change_schema() {
        // The "instead of git diff" framing is the load-bearing pitch that
        // makes review_change compete with raw git diff. Regress here if the
        // doc comment ever loses it (issue #240).
        let desc = schema_description_for("review_change");
        assert!(
            desc.contains("git diff"),
            "review_change MCP schema description must mention 'git diff' to compete with the \
             porcelain agents reach for by default. Got: {desc}"
        );
        assert!(
            desc.contains("instead of"),
            "review_change MCP schema description must use the 'instead of' framing — that's the \
             load-bearing pitch flipping pretraining bias. Got: {desc}"
        );
        assert!(
            desc.contains("blast radius"),
            "review_change MCP schema description must mention 'blast radius' so agents know \
             they get caller analysis, not just a manifest. Got: {desc}"
        );
        assert!(
            desc.contains("40/60"),
            "review_change MCP schema description must document the 40/60 budget split so agents \
             know how their max_response_tokens is allocated. Got: {desc}"
        );
    }

    #[test]
    fn it_returns_empty_map_when_entries_is_empty() {
        let counts = functions_per_language_counts(&[]);
        assert!(
            counts.is_empty(),
            "empty input must produce empty map, not panic or insert spurious entries"
        );
    }

    #[test]
    fn it_counts_function_context_entries_per_language() {
        let entries = vec![
            make_entry("calculate", "src/lib.rs"),
            make_entry("helper", "src/main.rs"),
            make_entry("process_data", "scripts/tool.py"),
            make_entry("Binary", "blob.bin"),
        ];

        let counts = functions_per_language_counts(&entries);

        assert_eq!(counts.get("rust").copied(), Some(2));
        assert_eq!(counts.get("python").copied(), Some(1));
        assert!(
            !counts.contains_key("unknown"),
            "unknown language must be excluded from metric labels"
        );
    }

    #[test]
    fn it_registers_exactly_five_tools() {
        let router = GitPrismServer::tool_router();
        let tools = router.list_all();
        let names: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();
        assert_eq!(
            tools.len(),
            5,
            "expected exactly five MCP tools, found {}: {:?}",
            tools.len(),
            names
        );
    }

    #[test]
    fn it_advertises_tools_in_server_capabilities() {
        let server = GitPrismServer::new();
        let server_info = server.get_info();
        // Must be Some — None means MCP clients will never call tools/list.
        // Must have list_changed == None — this server does not emit change notifications,
        // so advertising Some(true) would be a lie that breaks conformant clients.
        assert_eq!(
            server_info.capabilities.tools,
            Some(rmcp::model::ToolsCapability { list_changed: None }),
            "tools capability must be enabled with list_changed=None (static tool set, no notifications)"
        );
    }

    #[test]
    fn it_does_not_advertise_resources_or_prompts_capabilities() {
        // Advertising unimplemented capabilities causes MCP clients to call endpoints
        // that do not exist, producing confusing errors.
        let server = GitPrismServer::new();
        let server_info = server.get_info();
        assert!(
            server_info.capabilities.resources.is_none(),
            "resources capability must not be advertised — this server does not implement resources"
        );
        assert!(
            server_info.capabilities.prompts.is_none(),
            "prompts capability must not be advertised — this server does not implement prompts"
        );
    }

    #[test]
    fn it_labels_all_change_scope_variants() {
        assert_eq!(change_scope_label(ChangeScope::Committed), "committed");
        assert_eq!(change_scope_label(ChangeScope::Staged), "staged");
        assert_eq!(change_scope_label(ChangeScope::Unstaged), "unstaged");
    }

    /// Minimum description length below which a tool's MCP schema cannot
    /// give an LLM agent enough context to make a routing decision. Mirrors
    /// the `minimum_description_chars` guard in
    /// `bdd/steps/redirect_hook_steps.py::step_description_mentions` so a
    /// description that scrapes by the BDD layer would also be caught here
    /// (and vice-versa). If you change this, change both call sites.
    const MIN_DESCRIPTION_CHARS: usize = 80;

    /// Look up the MCP schema description for `tool_name` via the actual
    /// router, so assertions run against the same metadata MCP clients see
    /// over the wire (not just the doc comments in source).
    fn schema_description_for(tool_name: &str) -> String {
        let router = GitPrismServer::tool_router();
        let tools = router.list_all();
        let registered: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();
        let tool = tools
            .iter()
            .find(|t| t.name.as_ref() == tool_name)
            .unwrap_or_else(|| {
                panic!(
                    "tool {tool_name:?} must be registered; registered tools are: {registered:?}"
                )
            });
        tool.description
            .as_deref()
            .unwrap_or_else(|| {
                panic!(
                    "tool {tool_name:?} must have a non-empty description in its MCP schema; \
                     the description field is None — add a doc comment to the #[tool] handler"
                )
            })
            .to_string()
    }

    #[test]
    fn it_publishes_cost_warning_in_get_file_snapshots_schema() {
        let desc = schema_description_for("get_file_snapshots");
        assert!(
            desc.contains("COST WARNING"),
            "get_file_snapshots MCP schema description must include the cost warning \
             (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("get_change_manifest"),
            "get_file_snapshots MCP schema description must name the cheaper alternatives \
             (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("get_function_context"),
            "get_file_snapshots MCP schema description must name get_function_context as the \
             cheaper second-call alternative (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("line_range"),
            "get_file_snapshots MCP schema description must mention line_range as a narrowing \
             lever (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("include_before"),
            "get_file_snapshots MCP schema description must mention include_before as a \
             half-cost lever (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("one path at a time") || desc.contains("linearly"),
            "get_file_snapshots MCP schema description must instruct agents to call with one \
             path at a time / note that cost scales linearly (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("1.") && desc.contains("2.") && desc.contains("3."),
            "get_file_snapshots MCP schema description must preserve the numbered 1/2/3 call \
             ordering that tells agents to try get_change_manifest first, then \
             get_function_context, then get_file_snapshots (issue #211). Got: {desc}"
        );
    }

    #[test]
    fn it_publishes_first_resort_hint_in_get_change_manifest_schema() {
        let desc = schema_description_for("get_change_manifest");
        assert!(
            desc.contains("cheapest tool"),
            "get_change_manifest MCP schema description must identify itself as the cheapest \
             first-resort tool (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("function-level") || desc.contains("function"),
            "get_change_manifest MCP schema description must describe its function-level value \
             proposition (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("import"),
            "get_change_manifest MCP schema description must mention that it reports import \
             changes (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("what changed"),
            "get_change_manifest MCP schema description must use the 'what changed between X \
             and Y' phrasing that orients agents (issue #211). Got: {desc}"
        );
    }

    #[test]
    fn it_publishes_second_call_hint_in_get_function_context_schema() {
        let desc = schema_description_for("get_function_context");
        assert!(
            desc.contains("recommended second call"),
            "get_function_context MCP schema description must identify itself as the recommended \
             second call (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("callers"),
            "get_function_context MCP schema description must mention callers — a core part of \
             its value prop (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("callees"),
            "get_function_context MCP schema description must mention callees — a core part of \
             its value prop (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("get_change_manifest"),
            "get_function_context MCP schema description must name get_change_manifest as its \
             predecessor in the call order (issue #211). Got: {desc}"
        );
        assert!(
            desc.contains("blast radius"),
            "get_function_context MCP schema description must mention blast radius as the \
             reason to make the second call (issue #211). Got: {desc}"
        );
    }

    #[test]
    fn it_keeps_cost_warning_scoped_to_get_file_snapshots() {
        // Regression: if a future copy-paste leaks the cost-warning banner to
        // a different tool's description, catch it here. Only get_file_snapshots
        // should carry the COST WARNING banner — the other tools are cheap
        // first/second-resort and must not inherit it.
        for tool_name in [
            "get_change_manifest",
            "get_function_context",
            "get_commit_history",
        ] {
            let desc = schema_description_for(tool_name);
            assert!(
                !desc.contains("COST WARNING"),
                "{tool_name} MCP schema description must NOT contain the cost-warning banner; \
                 that text belongs only to get_file_snapshots. Got: {desc}"
            );
        }
    }

    #[test]
    fn it_does_not_market_get_file_snapshots_as_a_first_or_second_resort() {
        let desc = schema_description_for("get_file_snapshots");
        assert!(
            !desc.contains("cheapest tool"),
            "get_file_snapshots description must NOT claim to be the cheapest tool. Got: {desc}"
        );
        assert!(
            !desc.contains("recommended second call"),
            "get_file_snapshots description must NOT claim to be the recommended second call. \
             Got: {desc}"
        );
    }

    #[test]
    fn it_matches_expected_tools() {
        let router = GitPrismServer::tool_router();
        let mut actual: Vec<String> = router
            .list_all()
            .iter()
            .map(|t| t.name.to_string())
            .collect();
        actual.sort();
        let mut expected: Vec<String> = EXPECTED_TOOLS.iter().map(|s| s.to_string()).collect();
        expected.sort();
        assert_eq!(
            actual, expected,
            "MCP tool set drifted from EXPECTED_TOOLS. \
             If you added, removed, or renamed a tool, update the EXPECTED_TOOLS constant \
             in src/server.rs AND update README.md 'N MCP tools' count, CHANGELOG, and CLAUDE.md."
        );
    }

    /// Each tool description must reference the raw git command(s) the tool
    /// replaces, so an agent reading the MCP schema knows when to reach for
    /// `git-prism` instead of falling back to its pretraining-default
    /// `git diff`/`git log`/`git show`/`git log -S` reflex. These tests are
    /// the fast in-binary mirror of the `@ISSUE-237` BDD scenario in
    /// `bdd/features/redirect_hook.feature` — that scenario shells out to
    /// `git-prism serve` and reads the descriptions over JSON-RPC, while
    /// these tests read them straight off the in-process `tool_router`. Both
    /// must agree.
    #[test]
    fn it_publishes_comparative_framing_for_get_change_manifest() {
        let desc = schema_description_for("get_change_manifest");
        assert!(
            desc.contains("git diff"),
            "get_change_manifest description must reference \"git diff\" (issue #237). Got: {desc}",
        );
        assert!(
            desc.len() >= MIN_DESCRIPTION_CHARS,
            "get_change_manifest description is only {} chars; need >= {} (issue #237). Got: {desc}",
            desc.len(),
            MIN_DESCRIPTION_CHARS,
        );
    }

    #[test]
    fn it_publishes_comparative_framing_for_get_commit_history() {
        let desc = schema_description_for("get_commit_history");
        assert!(
            desc.contains("git log"),
            "get_commit_history description must reference \"git log\" (issue #237). Got: {desc}",
        );
        assert!(
            desc.len() >= MIN_DESCRIPTION_CHARS,
            "get_commit_history description is only {} chars; need >= {} (issue #237). Got: {desc}",
            desc.len(),
            MIN_DESCRIPTION_CHARS,
        );
    }

    #[test]
    fn it_publishes_comparative_framing_for_get_file_snapshots() {
        let desc = schema_description_for("get_file_snapshots");
        assert!(
            desc.contains("git show"),
            "get_file_snapshots description must reference \"git show\" (issue #237). Got: {desc}",
        );
        assert!(
            desc.len() >= MIN_DESCRIPTION_CHARS,
            "get_file_snapshots description is only {} chars; need >= {} (issue #237). Got: {desc}",
            desc.len(),
            MIN_DESCRIPTION_CHARS,
        );
    }

    #[test]
    fn it_publishes_comparative_framing_for_get_function_context() {
        let desc = schema_description_for("get_function_context");
        assert!(
            desc.contains("git log -S"),
            "get_function_context description must reference \"git log -S\" (issue #237). Got: {desc}",
        );
        assert!(
            desc.len() >= MIN_DESCRIPTION_CHARS,
            "get_function_context description is only {} chars; need >= {} (issue #237). Got: {desc}",
            desc.len(),
            MIN_DESCRIPTION_CHARS,
        );
    }

    /// Snapshot the full MCP-schema description for each tool so any future
    /// drift in the prose surfaces as a reviewable diff in the snapshot file
    /// rather than a silent change. The snapshots are the canonical record
    /// of what agents see; substring assertions above prevent accidental
    /// removal of load-bearing phrases, but only the snapshot catches "the
    /// description got rewritten in a way that changes the agent's mental
    /// model" (issue #237).
    #[test]
    fn it_snapshots_get_change_manifest_description() {
        insta::assert_snapshot!(
            "get_change_manifest_description",
            schema_description_for("get_change_manifest")
        );
    }

    #[test]
    fn it_snapshots_get_commit_history_description() {
        insta::assert_snapshot!(
            "get_commit_history_description",
            schema_description_for("get_commit_history")
        );
    }

    #[test]
    fn it_snapshots_get_file_snapshots_description() {
        insta::assert_snapshot!(
            "get_file_snapshots_description",
            schema_description_for("get_file_snapshots")
        );
    }

    #[test]
    fn it_snapshots_get_function_context_description() {
        insta::assert_snapshot!(
            "get_function_context_description",
            schema_description_for("get_function_context")
        );
    }

    #[test]
    fn it_snapshots_review_change_description() {
        insta::assert_snapshot!(
            "review_change_description",
            schema_description_for("review_change")
        );
    }
}